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

harnesses.md

291 lines9.8 KB

1---
2title: Harness Structured Output
3id: structured-outputs-harnesses
4order: 6
5description: "Ask a coding agent in a sandbox to inspect a repo, then read a typed object from chat({ outputSchema }). Works with Claude Code, Codex, OpenCode, Grok Build, and acpCompatible."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - harness
10 - claude code
11 - codex
12 - opencode
13 - grok build
14 - outputSchema
15 - sandbox
16---
17​
18You asked a coding agent to inspect a repository. The agent streams tool calls and prose. You need a typed object you can store or render, not a wall of text to parse.
19​
20Pass `outputSchema` on the same `chat()` call. The harness runs its native tools. Then you get a validated object from `await chat()` or from `useChat().final`.
21​
22This page is for sandbox harness adapters:
23​
24- [Claude Code](../adapters/claude-code)
25- [Codex](../adapters/codex)
26- [OpenCode](../adapters/opencode)
27- [Grok Build](../adapters/grok-build)
28- [ACP-Compatible](../adapters/acp-compatible) (`acpCompatible`)
29​
30If you only extract JSON from a prompt and you do not need a sandbox, use [One-Shot Extraction](./one-shot) with an HTTP adapter.
31​
32## Define the schema
33​
34```typescript group=harness-output
35import { z } from "zod";
36​
37export const ReportSchema = z.object({
38 name: z.string(),
39 oneLiner: z.string(),
40 audience: z.string(),
41 mainPackages: z.array(
42 z.object({
43 name: z.string(),
44 role: z.string(),
45 }),
46 ),
47 howToRun: z.string(),
48});
49```
50​
51The return type follows from the schema. You do not need a cast.
52​
53## Server: sandbox plus outputSchema
54​
55The harness needs a sandbox. Pass `withSandbox(...)`. If the client reads the stream, pass `stream: true`. Without `stream: true`, `chat()` returns a `Promise`, not SSE.
56​
57```typescript group=harness-output
58import { chat, toServerSentEventsResponse } from "@tanstack/ai";
59import { claudeCodeText } from "@tanstack/ai-claude-code";
60import {
61 defineSandbox,
62 defineWorkspace,
63 githubRepo,
64 withSandbox,
65} from "@tanstack/ai-sandbox";
66import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
67​
68const sandbox = defineSandbox({
69 id: "repo-report",
70 provider: dockerSandbox({ image: "node:22" }),
71 workspace: defineWorkspace({
72 source: githubRepo({ repo: "TanStack/ai" }),
73 }),
74});
75​
76export async function POST(request: Request) {
77 const body: unknown = await request.json();
78 const messages =
79 typeof body === "object" &&
80 body !== null &&
81 "messages" in body &&
82 Array.isArray(body.messages)
83 ? body.messages
84 : [];
85​
86 const stream = chat({
87 adapter: claudeCodeText("claude-opus-4-8"),
88 messages,
89 outputSchema: ReportSchema,
90 stream: true,
91 middleware: [withSandbox(sandbox)],
92 });
93​
94 return toServerSentEventsResponse(stream);
96```
97​
98Swap the adapter to change the agent:
99​
100- `codexText("gpt-5.3-codex")`
101- `opencodeText("anthropic/claude-opus-4-5")`
102- `grokBuildText("composer-2.5")`
103- `acpCompatibleText(...)` for any ACP CLI. See [ACP-Compatible](../adapters/acp-compatible).
104​
105The typed object arrives as a `structured-output.complete` event. Tool activity streams first.
106​
107## Client: read `parts` and `final`
108​
109The assistant message holds the live run. Walk `messages[].parts` for tool calls, reasoning, and the typed object. `useChat().final` is a shortcut for the latest `structured-output` part.
110​
111```tsx group=harness-output
112import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
113​
114function RepoReport() {
115 const { messages, sendMessage, isLoading, final } = useChat({
116 connection: fetchServerSentEvents("/api/repo-report"),
117 outputSchema: ReportSchema,
118 });
119​
120 return (
121 <>
122 <button
123 disabled={isLoading}
124 onClick={() => sendMessage("What is this repository about?")}
125 >
126 Run report
127 </button>
128 {messages.map((message) => (
129 <div key={message.id}>
130 {message.parts.map((part, index) => {
131 if (part.type === "thinking") {
132 return <p key={index}>{part.content}</p>;
133 }
134 if (part.type === "tool-call") {
135 return (
136 <p key={part.id}>
137 {part.name} ({part.state})
138 </p>
139 );
140 }
141 if (part.type === "text") {
142 return <p key={index}>{part.content}</p>;
143 }
144 if (part.type === "structured-output") {
145 const report = part.data ?? part.partial;
146 return report?.name ? <h2 key={index}>{report.name}</h2> : null;
147 }
148 return null;
149 })}
150 </div>
151 ))}
152 {final ? <p>{final.oneLiner}</p> : null}
153 </>
154 );
156```
157​
158Each part type:
159​
160- `thinking`: harness reasoning, when the agent emits it
161- `tool-call`: native harness tools such as `Read` or `Bash`
162- `text`: prose the agent writes before the JSON
163- `structured-output`: the schema object. `part.data` is the validated value. `part.partial` is a progressive parse when the adapter streams JSON text. `part.raw` is the source string.
164​
165`final` is typed as the schema. It stays `null` until `structured-output.complete` arrives. It always matches the latest assistant turn. Older turns stay on their own `structured-output` parts.
166​
167`partial` stays empty on harness adapters. The object is not streamed field by field. Render tool calls from `messages` while you wait. See [Streaming UIs](./streaming) for the `partial` / `final` shape.
168​
169## Persist the typed object
170​
171Add `withPersistence` next to `withSandbox`. The engine stores the completed
172structured-output part on the transcript. A new message id keeps harness prose
173and the structured object as two assistant messages. The last text message id
174keeps both on one message. A reload hydrates that transcript through
175`reconstructChat`. See [Chat Persistence](../persistence/chat-persistence).
176​
177```typescript group=harness-persist
178import { chat, toServerSentEventsResponse } from "@tanstack/ai";
179import { claudeCodeText } from "@tanstack/ai-claude-code";
180import { withPersistence } from "@tanstack/ai-persistence";
181import {
182 defineSandbox,
183 defineWorkspace,
184 githubRepo,
185 withSandbox,
186} from "@tanstack/ai-sandbox";
187import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
188import { persistence } from "./persistence";
189import { z } from "zod";
190​
191const ReportSchema = z.object({
192 name: z.string(),
193 oneLiner: z.string(),
194});
195​
196const sandbox = defineSandbox({
197 id: "repo-report",
198 provider: dockerSandbox({ image: "node:22" }),
199 workspace: defineWorkspace({
200 source: githubRepo({ repo: "TanStack/ai" }),
201 }),
202});
203​
204export async function POST(request: Request) {
205 const body: unknown = await request.json();
206 const messages =
207 typeof body === "object" &&
208 body !== null &&
209 "messages" in body &&
210 Array.isArray(body.messages)
211 ? body.messages
212 : [];
213 const threadId =
214 typeof body === "object" &&
215 body !== null &&
216 "threadId" in body &&
217 typeof body.threadId === "string"
218 ? body.threadId
219 : undefined;
220 const runId =
221 typeof body === "object" &&
222 body !== null &&
223 "runId" in body &&
224 typeof body.runId === "string"
225 ? body.runId
226 : undefined;
227​
228 const stream = chat({
229 adapter: claudeCodeText("claude-opus-4-8"),
230 messages,
231 outputSchema: ReportSchema,
232 stream: true,
233 threadId,
234 runId,
235 middleware: [withSandbox(sandbox), withPersistence(persistence)],
236 });
237​
238 return toServerSentEventsResponse(stream);
240```
241​
242## How each harness applies the schema
243​
244| Adapter | How the schema is applied |
245|---|---|
246| Claude Code | Native `--json-schema` flag on the same turn. The value is inline JSON, not a file path. |
247| Codex | Native `--output-schema` flag on the same turn. Assistant text streams as Codex writes it. The last message is also the schema object. |
248| OpenCode | Schema is added to the prompt. The adapter parses the last assistant text. |
249| Grok Build | Schema is added to the prompt. The adapter parses the last assistant text. |
250| ACP compatible | Schema is added to the prompt. The adapter parses the last assistant text. |
251​
252OpenCode, Grok Build, and `acpCompatible` parse JSON from the last assistant message. That parse fails if the message is not JSON. If the job is extract-only and you do not need a sandbox, use `@tanstack/ai-openai` or `@tanstack/ai-grok`.
253​
254## Approval gates and client tools
255​
256Harness adapters run tools inside the sandbox. They do not pause for a browser round-trip.
257​
258- A tool without a server `execute()` fails fast.
259- A tool with `needsApproval` fails fast.
260​
261If you need approval gates or client tools, use [With Tools](./with-tools) with an HTTP adapter.
262​
263## Script without a UI
264​
265If you do not stream to a browser, omit `stream: true`. The promise resolves with the typed object.
266​
267```typescript group=harness-output
268const report = await chat({
269 adapter: claudeCodeText("claude-opus-4-8"),
270 messages: [{ role: "user", content: "What is this repository about?" }],
271 outputSchema: ReportSchema,
272 middleware: [withSandbox(sandbox)],
273});
274​
275report.name;
276report.oneLiner;
277```
278​
279## Try it
280​
281The React chat example includes a repo-report page.
282​
2831. Open [`examples/ts-react-chat`](https://github.com/TanStack/ai/tree/main/examples/ts-react-chat).
2842. Open `/repo-report`.
2853. Pick Claude Code, Grok Build, ACP compatible, or Codex.
2864. Pick Auth. The default is **API key**. Use **Host login** if the machine already ran `claude login`, `grok login`, or `codex login`.
2875. Run the report. The page renders tool calls and reasoning from `messages[].parts`. It reads the typed object from the `structured-output` part and from `useChat().final`.
288​
289The page clones `TanStack/ai` into a sandbox, asks the agent to inspect it, and shows the validated report.
290​
291Claude Code does not need you to accept a trust dialog for that clone. The adapter loads only user settings, so the clone's `.claude/settings.json` does not block headless `-p`. Host login uses your host `claude login`. The sandbox type does not pick this. See [Harness Auth](../sandbox/auth).