UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

255 lines • 10.9 kB
/** * Tool dispatch seam (senpi#3566): the single place a tool call is resolved to a * placement and executed, and where user bash (`!`, RPC `bash`) resolves its * BashOperations. * * The dispatcher kind follows the session's tool runtime (`--tool-runtime`, absent * = in-process). Nothing moves yet: `InProcessToolDispatcher` calls * `definition.execute` exactly as the wrappers did before, and `ChildToolDispatcher` * refuses child-placed work with `tool_runtime_unavailable` until the tool child * runtime lands (senpi#3566 todo 4). An explicit `operations` override stays with * its caller, so caller-injected work is never re-routed. */ import { dirname, isAbsolute, resolve } from "node:path"; import { kernelToolInvokerStorage } from "../extensions/kernel-tools-context.js"; import { createLocalBashOperations } from "../tools/bash.js"; import { childBashOperations } from "./child-bash-operations.js"; import { runModuleInProcess } from "./in-process-module.js"; import { OffloadError } from "./offload.js"; export const TOOL_RUNTIME_UNAVAILABLE = "tool_runtime_unavailable"; /** * Placement of one call: only a definition that opted into `"child"` while the * session runs the child runtime dispatches there, and never when the definition * is server-pinned (injected `operations` / policy override captured at creation). */ export function resolveToolPlacement(definition, runtime) { if (runtime !== "child") return "server"; if (definition.placement !== "child") return "server"; if (definition.serverPinned === true) return "server"; return "child"; } class BaseToolDispatcher { #executing; get executing() { return this.#executing; } async run(call) { this.#executing++; try { return await this.dispatch(call); } finally { this.#executing--; } } dispose() { return Promise.resolve(); } constructor(notify) { this.#executing = 0; this.observers = new Set(); this.pinNotified = new Set(); this.notifySink = notify; } onDispatched(observer) { this.observers.add(observer); return () => { this.observers.delete(observer); }; } placementFor(definition) { const placement = resolveToolPlacement(definition, this.kind); if (placement === "server" && this.kind === "child" && definition.placement === "child") { if (!this.pinNotified.has(definition.name)) { this.pinNotified.add(definition.name); this.notifySink?.("tool_placement_pinned", { tool: definition.name, reason: "server_pinned" }); } } return placement; } runOnServer(call) { this.emitDispatched({ toolCallId: call.toolCallId, placement: "server", pid: process.pid, generation: 0 }); const execute = () => call.definition.execute(call.toolCallId, call.params, call.signal, call.onUpdate, call.ctx); // Context-free wrappers and child/observer contexts have no host identity. // Do not read an absent capability or inherit another dispatch's invoker. const manager = call.ctx && "sessionManager" in call.ctx ? call.ctx.sessionManager : undefined; return manager ? kernelToolInvokerStorage.run({ sessionId: manager.getSessionId() }, execute) : kernelToolInvokerStorage.exit(execute); } emitDispatched(info) { for (const observer of [...this.observers]) { try { observer(info); } catch (error) { // An observer is diagnostics only: its failure must never become the tool call's failure. this.notifySink?.("tool_dispatch_observer_failed", { message: error instanceof Error ? error.message : String(error), }); } } } } export class InProcessToolDispatcher extends BaseToolDispatcher { #options; #live; #disposed; constructor(notify, options = {}) { super(notify); this.kind = "in-process"; this.#live = new Set(); this.#disposed = false; this.#options = options; } /** Closes every in-process module run still live; settles once each has released its locks (`InProcessRun.close`). */ async dispose() { this.#disposed = true; await Promise.all([...this.#live].map((run) => run.close())); } dispatch(call) { return this.runOnServer(call); } bashOperations(options) { return createLocalBashOperations(options); } async offload(job, signal) { if (this.#disposed) throw new OffloadError("offload_session_closed", `${job.modulePath}: the session was closed`); return { value: await runModuleInProcess(job, signal, { ...(this.#options.hostCalls === undefined ? {} : { hostCalls: this.#options.hostCalls }), ...(this.#options.stuckGraceMs === undefined ? {} : { stuckGraceMs: this.#options.stuckGraceMs }), ...(this.#options.onModuleStuck === undefined ? {} : { onStuck: this.#options.onModuleStuck }), live: this.#live, }), placement: "server", pid: process.pid, generation: 0, }; } } /** * Refuses child-placed work and child-backed bash until the tool child runtime * lands (senpi#3566 todo 4 / todo 9); server-placed work still runs in-process, * so a session under `--tool-runtime child` stays usable at this stage. */ export class ChildToolDispatcher extends BaseToolDispatcher { #childRunner; #kindRunner; constructor(notify, childRunner, kindRunner) { super(notify); this.kind = "child"; this.#childRunner = childRunner; this.#kindRunner = kindRunner; } dispatch(call) { if (this.placementFor(call.definition) === "server") { return this.runOnServer(call); } const childJob = call.definition.childJob; if (childJob !== undefined) { const where = childJob.placement?.(call.params) ?? "child"; if (where === "server") return this.runOnServer(call); if (this.#kindRunner === undefined) return Promise.resolve(unavailableToolResult(call.definition.name)); if (where === "both") return this.#runOnBoth(this.#kindRunner, childJob, call); return this.#runKind(this.#kindRunner, childJob, call); } const job = childModuleJob(call); if (job === undefined || this.#childRunner === undefined) return Promise.resolve(unavailableToolResult(call.definition.name)); return this.#runOnChild(this.#childRunner, job, call); } /** The server's body first (its own state), then the child's job; the result carries both contents, the child's details. */ async #runOnBoth(runner, childJob, call) { const local = await this.runOnServer(call); const remote = await this.#runKind(runner, childJob, call); return { ...remote, content: [...local.content, ...remote.content] }; } async #runKind(runner, childJob, call) { const onUpdate = call.onUpdate; const kind = childJob.kind; const args = childJob.args(call.params, call.toolCallId, call.ctx); const { value, pid, generation } = await runner(kind, args, { toolCallId: call.toolCallId, signal: call.signal, ...(onUpdate === undefined ? {} : { onUpdate: (update) => { if (isToolResult(update)) onUpdate(update); }, }), }); this.emitDispatched({ toolCallId: call.toolCallId, placement: "child", pid, generation }); if (!isToolResult(value)) throw new Error(`tool_child_invalid_result: ${kind} must return { content: [...] }`); if (childJob.result === undefined) return value; return childJob.result(call.params, value, generation); } async #runOnChild(runner, job, call) { const { value, pid, generation } = await runner(job, call.signal); this.emitDispatched({ toolCallId: call.toolCallId, placement: "child", pid, generation }); if (!isToolResult(value)) throw new Error(`tool_child_invalid_result: ${job.modulePath}#${job.export} must return { content: [...] }`); return value; } bashOperations(options) { if (this.#kindRunner === undefined) return unavailableBashOperations(); return childBashOperations(this.#kindRunner, options); } /** Always on the session's child, started on demand; never in-process (no fallback). */ async offload(job, signal) { if (this.#childRunner === undefined) throw new OffloadError("tool_runtime_unavailable", "this session has no tool child to run the module on"); const { value, pid, generation } = await this.#childRunner(job, signal); return { value, placement: "child", pid, generation }; } } export function createToolDispatcher(options) { return options.runtime === "child" ? new ChildToolDispatcher(options.notify, options.childRunner, options.childKindRunner) : new InProcessToolDispatcher(options.notify, options); } function childModuleJob(call) { const childModule = call.definition.childModule; if (childModule === undefined) return undefined; const base = call.sourcePath === undefined ? undefined : dirname(call.sourcePath); if (!isAbsolute(childModule.path) && base === undefined) return undefined; const modulePath = isAbsolute(childModule.path) ? childModule.path : resolve(base ?? "", childModule.path); return { modulePath, export: childModule.export, args: { params: call.params, toolCallId: call.toolCallId } }; } function isToolResult(value) { return typeof value === "object" && value !== null && Array.isArray(Reflect.get(value, "content")); } export function unavailableToolResult(toolName) { return { content: [ { type: "text", text: `${TOOL_RUNTIME_UNAVAILABLE}: tool "${toolName}" is placed on the session tool child, which this build does not provide yet (senpi#3566).`, }, ], details: { code: TOOL_RUNTIME_UNAVAILABLE }, isError: true, }; } export function unavailableBashOperations() { return { exec: async () => { throw new Error(`${TOOL_RUNTIME_UNAVAILABLE}: user bash needs the session tool child, which this build does not provide yet (senpi#3566)`); }, }; } //# sourceMappingURL=tool-dispatcher.js.map