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

text.ts

789 lines30.2 KB

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