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

text.ts

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