Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

opencode.md

451 lines16.6 KB

1---
2title: OpenCode
3id: opencode-adapter
4order: 14
5description: "Run the OpenCode agent inside a sandbox from TanStack AI, with any model that OpenCode supports. It edits files and runs commands in a real repo and streams each step."
6keywords:
7 - tanstack ai
8 - opencode
9 - opencode sdk
10 - harness
11 - agent
12 - coding agent
13 - adapter
14---
15​
16The OpenCode adapter starts `opencode serve` in a sandbox and streams text and tool steps to `chat()`. The agent edits files and runs commands in a repo.
17​
18You need:
19​
20- A sandbox provider. The samples use Docker, so Docker must run on your machine.
21- An API key for the model provider that OpenCode uses. The samples use OpenAI, so they need `OPENAI_API_KEY`.
22- The `opencode` CLI inside the sandbox. A setup step in the sandbox installs it.
23​
24## 1. Install
25​
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27​
28react: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
29vue: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
30solid: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
31svelte: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
32preact: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
33angular: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
34vanilla: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
35octane: @tanstack/ai-opencode @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
36​
37<!-- ::end:tabs -->
38​
39## 2. Set the API key
40​
41Put the key in the environment of your server:
42​
43```bash
44OPENAI_API_KEY=sk-...
45```
46​
47OpenCode reads the key from the environment of its process. The sandbox in step 3 passes it in as a workspace secret. This adapter has no `authMode` option.
48​
49## 3. Run the agent from the server
50​
51Define the sandbox once. It clones your repo into a Docker container and installs the `opencode` CLI:
52​
53```ts
54// sandbox.ts
55import {
56 createSecrets,
57 defineSandbox,
58 defineWorkspace,
59 githubRepo,
60} from "@tanstack/ai-sandbox";
61import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
62​
63export const sandbox = defineSandbox({
64 id: "opencode-agent",
65 // The host talks to `opencode serve` on port 4096, so publish it.
66 provider: dockerSandbox({ image: "node:22", publishPorts: [4096] }),
67 workspace: defineWorkspace({
68 source: githubRepo({ repo: "owner/app" }),
69 setup: ["npm install -g opencode-ai --include=optional && opencode --version"],
70 secrets: createSecrets({
71 OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? "",
72 }),
73 }),
74});
75```
76​
77Then pass the adapter and the sandbox to `chat()` in your route:
78​
79```ts
80// api/agent.ts
81import {
82 chat,
83 chatParamsFromRequest,
84 toServerSentEventsResponse,
85} from "@tanstack/ai";
86import { opencodeText } from "@tanstack/ai-opencode";
87import { withSandbox } from "@tanstack/ai-sandbox";
88import { sandbox } from "./sandbox";
89​
90export async function POST(request: Request) {
91 const { messages, threadId, runId } = await chatParamsFromRequest(request);
92​
93 const stream = chat({
94 adapter: opencodeText("openai/gpt-5.2", {
95 permissionMode: "acceptEdits",
96 }),
97 messages,
98 threadId,
99 runId,
100 middleware: [withSandbox(sandbox)],
101 });
102​
103 return toServerSentEventsResponse(stream);
105```
106​
107- Replace `owner/app` with your repo.
108- Model ids are `provider/model`. The adapter splits the id at the first `/`.
109- `permissionMode: "acceptEdits"` lets the agent edit files. See [Permissions](#permissions).
110​
111## 4. Render the agent's work
112​
113The client is the same as for any chat. Render the text, and show each tool that the agent ran:
114​
115```tsx
116import { useState } from "react";
117import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
118​
119export function CodingAgent() {
120 const [input, setInput] = useState("");
121 const { messages, sendMessage } = useChat({
122 connection: fetchServerSentEvents("/api/agent"),
123 threadId: "support-chat",
124 });
125​
126 return (
127 <form
128 onSubmit={(event) => {
129 event.preventDefault();
130 sendMessage(input);
131 setInput("");
132 }}
133 >
134 {messages.map((message) =>
135 message.parts.map((part, index) => {
136 if (part.type === "text") {
137 return <p key={`${message.id}-${index}`}>{part.content}</p>;
138 }
139 if (part.type === "tool-call") {
140 return <code key={part.id}>{part.name}</code>;
141 }
142 return null;
143 }),
144 )}
145 <input value={input} onChange={(event) => setInput(event.target.value)} />
146 </form>
147 );
149```
150​
151Ask it "Fix the failing test in utils.test.ts". The text streams token by token, and you see a line for each tool the agent used: `read`, `edit`, `bash`, and more. The agent edited the files inside the container.
152​
153## How it works
154​
155- `opencodeText` declares that it needs a sandbox. `withSandbox(sandbox)` gives it one. Without a sandbox, `chat()` fails at the call site.
156- The adapter starts `opencode serve` inside the sandbox and connects to it over HTTP with the `@opencode-ai/sdk` client.
157- Each `chat()` call runs one full agent turn. OpenCode runs its own loop and its own tools.
158- Text and reasoning stream token by token. The tools of the agent stream back as `tool-call` parts with the results attached. Your code does not run them.
159- The adapter holds each message part until it knows the role of the message. It streams assistant parts and skips user parts.
160- OpenCode can send a tool part before the tool input is ready. The adapter waits for the next update, so each tool call streams with its arguments.
161- The running todo plan of the agent arrives as an `opencode.todo` custom event.
162​
163To learn more about sandboxes, see [Sandboxes](../sandbox/overview).
164​
165## Permissions
166​
167OpenCode asks for permission before it edits files or runs commands. A headless server has no person to answer, so the adapter answers each request from `permissionMode`. A turn never waits for an answer.
168​
169| Mode | What runs |
170| --- | --- |
171| `'default'` | Your bridged tools run. Every other request that asks (edits, shell, web fetch) is rejected. |
172| `'acceptEdits'` | Also allows file edits (edit, write, patch). |
173| `'bypassPermissions'` | Allows every request. Use it only in a sandbox or a scratch directory. |
174​
175To write your own rules, for example to allow only some commands, pass `onPermissionRequest`. It replaces the default policy.
176​
177## Resume a session
178​
179OpenCode keeps its working context between turns: the files it read, the commands it ran, and what it found. The adapter sends the session id of each new run as a custom event named `opencode.session-id`. Send it back in `modelOptions.sessionId` to continue the session.
180​
181On the server, read the id from the request:
182​
183```ts
184import {
185 chat,
186 chatParamsFromRequest,
187 toServerSentEventsResponse,
188} from "@tanstack/ai";
189import { opencodeText } from "@tanstack/ai-opencode";
190import { withSandbox } from "@tanstack/ai-sandbox";
191import { sandbox } from "./sandbox";
192​
193export async function POST(request: Request) {
194 const params = await chatParamsFromRequest(request);
195​
196 // Extra fields the client puts in the connection `body` arrive here.
197 const sessionId =
198 typeof params.forwardedProps.sessionId === "string"
199 ? params.forwardedProps.sessionId
200 : undefined;
201​
202 const stream = chat({
203 adapter: opencodeText("openai/gpt-5.2", { permissionMode: "acceptEdits" }),
204 messages: params.messages,
205 threadId: params.threadId,
206 runId: params.runId,
207 middleware: [withSandbox(sandbox)],
208 modelOptions: { sessionId },
209 });
210​
211 return toServerSentEventsResponse(stream);
213```
214​
215On the client, keep the id from the custom event and send it with each request:
216​
217```tsx
218import { useState } from "react";
219import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
220​
221export function useCodingAgent() {
222 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
223​
224 return useChat({
225 connection: fetchServerSentEvents("/api/agent", () => ({
226 body: { sessionId },
227 })),
228 threadId: "support-chat",
229 onCustomEvent: (name, value) => {
230 if (
231 name === "opencode.session-id" &&
232 typeof value === "object" &&
233 value !== null &&
234 "sessionId" in value &&
235 typeof value.sessionId === "string"
236 ) {
237 setSessionId(value.sessionId);
238 }
239 },
240 });
242```
243​
244- On a resumed session, the adapter sends only the latest user message. The agent already has the rest.
245- OpenCode saves the session inside the sandbox. Resume works only when the next call runs in the same sandbox. See [Lifecycle & Snapshots](../sandbox/lifecycle).
246​
247## Give the agent your own tools
248​
249The agent has its own tools for files and the shell. It cannot reach your database or your secrets. Pass your server tools to `chat()`, and the adapter bridges them into the sandbox:
250​
251```ts group=tools
252import { z } from "zod";
253import { chat, toolDefinition } from "@tanstack/ai";
254import { opencodeText } from "@tanstack/ai-opencode";
255import { withSandbox } from "@tanstack/ai-sandbox";
256import { sandbox } from "./sandbox";
257​
258const lookupTicket = toolDefinition({
259 name: "lookup_ticket",
260 description: "Look up an issue ticket by id",
261 inputSchema: z.object({ ticketId: z.string() }),
262}).server(async ({ ticketId }) => {
263 return { ticketId, status: "open", title: "Crash on startup" };
264});
265​
266const stream = chat({
267 adapter: opencodeText("openai/gpt-5.2"),
268 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
269 threadId: "thread-1",
270 tools: [lookupTicket],
271 middleware: [withSandbox(sandbox)],
272});
273```
274​
275- Each tool runs on your server, with its closures and secrets. The result goes back into the sandbox.
276- OpenCode names the tool `tanstack_lookup_ticket` internally. The adapter removes the prefix, so the events use the name you gave.
277- Your bridged tools always run, in every permission mode.
278- Only server tools work here. A client tool has no server `execute()`, so the agent cannot run it.
279​
280For how the bridge reaches your server from each provider, see [Sandbox Tools](../sandbox/tools).
281​
282## Tool choice
283​
284You want OpenCode to see only one of your tools, or none of them. Pass `toolChoice` to `chat()`:
285​
286```ts group=tools
287const onlyLookup = chat({
288 adapter: opencodeText("openai/gpt-5.2"),
289 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
290 threadId: "thread-1",
291 tools: [lookupTicket],
292 toolChoice: { type: "tool", name: "lookup_ticket" },
293 middleware: [withSandbox(sandbox)],
294});
295```
296​
297`toolChoice` limits only the tools that the adapter bridges into OpenCode. The built-in OpenCode tools (`bash`, `edit`, and the others) always stay on, and OpenCode decides when it calls a tool.
298​
299| Value | What the adapter does |
300| --- | --- |
301| `'auto'` | Bridges all of your tools. |
302| `'none'` | Bridges none of your tools. |
303| `{ type: 'tool', name }` | Bridges only the named tool. OpenCode does not have to call it. |
304| `'required'` | Bridges all of your tools. OpenCode does not have to call one. |
305​
306Each value except `'auto'` logs a warning the first time an adapter instance gets it.
307​
308For the values on other adapters, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
309​
310## Structured output
311​
312You want a typed report after the agent reads the repo. Pass `outputSchema` on the same `chat()` call:
313​
314```ts
315import { chat } from "@tanstack/ai";
316import { opencodeText } from "@tanstack/ai-opencode";
317import { withSandbox } from "@tanstack/ai-sandbox";
318import { z } from "zod";
319import { sandbox } from "./sandbox";
320​
321const Report = z.object({
322 summary: z.string(),
323 filesChanged: z.array(z.string()),
324});
325​
326const report = await chat({
327 adapter: opencodeText("openai/gpt-5.2"),
328 messages: [{ role: "user", content: "Review this repo." }],
329 threadId: "thread-1",
330 outputSchema: Report,
331 middleware: [withSandbox(sandbox)],
332});
333​
334console.log(report.summary);
335```
336​
337On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
338​
339```tsx
340import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
341import { z } from "zod";
342​
343const Report = z.object({
344 summary: z.string(),
345 filesChanged: z.array(z.string()),
346});
347​
348export function ReportView() {
349 const { final, isLoading } = useChat({
350 connection: fetchServerSentEvents("/api/repo-report"),
351 threadId: "support-chat",
352 outputSchema: Report,
353 });
354​
355 if (isLoading) return <p>The agent is inspecting the repo.</p>;
356 if (!final) return null;
357 return <p>{final.summary}</p>;
359```
360​
361- OpenCode has no schema flag. The adapter adds the JSON Schema to the prompt.
362- The adapter parses the last assistant text as JSON. It removes markdown fences first.
363- Tool activity still streams. The object arrives as `structured-output.complete`.
364​
365Do you only need JSON from a prompt, with no repo? Use a model adapter such as `@tanstack/ai-openai`. For the full walkthrough, see [Harness Agents](../structured-outputs/harnesses).
366​
367## Models and options
368​
369### Models
370​
371| Model | Reasoning levels | What `reasoning` sets |
372| --- | --- | --- |
373| `anthropic/claude-opus-4-5` | `low`, `medium`, `high` | `thinking` with a token budget |
374| `anthropic/claude-sonnet-4-5`, `opencode/claude-sonnet-4-5` | `off`, `minimal`, `low`, `medium`, `high` | `thinking` with a token budget |
375| `openai/gpt-5.2` | `off`, `low`, `medium`, `high`, `xhigh` | `reasoningEffort` |
376| `openai/gpt-5.1-codex`, `opencode/gpt-5.1-codex` | `low`, `medium`, `high` | `reasoningEffort` |
377| `google/gemini-3-pro-preview` | none | none |
378​
379The package exports this list as `OPENCODE_MODELS`. The adapter also takes any other `provider/model` id that your OpenCode providers support.
380​
381### Reasoning
382​
383Set `reasoning` on `chat()`. The adapter writes it into the `options` of the model in the OpenCode server config:
384​
385```ts
386import { chat } from "@tanstack/ai";
387import { opencodeText } from "@tanstack/ai-opencode";
388import { withSandbox } from "@tanstack/ai-sandbox";
389import { sandbox } from "./sandbox";
390​
391const stream = chat({
392 adapter: opencodeText("anthropic/claude-sonnet-4-5"),
393 messages: [{ role: "user", content: "Refactor the auth module" }],
394 threadId: "thread-1",
395 reasoning: { level: "high", budgetTokens: 8000 },
396 middleware: [withSandbox(sandbox)],
397});
398```
399​
400- Claude models get `thinking` with a token budget. `off` turns thinking off.
401- The other models get `reasoningEffort`, plus `reasoningSummary: "auto"` when the summary is on.
402​
403See [Reasoning](../chat/reasoning).
404​
405### Adapter options
406​
407Pass these as the second argument of `opencodeText`:
408​
409| Option | What it does |
410| --- | --- |
411| `directory` | The working directory inside the sandbox. Default `/workspace`. |
412| `port` | The port of `opencode serve` inside the sandbox. Default `4096`. On Docker, publish it with `publishPorts`. |
413| `hostname` | The hostname that the server binds in the sandbox. Default `0.0.0.0`. |
414| `permissionMode` | `'default'` (default), `'acceptEdits'`, or `'bypassPermissions'`. See [Permissions](#permissions). |
415| `onPermissionRequest` | Your own permission handler. It replaces the default policy. |
416​
417### Per-call options
418​
419Pass these in `modelOptions` on `chat()`:
420​
421- `sessionId`: resume a session. See [Resume a session](#resume-a-session).
422- `permissionMode`: the permission mode for this call.
423- `directory`: the working directory for this call.
424​
425## Advanced
426​
427### Ports on other providers
428​
429The host connects to `opencode serve` over HTTP, so the sandbox must expose the port:
430​
431- Docker: pass `publishPorts: [4096]` to `dockerSandbox()`.
432- Vercel: expose the port with the `ports` option of the provider.
433- Local-process and Daytona: nothing to do.
434​
435### No run journal
436​
437OpenCode does not write NDJSON to stdout, so this adapter writes no run journal, also on a durable run. See [Harnesses](../sandbox/harnesses#harness-output-can-go-to-a-journal).
438​
439### Limitations
440​
441- **A sandbox is required.** Every call needs `withSandbox(...)`.
442- **The agent owns the loop.** TanStack agent-loop strategies and per-iteration middleware do not apply inside a turn.
443- **No sampling options.** Options such as `temperature` do not exist here.
444- **Sessions stay in the sandbox.** Resume needs the same sandbox.
445- **Cold starts.** Each call starts the OpenCode server in the sandbox and stops it after the turn. So the first token arrives later than with an HTTP adapter.
446- **No `wrapFetch`.** This adapter ignores [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call), because the OpenCode server sends the model requests.
447​
448### Example apps
449​
450- [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare): a coding agent at the edge, with session resume, the tool timeline, and tool bridging.
451- [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web): Claude Code on Docker, with durable runs that continue after a page refresh. To use OpenCode there, change the adapter in `src/sandbox-agent.ts`.