Open History to see the last commit
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
81}
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
188}
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
210}
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, `'\\''`)}'`
218}
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()
226}
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 constructor(
255 config: AcpCompatibleConfig<ReadonlyArray<string>, TModelOptions>,
256 model: TModel,
257 ) {
258 super({}, model)
259 if (config.command === undefined && config.openTransport === undefined) {
260 throw new Error(
261 `acpCompatible("${config.name}") needs either a "command" or an "openTransport".`,
262 )
263 }
264 this.harness = config
265 this.name = config.name
266 }
267
268 supportsCombinedToolsAndSchema(): boolean {
269 return true
270 }
271
272 combinedStructuredOutputSource(): 'event' {
273 return 'event'
274 }
275
276 private sandboxFrom(
277 options: TextOptions<ResolvedOptions<TModelOptions>>,
278 ): SandboxHandle {
279 const ctx = options.capabilities
280 if (!ctx) {
281 throw new Error(
282 `Adapter "${this.name}" requires a sandbox. Add withSandbox(defineSandbox({ ... })) to chat() middleware.`,
283 )
284 }
285 return getSandbox(ctx)
286 }
287
288 private buildPrompt(
289 messages: Array<ModelMessage>,
290 sessionId: string | undefined,
291 ): BuiltAcpPrompt {
292 return this.harness.buildPrompt
293 ? this.harness.buildPrompt(messages, sessionId)
294 : buildAcpPrompt(messages, sessionId, this.name)
295 }
296
297 private applySystemPrompts(
298 systemPrompts: Array<string>,
299 prompt: string,
300 ): string {
301 if (systemPrompts.length === 0) return prompt
302 return `${systemPrompts.join('\n\n')}\n\n${prompt}`
303 }
304
305 private makePermissionHandler(input: {
306 mode: AcpPermissionMode
307 bridgedToolNames: ReadonlySet<string>
308 approvals: ReadonlyMap<string, boolean> | undefined
309 approvalRequests: Array<AdapterYieldChunk>
310 threadId: string
311 runId: string
312 }): PermissionHandler {
313 if (this.harness.onPermissionRequest)
314 return this.harness.onPermissionRequest
315
316 if (this.harness.permissions === 'interactive') {
317 return (request) => {
318 const result = resolveInteractivePermission(
319 request,
320 input.mode,
321 input.bridgedToolNames,
322 input.approvals,
323 this.name,
324 )
325 if (result.approvalId !== undefined) {
326 input.approvalRequests.push(
327 buildApprovalRequestedEvent({
328 approvalId: result.approvalId,
329 title:
330 result.title ??
331 request.toolCall.title ??
332 request.toolCall.toolCallId,
333 threadId: input.threadId,
334 runId: input.runId,
335 detail: { provider: this.name },
336 }),
337 )
338 }
339 return result.outcome
340 }
341 }
342
343 return (request) =>
344 resolvePermission(request, input.mode, input.bridgedToolNames)
345 }
346
347 async *chatStream(
348 options: TextOptions<ResolvedOptions<TModelOptions>>,
349 ): AsyncIterable<AdapterYieldChunk> {
350 const { logger } = options
351 let handle: AcpSessionHandle | undefined
352 let bridge: HostToolBridge | undefined
353 let transport: AcpSessionTransport | undefined
354 const externalSignal =
355 options.abortController?.signal ?? options.request?.signal ?? undefined
356 let onAbort: (() => void) | undefined
357
358 try {
359 const sandbox = this.sandboxFrom(options)
360 const modelOptions = options.modelOptions
361 const cwd = modelOptions?.cwd ?? this.harness.cwd ?? DEFAULT_WORKDIR
362 const harnessCwd = resolveHarnessCwd(sandbox, cwd)
363 // This adapter does not journal yet, so a generated id is still fine.
364 // Routed through the helper anyway so that whenever it gains journaling
365 // it inherits the caller-supplied-runId requirement instead of
366 // re-deriving it (see `packages/ai-sandbox/src/durability.ts`).
367 const runId = resolveDurableRunId(options.runId, {
368 durable: false,
369 adapter: 'acp',
370 fallback: () => this.generateId(),
371 })
372 const threadId = options.threadId ?? this.generateId()
373
374 // Durability wired onto a path that cannot deliver it. Two outcomes, split
375 // by whether a first attempt has already run.
376 //
377 // ATTACH is fatal. `sandboxRunDriver`'s `drive()` sets `attach: true` only
378 // when a previous host was already streaming this run, so continuing past
379 // here reaches `startAcpSession` + `session.prompt(...)` and re-runs the
380 // agent from scratch against the workspace that attempt already mutated,
381 // appending its whole output to a log that still holds the first
382 // attempt's. This adapter has no journal to tail, no
383 // `awaitAttachableJournal` to refuse the attach up front, and no
384 // `alignedIfAttaching` to suppress the already-delivered prefix — so there
385 // is nothing between here and that corruption except this throw.
386 //
387 // A FRESH durable run only fails to be recoverable LATER, which an app may
388 // knowingly accept (it can wire `withSandbox({ runs, durability })` once at
389 // the middleware level and still route some runs through this adapter). So
390 // that is a warn, not a throw: audible, not fatal. Once per run, not per
391 // chunk — a per-chunk warning would be worse than none. Mirrors
392 // `ai-grok-build`'s `chatStreamAcp`.
393 const durability = options.capabilities
394 ? getSandboxDurability(options.capabilities, { optional: true })
395 : undefined
396 if (durability !== undefined) {
397 if (durability.attach) {
398 throw new DurableAttachNotSupportedError(
399 'acp',
400 'this adapter drives the harness over a bidirectional ACP ' +
401 'connection and does not journal',
402 )
403 }
404 logger.warn(
405 'acp: sandbox durability is wired but this adapter never journals — ' +
406 'this run will not be recoverable on reconnect. Use a journaling ' +
407 'harness adapter for runs that must survive a host restart, or drop ' +
408 'durability if these runs are not meant to.',
409 { runId, adapter: 'acp' },
410 )
411 }
412
413 const channel = createBridgeEventChannel({
414 model: this.model,
415 threadId,
416 runId,
417 })
418
419 const sessionId = modelOptions?.sessionId
420 const { prompt: resumePrompt } = this.buildPrompt(
421 options.messages,
422 sessionId,
423 )
424
425 // Bridge chat()-provided tools into the agent over MCP (ACP http server).
426 const bridgedToolNames = new Set(
427 (options.tools ?? []).map((tool) => tool.name),
428 )
429 if (options.tools && options.tools.length > 0) {
430 const provisioner =
431 (options.capabilities
432 ? getToolBridgeProvisioner(options.capabilities, { optional: true })
433 : undefined) ?? nodeHttpBridgeProvisioner
434 bridge = await provisioner.provision(options.tools, {
435 provider: sandbox.provider,
436 context: options.context,
437 emitCustomEvent: channel.emitCustomEvent,
438 ...(externalSignal ? { signal: externalSignal } : {}),
439 })
440 }
441
442 // Project workspace skills declared via withSandbox. MCP skills ride ACP's
443 // native `mcpServers` (below); gitSkills are linked into `skillsDir`.
444 let workspaceServers: Array<AcpMcpServer> = []
445 const projection = options.capabilities
446 ? getWorkspaceProjection(options.capabilities, { optional: true })
447 : undefined
448 if (projection !== undefined) {
449 await projectAcpWorkspace(sandbox, projection, {
450 ...(this.harness.skillsDir !== undefined && {
451 skillsDir: this.harness.skillsDir,
452 }),
453 harnessName: this.name,
454 })
455 workspaceServers = workspaceMcpServers(projection)
456 }
457
458 const ctx: AcpHarnessContext<ResolvedOptions<TModelOptions>> = {
459 sandbox,
460 model: this.model,
461 cwd,
462 harnessCwd,
463 env: this.harness.env,
464 modelOptions,
465 signal: externalSignal,
466 }
467 transport = this.harness.openTransport
468 ? await this.harness.openTransport(ctx)
469 : await this.openStdioTransport(ctx)
470
471 const mode =
472 modelOptions?.permissionMode ??
473 this.harness.permissionMode ??
474 'bypassPermissions'
475 const authMode =
476 modelOptions?.authMode ?? this.harness.authMode ?? 'api-key'
477 const authMethodId =
478 authMode === 'host'
479 ? undefined
480 : (modelOptions?.authMethodId ?? this.harness.authMethodId)
481
482 const approvalRequests: Array<AdapterYieldChunk> = []
483 const permissionHandler = this.makePermissionHandler({
484 mode,
485 bridgedToolNames,
486 approvals: options.approvals,
487 approvalRequests,
488 threadId,
489 runId,
490 })
491
492 const queue = new AsyncQueue<AcpStreamEvent>()
493
494 logger.request(
495 `activity=chat provider=${this.name} model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${sessionId ?? 'none'}`,
496 { provider: this.name, model: this.model },
497 )
498
499 // The host tool-bridge (chat() tools) + workspace MCP skills, both over
500 // ACP's native MCP channel.
501 const mcpServers: Array<AcpMcpServer> = [
502 ...(bridge !== undefined
503 ? [
504 {
505 name: bridge.name,
506 url: bridge.url,
507 headers: [
508 { name: 'Authorization', value: `Bearer ${bridge.token}` },
509 ],
510 },
511 ]
512 : []),
513 ...workspaceServers,
514 ]
515
516 const onAcpUpdate = (update: AcpSessionUpdate) =>
517 queue.push({ kind: 'update', update })
518 handle = await startAcpSession({
519 transport,
520 cwd: harnessCwd,
521 ...(authMethodId !== undefined && { authMethodId }),
522 ...(sessionId !== undefined && { resumeSessionId: sessionId }),
523 ...(mcpServers.length > 0 && { mcpServers }),
524 onUpdate: onAcpUpdate,
525 ...(this.harness.onExtNotification && {
526 onExtNotification: this.harness.onExtNotification,
527 }),
528 onPermissionRequest: permissionHandler,
529 })
530 const session = handle
531
532 if (externalSignal !== undefined) {
533 onAbort = () => void session.cancel().catch(() => undefined)
534 if (externalSignal.aborted) onAbort()
535 else externalSignal.addEventListener('abort', onAbort, { once: true })
536 }
537
538 queue.push({ kind: 'session', sessionId: session.sessionId })
539
540 const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
541 .map((p) => p.content)
542 .filter((c) => c.trim() !== '')
543 let promptText = this.applySystemPrompts(
544 systemPrompts,
545 session.resumed || sessionId === undefined
546 ? resumePrompt
547 : this.buildPrompt(options.messages, undefined).prompt,
548 )
549 if (options.outputSchema) {
550 promptText = appendOutputSchemaInstruction(
551 promptText,
552 options.outputSchema,
553 )
554 }
555
556 session
557 .prompt(promptText)
558 .then(({ stopReason, usage }) => {
559 queue.push({
560 kind: 'done',
561 stopReason,
562 ...(usage !== undefined && { usage }),
563 })
564 queue.end()
565 })
566 .catch((error: unknown) => queue.fail(error))
567
568 const wantsStructured = options.outputSchema !== undefined
569 let lastAssistantText = ''
570 let lastTextMessageId: string | undefined
571 let heldFinished: AdapterYieldChunk | undefined
572 for await (const chunk of mergeChunkStreams(
573 translateAcpStream(queue, {
574 model: this.model,
575 runId,
576 threadId,
577 ...(options.parentRunId !== undefined && {
578 parentRunId: options.parentRunId,
579 }),
580 genId: () => this.generateId(),
581 bridgedToolNames,
582 labels: {
583 sessionIdEvent: `${this.name}.session-id`,
584 // Surface non-text agent content (image/audio/resource) instead of
585 // dropping it — emitted as a CUSTOM `<name>.message-content` event.
586 contentEvent: `${this.name}.message-content`,
587 ...(this.harness.planEventName !== undefined && {
588 planEvent: this.harness.planEventName,
589 }),
590 ...(this.harness.refusalMessage !== undefined && {
591 refusalMessage: this.harness.refusalMessage,
592 }),
593 },
594 onAcpEvent: (event) =>
595 logger.provider(`provider=${this.name} kind=${event.kind}`, {
596 chunk: event,
597 }),
598 }),
599 channel.stream,
600 )) {
601 if (wantsStructured && chunk.type === EventType.RUN_FINISHED) {
602 heldFinished = chunk
603 continue
604 }
605 if (wantsStructured) {
606 if (chunk.type === EventType.TEXT_MESSAGE_START) {
607 lastAssistantText = ''
608 if (typeof chunk.messageId === 'string' && chunk.messageId !== '') {
609 lastTextMessageId = chunk.messageId
610 }
611 } else if (
612 chunk.type === EventType.TEXT_MESSAGE_CONTENT &&
613 typeof chunk.delta === 'string'
614 ) {
615 lastAssistantText += chunk.delta
616 }
617 }
618 yield chunk
619 }
620
621 if (options.outputSchema) {
622 yield* this.emitParsedStructuredOutput(
623 lastAssistantText,
624 threadId,
625 runId,
626 lastTextMessageId,
627 )
628 }
629 if (heldFinished) yield heldFinished
630
631 // Surface any pending approval requests (interactive ask-policy actions
632 // awaiting a client decision); the client approves and re-runs to continue.
633 for (const event of approvalRequests) yield event
634
635 if (this.harness.emitDiff) {
636 yield* this.emitDiffChunks(sandbox, cwd, threadId, runId)
637 }
638 } catch (error: unknown) {
639 const err = error as Error & { code?: string }
640 const rawEvent = toRunErrorRawEvent(error)
641 logger.errors(`${this.name}.chatStream fatal`, {
642 error,
643 source: `${this.name}.chatStream`,
644 })
645 yield {
646 type: EventType.RUN_ERROR,
647 model: options.model,
648 timestamp: Date.now(),
649 message: err.message || 'Unknown error occurred',
650 ...(err.code !== undefined && { code: err.code }),
651 ...(rawEvent !== undefined && { rawEvent }),
652 error: {
653 message: err.message || 'Unknown error occurred',
654 ...(err.code !== undefined && { code: err.code }),
655 },
656 }
657 } finally {
658 if (externalSignal !== undefined && onAbort !== undefined) {
659 externalSignal.removeEventListener('abort', onAbort)
660 }
661 // startAcpSession owns transport teardown once a handle exists (and tears
662 // it down itself on a failed init). Only dispose here if we opened a
663 // transport but never reached a session.
664 if (handle !== undefined) await handle.dispose()
665 else if (transport !== undefined) await disposeTransport(transport)
666 await bridge?.close()
667 }
668 }
669
670 private async openStdioTransport(
671 ctx: AcpHarnessContext<ResolvedOptions<TModelOptions>>,
672 ): Promise<AcpSessionTransport> {
673 const build = this.harness.command
674 if (build === undefined) {
675 // Unreachable — the constructor requires `command` or `openTransport`,
676 // and this path only runs when `openTransport` is absent.
677 throw new Error(
678 `acpCompatible("${this.name}") has no "command" to launch over stdio.`,
679 )
680 }
681 const command = build(ctx)
682 const proc = await ctx.sandbox.process.spawn(command, {
683 cwd: ctx.cwd,
684 ...(this.harness.env ? { env: this.harness.env } : {}),
685 ...(ctx.signal ? { signal: ctx.signal } : {}),
686 })
687 return { kind: 'stdio', process: proc }
688 }
689
690 private async *emitDiffChunks(
691 sandbox: SandboxHandle,
692 cwd: string,
693 threadId: string,
694 runId: string,
695 ): AsyncIterable<AdapterYieldChunk> {
696 try {
697 const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, { cwd })
698 if (diff.exitCode === 0 && diff.stdout.trim() !== '') {
699 yield {
700 type: EventType.CUSTOM,
701 name: 'file.changed',
702 value: { path: '.', diff: diff.stdout },
703 timestamp: Date.now(),
704 threadId,
705 runId,
706 }
707 }
708 } catch {
709 // ignore — diff is best-effort
710 }
711 }
712
713 private *emitParsedStructuredOutput(
714 raw: string,
715 threadId: string,
716 runId: string,
717 messageId = this.generateId(),
718 ): Generator<AdapterYieldChunk> {
719 try {
720 const object = parseJsonFromAssistantText(raw)
721 yield structuredOutputStartChunk({
722 messageId,
723 model: this.model,
724 threadId,
725 runId,
726 })
727 yield structuredOutputCompleteChunk({
728 messageId,
729 model: this.model,
730 threadId,
731 runId,
732 object,
733 raw,
734 })
735 } catch (error: unknown) {
736 const parserMessage =
737 error instanceof Error
738 ? error.message
739 : 'Failed to parse structured output'
740 const preview = raw.trim().slice(0, 200)
741 const message =
742 preview === '' ? parserMessage : `${parserMessage} Content: ${preview}`
743 yield {
744 type: EventType.RUN_ERROR,
745 model: this.model,
746 timestamp: Date.now(),
747 message,
748 code: 'structured-output-parse-failed',
749 error: { message, code: 'structured-output-parse-failed' },
750 }
751 }
752 }
753
754 structuredOutput(
755 _options: StructuredOutputOptions<ResolvedOptions<TModelOptions>>,
756 ): Promise<StructuredOutputResult<unknown>> {
757 return Promise.reject(
758 new Error(
759 'This harness honors outputSchema on chat() in the same turn. ' +
760 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
761 ),
762 )
763 }
764}
765
766/**
767 * Configure an ACP-compatible harness once, then select a model per call.
768 *
769 * Mirrors `openaiCompatible`: it lets you plug ANY Agent Client Protocol agent
770 * into a TanStack AI sandbox without a dedicated adapter package.
771 *
772 * @example
773 * ```ts
774 * import { acpCompatible } from '@tanstack/ai-acp'
775 * import { chat } from '@tanstack/ai'
776 * import { defineSandbox, withSandbox } from '@tanstack/ai-sandbox'
777 *
778 * const pi = acpCompatible({
779 * name: 'pi',
780 * // declaring `models` makes pi('…') type-safe; omit to accept any string
781 * models: ['pi-fast', 'pi-pro'],
782 * // declare per-call options; merged with the base ACP options and exposed
783 * // on ctx.modelOptions inside `command` / `openTransport`
784 * modelOptions: {} as { reasoningEffort?: 'low' | 'high' },
785 * command: ({ model, harnessCwd, modelOptions }) =>
786 * `pi --acp -m ${model} --cwd ${harnessCwd}` +
787 * (modelOptions?.reasoningEffort ? ` --effort ${modelOptions.reasoningEffort}` : ''),
788 * authMethodId: 'pi-api-key',
789 * })
790 *
791 * chat({
792 * adapter: pi('pi-pro'),
793 * modelOptions: { reasoningEffort: 'high' }, // typed
794 * messages,
795 * middleware: [withSandbox(defineSandbox({ /* provider, install pi *\/ }))],
796 * })
797 * ```
798 */
799export function acpCompatible<
800 const TModels extends ReadonlyArray<string> = ReadonlyArray<string>,
801 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
802>(config: AcpCompatibleConfig<TModels, TModelOptions>) {
803 return <TModel extends AcpModelNameOf<TModels>>(
804 model: TModel,
805 overrides?: Partial<AcpCompatibleConfig<TModels, TModelOptions>>,
806 ): AcpCompatibleTextAdapter<TModel, TModelOptions> =>
807 new AcpCompatibleTextAdapter<TModel, TModelOptions>(
808 overrides ? { ...config, ...overrides } : config,
809 model,
810 )
811}
812
813/**
814 * One-shot helper: build a single-model ACP-compatible harness adapter inline.
815 *
816 * @example
817 * ```ts
818 * chat({
819 * adapter: acpCompatibleText('pi-fast', {
820 * name: 'pi',
821 * command: ({ model }) => `pi --acp -m ${model}`,
822 * }),
823 * messages,
824 * middleware: [withSandbox(defineSandbox({ ... }))],
825 * })
826 * ```
827 */
828export function acpCompatibleText<
829 TModel extends string,
830 TModelOptions extends Record<string, any> = AcpCompatibleProviderOptions,
831>(
832 model: TModel,
833 config: AcpCompatibleConfig<ReadonlyArray<string>, TModelOptions>,
834): AcpCompatibleTextAdapter<TModel, TModelOptions> {
835 return new AcpCompatibleTextAdapter<TModel, TModelOptions>(config, model)
836}