Skip to content

feat(codemode): idempotent and durable tools, and safe suspension on the VM - #62459

Merged
jlongster merged 4 commits into
devfrom
codemode-durable-tools
Nov 7, 2026
Merged

jlongster merged 4 commits into
devfrom
codemode-durable-tools

Conversation

@jlongster

@jlongster jlongster commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements Tool.idempotent and Tool.durable({ start, wait, cancel }) wrappers for Tool.make's execute, stable <runId>:<callId> call keys, safe suspension rules, and extension snapshot hooks in @opencode/codemode on the bytecode VM (engine: "vm").

API

1. Tool execution wrappers (Tool.make, Tool.idempotent, Tool.durable)

// plain (default): a suspend is refused while it runs
Tool.make({
  description: "...",
  input: ...,
  output: ...,
  execute: (input, { key }) => compute(input),
})

// idempotent: safe to run again; interrupted on suspend, rerun on resume with the same key
Tool.make({
  description: "...",
  input: ...,
  output: ...,
  execute: Tool.idempotent((input, { key }) => Db.get(input.name)),
})

// durable: keeps running across a suspend, reconnected through its JSON data on resume
Tool.make({
  description: "...",
  input: ...,
  output: ...,
  execute: Tool.durable({
    start: (input, { key }) => Jobs.submit(input, key).pipe(Effect.map((id) => ({ id }))),
    wait: ({ id }, { key }) => Jobs.wait(id),
    cancel: ({ id }) => Jobs.kill(id),
  }),
})
  • Plain (execute: (input, { key }) => ...): suspend is refused while the call is running.

  • Tool.idempotent(execute): idempotent/read-only work safe to run again. If a suspend lands while the call is running, the VM detaches and interrupts it without firing tool.after, keeps the call in the snapshot as queued, and re-runs it on resume with the same key without double-counting it against maxToolCalls.

  • Tool.durable({ start, wait, cancel }):

    • start(input, { key }) => Effect<Data /* Json */> begins the work and returns JSON data (inferred into wait and cancel);
    • wait(data, { key }) => Effect<Output> connects to the running work and waits for its result;
    • cancel(data) => Effect<void> stops the work when the run is interrupted for real or ends, never when it is suspended.

    While start is running, the call blocks suspend. Once start returns its JSON data, the call is in the started state with its data saved in the snapshot, and suspend is allowed.

    wait is not tied to the program's JavaScript await: the VM calls wait(data) right after start returns, and calls wait(data) again for every started call right when resume starts, whatever the program does with the call's promise (await, Promise.all, .then, or holding the unawaited promise in a variable and awaiting it later).

2. Call keys and runId

Every host call gets a stable key <runId>:<callId>, saved in the snapshot:

  • runtime.program(code, bindings?, { runId }) accepts an explicit runId (or generates a UUID by default).
  • Tools receive { key } as the second argument to execute(input, { key }) (and start(input, { key }) / wait(data, { key })).
  • tool.before and tool.after hooks receive key on ToolInvocation ({ name, input, key }).
  • SuspendError.running includes { key, path } for every call blocking suspension.

Safety Rule Table

Suspend is allowed only when every in-flight host call is queued, Tool.idempotent, or Tool.durable in started. Otherwise program.suspend() fails with SuspendError (leaving the run undisturbed) and lists each blocking call's { key, path } in running:

In-flight call state Suspend allowed? Behaviour on suspend & resume
Queued tool call (status: "queued") Yes Saved as queued; launched on resume.
Tool.idempotent tool (status: "running") Yes Interrupted without firing tool.after; saved as queued (admitted: true); re-run on resume with the same key without double-counting maxToolCalls.
Tool.durable tool in started (status: "started") Yes wait fiber detached without firing tool.after or cancel; JSON data saved in snapshot; VM calls wait(data) on resume.
Tool.durable tool still in start (status: "running") No (SuspendError) Refused with { key, path } in error.running; run continues undisturbed.
Plain tool (default) or search (status: "running") No (SuspendError) Refused with { key, path } in error.running; run continues undisturbed.
Extension call (async, queued, or sync on the stack) No (SuspendError) Refused with { key, path } in error.running; run continues undisturbed.

Extension Snapshot Hooks

Extension.make({
  name: "fetch",
  globals: { fetch: Extension.async(fetch) },
  snapshot: {
    encode: (value) => value[saved],
    decode: (data) => makeResponse(data),
  },
})
  • encode(value) receives a host value returned by one of the extension's functions and returns plain data (JSON values and Uint8Arrays), recorded once per root object as a HostValue record, with each method recorded as a HostFunction record.
  • On resume, decode(data) reconstructs the host value once per HostValue record and rebinds its methods onto the restored program functions.
  • Without snapshot hooks, extension-returned functions keep today's LostNative behaviour.
  • In the follow-up core PR, packages/core/src/codemode/fetch.ts will attach a private symbol holding { url, status, statusText, redirected, headers, body: Uint8Array } to each resolved response and use snapshot: { encode, decode } to rebuild the response and its text(), json(), bytes(), and headers methods on resume (while an in-flight fetch stays not durable).

Out of Scope

  • Package only: no changes in packages/core in this PR.
  • No suspension triggers or snapshot storage.
  • No real tools marked idempotent or durable yet (follow-up core PR will mark search, list/read tools, MCP resources, and worktree list as idempotent, subagent as durable, and keep fetch, shell, MCP tools, and plugin tools plain).

Verification

  • bun run test:legacy: 1,630 pass, 0 fail
  • bun run test:vm: 1,630 pass, 0 fail
  • bun run test:roundtrip: 1,629 pass, 1 skip, 0 fail
  • test262 on VM (CODEMODE_ENGINE=vm bun test test/test262.test.ts): 13,329 pass, 1,678 skip, 1 known fail (language/global-code/import.js)
  • bun run typecheck:tsc in packages/codemode and packages/core: 0 errors
  • Core Code Mode tests (packages/core: bun test test/tool-execute.test.ts test/codemode), with flag off and with OPENCODE_FLAGS=codemode_vm: 51 pass, 0 fail on both
  • bun run script/bench.ts --mixed: no regression

Visual

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 72" width="240" height="72" fill="none">
  <style>
    .track { stroke: currentColor; stroke-opacity: 0.18; stroke-width: 1.5; stroke-dasharray: 3 3; }
    .box { stroke: currentColor; stroke-width: 1.5; rx: 6; fill: currentColor; fill-opacity: 0.05; }
    .pill { fill: currentColor; }
    .label { font: 600 9px ui-monospace, SFMono-Regular, Menlo, monospace; fill: currentColor; }
    .sub { font: 500 8px ui-monospace, SFMono-Regular, Menlo, monospace; fill: currentColor; fill-opacity: 0.65; }
    .pulse { animation: flow 3.6s ease-in-out infinite; }
    .snap { animation: badge 3.6s ease-in-out infinite; }
    @keyframes flow {
      0%, 15% { transform: translateX(0px); opacity: 1; }
      40%, 60% { transform: translateX(74px); opacity: 0.85; }
      85%, 100% { transform: translateX(148px); opacity: 1; }
    }
    @keyframes badge {
      0%, 30%, 70%, 100% { opacity: 0.35; }
      45%, 55% { opacity: 1; }
    }
  </style>
  <line class="track" x1="56" y1="36" x2="184" y2="36" />
  <rect class="box" x="14" y="16" width="64" height="40" rx="6" />
  <text class="label" x="24" y="33">start()</text>
  <text class="sub" x="24" y="46">r:0 data</text>
  <g class="snap">
    <rect class="box" x="88" y="16" width="64" height="40" rx="6" />
    <text class="label" x="97" y="33">suspend</text>
    <text class="sub" x="97" y="46">snapshot</text>
  </g>
  <rect class="box" x="162" y="16" width="64" height="40" rx="6" />
  <text class="label" x="174" y="33">wait()</text>
  <text class="sub" x="169" y="46">resumed</text>
  <circle class="pill pulse" cx="46" cy="16" r="3.5" />
</svg>

Added by the opencode bot (AI-generated).

Public API: adds Tool.idempotent / Tool.durable execute wrappers, execute(input, { key }), ToolInvocation.key, SuspendError.running[].key, program(..., { runId }) and Extension.snapshot to @opencode/codemode (additive; snapshot format changes)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The VM side works as described. I ran the new suspend tests, the full VM and round-trip suites and typecheck:tsc, all green. I also checked the timeout/interrupt path of a reconnectable tool on both engines with a throwaway test. On vm, cancel(handle) runs as described. On the default legacy engine it never runs (see inline comment).

Public API (@opencode/codemode, published). Everything is additive and backwards compatible for existing callers:

  • Tool.make options gain durable?: false | "rerun" | { start, attach, cancel }, and execute becomes optional when reconnectable hooks are given. execute also receives a second { key } argument.
  • The Tool type gains durable?, and execute is now (input, context?).
  • ToolInvocation gains a required key. Code that only reads it is unaffected; code that builds ToolInvocation objects itself must now add key.
  • SuspendError.running items go from { path } to { key, path }.
  • VmRuntime.program(code, bindings?, options?) takes a new ProgramOptions { runId? }, which is also exported.
  • Extension.make / Extension gain an optional snapshot: { encode, decode }.
  • The snapshot format changes: the header gains runId, HostCall records gain key/handle/admitted, and there are new HostValue/HostFunction records. States from older builds already fail to resume because of the build hash check.

Comment thread packages/codemode/src/tool.ts Outdated
execute: (input, context = { key: crypto.randomUUID() }) => {
if (execute !== undefined) return execute(input, context)
const reconnectable = durable as Reconnectable<unknown, unknown, R>
return Effect.flatMap(reconnectable.start(input, context), (handle) => reconnectable.attach(handle, context))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When a tool only provides reconnectable hooks, this fallback runs start then attach and never calls cancel. It's what runs on the legacy engine, which is still the default, and for anyone who calls tool.execute directly. If the run is interrupted (timeout, abort) during attach, the started work keeps running. I reproduced it: the same tool with a never-ending attach and timeoutMs: 100 has cancel({id:1}) called on vm, but nothing on legacy. This also goes against the README's statement that cancel runs when the run is interrupted for real. Wrapping attach so it calls cancel(handle) on interrupt (e.g. Effect.onInterrupt) would make both engines behave the same.

@jlongster jlongster changed the title feat(codemode): durable tools and safe suspension on the VM feat(codemode): idempotent and durable tools, and safe suspension on the VM Nov 7, 2026

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new commit swaps the durable option for Tool.idempotent(execute) and Tool.durable({ start, wait, cancel }) wrappers on execute. The suspend behaviour is the same. I re-ran the suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc: all green.

My earlier point is not addressed yet. With the new API, a Tool.durable tool still never has cancel called when the run is interrupted on the legacy engine, which is the default, or when tool.execute is called directly. I reproduced it again: on a 100 ms timeout, vm calls cancel({id:1}) and legacy calls nothing (see the open thread).

Public API (@opencode/codemode, compared with the base), all additive:

  • New Tool.idempotent and Tool.durable wrappers, plus the ExecuteFn, Idempotent, Durable and DurableOptions types.
  • Tool.make's execute also accepts these wrappers, and gets a second { key } argument.
  • The Tool type gains mode?, and execute is now (input, context?).
  • ToolInvocation gains a required key.
  • SuspendError.running items go from { path } to { key, path }.
  • program(code, bindings?, { runId }) takes a new ProgramOptions.
  • Extension gains an optional snapshot: { encode, decode }.
  • The snapshot format changes: the header gains runId, HostCall records gain key, data and admitted, and there are new HostValue/HostFunction records.

Existing callers keep working. Code that builds ToolInvocation objects itself must now add key.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

My earlier point is addressed. Tool.durable(...) now cancels the started work on interrupt through acquireUseRelease, so the legacy engine and direct tool.execute callers behave like the VM. On a 100 ms timeout, I saw cancel({id:1}) called on both engines. I re-ran the suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc: all green.

Public API: unchanged from my last review. The new commit splits the requirement type into DurableOptions' RStart/RWait/RCancel parameters, and Idempotent/Durable values can now be called directly. Everything stays additive compared with the base.

One new concern: restoreStart relies on Effect's private internals (see inline comment).

Comment thread packages/codemode/src/tool-runtime.ts Outdated

// Runs `make` with interruptibility restored unless `make()` itself is `Effect.uninterruptible`, so an
// uninterruptible `start` returns its data into the outer mask without interrupting at its exit boundary.
const restoreStart = <A, E>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

restoreStart reads Effect's private "~effect/Effect/args" field and changes the fiber's _stack and interruptible flag directly. Neither is public API, so an Effect upgrade could silently change what this does. It could drop the data start returned, which leaks the job, or leave the fiber's stack corrupted. If the goal is that a start that has finished never has its data dropped, running start fully uninterruptible, as Effect.acquireRelease does with its acquire step, guarantees that without touching internals. The cost is that a slow start can't be interrupted, which it already can't be during a suspend. If start must stay interruptible, it would be safer to handle that inside the durable tool, for example by letting the tool's own start check its key on retry.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The Effect-internals concern is addressed: restoreStart is gone and start is back to a plain Effect.suspend.

This commit also undoes the earlier cancel fix. Tool.durable's execute is back to Effect.flatMap(start, wait), so an interrupted run on the legacy engine (the default), or a direct tool.execute caller, leaks the started work. I re-checked it: on a 100 ms timeout, vm calls cancel({id:1}) and legacy calls nothing (see inline comment).

The suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc all pass. The public API is unchanged since my last review.

const wait = options.wait as (data: Schema.Json, context: ToolContext) => Effect.Effect<Output, unknown, R>
return Object.assign(
(input: Input, context: ToolContext): Effect.Effect<Output, unknown, R> =>
Effect.flatMap(options.start(input, context), (data) => wait(data, context)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This brings back the leak from the earlier thread: with flatMap, nothing calls cancel(data) when wait is interrupted on the legacy engine or through a direct tool.execute. I confirmed it at this commit: with a 100 ms timeout, legacy never calls cancel, while vm does. The previous Effect.acquireUseRelease(start, wait, (data, exit) => interrupted ? cancel(data) : void) covered it, and it uses no internals.

@jlongster
jlongster merged commit c33eaa1 into dev Nov 7, 2026
13 checks passed
@jlongster
jlongster deleted the codemode-durable-tools branch November 7, 2026 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant