opencode v2 mirror
README.md

@opencode/codemode #

This is our take on code mode: a lightweight, pure interpreter for a JavaScript-like language built around calling tools. It supports familiar JavaScript syntax with a few key differences and limitations. See the interpreter support checklist for more details.

Rather than trying to sandbox arbitrary JavaScript, CodeMode only runs the language features we implement. Programs cannot directly access the network, filesystem, processes, or application APIs. They can interact with the outside world only through tools provided by the host, which can also limit execution time, tool calls, output size, and data.

The idea of code mode was originally introduced by Cloudflare. See their post to learn more about the concept and their isolate-based approach.

How it differs from JavaScript #

  • Only supported APIs are available. Programs can use the provided tools, supported JavaScript built-ins, and the globals the host adds through extensions. Timers, process, filesystem access, imports, and modules are unavailable.
  • Unfinished work must be joined. Tool calls and async functions start when called. Await them or register them with waitUntil or waitAfter to extend the invocation. After the program and registered work finish, anything still running is interrupted. Unhandled rejections from un-awaited, unregistered promises are returned as warnings.
  • REPL-style results. Without an explicit return, the final top-level expression becomes the result. undefined becomes null. With contribution registrations, collected outcomes replace this ordinary result.

Unsupported syntax returns an UnsupportedSyntax diagnostic with a source location. Current gaps are tracked in the interpreter support checklist.

Quick Start #

import { CodeMode, Namespace, Tool } from "@opencode/codemode"
import { Effect, Schema } from "effect"

const lookupOrder = Tool.make({
  description: "Look up an order by ID",
  input: Schema.Struct({ id: Schema.String }),
  output: Schema.Struct({ id: Schema.String, status: Schema.String }),
  execute: ({ id }) => Effect.succeed({ id, status: "open" }),
})

const runtime = CodeMode.make({
  tools: { orders: { lookup: lookupOrder } },
})

const result = await Effect.runPromise(
  runtime.execute(`
    const order = await tools.orders.lookup({ id: "order_42" })
    return { id: order.id, needsAttention: order.status !== "complete" }
  `),
)

result is always a CodeMode.Result.

API #

Tool.make #

input and output accept either an Effect Schema or a render-only JSON Schema document. Effect Schema input is decoded before execute; Effect Schema output is decoded and safely copied before the program sees it. JSON Schemas only shape the model-visible signature. Without output, the signature uses Promise<void>.

Descriptions and schemas are model-visible contracts. Authorization belongs in execute.

Nested records are the shorthand for ordinary namespaces. Use Namespace.make when a namespace needs a description:

const runtime = CodeMode.make({
  tools: {
    orders: Namespace.make({
      description: "Purchases, fulfillment, and shipment tracking",
      tools: { lookup: lookupOrder },
    }),
  },
})

Namespace descriptions are optional and participate in search matching for every descendant tool. Names still come from record keys, so the wrapper does not repeat orders. Dots in keys create nested paths; other characters use bracket notation, such as tools.context7["resolve-library-id"](...).

CodeMode.execute and CodeMode.make #

CodeMode.execute({ ...options, code }) runs once. CodeMode.make(options) creates a reusable runtime:

const runtime = CodeMode.make({ tools, limits: { timeoutMs: 30_000 } })

runtime.catalog() // structured tool descriptions
runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>

The Effect environment is inferred from the supplied tools. hooks surround every call the program makes into the host: tool.before/tool.after receive { name, input } with decoded input, extension.before/extension.after receive { extension, name, args }. An after hook also receives how the call ended (success with its value, failure with its error, or interrupted). A before hook runs before the call reaches the host, and a failing one denies it: the host function is never called, and the program catches the failure as a thrown error. A denied call fails the way the call itself would: a tool call or asynchronous global rejects its promise, and a synchronous global throws.

Extension.make #

Extensions are host functions a program calls directly as globals, such as fetch. Unlike tools they are not in the catalog, not counted against maxToolCalls, and not described to the model; the host decides what they mean.

const web = Extension.make({ name: "web", globals: { fetch: async (url: string) => globalThis.fetch(url) } })
const runtime = CodeMode.make({ tools, extensions: [web] })

A global is synchronous unless it is an async function or is marked with Extension.async. Mark a plain function that returns a Promise or an Effect, so a denied call rejects its promise like any other failure:

Extension.make({ name: "web", globals: { fetch: Extension.async((url: string) => globalThis.fetch(url)) } })

A global may return a value, a Promise, or an Effect. An Effect's requirements join the runtime's environment the same way a tool's do, so the host can provide per-execution services such as the calling session:

const web = Extension.make({
  name: "web",
  globals: {
    fetch: Extension.async((url: string) =>
      Effect.gen(function* () {
        const session = yield* Session
        yield* session.authorize(url)
        return yield* Effect.promise(() => globalThis.fetch(url))
      }),
    ),
  },
})
const result = yield* CodeMode.make({ extensions: [web] }).execute(code).pipe(Effect.provideService(Session, session))

Every value crossing in either direction is converted, never shared: arguments come in as copies, results go out as copies, and a function inside a result is callable the same way. A global that shadows a built-in or another extension throws at CodeMode.make.

OpenAPI tools #

OpenAPI.fromSpec converts an OpenAPI 3.x document into one tool per supported operation. Dotted operationId values create namespaces:

const api = OpenAPI.fromSpec({ spec, auth: { resolve } })
const runtime = CodeMode.make({ tools: { opencode: api.tools } })

The synchronous result is { tools, skipped }. Operations with unsupported parameter encodings, request bodies without JSON content, WebSocket or SSE semantics, or binary responses are reported in skipped.

Authentication is resolved by the host and never shown to the model. Generated tools require HttpClient.HttpClient. Request signatures omit readOnly properties; response signatures omit writeOnly properties. These JSON Schemas shape model-visible signatures but do not filter runtime values: nested JSON body properties and decoded server responses pass through unchanged. See src/openapi/types.ts for option details.

Joining contributed work #

The runtime intrinsic waitUntil(promiseOrThunk) registers work that must finish before execution returns. It returns undefined, adopts promises/thenables/plain values like Promise.resolve, or immediately invokes a supported function with no arguments and this === undefined. A thunk's returned promise is joined; its ordinary throw/rejection becomes a rejected contribution. Its ordered result slot is reserved before invocation, including before nested registrations. An optional leading name string labels the contribution: waitUntil("lookup", job) records name on that entry in the final array, listener snapshots, and fallback logs. A name without work is a catchable TypeError; to contribute a string value itself, wrap it: waitUntil(Promise.resolve("value")). These registration intrinsics are not catalog tools and do not count against maxToolCalls; their tools still count normally.

waitUntil(tools.orders.lookup({ id: "order_42" }))
waitUntil(Promise.reject("unavailable"))
return "ignored when work was registered"

The final Result.value is an array with one outcome per registration, in registration order, regardless of completion order. Each outcome is { status: "fulfilled", value } or { status: "rejected", reason }, just like Promise.allSettled, preceded by name when the registration carried one. Registered rejections do not fail execution, cancel peers, or produce duplicate unhandled warnings. Registering the same promise twice contributes twice. Without any registrations, the ordinary return/REPL result is unchanged. The usual JSON boundary rules still apply, including omitted undefined object fields.

With contributions and no custom settlement listeners, the runtime logs the outcomes through its captured console.log, using the same formatting and output budget as program console calls. It does not log [] for ordinary programs without contributions. Registering a custom listener replaces this fallback, even if that listener fails.

Reusable helpers and the caller's result #

Any contribution, including one hidden inside a helper, replaces main's ordinary result. A self-registering helper changes its caller's return contract even if the caller never calls a registration intrinsic itself:

function registerOrder(id) {
  waitUntil(tools.orders.lookup({ id }))
}
registerOrder("order_42")
return "summary" // replaced by the helper's contributed outcomes

Prefer helpers that return promises, such as const lookupOrder = id => tools.orders.lookup({ id }), letting callers choose await lookupOrder(id) or waitUntil(lookupOrder(id)). If registration is intentional, advertise that side effect in the helper's name and contract. Awaiting a self-registering helper does not undo its contribution.

After-work phases #

waitAfter(promiseOrThunk) also registers one contribution and returns undefined, but a function starts after the current immediate batch settles. waitAfter(name, thunk) and settleAfter(name, source, callback) accept the same optional leading name as waitUntil. This is a global batch barrier across every producer, not a per-source cleanup boundary: waitAfter thunks and settleAfter callbacks wait for all immediate work, including descendants. Use them for batch epilogues. For cleanup as soon as one source settles, use settle(job, callback), which has no batch barrier. For result-aware cleanup in the after phase, use settleAfter(source, callback): registration-only shorthand for waitAfter(() => settle(source, callback)), returning undefined and contributing exactly one preserved source outcome unless the callback fails. Unlike settle, it does not return a completion Promise. It validates the callback and observes/adopts its known source immediately while deferring callback invocation. Its source follows settle's value/promise contract, not a separate thunk overload.

const job = tools.orders.lookup({ id: "order_42" }) // already running
waitUntil(() => tools.orders.lookup({ id: "order_43" })) // starts immediately
settleAfter(job, async outcome => {
  console.log(outcome)
  await Promise.resolve()
  waitUntil(() => tools.orders.lookup({ id: "followup" }))
})

Use settleAfter as a registration statement, not a completion expression. It already contributes one outcome and returns undefined; settle(job, cb) instead returns a Promise and contributes nothing by itself:

settleAfter(job, cb) // one contribution; correct after-phase registration
waitUntil(settleAfter(job, cb)) // WRONG: also contributes a fulfilled-undefined entry
await settleAfter(job, cb) // WRONG for waiting: awaits undefined, not the job or cleanup
waitUntil(settle(job, cb)) // one contribution; per-source callback without a batch barrier
await settle(job, cb) // waits for this source and callback; no contribution

The global barrier couples otherwise independent producers. This is documented behavior, not per-source ordering:

function producerA(job) {
  settleAfter(job, () => console.log("A cleanup"))
}
function producerB(slowJob) {
  waitUntil(slowJob)
}
producerA(tools.orders.lookup({ id: "order_42" }))
producerB(tools.orders.lookup({ id: "slow_unrelated" }))
// Even if A's source finishes first, A cleanup waits for B's unrelated job.

If B waits for a resource that A's after callback must release, the barrier creates a release-wait cycle. Use settle(job, cb) for per-source release instead. Existing stuck-promise/timeout diagnostics are the backstop for such cycles, not an automatic repair or a way around the barrier.

  • Drain immediate work, capture one fixed after-work wave, start its thunks in registration order, and join their results concurrently. Immediate work registered during a wave starts normally; after-work registered during that wave waits for the next wave. Drain waves and immediate descendants before notifying waitUntil.onSettled. Consequently listeners see only entirely settled prefixes, including after-work outcomes. Listener-added work takes the same phase route before another notification. No registration is automatically replayed.
  • With no immediate jobs, a nonempty after wave still starts after the main program finishes. All registration types share one final registration-ordered array. waitUntil(job); settleAfter(job, cb) explicitly contributes twice; settleAfter(job, cb) alone contributes once, with no implicit source entry or nested outcome value.
  • A promise passed to waitAfter is observed immediately, but it is already running: only joining can be deferred. waitAfter(settle(job, cb)) cannot defer that combinator's callback. Use waitAfter(() => settle(job, cb)) or settleAfter(job, cb) instead. To defer job creation too, put the tool call inside the waitAfter thunk.
  • All registration functions return undefined: await waitAfter(...) does not wait for an after phase. Do not make an earlier batch depend on later after-work, or an active wave depend on a thunk queued for the next wave. These backward dependencies can deadlock and receive existing stuck/timeout diagnostics; there is no recursive drain.
  • Ordinary rejected after-work does not skip peers or descendants. Observed interruption bypasses phase delays and aborts active collection/listener joins promptly, cleaning up blocked host work. Ordinary main-program failures still drain admitted phases before failing. Closure before final copy-out applies to every registration function.

Completion listeners #

Register repeatable listeners with waitUntil.onSettled(callback, options?):

waitUntil(tools.orders.lookup({ id: "order_42" }))
let followedUp = false
waitUntil.onSettled(
  async (items) => {
    if (followedUp) return
    followedUp = true
    const order = items[0]
    if (order.status === "fulfilled") {
      const id = await tools.orders.next({ order: order.value })
      waitUntil(tools.orders.lookup({ id }))
    }
  },
  { mode: "new" },
)
// Explicitly keep the same globally available logger beside the custom listener.
waitUntil.onSettled(console.log, { mode: "new" })

mode: "new" is a delivery cursor, not loop protection. A listener that registers an output on every delivery self-feeds indefinitely: its output is new input for the next cycle, until an invocation limit stops it.

// WRONG unless deliberately bounded: every delivery creates another delivery.
waitUntil.onSettled(items => waitUntil(Promise.resolve(items.length)), { mode: "new" })

When follow-up outcomes should not become contributions, await that work inside the listener instead of registering it. The runtime joins the listener's promise, ignores its return value, and adds no contributions from these calls:

waitUntil.onSettled(async items => {
  await Promise.allSettled(items
    .filter(item => item.status === "fulfilled")
    .map(item => tools.orders.next({ order: item.value })))
}, { mode: "new" })

If follow-ups should contribute, use an explicit bound or stopping condition, such as followedUp above.

  • Listeners run after all currently registered immediate and after-work jobs settle. Each listener defaults to mode: "all", supplying every collected outcome; mode: "new" supplies only registrations not previously delivered to that listener. Both preserve registration order, and each listener has its own cursor.
  • Each cycle fixes the contribution cutoff and listener list before calling anyone. Callbacks start in registration order without waiting for earlier callbacks' promises, so independent async listeners can release one another. The runtime then implicitly awaits all returned values, promises, and thenables together. Return values are ignored, not contributions. Jobs added by any callback, even after its own await, drain before the next cycle.
  • A newly registered listener gets an initial snapshot, including [] for an empty collection, allowing bootstrap work. Listeners registered during a callback join the next cycle, even if no jobs were added. No listener repeats an unchanged delivered cutoff. The final returned array is always cumulative, including in new-only mode; if no jobs were registered, the ordinary program result remains.
  • Every delivery has a fresh array and fresh outcome records. Replacing an entry or its status, value, or reason field cannot corrupt retained outcomes. Contributed objects keep their interpreter identity: mutating an object inside value or reason affects that object normally, including in peer listeners. No JSON conversion occurs between cycles.
  • Registration stays open through registered jobs and awaited listeners, then closes before final result copy-out. Calling waitUntil from toJSON during that final copy-out throws; it is too late to extend collection.

Main-program errors and completion-listener errors remain execution failures, not contribution entries. A throwing or rejecting callback does not skip peer callbacks: the cycle and admitted jobs finish, failed listeners are not retried, and successful listeners can receive later snapshots. The first failed listener in registration order supplies the error, unless the main program failed, in which case its error wins. Cancellation, self-interrupted host work, and execution timeouts retain their existing interruption/cleanup behavior. A timeout during joined jobs or listeners is a TimeoutExceeded failure, not partial success. An endless chain of new registrations remains subject to the invocation's limits, and an impossible-to-settle registration gets the existing stuck-promise diagnostic.

Per-job settlement callbacks #

Use the global settle(promise, callback) for a result-aware finally. It returns a new interpreter Promise, adopting input promises, thenables, and plain values like Promise.resolve. The required callback receives one record, { status: "fulfilled", value } or { status: "rejected", reason }, for the input's ordinary settlement:

waitUntil(settle(tools.orders.lookup({ id: "order_42" }), async (outcome) => {
  console.log(outcome)
  await Promise.resolve()
  // More waitUntil work may be registered here, including after await.
}))
// For logging alone, use settle(job, console.log).

The callback runs for fulfillment or rejection, and its returned promise/thenable is awaited. A successful callback's return value is ignored: the wrapper preserves the original fulfilled value or rejection reason. If the callback throws/rejects, its failure becomes the wrapper's rejection, matching finally. Outcome containers are fresh, but contributed objects/reasons retain their identity and normal nested mutation. Interruption and cancellation are runner control flow, not ordinary rejection records: an interrupted input bypasses the callback, and interruption while joining the callback still propagates and cleans up host work.

waitUntil(settle(job, console.log)) therefore returns a flat allSettled-shaped array, not an array of nested outcome values. It logs the individual job explicitly; if no custom batch listeners exist, the final-batch fallback also logs the collected array. Both are intentional; there is no deduplication policy. Use waitUntil.onSettled(console.log, { mode: "new" }) for batch logging beside other custom batch listeners instead. settle itself does not extend invocation lifetime: await its promise or register it with waitUntil/waitAfter.

Unlike settle(job, console.log), job.finally(console.log) receives no outcome argument and job.then(console.log) replaces a fulfilled value with undefined while not handling rejection.

Implementation provenance: commission and reviewed lifecycle. Revision provenance: fallback logging, joined listeners, settle, and approved after-work phases. Teaching revision: registration, global-barrier, listener-cursor, and helper-contract hazards.

Results #

Every execution returns:

type Result =
  | {
      readonly ok: true
      readonly value: CodeMode.DataValue
      readonly warnings?: ReadonlyArray<CodeMode.Diagnostic>
      readonly logs?: ReadonlyArray<string>
      readonly truncated?: boolean
      readonly toolCalls: ReadonlyArray<CodeMode.ToolCall>
    }
  | {
      readonly ok: false
      readonly error: CodeMode.Diagnostic
      readonly logs?: ReadonlyArray<string>
      readonly truncated?: boolean
      readonly toolCalls: ReadonlyArray<CodeMode.ToolCall>
    }

value is JSON-safe. warnings are non-fatal diagnostics, logs contain program console output, and truncated indicates that retained output was cut by maxOutputBytes. toolCalls retains admitted calls in order, including after failure.

Diagnostic kinds:

Kind Meaning
ParseError Source is empty or cannot be parsed.
UnsupportedSyntax Parsed JavaScript is outside the supported subset.
UnknownTool The program referenced an unavailable tool.
InvalidToolInput Tool input failed schema decoding or safe-data copying.
InvalidToolOutput Tool output failed schema decoding or safe-data copying.
InvalidDataValue Program data violated the plain-data contract.
ToolCallLimitExceeded The program exceeded maxToolCalls.
TimeoutExceeded Execution timed out; as a warning, background work was interrupted after the program returned.
ToolFailure A tool refused or failed.
ExecutionFailure The program threw or another execution error occurred.
Truncated Warning only: additional warnings were omitted by maxOutputBytes.

Host failures and defects report their messages and underlying causes. Invalid outputs include the validation or copying error. Interruption propagates without becoming an error diagnostic.

Discovery #

runtime.catalog() returns structured descriptors — exact path, description, and generated TypeScript signature — for every visible tool. Hosts render their own model-facing instructions from these descriptors; CodeMode.searchSignature and CodeMode.toolExpression(path) supply the exact callable forms.

The synchronous search(...) built-in is always available. It supports exact-path lookup, namespace-scoped search, empty-query browsing, and pagination, and returns callable paths with full signatures. Its result can be used directly, awaited, or chained with then, catch, and finally, so programs work whichever way they treat it. Search counts toward maxToolCalls. Search also matches descriptions from enclosing Namespace values.

Execution Limits #

Limit Default Controls
timeoutMs unlimited Total execution time.
maxToolCalls unlimited Admitted tool calls.
maxOutputBytes unlimited Retained result value and logs.

Execution limits have no default values.

Invalid limit configuration throws RangeError. Warnings receive a separate budget equal to maxOutputBytes. Truncation does not fail execution; an oversized value becomes a string with an in-band marker. Timeouts interrupt tool calls and busy loops, while a result returned before cleanup times out remains successful with a TimeoutExceeded warning. Tool-call concurrency is unrestricted. Boundary data is limited to 32 nested levels.