Skip to content

computer: Let the exec tool attach a call made again to its run - #348

Open
scuffi wants to merge 3 commits into
mainfrom
computer/exec-tool-run-id
Open

scuffi wants to merge 3 commits into
mainfrom
computer/exec-tool-run-id

Conversation

@scuffi

@scuffi scuffi commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

A durable agent loop makes a tool call again when its object restarts before the call's result was saved; pi-durable does this for any call it hadn't finished. The exec tool starts a run for every call, so the replayed call runs the same code a second time. A run that sent a message or pushed a branch does it twice, and a run that was still going keeps going with nobody reading it.

A consumer that wants each call to run once has to wrap the runtime today: give runtime.exec() an id of its own, catch the refusal when the id is taken, read the run back with getExec(), poll while the first call's start is still under way (getExec() says there's no such execution until the start has saved the run), and tell the refusals apart by their messages.

Usage

The tool takes id, which picks each run's id from its tool call's, like metadata does:

const tools = createPiTools({
  workspace,
  exec: { id: ({ toolCallId }) => `${conversationId}:${toolCallId}` },
});

A call whose run already exists attaches to it instead of starting another. It reads the run from its start with getExec(id, { resume: "full" }), so it streams the same output and returns the same result the first call would have, whether the run is still going or has ended. Calls made at the same time share one run. Aborting any of them stops it, as aborting the first one would. A call with no tool call id starts a run of its own, so it can't attach to an unrelated run. The id must be unique to the tool call; tool call ids are often unique only within one conversation, so the function adds what tells conversations apart.

How it works

The tool tries to start the run with its id. If the runtime refuses it as taken, with EEXEC_EXISTS (ended but not disposed) or EEXEC_BUSY (starting or running), it attaches. Any other failure is the call's error, as before. id needs a runtime with getExec(); the tool throws when it's built otherwise, as detach does for detachExec().

For the "starting" case, CodemodeBackend's calls by id (getExec, killExec, detachExec, disposeExec) now wait for an exec with that id that's still starting, rather than reporting no such execution: the start had already claimed the id, so the call finds the run once it's saved, or gets ENOENT if the start failed. The runtime docs gain an Execution ids section listing the codes CodemodeBackend's id errors carry, which the tool relies on; they were thrown already but not documented.

With detach

A call made again for a run that detached goes through detach as before: if the run is still going, detachExec() succeeds again and the call replies as detached. If the run detached and has since ended, the call attaches and returns its result, while onDetachedExit has had the exit too, so the outcome arrives twice. That only happens when the loop lost the first call's detached reply, and delivery to onDetachedExit is already at least once.

Testing

  • codemode.test.ts: an id that's starting, running or ended is refused with EEXEC_BUSY or EEXEC_EXISTS, and an unknown one with ENOENT; getExec() called while an exec is still starting finds it once it has started (this fails without the backend change, with "no such execution"); and a pi exec tool call made twice at once and once more afterwards loads the code once, with every call getting the run's result.
  • exec.test.ts: the id comes from the tool call's id; a call made again attaches with resume: "full" and the tool's output limits and returns the same output; any other start failure is the call's error with no attach; a call without a tool call id starts its own run; and id without getExec() throws when the tool is built.

Follow-ups

This covers a call made again in the same object. A host whose tool calls come from another Durable Object also needs the run's host calls to go to whichever caller is attached now; that's a separate change, written up for review first.

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-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c9d1f48

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@cloudflare/computer Patch
@cloudflare/dofs Patch
@cloudflare/computer-rpc Patch
@cloudflare/computerd Patch
@cloudflare/remote-exec Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@cloudflare/computer@348

commit: c9d1f48

@scuffi
scuffi marked this pull request as ready for review November 27, 2026 10:48

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 5 potential issues.

Devin Review

Comment on lines +429 to +433
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;

@devin-ai-integration devin-ai-integration Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Duplicate exec side effects after pruning

When an agent replays a completed tool call after Codemode prunes its run, start executes the command again. Codemode deletes the record that would have triggered reattachment, so the command repeats any side effects.

Learn more

A durable agent can replay the same tool call when the command finished but the agent did not save its reply. The tool only consults the original run when a new start returns a duplicate-ID error. Codemode execution startup prunes completed records before checking the ID. Retention cleanup deletes both the record and its events when the age or count limit is reached. Once it does, the tool cannot distinguish a previously used ID from a new one.

Example: A command sends a notification and finishes, but the agent restarts before saving the tool reply. The agent replays the call 70 minutes later under the default 60-minute retention. Codemode removes the original run and sends the notification again instead of attaching.

Recommended fix: Keep the execution ID reserved for at least the agent's replay window, independently of output retention. If the output has expired, return a distinct error without executing the command again. Cover both age-based and count-based expiry in replay tests.

Devin Review


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

Comment on lines +434 to +439
return getExec.call(runtime, id, {
backend: startOptions.backend,
encoding: "utf8",
resume: "full",
output: startOptions.output,
});

@devin-ai-integration devin-ai-integration Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Partial logs overwrite full exec output

getExec saves replay output to the same log as the original stream. If the original stream stops early after the replay finishes, spoolEvents overwrites the full log with partial output.

Learn more

Each full execution handle writes long output through its own spool, which is a writer that saves output beyond the tool's display limit. Workspace output naming gives both the original and replay writers the same path. The stream cancellation path closes an unfinished spool, and the filesystem writer replaces the destination when it commits. The last writer therefore wins even when it has less output.

Example: The original streaming caller pauses after reading a snapshot with more than 64 KiB of stdout. The same tool call attaches and reads the entire run, then returns a full-output link. When the original caller stops consuming its stream, it commits only the prefix it read, replacing the file at that link.

Recommended fix: Give each reader its own staging destination and allow only a spool that has seen the exit event to publish the canonical full-output file. Discard incomplete staging files on cancellation, or save them under separate names. Test a replay that finishes before cancellation of a paused original reader.

Devin Review


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

Comment on lines +296 to +299
const getExec = runtime.getExec;
if (options.id !== undefined && getExec === undefined) {
throw new Error("createExecTool: id needs a runtime with getExec()");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Run IDs accept non-replayable backends

The getExec check passes for WorkerShell, but its lookup always returns ENOENT. Default backend selection can offer WorkerShell alongside Codemode under one exec.id setting.

Devin Review


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

Comment on lines +60 to +64
/**
* 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔍 Runnable examples omit exec IDs

The public exec.id option has a docs snippet, but the pi example leaves it unset. The repository requires example updates alongside public API changes.

Devin Review


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

…nes 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.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 2 new potential issues.

Devin Review

Comment on lines +505 to +511
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,
)

@devin-ai-integration devin-ai-integration Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Aborted exec replays keep waiting

When a replay attaches with detach enabled, onAbort leaves the run going but never ends the replay’s wait. It also stops the detach watcher, so the agent turn stays blocked until the run finishes.

Learn more

A replay reads an existing run rather than starting another. With detach enabled, aborting that replay is meant to leave the underlying run alone. But watchDetach stops its timer and polling when settle() runs. Both runExecution and its non-streaming path still wait for output or a successful detach; neither wait observes the abort. The Pi dispatcher waits for the executor to settle before returning the tool result.

Example: A command has already detached on a timer and is still running when its call is replayed. The user stops the replay before its detach timer fires. The command correctly keeps running, but the replay now waits for it to finish instead of releasing the cancelled turn.

Recommended fix: Add an abort outcome to both replay wait paths when keepRunning is true. Release the replay’s stream or result subscription without killing the run, and settle the tool call with a cancellation outcome. Test that the replay settles after abort while the underlying execution is still pending.

Devin Review


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

Comment thread docs/09_tool_interface.md
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant