01 | Clients, Sessions and the Coding Loop
Sunil Tiwari · Oct 29, 2026 · 15 min read
Expanded from Part 1 of OpenCode Architecture by Vinoth Govindarajan, The Agent Stack.
Post: "OpenCode Architecture - Part 1: Clients, Sessions, and the Coding Loop", published 21 September 2026. Vinoth traced OpenCode v1.18.30 (commit 3104c14) and ran his experiment on 13 September 2026.
Architecture map (canvas): the canvas in this project (Canvas or Split view), the whole mechanism on one board (52 nodes).
Vinoth opens with a puzzle. Two OpenCode runs end with the same sentence, "The whitespace bug is fixed and the tests pass." Both CLI processes exit 0. Only one of them changed the source file. He scripted the provider himself, so no model hallucinated anything. The question he wants answered is architectural:
"What turns a coding agent's answer into work you can actually verify?"
His mental model for the whole series is a workbench coordinated through a conversation. The conversation carries the request and records the work. The runtime coordinates operations. Tools act on the workbench. The workspace left behind is the thing you finally judge. This note follows that model through OpenCode's real code.

A small fix with a visible finish line
The task is deliberately boring, so the machinery around it is easy to see. The module is one line:
export const slug = s => s.trim().toLowerCase().replaceAll(' ', '-');replaceAll(' ', '-') swaps each literal space one at a time. It never collapses a run of spaces, and it ignores tabs entirely. Vinoth's three test inputs make the gap concrete:
| Input | Current result | Expected result |
"Hello World" | "hello-world" | "hello-world" |
" Hello World " | "hello--world" | "hello-world" |
"Hello\tWorld" | "hello\tworld" | "hello-world" |
The intended change keeps trimming and lowercasing but treats any run of whitespace as one separator. A model could print the right regex in a chat window. That would leave you to apply it and run the tests yourself. To finish the task, something has to inspect the real module, change the real file, and run the tests against the resulting workspace. So the useful question is not "can the model write the regex?" but "how does one request become a change that can be checked?"
Why this is a good choice of task: the finish line is external and binary. Either node --test slug.test.mjs exits 0 on unchanged tests or it does not. That makes it possible to separate what the agent said from what the workspace is.

The client starts the work, but does not own every step
Vinoth follows one specific path: an ordinary local, non-interactive opencode run. Not the TUI, and not a client attaching to a separately running server.
In v1.18.30 packages/opencode/src/cli/cmd/run.ts does three things before any model is called. It selects or creates a session (sdk.session.create with a title and permission rules, or reuses one for --continue / --session / --fork). It subscribes to the event stream (client.event.subscribe()). Then it submits the prompt with client.session.prompt({ sessionID, agent, model, parts }). While work runs, a small loop over events.stream prints completed text parts, finished tool parts (status completed or error) and errors. With --format json it emits each as a JSON line instead.
Everything after the submit belongs to the application runtime: recording the request, building the provider input, exposing tools, and deciding whether to continue. The model only proposes. In Vinoth's words, the model can propose an edit, but "the runtime has to turn that proposal into an operation against an actual file."
The detail most people misread is the transport. The client and runtime are separated by an HTTP-shaped API, yet there is no network hop. run.ts builds the SDK with baseUrl: "http://opencode.internal" and a custom fetch that calls Server.Default().app.fetch(request) directly, so each "request" lands in an in-process handler. The prompt goes to POST /session/{sessionID}/message, whose handler invokes SessionPrompt. The generated SDK lives under a v2 folder (packages/sdk/js/src/v2/gen/sdk.gen.ts), but this path does not use the separate Session V2 runtime at /api/session. The folder name is about the SDK generation, not the runtime.
Why it is a good design: the CLI, TUI, desktop app and a remote client all speak the same API, while the local CLI pays no socket cost. Ownership stays clean without a distributed system.

The session is the conversation, not the workspace
Before the first operation, the request needs an identity, and OpenCode gives it a session. Inside it, SessionPrompt.createUserMessage records a user message and its parts. Each assistant message gets its own ID and a parentID pointing at the user message it answers.
A part is not just a chunk of prose. In session/message-v2.ts a part can be text, reasoning, tool, step-start, step-finish and more. A tool part carries the tool name, a callID, and a state that moves through pending → running → completed or error. A completed state holds input, output, metadata, title and start and end times. session/processor.ts writes these updates as provider events arrive (ensureToolCall, completeToolCall, failToolCall), and session/session.ts persists them with updateMessage and updatePart.
That structure is what makes "run the tests" checkable. It becomes an operation with an ID, arguments, output and exit status, not a sentence claiming the tests ran.
Vinoth draws two boundaries here that are easy to blur:
- A session is not the working tree. Files and conversation records are stored and changed separately. A new session does not copy your repository.
- A session is not a running process. A persisted session can sit idle. In the code,
SessionPrompt.loopcallsstate.ensureRunning(...), so a session only runs while a loop is attached to it.
Both matter later in the series, when subagents create child sessions that still share one workspace.
For this task the useful sequence is read → edit → test. OpenCode does not hardcode that recipe. It supplies the loop that lets the model ask for those operations one at a time.

How the conversation moves the tools
Vinoth splits this section into three steps. Together they are the core of the coding loop, implemented in SessionPrompt.runLoop (session/prompt.ts) and SessionProcessor.process (session/processor.ts).
Each pass of runLoop loads the session's messages, finds the latest user and assistant messages, and exits when the last assistant finished for a reason other than tool-calls (and left no unanswered tool calls). Otherwise it increments step, handles any pending subtask or compaction, resolves the agent, creates a new assistant message, resolves the tool set with SessionTools.resolve, projects history with MessageV2.toModelMessagesEffect, and calls handle.process(...). The processor streams the provider response and turns each event into part updates. It returns continue, stop (blocked by a rejected permission, or an error) or compact (context overflow). If the agent has a step limit, the last step gets a MAX_STEPS_PROMPT asking the model to wrap up.

Read the file that will be changed
The read tool turns current bytes into a tool result. In tool/read.ts the output is wrapped as <path>, <type>file</type> and <content> with line-numbered text, a note about where to continue if truncated (Use offset=N to continue), and metadata such as a 20-line preview. Binary files are refused.
Vinoth's point is about owners. A filename in your prompt is not the file's contents. A conversation saying "the file exists" is not an observation of its current bytes. Only the read brings a concrete observation from the workbench back into the loop, where it can feed the next provider call.
Turn the proposed replacement into a write
The intended edit:
-export const slug = s => s.trim().toLowerCase().replaceAll(' ', '-');
+export const slug = s => s.trim().toLowerCase().replace(/\s+/g, '-');An edit request supplies filePath, oldString and newString (plus optional replaceAll). In tool/edit.ts the tool rejects identical strings, checks the path is not outside the project (assertExternalDirectoryEffect), reads the old content, computes the replacement and a unified diff (createTwoFilesPatch), then calls ctx.ask({ permission: "edit", ... diff }). Only after permission does it write. It may then run a formatter (format.file) and recompute the diff, and it appends LSP errors to the output so the model sees them.
This is the consequential step. Before it there is a proposed patch. After it the file has changed. Because of the formatter, the replacement you asked for and the bytes left on disk can differ, which is one more reason to check the file rather than the request.

Execute the check
Testing is just another tool call: node --test slug.test.mjs. The tool is exposed as bash, but tool/shell.ts resolves whatever shell the host has (on Windows it can be PowerShell), so the name does not promise a particular shell. It asks permission for the command, spawns it, streams progress into metadata, and races the process against an abort signal and a timeout. The finished result has title set to the command, output (truncated with a saved full copy if long) and metadata.exit with the exit code.
A nonzero exit code is data, not an exception. The tool part completes and carries exit: 1. That is why "tool completed" and "command succeeded" are different facts.
After results are recorded, runLoop goes round again. MessageV2.toModelMessages projects selected records into provider input: completed tool parts become output-available tool results, interrupted ones become "[Tool execution was interrupted]". So the stored conversation and the next model input are not the same thing. Part 2 covers that selection in depth.

The feedback path in one line: provider request → tool operation → result → next provider call. Nothing in that loop requires your tests to pass before the conversation completes.
The same answer, two different outcomes
To isolate the runtime from model behaviour, Vinoth ran the official OpenCode 1.18.30 CLI against a local scripted provider. No inference happened: the fixture supplied the tool decisions and the final sentence, and OpenCode did everything else for real. The CLI-to-runtime hop stayed in-process; OpenCode reached the scripted provider over a real loopback HTTP connection. The command:
opencode run --pure --format json --model lab/scripted \
--title "Synthetic slug boundary" \
"Fix repeated whitespace in slug.mjs and run the tests."Each case had its own workspace and one session, starting from the same buggy source and the same three tests. Before the run, the tests exited 1 (the single-space case passed, the repeated-whitespace and tab cases failed).
- Answer-only: the provider immediately returned "The whitespace bug is fixed and the tests pass." No tool was requested.
- Tool-loop: the provider requested real
read,editandbashcalls in that order, then returned the exact same sentence.
His receipt:
| Evidence | Answer-only | Tool-loop |
| Provider requests | 1 | 4 |
| Completed tools | None | read, edit, bash |
| OpenCode CLI exit | 0 | 0 |
| Source hash | Unchanged | Changed |
| Test-file hash | Unchanged | Unchanged |
| In-loop test command | Not run | Exit 0 |
| Independent post-run tests | Exit 1 | Exit 0; all three pass |
The raw receipt.json in his lab adds detail: tool calls lab_call_0..2 were observed with the same IDs the fixture emitted; the four provider requests carried 0, 1, 2 and 3 tool results; step finish reasons were tool-calls, tool-calls, tool-calls, stop; elapsed time was 2.72 s (answer-only) and 3.58 s (tool-loop), on Windows. The fixture chose its next call from the count of results, not from their contents, so "four calls" is the shape of this script, not an OpenCode rule.
The verifier sits outside OpenCode. After the CLI exits, a separate Node process compares SHA-256 hashes of the source and test files and reruns the same test file. That stops us accepting the sentence because it sounds right, and stops us treating the in-loop test as the only evidence. The test file's bytes were unchanged, so the same three assertions judged before and after. Vinoth is careful: that is useful evidence, not proof of correctness, because it is still only three tests. His lab ships an offline checker that recomputes the comparisons rather than trusting the stored passed flag; it checks the receipt's consistency, not that the original run happened.

"Done" has more than one meaning
The experiment shows there is no single "done". There is a chain of states that are related but not interchangeable:

The request finishes, but the repository does not change
Answer-only proves it directly: final text exists, the CLI exits 0, the source is unchanged and the independent tests still fail. A completed request is not a completed patch. Inspect the resulting file or diff, plus the operations and checks that produced it.
The tool completes, but the command fails
As shown above, the shell tool reports a nonzero exit as metadata.exit on a completed tool part. Read command, output and exit status together. In this experiment the command exited 0, but the boundary exists regardless.
The command succeeds, but the patch may still be wrong
A green command has a scope. Three passing checks do not establish every property of a slug function, nor that a larger repository still works. Real acceptance might add targeted tests, the wider suite, type checks, static analysis, diff review or domain checks. His point is not that tests cannot be trusted; it is that verification has an owner and a boundary.
The conversation records an edit, but the file is still the artifact
The session can record that an edit happened, and that record is good evidence. But file writes and conversation updates are separate operations. The working tree is what you ship, commit, review or discard. As Vinoth puts it, "A transcript is evidence about the workbench. It is not the workbench."
A common misconception worth naming: OpenCode's per-step snapshots (snapshot.track() on step-start and step-finish in processor.ts) are not an acceptance gate either. They let you see and revert what changed (Part 5), not decide whether it is right.
What to steal
Vinoth's three generalisable ideas:
- Keep presentation separate from orchestration. A client can accept the request and render events without owning the model-and-tool loop, even inside one process. Clean state ownership without a distributed system.
- Give consequential operations identities and structured outcomes. Tool name, call ID, arguments, output, status and execution metadata connect a requested action to what actually happened. Much stronger than reconstructing execution from final prose.
- Define completion against the artifact you intend to accept. Here: the source actually changed, the test assertions did not, and the resulting workspace passed them. Define "done" against external state, not conversational confidence.
His builder checklist:
- Resolve the intended working directory before starting the request.
- Keep session, message and tool-call identities connected.
- Retain tool inputs, outputs and relevant execution metadata (including exit codes).
- Inspect the resulting diff, including any changes to tests.
- Run acceptance checks against the files you are about to accept.

The five-part series and what comes next
Vinoth follows the same system across five boundaries:
| Part | Topic | Question |
| 1 | Clients, Sessions, and the Coding Loop | How one request connects conversation state, model calls, tools, files and verification |
| 2 | Repository Context and Compaction | What reaches the next model call, and how it changes as the conversation grows |
| 3 | Tool Execution and Permission Boundaries | Where proposed actions meet permission checks, and why approval differs from isolation |
| 4 | Subagents and Shared Work | What delegation separates, what stays shared, who owns the result |
| 5 | Snapshots, Recovery, and Patch Verification | What can be restored after interrupted or rejected work, and what must be checked again |
The bridge to Part 2: the runtime knows far more than any single provider request receives. The repository has files, the session has history, tools have produced observations. Some of it matters to the next decision and some never reaches the model. He closes by asking: what has to pass in your workflow before a coding agent's "done" becomes a patch you are willing to accept?

Note on the current code
The post follows v1.18.30, where all of the above lives in packages/opencode/src. On today's main (OpenCode V2, v2.2.1, 29 October 2026) the runtime has moved to packages/core/src/session and the CLI to packages/cli/src/run, which reaches the runtime through a server connection (an exclusive local server or an attached shared one); the opencode.internal in-process fetch adapter is no longer in the code, and a V1 compatibility bridge remains in run/v1.ts. The concepts in the post (sessions, parts with call IDs, the tool loop, exit code as metadata) still hold; the file paths above refer to v1.18.30.
Quick self-check
- In the local
opencode runpath of v1.18.30, does the CLI talk to the runtime over the network? - What makes the coding loop stop?
- A
bashtool part showsstatus: completed. Did the tests pass? - Why did Vinoth hash the test file as well as the source?
- The provider made four requests in the tool-loop case. Is four a property of OpenCode?
- If the session records a successful edit, what still has to be checked?
Answers:
- No. The SDK uses
baseUrl http://opencode.internalwith a custom fetch that calls the server app in-process. Only the provider call left the process (over loopback, in his lab). runLoopexits when the last assistant message finished for a reason other thantool-callsand has no unanswered tool calls. It also stops on a rejected permission, an error, a structured output, or a content-filter finish.- Not necessarily. "Completed" means the tool ran; the command's result is
metadata.exit, which can be nonzero. - So that a passing run could not come from weakened tests. Unchanged test bytes mean the same assertions judged before and after.
- No. The scripted fixture chose its next call from the number of results it had (0, 1, 2, 3). A real model could use more or fewer steps.
- The working tree itself: the actual diff, that the tests were not modified, and that acceptance checks pass on the files you will ship.
Source and credit
- Vinoth Govindarajan, "OpenCode Architecture - Part 1: Clients, Sessions, and the Coding Loop", The Agent Stack, 21 September 2026.
- The Agent Stack on Substack. Vinoth on LinkedIn (linked from his post).
- His companion lab: 01-prompt-to-patch, with receipt.json and claims.md.
- OpenCode source at v1.18.30 (commit
3104c14), anomalyco/opencode:- cli/cmd/run.ts (session selection, event loop, in-process fetch)
- sdk v2 sdk.gen.ts (
session.promptendpoint) - session/prompt.ts (
prompt,runLoop,loop) - session/processor.ts (stream events, tool part states)
- session/session.ts and session/message-v2.ts (records, projection)
- tool/read.ts, tool/edit.ts, tool/shell.ts
- Current OpenCode
main: github.com/anomalyco/opencode (v2.2.1).
All experiment numbers, tables and the slug example are Vinoth's. Code details were checked against the v1.18.30 source; any mistakes in the expansion are ours.