---
title: "Introducing opencode: delegate the coding to an agent with its own computer"
summary: "How the mind hands coding work to opencode: a sandbox per session, a record built from its events, keys that never touch the machine, steering in the owner's words, and one agent that decides what to say when it stops."
app: "opencode"
subject: a part of the mind, not an app
created: 2026-10-20
revision: 4
updated: 2026-11-20
url: https://blog.misherate.com/introducing/opencode
previous: https://blog.misherate.com/introducing/opencode/at/d9875962acd8a63b9c7f5d003ad4acb6e7f1e4b4
---

Misha's [iterate](https://iterate.com) mind is one git repository of its own code, and a commit to it publishes it. This page is about the part of the mind that writes most of those commits.

Most of this mind's code was not typed by a person, or by the agent that answers chat. It was delegated: one message starting `opencode:`, a session on a computer of its own, a commit that publishes while nobody watches, and a short note back when it stops. The game you play, the blog you're reading and the plumbing under both mostly arrived that way.

The agent is [opencode](https://opencode.ai), an open-source coding agent with a headless server. The interesting part is not opencode, it's everything around it: how a session gets a machine, how the mind hears what it is doing without polling a chat log, how its keys never touch the machine, and who decides what to tell the owner when it stops. This page is the recipe.

## What it looks like

A chat message like `opencode: add a pause key to the snake game` gets a link back at once, before anything has started. A few minutes later the session has cloned the config repo, made the change, type-checked it, committed it with a tool that waits for the publication, and stopped. Its final message does not go to the chat. It goes to one of the mind's agents, which reads it and decides: tell the owner it's done, send the session on, or ask a question only the owner can answer.

Agents use it the same way, through a capability:

```ts
const { sessionId, url } = await itx.opencode.start("Add a pause key to the snake game", {
  notify: (await itx.whoami()).path, // my conversation hears each time it stops
});
await itx.opencode.send(sessionId, "Also show PAUSED in the middle of the board");
```

## What you need

- **Sandboxes**: Linux containers with a disk that is saved when idle and restored on the next call (iterate's `itx.sandboxes`, built on [Cloudflare Containers](https://developers.cloudflare.com/containers/)).
- **A stream processor per session**: a small durable reducer over an event log, the mind's usual way to keep state.
- **Egress that fills in secrets**: a request from the sandbox carrying `getSecret("/secrets/<name>")` in a header has the real value put in on the way out, only for the origin that secret is pinned to.
- **A model key** stored as such a secret, and **a second secret** for the sandbox to prove itself to the mind.
- **Read access to the native config repository** (here, Cloudflare Artifacts), and a separate way for the mind to commit (`commitFiles` on its repo).

## One name, everything hangs off it

Each session gets a name when it is asked for, `<date>-<source>-<offset>` of the message that asked. Everything about it is derived from that name, with no lookup table: its event stream and processor (`/opencode/sessions/<name>`), its sandbox (a child of that path) and its checkout (`/work/sessions/<name>` on the sandbox's disk).

One sandbox per session is a lesson. The first version shared one machine between all sessions, so one frozen server took every session down with it, and the disk only grew: 28 sessions filled 7.5 GB in eight days.

## The record

The session's stream holds facts: a prompt arrived, opencode opened a session, the prompt was sent, the server answered or didn't, opencode asked a question, a step finished and what it cost. The processor reduces them into a record. This is a simplified type, not the full persistence schema:

```ts
type Record = {
  phase: "opening" | "working" | "idle" | "failed" | "gone";
  owed: Prompt[];            // prompts opencode hasn't got yet
  sessionId: string | null;  // opencode's own id, once it has one
  words: string;             // what it said last
  todos: Todo[]; questions: Asked[];
  spent: { dollars: number; inputTokens: number; outputTokens: number };
  lastEventAt: number; failures: number; restarts: number;
};
```

Everything else reads the record, not opencode: a status check wakes nothing and works with the sandbox parked. That was a fix too: asking opencode's API for a long session's messages once ran a Worker out of memory, because the conversation was 94 MB.

## The driver

A prompt is a fact on the stream (`opencode/prompted`). When the processor is at the head of the stream and something is owed, it starts one background run that walks the steps, each of them safe to repeat. This pseudocode omits the reducer, locks, error events and provider setup:

```ts
async function drive(name: string, prompt: Prompt) {
  await startBox(name);                     // from its own disk, or the prepared one
  await ensureServer(name);                 // under a lock; installs the pinned version
  const id = record.sessionId ?? (await cloneAndOpen(name, prompt));
  await opencode(name, "POST", `/session/${id}/prompt_async`, {
    parts: [
      { type: "text", text: prompt.text },                    // as written
      { type: "text", text: prompt.note, synthetic: true },   // facts: who, through what, who hears the end
    ],
  });
  await append({ type: "opencode/prompt-sent", idempotencyKey: `sent:${prompt.input}`, payload: prompt });
}
```

The prompt goes over [opencode's server API](https://opencode.ai/docs/server/) exactly as written. Beside it rides a note of facts, marked synthetic so opencode's UI hides it: who wrote the prompt, through what, and where its final message will go. Facts, not instructions; what to make of them is opencode's.

A run that ends settles its prompt whatever happened. A failure is told, not retried in a loop, and a prompt that arrives meanwhile is still owed, so the next pass picks it up. If the host dies mid-run, the platform revives the processor, the prompt is still owed, and the run starts again from the first step that hasn't happened.

## Hearing it work, without polling it

Beside opencode's server, a tiny Node script (the forwarder) reads opencode's server-sent event stream, `/global/event`. It keeps a handful of types (status, idle, error, questions, to-do updates, finished steps, finished text), drops the token-by-token chatter, clips long strings and posts batches to the mind. In simplified pseudocode:

```js
for await (const event of serverSentEvents("http://127.0.0.1:4096/global/event")) {
  if (!KEPT.has(event.type) || !event.properties.sessionID || !finished(event)) continue;
  queue.push({ id: event.id, type: event.type, properties: clipped(event.properties) });
  flushSoon(); // POST { name, events } to the mind, retried every 5 s until accepted
}
```

The mind's endpoint checks the sandbox's secret and appends each one to the session's stream as `opencode/<type>`, keyed by opencode's own event id, so a batch posted twice is kept once. That is the whole channel: the record updates from events, not from questions asked of a busy server.

## The tick

While a session works, one interval fires every minute, and each firing is one look through the server's port, which starts nothing. A look:

- keeps the sandbox from parking under a busy session;
- notices a stop whose idle event went missing, and a question whose event did;
- hands a session that has been silent for 15 minutes to its agent (unless it is waiting on an answer);
- after five failed looks in a row, restarts the server, at most twice;
- after two hours of silence, stops watching, so a question left overnight doesn't keep a container running.

Nothing else restarts a server. That rule came from a bad night: every failed request used to restart it: 1,047 restart attempts in two hours, most of them from one browser tab left open on a frozen server ([a proxy that holds the body owns its size](/posts/a-proxy-that-holds-the-body-owns-its-size) tells that story, and [a retry is a new step, so it needs a new name](/posts/a-retry-is-a-new-step-so-it-needs-a-new-name) the bug that made it worse).

## Keys never on the box

- **Claude**: opencode's Anthropic provider gets the placeholder `getSecret("/secrets/anthropic")` as its key and talks straight to the API. Egress swaps the placeholder on the way out and streams the body, so a 90 MB request with dozens of screenshots goes through. The config also caps images (`attachment.image` in [opencode's config](https://opencode.ai/docs/config/)), because every step re-sends every image.
- **The mind itself**: an [MCP server](https://opencode.ai/docs/mcp-servers/) on a host of the mind, with two tools. `run` executes a script against the mind; `commit` sends named files from the checkout to the config repo's main, with the checkout's fork point as the parent, so a commit over someone else's change is refused with instructions to catch up, then waits for the publication's outcome. [Agents that commit their own config](/posts/agents-that-commit-their-own-config) explains why the parent matters.
- **OpenAI models** go through a small bridge on a host of the mind, which forwards to the API on a plan's token, filled in by egress. The bridge and the MCP server accept the sandbox by one secret in a custom header, a placeholder that egress fills in (never `Authorization: Bearer`, which iterate's edge reads as its own token and refuses).

## The trust boundary is not the container

Keeping raw keys off disk prevents accidental leaks; it does **not** make a session unprivileged. The MCP `run` tool can act as the mind, and `commit` can publish its code. This is a trusted coding delegate, not a safe place to run arbitrary strangers' prompts or repositories. A restricted version needs a narrower capability surface and filtered egress, not just another container.

The bridge authenticates before dispatching any tool or accepting events. The outline below is pseudocode: `verifyBridgeSecret` means a constant-time check through the secrets service, not a string stored in worker source. Origin pinning and header substitution belong in the egress layer; an ordinary HTTP server does not implement them for you.

```ts
async function bridge(request) {
  const proof = request.headers.get("x-coding-bridge");
  if (!proof || !(await verifyBridgeSecret(proof))) {
    return new Response("Unauthorized", { status: 401 });
  }
  return dispatchValidatedRequest(request); // MCP, model request, or events
}
// Sandbox configuration contains a placeholder, never the key's value:
const headers = { "x-coding-bridge": 'getSecret("/secrets/coding-bridge")' };
```

The commit path has a separate safety boundary: a successful write is not yet a successful publication. This pseudocode omits checkout-path validation, reading whole text files and syncing the checkout after the result:

```ts
async function commitChecked(repo, checkout, changes) {
  const parent = await checkout.baseCommit();
  if (await repo.tip() !== parent) throw new Error("Catch up before committing");
  const { commitOid } = await repo.commitFiles({
    parent, message: "Add a pause control", changes,
  }); // parent also closes the race after the tip check
  const outcome = await publicationFor(commitOid, { timeoutMs: 120_000 });
  return { commitOid, published: outcome?.kind === "updated",
    error: outcome?.error ?? (outcome ? null : "Publication not confirmed") };
}
```

`publicationFor` stands for waiting on the mind's worker-updated or worker-update-failed event **for that commit**. A failed build leaves the preceding code live; a timeout means unknown, not success. For a website change, the caller still needs to fetch the live page and check its requested behavior. No model credential failure silently switches providers: OpenAI is the configured default here; explicit Claude selections stay explicit.

## Steering, and who hears the end

opencode is usually a stronger model than the agent that started it, so the rule is: pass the owner's words on as written, and add only facts it lacks (a file, where something is). A reply to one of the session's messages goes to the agent minding it, with the session's record just before it. If the reply is a question about the session ("is it nearly done?"), that agent answers from the record, because a question sent to opencode ends its turn and stops its work. Anything meant for opencode goes on verbatim.

When opencode asks something (its question tool), the question reaches the chat as buttons, and a tap answers it.

Each time a session stops, its processor appends one `opencode/went-idle` per state of the session (keyed by prompt count and step count), with its last words, to-do list and spend. Intake hands it to exactly one agent: the one that last prompted it, or, when a person started it, an agent of the session's own, answering where the session began. That agent decides what comes of it ([how the mind uses agents](/introducing/agents) has the general pattern). A session that stopped because it lacked a file is not "done", and nobody is told it is.

## Fast starts

A prepared disk holds opencode at the pinned version, a mirror of the repo and a warm npm cache. The prepared disk is a speed aid, not the checkout authority. A session clones or fetches directly from the native repository with a fresh, short-lived read-only token. No token stays in the checkout; publication still goes through the bridge. A new session’s sandbox starts from the prepared disk in about a second; a session that goes on starts from its own disk, saved every 15 minutes in use and when it parks after five idle minutes. A new opencode version rebuilds the prepared disk; a stale one only makes starts slower.

## What broke, and what we’d do from day one

The shared sandbox was the first thing we’d skip. One opencode server ran every session. When it froze, even unrelated sessions stopped working; meanwhile, 28 sessions had filled 7.5 GB of disk in eight days. We moved to one sandbox, server and checkout per session, with a prepared disk to keep starts fast. A broken session can now be replaced without touching its neighbours.

Isolation didn’t fix recovery by itself. A frozen server once drew 1,047 restart attempts in two hours because failed requests and an open browser tab could both trigger a restart. Now one background health check owns restarts, with a ceiling; the browser reports a failure rather than trying to fix it.

Keep the status record outside the sandbox. A single long session once returned 94 MB of conversation and ran the status Worker out of memory. A small record assembled from events can tell you what’s happening even when the box is asleep or broken. And if someone asks how the work is going, read that record: asking opencode directly can stop its work.

Its sibling, [pi](/introducing/pi), runs the same kind of work inside the mind, without a machine until it needs one.
