GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(codemode): make Code Mode runs suspendable and resumable by jlongster · Pull Request #61856 · anomalyco/opencode

Conversation

@jlongster

@jlongster jlongster commented Nov 5, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Summary

A Code Mode run can now be suspended at any step, saved as bytes, and resumed later in a brand-new runtime or another process. It continues exactly where it stopped. Nothing in OpenCode uses this yet: packages/core is unchanged, and execute() behaves as before.

To make that possible, the interpreter no longer keeps program state in host JavaScript generators, which can't be saved. Every activation, await, loop, generator and built-in callback is now a plain-data frame, run by a step loop with no Effect inside.

What changed

  • src/machine/: a new evaluator with no effect imports.
    • Frames and stepping: Frame { kind, node, phase, scope, slots } frames, stepped by a loop that returns done | host | slice | stuck.
    • Calls, await and yield: these are stack operations. await cuts the stack at the innermost async boundary and parks the slice on the promise as data. A generator keeps its suspended frames on the generator object.
    • Fast path: expressions that can't run program code still evaluate inline, without frames.
  • The scheduler is data.
    • Jobs, promise reactions, resolvers, bound functions and host calls are tagged records instead of closures.
    • Map and Set use an ordered table with integer cursors, and built-in iterators are position records.
  • Built-ins that call program code are frame kinds. That covers array callbacks and sort, JSON reviver/replacer, replace with a function, Promise combinators, iterator helpers, tool-call argument crossing and toBoundary. No host generator is left anywhere: the old runner, the generator-based evaluator and the bridge are deleted.
  • A thin Effect driver (src/interpreter/driver.ts) is the only code that talks to the host. It forks tool calls as fibers with the caller's services. Hooks, interruption, timeouts, maxToolCalls, diagnostics and output bounding are unchanged.
  • Snapshots (src/snapshot/):
    • Encoding: plain JSON that keeps shared references. Built-ins, frame kinds and tools are saved by name, and AST nodes by stable node id.
    • Header: a build id, a host-globals hash, source hashes, and the budget used so far.
    • Restore: re-parses the stored sources. It refuses a mismatched build, host or source with CodeMode.SnapshotError.
  • API:
    • runtime.start(code, bindings?) returns a Run with result and suspend.
    • runtime.resume(state | bytes, outcomes?) continues a saved run, and CodeMode.toBytes / fromBytes convert a state to bytes and back.
    • timeoutMs and maxToolCalls count across resumes.
  • Durable tools: Tool.make({ durable: { start, attach, lookup, cancel }, retry: "safe" | "unsafe" }).
    • Keys: each call has an idempotency key, <runId>:<id>, which is passed to execute(input, { key }) and to both hooks.
    • On suspend: durable work keeps running and is reattached on resume. Any other call still running is either retried, if its tool is retry: "safe", or rejected with an error the program can catch.

The API is documented in packages/codemode/README.md ("Suspending and resuming a run").

Verification

  • test262 (vendored corpus at the pinned revision): 13,329 pass, 1,678 skip, 1 fail. That matches dev; the one failure, language/global-code/import.js, also fails there.
  • Save-and-restore mode: bun run test:roundtrip saves every run to bytes and restores it into a fresh runtime at every host call and every 5 steps. The full suite and test262 give identical results that way, which is about 208,000 round trips across test262.
  • Code Mode suite: 1,500 tests before, about 1,550 now. New tests check that state is data, cover suspend and resume, durable tools, keys, and that no frame is ever opaque.
  • Core: the core Code Mode tests and the core typecheck pass.

Performance

script/bench.ts and a realistic 816-tool-call analytics script, fastest runs on a loaded 4-core machine:

dev this PR
array callbacks (50k) 258 ms 113 ms
promise fan-out (5k) 36 ms 13 ms
fib 22 34 ms 18 ms
Map/Set ops 73 ms 39 ms
816-tool-call analytics script 2.0–2.2 s 1.1 s

For 25 real Code Mode scripts taken from sessions (stub tools, identical results on both builds), total time drops from 462 ms to 250 ms, and the typical script is 1.12× faster. Each execution costs about 0.08 ms more to set up, so scripts under 1 ms are slightly slower.

Snapshot sizes for three of those scripts, suspended at 50% and 90% of their steps: 16–42 KB of JSON (2.7–4.3 KB gzipped). Suspending takes about 2 ms.

Notes

  • The plan was to write callback built-ins in Code Mode itself (a "prelude"). They're hand-written frame kinds instead, which kept error messages and call-site locations byte-identical and turned out faster.
  • A tool call now starts at the end of the current job instead of at its call site. Admission order and the toolCalls order are unchanged.
  • Functions an extension returned have no data form. After a resume, calling one throws a TypeError.

Visual

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 72" width="240" height="72" fill="none" stroke="currentColor">
  <style>
    .bar { animation: run 4s linear infinite; transform-origin: 20px 36px; }
    .pause { opacity: 0; animation: pause 4s linear infinite; }
    @keyframes run { 0% { transform: scaleX(0.05) } 40% { transform: scaleX(0.5) } 60% { transform: scaleX(0.5) } 100% { transform: scaleX(1) } }
    @keyframes pause { 0%, 39% { opacity: 0 } 41%, 59% { opacity: 1 } 61%, 100% { opacity: 0 } }
    @media (prefers-reduced-motion: reduce) { .bar, .pause { animation: none } .bar { transform: scaleX(0.5) } .pause { opacity: 1 } }
  </style>
  <rect x="20" y="28" width="200" height="16" rx="8" opacity="0.25" />
  <rect class="bar" x="20" y="28" width="200" height="16" rx="8" fill="currentColor" opacity="0.7" stroke="none" />
  <g class="pause" stroke-width="3" stroke-linecap="round">
    <line x1="116" y1="12" x2="116" y2="22" />
    <line x1="124" y1="12" x2="124" y2="22" />
    <path d="M112 52h16v8h-16z" stroke-width="1.5" opacity="0.6" />
  </g>
</svg>

Added by the opencode bot (AI-generated).

Public API: adds suspend/resume (runtime.start, runtime.resume, CodeMode.toBytes/fromBytes, SnapshotError) and durable tools (Tool.make({ durable, retry }), an idempotency key for execute and the hooks) to @opencode/codemode (backwards compatible)

Update: self-hosted prelude and sealed frame kinds

  • Prelude: built-ins that call program code are now mostly written in Code Mode JavaScript (src/prelude/). The prelude is parsed once per process, and its functions are named by path, so snapshots refer to them by name. This covers collection constructors, groupBy, the Set methods, Object.fromEntries, iterator helpers and Iterator.from, the JSON reviver, replace callbacks and Array.from over iterables. Array callbacks, comparator sort and the Promise combinators stay native, for speed and interruption handling. Frame kinds drop from 83 to 67, and all 18 iteration consumers are gone. src is now +9,834 / −5,012 lines vs dev. Built-ins moved to the prelude are 2–6× slower on 50k-element inputs.
  • Sealed frame kinds: the frame-kind registry is sealed once the package loads, so the snapshot build id no longer depends on what else was imported. The test262 harness no longer registers a kind. This also fixes the order-dependent failures in single-process save-and-restore runs.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
jlongster added 22 commits November 5, 2026 00:53
@jlongster
test(codemode): add interpreter benchmarks
e99c23f
@jlongster
refactor(codemode): number AST nodes with stable node ids
72d9582
@jlongster
refactor(codemode): name intrinsics deterministically
2daa79a
@jlongster
refactor(codemode): make bound functions and resolvers data kinds
377875d
@jlongster
refactor(codemode): keep Map, Set, iterators, weak collections and Re…
90b228d
…gExp state as data
@jlongster
refactor(codemode): queue jobs, reactions and host calls as data records
9c239c1
@jlongster
test(codemode): report the fastest run in benchmarks
252b78a
@jlongster
refactor(codemode): share synchronous operations and signal types bet…
9d233cf
…ween evaluators

Move the operators, property references, hoisting and iterator checks that never run
program code out of the generator evaluator into operations.ts, and the driver's signal
and activation types out of runner.ts into signals.ts, which needs no Effect at run time.
The machine evaluator builds on both.
@jlongster
feat(codemode): add the machine evaluator behind CODEMODE_EVALUATOR
a706db7
Program code can now run as explicit frames on a stack stepped by a loop (src/machine)
instead of host generators. Each frame is a kind, a node, a phase, slots and a scope chain;
expressions that cannot run program code still finish inline within one step. Abrupt
completions unwind frame by frame through try, for...of and array-pattern handlers.

Async bodies, generator bodies and calls the runner starts are machine tasks the runner
drives as activation bodies; built-ins that call program code run as opaque native frames
whose program calls become frames. CODEMODE_EVALUATOR=machine selects it; the generator
evaluator stays the default.
@jlongster
test(codemode): run the suite on both evaluators
8a4479e
@jlongster
refactor(codemode): keep the machine's hot paths free of per-evaluati…
1dd7488
…on closures
@jlongster
refactor(codemode): run every job on the machine and drive it from a …
ad4fd72
…thin Effect loop

The machine now owns the scheduler: job queue, inbox, parked awaits, unhandled
rejections, and promise operations. An await cuts the stack at the innermost
async boundary (the program's frame or an async function's call frame) and
parks the frames on the promise as data. Host calls are HostCall records the
machine hands to the driver at its stops; blocking host work is a blocking
HostCall. The generator evaluator, runner.ts, and CODEMODE_EVALUATOR are gone.
@jlongster
refactor(codemode): label blocking host calls and drop an unused boun…
14ccd9e
…dary getter
@jlongster
refactor(codemode): run generators, yield* and the async-from-sync ad…
b54d451
…apter as frames
@jlongster
test(codemode): check suspended generators and for await state is data
cd0478a
@jlongster
refactor(codemode): run array, collection, iterator helper and promis…
92ba3e6
…e built-ins as data frames
@jlongster
refactor(codemode): run JSON, Date, tool calls, search and extension …
a9d9cb7
…calls as data frames and drop the host generator bridge
@jlongster
docs(codemode): describe built-in frames instead of native host gener…
fce860c
…ators
@jlongster
feat(codemode): save and restore a run's state as a snapshot, with a …
5ad0d06
…round-trip test mode
@jlongster
feat(codemode): suspend and resume runs, with durable tool calls and …
3eab346
…idempotency keys
@jlongster
feat(codemode): pass each tool call its idempotency key, at the tool …
edbeec8
…and at both hooks
@jlongster
fix(codemode): report a durable call cancelled with its run to tool.a…
dc08129
…fter, and document suspend and resume hooks
@github-actions github-actions Bot added the contributor label Nov 5, 2026
opencodejr[bot]
opencodejr Bot reviewed Nov 5, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The suspend/resume machinery works as described, but there is one bug: the snapshot build id changes with what a process has loaded.

I ran the full Code Mode suite 3 times and it fails on 1 of 1551 tests every time (base: 1500/1500). resumes in another process gets a SnapshotError saying the state was saved by another build. The test passes alone and with every other test file except test262.test.ts: its harness registers a Throws frame kind, which changes the parent's build id. test:roundtrip (1551 pass), the core Code Mode tests and tsc --noEmit all pass. Details inline.

Public API (@opencode/codemode), all backwards-compatible additions:

  • runtime.start / runtime.resume
  • CodeMode.toBytes / fromBytes / SnapshotError
  • the Snapshot / SnapshotHeader types
  • Tool.make({ durable, retry })
  • Tool.execute(input, context?), which gains an optional key
  • the idempotency key passed to the hooks

Existing execute() callers and Tool.make({ execute }) tools are unaffected. One behaviour change: extension-returned functions throw after a resume.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread packages/codemode/src/snapshot/snapshot.ts
let build: string | undefined

/** This build's id; a snapshot resumes only on the build that wrote it. */
export const buildId = (bare: Bare): string =>

@opencodejr opencodejr Bot Nov 5, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The build id hashes codecShape(), which reads the process-global kinds/consumers registries, and the result is cached the first time it is used. So the id depends on which modules have registered frame kinds, and when, rather than only on the build. In this PR's own full bun test run, test262/run.ts registers Throws before the save. The child process in resumes in another process then computes a different id and rejects the state (saved by another Code Mode build (…9c2c86…); this runtime is …41c90a…). That test fails on every full-suite run.

A host that loads an extension or module defining a kind lazily, or in a different order from the resuming process, would hit the same refusal. Could the id come from the intrinsics plus a fixed, build-time set of kinds, or could the registry be frozen before the first buildId call?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@jlongster jlongster mentioned this pull request Nov 5, 2026
feat(codemode): suspend only durable work, resume with host outcomes, and save fetch responses #62086
Closed
jlongster added 3 commits November 5, 2026 15:04
@jlongster
fix(codemode): seal frame kinds so the snapshot build id doesn't depe…
cac2611
…nd on what was imported
@jlongster
refactor(codemode): add a Code Mode prelude for built-ins that call p…
1acdf4b
…rogram code, starting with array callbacks
@jlongster
refactor(codemode): keep array callbacks and sort native, move Array.…
0bff057
…from iterables and toLocaleString to the prelude
opencodejr[bot]
opencodejr Bot reviewed Nov 5, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The build-id issue is fixed: frame kinds and consumers are now sealed once the package has loaded, so the id no longer depends on what a process imported. The full suite passes twice in a row (1554/1554, including resumes in another process and the new kinds.test.ts), as do test:roundtrip and tsc --noEmit. Every module in src that defines a kind or consumer is imported by machine/kinds.ts. The public API is unchanged since the last review. Nothing new to flag.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@jlongster
refactor(codemode): move collection constructors, groupBy, forEach, g…
d8504a9
…etOrInsertComputed, and Set methods to the prelude
jlongster added 5 commits November 5, 2026 15:24
@jlongster
refactor(codemode): move fromEntries, sumPrecise, AggregateError, Uin…
fa7b94f
…t8Array sources, and Headers/URLSearchParams pairs to the prelude
@jlongster
refactor(codemode): move iterator consumers, Iterator.from, the JSON …
9cc8ec9
…reviver, and string replace callbacks to the prelude; drop Drain and consumers
@jlongster
test(codemode): cover prelude round trips, names, privacy, and failur…
6759bff
…e locations
@jlongster
refactor(codemode): write iterator helpers and Iterator.from as prelu…
2cdf6a6
…de generators; drop the Helper cursor and its kinds
@jlongster
chore(codemode): tidy the prelude helpers and native-kind notes
7e0fa40
opencodejr[bot]
opencodejr Bot reviewed Nov 5, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The build-id fix is still in place: kinds stay sealed, and kinds.test.ts plus the cross-process resume test pass. The prelude move doesn't change behaviour for the built-ins I tried against dev (collection forEach, groupBy, the new Map error, iterator helpers, replace callbacks). bun test and test:roundtrip both pass (1557/1557), and tsc --noEmit is clean. The public API is the same as in my earlier review. Nothing new to flag.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@jlongster

jlongster commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Closing: superseded by a new bytecode VM engine that lands side by side with dev's original interpreter behind CodeMode.make({ engine: "vm" }), plus the OpenCode integration behind an experimental flag. Links to follow. The branch is kept for reference.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jlongster jlongster closed this Nov 6, 2026
This was referenced Nov 6, 2026
feat(codemode): add a bytecode VM engine behind CodeMode.make({ engine: "vm" }) #62357
Merged
feat(core): run Code Mode on the bytecode VM behind experimental.codemodeVm #62358
Merged
@jlongster

jlongster commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #62357 (bytecode VM engine side by side with dev's interpreter, CodeMode.make({ engine: "vm" })) and #62358 (OpenCode integration behind experimental.codemode_vm).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

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

Reviewers

@opencodejr opencodejr[bot] opencodejr[bot] left review comments

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

contributor

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

1 participant

@jlongster
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.