feat(codemode): expose the VM's suspendable program API (#62413)

This commit is contained in:
James Long authored and GitHub committed 2026-11-06 16:44:13 -06:00
1 parent 0f090704c7
commit 33f94fce96
18 files changed
+1222 -97

No files matched your search

+53 -2
View File
@@ -97,8 +97,59 @@ denies it: the host function is never called, and the program catches the failur
fails the way the call itself would: a tool call or asynchronous global rejects its promise, and a synchronous global
throws.
`engine: "vm"` runs programs on the bytecode VM in `src/vm` instead of the default `"legacy"` interpreter. It is
experimental: `execute` has the same signature and results on both engines.
### Bytecode VM and suspending/resuming a run (experimental, `engine: "vm"`)
Pass `engine: "vm"` to `CodeMode.make` or `CodeMode.execute` to run programs on the bytecode VM instead of the default
`"legacy"` AST interpreter. `runtime.execute(code, bindings?)` keeps the same `Effect<CodeMode.Result>` signature on
both engines.
On `engine: "vm"`, `CodeMode.make` returns a `CodeMode.VmRuntime`, which can also run a program step by step:
`runtime.program(code, bindings?)` makes a `CodeMode.Program`, and nothing runs until `program.run()`. `run()` runs it in
the current fiber until it ends or is suspended, and gives a `CodeMode.Outcome`: a `Result`, or:
```ts
type Suspended = {
ok: "suspended"
state: CodeMode.Snapshot // JSON; CodeMode.toBytes / CodeMode.fromBytes convert it
}
const runtime = CodeMode.make({ tools, engine: "vm" })
// inline
const outcome = yield* runtime.program(code).run()
// in the background, suspended from another fiber
const program = runtime.program(code)
const fiber = yield* Effect.forkChild(program.run())
const suspended = yield* program.suspend() // the same Suspended that run() returns
const outcome = yield* Fiber.join(fiber)
// later, in this process or another one built from the same version
yield* runtime.resume(CodeMode.toBytes(suspended.state)).run()
```
The default runtime has no `program` or `resume`. A program runs once: running it again is a defect, so make another
with `runtime.program` or `runtime.resume`. `run()` owns the run's host calls: interrupting it interrupts the program and
every call in progress.
`program.suspend(options?)` saves the run's state and stops it at once, and `run()` returns the same `Suspended`. It
can be suspended only while no host call (tool, `search`, `fetch`, or extension call) is running. When one is in
progress, `suspend` fails with a `CodeMode.SuspendError` naming each blocking call by its path (`tools.x.y`, `fetch`),
and the run goes on untouched. Tool calls queued but not started don't block: they start on resume. Outcomes already
waiting in the inbox are part of the state. A suspend after the run ended gives its result; one issued before `run()`
has started waits for it to start (and for ever if it never runs).
The suspend is immediate: the program shares the thread with the caller, so it is at a step boundary. Its checks, saving
the state, and checking it against `options.maxBytes` all happen before anything about the run changes, so a state that
can't be saved or is too large fails the suspend the same way.
A resumed run keeps the limits it was saved with: `timeoutMs` counts active time across every resume, and `maxToolCalls`
counts every call of the run. A state resumes only on the same build of this package and with the same extensions. The
state is checked when the resumed program runs: its `run()` fails with a `CodeMode.SnapshotError` when it can't be
resumed here or is malformed. Built-ins are saved by name and only their changes are copied.
Set `CODEMODE_ROUNDTRIP=1` (`bun run test:roundtrip`) to run the tests on the VM with every run saved to bytes and
restored into a brand-new runtime at every host call and every few steps.
### `Extension.make`
+1 -1
View File
@@ -80,7 +80,7 @@ const argument = (flag: string) => {
}
const iterations = Number(argument("--iterations") ?? 7)
const filter = argument("--filter")
const engine = (argument("--engine") as "legacy" | "vm" | undefined) ?? "vm"
const engine = (argument("--engine") as CodeMode.Engine | undefined) ?? "vm"
const mixed = process.argv.includes("--mixed")
const jsc = mixed || process.argv.includes("--jsc")
const exec = Vm.prototype["exec"]
+143 -20
View File
@@ -1,15 +1,18 @@
import { Effect, Schema } from "effect"
import { Deferred, Effect, Exit, Schema } from "effect"
import { fromJson } from "./data.js"
import type { Extension } from "./extension.js"
import { executeProgram } from "./interpreter/execute.js"
import { extensionGlobals } from "./interpreter/extensions.js"
import { globalNames } from "./interpreter/globals.js"
import { scanTools } from "./scan.js"
import { fromBytes, SnapshotError, SuspendError, toBytes } from "./suspend-error.js"
import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js"
import type { Tools } from "./tools.js"
import type { VmEngine } from "./vm/index.js"
export { scanTools }
export { fromBytes, scanTools, SnapshotError, SuspendError, toBytes }
export type SnapshotHeader = VmEngine.SnapshotHeader
export type Snapshot = VmEngine.Snapshot
/** A tool call admitted during an execution. */
export type {
@@ -45,6 +48,15 @@ export type ResolvedExecutionLimits = {
readonly maxOutputBytes: number | undefined
}
/** Execution engine: the default AST generator interpreter (`"legacy"`) or the experimental bytecode VM (`"vm"`). */
export type Engine = "legacy" | "vm"
/** How `program.suspend` saves a run's state (`engine: "vm"` only). */
export type SuspendOptions = {
/** The most bytes a saved state may take; a larger one fails the suspend, and the run goes on. */
readonly maxBytes?: number
}
/** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
export type Options<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = {
/** Explicit tools exposed to the program as `tools`. */
@@ -53,10 +65,13 @@ export type Options<Provided extends Record<string, unknown> = {}, Extensions ex
hooks?: ToolRuntime.Hooks<Environment<Provided, Extensions>>
/** Host functions and objects exposed as globals, also importable by Node module name; see `Extension.make`. */
extensions?: Extensions
/** Resource limits enforced on each execution. */
/** Resource limits enforced on each execution. Time counts active time only, across every resume of a run. */
limits?: ExecutionLimits
/** Interpreter that runs programs. `"vm"` is the experimental bytecode VM; the default is `"legacy"`. */
engine?: "legacy" | "vm"
/**
* Interpreter that runs programs. `"vm"` is the experimental bytecode VM, whose runtime (`VmRuntime`) can also
* suspend and resume runs; the default is `"legacy"`.
*/
engine?: Engine
}
/** The Effect environment an execution needs: what the tools and the extensions' Effect globals require. */
@@ -134,12 +149,48 @@ export const Result = Schema.Union([Success, Failure])
/** Result of executing a CodeMode program. Program failures are data, not Effect failures. */
export type Result = typeof Result.Type
/** A run stopped by `program.suspend`: its whole state, to resume with `VmRuntime.resume`. */
export type Suspended = {
readonly ok: "suspended"
readonly state: Snapshot
}
/** How a run of a program ended: its result, or its saved state once suspended. */
export type Outcome = Result | Suspended
/** Reusable confined runtime over explicit tools. */
export type Runtime<R = never> = {
readonly catalog: ReadonlyArray<ToolDescription>
readonly execute: (code: string, bindings?: Readonly<Record<string, DataValue>>) => Effect.Effect<Result, never, R>
}
/** A runtime on the bytecode VM (`engine: "vm"`, experimental): it can also suspend runs and resume them. */
export type VmRuntime<R = never> = Runtime<R> & {
/** A program ready to run once; nothing runs until `program.run()`. */
readonly program: (code: string, bindings?: Readonly<Record<string, DataValue>>) => Program<R>
/**
* A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the
* same build with the same extensions. The state is checked when it runs: `run()` fails with a `SnapshotError` when
* it can't be resumed here.
*/
readonly resume: (state: Snapshot | Uint8Array) => Program<R, SnapshotError>
}
/**
* One run of a program on the VM. `run()` runs it in the current fiber until it ends or is suspended, and owns its host
* calls: interrupting `run()` interrupts them. A program runs once: running it again is a defect.
*/
export type Program<R = never, E = never> = {
readonly run: () => Effect.Effect<Outcome, E, R>
/**
* Saves the run's state and stops it, at once, from another fiber: `run()` then returns the same `Suspended`, and so
* does this. It fails with a `SuspendError`, leaving the run running, while a host call (tool, `search`, `fetch`, or
* extension call) is in progress, or when the state can't be saved or is over `options.maxBytes`. A run that already
* ended gives its result. Before `run()` starts, this waits for it to start.
*/
readonly suspend: (options?: SuspendOptions) => Effect.Effect<Outcome, SuspendError>
}
const validateLimit = (name: keyof ExecutionLimits, value: number | undefined, minimum: number): number | undefined => {
if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) {
throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`)
@@ -163,15 +214,20 @@ export const execute = <
make(options).execute(options.code, options.bindings)
/** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
export const make = <
export function make<
const Provided extends Record<string, unknown> = {},
const Extensions extends ReadonlyArray<Extension> = [],
>(
options: Options<Provided, Extensions> = {},
): Runtime<Environment<Provided, Extensions>> => {
const prepared = ToolRuntime.prepare<Environment<Provided, Extensions>>(
(options.tools ?? {}) as Tools<Services<Provided>>,
)
>(options: Options<Provided, Extensions> & { engine: "vm" }): VmRuntime<Environment<Provided, Extensions>>
export function make<
const Provided extends Record<string, unknown> = {},
const Extensions extends ReadonlyArray<Extension> = [],
>(options?: Options<Provided, Extensions>): Runtime<Environment<Provided, Extensions>>
export function make<
const Provided extends Record<string, unknown> = {},
const Extensions extends ReadonlyArray<Extension> = [],
>(options: Options<Provided, Extensions> = {}): Runtime<Environment<Provided, Extensions>> | VmRuntime<Environment<Provided, Extensions>> {
type R = Environment<Provided, Extensions>
const prepared = ToolRuntime.prepare<R>((options.tools ?? {}) as Tools<Services<Provided>>)
const limits = resolveExecutionLimits(options.limits)
const extensions = options.extensions ?? []
// Both engines bind the same global names; test/engines.test.ts keeps them in step.
@@ -182,22 +238,89 @@ export const make = <
bound.add(name)
}
}
if (options.engine !== "vm") {
return {
get catalog() {
return prepared.catalog
},
execute: (code, bindings) =>
executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => [
...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)] as const),
...extensionGlobals(ctx, extensions),
]),
}
}
let setup: VmEngine.Setup<R> | undefined
const getSetup = (vm: typeof VmEngine) =>
(setup ??= {
prepared,
limits,
hooks: options.hooks ?? {},
globals: extensions.length === 0 ? undefined : (ctx) => vm.extensionGlobals(ctx, extensions),
lossy: extensions.length > 0,
})
const data = (vm: typeof VmEngine, bindings: Readonly<Record<string, DataValue>> | undefined) =>
bindings === undefined
? undefined
: (ctx: Parameters<typeof vm.fromJson>[0]) =>
Object.entries(bindings).map(([name, value]) => [name, vm.fromJson(ctx, value)] as const)
const program = (code: string, bindings?: Readonly<Record<string, DataValue>>) =>
vmProgram((vm) => Effect.succeed(vm.startProgram(getSetup(vm), code, data(vm, bindings))))
return {
get catalog() {
return prepared.catalog
},
execute: (code, bindings) =>
options.engine === "vm"
? Effect.flatMap(loadVm(), (vm) =>
vm.execute(code, prepared, limits, options.hooks ?? {}, extensions, bindings),
Effect.flatMap(loadVm(), (vm) => vm.finishExecution(program(code, bindings).run())),
program,
resume: (state) => vmProgram((vm) => vm.resumeProgram(getSetup(vm), state)),
} satisfies VmRuntime<R>
}
// A program's one run: `start` makes it once the VM is loaded, and a suspend waits for it.
const vmProgram = <R, E>(
start: (vm: typeof VmEngine) => Effect.Effect<VmEngine.Running<R>, E>,
): Program<R, E> => {
let claimed = false
const started = Deferred.makeUnsafe<VmEngine.Running<R>, SuspendError>()
return {
run: () =>
Effect.suspend(() => {
if (claimed) {
return Effect.die(
new Error("A CodeMode program runs once; make another with runtime.program or runtime.resume."),
)
: executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => [
...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)] as const),
...extensionGlobals(ctx, extensions),
]),
}
claimed = true
return loadVm().pipe(
Effect.flatMap(start),
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? Deferred.succeed(started, exit.value)
: Deferred.fail(started, new SuspendError({ message: "The program didn't start.", running: [] })),
),
Effect.flatMap((running) => running.run()),
)
}),
suspend: (options) => {
const maxBytes = options?.maxBytes
if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
throw new RangeError("maxBytes must be a safe integer greater than or equal to 0.")
}
return Effect.flatMap(Deferred.await(started), (running) => running.suspend(maxBytes))
},
}
}
// The VM is loaded on first use so the default engine pulls in none of its code.
let vmLoaded: typeof VmEngine | undefined
let vmEngine: Promise<typeof VmEngine> | undefined
const loadVm = () => Effect.promise(() => (vmEngine ??= import("./vm/index.js")))
const loadVm = () =>
vmLoaded !== undefined
? Effect.succeed(vmLoaded)
: Effect.promise(() =>
(vmEngine ??= import("./vm/index.js").then((mod) => {
vmLoaded = mod
return mod
})),
)
+15 -1
View File
@@ -3,5 +3,19 @@ export * as Extension from "./extension.js"
export * as Namespace from "./namespace.js"
export * as Tool from "./tool.js"
export * as OpenAPI from "./openapi/index.js"
export { searchSignature, toolExpression } from "./codemode.js"
export {
fromBytes,
searchSignature,
SnapshotError,
SuspendError,
toBytes,
toolExpression,
type Outcome,
type Program,
type Snapshot,
type SnapshotHeader,
type Suspended,
type SuspendOptions,
type VmRuntime,
} from "./codemode.js"
export { ToolError, toolError } from "./tool-error.js"
+28
View File
@@ -0,0 +1,28 @@
import { Schema } from "effect"
import type { Snapshot } from "./vm/snapshot/snapshot.js"
/**
* A suspend that failed, leaving the run running: `running` names each host call that blocked it by its path
* (`tools.x.y`, `search`, or an extension function's path such as `fetch`). Empty when the state couldn't be
* saved or was too large.
*/
export class SuspendError extends Schema.TaggedError<SuspendError>()("SuspendError", {
message: Schema.String,
running: Schema.Array(Schema.Struct({ path: Schema.String })),
}) {}
export class SnapshotError extends Error {
override readonly name = "SnapshotError"
}
/** A snapshot as bytes: UTF-8 JSON. */
export const toBytes = (snapshot: Snapshot): Uint8Array => new TextEncoder().encode(JSON.stringify(snapshot))
/** Reads bytes `toBytes` wrote; `restore` checks what they hold. */
export const fromBytes = (bytes: Uint8Array): unknown => {
try {
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
} catch (error) {
throw new SnapshotError(`Invalid snapshot: the bytes are not UTF-8 JSON (${String(error)}).`)
}
}
+4 -1
View File
@@ -1,4 +1,7 @@
export * as VmEngine from "./index.js"
export { execute } from "./runtime/execute.js"
export { fromJson } from "./data.js"
export { execute, finishExecution, resumeProgram, type Running, type Setup, startProgram } from "./runtime/execute.js"
export { extensionGlobals } from "./runtime/extensions.js"
export { globalNames } from "./runtime/globals.js"
export { fromBytes, type Snapshot, SnapshotError, type SnapshotHeader, toBytes } from "./snapshot/snapshot.js"
+48 -6
View File
@@ -1,11 +1,14 @@
import { Cause, type Context, Effect, Exit, Fiber } from "effect"
import type { HostCall } from "../scheduler.js"
import type { ToolRuntime } from "../../tool-runtime.js"
import { type ToolRuntime, toolExpression } from "../../tool-runtime.js"
import { locate } from "./errors.js"
import { PendingThrow } from "./model.js"
import type { Vm } from "../vm.js"
import { abrupt, type Completion, Interruption, normal } from "./signals.js"
/** What `Driver.run` returns once the run was suspended: its state is saved, and the VM stopped. */
export const SUSPENDED: unique symbol = Symbol("codemode.suspended")
/**
* Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run`
* until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host
@@ -19,6 +22,7 @@ export class Driver<R> {
private readonly fibers = new Map<number, Fiber.Fiber<unknown, unknown>>()
private wake: (() => void) | undefined
private stopping = false
private suspending = false
// Blocking host work interrupted on its own, which interrupts the execution.
private interrupted: Cause.Cause<unknown> | undefined
/** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
@@ -32,15 +36,16 @@ export class Driver<R> {
) {}
/**
* Runs the VM until the program's body completes, then returns how it ended. Host work it started may still be
* running; `interrupt` stops it. Host work interrupted on its own that reaches the program's body, or blocking host
* work that is interrupted, interrupts the execution.
* Runs the VM until the program's body completes, then returns how it ended, or `SUSPENDED` once the run was
* suspended (see `detach`). Host work it started may still be running; `interrupt` stops it. Host work interrupted
* on its own that reaches the program's body, or blocking host work that is interrupted, interrupts the execution.
*/
run(): Effect.Effect<Completion, unknown, R> {
run(): Effect.Effect<Completion | typeof SUSPENDED, unknown, R> {
const self = this
return Effect.gen(function* () {
while (true) {
if (self.interrupted !== undefined) return yield* Effect.failCause(self.interrupted)
if (self.suspending) return SUSPENDED
const stop = self.vm.run()
if (stop.kind === "slice") {
if (self.checkpoint !== undefined) yield* self.checkpoint
@@ -53,6 +58,8 @@ export class Driver<R> {
continue
}
if (self.checkpoint !== undefined) yield* self.checkpoint
// Suspended now: the calls stay queued, and start on resume.
if (self.suspending) continue
for (const handed of stop.calls) self.launch(self.vm.call(handed.id) ?? handed)
continue
}
@@ -72,11 +79,32 @@ export class Driver<R> {
})
}
/**
* The host calls that block a suspend now: every call in progress, and a queued or synchronous extension call the
* program is in the middle of, which holds live host values. A tool call queued but not started starts on resume.
*/
blocking(): Array<{ readonly path: string }> {
const vm = this.vm
const calls = vm.calls().filter((call) => call.status !== "queued" || call.request.kind === "extension")
const running = calls.map((call) => ({ path: callPath(call) }))
const active = vm.activeExtension
if (active !== undefined && !calls.some((call) => call.blocking && call.request.kind === "extension")) {
running.push(active)
}
return running
}
/** Whether the run holds live host values: an extension call in progress. */
get holdsHostValues(): boolean {
return this.vm.calls().some((call) => call.request.kind === "extension") || this.vm.activeExtension !== undefined
}
/** Stops the run to suspend it, once its state is saved: `run` returns `SUSPENDED` at its next step. */
detach(): void {
this.suspending = true
this.wake?.()
}
/** Stops host work still running, waiting for its cleanup. */
interrupt(): Effect.Effect<void> {
const self = this
@@ -86,6 +114,13 @@ export class Driver<R> {
})
}
/** Starts any tool calls that were queued when the VM was saved. */
resume(): void {
for (const call of this.vm.calls()) {
if (call.status === "queued") this.launch(call)
}
}
// Starts host work now; its outcome goes back to the VM: a blocking call's continues the job that made it, a
// concurrent call's waits in the inbox and settles its promise in a later job, in completion order.
private launch(call: HostCall): void {
@@ -133,7 +168,7 @@ export class Driver<R> {
private get settled(): Effect.Effect<void> {
return Effect.callback<void>((resume) => {
if (this.vm.ready || this.interrupted !== undefined) return resume(Effect.void)
if (this.vm.ready || this.suspending || this.interrupted !== undefined) return resume(Effect.void)
this.wake = () => {
this.wake = undefined
resume(Effect.void)
@@ -144,3 +179,10 @@ export class Driver<R> {
})
}
}
/** A host call as the program wrote it: `tools.x.y`, `search`, or an extension function's path. */
export const callPath = (call: HostCall): string => {
const request = call.request
if (request.kind === "tool") return toolExpression(request.path.flatMap((segment) => segment.split(".")).join("."))
return request.kind === "search" ? "search" : request.call.label
}
+184 -35
View File
@@ -1,34 +1,46 @@
import { parse, type Program } from "acorn"
import { Cause, Effect, Option, Schema } from "effect"
import type { DataValue, Diagnostic, ResolvedExecutionLimits, Result } from "../../codemode.js"
import { Cause, Deferred, Effect, Option, Schema } from "effect"
import type { DataValue, Diagnostic, Outcome, ResolvedExecutionLimits, Result, Suspended } from "../../codemode.js"
import type { Extension } from "../../extension.js"
import { fromJson } from "../data.js"
import { fromBytes, SnapshotError, toBytes } from "../snapshot/snapshot.js"
import { fromBytes, header, type Snapshot, SnapshotError, toBytes } from "../snapshot/snapshot.js"
import { ToolRuntime } from "../../tool-runtime.js"
import { SuspendError } from "../../suspend-error.js"
import { normalizeError } from "./errors.js"
import { extensionGlobals } from "./extensions.js"
import { createBuiltins } from "./intrinsics.js"
import { Interpreter } from "./interpreter.js"
import type { Value } from "./objects.js"
import { formatLocation, sourceLocation } from "./model.js"
import { Driver } from "./driver.js"
import { Driver, SUSPENDED } from "./driver.js"
import { Interruption } from "./signals.js"
import { Source } from "./source.js"
import type { Vm } from "../vm.js"
type Globals<R> = (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>
/** How a runtime runs programs: its tools, limits, hooks, and host globals. */
type Setup<R> = {
/** How a runtime runs programs: its tools, limits, hooks, and host globals, shared by every run it starts. */
export type Setup<R> = {
readonly prepared: ToolRuntime.Prepared<R>
readonly limits: ResolvedExecutionLimits
readonly hooks: ToolRuntime.Hooks<R>
/** The host's globals, made again for a restored run; see `Interpreter`. */
readonly globals: Globals<R> | undefined
readonly globals?: Globals<R> | undefined
/** Whether the host globals can hand the program values with no data form (extensions can). */
readonly lossy: boolean
readonly lossy?: boolean
}
/** Turns a suspended outcome into a failure, for callers that only run programs to their end. */
export const finishExecution = <E, R>(outcome: Effect.Effect<Outcome, E, R>): Effect.Effect<Result, E, R> =>
Effect.map(outcome, (outcome): Result => {
if (outcome.ok !== "suspended") return outcome
return {
ok: false,
error: { kind: "ExecutionFailure", message: "The program suspended, which isn't supported here." },
toolCalls: outcome.state.header.toolCalls,
}
})
/** Runs a program on the VM with `CodeMode.make`'s extensions and JSON bindings. */
export const execute = <R>(
code: string,
@@ -59,26 +71,53 @@ export const executeProgram = <R>(
bindings?: Globals<R>,
lossy = false,
): Effect.Effect<Result, never, R> =>
Effect.suspend(() => {
finishExecution(startProgram({ prepared, limits, hooks, globals, lossy }, code, bindings).run())
/** A program ready to run on the VM: nothing runs until `run`. */
export const startProgram = <R>(setup: Setup<R>, code: string, bindings?: Globals<R>): Running<R> =>
new Running(setup, 0, () => {
if (code.trim().length === 0) {
return Effect.succeed<Result>({
ok: false,
error: { kind: "ParseError", message: "Code cannot be empty." },
toolCalls: [],
})
return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." }, toolCalls: [] }
}
const parsed = parseProgram(code)
if (!parsed.ok) return Effect.succeed<Result>({ ok: false, error: parsed.error, toolCalls: [] })
const setup: Setup<R> = { prepared, limits, hooks, globals, lossy }
const ctx = instantiate(setup, bindings)
ctx.vm.start(parsed.source)
return new Running(setup, ctx).run()
if (!parsed.ok) return { ok: false, error: parsed.error, toolCalls: [] }
const runtime = instantiate(setup, bindings)
runtime.vm.start(parsed.source)
return runtime
})
/**
* Restores a saved run into this runtime, under the limits it was saved with, ready to run as `startProgram`'s.
* Fails with a `SnapshotError` when the state can't be read or belongs to another build, other host globals, or other
* sources.
*/
export const resumeProgram = <R>(
setup: Setup<R>,
saved: Snapshot | Uint8Array | unknown,
): Effect.Effect<Running<R>, SnapshotError> =>
Effect.try({
try: () => {
const state = saved instanceof Uint8Array ? fromBytes(saved) : saved
const limits = header(state).limits
const resumed: Setup<R> = {
...setup,
limits: {
timeoutMs: limits.timeoutMs ?? undefined,
maxToolCalls: limits.maxToolCalls ?? undefined,
maxOutputBytes: limits.maxOutputBytes ?? undefined,
},
}
const fresh = instantiate(resumed)
const snapshot = restoreInto(state, fresh.vm)
return new Running(resumed, snapshot.header.budget.activeMs, () => fresh, true)
},
catch: (error) => (error instanceof SnapshotError ? error : new SnapshotError(String(error))),
})
// Sources restored recently, by text: the AST is never changed, so runs restored from the same program share it.
const restoredSources = new Map<string, Source>()
const restoreInto = (saved: unknown, vm: Vm): void => {
const restoreInto = (saved: unknown, vm: Vm): Snapshot =>
vm.restore(saved, {
parse: (code) => {
const known = restoredSources.get(code)
@@ -91,7 +130,6 @@ const restoreInto = (saved: unknown, vm: Vm): void => {
},
interruption: () => new Interruption(Cause.interrupt()),
})
}
// A new runtime: intrinsics, the host globals, the program's bindings, a fresh tool bridge, and its VM.
const instantiate = <R>(setup: Setup<R>, bindings?: Globals<R>): Interpreter<R> => {
@@ -118,27 +156,69 @@ export const setRoundTrip = (enabled: boolean) => {
const ROUND_TRIP_TICKS = 2
const ROUND_TRIP_MAX = 200
/** One run: the runtime it is in now (a round trip swaps it). */
class Running<R> {
/** One run's state: the runtime it is in now (restoring swaps it), its driver, and how much active time it used. */
export class Running<R> {
private ctx!: Interpreter<R>
private driver!: Driver<R>
private startedAt = 0
// Set once the program's body ends, and once a suspend saved the run: either way, `done` gets the outcome next.
private finished = false
private suspended: Suspended | undefined
private trips = 0
// Checkpoints to let pass before the next round trip, so a large state is not saved at every one.
private skip = 0
private readonly started = Deferred.makeUnsafe<void>()
private readonly done = Deferred.makeUnsafe<Outcome>()
constructor(
private readonly setup: Setup<R>,
private ctx: Interpreter<R>,
/** Active milliseconds used before this run, by earlier ones of the same execution. */
private readonly activeBefore: number,
private readonly prepare: () => Interpreter<R> | Result,
private readonly resuming = false,
) {}
run(): Effect.Effect<Result, never, R> {
/** Makes the run's runtime and driver, then runs the program in the current fiber until it ends or is suspended. */
run(): Effect.Effect<Outcome, never, R> {
const self = this
return Effect.gen(function* () {
const driver = new Driver(self.ctx.vm, self.ctx.tools, yield* Effect.context<R>())
if (roundTrip) driver.checkpoint = Effect.sync(() => self.trip(driver))
return yield* self.execute(driver)
})
const prepared = self.prepare()
if (!(prepared instanceof Interpreter)) {
self.finished = true
return prepared
}
self.ctx = prepared
self.driver = new Driver(prepared.vm, prepared.tools, yield* Effect.context<R>())
if (roundTrip) self.driver.checkpoint = Effect.sync(() => self.trip())
self.startedAt = Date.now()
yield* Deferred.succeed(self.started, undefined)
return yield* self.execute()
}).pipe(
Effect.onExit((exit) =>
Effect.andThen(Deferred.succeed(self.started, undefined), Deferred.done(self.done, exit)),
),
)
}
private execute(driver: Driver<R>): Effect.Effect<Result, never, R> {
/**
* Saves the run's state and stops it, at once: `run` then returns the same `Suspended`. It fails with a
* `SuspendError`, leaving the run running, while a host call is in progress. A run that already ended gives its result.
* Before the run has started, it waits for it.
*/
suspend(maxBytes: number | undefined): Effect.Effect<Outcome, SuspendError> {
return Effect.andThen(
Deferred.await(this.started),
Effect.suspend(() => {
if (this.finished) return Deferred.await(this.done)
const saved = this.save(maxBytes)
if (saved instanceof SuspendError) return Effect.fail(saved)
this.stop(saved)
return Deferred.await(this.done)
}),
)
}
private execute(): Effect.Effect<Outcome, never, R> {
const self = this
const limits = this.setup.limits
const logged = () => {
@@ -151,7 +231,11 @@ class Running<R> {
let returned: { value: DataValue; warnings: () => Array<Diagnostic> } | undefined
const base = Effect.gen(function* () {
const driver = self.driver
if (self.resuming) driver.resume()
const outcome = yield* driver.run()
if (outcome === SUSPENDED) return self.suspended!
self.finished = true
if (!outcome.ok) return failed(normalizeError(outcome.error))
const result = (outcome.value as DataValue | undefined) ?? null
const vm = self.ctx.vm
@@ -166,16 +250,18 @@ class Running<R> {
...logged(),
toolCalls: toolCalls(),
} satisfies Result
}).pipe(Effect.ensuring(Effect.suspend(() => driver.interrupt())))
}).pipe(Effect.ensuring(Effect.suspend(() => self.driver.interrupt())))
const timeoutMs = limits.timeoutMs
const operation =
timeoutMs === undefined
? base
: base.pipe(
Effect.timeoutOrElse({
duration: timeoutMs,
duration: Math.max(0, timeoutMs - this.activeBefore),
orElse: () =>
Effect.sync((): Result => {
Effect.sync((): Outcome => {
self.finished = true
if (self.suspended !== undefined) return self.suspended
if (returned === undefined) {
return failed({ kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` })
}
@@ -202,15 +288,70 @@ class Running<R> {
Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.succeed(failed(normalizeError(Cause.squash(cause)))),
),
Effect.map((result) =>
limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes),
result.ok === "suspended" || limits.maxOutputBytes === undefined
? result
: boundOutput(result, limits.maxOutputBytes),
),
)
}
// Suspends the run once its state is saved: the driver stops.
private stop(saved: Suspended): void {
this.finished = true
this.suspended = saved
this.driver.detach()
}
/**
* Saves the run's state, with no effect on the run: the calls that block a suspend, or the state as it is now. The
* program shares this thread with the caller, so it is at a step boundary.
*/
private save(maxBytes: number | undefined): Suspended | SuspendError {
const vm = this.ctx.vm
const running = this.driver.blocking()
if (running.length > 0) {
return new SuspendError({
message: `The run can't be suspended while ${running.map((call) => call.path).join(", ")} ${running.length === 1 ? "is" : "are"} running.`,
running,
})
}
const limits = this.setup.limits
const saved = attempt(() =>
vm.capture({
limits: {
timeoutMs: limits.timeoutMs ?? null,
maxToolCalls: limits.maxToolCalls ?? null,
maxOutputBytes: limits.maxOutputBytes ?? null,
},
activeMs: this.activeBefore + Date.now() - this.startedAt,
strict: false,
}),
)
if (!saved.ok) {
const error = saved.error
return new SuspendError({
message: `The run's state couldn't be saved: ${error instanceof Error ? error.message : String(error)}`,
running: [],
})
}
const snapshot = saved.value.snapshot
if (maxBytes !== undefined) {
const size = toBytes(snapshot).byteLength
if (size > maxBytes) {
return new SuspendError({
message: `The run's state takes ${size} bytes, more than the ${maxBytes}-byte limit, so it couldn't be suspended.`,
running: [],
})
}
}
return { ok: "suspended", state: snapshot }
}
// The round-trip test mode's checkpoint: saves the state to bytes and continues in a brand-new runtime. States that
// hold live host values (an extension call in flight, a function an extension returned) can't round-trip, so they
// are skipped; a lost value anywhere else is a codec gap and fails the run.
private trip(driver: Driver<R>): void {
private trip(): void {
const driver = this.driver
if (this.trips >= ROUND_TRIP_MAX) {
this.ctx.vm.tripEvery = 0
return
@@ -233,6 +374,14 @@ class Running<R> {
}
}
const attempt = <A>(run: () => A): { ok: true; value: A } | { ok: false; error: unknown } => {
try {
return { ok: true, value: run() }
} catch (error) {
return { ok: false, error }
}
}
export const parseProgram = (
code: string,
): { ok: true; program: Program; source: Source } | { ok: false; error: Diagnostic } => {
+6 -1
View File
@@ -4,7 +4,7 @@ import { staticNames, unchanged } from "./runtime/intrinsic-names.js"
import { Fn, Obj } from "./runtime/objects.js"
import { nodeId, type Source } from "./runtime/source.js"
import { type ClassSpec, codecShape, decode, encode, type Json, SnapshotError } from "./snapshot/codec.js"
import { FORMAT, hash, hostsId, type Snapshot, validate } from "./snapshot/snapshot.js"
import { FORMAT, type Header, hash, hostsId, type Snapshot, validate } from "./snapshot/snapshot.js"
import { AsyncFromSyncCloseTarget, FinallyTarget, VmScheduler } from "./async.js"
import { Code, hashOf } from "./code.js"
import { COMPILER_VERSION, compileSource } from "./compiler/compile.js"
@@ -25,6 +25,9 @@ import { CustomIter, Frame, Mode, Vm, VmInternalFn } from "./vm.js"
// - New VM state must be listed in the `Vm` spec: an unknown own field is a codec gap, so nothing is silently dropped.
export type CaptureOptions = {
readonly limits?: Header["limits"]
/** Active milliseconds used so far, across every resume. */
readonly activeMs?: number
/** Throw on the first value with no data form, instead of reporting it in `lost`. */
readonly strict: boolean
}
@@ -163,6 +166,8 @@ export const captureVm = (
hash: hash(source.code),
bytecode: vm.sourceCodes.get(source.id)![0]!.source.hash,
})),
limits: options.limits ?? { timeoutMs: null, maxToolCalls: null, maxOutputBytes: null },
budget: { activeMs: options.activeMs ?? 0, toolCalls: ctx.tools.calls.length },
toolCalls: ctx.tools.calls.map((call) => ({ name: call.name })),
},
roots: encoded.roots,
+3 -3
View File
@@ -66,9 +66,9 @@ export type Encoded = string | number | boolean | null | ReadonlyArray<Json>
export type Record = { readonly t: string; readonly [field: string]: Json }
/** A saved state can't be read, or doesn't fit this runtime. */
export class SnapshotError extends Error {
override readonly name = "SnapshotError"
}
import { SnapshotError } from "../../suspend-error.js"
export { SnapshotError }
/** What the encoder asks of the runtime whose state it saves. */
export type EncodeEnv = {
+29 -15
View File
@@ -1,15 +1,16 @@
import type { Interpreter } from "../runtime/interpreter.js"
import type { ToolCall } from "../../tool-runtime.js"
import { fromBytes, SnapshotError, toBytes } from "../../suspend-error.js"
import type { Encoded, Record } from "./codec.js"
import { SnapshotError } from "./codec.js"
export { SnapshotError }
export { fromBytes, SnapshotError, toBytes }
/** The snapshot format this build writes and reads: the bytecode VM's (see `src/vm/snapshot.ts`). */
export const FORMAT = 2
/**
* A run's whole state as JSON: a header that says which build and sources it belongs to, and the graph of records (see codec.ts) rooted at the VM, the interpreter, and the global scope, then
* A suspended run's whole state as JSON: a header that says which build and sources it belongs to and what budget it
* has used, and the graph of records (see codec.ts) rooted at the VM, the interpreter, and the global scope, then
* every built-in or host global the run changed.
*/
export type Snapshot = {
@@ -31,24 +32,21 @@ export type Header = {
readonly hash: string
readonly bytecode: string
}>
readonly limits: {
readonly timeoutMs: number | null
readonly maxToolCalls: number | null
readonly maxOutputBytes: number | null
}
/** What the run has used so far, across every resume: active milliseconds, and tool calls admitted. */
readonly budget: { readonly activeMs: number; readonly toolCalls: number }
/** The tool calls admitted so far. */
readonly toolCalls: ReadonlyArray<ToolCall>
}
export type SnapshotHeader = Header
export const hostsId = (ctx: Interpreter<unknown>): string => hash(ctx.intrinsics.hosts().join("\n"))
/** A snapshot as bytes: UTF-8 JSON. */
export const toBytes = (snapshot: Snapshot): Uint8Array => new TextEncoder().encode(JSON.stringify(snapshot))
/** Reads bytes `toBytes` wrote; `restore` checks what they hold. */
export const fromBytes = (bytes: Uint8Array): unknown => {
try {
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
} catch (error) {
throw new SnapshotError(`Invalid snapshot: the bytes are not UTF-8 JSON (${String(error)}).`)
}
}
// --- Validation ---
const fail = (message: string): never => {
@@ -66,11 +64,21 @@ const array = (value: unknown, what: string): ReadonlyArray<unknown> =>
const string = (value: unknown, what: string): string =>
typeof value === "string" ? value : fail(`${what} is not text.`)
const number = (value: unknown, what: string): number =>
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fail(`${what} is not a number.`)
const limit = (value: unknown, what: string): number | null => (value === null ? null : number(value, what))
/** A saved state's header, checked in full, before anything is restored. */
export const header = (saved: unknown): Header => validate(saved).header
// The header is checked in full; records are checked as they are decoded.
export const validate = (saved: unknown): Snapshot => {
const root = object(saved, "the snapshot")
if (root.format !== FORMAT) fail(`format ${String(root.format)} is not ${FORMAT}.`)
const header = object(root.header, "the header")
const limits = object(header.limits, "the limits")
const budget = object(header.budget, "the budget")
const checked: Header = {
build: string(header.build, "the build"),
hosts: string(header.hosts, "the host globals"),
@@ -83,6 +91,12 @@ export const validate = (saved: unknown): Snapshot => {
bytecode: string(source.bytecode, "a bytecode hash"),
}
}),
limits: {
timeoutMs: limit(limits.timeoutMs, "timeoutMs"),
maxToolCalls: limit(limits.maxToolCalls, "maxToolCalls"),
maxOutputBytes: limit(limits.maxOutputBytes, "maxOutputBytes"),
},
budget: { activeMs: number(budget.activeMs, "the active time"), toolCalls: number(budget.toolCalls, "tool calls") },
toolCalls: array(header.toolCalls, "the tool calls").map((item) => ({
name: string(object(item, "a tool call").name, "a tool name"),
})),
+13 -3
View File
@@ -249,7 +249,8 @@ export class Vm {
depth = 0
fuel = INITIAL_FUEL
sliceStart = 0
/** When the current slice began; -1 until the next `run` starts one. Host stops don't end a slice, only a yield does. */
sliceStart = -1
sliced = false
outcome: Completion | undefined = undefined
/** Round-trip test mode (task C): slice after this many fuel ticks, so the run is saved and restored all through. */
@@ -319,7 +320,7 @@ export class Vm {
* other; the outcome; the next job; one inbox completion; wait for running calls; stuck.
*/
run(): Stop {
this.sliceStart = performance.now()
if (this.sliceStart < 0) this.sliceStart = performance.now()
if (this.tripEvery > 0) this.fuel = this.tripEvery
const sched = this.scheduler
const hosts = this.hosts
@@ -327,6 +328,7 @@ export class Vm {
if (hosts.queued.length > 0) return { kind: "host", calls: hosts.handOver() }
if (this.sliced) {
this.sliced = false
this.sliceStart = -1
return { kind: "slice" }
}
const input = hosts.input
@@ -337,7 +339,15 @@ export class Vm {
}
if (this.frames.length > 0) {
if (hosts.blocked !== undefined) return { kind: "host", calls: [] }
if (this.fuel <= 0) this.fuel = this.tripEvery || INITIAL_FUEL
// Fuel can run out on a call that then stopped for the host (a built-in or sync extension call costs fuel too):
// that's a slice point as well, or a loop of such calls would refill forever without yielding.
if (this.fuel <= 0) {
this.fuel = this.tripEvery || INITIAL_FUEL
if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) {
this.sliced = true
continue
}
}
let signal = EXEC_DONE
try {
signal = this.exec()
+16
View File
@@ -0,0 +1,16 @@
// Resumes a saved run in its own process: `bun resume-process.ts <state file>`. The `slow` tool answers
// `{ value: input.value * 2 }`.
import { Effect, Schema } from "effect"
import { CodeMode, Tool } from "../../src/index.js"
const Value = Schema.Struct({ value: Schema.Number })
const slow = Tool.make({
description: "Doubles",
input: Value,
output: Value,
execute: (input) => Effect.succeed({ value: input.value * 2 }),
})
const [file] = process.argv.slice(2)
const bytes = new Uint8Array(await Bun.file(file!).arrayBuffer())
const resumed = CodeMode.make({ tools: { slow }, engine: "vm" }).resume(bytes)
console.log(JSON.stringify(await Effect.runPromise(resumed.run())))
+7 -2
View File
@@ -1,4 +1,4 @@
import { CodeMode } from "../../src/index.js"
import { CodeMode, type Extension } from "../../src/index.js"
export * from "../../src/codemode.js"
@@ -11,6 +11,11 @@ if (process.env.CODEMODE_ROUNDTRIP === "1") {
setRoundTrip(true)
}
export const make: typeof CodeMode.make = (options = {}) => CodeMode.make({ engine, ...options })
export const make = <
const Provided extends Record<string, unknown> = {},
const Extensions extends ReadonlyArray<Extension.Extension> = [],
>(
options: CodeMode.Options<Provided, Extensions> = {},
) => CodeMode.make<Provided, Extensions>({ engine, ...options })
export const execute: typeof CodeMode.execute = (options) => CodeMode.execute({ engine, ...options })
@@ -25,4 +25,9 @@ describe("build id", () => {
expect(ids[1]).toBe(ids[0]!)
expect(ids[2]).toBe(ids[0]!)
})
// A process with the test262 harness loaded saves the run; the child that resumes it has not loaded it.
test("a run saved with the test262 harness loaded resumes in another process", async () => {
await output(["bun", "test", "--preload", "./test/test262/run.ts", "test/vm/suspend.test.ts", "-t", "another process"])
}, 15_000)
})
@@ -1,4 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../../src/index.js"
import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
import { Interpreter } from "../../src/vm/runtime/interpreter.js"
import { type Snapshot, SnapshotError } from "../../src/vm/snapshot/snapshot.js"
@@ -242,6 +244,25 @@ describe("snapshots", () => {
})
})
describe("suspend", () => {
test("a sync program suspended mid-loop resumes where it stopped, in a new runtime", async () => {
const runtime = CodeMode.make({ tools: {}, engine: "vm" })
const code = `
const seen = []
let n = 0
for (let i = 0; i < 400_000; i++) { n = (n + i) % 1_000_003; if (i % 100_000 === 0) seen.push(i) }
return [n, seen]`
const expected = await Effect.runPromise(runtime.execute(code))
const program = runtime.program(code)
const run = Effect.runPromise(program.run())
await new Promise((done) => setTimeout(done, 5))
const suspended = await Effect.runPromise(program.suspend())
if (suspended.ok !== "suspended") throw new Error("the run ended before it could be suspended")
expect(await run).toBe(suspended)
expect(await Effect.runPromise(runtime.resume(suspended.state).run())).toEqual(expected)
})
})
describe("determinism", () => {
test("another process compiles the same bytecode and has the same build id", async () => {
const codes = Object.values(programs)
+635
View File
@@ -0,0 +1,635 @@
import { describe, expect, test } from "bun:test"
import { tmpdir } from "node:os"
import path from "node:path"
import { Effect, Fiber, Schema } from "effect"
import { CodeMode, Extension, Tool } from "../../src/index.js"
// Suspending a run, saving its state, and resuming it in a brand-new runtime.
const Value = Schema.Struct({ value: Schema.Number })
/** Runs a program in a fiber of its own: its outcome, and a way to suspend it. */
const background = <E>(program: CodeMode.Program<never, E>) => {
const fiber = Effect.runFork(program.run())
return { program, result: Fiber.join(fiber), suspend: program.suspend() }
}
/** Why resuming a state fails. */
const refusal = (resumed: CodeMode.Program<never, CodeMode.SnapshotError>) =>
Effect.runPromise(Effect.flip(resumed.run()))
/** Why a suspend fails. */
const blocked = (execution: { readonly suspend: Effect.Effect<unknown, CodeMode.SuspendError> }) =>
Effect.runPromise(Effect.flip(execution.suspend))
/** A promise and its resolver, for host work a test finishes by hand. */
const latch = <A = void>() => {
let resolve!: (value: A) => void
const promise = new Promise<A>((done) => (resolve = done))
return { promise, resolve }
}
/** A tool that announces each call and waits for the test to answer it. */
const manual = () => {
const calls: Array<{ input: number; answer: (value: number) => void }> = []
let called = latch()
const tool = Tool.make({
description: "Waits for the test",
input: Value,
output: Value,
execute: (input) =>
Effect.promise(() => {
const answer = latch<number>()
calls.push({ input: input.value, answer: answer.resolve })
called.resolve()
return answer.promise.then((value) => ({ value }))
}),
})
return {
tool,
calls,
called: () => called.promise,
reset: () => {
called = latch()
},
}
}
/** A tool that doubles its input immediately and signals when called. */
const stepTool = () => {
let called = latch()
const tool = Tool.make({
description: "Doubles",
input: Value,
output: Value,
execute: (input) =>
Effect.sync(() => {
called.resolve()
return { value: input.value * 2 }
}),
})
return {
tool,
called: () => called.promise,
reset: () => {
called = latch()
},
}
}
const suspendedOf = (outcome: CodeMode.Result | CodeMode.Suspended): CodeMode.Suspended => {
if (outcome.ok !== "suspended") throw new Error(`expected a suspended run, got ${JSON.stringify(outcome)}`)
return outcome
}
/** Runs `code` until `step` has completed and the VM is yielding at a slice boundary with no host call running. */
const suspendBetweenCalls = async (
code: string,
options: {
readonly extensions?: ReadonlyArray<Extension.Extension>
readonly limits?: CodeMode.ExecutionLimits
} = {},
) => {
const step = stepTool()
const runtime = CodeMode.make({
engine: "vm",
tools: { step: step.tool },
...(options.extensions ? { extensions: options.extensions } : {}),
...(options.limits ? { limits: options.limits } : {}),
})
const run = background(runtime.program(code))
await step.called()
await Bun.sleep(10)
return { step, runtime, run }
}
describe("synchronous host calls", () => {
// Each sync extension call stops the VM; the slice clock must keep running across those stops, or a loop of them
// never yields: suspend can't land and timeouts can't interrupt it.
const counter = () => {
let calls = 0
let reached = latch()
const extension = Extension.make({
name: "draw",
globals: {
draw: (n: number) => {
calls += 1
if (calls === 500) reached.resolve()
return n
},
},
})
return { extension, reached: () => reached.promise, calls: () => calls }
}
// Round-trip mode also yields at every host stop, where a suspend lands mid-call and is rightly refused.
test.skipIf(process.env.CODEMODE_ROUNDTRIP === "1")(
"a loop of sync extension calls can be suspended and resumed",
async () => {
const draw = counter()
const runtime = CodeMode.make({ engine: "vm", extensions: [draw.extension] })
const run = background(runtime.program("let n = 0\nwhile (n < 200000) draw(n++)\nreturn n"))
await draw.reached()
const suspended = suspendedOf(await Effect.runPromise(run.suspend))
expect(draw.calls()).toBeLessThan(200000)
const resumed = await Effect.runPromise(background(runtime.resume(CodeMode.toBytes(suspended.state))).result)
expect(resumed).toMatchObject({ ok: true, value: 200000 })
},
)
test("a loop of sync extension calls is interrupted by the timeout", async () => {
const draw = counter()
const outcome = await Effect.runPromise(
CodeMode.make({ engine: "vm", extensions: [draw.extension], limits: { timeoutMs: 100 } }).execute(
"let n = 0\nwhile (true) draw(n++)",
),
)
expect(outcome).toMatchObject({ ok: false, error: { kind: "TimeoutExceeded" } })
})
})
describe("suspend", () => {
test("a run suspended while idle-awaiting between calls resumes from state and from bytes", async () => {
const code = `
const log = ["before"]
const a = await tools.step({ value: 20 })
const started = Date.now()
while (Date.now() - started < 300) await Promise.resolve()
const b = await tools.step({ value: 1 })
log.push("after " + (a.value + b.value))
console.log("resumed")
return { log, total: a.value + b.value }`
const { step, run } = await suspendBetweenCalls(code)
const suspended = suspendedOf(await Effect.runPromise(run.suspend))
// The run's own result is the same saved state.
expect(suspendedOf(await Effect.runPromise(run.result))).toBe(suspended)
for (const state of [suspended.state, CodeMode.toBytes(suspended.state)] as const) {
const outcome = await Effect.runPromise(
background(CodeMode.make({ engine: "vm", tools: { step: step.tool } }).resume(state)).result,
)
expect(outcome).toEqual({
ok: true,
value: { log: ["before", "after 42"], total: 42 },
logs: ["resumed"],
toolCalls: [{ name: "step" }, { name: "step" }],
})
}
})
test("a suspend fails while a tool, search, or an extension call is running, and the run goes on", async () => {
const slow = manual()
const searching = latch()
const searched = latch()
const fetched = latch<string>()
const fetching = latch()
const hookGate = latch()
const hooked = latch()
const extension = Extension.make({
name: "web",
globals: {
fetch: async (url: string) => {
fetching.resolve()
return `${url} ${await fetched.promise}`
},
now: () => 7,
},
})
const runtime = CodeMode.make({
engine: "vm",
tools: { slow: slow.tool },
extensions: [extension],
hooks: {
"tool.before": (call) =>
call.name === "search"
? Effect.promise(() => {
searching.resolve()
return searched.promise
})
: Effect.void,
"extension.before": (call) =>
call.name === "now"
? Effect.promise(() => {
hooked.resolve()
return hookGate.promise
})
: Effect.void,
},
})
const cases: ReadonlyArray<
readonly [
name: string,
code: string,
running: () => Promise<void>,
release: () => void,
path: string,
value: unknown,
]
> = [
[
"a tool",
`return (await tools.slow({ value: 1 })).value`,
slow.called,
() => slow.calls[0]!.answer(5),
"tools.slow",
5,
],
[
"search",
`return (await search({ query: "slow" })).items.length`,
() => searching.promise,
() => searched.resolve(),
"search",
1,
],
[
"an async extension function",
`return await fetch("https://a.test/")`,
() => fetching.promise,
() => fetched.resolve("ok"),
"fetch",
"https://a.test/ ok",
],
[
"a synchronous extension function",
`return now() + 1`,
() => hooked.promise,
() => hookGate.resolve(),
"now",
8,
],
]
for (const [name, code, running, release, path, value] of cases) {
const run = background(runtime.program(code))
await running()
const error = await blocked(run)
expect(error, name).toBeInstanceOf(CodeMode.SuspendError)
expect(error.running, name).toEqual([{ path }])
expect(error.message, name).toBe(`The run can't be suspended while ${path} is running.`)
release()
expect(await Effect.runPromise(run.result), name).toMatchObject({ ok: true, value })
}
})
test("every running call that blocks a suspend is named", async () => {
const slow = manual()
const run = background(
CodeMode.make({ engine: "vm", tools: { slow: slow.tool, "a-b": { work: slow.tool } } }).program(
`return await Promise.all([tools["a-b"].work({ value: 1 }), tools.slow({ value: 2 })])`,
),
)
while (slow.calls.length < 2) await Bun.sleep(1)
expect((await blocked(run)).running).toEqual([{ path: 'tools["a-b"].work' }, { path: "tools.slow" }])
})
test("a suspend after the run ended gives its result", async () => {
const program = CodeMode.make({ engine: "vm" }).program(`return 1 + 1`)
expect(await Effect.runPromise(program.run())).toEqual({ ok: true, value: 2, toolCalls: [] })
expect(await Effect.runPromise(program.suspend())).toEqual({ ok: true, value: 2, toolCalls: [] })
})
test("a program runs inline in the current fiber", async () => {
const runtime = CodeMode.make({ engine: "vm", tools: { step: stepTool().tool } })
expect(
await Effect.runPromise(runtime.program(`return (await tools.step({ value: x })).value`, { x: 21 }).run()),
).toEqual({ ok: true, value: 42, toolCalls: [{ name: "step" }] })
})
test("a suspend from another fiber stops a background run, which returns the same state", async () => {
const runtime = CodeMode.make({ engine: "vm", tools: {} })
const code = `let n = 0; for (let i = 0; i < 2_000_000; i++) n = (n + i) % 1_000_003; return n`
const expected = await Effect.runPromise(runtime.execute(code))
const [suspended, outcome] = await Effect.runPromise(
Effect.gen(function* () {
const program = runtime.program(code)
const fiber = yield* Effect.forkChild(program.run())
// Issued before the run starts: it waits for it.
const suspended = yield* program.suspend()
return [suspended, yield* Fiber.join(fiber)] as const
}),
)
expect(outcome).toBe(suspended)
const fresh = CodeMode.make({ engine: "vm", tools: {} })
expect(await Effect.runPromise(fresh.resume(CodeMode.toBytes(suspendedOf(suspended).state)).run())).toEqual(
expected,
)
})
test("a program runs once", async () => {
const program = CodeMode.make({ engine: "vm" }).program(`return 1`)
expect(await Effect.runPromise(program.run())).toMatchObject({ ok: true, value: 1 })
const exit = await Effect.runPromise(Effect.exit(program.run()))
expect(String(exit)).toContain("A CodeMode program runs once")
})
test("interrupting run interrupts the program and its running calls", async () => {
const called = latch()
const interrupted = latch()
const hang = Tool.make({
description: "Never answers",
input: Value,
output: Value,
execute: () =>
Effect.sync(() => called.resolve()).pipe(
Effect.andThen(Effect.never),
Effect.onInterrupt(() => Effect.sync(() => interrupted.resolve())),
),
})
const program = CodeMode.make({ engine: "vm", tools: { hang } }).program(`return await tools.hang({ value: 1 })`)
const fiber = Effect.runFork(program.run())
await called.promise
await Effect.runPromise(Fiber.interrupt(fiber))
await interrupted.promise
})
test("a state over the byte budget fails the suspend, and the run goes on", async () => {
const { run } = await suspendBetweenCalls(
`const big = "x".repeat(1000); await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} return big.length`,
)
const error = await blocked({ suspend: run.program.suspend({ maxBytes: 100 }) })
expect(error.running).toEqual([])
expect(error.message).toMatch(/^The run's state takes \d+ bytes, more than the 100-byte limit/)
expect(await Effect.runPromise(run.result)).toMatchObject({ ok: true, value: 1000 })
})
test("a maxBytes that isn't a non-negative integer is rejected", () => {
const program = CodeMode.make({ engine: "vm" }).program("return 1")
expect(() => program.suspend({ maxBytes: -1 })).toThrow(RangeError)
})
test("only a VM runtime has program and resume", () => {
const vm = CodeMode.make({ engine: "vm" })
expect([typeof vm.program, typeof vm.resume]).toEqual(["function", "function"])
for (const legacy of [CodeMode.make(), CodeMode.make({ engine: "legacy" })]) {
// @ts-expect-error only engine: "vm" runs programs one by one
void legacy.program
// @ts-expect-error only engine: "vm" resumes runs
void legacy.resume
expect("program" in legacy || "resume" in legacy).toBe(false)
}
})
test("the snapshot codec does not import Effect", async () => {
for (const file of ["codec.ts", "snapshot.ts"]) {
expect(await Bun.file(path.join(import.meta.dir, "../../src/vm/snapshot", file)).text()).not.toMatch(
/from "effect"/,
)
}
})
})
describe("resume", () => {
const suspendAt = async (code: string, extensions: ReadonlyArray<Extension.Extension> = []) => {
const { step, run } = await suspendBetweenCalls(code, { extensions })
return { step, suspended: suspendedOf(await Effect.runPromise(run.suspend)) }
}
test("a run saved to a file resumes in another process", async () => {
const step = stepTool()
const run = background(
CodeMode.make({ engine: "vm", tools: { slow: step.tool } }).program(`
const seen = new Map([["first", await tools.slow({ value: 10 })]])
const started = Date.now()
while (Date.now() - started < 300) {}
const second = await tools.slow({ value: 21 })
return [seen.get("first").value, second.value]`),
)
await step.called()
await Bun.sleep(10)
const suspended = suspendedOf(await Effect.runPromise(run.suspend))
const file = path.join(tmpdir(), `codemode-${crypto.randomUUID()}.state`)
await Bun.write(file, CodeMode.toBytes(suspended.state))
try {
const child = Bun.spawn(["bun", path.join(import.meta.dir, "../fixtures/resume-process.ts"), file], {
stdout: "pipe",
stderr: "inherit",
})
const output = await new Response(child.stdout).text()
expect(await child.exited).toBe(0)
expect(JSON.parse(output)).toEqual({ ok: true, value: [20, 42], toolCalls: [{ name: "slow" }, { name: "slow" }] })
} finally {
await Bun.file(file).delete()
}
})
test("a resumed run keeps the limits it was saved with", async () => {
const { step, run } = await suspendBetweenCalls(
`await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} await tools.step({ value: 2 }); await tools.step({ value: 3 }); return "done"`,
{ limits: { maxToolCalls: 2, maxOutputBytes: 10 } },
)
const suspended = suspendedOf(await Effect.runPromise(run.suspend))
expect(suspended.state.header.limits).toEqual({ timeoutMs: null, maxToolCalls: 2, maxOutputBytes: 10 })
// The resuming runtime has no limits of its own; the saved ones apply.
const result = await Effect.runPromise(
background(CodeMode.make({ engine: "vm", tools: { step: step.tool } }).resume(suspended.state)).result,
)
expect(result).toMatchObject({ ok: false, error: { kind: "ToolCallLimitExceeded" } })
const { step: step2, run: long } = await suspendBetweenCalls(
`await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} return "x".repeat(100)`,
{ limits: { maxOutputBytes: 10 } },
)
const saved = suspendedOf(await Effect.runPromise(long.suspend))
expect(
await Effect.runPromise(
background(CodeMode.make({ engine: "vm", tools: { step: step2.tool } }).resume(saved.state)).result,
),
).toMatchObject({ ok: true, truncated: true })
})
test("active time and tool calls count across resumes", async () => {
const step = stepTool()
const runtime = CodeMode.make({ engine: "vm", tools: { step: step.tool }, limits: { timeoutMs: 300 } })
const run = background(
runtime.program(`
await tools.step({ value: 1 })
const started = Date.now()
while (Date.now() - started < 220) {}
const again = Date.now()
while (Date.now() - again < 200) {}
return "done"`),
)
await step.called()
await Bun.sleep(210)
const suspended = suspendedOf(await Effect.runPromise(run.suspend))
expect(suspended.state.header.budget.activeMs).toBeGreaterThanOrEqual(200)
expect(suspended.state.header.budget.toolCalls).toBe(1)
// 200ms were used before the suspend; the next 200ms of work go past the 300ms limit.
const timedOut = await Effect.runPromise(background(runtime.resume(suspended.state)).result)
expect(timedOut).toMatchObject({ ok: false, error: { kind: "TimeoutExceeded" }, toolCalls: [{ name: "step" }] })
})
test("a state is refused by another build, other extensions, or a changed source", async () => {
const { suspended } = await suspendAt(
`await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} return 1`,
)
const state = suspended.state
const header = state.header
const runtime = CodeMode.make({ engine: "vm", tools: {} })
expect((await refusal(runtime.resume({ ...state, header: { ...header, build: "0.0.0+0" } }))).message).toMatch(
/saved by another Code Mode build \(0\.0\.0\+0\)/,
)
const other = CodeMode.make({ engine: "vm", extensions: [Extension.make({ name: "x", globals: { f: () => 1 } })] })
expect((await refusal(other.resume(state))).message).toMatch("saved by a runtime with other host globals")
const source = header.sources[0]!
expect(
(
await refusal(
runtime.resume({ ...state, header: { ...header, sources: [{ ...source, code: `${source.code} ` }] } }),
)
).message,
).toBe("Source main does not match its hash.")
expect(await refusal(runtime.resume(new TextEncoder().encode("{")))).toBeInstanceOf(CodeMode.SnapshotError)
expect((await refusal(runtime.resume({ ...state, records: [{ t: "Nope" }] }))).message).toMatch("Invalid snapshot")
})
test("a function an extension returned is lost on resume, and calling it fails clearly", async () => {
const extension = Extension.make({
name: "maker",
globals: {
make: () =>
function inc(x: number) {
return x + 1
},
},
})
const { step, suspended } = await suspendAt(
`
const inc = make()
const before = inc(1)
await tools.step({ value: 0 })
const t = Date.now()
while (Date.now() - t < 300) {}
try {
return { before, after: inc(1) }
} catch (error) {
return { before, error: String(error) }
}`,
[extension],
)
const outcome = await Effect.runPromise(
background(
CodeMode.make({ engine: "vm", tools: { step: step.tool }, extensions: [extension] }).resume(suspended.state),
).result,
)
expect(outcome).toMatchObject({
ok: true,
value: {
before: 2,
error:
"TypeError: The function inc came from the host and was lost when the run was suspended; get it again after resuming.",
},
})
})
test("program state of every kind survives a suspend", async () => {
const code = `
const shared = { n: 1 }
const map = new Map([[shared, "a"], ["k", shared]])
const set = new Set([1, shared])
const it = map.keys()
it.next()
const url = new URL("https://example.com/a?x=1")
const params = url.searchParams
const bytes = new Uint8Array([1, 2, 3, 4])
const view = bytes.subarray(1, 3)
const re = /a(b)/g
re.test("abab")
const date = new Date(0)
const weak = new WeakMap([[shared, 5]])
function* counter() { let i = 0; while (true) yield i++ }
const gen = counter()
gen.next()
const bound = ((a, b) => a + b).bind(null, 10)
const sparse = []
sparse[5000] = "far"
const pending = new Promise((resolve) => (globalResolve = resolve))
var globalResolve
Array.prototype.extra = "patched"
await tools.step({ value: 1 })
const t = Date.now()
while (Date.now() - t < 300) {}
params.append("y", "2")
view[0] = 9
globalResolve("later")
return {
same: map.get("k") === shared && set.has(shared) && weak.get(shared) === 5,
next: it.next().value,
url: url.href,
bytes: [...bytes],
lastIndex: re.lastIndex,
date: date.getTime(),
gen: [gen.next().value, gen.next().value],
bound: bound(5),
sparse: [5001, "far", false],
pending: await pending,
extra: [].extra,
negative: Object.is(-0, -0 * 1),
}`
const { step, suspended } = await suspendAt(code)
const outcome = await Effect.runPromise(
background(CodeMode.make({ engine: "vm", tools: { step: step.tool } }).resume(CodeMode.toBytes(suspended.state)))
.result,
)
expect(outcome).toMatchObject({
ok: true,
value: {
same: true,
next: "k",
url: "https://example.com/a?x=1&y=2",
bytes: [1, 9, 3, 4],
lastIndex: 2,
date: 0,
gen: [1, 2],
bound: 15,
sparse: [5001, "far", false],
pending: "later",
extra: "patched",
negative: true,
},
})
})
test("changes to built-ins survive a second suspend, including freeze, seal, and deletes", async () => {
const code = `
Array.prototype.extra = "patched"
delete Math.max
Object.freeze(JSON)
Object.seal(Number.prototype)
Object.preventExtensions(Date.prototype)
await tools.step({ value: 1 })
const t1 = Date.now()
while (Date.now() - t1 < 300) {}
await tools.step({ value: 2 })
const t2 = Date.now()
while (Date.now() - t2 < 300) {}
return {
extra: [].extra,
max: typeof Math.max,
frozen: Object.isFrozen(JSON),
sealed: Object.isSealed(Number.prototype) && !Object.isFrozen(Number.prototype),
extensible: Object.isExtensible(Date.prototype),
untouched: Object.isExtensible(Map.prototype) && typeof Math.min,
}`
const { step, suspended } = await suspendAt(code)
step.reset()
const runtime = CodeMode.make({ engine: "vm", tools: { step: step.tool } })
const again = background(runtime.resume(CodeMode.toBytes(suspended.state)))
await step.called()
await Bun.sleep(10)
// Nothing changed a built-in since the first resume: the second state keeps what changed before.
const second = suspendedOf(await Effect.runPromise(again.suspend))
const outcome = await Effect.runPromise(background(runtime.resume(CodeMode.toBytes(second.state))).result)
expect(outcome).toMatchObject({
ok: true,
value: {
extra: "patched",
max: "undefined",
frozen: true,
sealed: true,
extensible: false,
untouched: "function",
},
})
})
})
+11 -7
View File
@@ -1,6 +1,7 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
import { CodeModeTool } from "@opencode/core/codemode/tool"
import { Config } from "@opencode/core/config"
import { Flag } from "@opencode/core/flag"
import { Permission } from "@opencode/core/permission"
import { Tool } from "@opencode/core/tool"
import { execute } from "@opencode/core/tool/runtime"
@@ -10,7 +11,7 @@ import { ConfigExperimental } from "@opencode/schema/config/experimental"
import { Session } from "@opencode/schema/session"
import { SessionMessage } from "@opencode/schema/session-message"
import type { Info } from "@opencode/schema/tool"
import { Deferred, Effect, Fiber, Schema } from "effect"
import { Deferred, Effect, Fiber, Layer, Schema } from "effect"
import { TestClock } from "effect/testing"
import { it } from "./lib/effect"
import { permissionService } from "./lib/permission"
@@ -29,12 +30,15 @@ const createCodeMode = (tools: ReadonlyMap<string, Info>, permission = allowAll)
CodeModeTool.create({ tools }, (_, tool, input, context) => execute(tool, input, context), permission)
const vmConfig = (codemode_vm: boolean) =>
Config.testLayer([
new Document({
type: "document",
info: new ConfigInfo({ experimental: new ConfigExperimental.Info({ codemode_vm }) }),
}),
])
Layer.merge(
Layer.succeed(Flag.Overrides, undefined),
Config.testLayer([
new Document({
type: "document",
info: new ConfigInfo({ experimental: new ConfigExperimental.Info({ codemode_vm }) }),
}),
]),
)
test("execute describes invariant Code Mode behavior", () => {
expect(createCodeMode(new Map()).description).toBe(