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

opencode.md

263 lines11.6 KB

1---
2title: OpenCode
3id: opencode-adapter
4order: 14
5description: "Use OpenCode as a chat backend in TanStack AI — agent harness with local tool execution, token-level streaming, stateful sessions, and tool bridging via @tanstack/ai-opencode."
6keywords:
7 - tanstack ai
8 - opencode
9 - opencode sdk
10 - harness
11 - agent
12 - coding agent
13 - adapter
14---
15​
16The OpenCode adapter runs [OpenCode](https://opencode.ai) as a chat backend, driving it over its local HTTP server (`@opencode-ai/sdk`). Unlike HTTP provider adapters, this is a **harness adapter**: OpenCode runs its own agent loop and executes its own tools — shell commands, file reads and edits, search — locally on your server. Each `chat()` call runs one full harness turn; assistant text and reasoning stream as true token-level deltas, and the harness's tool activity streams back as already-resolved tool-call events your UI can render.
17​
18> **Server-only.** The adapter spawns (or attaches to) an `opencode serve` process, so it only works in a Node.js server environment — never in the browser. Treat it like giving OpenCode a shell on the machine it runs on, and configure permissions accordingly.
19​
20## Installation
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24react: @tanstack/ai-opencode
25vue: @tanstack/ai-opencode
26solid: @tanstack/ai-opencode
27svelte: @tanstack/ai-opencode
28preact: @tanstack/ai-opencode
29angular: @tanstack/ai-opencode
30vanilla: @tanstack/ai-opencode
31octane: @tanstack/ai-opencode
32​
33<!-- ::end:tabs -->
34​
35The `opencode` CLI must be installed and its providers authenticated on the host:
36​
37<!-- ::start:tabs variant="package-manager" mode="custom" -->
38​
39react: install -g opencode-ai
40vue: install -g opencode-ai
41solid: install -g opencode-ai
42svelte: install -g opencode-ai
43preact: install -g opencode-ai
44angular: install -g opencode-ai
45vanilla: install -g opencode-ai
46octane: install -g opencode-ai
47​
48<!-- ::end:tabs -->
49​
50Then authenticate:
51​
52```bash
53opencode auth login
54```
55​
56A runnable demo lives at [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare) — pick Claude Code, Codex, or Grok Build in the UI, with session resume, the harness tool timeline, and tool bridging, wired into a TanStack Start app on Workers. For the same wiring on plain Node with durable, refresh-surviving runs (Claude Code on Docker), see [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web) — swapping in this adapter is a one-line change (`src/sandbox-agent.ts`).
57​
58## Models
59​
60OpenCode is provider-agnostic: it resolves any `provider/model` id its configured providers support. Address models as `provider/model` (the adapter splits on the first `/`):
61​
62```typescript
63import { chat } from "@tanstack/ai";
64import { opencodeText } from "@tanstack/ai-opencode";
65​
66const stream = chat({
67 adapter: opencodeText("anthropic/claude-sonnet-4-5", {
68 directory: "/path/to/project",
69 permissionMode: "acceptEdits",
70 }),
71 messages: [{ role: "user", content: "Fix the failing test in utils.test.ts" }],
72});
73```
74​
75## Configuration
76​
77| Option | Description |
78| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
79| `directory` | Working directory for the harness session. Defaults to `process.cwd()`. |
80| `baseUrl` | Attach to an already-running `opencode serve` (e.g. `http://127.0.0.1:4096`) instead of spawning a new server per turn. |
81| `hostname` | Hostname for the spawned server. Defaults to the SDK default (`127.0.0.1`). |
82| `port` | Port for the spawned server. Defaults to the SDK default (`4096`). |
83| `permissionMode` | `'default'` (bridged tools run, everything else that prompts is rejected), `'acceptEdits'` (also auto-approves file edits), or `'bypassPermissions'` (allow all). |
84| `onPermissionRequest` | Custom permission handler; replaces the default policy entirely. |
85| `config` | Extra OpenCode config merged with the adapter's MCP and permission config. |
86​
87Per-call overrides — `sessionId`, `permissionMode`, `directory` — go through `modelOptions`.
88​
89## Permissions
90​
91OpenCode asks for permission before mutating files or running commands. A headless server has no one to answer those prompts, so the adapter applies a policy automatically — it never hangs a turn:
92​
93- **`'default'`** — bridged TanStack tools run; anything else that would prompt (edits, shell, web fetch) is rejected.
94- **`'acceptEdits'`** — additionally auto-approves file-mutation requests (edit / write / patch).
95- **`'bypassPermissions'`** — approves everything. Only use this against a sandbox or scratch directory.
96​
97Provide `onPermissionRequest` to implement your own policy (e.g. allow-list specific commands).
98​
99## Stateful Sessions
100​
101OpenCode sessions are stateful — the harness keeps the full working context (files read, commands run, conclusions reached) between turns. The adapter surfaces the session id of every fresh run as a custom stream event named `opencode.session-id`; thread it back via `modelOptions.sessionId` to resume. When resuming, only the latest user message is sent — the harness already holds the prior context.
102​
103Server endpoint:
104​
105```typescript
106import {
107 chat,
108 chatParamsFromRequest,
109 toServerSentEventsResponse,
110} from "@tanstack/ai";
111import { opencodeText } from "@tanstack/ai-opencode";
112​
113export async function POST(request: Request) {
114 const params = await chatParamsFromRequest(request);
115​
116 // Extra fields the client puts in the connection `body` arrive here.
117 const sessionId =
118 typeof params.forwardedProps.sessionId === "string"
119 ? params.forwardedProps.sessionId
120 : undefined;
121​
122 const stream = chat({
123 adapter: opencodeText("anthropic/claude-sonnet-4-5", {
124 directory: "/path/to/project",
125 permissionMode: "acceptEdits",
126 }),
127 messages: params.messages,
128 modelOptions: { sessionId },
129 });
130​
131 return toServerSentEventsResponse(stream);
133```
134​
135Client (React) — capture the session id from the custom event and send it back on subsequent requests:
136​
137```typescript
138import { useState } from "react";
139import { useChat } from "@tanstack/ai-react";
140import { fetchServerSentEvents } from "@tanstack/ai-client";
141​
142function CodingAssistant() {
143 const [sessionId, setSessionId] = useState<string | undefined>(undefined);
144​
145 const { messages, sendMessage } = useChat({
146 connection: fetchServerSentEvents("/api/chat", () => ({
147 body: { sessionId },
148 })),
149 onCustomEvent: (name, value) => {
150 if (
151 name === "opencode.session-id" &&
152 typeof value === "object" &&
153 value !== null &&
154 "sessionId" in value &&
155 typeof value.sessionId === "string"
156 ) {
157 setSessionId(value.sessionId);
158 }
159 },
160 });
161​
162 // ... render messages; harness tool activity (bash, edit, read, ...)
163 // arrives as regular tool-call parts with results.
165```
166​
167Sessions live on the server that ran them, so resuming only works against the same server instance (or a shared `baseUrl`).
168​
169## Tools
170​
171Two kinds of tools flow through this adapter:
172​
1731. **Built-in harness tools** are executed by OpenCode itself and stream back as tool-call events with results already attached: `bash`, `edit`, `write`, `read`, `grep`, and the agent's running todo plan (surfaced as an `opencode.todo` custom event). Your code never executes them.
174​
1752. **Your TanStack tools** are bridged *into* the harness: the adapter starts a short-lived Streamable-HTTP MCP server on `127.0.0.1` for the duration of the turn and registers it with OpenCode. Define tools as usual with `toolDefinition().server()`; tool-call events come back under the names you registered (OpenCode prefixes MCP tools `tanstack_…` internally, which the adapter strips).
176​
177```typescript
178import { z } from "zod";
179import { chat, toolDefinition } from "@tanstack/ai";
180import { opencodeText } from "@tanstack/ai-opencode";
181​
182const lookupTicket = toolDefinition({
183 name: "lookup_ticket",
184 description: "Look up an issue ticket by id",
185 inputSchema: z.object({ ticketId: z.string() }),
186}).server(async ({ ticketId }) => {
187 return { ticketId, status: "open", title: "Crash on startup" };
188});
189​
190const stream = chat({
191 adapter: opencodeText("anthropic/claude-sonnet-4-5"),
192 messages: [{ role: "user", content: "What's the status of ticket T-123?" }],
193 tools: [lookupTicket],
194});
195```
196​
197**Client-side and approval-gated tools are not supported.** The harness executes tools inside a live process, which cannot pause across HTTP requests to wait for a browser round-trip or a human approval. Passing a tool without a server `execute()` implementation — or one marked `needsApproval` — fails fast with a descriptive error. Run those tools outside the harness with a regular provider adapter.
198​
199## Structured Output
200​
201Pass `outputSchema` on `chat()`. OpenCode has no native schema flag. The adapter adds the JSON Schema to the prompt and parses the last assistant text (markdown fences are stripped). Tool activity still streams. The object arrives as `structured-output.complete`.
202​
203```ts
204import { chat } from "@tanstack/ai"
205import { opencodeText } from "@tanstack/ai-opencode"
206import { defineSandbox, withSandbox } from "@tanstack/ai-sandbox"
207import { dockerSandbox } from "@tanstack/ai-sandbox-docker"
208import { z } from "zod"
209​
210const Report = z.object({
211 summary: z.string(),
212 filesChanged: z.array(z.string()),
213})
214​
215const sandbox = defineSandbox({
216 id: "repo-report",
217 provider: dockerSandbox({ image: "node:22" }),
218})
219​
220const report = await chat({
221 adapter: opencodeText("anthropic/claude-opus-4-5"),
222 messages: [{ role: "user", content: "Review this repo." }],
223 outputSchema: Report,
224 middleware: [withSandbox(sandbox)],
225})
226​
227report.summary
228```
229​
230This path parses JSON from the last assistant message. If extract-only is the job, use a model adapter such as `@tanstack/ai-openai`.
231​
232On the client, pass the same schema to `useChat` and read `final`. `partial` stays empty until the end.
233​
234```tsx
235import { fetchServerSentEvents, useChat } from "@tanstack/ai-react"
236import { z } from "zod"
237​
238const Report = z.object({
239 summary: z.string(),
240 filesChanged: z.array(z.string()),
241})
242​
243function ReportView() {
244 const { final, isLoading } = useChat({
245 connection: fetchServerSentEvents("/api/repo-report"),
246 outputSchema: Report,
247 })
248​
249 if (isLoading) return <p>The agent is inspecting the repo.</p>
250 if (!final) return null
251 return <p>{final.summary}</p>
253```
254​
255Full walkthrough, including the client: [Harness Agents](../structured-outputs/harnesses).
256​
257## Limitations
258​
259- **Server-only (Node).** The adapter spawns or attaches to an `opencode serve` process.
260- **The harness owns the agent loop.** TanStack's agent-loop strategies and per-iteration middleware don't apply inside a harness turn.
261- **No sampling controls.** `temperature`-style options don't exist here.
262- **Sessions are server-local.** Resume requires hitting the same server instance (or a shared `baseUrl`).
263- **Cold starts.** Spawning a server per turn adds first-token latency; point the adapter at a long-lived `baseUrl` to avoid it.