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

acp-compatible.md

467 lines19.3 KB

1---
2title: ACP-Compatible Harness
3id: acp-compatible-harness
4description: "Run any coding agent that speaks the Agent Client Protocol (ACP) inside a TanStack AI sandbox, with one generic harness adapter and no dedicated package."
5keywords:
6 - tanstack ai
7 - acp
8 - agent client protocol
9 - coding agent
10 - harness
11 - sandbox
12 - custom adapter
13---
14​
15`acpCompatible` builds a `chat()` adapter for an ACP agent CLI that has no `@tanstack/ai-*` package. You pass the start command. The adapter runs the agent in a sandbox.
16​
17It is the harness version of the [OpenAI-Compatible adapter](./openai-compatible). Does a dedicated harness adapter exist for your agent, such as [Grok Build](./grok-build)? Use that one. It knows the models and the special behavior of its agent.
18​
19You need:
20​
21- A sandbox provider. The samples use Docker, so Docker must run on your machine.
22- An agent CLI that runs an ACP server over stdio, installed inside the sandbox. The samples use the `grok` CLI.
23- The API key of that agent, or a CLI login on the machine.
24​
25## 1. Install
26​
27<!-- ::start:tabs variant="package-manager" mode="install" -->
28​
29react: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
30vue: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
31solid: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
32svelte: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
33preact: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
34angular: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
35vanilla: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
36octane: @tanstack/ai @tanstack/ai-acp @tanstack/ai-sandbox @tanstack/ai-sandbox-docker @tanstack/ai-grok-build
37​
38<!-- ::end:tabs -->
39​
40The samples import `GROK_CLI_INSTALL_COMMAND` from `@tanstack/ai-grok-build`, to install the `grok` CLI in the sandbox. For another agent, use its own install command and skip that package.
41​
42## 2. Set the API key
43​
44Put the key of your agent in the environment of your server. For the `grok` CLI:
45​
46```bash
47XAI_API_KEY=xai-...
48```
49​
50The sandbox in step 3 gives this key to the agent as a workspace secret. Then the adapter signs in through ACP `authenticate`, with the auth method that you name in `authMethodId`. For Grok, it is `xai.api_key`.
51​
52Did the machine already log in to the agent CLI? Set `authMode: 'host'`. The adapter then skips ACP `authenticate`. See [Harness Auth](../sandbox/auth).
53​
54## 3. Run the agent from the server
55​
56Define the sandbox once. It clones your repo into a Docker container and installs the agent CLI:
57​
58```ts
59// sandbox.ts
60import { GROK_CLI_INSTALL_COMMAND } from "@tanstack/ai-grok-build";
61import {
62 createSecrets,
63 defineSandbox,
64 defineWorkspace,
65 githubRepo,
66} from "@tanstack/ai-sandbox";
67import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
68​
69export const sandbox = defineSandbox({
70 id: "acp-agent",
71 provider: dockerSandbox({ image: "node:22" }),
72 workspace: defineWorkspace({
73 source: githubRepo({ repo: "owner/app" }),
74 setup: [GROK_CLI_INSTALL_COMMAND],
75 secrets: createSecrets({
76 XAI_API_KEY: process.env.XAI_API_KEY ?? "",
77 }),
78 }),
79});
80```
81​
82Then build the adapter with `acpCompatibleText` and pass it to `chat()`. `command` returns the shell command that starts the ACP server of the agent over stdio:
83​
84```ts
85// api/agent.ts
86import {
87 chat,
88 chatParamsFromRequest,
89 toServerSentEventsResponse,
90} from "@tanstack/ai";
91import { acpCompatibleText } from "@tanstack/ai-acp";
92import { withSandbox } from "@tanstack/ai-sandbox";
93import { sandbox } from "./sandbox";
94​
95export async function POST(request: Request) {
96 const { messages, threadId, runId } = await chatParamsFromRequest(request);
97​
98 const stream = chat({
99 adapter: acpCompatibleText("composer-2.5", {
100 name: "acp",
101 command: ({ model }) => `grok agent -m '${model}' --always-approve stdio`,
102 authMethodId: "xai.api_key",
103 }),
104 messages,
105 threadId,
106 runId,
107 middleware: [withSandbox(sandbox)],
108 });
109​
110 return toServerSentEventsResponse(stream);
112```
113​
114Replace `owner/app` with your repo.
115​
116## 4. Render the agent's work
117​
118The client is the same as for any chat. Render the text, and show each tool that the agent ran:
119​
120```tsx
121import { useState } from "react";
122import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
123​
124export function CodingAgent() {
125 const [input, setInput] = useState("");
126 const { messages, sendMessage } = useChat({
127 connection: fetchServerSentEvents("/api/agent"),
128 threadId: "support-chat",
129 });
130​
131 return (
132 <form
133 onSubmit={(event) => {
134 event.preventDefault();
135 sendMessage(input);
136 setInput("");
137 }}
138 >
139 {messages.map((message) =>
140 message.parts.map((part, index) => {
141 if (part.type === "text") {
142 return <p key={`${message.id}-${index}`}>{part.content}</p>;
143 }
144 if (part.type === "tool-call") {
145 return <code key={part.id}>{part.name}</code>;
146 }
147 return null;
148 }),
149 )}
150 <input value={input} onChange={(event) => setInput(event.target.value)} />
151 </form>
152 );
154```
155​
156Ask it "Fix the failing test in utils.test.ts". You see the agent's text, plus a line for each tool it used. The agent edited the files inside the container.
157​
158## How it works
159​
160`acpCompatible` gives you the full ACP flow:
161​
162- It finds the sandbox from `withSandbox(...)` and starts the agent there.
163- It bridges your `chat()` tools into the agent over MCP.
164- It handles session resume, permission requests, and abort.
165- It turns the ACP updates of the agent into `chat()` stream chunks.
166​
167## Configure an agent once
168​
169For more than one model, configure the agent once with `acpCompatible`. You get a factory. Then pick the model on each call:
170​
171```ts
172// pi-harness.ts
173import { acpCompatible } from "@tanstack/ai-acp";
174​
175export const pi = acpCompatible({
176 name: "pi",
177 models: ["pi-fast", "pi-pro"],
178 modelOptions: {} as { reasoningEffort?: "low" | "high" },
179 command: ({ model, harnessCwd, modelOptions }) =>
180 `pi --acp -m ${model} --cwd ${harnessCwd}` +
181 (modelOptions?.reasoningEffort
182 ? ` --effort ${modelOptions.reasoningEffort}`
183 : ""),
184 authMethodId: "pi-api-key",
185 refusalMessage: "Pi refused the request.",
186});
187```
188​
189```ts
190import { chat } from "@tanstack/ai";
191import { withSandbox } from "@tanstack/ai-sandbox";
192import { pi } from "./pi-harness";
193import { sandbox } from "./sandbox";
194​
195const stream = chat({
196 adapter: pi("pi-pro"),
197 modelOptions: { reasoningEffort: "high" },
198 messages: [{ role: "user", content: "Fix the failing test." }],
199 threadId: "thread-1",
200 middleware: [withSandbox(sandbox)],
201});
202```
203​
204- `models` makes the factory type-safe. `pi("pi-ultra")` is a type error. Without `models`, the factory takes any string.
205- `modelOptions` is a type-only brand. The value `{} as { ... }` is not used at run time. It types what `chat({ modelOptions })` takes.
206- Your declared options join the base options. `command` and `openTransport` get them as `ctx.modelOptions`, so you can turn them into CLI flags.
207- The base options are always there: `sessionId`, `cwd`, `authMode`, `authMethodId`, and `permissionMode`.
208​
209## Permissions
210​
211Inside a sandbox, the sandbox is the security boundary. So by default, the adapter answers each permission request of the agent with `permissionMode: 'bypassPermissions'`. The agent edits files and runs commands with no prompt.
212​
213To send tool approvals to a client, switch to `'interactive'`:
214​
215```ts
216import { acpCompatible } from "@tanstack/ai-acp";
217​
218export const pi = acpCompatible({
219 name: "pi",
220 command: ({ model }) => `pi --acp -m ${model}`,
221 permissions: "interactive", // send approval-requested events for `ask` prompts
222 permissionMode: "acceptEdits", // still allow file edits with no prompt
223});
224```
225​
226- With `'interactive'`, an `ask` prompt sends an approval-requested event. The client approves, then runs the turn again.
227- Your `chat()` tools that the adapter bridges into the agent are always allowed, in every mode.
228- To write your own rules, pass `onPermissionRequest`. It overrides `permissions` and `permissionMode`.
229​
230## Tool choice
231​
232You want the agent to see only one of your tools, or none of them. Pass `toolChoice` to `chat()`. It limits only the tools that the adapter bridges into the agent. ACP has no field to turn off the built-in tools of the agent or to force a tool call. So the agent decides when it calls a tool.
233​
234| Value | What the adapter does |
235| --- | --- |
236| `'auto'` | Bridges all of your tools. |
237| `'none'` | Bridges none of your tools. |
238| `{ type: 'tool', name }` | Bridges only the named tool. The agent does not have to call it. |
239| `'required'` | Bridges all of your tools. The agent does not have to call one. |
240​
241Each value except `'auto'` logs a warning the first time an adapter instance gets it. The warning starts with the harness `name`, for example `pi:`.
242​
243For the values on other adapters, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
244​
245## Session resume
246​
247On each run, the adapter sends the session id of the agent as a custom event named `<name>.session-id`, for example `pi.session-id`. Send the id back in `modelOptions.sessionId` on the next call, and the agent continues the session:
248​
249```ts
250import {
251 chat,
252 chatParamsFromRequest,
253 toServerSentEventsResponse,
254} from "@tanstack/ai";
255import { withSandbox } from "@tanstack/ai-sandbox";
256import { pi } from "./pi-harness";
257import { sandbox } from "./sandbox";
258​
259export async function POST(request: Request) {
260 const params = await chatParamsFromRequest(request);
261 const sessionId =
262 typeof params.forwardedProps.sessionId === "string"
263 ? params.forwardedProps.sessionId
264 : undefined;
265​
266 const stream = chat({
267 adapter: pi("pi-fast"),
268 messages: params.messages,
269 threadId: params.threadId,
270 middleware: [withSandbox(sandbox)],
271 modelOptions: { sessionId },
272 });
273​
274 return toServerSentEventsResponse(stream);
276```
277​
278On a resumed session, the adapter sends only the last user message. The agent already has the rest. For the client half, see [Resume a session](./claude-code#resume-a-session) on the Claude Code page. Use your `<name>.session-id` as the event name.
279​
280## Typed output
281​
282You want a typed object after the agent works. Pass `outputSchema` on the same `chat()` call. The agent runs its own tools. Then the adapter adds the schema to the prompt and parses the last assistant text as JSON.
283​
284```ts
285import {
286 chat,
287 chatParamsFromRequest,
288 toServerSentEventsResponse,
289} from "@tanstack/ai";
290import { acpCompatibleText } from "@tanstack/ai-acp";
291import { withSandbox } from "@tanstack/ai-sandbox";
292import { z } from "zod";
293import { sandbox } from "./sandbox";
294​
295const ReportSchema = z.object({
296 name: z.string(),
297 oneLiner: z.string(),
298});
299​
300export async function POST(request: Request) {
301 const { messages, threadId } = await chatParamsFromRequest(request);
302​
303 const stream = chat({
304 adapter: acpCompatibleText("pi-fast", {
305 name: "pi",
306 command: ({ model }) => `pi --acp -m ${model}`,
307 }),
308 messages,
309 threadId,
310 outputSchema: ReportSchema,
311 stream: true,
312 middleware: [withSandbox(sandbox)],
313 });
314​
315 return toServerSentEventsResponse(stream);
317```
318​
319On the client, walk `messages[].parts` for tool calls and reasoning. Read the typed object from the `structured-output` part or from `useChat().final`:
320​
321```tsx
322import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
323import { z } from "zod";
324​
325const ReportSchema = z.object({
326 name: z.string(),
327 oneLiner: z.string(),
328});
329​
330export function Report() {
331 const { messages, final } = useChat({
332 connection: fetchServerSentEvents("/api/report"),
333 threadId: "support-chat",
334 outputSchema: ReportSchema,
335 });
336​
337 return (
338 <>
339 {messages.map((message) =>
340 message.parts.map((part, index) => {
341 if (part.type === "tool-call") {
342 return <p key={part.id}>{part.name}</p>;
343 }
344 if (part.type === "structured-output") {
345 const report = part.data ?? part.partial;
346 return report?.name ? <h2 key={index}>{report.name}</h2> : null;
347 }
348 return null;
349 }),
350 )}
351 {final ? <p>{final.oneLiner}</p> : null}
352 </>
353 );
355```
356​
357You can also read the object from `await chat()` when you do not stream. See [Harness Agents](../structured-outputs/harnesses) for the full part list and the repo-report example.
358​
359## Models and options
360​
361`acpCompatible` has no built-in model list. The model is any string that your agent takes, or one of the `models` that you declare.
362​
363### Configuration
364​
365Pass these to `acpCompatible` or as the second argument of `acpCompatibleText`:
366​
367| Field | What it does |
368| --- | --- |
369| `name` (required) | The harness label, the log prefix, and the name of the `<name>.session-id` custom event. |
370| `command` | Builds the stdio launch command from `{ model, cwd, harnessCwd, sandbox, env, modelOptions, signal }`. Required unless you pass `openTransport`. |
371| `openTransport` | Opens any `AcpSessionTransport` yourself, for example a WebSocket. It overrides `command`. See [WebSocket and custom transports](#websocket-and-custom-transports). |
372| `models` | The model ids that the harness takes. With this list, unknown ids are a type error. |
373| `modelOptions` | Type-only brand for the per-call options of `chat({ modelOptions })`. Declare it with `{} as { ... }`. |
374| `cwd` | The working directory inside the sandbox. Default `/workspace`. |
375| `env` | More environment variables for the agent process. |
376| `authMode` | `'api-key'` (default) uses `authMethodId`. `'host'` skips ACP `authenticate`. See [Harness Auth](../sandbox/auth). |
377| `authMethodId` | The ACP auth method to select before the session starts. Ignored when `authMode` is `'host'`. |
378| `permissionMode` | `'default'`, `'acceptEdits'`, or `'bypassPermissions'` (default). |
379| `permissions` | `'headless'` (default) answers each request. `'interactive'` sends approval-requested events for `ask` prompts. |
380| `onPermissionRequest` | Your own permission handler. It overrides `permissions` and `permissionMode`. |
381​
382More options, for special cases:
383​
384| Field | What it does |
385| --- | --- |
386| `skillsDir` | The skills directory of the agent, relative to the workspace root, for example `'.pi/skills'`. Workspace `gitSkill`s are linked here. Without it, they stay unlinked and the adapter logs a warning. |
387| `refusalMessage` | The `RUN_ERROR` message when the agent refuses a request. |
388| `planEventName` | Send ACP `plan` updates as a custom event with this name. |
389| `emitDiff` | Send the `git diff` of `cwd` after the run as a `file.changed` custom event. Off by default. Needs a git repo at `cwd`. |
390| `onExtNotification` | Handles vendor `_x/...` JSON-RPC notifications. It must not throw. |
391| `buildPrompt` | Changes how the chat history becomes the prompt of the agent. |
392​
393This adapter ignores [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call), because the agent process sends the model requests.
394​
395## Advanced
396​
397### WebSocket and custom transports
398​
399Some agents run an ACP server that you reach over WebSocket, not stdio (the `grok agent serve` pattern). Open the transport yourself with `openTransport`. It gets the same context as `command` and returns an `AcpSessionTransport`. Put all teardown in the `dispose` of the transport:
400​
401```ts
402import { acpCompatible, startAcpServerInSandbox } from "@tanstack/ai-acp";
403​
404export const myAgent = acpCompatible({
405 name: "my-agent",
406 openTransport: async ({ sandbox, model, harnessCwd, signal }) => {
407 const server = await startAcpServerInSandbox(sandbox, {
408 port: 9100,
409 cwd: harnessCwd,
410 command: `my-agent serve --bind 0.0.0.0:9100 -m ${model}`,
411 readyMarker: "listening",
412 buildWsUrl: ({ channel, port }) =>
413 `${channel.url.replace(/^http/i, "ws")}:${port}`,
414 ...(signal ? { signal } : {}),
415 });
416 const ws = await server.connect(signal);
417 return {
418 kind: "stream",
419 stream: ws.stream,
420 dispose: async () => {
421 ws.close();
422 await server.dispose();
423 },
424 };
425 },
426});
427```
428​
429### Workspace skills
430​
431When you set up a [workspace](../sandbox/workspace) with `withSandbox`, `acpCompatible` puts its skills where the agent expects them:
432​
433| Workspace input | What `acpCompatible` does |
434| --- | --- |
435| `mcpSkill(name, config)` | Passes the server to the agent over ACP, in the `mcpServers` of `newSession`, with secrets and bearer headers resolved. No config file is needed. |
436| `gitSkill({ repo })` | Clones the repo during bootstrap, then links it into your [`skillsDir`](#configuration). Without `skillsDir`, it stays unlinked and the adapter logs a warning. |
437| `fileSkill({ path, content })` | Writes the file into the workspace root during bootstrap. |
438| `instructions` | Writes them to `AGENTS.md` (and symlinks) during bootstrap. |
439| `agentSkill(name)`, `plugins` | Skipped with a warning, because ACP has no generic way to pass them. Use a `gitSkill` or an MCP server. |
440​
441The workspace `secrets` go into the environment of the agent on create and on resume. They are never saved to snapshots. The agent CLI reads them like any environment variable.
442​
443### Protocol coverage
444​
445`acpCompatible` implements the client side of ACP: enough to drive an agent through a full prompt turn. It is a minimal client that follows the spec. Each part it does not implement is either gated by a capability, so it advertises no support, or a rendering choice.
446​
447It covers:
448​
449- The `initialize` handshake. It sends `clientInfo` and the protocol version, agrees on the version, and advertises capabilities.
450- `authenticate` (when the agent advertises auth methods), `session/new`, `session/load` (resume), `session/prompt`, and `session/cancel`.
451- `session/request_permission` with all four option kinds, mapped by the [permission mode](#permissions).
452- The streamed `session/update`s that carry turn output: `agent_message_chunk`, `agent_thought_chunk` (as reasoning), `tool_call`, `tool_call_update`, and `plan`.
453- All five stop reasons: `end_turn`, `max_tokens`, `max_turn_requests`, `refusal`, and `cancelled`.
454​
455Some output arrives as `CUSTOM` stream events, because the AG-UI chat events have no event for non-text assistant output:
456​
457- `<name>.session-id`: the session id of the agent, for [resume](#session-resume).
458- `<name>.message-content`: non-text agent content (`image`, `audio`, `resource`, or `resource_link` blocks). Its `value` is `{ content: <ACP content block> }`. Non-text tool content (diffs, terminal output, images) stays inside the `TOOL_CALL_RESULT` payload.
459- The plan event, when you set `planEventName`.
460​
461It does not implement:
462​
463- `fs/read_text_file`, `fs/write_text_file`, and `terminal/*`. It advertises them as unsupported. The agent runs inside the sandbox with direct file and shell access, so it never sends these back to the client.
464- Multimodal prompts. Prompts go to the agent as text. Multimodal output of the agent arrives as `message-content`, shown above.
465- Incremental `usage_update` (the final usage of the turn arrives instead), `available_commands_update`, `current_mode_update`, and the experimental features (elicitation, NES, providers, session modes and config).
466​
467To find agents, see the [ACP agents list](https://agentclientprotocol.com/get-started/agents). For how harnesses fit with sandboxes, see [Harnesses](../sandbox/harnesses).