From 9c5fd37eaa1a9665a9639d1cd80621602a8347dd Mon Sep 17 00:00:00 2001 From: scuffi Date: Wed, 25 Nov 2026 18:15:14 +0000 Subject: [PATCH 1/3] computer: Let the exec tool attach a call made again to its run A durable agent loop makes a tool call again when its object restarts before the call's result was saved. The exec tool then started a second run of the same code, so a run that had sent a message or pushed a branch did it twice, and a run that was still going was left running with nobody reading it. A consumer that wanted each call to run once had to wrap the runtime: start the run under an id of its own, and on a refusal read the run back instead, polling while the first start was still under way, and telling the refusals apart by their messages. The exec tool now takes `id`, which picks each run's id from its tool call's. When the runtime refuses the id because the run exists or is starting (`EEXEC_EXISTS`, `EEXEC_BUSY`), the tool attaches to the run with getExec() and reads it from its start, so the call returns the run's result whether it's still going or has ended. A call without a tool call id starts a run of its own. CodemodeBackend's calls by id now wait for an exec with that id that is still starting, rather than reporting no such execution, so calls made at the same time share one run without polling. The runtime docs list the codes its id errors carry. --- .changeset/exec-tool-run-id.md | 5 + docs/05_runtime_interface.md | 12 +++ docs/09_tool_interface.md | 15 ++- .../src/backends/codemode/codemode.test.ts | 67 +++++++++++++ .../src/backends/codemode/codemode.ts | 22 ++++- .../computer/src/tools/common/exec.test.ts | 99 +++++++++++++++++++ packages/computer/src/tools/common/exec.ts | 80 ++++++++++++--- packages/computer/src/tools/common/options.ts | 15 ++- packages/computer/src/tools/core.ts | 1 + packages/computer/src/tools/index.ts | 1 + 10 files changed, 296 insertions(+), 21 deletions(-) create mode 100644 .changeset/exec-tool-run-id.md diff --git a/.changeset/exec-tool-run-id.md b/.changeset/exec-tool-run-id.md new file mode 100644 index 00000000..81a268a8 --- /dev/null +++ b/.changeset/exec-tool-run-id.md @@ -0,0 +1,5 @@ +--- +"@cloudflare/computer": patch +--- + +The `exec` tool takes `id`, which picks each run's id from its tool call's, so a call made again, as a durable agent loop does after a restart, attaches to the run it started instead of starting another; see [Run ids](https://github.com/cloudflare/computer/blob/main/docs/09_tool_interface.md#run-ids). `CodemodeBackend`'s calls by id wait for an exec that's still starting. diff --git a/docs/05_runtime_interface.md b/docs/05_runtime_interface.md index 5401b63f..45075067 100644 --- a/docs/05_runtime_interface.md +++ b/docs/05_runtime_interface.md @@ -48,6 +48,18 @@ interface WorkspaceRuntimeExecHandle extends ReadableStream metadata` to pick it per call. See [Run metadata](#run-metadata). | +| `exec.id` | none | `({ toolCallId }) => id`: each `exec` run's id, so a call made again attaches to its run. See [Run ids](#run-ids). | | `shell` | omitted | Deprecated, and ignored when `exec` is given. `{ backends }` becomes `exec: { backends }` and its output limits become `exec.output`; `defaultBackend` is ignored. | -`exec` is an `ExecToolSetOptions`, exported from `@cloudflare/computer/tools` with `ExecBackends` and `ExecBackendOptions`. `exec: {}` throws, as does any key other than `backends`, `output`, and `metadata`: pass `exec: { backends: {} }` for no exec tool, or leave `exec` out for every backend. +`exec` is an `ExecToolSetOptions`, exported from `@cloudflare/computer/tools` with `ExecBackends` and `ExecBackendOptions`. `exec: {}` throws, as does any key other than `backends`, `output`, `metadata`, `id`, and `detach`: pass `exec: { backends: {} }` for no exec tool, or leave `exec` out for every backend. `createPiTools` and `createTanStackTools` take the same options, plus their own listed above. @@ -400,6 +401,16 @@ const tools = createAITools({ A pi caller runs each call itself, so it can instead pass the metadata with the call: `execute(call, { metadata })`. Metadata passed with a call wins over `exec: { metadata }`. A caller of `defineExec` passes `metadata` or `toolCallId` on each `execute` the same way. +### Run ids + +An agent loop can make a tool call again: a durable one replays a call whose result it hadn't saved when its object restarted. By default the exec tool then starts a second run. `id` on `createExecTool`, or `exec: { id }` on a tool set, picks each run's id from its tool call's id instead, and a call whose run already exists attaches to it: it reads the run from its start, whether it's still going or has ended, and returns its result as the first call would have. A call without a tool call id starts a run of its own. A call made while its run is still starting waits for it, so calls made at the same time share one run. Aborting any of them stops the run. + +```ts +const tools = createPiTools({ workspace, exec: { id: ({ toolCallId }) => `exec:${toolCallId}` } }); +``` + +The id must be unique to the tool call: a call attaches to any run with its id, and tool call ids are often unique only within one conversation, so add what tells the conversations apart. The tool attaches when the runtime refuses the id as taken (`EEXEC_EXISTS` or `EEXEC_BUSY`, see [Execution ids](./05_runtime_interface.md#execution-ids)), so `id` needs a runtime with `getExec()`, such as a `Workspace`'s, and a backend that keeps ended runs, such as `CodemodeBackend`, until they're disposed. + ### Detaching By default, `exec` returns when its run ends. A run that waits for a person in [`ctx.interrupt()`](./17_isolate_javascript.md#waiting-for-an-answer), such as for an approval, can take hours, and the agent's turn waits with it: the agent can't tell anyone what it's doing until the answer comes. `detach` lets the tool return early and leave the run going on its own. It's experimental, and needs a backend that can [detach](./05_runtime_interface.md#detaching), such as a `CodemodeBackend` with `onDetachedExit`, which is where the run's exit goes. diff --git a/packages/computer/src/backends/codemode/codemode.test.ts b/packages/computer/src/backends/codemode/codemode.test.ts index f1a63559..8a3e04e4 100644 --- a/packages/computer/src/backends/codemode/codemode.test.ts +++ b/packages/computer/src/backends/codemode/codemode.test.ts @@ -9,6 +9,7 @@ import type { WorkspaceRuntimeExecExit, WorkspaceRuntimeLoader, } from "../../runtime/types"; +import { createPiTools } from "../../tools/pi-ai"; import { Workspace } from "../../workspace"; import { runtimeCode, CodemodeBackend } from "./codemode"; import { ExecutionJournal, fingerprint, loadResume, type ResumeStart, saveResume } from "./journal"; @@ -237,6 +238,72 @@ describe("CodemodeBackend", () => { expect(workerDisposals).toBe(1); }); + describe("execs by id", () => { + function workspaceWith(value: unknown) { + const load = vi.fn(() => ({ + getEntrypoint() { + return { + evaluate: ( + _input: unknown, + host: { + assertResult(value: unknown): Promise; + attachOutput(readable: ReadableStream): Promise; + }, + ) => evaluateResult(host, value), + }; + }, + })); + const workspace = new Workspace({ + storage: new SQLiteTestStorage(), + backends: [new CodemodeBackend({ loader: { load } })], + }); + return { workspace, load }; + } + + it("refuses an id that's starting, running or taken, with a code for each", async () => { + const { workspace } = workspaceWith(1); + await workspace.fs.mkdir("/workspace", { recursive: true }); + + const first = workspace.runtime.exec("export default 1", { id: "run-1" }); + await expect( + workspace.runtime.exec("export default 1", { id: "run-1" }), + ).rejects.toMatchObject({ code: "EEXEC_BUSY" }); + await (await first).result(); + await expect( + workspace.runtime.exec("export default 1", { id: "run-1" }), + ).rejects.toMatchObject({ code: "EEXEC_EXISTS" }); + await expect(workspace.runtime.getExec("run-2")).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("finds an exec that's still starting, once it has started", async () => { + const { workspace, load } = workspaceWith({ answer: 42 }); + await workspace.fs.mkdir("/workspace", { recursive: true }); + + const started = workspace.runtime.exec("export default null", { id: "run-1" }); + const found = workspace.runtime.getExec("run-1"); + + expect((await (await found).result()).value).toEqual({ answer: 42 }); + await (await started).result(); + expect(load).toHaveBeenCalledTimes(1); + }); + + it("runs an exec tool call once, however often it's made", async () => { + const { workspace, load } = workspaceWith({ answer: 42 }); + await workspace.fs.mkdir("/workspace", { recursive: true }); + const tools = createPiTools({ workspace, exec: { id: ({ toolCallId }) => toolCallId } }); + const call = { id: "call-1", name: "exec", arguments: { command: "export default null" } }; + + const together = await Promise.all([tools.execute(call), tools.execute(call)]); + const later = await tools.execute(call); + + expect(load).toHaveBeenCalledTimes(1); + for (const result of [...together, later]) { + expect(result.isError).toBe(false); + expect(result.details).toMatchObject({ exitCode: 0, result: { answer: 42 } }); + } + }); + }); + describe("detaching", () => { // A loader whose runs return `value` once `release` is called, so a // test can act while the run is still going. diff --git a/packages/computer/src/backends/codemode/codemode.ts b/packages/computer/src/backends/codemode/codemode.ts index c428f68c..17913eea 100644 --- a/packages/computer/src/backends/codemode/codemode.ts +++ b/packages/computer/src/backends/codemode/codemode.ts @@ -497,7 +497,9 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { readonly #codemodeModules: ReadonlyMap; #sourceModules: Readonly> | undefined; readonly #records = new Map(); - readonly #pendingIds = new Set(); + // Execs that are starting, by id, each settling once its start has + // succeeded or failed. + readonly #starting = new Map>(); #closed = false; readonly #activeStreams = new Map(); #pendingStarts = 0; @@ -641,6 +643,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { if (this.#options.onDetachedExit === undefined) { throw new Error(`Backend ${this.#backendId} can't detach execs without onDetachedExit.`); } + await this.#started(input.id); const record = this.#recordFor(input.id); if (record === undefined) { throw runtimeError("ENOENT", `no such execution: ${input.id}`); @@ -1175,7 +1178,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { const id = input.id ?? crypto.randomUUID(); assertExecutionId(id); this.#prune(); - if (this.#pendingIds.has(id)) { + if (this.#starting.has(id)) { throw runtimeError("EEXEC_BUSY", `execution ${id} is already starting`); } const existing = this.#recordFor(id); @@ -1217,7 +1220,8 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { // concurrent Dynamic Workers itself and reports that limit as the // execution's error. this.#pendingStarts += 1; - this.#pendingIds.add(id); + let started = () => {}; + this.#starting.set(id, new Promise((resolve) => (started = resolve))); try { if (this.#options.access === "read-write") await ensureDirectory(this.#host.fs, this.#options.root); @@ -1312,7 +1316,8 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { }); return { id, events: this.#stream(record) }; } finally { - this.#pendingIds.delete(id); + this.#starting.delete(id); + started(); this.#pendingStarts -= 1; if (this.#pendingStarts === 0) { for (const resolve of this.#pendingStartWaiters) resolve(); @@ -1435,6 +1440,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { async getExec(input: { id: string; after?: number | "tail" }): Promise { assertExecutionId(input.id); + await this.#started(input.id); this.#prune(); const record = this.#recordFor(input.id); if (!record) throw runtimeError("ENOENT", `no such execution: ${input.id}`); @@ -1443,6 +1449,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { async killExec(input: { id: string }): Promise { assertExecutionId(input.id); + await this.#started(input.id); const record = this.#recordFor(input.id); if (!record) throw runtimeError("ENOENT", `no such execution: ${input.id}`); await this.#cancel(record, "Execution cancelled.\n"); @@ -1450,6 +1457,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { async disposeExec(input: { id: string }): Promise { assertExecutionId(input.id); + await this.#started(input.id); const record = this.#recordFor(input.id); if (!record) throw runtimeError("ENOENT", `no such execution: ${input.id}`); if (record.status === "running") { @@ -1470,6 +1478,12 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle { this.#records.delete(input.id); } + // A call by id waits for an exec with that id that is starting, so it + // finds the exec once it exists rather than missing it. + async #started(id: string): Promise { + await this.#starting.get(id); + } + async close(): Promise { this.#closed = true; if (this.#pendingStarts > 0) { diff --git a/packages/computer/src/tools/common/exec.test.ts b/packages/computer/src/tools/common/exec.test.ts index 26317c28..4dd9ee05 100644 --- a/packages/computer/src/tools/common/exec.test.ts +++ b/packages/computer/src/tools/common/exec.test.ts @@ -94,6 +94,105 @@ describe("defineExec metadata", () => { }); }); +describe("defineExec id", () => { + // A runtime whose runs are taken once started: starting one again + // fails as the runtime does, and getExec() reads it back. + function runsById(fail?: Error) { + const started: Array<{ id: string | undefined; command: string }> = []; + const attached: Array<{ id: string; options: unknown }> = []; + const outcome = (id: string) => ({ + id, + result: async () => ({ exitCode: 0, stdout: `ran ${id}\n`, stderr: "" }), + }); + const workspace: ExecWorkspaceLike = { + runtime: { + async exec(command, options) { + if (fail !== undefined) throw fail; + if (options.id !== undefined && started.some((run) => run.id === options.id)) { + throw Object.assign(new Error(`execution ${options.id} already exists`), { + code: "EEXEC_EXISTS", + }); + } + started.push({ id: options.id, command }); + return outcome(options.id ?? "random"); + }, + async getExec(id, options) { + attached.push({ id, options }); + return outcome(id); + }, + backends: () => [{ id: "js", protocol: "module", callable: true }], + }, + }; + return { workspace, started, attached }; + } + + it("starts each run with the id it picks from the tool call's id", async () => { + const { workspace, started } = runsById(); + const exec = defineExec({ workspace, id: ({ toolCallId }) => `agent-1:${toolCallId}` }); + + await last(exec.execute({ command: "a" }, { toolCallId: "call-1" })); + await last(exec.execute({ command: "b" }, { toolCallId: "call-2" })); + + expect(started).toEqual([ + { id: "agent-1:call-1", command: "a" }, + { id: "agent-1:call-2", command: "b" }, + ]); + }); + + it("starts a run of its own for a call with no tool call id", async () => { + const { workspace, started } = runsById(); + const exec = defineExec({ workspace, id: ({ toolCallId }) => `agent-1:${toolCallId}` }); + + await last(exec.execute({ command: "a" })); + await last(exec.execute({ command: "a" })); + + expect(started).toEqual([ + { id: undefined, command: "a" }, + { id: undefined, command: "a" }, + ]); + }); + + it("attaches a call made again to the run it started, from the start", async () => { + const { workspace, started, attached } = runsById(); + const exec = defineExec({ workspace, id: ({ toolCallId }) => toolCallId, maxLines: 10 }); + + const first = await last(exec.execute({ command: "a" }, { toolCallId: "call-1" })); + const again = await last(exec.execute({ command: "a" }, { toolCallId: "call-1" })); + + expect(started).toHaveLength(1); + expect(attached).toEqual([ + { + id: "call-1", + options: { + backend: "js", + encoding: "utf8", + resume: "full", + output: expect.objectContaining({ maxLines: 10 }), + }, + }, + ]); + expect(again).toEqual(first); + expect(again).toMatchObject({ exitCode: 0, stdout: "ran call-1\n" }); + }); + + it("reports any other failure to start as the call's error", async () => { + const { workspace, attached } = runsById(new Error("no room")); + const exec = defineExec({ workspace, id: ({ toolCallId }) => toolCallId }); + + const output = await last(exec.execute({ command: "a" }, { toolCallId: "call-1" })); + + expect(output).toMatchObject({ error: "no room" }); + expect(attached).toEqual([]); + }); + + it("needs a runtime that can find a run by id", () => { + const { workspace } = recordingWorkspace(); + expect(() => defineExec({ workspace, id: ({ toolCallId }) => toolCallId })).toThrow( + /id needs a runtime with getExec\(\)/, + ); + }); +}); + describe("defineExec result bound", () => { it("saves a return value past the output limit to a file", async () => { const written: Array<{ path: string; size: number }> = []; diff --git a/packages/computer/src/tools/common/exec.ts b/packages/computer/src/tools/common/exec.ts index 4888ceab..6c752ddc 100644 --- a/packages/computer/src/tools/common/exec.ts +++ b/packages/computer/src/tools/common/exec.ts @@ -70,6 +70,18 @@ export interface ExecWorkspaceLike { input?: WorkspaceRuntimeValue; metadata?: Record; output?: { maxBytes: number; maxLines: number }; + id?: string; + }, + ): Promise; + // An exec by id, read from its start. Needed for `id`, to attach to + // a run a tool call already started. + getExec?( + id: string, + options: { + backend?: string; + encoding: "utf8"; + resume: "full"; + output?: { maxBytes: number; maxLines: number }; }, ): Promise; // Calls waiting in ctx.interrupt(), by execution id, and noting @@ -114,6 +126,12 @@ export type ExecMetadata = | Record | ((call: { toolCallId: string }) => Record); +/** + * The id of a tool call's run, picked from the tool call's id. It must + * be unique to the tool call. + */ +export type ExecId = (call: { toolCallId: string }) => string; + /** * Whether the exec tool may return before a run ends, leaving it * running. `true` detaches a run once it waits for an answer in @@ -146,6 +164,13 @@ export interface ExecToolOptions { * belongs to. Metadata a call passes itself, as a pi caller can, wins. */ metadata?: ExecMetadata; + /** + * Each run's id, from its tool call's. A call made again, as when a + * restart replays it, attaches to the run it started rather than + * starting another, and reads it from the start. A call with no tool + * call id starts a run of its own. Needs a runtime with `getExec()`. + */ + id?: ExecId; /** * Return before a run ends, and leave it running, so the agent can * carry on. The reply has the run's `executionId`, a `status` of @@ -268,6 +293,10 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { ); const detachExec = runtime.detachExec; const pending = runtime.pending; + const getExec = runtime.getExec; + if (options.id !== undefined && getExec === undefined) { + throw new Error("createExecTool: id needs a runtime with getExec()"); + } if (detach !== undefined) { if (detachExec === undefined || pending === undefined) { throw new Error("createExecTool: detach needs a runtime with detachExec() and pending()"); @@ -389,6 +418,28 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { }; } + // Start the run. A run with its id exists, or is starting, when this + // tool call started it before: attach to it, from its start, instead. + async function start( + command: string, + startOptions: Parameters[1], + id: string | undefined, + ): Promise { + if (id === undefined) return runtime.exec(command, startOptions); + try { + return await runtime.exec(command, { ...startOptions, id }); + } catch (error) { + const code = (error as { code?: unknown } | null)?.code; + if ((code !== "EEXEC_EXISTS" && code !== "EEXEC_BUSY") || getExec === undefined) throw error; + return getExec.call(runtime, id, { + backend: startOptions.backend, + encoding: "utf8", + resume: "full", + output: startOptions.output, + }); + } + } + return { description, inputSchema, @@ -415,17 +466,24 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { (typeof options.metadata === "function" ? options.metadata({ toolCallId: context.toolCallId ?? "" }) : options.metadata); - handle = await options.workspace.runtime.exec(command, { - cwd, - encoding: "utf8", - backend: selectedBackend, - env, - input, - ...(metadata === undefined ? {} : { metadata }), - // The runtime cuts and saves by the same limits the tool - // shows, so whatever the model does not see is in the file. - output: limits, - }); + // A call with no tool call id has nothing to be made again by. + const toolCallId = context.toolCallId; + const id = toolCallId === undefined ? undefined : options.id?.({ toolCallId }); + handle = await start( + command, + { + cwd, + encoding: "utf8", + backend: selectedBackend, + env, + input, + ...(metadata === undefined ? {} : { metadata }), + // The runtime cuts and saves by the same limits the tool + // shows, so whatever the model does not see is in the file. + output: limits, + }, + id, + ); } catch (err) { yield { ...base, error: errorMessage(err) }; return; diff --git a/packages/computer/src/tools/common/options.ts b/packages/computer/src/tools/common/options.ts index f55ac8a5..9bb9ec19 100644 --- a/packages/computer/src/tools/common/options.ts +++ b/packages/computer/src/tools/common/options.ts @@ -1,6 +1,7 @@ import type { ExecBackends, ExecDetachOptions, + ExecId, ExecMetadata, ExecToolOptions, ExecWorkspaceLike, @@ -27,7 +28,7 @@ export interface CreateToolsOptions { * Options for the `exec` tool. Omit `exec` or its `backends` to offer * every backend the Workspace has; `{ backends: {} }` means no exec * tool. `exec: {}` and keys other than `backends`, `output`, - * `metadata` and `detach`, such as a backend map from before `exec.backends`, + * `metadata`, `id` and `detach`, such as a backend map from before `exec.backends`, * throw. */ exec?: ExecToolSetOptions; @@ -56,6 +57,11 @@ export interface ExecToolSetOptions { * sees it. */ metadata?: ExecMetadata; + /** + * Each `exec` run's id, picked from its tool call's id, so a call made + * again attaches to the run it started; see `ExecToolOptions.id`. + */ + id?: ExecId; /** * Return before a run ends and leave it running, once it waits for an * answer or, with `afterMs`, has gone on that long. Its exit goes to @@ -102,7 +108,7 @@ export function resolveToolOptions(options: CreateToolsOptions): ResolvedToolOpt }; } -const EXEC_KEYS = new Set(["backends", "output", "metadata", "detach"]); +const EXEC_KEYS = new Set(["backends", "output", "metadata", "id", "detach"]); // Reject the shapes `exec` had before it took `{ backends, output, // metadata }`, rather than offering every backend for them. @@ -111,7 +117,7 @@ function checkExec(exec: ExecToolSetOptions | undefined): void { const keys = Object.keys(exec); if (keys.some((key) => !EXEC_KEYS.has(key))) { throw new TypeError( - "exec takes `{ backends, output, metadata, detach }`; move backend options under `exec.backends`", + "exec takes `{ backends, output, metadata, id, detach }`; move backend options under `exec.backends`", ); } if (keys.length === 0) { @@ -127,13 +133,14 @@ function execOptions(options: CreateToolsOptions): ExecToolOptions | undefined { if (runtime === undefined) return undefined; const selected = selectExec(options, runtime); if (Object.keys(selected.backends).length === 0) return undefined; - const { output, metadata, detach } = options.exec ?? {}; + const { output, metadata, id, detach } = options.exec ?? {}; return { workspace: { runtime }, ...selected, ...(output?.maxBytes === undefined ? {} : { maxBytes: output.maxBytes }), ...(output?.maxLines === undefined ? {} : { maxLines: output.maxLines }), ...(metadata === undefined ? {} : { metadata }), + ...(id === undefined ? {} : { id }), ...(detach === undefined ? {} : { detach }), }; } diff --git a/packages/computer/src/tools/core.ts b/packages/computer/src/tools/core.ts index a959be5b..7722a3e4 100644 --- a/packages/computer/src/tools/core.ts +++ b/packages/computer/src/tools/core.ts @@ -5,6 +5,7 @@ export { type ExecCallContext, type ExecDefinition, type ExecInput, + type ExecId, type ExecMetadata, type ExecRuntimeHandle, type ExecStreamEvent, diff --git a/packages/computer/src/tools/index.ts b/packages/computer/src/tools/index.ts index 310f9ee6..3b6b2948 100644 --- a/packages/computer/src/tools/index.ts +++ b/packages/computer/src/tools/index.ts @@ -18,6 +18,7 @@ export { export type { ExecBackendOptions, ExecBackends, + ExecId, ExecMetadata, ExecRuntimeHandle, ExecStreamEvent, From 097d7d155f78c7ae72e0b09f3b0b367ce4e380fc Mon Sep 17 00:00:00 2001 From: scuffi Date: Fri, 27 Nov 2026 11:25:37 +0000 Subject: [PATCH 2/3] computer: Say how long a run can be attached to, and leave detached ones alone A call made again attaches to its run only while the backend keeps it. CodemodeBackend prunes an ended run after its retentionMs or past maxRetainedExecutions, and a backend that keeps no runs, such as WorkerShellBackend, never has one to attach to; in both cases the call runs again. Say so where `id` is documented. With `detach`, a call made again may attach to a run the first call detached. Aborting it killed the run, though a detached run is meant to carry on. A call that attached now leaves the run going when it's aborted, if the tool detaches. --- docs/09_tool_interface.md | 4 +- .../computer/src/tools/common/exec.test.ts | 40 +++++++++++++++++++ packages/computer/src/tools/common/exec.ts | 30 +++++++++----- 3 files changed, 62 insertions(+), 12 deletions(-) diff --git a/docs/09_tool_interface.md b/docs/09_tool_interface.md index e772f2c7..0bff4a63 100644 --- a/docs/09_tool_interface.md +++ b/docs/09_tool_interface.md @@ -403,13 +403,13 @@ A pi caller runs each call itself, so it can instead pass the metadata with the ### Run ids -An agent loop can make a tool call again: a durable one replays a call whose result it hadn't saved when its object restarted. By default the exec tool then starts a second run. `id` on `createExecTool`, or `exec: { id }` on a tool set, picks each run's id from its tool call's id instead, and a call whose run already exists attaches to it: it reads the run from its start, whether it's still going or has ended, and returns its result as the first call would have. A call without a tool call id starts a run of its own. A call made while its run is still starting waits for it, so calls made at the same time share one run. Aborting any of them stops the run. +An agent loop can make a tool call again: a durable one replays a call whose result it hadn't saved when its object restarted. By default the exec tool then starts a second run. `id` on `createExecTool`, or `exec: { id }` on a tool set, picks each run's id from its tool call's id instead, and a call whose run already exists attaches to it: it reads the run from its start, whether it's still going or has ended, and returns its result as the first call would have. A call without a tool call id starts a run of its own. A call made while its run is still starting waits for it, so calls made at the same time share one run. Aborting any of them stops the run, except as below. ```ts const tools = createPiTools({ workspace, exec: { id: ({ toolCallId }) => `exec:${toolCallId}` } }); ``` -The id must be unique to the tool call: a call attaches to any run with its id, and tool call ids are often unique only within one conversation, so add what tells the conversations apart. The tool attaches when the runtime refuses the id as taken (`EEXEC_EXISTS` or `EEXEC_BUSY`, see [Execution ids](./05_runtime_interface.md#execution-ids)), so `id` needs a runtime with `getExec()`, such as a `Workspace`'s, and a backend that keeps ended runs, such as `CodemodeBackend`, until they're disposed. +The id must be unique to the tool call: a call attaches to any run with its id, and tool call ids are often unique only within one conversation, so add what tells the conversations apart. The tool attaches when the runtime refuses the id as taken (`EEXEC_EXISTS` or `EEXEC_BUSY`, see [Execution ids](./05_runtime_interface.md#execution-ids)), so `id` needs a runtime with `getExec()`, such as a `Workspace`'s, and a backend that keeps runs by id. `CodemodeBackend` keeps an ended run until it's disposed or pruned: after its `retentionMs` (an hour by default), or once it has more than `maxRetainedExecutions` (100). A call made again after that runs again. On a backend that doesn't keep runs, such as `WorkerShellBackend`, every call starts a run. With `detach`, aborting a call that attached leaves the run going, since the call that started it may have detached it. ### Detaching diff --git a/packages/computer/src/tools/common/exec.test.ts b/packages/computer/src/tools/common/exec.test.ts index 4dd9ee05..b776a07a 100644 --- a/packages/computer/src/tools/common/exec.test.ts +++ b/packages/computer/src/tools/common/exec.test.ts @@ -185,6 +185,46 @@ describe("defineExec id", () => { expect(attached).toEqual([]); }); + it("leaves a run it attached to going when aborted, if the tool detaches", async () => { + const kills: string[] = []; + let finish = () => {}; + const done = new Promise((resolve) => (finish = resolve)); + const running = (id: string) => ({ + id, + result: async () => { + await done; + return { exitCode: 0, stdout: "", stderr: "" }; + }, + kill: async () => void kills.push(id), + }); + const workspace: ExecWorkspaceLike = { + runtime: { + async exec() { + throw Object.assign(new Error("execution call-1 is already running"), { + code: "EEXEC_BUSY", + }); + }, + getExec: async (id) => running(id), + pending: async () => [], + detachExec: async () => false, + backends: () => [{ id: "js", protocol: "module", callable: true, detachable: true }], + }, + }; + const exec = defineExec({ workspace, id: ({ toolCallId }) => toolCallId, detach: true }); + const abort = new AbortController(); + + const call = last( + exec.execute({ command: "a" }, { toolCallId: "call-1", abortSignal: abort.signal }), + ); + await new Promise((resolve) => setTimeout(resolve, 10)); + abort.abort(); + await new Promise((resolve) => setTimeout(resolve, 10)); + finish(); + await call; + + expect(kills).toEqual([]); + }); + it("needs a runtime that can find a run by id", () => { const { workspace } = recordingWorkspace(); expect(() => defineExec({ workspace, id: ({ toolCallId }) => toolCallId })).toThrow( diff --git a/packages/computer/src/tools/common/exec.ts b/packages/computer/src/tools/common/exec.ts index 6c752ddc..66b1c18f 100644 --- a/packages/computer/src/tools/common/exec.ts +++ b/packages/computer/src/tools/common/exec.ts @@ -167,8 +167,11 @@ export interface ExecToolOptions { /** * Each run's id, from its tool call's. A call made again, as when a * restart replays it, attaches to the run it started rather than - * starting another, and reads it from the start. A call with no tool - * call id starts a run of its own. Needs a runtime with `getExec()`. + * starting another, and reads it from the start, while the backend + * keeps the run: `CodemodeBackend` keeps ended runs for its + * `retentionMs` (an hour by default), at most `maxRetainedExecutions` + * of them. A call with no tool call id starts a run of its own. Needs + * a runtime with `getExec()`. */ id?: ExecId; /** @@ -424,19 +427,20 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { command: string, startOptions: Parameters[1], id: string | undefined, - ): Promise { - if (id === undefined) return runtime.exec(command, startOptions); + ): Promise<{ handle: ExecRuntimeHandle; attached: boolean }> { + if (id === undefined) return { handle: await runtime.exec(command, startOptions), attached: false }; try { - return await runtime.exec(command, { ...startOptions, id }); + return { handle: await runtime.exec(command, { ...startOptions, id }), attached: false }; } catch (error) { const code = (error as { code?: unknown } | null)?.code; if ((code !== "EEXEC_EXISTS" && code !== "EEXEC_BUSY") || getExec === undefined) throw error; - return getExec.call(runtime, id, { + const handle = await getExec.call(runtime, id, { backend: startOptions.backend, encoding: "utf8", resume: "full", output: startOptions.output, }); + return { handle, attached: true }; } } @@ -460,6 +464,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { return; } let handle: ExecRuntimeHandle; + let attached = false; try { const metadata = context.metadata ?? @@ -469,7 +474,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { // A call with no tool call id has nothing to be made again by. const toolCallId = context.toolCallId; const id = toolCallId === undefined ? undefined : options.id?.({ toolCallId }); - handle = await start( + ({ handle, attached } = await start( command, { cwd, @@ -483,7 +488,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { output: limits, }, id, - ); + )); } catch (err) { yield { ...base, error: errorMessage(err) }; return; @@ -494,11 +499,16 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { // not run on unobserved after the tool stops iterating. The run // then emits its terminal event and the stream closes normally. // A run that detached is meant to run on, so it's left alone, - // including one whose detach went through as the turn aborted. + // including one whose detach went through as the turn aborted. So + // is a run this call attached to when the tool detaches: the call + // that started it may have detached it already. + const keepRunning = attached && detach !== undefined; const onAbort = () => void detaching .settle() - .then((detached) => (detached === undefined ? handle.kill?.() : undefined)) + .then((detached) => + detached === undefined && !keepRunning ? handle.kill?.() : undefined, + ) .catch(() => undefined); if (abortSignal?.aborted) onAbort(); else abortSignal?.addEventListener("abort", onAbort, { once: true }); From c9d1f48ee95d94dc398eb9ffafc6db897f2c8e0c Mon Sep 17 00:00:00 2001 From: scuffi Date: Fri, 27 Nov 2026 13:04:31 +0000 Subject: [PATCH 3/3] computer: Format exec.ts --- packages/computer/src/tools/common/exec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/computer/src/tools/common/exec.ts b/packages/computer/src/tools/common/exec.ts index 66b1c18f..7388955e 100644 --- a/packages/computer/src/tools/common/exec.ts +++ b/packages/computer/src/tools/common/exec.ts @@ -428,7 +428,8 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { startOptions: Parameters[1], id: string | undefined, ): Promise<{ handle: ExecRuntimeHandle; attached: boolean }> { - if (id === undefined) return { handle: await runtime.exec(command, startOptions), attached: false }; + if (id === undefined) + return { handle: await runtime.exec(command, startOptions), attached: false }; try { return { handle: await runtime.exec(command, { ...startOptions, id }), attached: false }; } catch (error) {