@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
136 lines • 7.29 kB
JavaScript
import { Value } from "typebox/value";
import { TerminalManager } from "../../../core/extensions/builtin/terminal/manager.js";
import { NOTICE_TAIL_MAX_CHARS } from "../../../core/extensions/builtin/terminal/notify.js";
import { sanitizeTerminalOutput } from "../../../core/extensions/builtin/terminal/output-format.js";
import { createPtyBashTool } from "../../../core/extensions/builtin/terminal/tools/bash.js";
import { createBashInputTool } from "../../../core/extensions/builtin/terminal/tools/bash-input.js";
import { createBashOutputTool } from "../../../core/extensions/builtin/terminal/tools/bash-output.js";
import { createBashResizeTool } from "../../../core/extensions/builtin/terminal/tools/bash-resize.js";
import { createKillBashTool } from "../../../core/extensions/builtin/terminal/tools/kill-bash.js";
import { ToolChildJobError } from "./entry-error.js";
/** Inside the PTY: no echo while it waits for the go-line, then the real command keeps the PTY's pid and group. */
const PTY_GO_SHIM = 'stty -echo 2>/dev/null; IFS= read -r _go || exit 127; stty echo 2>/dev/null; exec "$0" "$@"';
import { childTerminalIdScope, TERMINAL_CHILD_JOB_KINDS as TERMINAL_JOB_KINDS, } from "../../../core/extensions/builtin/terminal/tools/child-placement.js";
export { TERMINAL_JOB_KINDS };
function parseArgs(value) {
const field = (name) => typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined;
const cwd = field("cwd");
const toolCallId = field("toolCallId");
const env = field("env");
if (typeof cwd !== "string" || typeof toolCallId !== "string" || typeof env !== "object" || env === null)
throw new ToolChildJobError("terminal_job_bad_args", "a terminal job needs cwd, toolCallId and env");
const shellPath = field("shellPath");
const timeoutAction = field("timeoutAction");
const autoReap = field("backgroundAutoReapMinutes");
return {
params: field("params"),
toolCallId,
cwd,
env: Object.fromEntries(Object.entries(env).filter((entry) => typeof entry[1] === "string")),
...(typeof shellPath === "string" ? { shellPath } : {}),
defaultCols: Number(field("defaultCols")) || 0,
defaultRows: Number(field("defaultRows")) || 0,
redactSecretsInOutput: field("redactSecretsInOutput") === true,
...(timeoutAction === "background" || timeoutAction === "kill" ? { timeoutAction } : {}),
...(typeof autoReap === "number" && Number.isFinite(autoReap) ? { backgroundAutoReapMinutes: autoReap } : {}),
};
}
function barrierFor(job) {
return {
wrap: (command, args) => ({ command: "/bin/sh", args: ["-c", PTY_GO_SHIM, command, ...args] }),
async release(session) {
if (session.pid === undefined)
throw new ToolChildJobError("terminal_spawn_failed", "the PTY reported no pid");
const gated = job.gate.request({
jobId: job.jobId,
origin: "terminal",
api: "pty.spawn",
containment: "own-group",
lifetime: "owned",
pid: session.pid,
pgid: session.pid,
});
session.onExit((exitCode) => job.gate.done(gated.launchId, exitCode === null ? {} : { exitCode }));
if (!job.gate.skipsAckWait)
await gated.acked;
job.gate.invokeNow(gated.launchId);
session.write("go\n");
},
};
}
/** The tail a background exit notice shows, sanitized here so the wake carries only what the notice can use. */
function exitSummary(id, runtime) {
const output = sanitizeTerminalOutput(runtime.fullOutput()).trimEnd();
const exit = runtime.exitResult;
return {
event: "background_exit",
id,
exit: exit === null
? null
: { exitCode: exit.exitCode, signal: exit.signal, cancelled: exit.cancelled, timedOut: exit.timedOut },
output: output.length > NOTICE_TAIL_MAX_CHARS ? output.slice(output.length - NOTICE_TAIL_MAX_CHARS - 1) : output,
...(runtime.autoReapedAfterMinutes === undefined
? {}
: { autoReapedAfterMinutes: runtime.autoReapedAfterMinutes }),
};
}
/**
* The handlers. The child's one terminal manager (shared by every terminal job of this child) is made on the first job,
* its ids scoped by this child's generation so they never collide with the server's or an earlier child's.
*/
export function createTerminalJobHandlers(injected) {
let manager = injected;
const managerFor = (generation) => {
manager ??= new TerminalManager({ idScope: childTerminalIdScope(generation) });
return manager;
};
const tell = (job, wake) => {
job.wake(TERMINAL_JOB_KINDS.bash, wake).catch((error) => {
process.stderr.write(`tool-child: terminal ${wake.event} for ${wake.id} not delivered: ${error instanceof Error ? error.message : String(error)}\n`);
});
};
const contextFor = (args, job) => ({
manager: managerFor(job.generation),
...(args.timeoutAction === undefined ? {} : { timeoutAction: args.timeoutAction }),
...(args.backgroundAutoReapMinutes === undefined
? {}
: { backgroundAutoReapMinutes: args.backgroundAutoReapMinutes }),
onBackgroundStart: (id, description, startedAtMs, command, autoReapMinutes) => tell(job, {
event: "background_start",
id,
description,
startedAtMs,
...(command === undefined ? {} : { command }),
...(autoReapMinutes === undefined ? {} : { autoReapMinutes }),
}),
onBackgroundExit: (id, runtime) => tell(job, exitSummary(id, runtime)),
onBackgroundReapFailed: (id, autoReapMinutes, reason) => tell(job, { event: "background_reap_failed", id, autoReapMinutes, reason }),
cwd: args.cwd,
...(args.shellPath === undefined ? {} : { shellPath: args.shellPath }),
defaultCols: args.defaultCols,
defaultRows: args.defaultRows,
redactSecretsInOutput: args.redactSecretsInOutput,
getEnv: () => ({ ...args.env }),
launchBarrier: barrierFor(job),
});
const run = (create) => async (value, job) => {
const args = parseArgs(value);
const tool = create(contextFor(args, job));
if (!Value.Check(tool.parameters, args.params))
throw new ToolChildJobError("terminal_job_bad_args", "the tool's parameters do not match its schema");
const onUpdate = (update) => {
job.update(update).catch((error) => {
process.stderr.write(`tool-child: ${args.toolCallId} update not sent: ${error instanceof Error ? error.message : String(error)}\n`);
});
};
return tool.execute(args.toolCallId, args.params, job.signal, onUpdate, { cwd: args.cwd });
};
return {
[TERMINAL_JOB_KINDS.bash]: run(createPtyBashTool),
[TERMINAL_JOB_KINDS.output]: run(createBashOutputTool),
[TERMINAL_JOB_KINDS.input]: run(createBashInputTool),
[TERMINAL_JOB_KINDS.resize]: run(createBashResizeTool),
[TERMINAL_JOB_KINDS.kill]: run(createKillBashTool),
};
}
//# sourceMappingURL=terminal-jobs.js.map