Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/exec-tool-run-id.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions docs/05_runtime_interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ interface WorkspaceRuntimeExecHandle extends ReadableStream<WorkspaceRuntimeEven

`input` is accepted by callable backends and rejected by the rest; it carries a structured value that the callable backend returns a structured value for. `env` is accepted everywhere: command backends inherit it for the spawned command, and the JavaScript module backend exposes it through `process.env`. Its values apply to that execution only and do not change later executions. `stdin` is the caller-supplied standard input, accepted by backends that model it (the JavaScript module backend reads it through `process.stdin`). `cwd` is the command working directory or the base for durable relative module imports. `metadata` is for host modules: the JavaScript module backend hands it to every host module call as `context.execution.metadata` and keeps it from the run's code, and backends without host modules ignore it. A handle is single-consumer: call `result()` or consume its event stream, not both. Repeated `result()` calls return the same promise. `backend` records the resolved backend needed for later reattachment.

## Execution ids

`exec()` takes an `id`, or makes one up. An id addresses one execution on its backend until the execution is disposed, and the backend refuses to reuse it. `CodemodeBackend`'s errors for ids carry a `code`, so callers can branch on it rather than on the message:

| Code | Meaning |
| --- | --- |
| `EEXEC_BUSY` | `exec()` was given the id of an execution that's starting or running, or `disposeExec()` one that's running. |
| `EEXEC_EXISTS` | `exec()` was given the id of an execution that has ended but hasn't been disposed. |
| `ENOENT` | `getExec()`, `killExec()`, `detachExec()` or `disposeExec()` was given an id with no execution. |

On `CodemodeBackend`, a call by id waits for an execution with that id that's still starting, so `getExec()` right after a refused `exec()` finds it. The [`exec` tool's `id`](./09_tool_interface.md#run-ids) attaches to a tool call's run this way.

## Results

```ts
Expand Down
15 changes: 13 additions & 2 deletions docs/09_tool_interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ createAITools({
read?,
write?,
edit?,
exec?: { backends?, output?, metadata? },
exec?: { backends?, output?, metadata?, id?, detach? },
root?,
});
```
Expand All @@ -191,9 +191,10 @@ createAITools({
| `exec.backends` | every backend | An `ExecBackends` map from backend id to `ExecBackendOptions` (`{ description? }`). `{}` omits `exec`. |
| `exec.output` | 2000 lines, 64 KiB | `{ maxLines?, maxBytes? }`: how much of each `exec` stream the model sees. See [`exec`](#exec). |
| `exec.metadata` | none | The `metadata` each `exec` run starts with, or `({ toolCallId }) => 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.

Expand Down Expand Up @@ -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, 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 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Conflicting cancellation rules for mixed backends

keepRunning applies to replays on every backend once the tool enables detach. The detaching contract says aborting kills runs that remain attached, including runs on backends that cannot detach.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


### 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.
Expand Down
67 changes: 67 additions & 0 deletions packages/computer/src/backends/codemode/codemode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -237,6 +238,72 @@ describe("CodemodeBackend", () => {
expect(workerDisposals).toBe(1);
});

describe("execs by id", () => {
function workspaceWith(value: unknown) {
const load = vi.fn<WorkspaceRuntimeLoader["load"]>(() => ({
getEntrypoint() {
return {
evaluate: (
_input: unknown,
host: {
assertResult(value: unknown): Promise<void>;
attachOutput(readable: ReadableStream<Uint8Array>): Promise<void>;
},
) => 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.
Expand Down
22 changes: 18 additions & 4 deletions packages/computer/src/backends/codemode/codemode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,9 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle {
readonly #codemodeModules: ReadonlyMap<string, CodemodeModuleRuntime>;
#sourceModules: Readonly<Record<string, string>> | undefined;
readonly #records = new Map<string, ExecutionRecord>();
readonly #pendingIds = new Set<string>();
// Execs that are starting, by id, each settling once its start has
// succeeded or failed.
readonly #starting = new Map<string, Promise<void>>();
#closed = false;
readonly #activeStreams = new Map<string, number>();
#pendingStarts = 0;
Expand Down Expand Up @@ -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}`);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<void>((resolve) => (started = resolve)));
try {
if (this.#options.access === "read-write")
await ensureDirectory(this.#host.fs, this.#options.root);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -1435,6 +1440,7 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle {

async getExec(input: { id: string; after?: number | "tail" }): Promise<ModuleExecutionEnvelope> {
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}`);
Expand All @@ -1443,13 +1449,15 @@ class CodemodeBackendHandle implements WorkspaceModuleBackendHandle {

async killExec(input: { id: string }): Promise<void> {
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");
}

async disposeExec(input: { id: string }): Promise<void> {
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") {
Expand All @@ -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<void> {
await this.#starting.get(id);
}

async close(): Promise<void> {
this.#closed = true;
if (this.#pendingStarts > 0) {
Expand Down
139 changes: 139 additions & 0 deletions packages/computer/src/tools/common/exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,145 @@ 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("leaves a run it attached to going when aborted, if the tool detaches", async () => {
const kills: string[] = [];
let finish = () => {};
const done = new Promise<void>((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(
/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 }> = [];
Expand Down
Loading
Loading