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

text.ts

720 lines27.9 KB

1import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
2import {
3 appendOutputSchemaInstruction,
4 toRunErrorRawEvent,
5} from '@tanstack/ai/adapter-internals'
6import { BaseTextAdapter } from '@tanstack/ai/adapters'
7import {
8 SandboxCapability,
9 alignedIfAttaching,
10 approvalId,
11 buildApprovalRequestedEvent,
12 createBridgeEventChannel,
13 createRunScopedIdGen,
14 encodeRunId,
15 getSandbox,
16 getSandboxDurability,
17 getSandboxPolicy,
18 getToolBridgeProvisioner,
19 getWorkspaceProjection,
20 journalOptionsFor,
21 mergeChunkStreams,
22 nodeHttpBridgeProvisioner,
23 resolveApproval,
24 resolveDurableRunId,
25 resolveDurableThreadId,
26 spawnNdjson,
27} from '@tanstack/ai-sandbox'
28import { buildPrompt } from '../messages/prompt'
29import { translateSdkStream } from '../stream/translate'
30import { mapPolicyToClaudeFlags } from './policy-map'
31import { projectClaudeWorkspace } from './projection'
32import {
33 CLAUDE_JSON_SCHEMA_PLACEHOLDER,
34 CLAUDE_RUNNER_SOURCE,
35} from './claude-run-source'
36​
37import type { ClaudePolicyFlags } from './policy-map'
38import type {
39 BridgeEventChannel,
40 HostToolBridge,
41 PermissionToolResult,
42 SandboxHandle,
43 SandboxPolicy,
44} from '@tanstack/ai-sandbox'
45import type {
46 StructuredOutputOptions,
47 StructuredOutputResult,
48} from '@tanstack/ai/adapters'
49import type {
50 DefaultMessageMetadataByModality,
51 Modality,
52 AdapterYieldChunk,
53 TextOptions,
54} from '@tanstack/ai'
55import type { ClaudeCodeModel } from '../model-meta'
56import type { ClaudeCodeTextProviderOptions } from '../provider-options'
57import type { AgentSdkMessage } from '../stream/sdk-types'
58​
59export type ClaudeCodePermissionMode =
60 | 'default'
61 | 'acceptEdits'
62 | 'bypassPermissions'
63 | 'plan'
64​
65export type ClaudeCodeSettingSource = 'user' | 'project' | 'local'
66​
67const DEFAULT_WORKDIR = '/workspace'
68​
69export interface ClaudeCodeTextConfig {
70 /**
71 * Working directory inside the sandbox where `claude` runs. Defaults to
72 * `/workspace` (the conventional sandbox workspace root).
73 */
74 cwd?: string
75 /**
76 * Claude Code permission mode passed via `--permission-mode`. Defaults to
77 * `'bypassPermissions'` — a sandbox is isolated, so the agent is allowed to
78 * edit files and run commands without prompting. Tighten via `defineSandboxPolicy`
79 * / this option for less autonomy.
80 */
81 permissionMode?: ClaudeCodePermissionMode
82 /** Built-in tools the harness may use (`--allowedTools`). */
83 allowedTools?: Array<string>
84 /** Built-in tools removed from the harness (`--disallowedTools`). */
85 disallowedTools?: Array<string>
86 /** Extra directories the agent may access (`--add-dir`). */
87 addDirs?: Array<string>
88 /** Maximum harness-internal turns (`--max-turns`). */
89 maxTurns?: number
90 /**
91 * Claude Code settings tiers loaded via `--setting-sources`. Defaults to
92 * `['project']`: workspace projections (instructions, skills, MCP config)
93 * are project-scoped, and the host's `~/.claude` stays out of local-process
94 * runs. Pass `['user', 'project', 'local']` for CLI-equivalent behavior.
95 */
96 settingSources?: Array<ClaudeCodeSettingSource>
97 /**
98 * How `systemPrompts` from `chat()` are applied:
99 * - `'append'` (default): `--append-system-prompt` on top of the preset.
100 * - `'replace'`: `--system-prompt` as the entire system prompt.
101 */
102 systemPromptMode?: 'append' | 'replace'
103 /** Path/name of the claude executable inside the sandbox. Defaults to `claude`. */
104 claudeExecutable?: string
105 /** Emit token-level deltas via `--include-partial-messages` (default true). */
106 streamPartials?: boolean
107 /** Extra environment variables for the claude process inside the sandbox. */
108 env?: Record<string, string>
109 /**
110 * `'api-key'` (default) injects `ANTHROPIC_API_KEY`.
111 * `'host'` uses `claude login` and does not inject the key.
112 * Not inferred from the sandbox.
113 */
114 authMode?: 'host' | 'api-key'
115 /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */
116 emitDiff?: boolean
118​
119/** POSIX single-quote escape for embedding values in the `claude …` command. */
120function q(value: string): string {
121 return `'${value.replace(/'/g, `'\\''`)}'`
123​
124/** Copy host Anthropic auth into the sandbox process. Docker `exec` Env replaces the container env, so a key set only at create time can vanish. */
125function hostClaudeAuthEnv(): Record<string, string> {
126 const env: Record<string, string> = {}
127 const apiKey = process.env.ANTHROPIC_API_KEY
128 if (apiKey) env.ANTHROPIC_API_KEY = apiKey
129 const authToken = process.env.ANTHROPIC_AUTH_TOKEN
130 if (authToken) env.ANTHROPIC_AUTH_TOKEN = authToken
131 return env
133​
134/**
135 * Windows Node often has USERPROFILE but no HOME. Claude then cannot find
136 * `~/.claude.json` (the `claude login` file) and prints "Not logged in".
137 */
138function localProcessHomeEnv(provider: string): Record<string, string> {
139 if (provider !== 'local-process') return {}
140 if (process.env.HOME) return {}
141 const home = process.env.USERPROFILE
142 return home ? { HOME: home } : {}
144​
145/** Format a host tool-bridge as claude's `--mcp-config` JSON. */
146function bridgeToMcpConfig(bridge: HostToolBridge): string {
147 return JSON.stringify({
148 mcpServers: {
149 [bridge.name]: {
150 type: 'http',
151 url: bridge.url,
152 headers: { Authorization: `Bearer ${bridge.token}` },
153 },
154 },
155 })
157​
158export class ClaudeCodeTextAdapter<
159 TModel extends ClaudeCodeModel,
160> extends BaseTextAdapter<
161 TModel,
162 ClaudeCodeTextProviderOptions,
163 ReadonlyArray<Modality> & readonly ['text'],
164 DefaultMessageMetadataByModality,
165 ReadonlyArray<string>,
166 unknown,
167 never
168> {
169 readonly name = 'claude-code' as const
170​
171 // Harness adapter: requires a sandbox to run the agent CLI inside.
172 override readonly requires = [SandboxCapability] as const
173​
174 private readonly adapterConfig: ClaudeCodeTextConfig
175​
176 constructor(config: ClaudeCodeTextConfig, model: TModel) {
177 super({}, model)
178 this.adapterConfig = config
179 }
180​
181 private sandboxFrom(
182 options: TextOptions<ClaudeCodeTextProviderOptions>,
183 ): SandboxHandle {
184 const ctx = options.capabilities
185 if (!ctx) {
186 throw new Error(
187 'Adapter "claude-code" requires a sandbox. Add withSandbox(defineSandbox({ ... })) ' +
188 'to chat() middleware (e.g. with the local-process or docker provider).',
189 )
190 }
191 return getSandbox(ctx)
192 }
193​
194 private workdir(options: TextOptions<ClaudeCodeTextProviderOptions>): string {
195 return (
196 options.modelOptions?.cwd ?? this.adapterConfig.cwd ?? DEFAULT_WORKDIR
197 )
198 }
199​
200 supportsCombinedToolsAndSchema(): boolean {
201 return true
202 }
203​
204 combinedStructuredOutputSource(): 'event' {
205 return 'event'
206 }
207​
208 /** Build the `claude` command line (prompt goes via stdin, not argv). */
209 private buildArgv(
210 options: TextOptions<ClaudeCodeTextProviderOptions>,
211 resume: string | undefined,
212 policyFlags: ClaudePolicyFlags,
213 mcpConfigPath: string | undefined,
214 permissionPromptTool: string | undefined,
215 hasJsonSchema: boolean,
216 ): Array<string> {
217 const config = this.adapterConfig
218 const modelOptions = options.modelOptions
219 const exeParts = (config.claudeExecutable ?? 'claude').split(' ')
220 // Claude only reads project-scoped config (CLAUDE.md, `.claude/skills`,
221 // `.mcp.json`) with `project` in the sources. `user` is off by default so
222 // a local-process run does not pull in the host's `~/.claude`.
223 const settingSources = config.settingSources ?? ['project']
224​
225 // `--setting-sources` before `-p`. Do not pass `--bare`: that flag
226 // skips stored `claude login` credentials and prints
227 // "Not logged in · Please run /login" (claude-code#51047).
228 // `-p` can take the next token as the prompt, so these flags stay first.
229 const args: Array<string> = [
230 ...exeParts,
231 '--setting-sources',
232 settingSources.join(','),
233 '-p',
234 '--output-format',
235 'stream-json',
236 '--verbose',
237 '--model',
238 this.model,
239 ]
240​
241 if (config.streamPartials !== false) args.push('--include-partial-messages')
242 if (resume !== undefined) args.push('--resume', resume)
243​
244 const permissionMode =
245 modelOptions?.permissionMode ??
246 config.permissionMode ??
247 policyFlags.permissionMode ??
248 'bypassPermissions'
249 args.push('--permission-mode', permissionMode)
250​
251 const maxTurns = modelOptions?.maxTurns ?? config.maxTurns
252 if (maxTurns !== undefined) args.push('--max-turns', String(maxTurns))
253​
254 for (const dir of config.addDirs ?? []) args.push('--add-dir', dir)
255​
256 const allowedTools = [
257 ...(modelOptions?.allowedTools ?? config.allowedTools ?? []),
258 ...policyFlags.allowedTools,
259 ]
260 if (allowedTools.length > 0) {
261 args.push('--allowedTools', [...new Set(allowedTools)].join(','))
262 }
263 const disallowedTools = [
264 ...(modelOptions?.disallowedTools ?? config.disallowedTools ?? []),
265 ...policyFlags.disallowedTools,
266 ]
267 if (disallowedTools.length > 0) {
268 args.push('--disallowedTools', [...new Set(disallowedTools)].join(','))
269 }
270​
271 const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
272 .map((prompt) => prompt.content)
273 .filter((content) => content.trim() !== '')
274 if (systemPrompts.length > 0) {
275 const joined = systemPrompts.join('\n\n')
276 const flag =
277 config.systemPromptMode === 'replace'
278 ? '--system-prompt'
279 : '--append-system-prompt'
280 args.push(flag, joined)
281 }
282​
283 if (mcpConfigPath !== undefined) args.push('--mcp-config', mcpConfigPath)
284 if (hasJsonSchema) {
285 args.push('--json-schema', CLAUDE_JSON_SCHEMA_PLACEHOLDER)
286 }
287 if (permissionPromptTool !== undefined) {
288 args.push('--permission-prompt-tool', permissionPromptTool)
289 }
290​
291 return args
292 }
293​
294 /**
295 * Build the permission-prompt resolver the host MCP bridge exposes to claude
296 * (`--permission-prompt-tool`). Maps claude's permission request onto the
297 * sandbox policy + client approvals; on an `ask` action with no decision yet,
298 * records an approval-requested event and denies (the client re-runs to grant).
299 */
300 private buildPermissionResolver(
301 policy: SandboxPolicy | undefined,
302 approvals: ReadonlyMap<string, boolean> | undefined,
303 scripts: Record<string, string> | undefined,
304 sink: Array<AdapterYieldChunk>,
305 threadId: string,
306 runId: string,
307 ): (input: { tool_name?: string; input?: unknown }) => PermissionToolResult {
308 const writeTools = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
309 const networkTools = new Set(['WebFetch', 'WebSearch'])
310 return (request) => {
311 const toolName = request.tool_name ?? 'tool'
312 const cmdInput = request.input
313 const command =
314 toolName === 'Bash' &&
315 cmdInput !== null &&
316 typeof cmdInput === 'object' &&
317 'command' in cmdInput &&
318 typeof (cmdInput as { command?: unknown }).command === 'string'
319 ? (cmdInput as { command: string }).command
320 : undefined
321 const capability = writeTools.has(toolName)
322 ? 'fileWrite'
323 : networkTools.has(toolName)
324 ? 'network'
325 : undefined
326 const id = approvalId({
327 provider: 'claude-code',
328 kind: command !== undefined ? 'command' : (capability ?? 'tool'),
329 target: command ?? toolName,
330 })
331 const outcome = resolveApproval({
332 policy,
333 approvals,
334 id,
335 scripts,
336 ...(command !== undefined ? { command } : {}),
337 ...(capability !== undefined ? { capability } : {}),
338 })
339 if (outcome.needsApproval) {
340 sink.push(
341 buildApprovalRequestedEvent({
342 approvalId: id,
343 title: `Approve ${toolName}${command !== undefined ? `: ${command}` : ''}`,
344 threadId,
345 runId,
346 detail: { provider: 'claude-code', toolName },
347 }),
348 )
349 return {
350 behavior: 'deny',
351 message:
352 'Awaiting client approval. Approve in the UI and re-run to continue.',
353 }
354 }
355 return outcome.decision === 'allow'
356 ? { behavior: 'allow' }
357 : { behavior: 'deny', message: 'Denied by sandbox policy.' }
358 }
359 }
360​
361 async *chatStream(
362 options: TextOptions<ClaudeCodeTextProviderOptions>,
363 ): AsyncIterable<AdapterYieldChunk> {
364 const { logger } = options
365 let bridge: HostToolBridge | undefined
366 let channel: BridgeEventChannel | undefined
367 const approvalRequests: Array<AdapterYieldChunk> = []
368 // Temp files written for the run (bridge MCP config, redirected prompt) that
369 // carry the bearer token / prompt; removed in `finally` so they don't linger
370 // in the sandbox after the run.
371 let cleanupSandbox: SandboxHandle | undefined
372 const tempFiles: Array<string> = []
373 try {
374 const sandbox = this.sandboxFrom(options)
375 cleanupSandbox = sandbox
376 const cwd = this.workdir(options)
377​
378 // Durability comes from `withSandbox(sandbox, { runs, durability })`, read
379 // back off the capability bus. Absent it, everything below resolves to
380 // exactly today's behavior (no journal option, no alignment, and a
381 // generated `runId` when the caller didn't supply one).
382 const durability = options.capabilities
383 ? getSandboxDurability(options.capabilities, { optional: true })
384 : undefined
385 // The journaled path below derives its journal path and its
386 // message-id generator from `runId`. A resuming host must recompute
387 // the same `runId` to find the same journal file and reproduce the
388 // same translated ids — that's only possible when the caller supplies
389 // `runId` explicitly. `resolveDurableRunId` enforces that loudly (via
390 // `DurableRunIdRequiredError`) whenever durability is wired, and falls
391 // back to a fresh `this.generateId()` otherwise, preserving today's
392 // behavior for non-durable runs.
393 const runId = resolveDurableRunId(options.runId, {
394 durable: durability !== undefined,
395 adapter: 'claude-code',
396 fallback: () => this.generateId(),
397 })
398 // `threadId` is stamped on every chunk `translateSdkStream` emits, so an
399 // ATTACHING run that mints a fresh one replays a stream the stored log
400 // cannot match at index 0. `resolveDurableThreadId` refuses that up front
401 // instead of letting alignment discover it mid-stream; a durable FRESH run
402 // and a non-durable run both keep the generated fallback untouched.
403 const threadId = resolveDurableThreadId(options.threadId, {
404 durable: durability !== undefined,
405 attaching: durability?.attach === true,
406 adapter: 'claude-code',
407 fallback: () => this.generateId(),
408 })
409 // Surfaces custom events from bridged tools (e.g. code mode console logs)
410 // on this run's live output stream.
411 channel = createBridgeEventChannel({ model: this.model, threadId, runId })
412​
413 // Idempotently project workspace skills/plugins/MCP into the sandbox in
414 // claude's native format (guarded by the projection marker file).
415 const projection = options.capabilities
416 ? getWorkspaceProjection(options.capabilities, { optional: true })
417 : undefined
418 if (projection) await projectClaudeWorkspace(sandbox, projection)
419​
420 const policy = options.capabilities
421 ? getSandboxPolicy(options.capabilities, { optional: true })
422 : undefined
423​
424 // A permission-prompt tool gates the agent's native tools when a policy
425 // can `ask`/`deny` (interactive approvals).
426 const permission =
427 policy !== undefined
428 ? {
429 toolName: 'approval_prompt',
430 resolve: this.buildPermissionResolver(
431 policy,
432 options.approvals,
433 projection?.scripts,
434 approvalRequests,
435 threadId,
436 runId,
437 ),
438 }
439 : undefined
440​
441 // Bridge chat()-provided server tools (and/or the permission tool) into
442 // the sandbox over MCP.
443 const hasTools = options.tools !== undefined && options.tools.length > 0
444 if (hasTools || permission !== undefined) {
445 const provisioner =
446 (options.capabilities
447 ? getToolBridgeProvisioner(options.capabilities, { optional: true })
448 : undefined) ?? nodeHttpBridgeProvisioner
449 bridge = await provisioner.provision(options.tools ?? [], {
450 provider: sandbox.provider,
451 context: options.context,
452 emitCustomEvent: channel.emitCustomEvent,
453 ...(permission !== undefined ? { permission } : {}),
454 ...(options.abortController?.signal
455 ? { signal: options.abortController.signal }
456 : {}),
457 })
458 }
459​
460 const built = buildPrompt(
461 options.messages,
462 options.modelOptions?.sessionId,
463 )
464 const resume = built.resume
465 const prompt =
466 options.outputSchema !== undefined
467 ? appendOutputSchemaInstruction(built.prompt, options.outputSchema)
468 : built.prompt
469 // Both files below name themselves after `runId`, and durability makes
470 // `runId` CALLER-chosen. Raw, a `/` in it would silently turn each basename
471 // into a nested path (writing outside the intended directory, or failing on
472 // one that does not exist), `..` would climb out of that directory, and a
473 // long id would fail the spawn with `ENAMETOOLONG`. `encodeRunId` collapses
474 // any id to one bounded, injective path segment — the same encoder
475 // `journalPaths` uses, so these files and the journal agree on how a given
476 // id spells. Computed once so the two filenames cannot drift apart.
477 const runIdSegment = encodeRunId(runId)
478​
479 // The bridge MCP config carries the per-run bearer token. Write it to a
480 // file and pass claude the PATH, so the token never appears in argv (where
481 // any process in the sandbox could read it via `ps` / `/proc/<pid>/cmdline`).
482 let mcpConfigArg: string | undefined
483 if (bridge) {
484 // Pass claude a path RELATIVE to its cwd (the real workdir the handle
485 // runs the process in). An absolute VIRTUAL path like `/workspace/…` is
486 // wrong wherever claude runs outside a sandbox that literally uses
487 // `/workspace` — e.g. local-process on Windows, where git-bash resolves
488 // `/workspace` to `C:\Program Files\Git\workspace` and the file is "not
489 // found". The bare filename resolves correctly on every provider.
490 const mcpConfigFile = `.tanstack-mcp-bridge-${runIdSegment}.json`
491 const mcpConfigPath = `${cwd}/${mcpConfigFile}`
492 await sandbox.fs.write(mcpConfigPath, bridgeToMcpConfig(bridge))
493 tempFiles.push(mcpConfigPath)
494 mcpConfigArg = mcpConfigFile
495 }
496 let jsonSchemaFile: string | undefined
497 if (options.outputSchema !== undefined) {
498 jsonSchemaFile = `tanstack-output-schema-${runIdSegment}.json`
499 const schemaPath = `${cwd}/${jsonSchemaFile}`
500 await sandbox.fs.write(schemaPath, JSON.stringify(options.outputSchema))
501 tempFiles.push(schemaPath)
502 }
503 const runnerFile = `tanstack-claude-run-${runIdSegment}.mjs`
504 await sandbox.fs.write(`${cwd}/${runnerFile}`, CLAUDE_RUNNER_SOURCE)
505 tempFiles.push(`${cwd}/${runnerFile}`)
506 const argv = this.buildArgv(
507 options,
508 resume,
509 mapPolicyToClaudeFlags(policy),
510 mcpConfigArg,
511 bridge && permission
512 ? `mcp__${bridge.name}__${permission.toolName}`
513 : undefined,
514 jsonSchemaFile !== undefined,
515 )
516 // Filenames only on the shell line. JSON (schema, system prompt, MCP
517 // config path) lives in the argv file so git-bash cannot retokenize it.
518 const argvFile = `tanstack-claude-argv-${runIdSegment}.json`
519 await sandbox.fs.write(`${cwd}/${argvFile}`, JSON.stringify(argv))
520 tempFiles.push(`${cwd}/${argvFile}`)
521 const command =
522 jsonSchemaFile === undefined
523 ? `node ${q(runnerFile)} ${q(argvFile)}`
524 : `node ${q(runnerFile)} ${q(argvFile)} ${q(jsonSchemaFile)}`
525​
526 // Deliver the prompt. The default feeds it over stdin (keeps it out of
527 // argv). Providers without a writable host→process stdin (e.g. Cloudflare)
528 // can't accept that write, so write the prompt to a file and redirect the
529 // CLI's stdin from it in-shell (`claude -p … < file`) — still out of argv.
530 let runCommand = command
531 let stdinInput: string | undefined = prompt
532 if (sandbox.capabilities.writableStdin === false) {
533 const promptPath = `/tmp/tanstack-claude-prompt-${runIdSegment}`
534 await sandbox.fs.write(promptPath, prompt)
535 tempFiles.push(promptPath)
536 runCommand = `${command} < ${q(promptPath)}`
537 stdinInput = undefined
538 }
539​
540 logger.request(
541 `activity=chat provider=claude-code model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,
542 { provider: 'claude-code', model: this.model },
543 )
544​
545 const authMode =
546 options.modelOptions?.authMode ??
547 this.adapterConfig.authMode ??
548 'api-key'
549 const injectApiKey = authMode === 'api-key'
550​
551 const journalOptions = journalOptionsFor(durability, runId)
552 const rawEvents = spawnNdjson(sandbox, runCommand, {
553 cwd,
554 ...(stdinInput !== undefined ? { input: stdinInput } : {}),
555 // Isolated sandboxes often run as root. Claude refuses
556 // `--dangerously-skip-permissions` as root unless IS_SANDBOX=1.
557 // CLAUDE_CODE_SANDBOXED marks a real isolation boundary. Do not set
558 // either on local-process: that provider runs on the host.
559 env: {
560 ...(sandbox.provider === 'local-process'
561 ? {}
562 : {
563 IS_SANDBOX: '1',
564 CLAUDE_CODE_SANDBOXED: '1',
565 }),
566 ...(injectApiKey ? hostClaudeAuthEnv() : {}),
567 ...localProcessHomeEnv(sandbox.provider),
568 ...this.adapterConfig.env,
569 },
570 ...(options.abortController?.signal
571 ? { signal: options.abortController.signal }
572 : options.request?.signal
573 ? { signal: options.request.signal }
574 : {}),
575 onNonJsonLine: (line) =>
576 logger.provider(`provider=claude-code non-json line: ${line}`, {
577 chunk: line,
578 }),
579 // Journal + attach both come from the sandbox durability capability, so
580 // the attach route configures takeover by passing `attach: true` to
581 // `withSandbox` — `chat()` stays free of sandbox vocabulary. Omitted
582 // entirely (not passed as `undefined`) when the run isn't durable, so
583 // `spawnNdjson` takes its original, unjournaled path byte-for-byte.
584 ...(journalOptions === undefined ? {} : { journal: journalOptions }),
585 })
586​
587 async function* asMessages(): AsyncIterable<AgentSdkMessage> {
588 for await (const event of rawEvents) yield event as AgentSdkMessage
589 }
590​
591 // `mergeChunkStreams` splices `channel.stream` (host-tool-bridge CUSTOM
592 // events from LIVE tool execution) into the deterministic translator
593 // output. Those events do not occur on a replay, so a takeover's replay is
594 // NOT chunk-for-chunk identical to what the log holds. `alignedIfAttaching`
595 // handles it: alignment skips stored out-of-band CUSTOM entries within a
596 // bounded window (see `align.ts`), so a bridged-tool run can be taken over
597 // without a spurious `JournalReplayDivergedError` — while a genuine
598 // determinism regression still throws. The wrap goes OUTSIDE the merge:
599 // the stored log holds the previous host's merged output, so aligning the
600 // pre-merge translated stream alone would compare against a log it never
601 // produced. On a non-attaching run this is a pure passthrough (see
602 // `alignedIfAttaching`'s `attach` guard).
603 yield* alignedIfAttaching(
604 mergeChunkStreams(
605 translateSdkStream(asMessages(), {
606 model: this.model,
607 runId,
608 threadId,
609 ...(options.parentRunId !== undefined && {
610 parentRunId: options.parentRunId,
611 }),
612 // Deterministic on the journaled path: two translations of the same
613 // journal prefix from a fresh generator seeded with the same
614 // `runId` mint the same message ids (unlike `this.generateId()`,
615 // which mixes in `Date.now()` / `Math.random()`). See
616 // `createRunScopedIdGen` in `@tanstack/ai-sandbox`.
617 genId: createRunScopedIdGen(runId),
618 ...(options.outputSchema ? { expectStructuredOutput: true } : {}),
619 onSdkMessage: (message) =>
620 logger.provider(`provider=claude-code type=${message.type}`, {
621 chunk: message,
622 }),
623 }),
624 channel.stream,
625 ),
626 durability,
627 logger,
628 )
629​
630 // Surface the working-tree diff so UIs can render what the agent changed.
631 if (this.adapterConfig.emitDiff !== false) {
632 try {
633 const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, {
634 cwd,
635 })
636 if (diff.exitCode === 0 && diff.stdout.trim() !== '') {
637 yield {
638 type: EventType.CUSTOM,
639 name: 'file.changed',
640 value: { path: '.', diff: diff.stdout },
641 timestamp: Date.now(),
642 threadId,
643 runId,
644 }
645 }
646 } catch {
647 // not a git repo / git unavailable — skip the diff event
648 }
649 }
650​
651 // Surface any pending approval requests (policy `ask` actions awaiting a
652 // client decision); the client approves and re-runs to continue.
653 for (const event of approvalRequests) yield event
654 } catch (error: unknown) {
655 const err = error as Error & { code?: string }
656 const rawEvent = toRunErrorRawEvent(error)
657 logger.errors('claude-code.chatStream fatal', {
658 error,
659 source: 'claude-code.chatStream',
660 })
661 yield {
662 type: EventType.RUN_ERROR,
663 model: options.model,
664 timestamp: Date.now(),
665 message: err.message || 'Unknown error occurred',
666 ...(err.code !== undefined && { code: err.code }),
667 ...(rawEvent !== undefined && { rawEvent }),
668 error: {
669 message: err.message || 'Unknown error occurred',
670 ...(err.code !== undefined && { code: err.code }),
671 },
672 }
673 } finally {
674 channel?.close()
675 if (bridge) await bridge.close()
676 // Remove the per-run token/prompt files. Best-effort: a cleanup failure
677 // must not mask the run's own outcome.
678 if (cleanupSandbox) {
679 for (const path of tempFiles) {
680 try {
681 await cleanupSandbox.fs.remove(path)
682 } catch {
683 // file already gone / sandbox torn down — nothing to clean up
684 }
685 }
686 }
687 }
688 }
689​
690 structuredOutput(
691 _options: StructuredOutputOptions<ClaudeCodeTextProviderOptions>,
692 ): Promise<StructuredOutputResult<unknown>> {
693 return Promise.reject(
694 new Error(
695 'This harness honors outputSchema on chat() in the same turn. ' +
696 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
697 ),
698 )
699 }
701​
702/**
703 * Creates a Claude Code harness adapter that runs **inside a sandbox**.
704 *
705 * Unlike HTTP provider adapters, this is a *harness* adapter: it spawns the
706 * `claude` CLI inside the sandbox provided by `withSandbox(...)` (the adapter
707 * declares `requires: [SandboxCapability]`), streams its `stream-json` stdout
708 * back as AG-UI events, and lets Claude Code run its own agent loop and native
709 * tools (Bash, file edits, search, …) against the sandbox workspace. The
710 * sandbox image must provide the `claude` executable and `ANTHROPIC_API_KEY`
711 * in its environment (e.g. via `workspace.secrets`). The session id is
712 * surfaced via a CUSTOM `claude-code.session-id` event so follow-up calls can
713 * resume through `modelOptions.sessionId`.
714 */
715export function claudeCodeText<TModel extends ClaudeCodeModel>(
716 model: TModel,
717 config: ClaudeCodeTextConfig = {},
718): ClaudeCodeTextAdapter<TModel> {
719 return new ClaudeCodeTextAdapter(config, model)