@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
49 lines • 2.09 kB
JavaScript
/**
* The background jobs each turn started (a bash command run with `run_in_background` or one that auto-detached),
* keyed by the turn id (`turn_epoch`) that was running when the job became background. `interrupt { background:
* "stop" }` stops the jobs of the turn it interrupted, so nothing that turn left running wakes the session later.
* A job leaves the registry when it ends on its own (`release`) or once it is stopped.
*/
function named(job) {
return { kind: job.kind, id: job.id, ...(job.description === undefined ? {} : { description: job.description }) };
}
export class RunBackgroundJobs {
#byTurn = new Map();
/** Record `job` under `turnId`; the returned release drops it once it ended on its own. */
register(turnId, job) {
let jobs = this.#byTurn.get(turnId);
if (jobs === undefined) {
jobs = new Set();
this.#byTurn.set(turnId, jobs);
}
jobs.add(job);
return () => this.#drop(turnId, job);
}
/** Stops the turn's jobs all at once, so jobs that ignore TERM cost one grace period, not one each; lists keep start order. */
async stop(turnId) {
const jobs = [...(this.#byTurn.get(turnId) ?? [])];
this.#byTurn.delete(turnId);
const results = await Promise.allSettled(jobs.map(async (job) => job.stop(turnId)));
const stopped = [];
const failed = [];
jobs.forEach((job, index) => {
const result = results[index];
if (result?.status === "fulfilled") {
stopped.push(named(job));
return;
}
const error = result?.reason;
failed.push({ ...named(job), reason: error instanceof Error ? error.message : String(error) });
});
return { stopped, failed };
}
#drop(turnId, job) {
const jobs = this.#byTurn.get(turnId);
if (jobs === undefined)
return;
jobs.delete(job);
if (jobs.size === 0)
this.#byTurn.delete(turnId);
}
}
//# sourceMappingURL=run-background-jobs.js.map