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

compatible.ts

861 lines30.2 KB

1import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
2import {
3 appendOutputSchemaInstruction,
4 parseJsonFromAssistantText,
5 structuredOutputCompleteChunk,
6 structuredOutputStartChunk,
7 toRunErrorRawEvent,
8} from '@tanstack/ai/adapter-internals'
9import { BaseTextAdapter } from '@tanstack/ai/adapters'
10import {
11 DurableAttachNotSupportedError,
12 SandboxCapability,
13 buildApprovalRequestedEvent,
14 createBridgeEventChannel,
15 getSandbox,
16 getSandboxDurability,
17 getToolBridgeProvisioner,
18 getWorkspaceProjection,
19 mergeChunkStreams,
20 nodeHttpBridgeProvisioner,
21 resolveDurableRunId,
22 resolveHarnessCwd,
23} from '@tanstack/ai-sandbox'
24import { AsyncQueue } from '../stream/queue'
25import { startAcpSession } from '../session/acp-client'
26import { translateAcpStream } from '../stream/translate'
27import { resolveInteractivePermission, resolvePermission } from '../permissions'
28import { buildAcpPrompt } from '../messages/prompt'
29import { projectAcpWorkspace, workspaceMcpServers } from './projection'
30import type { AcpMcpServer } from './projection'
31import type { HostToolBridge, SandboxHandle } from '@tanstack/ai-sandbox'
32import type {
33 StructuredOutputOptions,
34 StructuredOutputResult,
35} from '@tanstack/ai/adapters'
36import type {
37 DefaultMessageMetadataByModality,
38 Modality,
39 ModelMessage,
40 AdapterYieldChunk,
41 TextOptions,
42} from '@tanstack/ai'
43import type { AcpSessionHandle } from '../session/acp-client'
44import type { AcpStreamEvent } from '../stream/translate'
45import type { AcpSessionTransport } from '../transport/types'
46import type {
47 AcpPermissionMode,
48 AcpSessionUpdate,
49 PermissionHandler,
50} from '../types/acp-types'
51import type { BuiltAcpPrompt } from '../messages/prompt'
52​
53const DEFAULT_WORKDIR = '/workspace'
54​
55/**
56 * Everything a harness needs to know to launch its ACP server inside the
57 * sandbox. Passed to {@link AcpCompatibleConfig.command} /
58 * {@link AcpCompatibleConfig.openTransport}.
59 */
60export interface AcpHarnessContext<
61 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
62> {
63 /** The sandbox the harness runs in (from `withSandbox(...)` middleware). */
64 sandbox: SandboxHandle
65 /** The selected model id. */
66 model: string
67 /** Virtual cwd for `sandbox.process.spawn` (the provider maps `/workspace`). */
68 cwd: string
69 /** Literal cwd for the harness's own `--cwd` flag / ACP `newSession`. */
70 harnessCwd: string
71 /** Extra env vars configured for the harness process. */
72 env: Record<string, string> | undefined
73 /**
74 * Per-call options from `chat({ modelOptions })` — the base ACP options plus
75 * whatever you declared via {@link AcpCompatibleConfig.modelOptions}. Read
76 * these to turn options into CLI flags / transport choices.
77 */
78 modelOptions: TModelOptions | undefined
79 /** Abort signal for the run, when one was provided. */
80 signal: AbortSignal | undefined
82​
83/** Union of selectable model names from a `models` tuple (any string if omitted). */
84export type AcpModelNameOf<TModels extends ReadonlyArray<string>> =
85 TModels[number]
86​
87export interface AcpCompatibleConfig<
88 TModels extends ReadonlyArray<string> = ReadonlyArray<string>,
89 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
90> {
91 /**
92 * Harness name. Used as the provider label, the log prefix, and the CUSTOM
93 * session-id event name (`<name>.session-id`).
94 */
95 name: string
96 /**
97 * The models this harness accepts. Declaring them makes the returned factory
98 * type-safe — `harness('known-model')` is checked, unknown ids are rejected.
99 * Omit to accept any string.
100 */
101 models?: TModels
102 /**
103 * Type-only brand for the per-call options accepted via `chat({ modelOptions })`.
104 * Declare your harness's options here with `{} as { ... }` (the value is unused
105 * at runtime); they are merged with the base {@link AcpCompatibleProviderOptions}
106 * and exposed on {@link AcpHarnessContext.modelOptions} so `command` /
107 * `openTransport` can turn them into CLI flags.
108 *
109 * @example modelOptions: {} as { reasoningEffort?: 'low' | 'high' }
110 */
111 modelOptions?: TModelOptions
112 /**
113 * Build the shell command that launches the harness's ACP server over
114 * **stdio** inside the sandbox (e.g. `` `pi --acp -m ${model}` ``). Required
115 * unless {@link openTransport} is provided.
116 */
117 command?: (
118 ctx: AcpHarnessContext<AcpCompatibleProviderOptions & TModelOptions>,
119 ) => string
120 /**
121 * Full transport escape hatch — open any {@link AcpSessionTransport} yourself
122 * (e.g. boot a `serve` process and connect over WebSocket, as Grok Build
123 * does). Overrides {@link command}. Put ALL teardown in the returned
124 * transport's `dispose` (stream) / process (stdio); it is disposed when the
125 * session ends.
126 */
127 openTransport?: (
128 ctx: AcpHarnessContext<AcpCompatibleProviderOptions & TModelOptions>,
129 ) => Promise<AcpSessionTransport> | AcpSessionTransport
130 /** Working directory inside the sandbox. Defaults to `/workspace`. */
131 cwd?: string
132 /**
133 * The harness's skills directory, relative to the workspace root (e.g.
134 * `'.pi/skills'`) — its native convention for where it auto-discovers skills,
135 * the way Claude Code uses `.claude/skills`. When set, `withSandbox` workspace
136 * `gitSkill`s are linked here. MCP skills don't need this: they're passed to
137 * the agent over ACP natively. Omit and `gitSkill`s are left unlinked (warned).
138 */
139 skillsDir?: string
140 /** Extra environment variables for the harness process. */
141 env?: Record<string, string>
142 /**
143 * `'api-key'` (default) uses {@link authMethodId} (or `modelOptions.authMethodId`).
144 * `'host'` skips ACP authenticate (use the CLI login on the machine).
145 * Not inferred from the sandbox.
146 */
147 authMode?: 'host' | 'api-key'
148 /**
149 * ACP auth method to select before the session starts, when the harness
150 * advertises one (e.g. `'pi-api-key'`). Overridable per call via
151 * `modelOptions.authMethodId`. Ignored when {@link authMode} is `'host'`.
152 */
153 authMethodId?: string
154 /** ACP permission policy. Defaults to `'bypassPermissions'`. */
155 permissionMode?: AcpPermissionMode
156 /**
157 * Permission strategy:
158 * - `'headless'` (default) — auto-resolve via {@link permissionMode}; the
159 * sandbox is the boundary, so the agent runs without prompting.
160 * - `'interactive'` — same policy, but `ask`-style prompts emit an
161 * approval-requested event so a client can approve and re-run.
162 */
163 permissions?: 'headless' | 'interactive'
164 /** Custom permission handler; overrides {@link permissions}/{@link permissionMode}. */
165 onPermissionRequest?: PermissionHandler
166 /** Message used for `RUN_ERROR` when the harness refuses a request. */
167 refusalMessage?: string
168 /** Emit ACP `plan` updates as a CUSTOM event under this name (off by default). */
169 planEventName?: string
170 /**
171 * After the run, emit the `git diff` of the working dir as a `file.changed`
172 * CUSTOM event. Requires a git repo at `cwd`. Off by default.
173 */
174 emitDiff?: boolean
175 /**
176 * Harness-specific JSON-RPC notifications (vendor `_x/...` extensions). Must
177 * return without throwing — unknown extensions must not tear down the session.
178 */
179 onExtNotification?: (method: string, params: Record<string, unknown>) => void
180 /**
181 * Convert chat history into the harness prompt + resume inputs. Defaults to
182 * {@link buildAcpPrompt} (trailing user message + flattened transcript).
183 */
184 buildPrompt?: (
185 messages: Array<ModelMessage>,
186 sessionId: string | undefined,
187 ) => BuiltAcpPrompt
189​
190/** Per-call provider options, passed via `modelOptions` on `chat()`. */
191export interface AcpCompatibleProviderOptions {
192 /**
193 * Resume an existing harness session. The adapter emits the session id of
194 * every run via a CUSTOM `<name>.session-id` event; thread it back here to
195 * continue (only the trailing user message is sent).
196 */
197 sessionId?: string
198 /** Per-call override of the harness working directory. */
199 cwd?: string
200 /**
201 * `'api-key'` (default) uses {@link authMethodId}.
202 * `'host'` skips ACP authenticate.
203 * Not inferred from the sandbox.
204 */
205 authMode?: 'host' | 'api-key'
206 /** Per-call override of the ACP auth method. Ignored when authMode is `'host'`. */
207 authMethodId?: string
208 /** Per-call override of the ACP permission policy. */
209 permissionMode?: AcpPermissionMode
211​
212/** Per-call options the adapter sees: the base ACP options + the harness's own. */
213type ResolvedOptions<TModelOptions extends Record<string, any>> =
214 AcpCompatibleProviderOptions & TModelOptions
215​
216function q(value: string): string {
217 return `'${value.replace(/'/g, `'\\''`)}'`
219​
220async function disposeTransport(transport: AcpSessionTransport): Promise<void> {
221 if (transport.kind === 'stdio') {
222 await transport.process.kill()
223 return
224 }
225 await transport.dispose()
227​
228/**
229 * A generic ACP harness adapter built from {@link AcpCompatibleConfig}. Runs the
230 * configured coding-agent CLI inside the sandbox provided by `withSandbox(...)`
231 * and translates its ACP session into AG-UI `StreamChunk`s.
232 */
233export class AcpCompatibleTextAdapter<
234 TModel extends string,
235 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
236> extends BaseTextAdapter<
237 TModel,
238 ResolvedOptions<TModelOptions>,
239 ReadonlyArray<Modality> & readonly ['text'],
240 DefaultMessageMetadataByModality,
241 ReadonlyArray<string>,
242 unknown,
243 never
244> {
245 override readonly name: string
246​
247 override readonly requires = [SandboxCapability] as const
248​
249 private readonly harness: AcpCompatibleConfig<
250 ReadonlyArray<string>,
251 TModelOptions
252 >
253​
254 /** `toolChoice` warnings that this instance already logged. */
255 private readonly toolChoiceWarnings = new Set<string>()
256​
257 constructor(
258 config: AcpCompatibleConfig<ReadonlyArray<string>, TModelOptions>,
259 model: TModel,
260 ) {
261 super({}, model)
262 if (config.command === undefined && config.openTransport === undefined) {
263 throw new Error(
264 `acpCompatible("${config.name}") needs either a "command" or an "openTransport".`,
265 )
266 }
267 this.harness = config
268 this.name = config.name
269 }
270​
271 supportsCombinedToolsAndSchema(): boolean {
272 return true
273 }
274​
275 combinedStructuredOutputSource(): 'event' {
276 return 'event'
277 }
278​
279 private sandboxFrom(
280 options: TextOptions<ResolvedOptions<TModelOptions>>,
281 ): SandboxHandle {
282 const ctx = options.capabilities
283 if (!ctx) {
284 throw new Error(
285 `Adapter "${this.name}" requires a sandbox. Add withSandbox(defineSandbox({ ... })) to chat() middleware.`,
286 )
287 }
288 return getSandbox(ctx)
289 }
290​
291 /**
292 * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only
293 * the named tool for `{ type: 'tool', name }`. ACP has no field to turn off
294 * the built-in agent tools or to force a tool call, so every value except
295 * `'auto'` logs a warning once.
296 */
297 private toolsForChoice(options: TextOptions<ResolvedOptions<TModelOptions>>) {
298 const { toolChoice, tools = [] } = options
299 if (toolChoice === undefined || toolChoice === 'auto') return tools
300 const warning =
301 toolChoice === 'required'
302 ? `${this.name}: toolChoice 'required' is not supported. The agent decides which tools to call.`
303 : `${this.name}: toolChoice limits only the chat() tools. The built-in agent tools stay on.`
304 if (!this.toolChoiceWarnings.has(warning)) {
305 this.toolChoiceWarnings.add(warning)
306 options.logger.warn(warning)
307 }
308 if (toolChoice === 'none') return []
309 if (toolChoice === 'required') return tools
310 return tools.filter((tool) => tool.name === toolChoice.name)
311 }
312​
313 private buildPrompt(
314 messages: Array<ModelMessage>,
315 sessionId: string | undefined,
316 ): BuiltAcpPrompt {
317 return this.harness.buildPrompt
318 ? this.harness.buildPrompt(messages, sessionId)
319 : buildAcpPrompt(messages, sessionId, this.name)
320 }
321​
322 private applySystemPrompts(
323 systemPrompts: Array<string>,
324 prompt: string,
325 ): string {
326 if (systemPrompts.length === 0) return prompt
327 return `${systemPrompts.join('\n\n')}\n\n${prompt}`
328 }
329​
330 private makePermissionHandler(input: {
331 mode: AcpPermissionMode
332 bridgedToolNames: ReadonlySet<string>
333 approvals: ReadonlyMap<string, boolean> | undefined
334 approvalRequests: Array<AdapterYieldChunk>
335 threadId: string
336 runId: string
337 }): PermissionHandler {
338 if (this.harness.onPermissionRequest)
339 return this.harness.onPermissionRequest
340​
341 if (this.harness.permissions === 'interactive') {
342 return (request) => {
343 const result = resolveInteractivePermission(
344 request,
345 input.mode,
346 input.bridgedToolNames,
347 input.approvals,
348 this.name,
349 )
350 if (result.approvalId !== undefined) {
351 input.approvalRequests.push(
352 buildApprovalRequestedEvent({
353 approvalId: result.approvalId,
354 title:
355 result.title ??
356 request.toolCall.title ??
357 request.toolCall.toolCallId,
358 threadId: input.threadId,
359 runId: input.runId,
360 detail: { provider: this.name },
361 }),
362 )
363 }
364 return result.outcome
365 }
366 }
367​
368 return (request) =>
369 resolvePermission(request, input.mode, input.bridgedToolNames)
370 }
371​
372 async *chatStream(
373 options: TextOptions<ResolvedOptions<TModelOptions>>,
374 ): AsyncIterable<AdapterYieldChunk> {
375 const { logger } = options
376 let handle: AcpSessionHandle | undefined
377 let bridge: HostToolBridge | undefined
378 let transport: AcpSessionTransport | undefined
379 const externalSignal =
380 options.abortController?.signal ?? options.request?.signal ?? undefined
381 let onAbort: (() => void) | undefined
382​
383 try {
384 const tools = this.toolsForChoice(options)
385 const sandbox = this.sandboxFrom(options)
386 const modelOptions = options.modelOptions
387 const cwd = modelOptions?.cwd ?? this.harness.cwd ?? DEFAULT_WORKDIR
388 const harnessCwd = resolveHarnessCwd(sandbox, cwd)
389 // This adapter does not journal yet, so a generated id is still fine.
390 // Routed through the helper anyway so that whenever it gains journaling
391 // it inherits the caller-supplied-runId requirement instead of
392 // re-deriving it (see `packages/ai-sandbox/src/durability.ts`).
393 const runId = resolveDurableRunId(options.runId, {
394 durable: false,
395 adapter: 'acp',
396 fallback: () => this.generateId(),
397 })
398 const threadId = options.threadId
399​
400 // Durability wired onto a path that cannot deliver it. Two outcomes, split
401 // by whether a first attempt has already run.
402 //
403 // ATTACH is fatal. `sandboxRunDriver`'s `drive()` sets `attach: true` only
404 // when a previous host was already streaming this run, so continuing past
405 // here reaches `startAcpSession` + `session.prompt(...)` and re-runs the
406 // agent from scratch against the workspace that attempt already mutated,
407 // appending its whole output to a log that still holds the first
408 // attempt's. This adapter has no journal to tail, no
409 // `awaitAttachableJournal` to refuse the attach up front, and no
410 // `alignedIfAttaching` to suppress the already-delivered prefix — so there
411 // is nothing between here and that corruption except this throw.
412 //
413 // A FRESH durable run only fails to be recoverable LATER, which an app may
414 // knowingly accept (it can wire `withSandbox({ runs, durability })` once at
415 // the middleware level and still route some runs through this adapter). So
416 // that is a warn, not a throw: audible, not fatal. Once per run, not per
417 // chunk — a per-chunk warning would be worse than none. Mirrors
418 // `ai-grok-build`'s `chatStreamAcp`.
419 const durability = options.capabilities
420 ? getSandboxDurability(options.capabilities, { optional: true })
421 : undefined
422 if (durability !== undefined) {
423 if (durability.attach) {
424 throw new DurableAttachNotSupportedError(
425 'acp',
426 'this adapter drives the harness over a bidirectional ACP ' +
427 'connection and does not journal',
428 )
429 }
430 logger.warn(
431 'acp: sandbox durability is wired but this adapter never journals — ' +
432 'this run will not be recoverable on reconnect. Use a journaling ' +
433 'harness adapter for runs that must survive a host restart, or drop ' +
434 'durability if these runs are not meant to.',
435 { runId, adapter: 'acp' },
436 )
437 }
438​
439 const channel = createBridgeEventChannel({
440 model: this.model,
441 threadId,
442 runId,
443 })
444​
445 const sessionId = modelOptions?.sessionId
446 const { prompt: resumePrompt } = this.buildPrompt(
447 options.messages,
448 sessionId,
449 )
450​
451 // Bridge chat()-provided tools into the agent over MCP (ACP http server).
452 const bridgedToolNames = new Set(tools.map((tool) => tool.name))
453 if (tools.length > 0) {
454 const provisioner =
455 (options.capabilities
456 ? getToolBridgeProvisioner(options.capabilities, { optional: true })
457 : undefined) ?? nodeHttpBridgeProvisioner
458 bridge = await provisioner.provision(tools, {
459 provider: sandbox.provider,
460 threadId,
461 context: options.context,
462 emitCustomEvent: channel.emitCustomEvent,
463 ...(externalSignal ? { signal: externalSignal } : {}),
464 })
465 }
466​
467 // Project workspace skills declared via withSandbox. MCP skills ride ACP's
468 // native `mcpServers` (below); gitSkills are linked into `skillsDir`.
469 let workspaceServers: Array<AcpMcpServer> = []
470 const projection = options.capabilities
471 ? getWorkspaceProjection(options.capabilities, { optional: true })
472 : undefined
473 if (projection !== undefined) {
474 await projectAcpWorkspace(sandbox, projection, {
475 ...(this.harness.skillsDir !== undefined && {
476 skillsDir: this.harness.skillsDir,
477 }),
478 harnessName: this.name,
479 })
480 workspaceServers = workspaceMcpServers(projection)
481 }
482​
483 const ctx: AcpHarnessContext<ResolvedOptions<TModelOptions>> = {
484 sandbox,
485 model: this.model,
486 cwd,
487 harnessCwd,
488 env: this.harness.env,
489 modelOptions,
490 signal: externalSignal,
491 }
492 transport = this.harness.openTransport
493 ? await this.harness.openTransport(ctx)
494 : await this.openStdioTransport(ctx)
495​
496 const mode =
497 modelOptions?.permissionMode ??
498 this.harness.permissionMode ??
499 'bypassPermissions'
500 const authMode =
501 modelOptions?.authMode ?? this.harness.authMode ?? 'api-key'
502 const authMethodId =
503 authMode === 'host'
504 ? undefined
505 : (modelOptions?.authMethodId ?? this.harness.authMethodId)
506​
507 const approvalRequests: Array<AdapterYieldChunk> = []
508 const permissionHandler = this.makePermissionHandler({
509 mode,
510 bridgedToolNames,
511 approvals: options.approvals,
512 approvalRequests,
513 threadId,
514 runId,
515 })
516​
517 const queue = new AsyncQueue<AcpStreamEvent>()
518​
519 logger.request(
520 `activity=chat provider=${this.name} model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${sessionId ?? 'none'}`,
521 { provider: this.name, model: this.model },
522 )
523​
524 // The host tool-bridge (chat() tools) + workspace MCP skills, both over
525 // ACP's native MCP channel.
526 const mcpServers: Array<AcpMcpServer> = [
527 ...(bridge !== undefined
528 ? [
529 {
530 name: bridge.name,
531 url: bridge.url,
532 headers: [
533 { name: 'Authorization', value: `Bearer ${bridge.token}` },
534 ],
535 },
536 ]
537 : []),
538 ...workspaceServers,
539 ]
540​
541 const onAcpUpdate = (update: AcpSessionUpdate) =>
542 queue.push({ kind: 'update', update })
543 handle = await startAcpSession({
544 transport,
545 cwd: harnessCwd,
546 ...(authMethodId !== undefined && { authMethodId }),
547 ...(sessionId !== undefined && { resumeSessionId: sessionId }),
548 ...(mcpServers.length > 0 && { mcpServers }),
549 onUpdate: onAcpUpdate,
550 ...(this.harness.onExtNotification && {
551 onExtNotification: this.harness.onExtNotification,
552 }),
553 onPermissionRequest: permissionHandler,
554 })
555 const session = handle
556​
557 if (externalSignal !== undefined) {
558 onAbort = () => void session.cancel().catch(() => undefined)
559 if (externalSignal.aborted) onAbort()
560 else externalSignal.addEventListener('abort', onAbort, { once: true })
561 }
562​
563 queue.push({ kind: 'session', sessionId: session.sessionId })
564​
565 const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
566 .map((p) => p.content)
567 .filter((c) => c.trim() !== '')
568 let promptText = this.applySystemPrompts(
569 systemPrompts,
570 session.resumed || sessionId === undefined
571 ? resumePrompt
572 : this.buildPrompt(options.messages, undefined).prompt,
573 )
574 if (options.outputSchema) {
575 promptText = appendOutputSchemaInstruction(
576 promptText,
577 options.outputSchema,
578 )
579 }
580​
581 session
582 .prompt(promptText)
583 .then(({ stopReason, usage }) => {
584 queue.push({
585 kind: 'done',
586 stopReason,
587 ...(usage !== undefined && { usage }),
588 })
589 queue.end()
590 })
591 .catch((error: unknown) => queue.fail(error))
592​
593 const wantsStructured = options.outputSchema !== undefined
594 let lastAssistantText = ''
595 let lastTextMessageId: string | undefined
596 let heldFinished: AdapterYieldChunk | undefined
597 for await (const chunk of mergeChunkStreams(
598 translateAcpStream(queue, {
599 model: this.model,
600 runId,
601 threadId,
602 ...(options.parentRunId !== undefined && {
603 parentRunId: options.parentRunId,
604 }),
605 genId: () => this.generateId(),
606 bridgedToolNames,
607 labels: {
608 sessionIdEvent: `${this.name}.session-id`,
609 // Surface non-text agent content (image/audio/resource) instead of
610 // dropping it — emitted as a CUSTOM `<name>.message-content` event.
611 contentEvent: `${this.name}.message-content`,
612 ...(this.harness.planEventName !== undefined && {
613 planEvent: this.harness.planEventName,
614 }),
615 ...(this.harness.refusalMessage !== undefined && {
616 refusalMessage: this.harness.refusalMessage,
617 }),
618 },
619 onAcpEvent: (event) =>
620 logger.provider(`provider=${this.name} kind=${event.kind}`, {
621 chunk: event,
622 }),
623 }),
624 channel.stream,
625 )) {
626 if (wantsStructured && chunk.type === EventType.RUN_FINISHED) {
627 heldFinished = chunk
628 continue
629 }
630 if (wantsStructured) {
631 if (chunk.type === EventType.TEXT_MESSAGE_START) {
632 lastAssistantText = ''
633 if (typeof chunk.messageId === 'string' && chunk.messageId !== '') {
634 lastTextMessageId = chunk.messageId
635 }
636 } else if (
637 chunk.type === EventType.TEXT_MESSAGE_CONTENT &&
638 typeof chunk.delta === 'string'
639 ) {
640 lastAssistantText += chunk.delta
641 }
642 }
643 yield chunk
644 }
645​
646 if (options.outputSchema) {
647 yield* this.emitParsedStructuredOutput(
648 lastAssistantText,
649 threadId,
650 runId,
651 lastTextMessageId,
652 )
653 }
654 if (heldFinished) yield heldFinished
655​
656 // Surface any pending approval requests (interactive ask-policy actions
657 // awaiting a client decision); the client approves and re-runs to continue.
658 for (const event of approvalRequests) yield event
659​
660 if (this.harness.emitDiff) {
661 yield* this.emitDiffChunks(sandbox, cwd, threadId, runId)
662 }
663 } catch (error: unknown) {
664 const err = error as Error & { code?: string }
665 const rawEvent = toRunErrorRawEvent(error)
666 logger.errors(`${this.name}.chatStream fatal`, {
667 error,
668 source: `${this.name}.chatStream`,
669 })
670 yield {
671 type: EventType.RUN_ERROR,
672 model: options.model,
673 timestamp: Date.now(),
674 message: err.message || 'Unknown error occurred',
675 ...(err.code !== undefined && { code: err.code }),
676 ...(rawEvent !== undefined && { rawEvent }),
677 error: {
678 message: err.message || 'Unknown error occurred',
679 ...(err.code !== undefined && { code: err.code }),
680 },
681 }
682 } finally {
683 if (externalSignal !== undefined && onAbort !== undefined) {
684 externalSignal.removeEventListener('abort', onAbort)
685 }
686 // startAcpSession owns transport teardown once a handle exists (and tears
687 // it down itself on a failed init). Only dispose here if we opened a
688 // transport but never reached a session.
689 if (handle !== undefined) await handle.dispose()
690 else if (transport !== undefined) await disposeTransport(transport)
691 await bridge?.close()
692 }
693 }
694​
695 private async openStdioTransport(
696 ctx: AcpHarnessContext<ResolvedOptions<TModelOptions>>,
697 ): Promise<AcpSessionTransport> {
698 const build = this.harness.command
699 if (build === undefined) {
700 // Unreachable — the constructor requires `command` or `openTransport`,
701 // and this path only runs when `openTransport` is absent.
702 throw new Error(
703 `acpCompatible("${this.name}") has no "command" to launch over stdio.`,
704 )
705 }
706 const command = build(ctx)
707 const proc = await ctx.sandbox.process.spawn(command, {
708 cwd: ctx.cwd,
709 ...(this.harness.env ? { env: this.harness.env } : {}),
710 ...(ctx.signal ? { signal: ctx.signal } : {}),
711 })
712 return { kind: 'stdio', process: proc }
713 }
714​
715 private async *emitDiffChunks(
716 sandbox: SandboxHandle,
717 cwd: string,
718 threadId: string,
719 runId: string,
720 ): AsyncIterable<AdapterYieldChunk> {
721 try {
722 const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, { cwd })
723 if (diff.exitCode === 0 && diff.stdout.trim() !== '') {
724 yield {
725 type: EventType.CUSTOM,
726 name: 'file.changed',
727 value: { path: '.', diff: diff.stdout },
728 timestamp: Date.now(),
729 threadId,
730 runId,
731 }
732 }
733 } catch {
734 // ignore — diff is best-effort
735 }
736 }
737​
738 private *emitParsedStructuredOutput(
739 raw: string,
740 threadId: string,
741 runId: string,
742 messageId = this.generateId(),
743 ): Generator<AdapterYieldChunk> {
744 try {
745 const object = parseJsonFromAssistantText(raw)
746 yield structuredOutputStartChunk({
747 messageId,
748 model: this.model,
749 threadId,
750 runId,
751 })
752 yield structuredOutputCompleteChunk({
753 messageId,
754 model: this.model,
755 threadId,
756 runId,
757 object,
758 raw,
759 })
760 } catch (error: unknown) {
761 const parserMessage =
762 error instanceof Error
763 ? error.message
764 : 'Failed to parse structured output'
765 const preview = raw.trim().slice(0, 200)
766 const message =
767 preview === '' ? parserMessage : `${parserMessage} Content: ${preview}`
768 yield {
769 type: EventType.RUN_ERROR,
770 model: this.model,
771 timestamp: Date.now(),
772 message,
773 code: 'structured-output-parse-failed',
774 error: { message, code: 'structured-output-parse-failed' },
775 }
776 }
777 }
778​
779 structuredOutput(
780 _options: StructuredOutputOptions<ResolvedOptions<TModelOptions>>,
781 ): Promise<StructuredOutputResult<unknown>> {
782 return Promise.reject(
783 new Error(
784 'This harness honors outputSchema on chat() in the same turn. ' +
785 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
786 ),
787 )
788 }
790​
791/**
792 * Configure an ACP-compatible harness once, then select a model per call.
793 *
794 * Mirrors `openaiCompatible`: it lets you plug ANY Agent Client Protocol agent
795 * into a TanStack AI sandbox without a dedicated adapter package.
796 *
797 * @example
798 * ```ts
799 * import { acpCompatible } from '@tanstack/ai-acp'
800 * import { chat } from '@tanstack/ai'
801 * import { defineSandbox, withSandbox } from '@tanstack/ai-sandbox'
802 *
803 * const pi = acpCompatible({
804 * name: 'pi',
805 * // declaring `models` makes pi('…') type-safe; omit to accept any string
806 * models: ['pi-fast', 'pi-pro'],
807 * // declare per-call options; merged with the base ACP options and exposed
808 * // on ctx.modelOptions inside `command` / `openTransport`
809 * modelOptions: {} as { reasoningEffort?: 'low' | 'high' },
810 * command: ({ model, harnessCwd, modelOptions }) =>
811 * `pi --acp -m ${model} --cwd ${harnessCwd}` +
812 * (modelOptions?.reasoningEffort ? ` --effort ${modelOptions.reasoningEffort}` : ''),
813 * authMethodId: 'pi-api-key',
814 * })
815 *
816 * chat({
817 * adapter: pi('pi-pro'),
818 * modelOptions: { reasoningEffort: 'high' }, // typed
819 * messages,
820 * middleware: [withSandbox(defineSandbox({ /* provider, install pi *\/ }))],
821 * })
822 * ```
823 */
824export function acpCompatible<
825 const TModels extends ReadonlyArray<string> = ReadonlyArray<string>,
826 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
827>(config: AcpCompatibleConfig<TModels, TModelOptions>) {
828 return <TModel extends AcpModelNameOf<TModels>>(
829 model: TModel,
830 overrides?: Partial<AcpCompatibleConfig<TModels, TModelOptions>>,
831 ): AcpCompatibleTextAdapter<TModel, TModelOptions> =>
832 new AcpCompatibleTextAdapter<TModel, TModelOptions>(
833 overrides ? { ...config, ...overrides } : config,
834 model,
835 )
837​
838/**
839 * One-shot helper: build a single-model ACP-compatible harness adapter inline.
840 *
841 * @example
842 * ```ts
843 * chat({
844 * adapter: acpCompatibleText('pi-fast', {
845 * name: 'pi',
846 * command: ({ model }) => `pi --acp -m ${model}`,
847 * }),
848 * messages,
849 * middleware: [withSandbox(defineSandbox({ ... }))],
850 * })
851 * ```
852 */
853export function acpCompatibleText<
854 TModel extends string,
855 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
856>(
857 model: TModel,
858 config: AcpCompatibleConfig<ReadonlyArray<string>, TModelOptions>,
859): AcpCompatibleTextAdapter<TModel, TModelOptions> {
860 return new AcpCompatibleTextAdapter<TModel, TModelOptions>(config, model)