@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
180 lines • 7.64 kB
JavaScript
import { sessionEnvOverrides } from "./bash.js";
export const TERMINAL_CHILD_JOB_KINDS = {
bash: "terminal.bash",
output: "terminal.output",
input: "terminal.input",
resize: "terminal.resize",
kill: "terminal.kill",
};
/**
* A tool child's terminal manager scopes its ids by generation (`bash_c<generation>_<n>`, `idScope`), so they never
* match the server's own (a monitor's `bash_N`, `mon_*`, `watch_*`, `rpc_*`): the id alone says who owns the session.
*/
export function childTerminalIdScope(generation) {
return `c${generation}`;
}
const CHILD_SESSION_ID = /_c(\d+)_\d+$/;
export function isChildSessionId(id) {
return CHILD_SESSION_ID.test(id);
}
/**
* The child generation a child session was started on, read from its id. A session lives in its child's manager, so
* once that generation exits the id is gone: a call reaching a later child turns "unknown id" into "lost".
*/
function childGenerationOf(id) {
const generation = CHILD_SESSION_ID.exec(id)?.[1];
return generation === undefined ? undefined : Number(generation);
}
function optionalMinutes(value) {
return typeof value === "number" && Number.isFinite(value) && value >= 1 ? Math.trunc(value) : undefined;
}
function parseBackgroundWake(value) {
if (typeof value !== "object" || value === null)
return undefined;
const event = Reflect.get(value, "event");
const id = Reflect.get(value, "id");
if (typeof id !== "string" || !isChildSessionId(id))
return undefined;
if (event === "background_start") {
const description = Reflect.get(value, "description");
const startedAtMs = Reflect.get(value, "startedAtMs");
if (typeof description !== "string" || typeof startedAtMs !== "number")
return undefined;
const command = Reflect.get(value, "command");
const autoReapMinutes = optionalMinutes(Reflect.get(value, "autoReapMinutes"));
return {
event,
id,
description,
startedAtMs,
...(typeof command === "string" ? { command } : {}),
...(autoReapMinutes === undefined ? {} : { autoReapMinutes }),
};
}
if (event === "background_reap_failed") {
const autoReapMinutes = optionalMinutes(Reflect.get(value, "autoReapMinutes"));
const reason = Reflect.get(value, "reason");
if (autoReapMinutes === undefined || typeof reason !== "string")
return undefined;
return { event, id, autoReapMinutes, reason };
}
if (event === "background_exit") {
const output = Reflect.get(value, "output");
const exit = Reflect.get(value, "exit");
if (typeof output !== "string" || (exit !== null && typeof exit !== "object"))
return undefined;
const autoReapedAfterMinutes = optionalMinutes(Reflect.get(value, "autoReapedAfterMinutes"));
return {
event,
id,
exit: exit,
output,
...(autoReapedAfterMinutes === undefined ? {} : { autoReapedAfterMinutes }),
};
}
return undefined;
}
function exitView(exit, output, autoReapedAfterMinutes) {
return {
exitResult: exit,
fullOutput: () => output,
...(autoReapedAfterMinutes === undefined ? {} : { autoReapedAfterMinutes }),
};
}
function bashIdOf(value) {
if (typeof value !== "object" || value === null)
return undefined;
const id = value.bash_id;
return typeof id === "string" ? id : undefined;
}
export function lostSessionResult(id, generation) {
return {
content: [
{
type: "text",
text: `bash_id ${id} is lost: the session's tool child (generation ${generation}) exited, which ended this session and every process it started. Start a new session with bash.`,
},
],
details: { bash_id: id, lost: true, generation },
};
}
export function terminalChildJob(ctx, kind) {
return {
kind,
...(kind === TERMINAL_CHILD_JOB_KINDS.bash ? backgroundRelay(ctx) : {}),
...(kind === TERMINAL_CHILD_JOB_KINDS.bash
? {}
: {
placement: (params) => {
const id = bashIdOf(params);
if (id === undefined)
return kind === TERMINAL_CHILD_JOB_KINDS.kill ? "both" : "child";
return isChildSessionId(id) ? "child" : "server";
},
}),
result: (params, value, generation) => {
if (kind === TERMINAL_CHILD_JOB_KINDS.bash)
return value;
const id = bashIdOf(params);
const startedOn = id === undefined ? undefined : childGenerationOf(id);
if (id === undefined || startedOn === undefined || startedOn === generation)
return value;
return lostSessionResult(id, startedOn);
},
args: (params, toolCallId, execCtx) => {
const env = {};
for (const [name, value] of Object.entries(ctx.getEnv()))
if (typeof value === "string")
env[name] = value;
return {
params,
toolCallId,
cwd: execCtx.cwd ?? ctx.cwd,
env: { ...env, ...sessionEnvOverrides(ctx, execCtx) },
...(ctx.shellPath === undefined ? {} : { shellPath: ctx.shellPath }),
defaultCols: ctx.defaultCols,
defaultRows: ctx.defaultRows,
redactSecretsInOutput: ctx.redactSecretsInOutput === true,
...(ctx.timeoutAction === undefined ? {} : { timeoutAction: ctx.timeoutAction }),
...(ctx.backgroundAutoReapMinutes === undefined
? {}
: { backgroundAutoReapMinutes: ctx.backgroundAutoReapMinutes }),
};
},
};
}
/**
* The server's half of a background session that lives on the child: the child's start and exit arrive as wakes and go
* to the same hooks the in-process tools call (liveness snapshot, manifest, the completion notice). A generation that
* exits takes its sessions with it; each one still running gets its exit notice then.
*/
function backgroundRelay(ctx) {
const running = new Map();
return {
wake: (value, generation) => {
const wake = parseBackgroundWake(value);
if (wake === undefined)
return;
if (wake.event === "background_start") {
running.set(wake.id, generation);
ctx.onBackgroundStart?.(wake.id, wake.description, wake.startedAtMs, wake.command, wake.autoReapMinutes);
return;
}
if (wake.event === "background_reap_failed") {
ctx.onBackgroundReapFailed?.(wake.id, wake.autoReapMinutes, wake.reason);
return;
}
running.delete(wake.id);
ctx.onBackgroundExit?.(wake.id, exitView(wake.exit, wake.output, wake.autoReapedAfterMinutes));
},
childExited: (generation) => {
for (const [id, startedOn] of running) {
if (startedOn !== generation)
continue;
running.delete(id);
ctx.onBackgroundExit?.(id, exitView({ exitCode: null, signal: null, timedOut: false, cancelled: true }, `The session's tool child (generation ${generation}) exited, which ended this session and every process it started.`));
}
},
};
}
//# sourceMappingURL=child-placement.js.map