@tanstack/ai-claude-code 0.9.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,6 +32,7 @@ const stream = chat({
32
32
  permissionMode: 'acceptEdits',
33
33
  }),
34
34
  messages: [{ role: 'user', content: 'Fix the failing test.' }],
35
+ threadId: 'thread-1',
35
36
  })
36
37
  ```
37
38
 
@@ -7,7 +7,7 @@ import { CLAUDE_JSON_SCHEMA_PLACEHOLDER, CLAUDE_RUNNER_SOURCE } from "./claude-r
7
7
  import { EventType, normalizeSystemPrompts } from "@tanstack/ai";
8
8
  import { appendOutputSchemaInstruction, reasoningBudget, resolveReasoning, toRunErrorRawEvent } from "@tanstack/ai/adapter-internals";
9
9
  import { BaseTextAdapter } from "@tanstack/ai/adapters";
10
- import { SandboxCapability, alignedIfAttaching, approvalId, buildApprovalRequestedEvent, createBridgeEventChannel, createRunScopedIdGen, encodeRunId, getSandbox, getSandboxDurability, getSandboxPolicy, getToolBridgeProvisioner, getWorkspaceProjection, journalOptionsFor, mergeChunkStreams, nodeHttpBridgeProvisioner, resolveApproval, resolveDurableRunId, resolveDurableThreadId, spawnNdjson } from "@tanstack/ai-sandbox";
10
+ import { SandboxCapability, alignedIfAttaching, approvalId, buildApprovalRequestedEvent, createBridgeEventChannel, createRunScopedIdGen, encodeRunId, getSandbox, getSandboxDurability, getSandboxPolicy, getToolBridgeProvisioner, getWorkspaceProjection, journalOptionsFor, mergeChunkStreams, nodeHttpBridgeProvisioner, resolveApproval, resolveDurableRunId, spawnNdjson } from "@tanstack/ai-sandbox";
11
11
  //#region src/adapters/text.ts
12
12
  var DEFAULT_WORKDIR = "/workspace";
13
13
  /** POSIX single-quote escape for embedding values in the `claude …` command. */
@@ -221,12 +221,7 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
221
221
  adapter: "claude-code",
222
222
  fallback: () => this.generateId()
223
223
  });
224
- const threadId = resolveDurableThreadId(options.threadId, {
225
- durable: durability !== void 0,
226
- attaching: durability?.attach === true,
227
- adapter: "claude-code",
228
- fallback: () => this.generateId()
229
- });
224
+ const threadId = options.threadId;
230
225
  channel = createBridgeEventChannel({
231
226
  model: this.model,
232
227
  threadId,
@@ -242,6 +237,7 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
242
237
  const tools = toolsForChoice(options);
243
238
  if (tools.length > 0 || permission !== void 0) bridge = await ((options.capabilities ? getToolBridgeProvisioner(options.capabilities, { optional: true }) : void 0) ?? nodeHttpBridgeProvisioner).provision(tools, {
244
239
  provider: sandbox.provider,
240
+ threadId,
245
241
  context: options.context,
246
242
  emitCustomEvent: channel.emitCustomEvent,
247
243
  ...permission !== void 0 ? { permission } : {},
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport {\n appendOutputSchemaInstruction,\n reasoningBudget,\n resolveReasoning,\n toRunErrorRawEvent,\n} from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n SandboxCapability,\n alignedIfAttaching,\n approvalId,\n buildApprovalRequestedEvent,\n createBridgeEventChannel,\n createRunScopedIdGen,\n encodeRunId,\n getSandbox,\n getSandboxDurability,\n getSandboxPolicy,\n getToolBridgeProvisioner,\n getWorkspaceProjection,\n journalOptionsFor,\n mergeChunkStreams,\n nodeHttpBridgeProvisioner,\n resolveApproval,\n resolveDurableRunId,\n resolveDurableThreadId,\n spawnNdjson,\n} from '@tanstack/ai-sandbox'\nimport { buildPrompt } from '../messages/prompt'\nimport { translateSdkStream } from '../stream/translate'\nimport { mapPolicyToClaudeFlags } from './policy-map'\nimport { projectClaudeWorkspace } from './projection'\nimport { CLAUDE_CODE_MODEL_REASONING } from '../model-meta'\nimport {\n CLAUDE_JSON_SCHEMA_PLACEHOLDER,\n CLAUDE_RUNNER_SOURCE,\n} from './claude-run-source'\n\nimport type { ClaudePolicyFlags } from './policy-map'\nimport type {\n BridgeEventChannel,\n HostToolBridge,\n PermissionToolResult,\n SandboxHandle,\n SandboxPolicy,\n} from '@tanstack/ai-sandbox'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n DefaultMessageMetadataByModality,\n Modality,\n AdapterYieldChunk,\n ReasoningRequest,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n ClaudeCodeModel,\n ClaudeCodeModelReasoningByName,\n} from '../model-meta'\nimport type { ClaudeCodeTextProviderOptions } from '../provider-options'\nimport type { AgentSdkMessage } from '../stream/sdk-types'\n\nexport type ClaudeCodePermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n\nexport type ClaudeCodeSettingSource = 'user' | 'project' | 'local'\n\nconst DEFAULT_WORKDIR = '/workspace'\n\nexport interface ClaudeCodeTextConfig {\n /**\n * Working directory inside the sandbox where `claude` runs. Defaults to\n * `/workspace` (the conventional sandbox workspace root).\n */\n cwd?: string\n /**\n * Claude Code permission mode passed via `--permission-mode`. Defaults to\n * `'bypassPermissions'` — a sandbox is isolated, so the agent is allowed to\n * edit files and run commands without prompting. Tighten via `defineSandboxPolicy`\n * / this option for less autonomy.\n */\n permissionMode?: ClaudeCodePermissionMode\n /** Built-in tools the harness may use (`--allowedTools`). */\n allowedTools?: Array<string>\n /** Built-in tools removed from the harness (`--disallowedTools`). */\n disallowedTools?: Array<string>\n /** Extra directories the agent may access (`--add-dir`). */\n addDirs?: Array<string>\n /** Maximum harness-internal turns (`--max-turns`). */\n maxTurns?: number\n /**\n * Claude Code settings tiers loaded via `--setting-sources`. Defaults to\n * `['project']`: workspace projections (instructions, skills, MCP config)\n * are project-scoped, and the host's `~/.claude` stays out of local-process\n * runs. Pass `['user', 'project', 'local']` for CLI-equivalent behavior.\n */\n settingSources?: Array<ClaudeCodeSettingSource>\n /**\n * How `systemPrompts` from `chat()` are applied:\n * - `'append'` (default): `--append-system-prompt` on top of the preset.\n * - `'replace'`: `--system-prompt` as the entire system prompt.\n */\n systemPromptMode?: 'append' | 'replace'\n /** Path/name of the claude executable inside the sandbox. Defaults to `claude`. */\n claudeExecutable?: string\n /** Emit token-level deltas via `--include-partial-messages` (default true). */\n streamPartials?: boolean\n /** Extra environment variables for the claude process inside the sandbox. */\n env?: Record<string, string>\n /**\n * `'api-key'` (default) injects `ANTHROPIC_API_KEY`.\n * `'host'` uses `claude login` and does not inject the key.\n * Not inferred from the sandbox.\n */\n authMode?: 'host' | 'api-key'\n /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */\n emitDiff?: boolean\n}\n\n/** POSIX single-quote escape for embedding values in the `claude …` command. */\nfunction q(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n/** 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. */\nfunction hostClaudeAuthEnv(): Record<string, string> {\n const env: Record<string, string> = {}\n const apiKey = process.env.ANTHROPIC_API_KEY\n if (apiKey) env.ANTHROPIC_API_KEY = apiKey\n const authToken = process.env.ANTHROPIC_AUTH_TOKEN\n if (authToken) env.ANTHROPIC_AUTH_TOKEN = authToken\n return env\n}\n\n/**\n * Windows Node often has USERPROFILE but no HOME. Claude then cannot find\n * `~/.claude.json` (the `claude login` file) and prints \"Not logged in\".\n */\nfunction localProcessHomeEnv(provider: string): Record<string, string> {\n if (provider !== 'local-process') return {}\n if (process.env.HOME) return {}\n const home = process.env.USERPROFILE\n return home ? { HOME: home } : {}\n}\n\n/**\n * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only\n * the named tool for `{ type: 'tool', name }`.\n */\nfunction toolsForChoice(options: TextOptions<ClaudeCodeTextProviderOptions>) {\n const { toolChoice, tools = [] } = options\n if (toolChoice === 'none') return []\n if (typeof toolChoice === 'object') {\n return tools.filter((tool) => tool.name === toolChoice.name)\n }\n return tools\n}\n\n/** Format a host tool-bridge as claude's `--mcp-config` JSON. */\nfunction bridgeToMcpConfig(bridge: HostToolBridge): string {\n return JSON.stringify({\n mcpServers: {\n [bridge.name]: {\n type: 'http',\n url: bridge.url,\n headers: { Authorization: `Bearer ${bridge.token}` },\n },\n },\n })\n}\n\n/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */\ntype ResolveReasoning<TModel extends string> =\n TModel extends keyof ClaudeCodeModelReasoningByName\n ? ClaudeCodeModelReasoningByName[TModel]\n : never\n\n/** The models that take `--effort`. The same list as the Anthropic adapter's adaptive thinking. */\nconst EFFORT_MODELS =\n /^(opus|sonnet)$|opus-4-[6-9]|sonnet-4-[6-9]|opus-5|sonnet-5|fable-5/\n\n/**\n * The CLI settings for `chat({ reasoning })`, from the Claude Code docs:\n * - Claude 4.6 and later, and the `opus` and `sonnet` aliases:\n * `--effort <level>`.\n * - an older model (Haiku 4.5): `MAX_THINKING_TOKENS`, the budget (pi's\n * table when the request sets none), or `0` for `off`.\n */\nexport function claudeCodeReasoning(\n model: string,\n request: ReasoningRequest | undefined,\n): { args: Array<string>; env: Record<string, string> } {\n const resolved = resolveReasoning(request, CLAUDE_CODE_MODEL_REASONING[model])\n if (!resolved) return { args: [], env: {} }\n if (EFFORT_MODELS.test(model)) {\n return { args: ['--effort', resolved.value], env: {} }\n }\n const budget =\n resolved.level === 'off'\n ? 0\n : reasoningBudget({\n level: resolved.level,\n summary: resolved.summary,\n ...(resolved.budgetTokens !== undefined\n ? { budgetTokens: resolved.budgetTokens }\n : {}),\n })\n return { args: [], env: { MAX_THINKING_TOKENS: String(budget) } }\n}\n\nexport class ClaudeCodeTextAdapter<\n TModel extends ClaudeCodeModel,\n> extends BaseTextAdapter<\n TModel,\n ClaudeCodeTextProviderOptions,\n ReadonlyArray<Modality> & readonly ['text'],\n DefaultMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never,\n ResolveReasoning<TModel>\n> {\n readonly name = 'claude-code' as const\n\n // Harness adapter: requires a sandbox to run the agent CLI inside.\n override readonly requires = [SandboxCapability] as const\n\n private readonly adapterConfig: ClaudeCodeTextConfig\n\n /** Set after the first `toolChoice: 'required'` warning. */\n private warnedRequired = false\n\n constructor(config: ClaudeCodeTextConfig, model: TModel) {\n super({}, model)\n this.adapterConfig = config\n }\n\n private sandboxFrom(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): SandboxHandle {\n const ctx = options.capabilities\n if (!ctx) {\n throw new Error(\n 'Adapter \"claude-code\" requires a sandbox. Add withSandbox(defineSandbox({ ... })) ' +\n 'to chat() middleware (e.g. with the local-process or docker provider).',\n )\n }\n return getSandbox(ctx)\n }\n\n private workdir(options: TextOptions<ClaudeCodeTextProviderOptions>): string {\n return (\n options.modelOptions?.cwd ?? this.adapterConfig.cwd ?? DEFAULT_WORKDIR\n )\n }\n\n supportsCombinedToolsAndSchema(): boolean {\n return true\n }\n\n combinedStructuredOutputSource(): 'event' {\n return 'event'\n }\n\n /** Build the `claude` command line (prompt goes via stdin, not argv). */\n private buildArgv(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n resume: string | undefined,\n policyFlags: ClaudePolicyFlags,\n mcpConfigPath: string | undefined,\n permissionPromptTool: string | undefined,\n hasJsonSchema: boolean,\n ): Array<string> {\n const config = this.adapterConfig\n const modelOptions = options.modelOptions\n const exeParts = (config.claudeExecutable ?? 'claude').split(' ')\n // Claude only reads project-scoped config (CLAUDE.md, `.claude/skills`,\n // `.mcp.json`) with `project` in the sources. `user` is off by default so\n // a local-process run does not pull in the host's `~/.claude`.\n const settingSources = config.settingSources ?? ['project']\n\n // `--setting-sources` before `-p`. Do not pass `--bare`: that flag\n // skips stored `claude login` credentials and prints\n // \"Not logged in · Please run /login\" (claude-code#51047).\n // `-p` can take the next token as the prompt, so these flags stay first.\n const args: Array<string> = [\n ...exeParts,\n '--setting-sources',\n settingSources.join(','),\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--model',\n this.model,\n ]\n\n if (config.streamPartials !== false) args.push('--include-partial-messages')\n if (resume !== undefined) args.push('--resume', resume)\n args.push(...claudeCodeReasoning(this.model, options.reasoning).args)\n\n const permissionMode =\n modelOptions?.permissionMode ??\n config.permissionMode ??\n policyFlags.permissionMode ??\n 'bypassPermissions'\n args.push('--permission-mode', permissionMode)\n\n const maxTurns = modelOptions?.maxTurns ?? config.maxTurns\n if (maxTurns !== undefined) args.push('--max-turns', String(maxTurns))\n\n for (const dir of config.addDirs ?? []) args.push('--add-dir', dir)\n\n const allowedTools = [\n ...(modelOptions?.allowedTools ?? config.allowedTools ?? []),\n ...policyFlags.allowedTools,\n ]\n if (allowedTools.length > 0) {\n args.push('--allowedTools', [...new Set(allowedTools)].join(','))\n }\n const disallowedTools = [\n ...(modelOptions?.disallowedTools ?? config.disallowedTools ?? []),\n ...policyFlags.disallowedTools,\n ]\n if (disallowedTools.length > 0) {\n args.push('--disallowedTools', [...new Set(disallowedTools)].join(','))\n }\n // `'none'` and a named tool: `--tools ''` turns off every built-in tool,\n // and `--strict-mcp-config` keeps only the bridge, which then has no\n // chat() tool or only the named one (see `toolsForChoice`).\n const toolChoice = options.toolChoice\n if (toolChoice === 'none' || typeof toolChoice === 'object') {\n args.push('--tools', '', '--strict-mcp-config')\n }\n\n const systemPrompts = normalizeSystemPrompts(options.systemPrompts)\n .map((prompt) => prompt.content)\n .filter((content) => content.trim() !== '')\n if (systemPrompts.length > 0) {\n const joined = systemPrompts.join('\\n\\n')\n const flag =\n config.systemPromptMode === 'replace'\n ? '--system-prompt'\n : '--append-system-prompt'\n args.push(flag, joined)\n }\n\n if (mcpConfigPath !== undefined) args.push('--mcp-config', mcpConfigPath)\n if (hasJsonSchema) {\n args.push('--json-schema', CLAUDE_JSON_SCHEMA_PLACEHOLDER)\n }\n if (permissionPromptTool !== undefined) {\n args.push('--permission-prompt-tool', permissionPromptTool)\n }\n\n return args\n }\n\n /**\n * Build the permission-prompt resolver the host MCP bridge exposes to claude\n * (`--permission-prompt-tool`). Maps claude's permission request onto the\n * sandbox policy + client approvals; on an `ask` action with no decision yet,\n * records an approval-requested event and denies (the client re-runs to grant).\n */\n private buildPermissionResolver(\n policy: SandboxPolicy | undefined,\n approvals: ReadonlyMap<string, boolean> | undefined,\n scripts: Record<string, string> | undefined,\n sink: Array<AdapterYieldChunk>,\n threadId: string,\n runId: string,\n ): (input: { tool_name?: string; input?: unknown }) => PermissionToolResult {\n const writeTools = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])\n const networkTools = new Set(['WebFetch', 'WebSearch'])\n return (request) => {\n const toolName = request.tool_name ?? 'tool'\n const cmdInput = request.input\n const command =\n toolName === 'Bash' &&\n cmdInput !== null &&\n typeof cmdInput === 'object' &&\n 'command' in cmdInput &&\n typeof (cmdInput as { command?: unknown }).command === 'string'\n ? (cmdInput as { command: string }).command\n : undefined\n const capability = writeTools.has(toolName)\n ? 'fileWrite'\n : networkTools.has(toolName)\n ? 'network'\n : undefined\n const id = approvalId({\n provider: 'claude-code',\n kind: command !== undefined ? 'command' : (capability ?? 'tool'),\n target: command ?? toolName,\n })\n const outcome = resolveApproval({\n policy,\n approvals,\n id,\n scripts,\n ...(command !== undefined ? { command } : {}),\n ...(capability !== undefined ? { capability } : {}),\n })\n if (outcome.needsApproval) {\n sink.push(\n buildApprovalRequestedEvent({\n approvalId: id,\n title: `Approve ${toolName}${command !== undefined ? `: ${command}` : ''}`,\n threadId,\n runId,\n detail: { provider: 'claude-code', toolName },\n }),\n )\n return {\n behavior: 'deny',\n message:\n 'Awaiting client approval. Approve in the UI and re-run to continue.',\n }\n }\n return outcome.decision === 'allow'\n ? { behavior: 'allow' }\n : { behavior: 'deny', message: 'Denied by sandbox policy.' }\n }\n }\n\n async *chatStream(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { logger } = options\n let bridge: HostToolBridge | undefined\n let channel: BridgeEventChannel | undefined\n const approvalRequests: Array<AdapterYieldChunk> = []\n // Temp files written for the run (bridge MCP config, redirected prompt) that\n // carry the bearer token / prompt; removed in `finally` so they don't linger\n // in the sandbox after the run.\n let cleanupSandbox: SandboxHandle | undefined\n const tempFiles: Array<string> = []\n try {\n // Claude Code cannot force a tool call.\n if (options.toolChoice === 'required' && !this.warnedRequired) {\n this.warnedRequired = true\n logger.warn(\n \"claude-code: toolChoice 'required' is not supported. The agent decides which tools to call.\",\n )\n }\n const sandbox = this.sandboxFrom(options)\n cleanupSandbox = sandbox\n const cwd = this.workdir(options)\n\n // Durability comes from `withSandbox(sandbox, { runs, durability })`, read\n // back off the capability bus. Absent it, everything below resolves to\n // exactly today's behavior (no journal option, no alignment, and a\n // generated `runId` when the caller didn't supply one).\n const durability = options.capabilities\n ? getSandboxDurability(options.capabilities, { optional: true })\n : undefined\n // The journaled path below derives its journal path and its\n // message-id generator from `runId`. A resuming host must recompute\n // the same `runId` to find the same journal file and reproduce the\n // same translated ids — that's only possible when the caller supplies\n // `runId` explicitly. `resolveDurableRunId` enforces that loudly (via\n // `DurableRunIdRequiredError`) whenever durability is wired, and falls\n // back to a fresh `this.generateId()` otherwise, preserving today's\n // behavior for non-durable runs.\n const runId = resolveDurableRunId(options.runId, {\n durable: durability !== undefined,\n adapter: 'claude-code',\n fallback: () => this.generateId(),\n })\n // `threadId` is stamped on every chunk `translateSdkStream` emits, so an\n // ATTACHING run that mints a fresh one replays a stream the stored log\n // cannot match at index 0. `resolveDurableThreadId` refuses that up front\n // instead of letting alignment discover it mid-stream; a durable FRESH run\n // and a non-durable run both keep the generated fallback untouched.\n const threadId = resolveDurableThreadId(options.threadId, {\n durable: durability !== undefined,\n attaching: durability?.attach === true,\n adapter: 'claude-code',\n fallback: () => this.generateId(),\n })\n // Surfaces custom events from bridged tools (e.g. code mode console logs)\n // on this run's live output stream.\n channel = createBridgeEventChannel({ model: this.model, threadId, runId })\n\n // Idempotently project workspace skills/plugins/MCP into the sandbox in\n // claude's native format (guarded by the projection marker file).\n const projection = options.capabilities\n ? getWorkspaceProjection(options.capabilities, { optional: true })\n : undefined\n if (projection) await projectClaudeWorkspace(sandbox, projection)\n\n const policy = options.capabilities\n ? getSandboxPolicy(options.capabilities, { optional: true })\n : undefined\n\n // A permission-prompt tool gates the agent's native tools when a policy\n // can `ask`/`deny` (interactive approvals).\n const permission =\n policy !== undefined\n ? {\n toolName: 'approval_prompt',\n resolve: this.buildPermissionResolver(\n policy,\n options.approvals,\n projection?.scripts,\n approvalRequests,\n threadId,\n runId,\n ),\n }\n : undefined\n\n // Bridge chat()-provided server tools (and/or the permission tool) into\n // the sandbox over MCP.\n const tools = toolsForChoice(options)\n if (tools.length > 0 || permission !== undefined) {\n const provisioner =\n (options.capabilities\n ? getToolBridgeProvisioner(options.capabilities, { optional: true })\n : undefined) ?? nodeHttpBridgeProvisioner\n bridge = await provisioner.provision(tools, {\n provider: sandbox.provider,\n context: options.context,\n emitCustomEvent: channel.emitCustomEvent,\n ...(permission !== undefined ? { permission } : {}),\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : {}),\n })\n }\n\n const built = buildPrompt(\n options.messages,\n options.modelOptions?.sessionId,\n )\n const resume = built.resume\n const prompt =\n options.outputSchema !== undefined\n ? appendOutputSchemaInstruction(built.prompt, options.outputSchema)\n : built.prompt\n // Both files below name themselves after `runId`, and durability makes\n // `runId` CALLER-chosen. Raw, a `/` in it would silently turn each basename\n // into a nested path (writing outside the intended directory, or failing on\n // one that does not exist), `..` would climb out of that directory, and a\n // long id would fail the spawn with `ENAMETOOLONG`. `encodeRunId` collapses\n // any id to one bounded, injective path segment — the same encoder\n // `journalPaths` uses, so these files and the journal agree on how a given\n // id spells. Computed once so the two filenames cannot drift apart.\n const runIdSegment = encodeRunId(runId)\n\n // The bridge MCP config carries the per-run bearer token. Write it to a\n // file and pass claude the PATH, so the token never appears in argv (where\n // any process in the sandbox could read it via `ps` / `/proc/<pid>/cmdline`).\n let mcpConfigArg: string | undefined\n if (bridge) {\n // Pass claude a path RELATIVE to its cwd (the real workdir the handle\n // runs the process in). An absolute VIRTUAL path like `/workspace/…` is\n // wrong wherever claude runs outside a sandbox that literally uses\n // `/workspace` — e.g. local-process on Windows, where git-bash resolves\n // `/workspace` to `C:\\Program Files\\Git\\workspace` and the file is \"not\n // found\". The bare filename resolves correctly on every provider.\n const mcpConfigFile = `.tanstack-mcp-bridge-${runIdSegment}.json`\n const mcpConfigPath = `${cwd}/${mcpConfigFile}`\n await sandbox.fs.write(mcpConfigPath, bridgeToMcpConfig(bridge))\n tempFiles.push(mcpConfigPath)\n mcpConfigArg = mcpConfigFile\n }\n let jsonSchemaFile: string | undefined\n if (options.outputSchema !== undefined) {\n jsonSchemaFile = `tanstack-output-schema-${runIdSegment}.json`\n const schemaPath = `${cwd}/${jsonSchemaFile}`\n await sandbox.fs.write(schemaPath, JSON.stringify(options.outputSchema))\n tempFiles.push(schemaPath)\n }\n const runnerFile = `tanstack-claude-run-${runIdSegment}.mjs`\n await sandbox.fs.write(`${cwd}/${runnerFile}`, CLAUDE_RUNNER_SOURCE)\n tempFiles.push(`${cwd}/${runnerFile}`)\n const argv = this.buildArgv(\n options,\n resume,\n mapPolicyToClaudeFlags(policy),\n mcpConfigArg,\n bridge && permission\n ? `mcp__${bridge.name}__${permission.toolName}`\n : undefined,\n jsonSchemaFile !== undefined,\n )\n // Filenames only on the shell line. JSON (schema, system prompt, MCP\n // config path) lives in the argv file so git-bash cannot retokenize it.\n const argvFile = `tanstack-claude-argv-${runIdSegment}.json`\n await sandbox.fs.write(`${cwd}/${argvFile}`, JSON.stringify(argv))\n tempFiles.push(`${cwd}/${argvFile}`)\n const command =\n jsonSchemaFile === undefined\n ? `node ${q(runnerFile)} ${q(argvFile)}`\n : `node ${q(runnerFile)} ${q(argvFile)} ${q(jsonSchemaFile)}`\n\n // Deliver the prompt. The default feeds it over stdin (keeps it out of\n // argv). Providers without a writable host→process stdin (e.g. Cloudflare)\n // can't accept that write, so write the prompt to a file and redirect the\n // CLI's stdin from it in-shell (`claude -p … < file`) — still out of argv.\n let runCommand = command\n let stdinInput: string | undefined = prompt\n if (sandbox.capabilities.writableStdin === false) {\n const promptPath = `/tmp/tanstack-claude-prompt-${runIdSegment}`\n await sandbox.fs.write(promptPath, prompt)\n tempFiles.push(promptPath)\n runCommand = `${command} < ${q(promptPath)}`\n stdinInput = undefined\n }\n\n logger.request(\n `activity=chat provider=claude-code model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,\n { provider: 'claude-code', model: this.model },\n )\n\n const authMode =\n options.modelOptions?.authMode ??\n this.adapterConfig.authMode ??\n 'api-key'\n const injectApiKey = authMode === 'api-key'\n\n const journalOptions = journalOptionsFor(durability, runId)\n const rawEvents = spawnNdjson(sandbox, runCommand, {\n cwd,\n ...(stdinInput !== undefined ? { input: stdinInput } : {}),\n // Isolated sandboxes often run as root. Claude refuses\n // `--dangerously-skip-permissions` as root unless IS_SANDBOX=1.\n // CLAUDE_CODE_SANDBOXED marks a real isolation boundary. Do not set\n // either on local-process: that provider runs on the host.\n env: {\n ...(sandbox.provider === 'local-process'\n ? {}\n : {\n IS_SANDBOX: '1',\n CLAUDE_CODE_SANDBOXED: '1',\n }),\n ...(injectApiKey ? hostClaudeAuthEnv() : {}),\n ...localProcessHomeEnv(sandbox.provider),\n ...claudeCodeReasoning(this.model, options.reasoning).env,\n ...this.adapterConfig.env,\n },\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : options.request?.signal\n ? { signal: options.request.signal }\n : {}),\n onNonJsonLine: (line) =>\n logger.provider(`provider=claude-code non-json line: ${line}`, {\n chunk: line,\n }),\n // Journal + attach both come from the sandbox durability capability, so\n // the attach route configures takeover by passing `attach: true` to\n // `withSandbox` — `chat()` stays free of sandbox vocabulary. Omitted\n // entirely (not passed as `undefined`) when the run isn't durable, so\n // `spawnNdjson` takes its original, unjournaled path byte-for-byte.\n ...(journalOptions === undefined ? {} : { journal: journalOptions }),\n })\n\n async function* asMessages(): AsyncIterable<AgentSdkMessage> {\n for await (const event of rawEvents) yield event as AgentSdkMessage\n }\n\n // `mergeChunkStreams` splices `channel.stream` (host-tool-bridge CUSTOM\n // events from LIVE tool execution) into the deterministic translator\n // output. Those events do not occur on a replay, so a takeover's replay is\n // NOT chunk-for-chunk identical to what the log holds. `alignedIfAttaching`\n // handles it: alignment skips stored out-of-band CUSTOM entries within a\n // bounded window (see `align.ts`), so a bridged-tool run can be taken over\n // without a spurious `JournalReplayDivergedError` — while a genuine\n // determinism regression still throws. The wrap goes OUTSIDE the merge:\n // the stored log holds the previous host's merged output, so aligning the\n // pre-merge translated stream alone would compare against a log it never\n // produced. On a non-attaching run this is a pure passthrough (see\n // `alignedIfAttaching`'s `attach` guard).\n yield* alignedIfAttaching(\n mergeChunkStreams(\n translateSdkStream(asMessages(), {\n model: this.model,\n runId,\n threadId,\n ...(options.parentRunId !== undefined && {\n parentRunId: options.parentRunId,\n }),\n // Deterministic on the journaled path: two translations of the same\n // journal prefix from a fresh generator seeded with the same\n // `runId` mint the same message ids (unlike `this.generateId()`,\n // which mixes in `Date.now()` / `Math.random()`). See\n // `createRunScopedIdGen` in `@tanstack/ai-sandbox`.\n genId: createRunScopedIdGen(runId),\n ...(options.outputSchema ? { expectStructuredOutput: true } : {}),\n onSdkMessage: (message) =>\n logger.provider(`provider=claude-code type=${message.type}`, {\n chunk: message,\n }),\n }),\n channel.stream,\n ),\n durability,\n logger,\n )\n\n // Surface the working-tree diff so UIs can render what the agent changed.\n if (this.adapterConfig.emitDiff !== false) {\n try {\n const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, {\n cwd,\n })\n if (diff.exitCode === 0 && diff.stdout.trim() !== '') {\n yield {\n type: EventType.CUSTOM,\n name: 'file.changed',\n value: { path: '.', diff: diff.stdout },\n timestamp: Date.now(),\n threadId,\n runId,\n }\n }\n } catch {\n // not a git repo / git unavailable — skip the diff event\n }\n }\n\n // Surface any pending approval requests (policy `ask` actions awaiting a\n // client decision); the client approves and re-runs to continue.\n for (const event of approvalRequests) yield event\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('claude-code.chatStream fatal', {\n error,\n source: 'claude-code.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n },\n }\n } finally {\n channel?.close()\n if (bridge) await bridge.close()\n // Remove the per-run token/prompt files. Best-effort: a cleanup failure\n // must not mask the run's own outcome.\n if (cleanupSandbox) {\n for (const path of tempFiles) {\n try {\n await cleanupSandbox.fs.remove(path)\n } catch {\n // file already gone / sandbox torn down — nothing to clean up\n }\n }\n }\n }\n }\n\n structuredOutput(\n _options: StructuredOutputOptions<ClaudeCodeTextProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n return Promise.reject(\n new Error(\n 'This harness honors outputSchema on chat() in the same turn. ' +\n 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',\n ),\n )\n }\n}\n\n/**\n * Creates a Claude Code harness adapter that runs **inside a sandbox**.\n *\n * Unlike HTTP provider adapters, this is a *harness* adapter: it spawns the\n * `claude` CLI inside the sandbox provided by `withSandbox(...)` (the adapter\n * declares `requires: [SandboxCapability]`), streams its `stream-json` stdout\n * back as AG-UI events, and lets Claude Code run its own agent loop and native\n * tools (Bash, file edits, search, …) against the sandbox workspace. The\n * sandbox image must provide the `claude` executable and `ANTHROPIC_API_KEY`\n * in its environment (e.g. via `workspace.secrets`). The session id is\n * surfaced via a CUSTOM `claude-code.session-id` event so follow-up calls can\n * resume through `modelOptions.sessionId`.\n */\nexport function claudeCodeText<TModel extends ClaudeCodeModel>(\n model: TModel,\n config: ClaudeCodeTextConfig = {},\n): ClaudeCodeTextAdapter<TModel> {\n return new ClaudeCodeTextAdapter(config, model)\n}\n"],"mappings":";;;;;;;;;;;AAyEA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CAER;EAGN;CACF;CAEA,iBACE,UAC0C;EAC1C,OAAO,QAAQ,uBACb,IAAI,MACF,0IAEF,CACF;CACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,eACd,OACA,SAA+B,CAAC,GACD;CAC/B,OAAO,IAAI,sBAAsB,QAAQ,KAAK;AAChD"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport {\n appendOutputSchemaInstruction,\n reasoningBudget,\n resolveReasoning,\n toRunErrorRawEvent,\n} from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n SandboxCapability,\n alignedIfAttaching,\n approvalId,\n buildApprovalRequestedEvent,\n createBridgeEventChannel,\n createRunScopedIdGen,\n encodeRunId,\n getSandbox,\n getSandboxDurability,\n getSandboxPolicy,\n getToolBridgeProvisioner,\n getWorkspaceProjection,\n journalOptionsFor,\n mergeChunkStreams,\n nodeHttpBridgeProvisioner,\n resolveApproval,\n resolveDurableRunId,\n spawnNdjson,\n} from '@tanstack/ai-sandbox'\nimport { buildPrompt } from '../messages/prompt'\nimport { translateSdkStream } from '../stream/translate'\nimport { mapPolicyToClaudeFlags } from './policy-map'\nimport { projectClaudeWorkspace } from './projection'\nimport { CLAUDE_CODE_MODEL_REASONING } from '../model-meta'\nimport {\n CLAUDE_JSON_SCHEMA_PLACEHOLDER,\n CLAUDE_RUNNER_SOURCE,\n} from './claude-run-source'\n\nimport type { ClaudePolicyFlags } from './policy-map'\nimport type {\n BridgeEventChannel,\n HostToolBridge,\n PermissionToolResult,\n SandboxHandle,\n SandboxPolicy,\n} from '@tanstack/ai-sandbox'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n DefaultMessageMetadataByModality,\n Modality,\n AdapterYieldChunk,\n ReasoningRequest,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n ClaudeCodeModel,\n ClaudeCodeModelReasoningByName,\n} from '../model-meta'\nimport type { ClaudeCodeTextProviderOptions } from '../provider-options'\nimport type { AgentSdkMessage } from '../stream/sdk-types'\n\nexport type ClaudeCodePermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n\nexport type ClaudeCodeSettingSource = 'user' | 'project' | 'local'\n\nconst DEFAULT_WORKDIR = '/workspace'\n\nexport interface ClaudeCodeTextConfig {\n /**\n * Working directory inside the sandbox where `claude` runs. Defaults to\n * `/workspace` (the conventional sandbox workspace root).\n */\n cwd?: string\n /**\n * Claude Code permission mode passed via `--permission-mode`. Defaults to\n * `'bypassPermissions'` — a sandbox is isolated, so the agent is allowed to\n * edit files and run commands without prompting. Tighten via `defineSandboxPolicy`\n * / this option for less autonomy.\n */\n permissionMode?: ClaudeCodePermissionMode\n /** Built-in tools the harness may use (`--allowedTools`). */\n allowedTools?: Array<string>\n /** Built-in tools removed from the harness (`--disallowedTools`). */\n disallowedTools?: Array<string>\n /** Extra directories the agent may access (`--add-dir`). */\n addDirs?: Array<string>\n /** Maximum harness-internal turns (`--max-turns`). */\n maxTurns?: number\n /**\n * Claude Code settings tiers loaded via `--setting-sources`. Defaults to\n * `['project']`: workspace projections (instructions, skills, MCP config)\n * are project-scoped, and the host's `~/.claude` stays out of local-process\n * runs. Pass `['user', 'project', 'local']` for CLI-equivalent behavior.\n */\n settingSources?: Array<ClaudeCodeSettingSource>\n /**\n * How `systemPrompts` from `chat()` are applied:\n * - `'append'` (default): `--append-system-prompt` on top of the preset.\n * - `'replace'`: `--system-prompt` as the entire system prompt.\n */\n systemPromptMode?: 'append' | 'replace'\n /** Path/name of the claude executable inside the sandbox. Defaults to `claude`. */\n claudeExecutable?: string\n /** Emit token-level deltas via `--include-partial-messages` (default true). */\n streamPartials?: boolean\n /** Extra environment variables for the claude process inside the sandbox. */\n env?: Record<string, string>\n /**\n * `'api-key'` (default) injects `ANTHROPIC_API_KEY`.\n * `'host'` uses `claude login` and does not inject the key.\n * Not inferred from the sandbox.\n */\n authMode?: 'host' | 'api-key'\n /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */\n emitDiff?: boolean\n}\n\n/** POSIX single-quote escape for embedding values in the `claude …` command. */\nfunction q(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n/** 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. */\nfunction hostClaudeAuthEnv(): Record<string, string> {\n const env: Record<string, string> = {}\n const apiKey = process.env.ANTHROPIC_API_KEY\n if (apiKey) env.ANTHROPIC_API_KEY = apiKey\n const authToken = process.env.ANTHROPIC_AUTH_TOKEN\n if (authToken) env.ANTHROPIC_AUTH_TOKEN = authToken\n return env\n}\n\n/**\n * Windows Node often has USERPROFILE but no HOME. Claude then cannot find\n * `~/.claude.json` (the `claude login` file) and prints \"Not logged in\".\n */\nfunction localProcessHomeEnv(provider: string): Record<string, string> {\n if (provider !== 'local-process') return {}\n if (process.env.HOME) return {}\n const home = process.env.USERPROFILE\n return home ? { HOME: home } : {}\n}\n\n/**\n * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only\n * the named tool for `{ type: 'tool', name }`.\n */\nfunction toolsForChoice(options: TextOptions<ClaudeCodeTextProviderOptions>) {\n const { toolChoice, tools = [] } = options\n if (toolChoice === 'none') return []\n if (typeof toolChoice === 'object') {\n return tools.filter((tool) => tool.name === toolChoice.name)\n }\n return tools\n}\n\n/** Format a host tool-bridge as claude's `--mcp-config` JSON. */\nfunction bridgeToMcpConfig(bridge: HostToolBridge): string {\n return JSON.stringify({\n mcpServers: {\n [bridge.name]: {\n type: 'http',\n url: bridge.url,\n headers: { Authorization: `Bearer ${bridge.token}` },\n },\n },\n })\n}\n\n/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */\ntype ResolveReasoning<TModel extends string> =\n TModel extends keyof ClaudeCodeModelReasoningByName\n ? ClaudeCodeModelReasoningByName[TModel]\n : never\n\n/** The models that take `--effort`. The same list as the Anthropic adapter's adaptive thinking. */\nconst EFFORT_MODELS =\n /^(opus|sonnet)$|opus-4-[6-9]|sonnet-4-[6-9]|opus-5|sonnet-5|fable-5/\n\n/**\n * The CLI settings for `chat({ reasoning })`, from the Claude Code docs:\n * - Claude 4.6 and later, and the `opus` and `sonnet` aliases:\n * `--effort <level>`.\n * - an older model (Haiku 4.5): `MAX_THINKING_TOKENS`, the budget (pi's\n * table when the request sets none), or `0` for `off`.\n */\nexport function claudeCodeReasoning(\n model: string,\n request: ReasoningRequest | undefined,\n): { args: Array<string>; env: Record<string, string> } {\n const resolved = resolveReasoning(request, CLAUDE_CODE_MODEL_REASONING[model])\n if (!resolved) return { args: [], env: {} }\n if (EFFORT_MODELS.test(model)) {\n return { args: ['--effort', resolved.value], env: {} }\n }\n const budget =\n resolved.level === 'off'\n ? 0\n : reasoningBudget({\n level: resolved.level,\n summary: resolved.summary,\n ...(resolved.budgetTokens !== undefined\n ? { budgetTokens: resolved.budgetTokens }\n : {}),\n })\n return { args: [], env: { MAX_THINKING_TOKENS: String(budget) } }\n}\n\nexport class ClaudeCodeTextAdapter<\n TModel extends ClaudeCodeModel,\n> extends BaseTextAdapter<\n TModel,\n ClaudeCodeTextProviderOptions,\n ReadonlyArray<Modality> & readonly ['text'],\n DefaultMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never,\n ResolveReasoning<TModel>\n> {\n readonly name = 'claude-code' as const\n\n // Harness adapter: requires a sandbox to run the agent CLI inside.\n override readonly requires = [SandboxCapability] as const\n\n private readonly adapterConfig: ClaudeCodeTextConfig\n\n /** Set after the first `toolChoice: 'required'` warning. */\n private warnedRequired = false\n\n constructor(config: ClaudeCodeTextConfig, model: TModel) {\n super({}, model)\n this.adapterConfig = config\n }\n\n private sandboxFrom(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): SandboxHandle {\n const ctx = options.capabilities\n if (!ctx) {\n throw new Error(\n 'Adapter \"claude-code\" requires a sandbox. Add withSandbox(defineSandbox({ ... })) ' +\n 'to chat() middleware (e.g. with the local-process or docker provider).',\n )\n }\n return getSandbox(ctx)\n }\n\n private workdir(options: TextOptions<ClaudeCodeTextProviderOptions>): string {\n return (\n options.modelOptions?.cwd ?? this.adapterConfig.cwd ?? DEFAULT_WORKDIR\n )\n }\n\n supportsCombinedToolsAndSchema(): boolean {\n return true\n }\n\n combinedStructuredOutputSource(): 'event' {\n return 'event'\n }\n\n /** Build the `claude` command line (prompt goes via stdin, not argv). */\n private buildArgv(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n resume: string | undefined,\n policyFlags: ClaudePolicyFlags,\n mcpConfigPath: string | undefined,\n permissionPromptTool: string | undefined,\n hasJsonSchema: boolean,\n ): Array<string> {\n const config = this.adapterConfig\n const modelOptions = options.modelOptions\n const exeParts = (config.claudeExecutable ?? 'claude').split(' ')\n // Claude only reads project-scoped config (CLAUDE.md, `.claude/skills`,\n // `.mcp.json`) with `project` in the sources. `user` is off by default so\n // a local-process run does not pull in the host's `~/.claude`.\n const settingSources = config.settingSources ?? ['project']\n\n // `--setting-sources` before `-p`. Do not pass `--bare`: that flag\n // skips stored `claude login` credentials and prints\n // \"Not logged in · Please run /login\" (claude-code#51047).\n // `-p` can take the next token as the prompt, so these flags stay first.\n const args: Array<string> = [\n ...exeParts,\n '--setting-sources',\n settingSources.join(','),\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--model',\n this.model,\n ]\n\n if (config.streamPartials !== false) args.push('--include-partial-messages')\n if (resume !== undefined) args.push('--resume', resume)\n args.push(...claudeCodeReasoning(this.model, options.reasoning).args)\n\n const permissionMode =\n modelOptions?.permissionMode ??\n config.permissionMode ??\n policyFlags.permissionMode ??\n 'bypassPermissions'\n args.push('--permission-mode', permissionMode)\n\n const maxTurns = modelOptions?.maxTurns ?? config.maxTurns\n if (maxTurns !== undefined) args.push('--max-turns', String(maxTurns))\n\n for (const dir of config.addDirs ?? []) args.push('--add-dir', dir)\n\n const allowedTools = [\n ...(modelOptions?.allowedTools ?? config.allowedTools ?? []),\n ...policyFlags.allowedTools,\n ]\n if (allowedTools.length > 0) {\n args.push('--allowedTools', [...new Set(allowedTools)].join(','))\n }\n const disallowedTools = [\n ...(modelOptions?.disallowedTools ?? config.disallowedTools ?? []),\n ...policyFlags.disallowedTools,\n ]\n if (disallowedTools.length > 0) {\n args.push('--disallowedTools', [...new Set(disallowedTools)].join(','))\n }\n // `'none'` and a named tool: `--tools ''` turns off every built-in tool,\n // and `--strict-mcp-config` keeps only the bridge, which then has no\n // chat() tool or only the named one (see `toolsForChoice`).\n const toolChoice = options.toolChoice\n if (toolChoice === 'none' || typeof toolChoice === 'object') {\n args.push('--tools', '', '--strict-mcp-config')\n }\n\n const systemPrompts = normalizeSystemPrompts(options.systemPrompts)\n .map((prompt) => prompt.content)\n .filter((content) => content.trim() !== '')\n if (systemPrompts.length > 0) {\n const joined = systemPrompts.join('\\n\\n')\n const flag =\n config.systemPromptMode === 'replace'\n ? '--system-prompt'\n : '--append-system-prompt'\n args.push(flag, joined)\n }\n\n if (mcpConfigPath !== undefined) args.push('--mcp-config', mcpConfigPath)\n if (hasJsonSchema) {\n args.push('--json-schema', CLAUDE_JSON_SCHEMA_PLACEHOLDER)\n }\n if (permissionPromptTool !== undefined) {\n args.push('--permission-prompt-tool', permissionPromptTool)\n }\n\n return args\n }\n\n /**\n * Build the permission-prompt resolver the host MCP bridge exposes to claude\n * (`--permission-prompt-tool`). Maps claude's permission request onto the\n * sandbox policy + client approvals; on an `ask` action with no decision yet,\n * records an approval-requested event and denies (the client re-runs to grant).\n */\n private buildPermissionResolver(\n policy: SandboxPolicy | undefined,\n approvals: ReadonlyMap<string, boolean> | undefined,\n scripts: Record<string, string> | undefined,\n sink: Array<AdapterYieldChunk>,\n threadId: string,\n runId: string,\n ): (input: { tool_name?: string; input?: unknown }) => PermissionToolResult {\n const writeTools = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])\n const networkTools = new Set(['WebFetch', 'WebSearch'])\n return (request) => {\n const toolName = request.tool_name ?? 'tool'\n const cmdInput = request.input\n const command =\n toolName === 'Bash' &&\n cmdInput !== null &&\n typeof cmdInput === 'object' &&\n 'command' in cmdInput &&\n typeof (cmdInput as { command?: unknown }).command === 'string'\n ? (cmdInput as { command: string }).command\n : undefined\n const capability = writeTools.has(toolName)\n ? 'fileWrite'\n : networkTools.has(toolName)\n ? 'network'\n : undefined\n const id = approvalId({\n provider: 'claude-code',\n kind: command !== undefined ? 'command' : (capability ?? 'tool'),\n target: command ?? toolName,\n })\n const outcome = resolveApproval({\n policy,\n approvals,\n id,\n scripts,\n ...(command !== undefined ? { command } : {}),\n ...(capability !== undefined ? { capability } : {}),\n })\n if (outcome.needsApproval) {\n sink.push(\n buildApprovalRequestedEvent({\n approvalId: id,\n title: `Approve ${toolName}${command !== undefined ? `: ${command}` : ''}`,\n threadId,\n runId,\n detail: { provider: 'claude-code', toolName },\n }),\n )\n return {\n behavior: 'deny',\n message:\n 'Awaiting client approval. Approve in the UI and re-run to continue.',\n }\n }\n return outcome.decision === 'allow'\n ? { behavior: 'allow' }\n : { behavior: 'deny', message: 'Denied by sandbox policy.' }\n }\n }\n\n async *chatStream(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { logger } = options\n let bridge: HostToolBridge | undefined\n let channel: BridgeEventChannel | undefined\n const approvalRequests: Array<AdapterYieldChunk> = []\n // Temp files written for the run (bridge MCP config, redirected prompt) that\n // carry the bearer token / prompt; removed in `finally` so they don't linger\n // in the sandbox after the run.\n let cleanupSandbox: SandboxHandle | undefined\n const tempFiles: Array<string> = []\n try {\n // Claude Code cannot force a tool call.\n if (options.toolChoice === 'required' && !this.warnedRequired) {\n this.warnedRequired = true\n logger.warn(\n \"claude-code: toolChoice 'required' is not supported. The agent decides which tools to call.\",\n )\n }\n const sandbox = this.sandboxFrom(options)\n cleanupSandbox = sandbox\n const cwd = this.workdir(options)\n\n // Durability comes from `withSandbox(sandbox, { runs, durability })`, read\n // back off the capability bus. Absent it, everything below resolves to\n // exactly today's behavior (no journal option, no alignment, and a\n // generated `runId` when the caller didn't supply one).\n const durability = options.capabilities\n ? getSandboxDurability(options.capabilities, { optional: true })\n : undefined\n // The journaled path below derives its journal path and its\n // message-id generator from `runId`. A resuming host must recompute\n // the same `runId` to find the same journal file and reproduce the\n // same translated ids — that's only possible when the caller supplies\n // `runId` explicitly. `resolveDurableRunId` enforces that loudly (via\n // `DurableRunIdRequiredError`) whenever durability is wired, and falls\n // back to a fresh `this.generateId()` otherwise, preserving today's\n // behavior for non-durable runs.\n const runId = resolveDurableRunId(options.runId, {\n durable: durability !== undefined,\n adapter: 'claude-code',\n fallback: () => this.generateId(),\n })\n const threadId = options.threadId\n // Surfaces custom events from bridged tools (e.g. code mode console logs)\n // on this run's live output stream.\n channel = createBridgeEventChannel({ model: this.model, threadId, runId })\n\n // Idempotently project workspace skills/plugins/MCP into the sandbox in\n // claude's native format (guarded by the projection marker file).\n const projection = options.capabilities\n ? getWorkspaceProjection(options.capabilities, { optional: true })\n : undefined\n if (projection) await projectClaudeWorkspace(sandbox, projection)\n\n const policy = options.capabilities\n ? getSandboxPolicy(options.capabilities, { optional: true })\n : undefined\n\n // A permission-prompt tool gates the agent's native tools when a policy\n // can `ask`/`deny` (interactive approvals).\n const permission =\n policy !== undefined\n ? {\n toolName: 'approval_prompt',\n resolve: this.buildPermissionResolver(\n policy,\n options.approvals,\n projection?.scripts,\n approvalRequests,\n threadId,\n runId,\n ),\n }\n : undefined\n\n // Bridge chat()-provided server tools (and/or the permission tool) into\n // the sandbox over MCP.\n const tools = toolsForChoice(options)\n if (tools.length > 0 || permission !== undefined) {\n const provisioner =\n (options.capabilities\n ? getToolBridgeProvisioner(options.capabilities, { optional: true })\n : undefined) ?? nodeHttpBridgeProvisioner\n bridge = await provisioner.provision(tools, {\n provider: sandbox.provider,\n threadId,\n context: options.context,\n emitCustomEvent: channel.emitCustomEvent,\n ...(permission !== undefined ? { permission } : {}),\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : {}),\n })\n }\n\n const built = buildPrompt(\n options.messages,\n options.modelOptions?.sessionId,\n )\n const resume = built.resume\n const prompt =\n options.outputSchema !== undefined\n ? appendOutputSchemaInstruction(built.prompt, options.outputSchema)\n : built.prompt\n // Both files below name themselves after `runId`, and durability makes\n // `runId` CALLER-chosen. Raw, a `/` in it would silently turn each basename\n // into a nested path (writing outside the intended directory, or failing on\n // one that does not exist), `..` would climb out of that directory, and a\n // long id would fail the spawn with `ENAMETOOLONG`. `encodeRunId` collapses\n // any id to one bounded, injective path segment — the same encoder\n // `journalPaths` uses, so these files and the journal agree on how a given\n // id spells. Computed once so the two filenames cannot drift apart.\n const runIdSegment = encodeRunId(runId)\n\n // The bridge MCP config carries the per-run bearer token. Write it to a\n // file and pass claude the PATH, so the token never appears in argv (where\n // any process in the sandbox could read it via `ps` / `/proc/<pid>/cmdline`).\n let mcpConfigArg: string | undefined\n if (bridge) {\n // Pass claude a path RELATIVE to its cwd (the real workdir the handle\n // runs the process in). An absolute VIRTUAL path like `/workspace/…` is\n // wrong wherever claude runs outside a sandbox that literally uses\n // `/workspace` — e.g. local-process on Windows, where git-bash resolves\n // `/workspace` to `C:\\Program Files\\Git\\workspace` and the file is \"not\n // found\". The bare filename resolves correctly on every provider.\n const mcpConfigFile = `.tanstack-mcp-bridge-${runIdSegment}.json`\n const mcpConfigPath = `${cwd}/${mcpConfigFile}`\n await sandbox.fs.write(mcpConfigPath, bridgeToMcpConfig(bridge))\n tempFiles.push(mcpConfigPath)\n mcpConfigArg = mcpConfigFile\n }\n let jsonSchemaFile: string | undefined\n if (options.outputSchema !== undefined) {\n jsonSchemaFile = `tanstack-output-schema-${runIdSegment}.json`\n const schemaPath = `${cwd}/${jsonSchemaFile}`\n await sandbox.fs.write(schemaPath, JSON.stringify(options.outputSchema))\n tempFiles.push(schemaPath)\n }\n const runnerFile = `tanstack-claude-run-${runIdSegment}.mjs`\n await sandbox.fs.write(`${cwd}/${runnerFile}`, CLAUDE_RUNNER_SOURCE)\n tempFiles.push(`${cwd}/${runnerFile}`)\n const argv = this.buildArgv(\n options,\n resume,\n mapPolicyToClaudeFlags(policy),\n mcpConfigArg,\n bridge && permission\n ? `mcp__${bridge.name}__${permission.toolName}`\n : undefined,\n jsonSchemaFile !== undefined,\n )\n // Filenames only on the shell line. JSON (schema, system prompt, MCP\n // config path) lives in the argv file so git-bash cannot retokenize it.\n const argvFile = `tanstack-claude-argv-${runIdSegment}.json`\n await sandbox.fs.write(`${cwd}/${argvFile}`, JSON.stringify(argv))\n tempFiles.push(`${cwd}/${argvFile}`)\n const command =\n jsonSchemaFile === undefined\n ? `node ${q(runnerFile)} ${q(argvFile)}`\n : `node ${q(runnerFile)} ${q(argvFile)} ${q(jsonSchemaFile)}`\n\n // Deliver the prompt. The default feeds it over stdin (keeps it out of\n // argv). Providers without a writable host→process stdin (e.g. Cloudflare)\n // can't accept that write, so write the prompt to a file and redirect the\n // CLI's stdin from it in-shell (`claude -p … < file`) — still out of argv.\n let runCommand = command\n let stdinInput: string | undefined = prompt\n if (sandbox.capabilities.writableStdin === false) {\n const promptPath = `/tmp/tanstack-claude-prompt-${runIdSegment}`\n await sandbox.fs.write(promptPath, prompt)\n tempFiles.push(promptPath)\n runCommand = `${command} < ${q(promptPath)}`\n stdinInput = undefined\n }\n\n logger.request(\n `activity=chat provider=claude-code model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,\n { provider: 'claude-code', model: this.model },\n )\n\n const authMode =\n options.modelOptions?.authMode ??\n this.adapterConfig.authMode ??\n 'api-key'\n const injectApiKey = authMode === 'api-key'\n\n const journalOptions = journalOptionsFor(durability, runId)\n const rawEvents = spawnNdjson(sandbox, runCommand, {\n cwd,\n ...(stdinInput !== undefined ? { input: stdinInput } : {}),\n // Isolated sandboxes often run as root. Claude refuses\n // `--dangerously-skip-permissions` as root unless IS_SANDBOX=1.\n // CLAUDE_CODE_SANDBOXED marks a real isolation boundary. Do not set\n // either on local-process: that provider runs on the host.\n env: {\n ...(sandbox.provider === 'local-process'\n ? {}\n : {\n IS_SANDBOX: '1',\n CLAUDE_CODE_SANDBOXED: '1',\n }),\n ...(injectApiKey ? hostClaudeAuthEnv() : {}),\n ...localProcessHomeEnv(sandbox.provider),\n ...claudeCodeReasoning(this.model, options.reasoning).env,\n ...this.adapterConfig.env,\n },\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : options.request?.signal\n ? { signal: options.request.signal }\n : {}),\n onNonJsonLine: (line) =>\n logger.provider(`provider=claude-code non-json line: ${line}`, {\n chunk: line,\n }),\n // Journal + attach both come from the sandbox durability capability, so\n // the attach route configures takeover by passing `attach: true` to\n // `withSandbox` — `chat()` stays free of sandbox vocabulary. Omitted\n // entirely (not passed as `undefined`) when the run isn't durable, so\n // `spawnNdjson` takes its original, unjournaled path byte-for-byte.\n ...(journalOptions === undefined ? {} : { journal: journalOptions }),\n })\n\n async function* asMessages(): AsyncIterable<AgentSdkMessage> {\n for await (const event of rawEvents) yield event as AgentSdkMessage\n }\n\n // `mergeChunkStreams` splices `channel.stream` (host-tool-bridge CUSTOM\n // events from LIVE tool execution) into the deterministic translator\n // output. Those events do not occur on a replay, so a takeover's replay is\n // NOT chunk-for-chunk identical to what the log holds. `alignedIfAttaching`\n // handles it: alignment skips stored out-of-band CUSTOM entries within a\n // bounded window (see `align.ts`), so a bridged-tool run can be taken over\n // without a spurious `JournalReplayDivergedError` — while a genuine\n // determinism regression still throws. The wrap goes OUTSIDE the merge:\n // the stored log holds the previous host's merged output, so aligning the\n // pre-merge translated stream alone would compare against a log it never\n // produced. On a non-attaching run this is a pure passthrough (see\n // `alignedIfAttaching`'s `attach` guard).\n yield* alignedIfAttaching(\n mergeChunkStreams(\n translateSdkStream(asMessages(), {\n model: this.model,\n runId,\n threadId,\n ...(options.parentRunId !== undefined && {\n parentRunId: options.parentRunId,\n }),\n // Deterministic on the journaled path: two translations of the same\n // journal prefix from a fresh generator seeded with the same\n // `runId` mint the same message ids (unlike `this.generateId()`,\n // which mixes in `Date.now()` / `Math.random()`). See\n // `createRunScopedIdGen` in `@tanstack/ai-sandbox`.\n genId: createRunScopedIdGen(runId),\n ...(options.outputSchema ? { expectStructuredOutput: true } : {}),\n onSdkMessage: (message) =>\n logger.provider(`provider=claude-code type=${message.type}`, {\n chunk: message,\n }),\n }),\n channel.stream,\n ),\n durability,\n logger,\n )\n\n // Surface the working-tree diff so UIs can render what the agent changed.\n if (this.adapterConfig.emitDiff !== false) {\n try {\n const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, {\n cwd,\n })\n if (diff.exitCode === 0 && diff.stdout.trim() !== '') {\n yield {\n type: EventType.CUSTOM,\n name: 'file.changed',\n value: { path: '.', diff: diff.stdout },\n timestamp: Date.now(),\n threadId,\n runId,\n }\n }\n } catch {\n // not a git repo / git unavailable — skip the diff event\n }\n }\n\n // Surface any pending approval requests (policy `ask` actions awaiting a\n // client decision); the client approves and re-runs to continue.\n for (const event of approvalRequests) yield event\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('claude-code.chatStream fatal', {\n error,\n source: 'claude-code.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n },\n }\n } finally {\n channel?.close()\n if (bridge) await bridge.close()\n // Remove the per-run token/prompt files. Best-effort: a cleanup failure\n // must not mask the run's own outcome.\n if (cleanupSandbox) {\n for (const path of tempFiles) {\n try {\n await cleanupSandbox.fs.remove(path)\n } catch {\n // file already gone / sandbox torn down — nothing to clean up\n }\n }\n }\n }\n }\n\n structuredOutput(\n _options: StructuredOutputOptions<ClaudeCodeTextProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n return Promise.reject(\n new Error(\n 'This harness honors outputSchema on chat() in the same turn. ' +\n 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',\n ),\n )\n }\n}\n\n/**\n * Creates a Claude Code harness adapter that runs **inside a sandbox**.\n *\n * Unlike HTTP provider adapters, this is a *harness* adapter: it spawns the\n * `claude` CLI inside the sandbox provided by `withSandbox(...)` (the adapter\n * declares `requires: [SandboxCapability]`), streams its `stream-json` stdout\n * back as AG-UI events, and lets Claude Code run its own agent loop and native\n * tools (Bash, file edits, search, …) against the sandbox workspace. The\n * sandbox image must provide the `claude` executable and `ANTHROPIC_API_KEY`\n * in its environment (e.g. via `workspace.secrets`). The session id is\n * surfaced via a CUSTOM `claude-code.session-id` event so follow-up calls can\n * resume through `modelOptions.sessionId`.\n */\nexport function claudeCodeText<TModel extends ClaudeCodeModel>(\n model: TModel,\n config: ClaudeCodeTextConfig = {},\n): ClaudeCodeTextAdapter<TModel> {\n return new ClaudeCodeTextAdapter(config, model)\n}\n"],"mappings":";;;;;;;;;;;AAwEA,IAAM,kBAAkB;;AAqDxB,SAAS,EAAE,OAAuB;CAChC,OAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,EAAE;AAC1C;;AAGA,SAAS,oBAA4C;CACnD,MAAM,MAA8B,CAAC;CACrC,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,QAAQ,IAAI,oBAAoB;CACpC,MAAM,YAAY,QAAQ,IAAI;CAC9B,IAAI,WAAW,IAAI,uBAAuB;CAC1C,OAAO;AACT;;;;;AAMA,SAAS,oBAAoB,UAA0C;CACrE,IAAI,aAAa,iBAAiB,OAAO,CAAC;CAC1C,IAAI,QAAQ,IAAI,MAAM,OAAO,CAAC;CAC9B,MAAM,OAAO,QAAQ,IAAI;CACzB,OAAO,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAClC;;;;;AAMA,SAAS,eAAe,SAAqD;CAC3E,MAAM,EAAE,Y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;GACvB,MAAM,MAAM;GACZ,MAAM,WAAW,mBAAmB,KAAK;GACzC,OAAO,OAAO,gCAAgC;IAC5C;IACA,QAAQ;GACV,CAAC;GACD,MAAM;IACJ,MAAM,UAAU;IAChB,OAAO,QAAQ;IACf,WAAW,KAAK,IAAI;IACpB,SAAS,IAAI,WAAW;IACxB,GAAI,IAAI,SAAS,KAAA,KAAa,EAAE,MAAM,IAAI,KAAK;IAC/C,GAAI,aAAa,KAAA,KAAa,EAAE,SAAS;IACzC,OAAO;KACL,SAAS,IAAI,WAAW;KACxB,GAAI,IAAI,SAAS,KAAA,KAAa,EAAE,MAAM,IAAI,KAAK;IACjD;GACF;EACF,UAAU;GACR,SAAS,MAAM;GACf,IAAI,QAAQ,MAAM,OAAO,MAAM;GAG/B,IAAI,gBACF,KAAK,MAAM,QAAQ,WACjB,IAAI;IACF,MAAM,eAAe,GAAG,OAAO,IAAI;GACrC,QAAQ,CAER;EAGN;CACF;CAEA,iBACE,UAC0C;EAC1C,OAAO,QAAQ,uBACb,IAAI,MACF,0IAEF,CACF;CACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,eACd,OACA,SAA+B,CAAC,GACD;CAC/B,OAAO,IAAI,sBAAsB,QAAQ,KAAK;AAChD"}
@@ -153,7 +153,6 @@ async function* translateSdkStream(sdkMessages, ctx) {
153
153
  type: EventType.TOOL_CALL_END,
154
154
  toolCallId: toolCall.id,
155
155
  toolCallName: toolCall.name,
156
- toolName: toolCall.name,
157
156
  model,
158
157
  timestamp: now(),
159
158
  input
@@ -194,7 +193,6 @@ async function* translateSdkStream(sdkMessages, ctx) {
194
193
  type: EventType.TOOL_CALL_START,
195
194
  toolCallId: block.id,
196
195
  toolCallName,
197
- toolName: toolCallName,
198
196
  model,
199
197
  timestamp: now()
200
198
  };
@@ -210,7 +208,6 @@ async function* translateSdkStream(sdkMessages, ctx) {
210
208
  type: EventType.TOOL_CALL_END,
211
209
  toolCallId: block.id,
212
210
  toolCallName,
213
- toolName: toolCallName,
214
211
  model,
215
212
  timestamp: now(),
216
213
  input: block.input ?? {}
@@ -418,7 +415,6 @@ async function* translateSdkStream(sdkMessages, ctx) {
418
415
  type: EventType.TOOL_CALL_START,
419
416
  toolCallId: block.id,
420
417
  toolCallName: name,
421
- toolName: name,
422
418
  model,
423
419
  timestamp: now(),
424
420
  ...partialMessageId !== null && { parentMessageId: partialMessageId }
@@ -1 +1 @@
1
- {"version":3,"file":"translate.js","names":[],"sources":["../../../src/stream/translate.ts"],"sourcesContent":["import { EventType, buildBaseUsage } from '@tanstack/ai'\nimport {\n parseJsonFromAssistantText,\n structuredOutputCompleteChunk,\n structuredOutputStartChunk,\n} from '@tanstack/ai/adapter-internals'\nimport type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'\nimport type {\n AgentSdkMessage,\n SdkAssistantMessage,\n SdkPartialAssistantMessage,\n SdkResultMessage,\n SdkToolResultContent,\n SdkUsage,\n SdkUserMessage,\n} from './sdk-types'\n\n/** Name of the CUSTOM event carrying the Claude Code session id. */\nexport const SESSION_ID_EVENT = 'claude-code.session-id'\n\n/** Server name used for bridged TanStack tools (model sees `mcp__tanstack__<name>`). */\nexport const BRIDGED_MCP_SERVER_NAME = 'tanstack'\n\nconst BRIDGED_MCP_PREFIX = `mcp__${BRIDGED_MCP_SERVER_NAME}__`\n\n/**\n * Claude Code `--json-schema` injects a fake tool named StructuredOutput.\n * The model \"calls\" it with the schema JSON. The result message may omit\n * `structured_output`; harvest the tool input in that case.\n */\nexport const SYNTHETIC_STRUCTURED_OUTPUT_TOOL = 'StructuredOutput'\n\n/** Claude Code-specific usage details attached to RUN_FINISHED usage. */\nexport type ClaudeCodeProviderUsageDetails = {\n /** Total cost of the harness run in USD, as reported by Claude Code. */\n totalCostUsd?: number\n}\n\nexport interface TranslateContext {\n model: string\n runId: string\n threadId: string\n parentRunId?: string\n genId: () => string\n /** Called as soon as the harness reports its session id. */\n onSessionId?: (sessionId: string) => void\n /** Called for each raw SDK message, for logging. */\n onSdkMessage?: (message: AgentSdkMessage) => void\n /** Emit structured-output events from `result.structured_output`. */\n expectStructuredOutput?: boolean\n}\n\n/**\n * Strip the bridged MCP server prefix so tool-call events match the TanStack\n * tool names the application registered. Built-in harness tools (Bash, Read,\n * Edit, ...) and foreign MCP tools pass through verbatim.\n */\nexport function stripMcpPrefix(name: string): string {\n return name.startsWith(BRIDGED_MCP_PREFIX)\n ? name.slice(BRIDGED_MCP_PREFIX.length)\n : name\n}\n\nfunction isUsefulStructuredObject(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length > 0\n )\n}\n\nfunction rememberStructuredOutput(current: unknown, next: unknown): unknown {\n return isUsefulStructuredObject(next) ? next : current\n}\n\nfunction stringifyToolResultContent(\n content: SdkToolResultContent | undefined,\n): string {\n if (content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .map((block) => (typeof block.text === 'string' ? block.text : ''))\n .join('')\n}\n\nfunction buildUsage(\n usage: SdkUsage | undefined,\n totalCostUsd: number | undefined,\n): TokenUsage<ClaudeCodeProviderUsageDetails> | undefined {\n if (!usage) return undefined\n const cacheWrite = usage.cache_creation_input_tokens ?? 0\n const cacheRead = usage.cache_read_input_tokens ?? 0\n // `input_tokens` counts only the uncached input. Add the cache reads and\n // writes so promptTokens is the total input, the same as other providers.\n const promptTokens = (usage.input_tokens ?? 0) + cacheRead + cacheWrite\n const completionTokens = usage.output_tokens ?? 0\n const result = buildBaseUsage<ClaudeCodeProviderUsageDetails>({\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n })\n const promptTokensDetails = {\n ...(cacheWrite ? { cacheWriteTokens: cacheWrite } : {}),\n ...(cacheRead ? { cachedTokens: cacheRead } : {}),\n }\n if (Object.keys(promptTokensDetails).length > 0) {\n result.promptTokensDetails = promptTokensDetails\n }\n if (totalCostUsd !== undefined) {\n result.providerUsageDetails = { totalCostUsd }\n }\n return result\n}\n\n/**\n * Translate a Claude Code Agent SDK message stream into AG-UI StreamChunk\n * events.\n *\n * The harness runs its own agent loop and executes its own tools, so the\n * translation always ends with `finishReason: 'stop'` (or `'length'` /\n * RUN_ERROR) — never `'tool_calls'`. Harness tool activity is emitted as\n * already-resolved TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so\n * UIs can render it, while the TanStack engine never tries to execute them.\n *\n * Invariant: every TOOL_CALL_START is eventually paired with a\n * TOOL_CALL_RESULT (synthesized as `{\"status\":\"interrupted\"}` when the run\n * ends or aborts before the harness reported one) so the engine's\n * pending-tool-call scan on the next request never force-executes them.\n */\nexport async function* translateSdkStream(\n sdkMessages: AsyncIterable<AgentSdkMessage>,\n ctx: TranslateContext,\n): AsyncIterable<AdapterYieldChunk> {\n const { model, runId, threadId, genId } = ctx\n const now = () => Date.now()\n\n let runStarted = false\n /** Tool calls started but with no result yet. */\n const unresolvedToolCalls = new Set<string>()\n const syntheticOutputToolIds = new Set<string>()\n let capturedStructuredOutput: unknown\n let assistantTextForHarvest = ''\n let partialStructuredJson = ''\n let partialIsStructuredOutput = false\n /** Anthropic message ids whose text/thinking already streamed via partials. */\n const streamedMessageIds = new Set<string>()\n /** Tool-call ids already streamed via partials, so the complete message dedupes them. */\n const streamedToolCallIds = new Set<string>()\n\n // Partial-stream state\n let partialMessageId: string | null = null\n const partialBlockTypes = new Map<number, string>()\n let partialTextMessageId: string | null = null\n let partialTextContent = ''\n let partialTextStarted = false\n let partialReasoningId: string | null = null\n const partialToolCalls = new Map<\n number,\n { id: string; name: string; args: string }\n >()\n\n function* startRun(): Generator<AdapterYieldChunk> {\n if (runStarted) return\n runStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: now(),\n ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),\n }\n }\n\n function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {\n for (const toolCallId of unresolvedToolCalls) {\n yield {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: genId(),\n model,\n timestamp: now(),\n content: JSON.stringify({ status: 'interrupted' }),\n }\n }\n unresolvedToolCalls.clear()\n }\n\n function* closePartialText(): Generator<AdapterYieldChunk> {\n if (partialTextStarted && partialTextMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n }\n }\n partialTextStarted = false\n partialTextMessageId = null\n partialTextContent = ''\n }\n\n function* closePartialReasoning(): Generator<AdapterYieldChunk> {\n if (partialReasoningId) {\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n }\n partialReasoningId = null\n }\n\n function* closePartialToolUse(\n index: number,\n interrupted = false,\n ): Generator<AdapterYieldChunk> {\n const toolCall = partialToolCalls.get(index)\n if (toolCall) {\n let input: unknown = {}\n try {\n const parsed = toolCall.args ? JSON.parse(toolCall.args) : {}\n input = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (error) {\n if (!interrupted) throw error\n }\n partialToolCalls.delete(index)\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model,\n timestamp: now(),\n input,\n }\n unresolvedToolCalls.add(toolCall.id)\n }\n }\n\n function* closePartialToolUses(\n interrupted = false,\n ): Generator<AdapterYieldChunk> {\n for (const index of [...partialToolCalls.keys()]) {\n yield* closePartialToolUse(index, interrupted)\n }\n }\n\n function* emitStructuredOutput(\n object: unknown,\n ): Generator<AdapterYieldChunk> {\n const raw = JSON.stringify(object)\n const messageId = genId()\n yield structuredOutputStartChunk({\n messageId,\n model,\n threadId,\n runId,\n })\n yield structuredOutputCompleteChunk({\n messageId,\n model,\n threadId,\n runId,\n object,\n raw,\n })\n }\n\n function* emitToolUse(block: {\n id: string\n name: string\n input: unknown\n }): Generator<AdapterYieldChunk> {\n const toolCallName = stripMcpPrefix(block.name)\n if (\n ctx.expectStructuredOutput === true &&\n toolCallName === SYNTHETIC_STRUCTURED_OUTPUT_TOOL\n ) {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n block.input,\n )\n syntheticOutputToolIds.add(block.id)\n return\n }\n const args = JSON.stringify(block.input ?? {})\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: block.id,\n toolCallName,\n toolName: toolCallName,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: block.id,\n model,\n timestamp: now(),\n delta: args,\n args,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: block.id,\n toolCallName,\n toolName: toolCallName,\n model,\n timestamp: now(),\n input: block.input ?? {},\n }\n unresolvedToolCalls.add(block.id)\n }\n\n function* handleAssistant(\n message: SdkAssistantMessage,\n ): Generator<AdapterYieldChunk> {\n const alreadyStreamed =\n message.message.id !== undefined &&\n streamedMessageIds.has(message.message.id)\n\n for (const block of message.message.content) {\n if (block.type === 'text') {\n if (alreadyStreamed) continue\n const messageId = message.message.id ?? genId()\n const text = (block as { text: string }).text\n if (!alreadyStreamed) assistantTextForHarvest += text\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: now(),\n role: 'assistant',\n }\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: now(),\n delta: text,\n content: text,\n }\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: now(),\n }\n } else if (block.type === 'thinking') {\n if (alreadyStreamed) continue\n const reasoningId = genId()\n const thinking = (block as { thinking: string }).thinking\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningId,\n role: 'reasoning' as const,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningId,\n delta: thinking,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n } else if (block.type === 'tool_use') {\n const toolBlock = block as { id: string; name: string; input: unknown }\n // Skip the tool call if the partial stream already emitted it.\n if (streamedToolCallIds.has(toolBlock.id)) continue\n yield* emitToolUse(toolBlock)\n }\n }\n }\n\n function* handleUser(message: SdkUserMessage): Generator<AdapterYieldChunk> {\n const content = message.message.content\n if (typeof content === 'string') return\n for (const block of content) {\n if (block.type !== 'tool_result') continue\n const toolResult = block as {\n tool_use_id: string\n content?: SdkToolResultContent\n is_error?: boolean\n }\n if (syntheticOutputToolIds.has(toolResult.tool_use_id)) {\n syntheticOutputToolIds.delete(toolResult.tool_use_id)\n continue\n }\n unresolvedToolCalls.delete(toolResult.tool_use_id)\n yield {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId: toolResult.tool_use_id,\n messageId: genId(),\n model,\n timestamp: now(),\n content: stringifyToolResultContent(toolResult.content),\n ...(toolResult.is_error === true && { state: 'output-error' as const }),\n }\n }\n }\n\n function* handleResult(\n message: SdkResultMessage,\n ): Generator<AdapterYieldChunk> {\n yield* closePartialText()\n yield* closePartialReasoning()\n yield* closePartialToolUses()\n yield* synthesizeUnresolvedResults()\n\n const usage = buildUsage(message.usage, message.total_cost_usd)\n if (ctx.expectStructuredOutput === true) {\n const fromResult = isUsefulStructuredObject(message.structured_output)\n ? message.structured_output\n : undefined\n const fromTool = isUsefulStructuredObject(capturedStructuredOutput)\n ? capturedStructuredOutput\n : undefined\n let fromText: unknown\n if (fromResult === undefined && fromTool === undefined) {\n const raw = assistantTextForHarvest || message.result || ''\n if (raw.trim() !== '') {\n try {\n fromText = parseJsonFromAssistantText(raw)\n } catch {\n fromText = undefined\n }\n }\n }\n const object = fromResult ?? fromTool ?? fromText\n if (isUsefulStructuredObject(object)) {\n yield* emitStructuredOutput(object)\n }\n }\n if (message.subtype === 'success') {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: now(),\n finishReason: 'stop',\n ...(usage !== undefined && { usage }),\n }\n } else if (message.subtype === 'error_max_turns') {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: now(),\n finishReason: 'length',\n ...(usage !== undefined && { usage }),\n }\n } else {\n const errorMessage =\n message.errors && message.errors.length > 0\n ? message.errors.join('; ')\n : `Claude Code run failed: ${message.subtype}`\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: now(),\n message: errorMessage,\n code: message.subtype,\n error: { message: errorMessage, code: message.subtype },\n }\n }\n }\n\n function* handleStreamEvent(\n message: SdkPartialAssistantMessage,\n ): Generator<AdapterYieldChunk> {\n const event = message.event\n if (event.type === 'message_start') {\n partialMessageId = event.message.id ?? genId()\n streamedMessageIds.add(partialMessageId)\n } else if (event.type === 'content_block_start') {\n const block = event.content_block\n const partialBlockType = block.type\n partialBlockTypes.set(event.index, partialBlockType)\n partialIsStructuredOutput =\n ctx.expectStructuredOutput === true &&\n block.type === 'tool_use' &&\n block.name === SYNTHETIC_STRUCTURED_OUTPUT_TOOL\n if (partialIsStructuredOutput) {\n partialStructuredJson = ''\n if (typeof block.id === 'string') {\n syntheticOutputToolIds.add(block.id)\n }\n if ('input' in block) {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n block.input,\n )\n }\n }\n if (partialBlockType === 'text') {\n partialTextMessageId = partialMessageId ?? genId()\n partialTextContent = ''\n if (!partialTextStarted) {\n partialTextStarted = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n role: 'assistant',\n }\n }\n } else if (partialBlockType === 'thinking') {\n partialReasoningId = genId()\n yield {\n type: EventType.REASONING_START,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: partialReasoningId,\n role: 'reasoning' as const,\n model,\n timestamp: now(),\n }\n } else if (\n partialBlockType === 'tool_use' &&\n !partialIsStructuredOutput &&\n typeof block.id === 'string' &&\n typeof block.name === 'string'\n ) {\n const name = stripMcpPrefix(block.name)\n partialToolCalls.set(event.index, { id: block.id, name, args: '' })\n streamedToolCallIds.add(block.id)\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: block.id,\n toolCallName: name,\n toolName: name,\n model,\n timestamp: now(),\n ...(partialMessageId !== null && {\n parentMessageId: partialMessageId,\n }),\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (\n event.delta.type === 'text_delta' &&\n partialTextStarted &&\n partialTextMessageId &&\n typeof event.delta.text === 'string'\n ) {\n partialTextContent += event.delta.text\n assistantTextForHarvest += event.delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n delta: event.delta.text,\n content: partialTextContent,\n }\n } else if (\n event.delta.type === 'input_json_delta' &&\n partialIsStructuredOutput &&\n typeof event.delta.partial_json === 'string'\n ) {\n partialStructuredJson += event.delta.partial_json\n } else if (\n event.delta.type === 'thinking_delta' &&\n partialReasoningId &&\n typeof event.delta.thinking === 'string'\n ) {\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: partialReasoningId,\n delta: event.delta.thinking,\n model,\n timestamp: now(),\n }\n } else if (\n event.delta.type === 'input_json_delta' &&\n typeof event.delta.partial_json === 'string'\n ) {\n const toolCall = partialToolCalls.get(event.index)\n if (toolCall) {\n toolCall.args += event.delta.partial_json\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: toolCall.id,\n model,\n timestamp: now(),\n delta: event.delta.partial_json,\n }\n }\n }\n } else if (event.type === 'content_block_stop') {\n const partialBlockType = partialBlockTypes.get(event.index)\n partialBlockTypes.delete(event.index)\n if (partialIsStructuredOutput && partialStructuredJson !== '') {\n try {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n JSON.parse(partialStructuredJson),\n )\n } catch {\n // Incomplete JSON; the complete assistant tool_use may still arrive.\n }\n }\n if (partialBlockType === 'text') {\n yield* closePartialText()\n } else if (partialBlockType === 'thinking') {\n yield* closePartialReasoning()\n } else if (partialBlockType === 'tool_use') {\n yield* closePartialToolUse(event.index)\n }\n partialIsStructuredOutput = false\n partialStructuredJson = ''\n }\n }\n\n try {\n for await (const sdkMessage of sdkMessages) {\n ctx.onSdkMessage?.(sdkMessage)\n\n if (sdkMessage.type === 'system' && sdkMessage.subtype === 'init') {\n yield* startRun()\n ctx.onSessionId?.(sdkMessage.session_id)\n yield {\n type: EventType.CUSTOM,\n model,\n timestamp: now(),\n name: SESSION_ID_EVENT,\n value: {\n sessionId: sdkMessage.session_id,\n model: sdkMessage.model,\n tools: sdkMessage.tools,\n skills: sdkMessage.skills ?? [],\n },\n }\n continue\n }\n\n // Anything before init still needs RUN_STARTED first.\n yield* startRun()\n\n if (sdkMessage.type === 'stream_event') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleStreamEvent(sdkMessage)\n } else if (sdkMessage.type === 'assistant') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleAssistant(sdkMessage)\n } else if (sdkMessage.type === 'user') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleUser(sdkMessage)\n } else if (sdkMessage.type === 'result') {\n yield* handleResult(sdkMessage)\n }\n // All other SDK message types (status, hooks, notifications, ...) are\n // harness-internal and intentionally ignored.\n }\n } catch (error) {\n // The run is dying (abort or SDK failure). Close any half-streamed tool\n // calls, then pair every started tool call with a synthetic result so the\n // next request's pending-tool-call scan doesn't try to execute them. Then\n // let the adapter surface the error as RUN_ERROR.\n yield* closePartialToolUses(true)\n yield* synthesizeUnresolvedResults()\n throw error\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,mBAAmB;;AAGhC,IAAa,0BAA0B;AAEvC,IAAM,qBAAqB,QAAQ,wBAAwB;;;;;;AAO3D,IA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C,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"translate.js","names":[],"sources":["../../../src/stream/translate.ts"],"sourcesContent":["import { EventType, buildBaseUsage } from '@tanstack/ai'\nimport {\n parseJsonFromAssistantText,\n structuredOutputCompleteChunk,\n structuredOutputStartChunk,\n} from '@tanstack/ai/adapter-internals'\nimport type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'\nimport type {\n AgentSdkMessage,\n SdkAssistantMessage,\n SdkPartialAssistantMessage,\n SdkResultMessage,\n SdkToolResultContent,\n SdkUsage,\n SdkUserMessage,\n} from './sdk-types'\n\n/** Name of the CUSTOM event carrying the Claude Code session id. */\nexport const SESSION_ID_EVENT = 'claude-code.session-id'\n\n/** Server name used for bridged TanStack tools (model sees `mcp__tanstack__<name>`). */\nexport const BRIDGED_MCP_SERVER_NAME = 'tanstack'\n\nconst BRIDGED_MCP_PREFIX = `mcp__${BRIDGED_MCP_SERVER_NAME}__`\n\n/**\n * Claude Code `--json-schema` injects a fake tool named StructuredOutput.\n * The model \"calls\" it with the schema JSON. The result message may omit\n * `structured_output`; harvest the tool input in that case.\n */\nexport const SYNTHETIC_STRUCTURED_OUTPUT_TOOL = 'StructuredOutput'\n\n/** Claude Code-specific usage details attached to RUN_FINISHED usage. */\nexport type ClaudeCodeProviderUsageDetails = {\n /** Total cost of the harness run in USD, as reported by Claude Code. */\n totalCostUsd?: number\n}\n\nexport interface TranslateContext {\n model: string\n runId: string\n threadId: string\n parentRunId?: string\n genId: () => string\n /** Called as soon as the harness reports its session id. */\n onSessionId?: (sessionId: string) => void\n /** Called for each raw SDK message, for logging. */\n onSdkMessage?: (message: AgentSdkMessage) => void\n /** Emit structured-output events from `result.structured_output`. */\n expectStructuredOutput?: boolean\n}\n\n/**\n * Strip the bridged MCP server prefix so tool-call events match the TanStack\n * tool names the application registered. Built-in harness tools (Bash, Read,\n * Edit, ...) and foreign MCP tools pass through verbatim.\n */\nexport function stripMcpPrefix(name: string): string {\n return name.startsWith(BRIDGED_MCP_PREFIX)\n ? name.slice(BRIDGED_MCP_PREFIX.length)\n : name\n}\n\nfunction isUsefulStructuredObject(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length > 0\n )\n}\n\nfunction rememberStructuredOutput(current: unknown, next: unknown): unknown {\n return isUsefulStructuredObject(next) ? next : current\n}\n\nfunction stringifyToolResultContent(\n content: SdkToolResultContent | undefined,\n): string {\n if (content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .map((block) => (typeof block.text === 'string' ? block.text : ''))\n .join('')\n}\n\nfunction buildUsage(\n usage: SdkUsage | undefined,\n totalCostUsd: number | undefined,\n): TokenUsage<ClaudeCodeProviderUsageDetails> | undefined {\n if (!usage) return undefined\n const cacheWrite = usage.cache_creation_input_tokens ?? 0\n const cacheRead = usage.cache_read_input_tokens ?? 0\n // `input_tokens` counts only the uncached input. Add the cache reads and\n // writes so promptTokens is the total input, the same as other providers.\n const promptTokens = (usage.input_tokens ?? 0) + cacheRead + cacheWrite\n const completionTokens = usage.output_tokens ?? 0\n const result = buildBaseUsage<ClaudeCodeProviderUsageDetails>({\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n })\n const promptTokensDetails = {\n ...(cacheWrite ? { cacheWriteTokens: cacheWrite } : {}),\n ...(cacheRead ? { cachedTokens: cacheRead } : {}),\n }\n if (Object.keys(promptTokensDetails).length > 0) {\n result.promptTokensDetails = promptTokensDetails\n }\n if (totalCostUsd !== undefined) {\n result.providerUsageDetails = { totalCostUsd }\n }\n return result\n}\n\n/**\n * Translate a Claude Code Agent SDK message stream into AG-UI StreamChunk\n * events.\n *\n * The harness runs its own agent loop and executes its own tools, so the\n * translation always ends with `finishReason: 'stop'` (or `'length'` /\n * RUN_ERROR) — never `'tool_calls'`. Harness tool activity is emitted as\n * already-resolved TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so\n * UIs can render it, while the TanStack engine never tries to execute them.\n *\n * Invariant: every TOOL_CALL_START is eventually paired with a\n * TOOL_CALL_RESULT (synthesized as `{\"status\":\"interrupted\"}` when the run\n * ends or aborts before the harness reported one) so the engine's\n * pending-tool-call scan on the next request never force-executes them.\n */\nexport async function* translateSdkStream(\n sdkMessages: AsyncIterable<AgentSdkMessage>,\n ctx: TranslateContext,\n): AsyncIterable<AdapterYieldChunk> {\n const { model, runId, threadId, genId } = ctx\n const now = () => Date.now()\n\n let runStarted = false\n /** Tool calls started but with no result yet. */\n const unresolvedToolCalls = new Set<string>()\n const syntheticOutputToolIds = new Set<string>()\n let capturedStructuredOutput: unknown\n let assistantTextForHarvest = ''\n let partialStructuredJson = ''\n let partialIsStructuredOutput = false\n /** Anthropic message ids whose text/thinking already streamed via partials. */\n const streamedMessageIds = new Set<string>()\n /** Tool-call ids already streamed via partials, so the complete message dedupes them. */\n const streamedToolCallIds = new Set<string>()\n\n // Partial-stream state\n let partialMessageId: string | null = null\n const partialBlockTypes = new Map<number, string>()\n let partialTextMessageId: string | null = null\n let partialTextContent = ''\n let partialTextStarted = false\n let partialReasoningId: string | null = null\n const partialToolCalls = new Map<\n number,\n { id: string; name: string; args: string }\n >()\n\n function* startRun(): Generator<AdapterYieldChunk> {\n if (runStarted) return\n runStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp: now(),\n ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),\n }\n }\n\n function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {\n for (const toolCallId of unresolvedToolCalls) {\n yield {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: genId(),\n model,\n timestamp: now(),\n content: JSON.stringify({ status: 'interrupted' }),\n }\n }\n unresolvedToolCalls.clear()\n }\n\n function* closePartialText(): Generator<AdapterYieldChunk> {\n if (partialTextStarted && partialTextMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n }\n }\n partialTextStarted = false\n partialTextMessageId = null\n partialTextContent = ''\n }\n\n function* closePartialReasoning(): Generator<AdapterYieldChunk> {\n if (partialReasoningId) {\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n }\n partialReasoningId = null\n }\n\n function* closePartialToolUse(\n index: number,\n interrupted = false,\n ): Generator<AdapterYieldChunk> {\n const toolCall = partialToolCalls.get(index)\n if (toolCall) {\n let input: unknown = {}\n try {\n const parsed = toolCall.args ? JSON.parse(toolCall.args) : {}\n input = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (error) {\n if (!interrupted) throw error\n }\n partialToolCalls.delete(index)\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n model,\n timestamp: now(),\n input,\n }\n unresolvedToolCalls.add(toolCall.id)\n }\n }\n\n function* closePartialToolUses(\n interrupted = false,\n ): Generator<AdapterYieldChunk> {\n for (const index of [...partialToolCalls.keys()]) {\n yield* closePartialToolUse(index, interrupted)\n }\n }\n\n function* emitStructuredOutput(\n object: unknown,\n ): Generator<AdapterYieldChunk> {\n const raw = JSON.stringify(object)\n const messageId = genId()\n yield structuredOutputStartChunk({\n messageId,\n model,\n threadId,\n runId,\n })\n yield structuredOutputCompleteChunk({\n messageId,\n model,\n threadId,\n runId,\n object,\n raw,\n })\n }\n\n function* emitToolUse(block: {\n id: string\n name: string\n input: unknown\n }): Generator<AdapterYieldChunk> {\n const toolCallName = stripMcpPrefix(block.name)\n if (\n ctx.expectStructuredOutput === true &&\n toolCallName === SYNTHETIC_STRUCTURED_OUTPUT_TOOL\n ) {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n block.input,\n )\n syntheticOutputToolIds.add(block.id)\n return\n }\n const args = JSON.stringify(block.input ?? {})\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: block.id,\n toolCallName,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: block.id,\n model,\n timestamp: now(),\n delta: args,\n args,\n }\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: block.id,\n toolCallName,\n model,\n timestamp: now(),\n input: block.input ?? {},\n }\n unresolvedToolCalls.add(block.id)\n }\n\n function* handleAssistant(\n message: SdkAssistantMessage,\n ): Generator<AdapterYieldChunk> {\n const alreadyStreamed =\n message.message.id !== undefined &&\n streamedMessageIds.has(message.message.id)\n\n for (const block of message.message.content) {\n if (block.type === 'text') {\n if (alreadyStreamed) continue\n const messageId = message.message.id ?? genId()\n const text = (block as { text: string }).text\n if (!alreadyStreamed) assistantTextForHarvest += text\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp: now(),\n role: 'assistant',\n }\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp: now(),\n delta: text,\n content: text,\n }\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp: now(),\n }\n } else if (block.type === 'thinking') {\n if (alreadyStreamed) continue\n const reasoningId = genId()\n const thinking = (block as { thinking: string }).thinking\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningId,\n role: 'reasoning' as const,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningId,\n delta: thinking,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningId,\n model,\n timestamp: now(),\n }\n } else if (block.type === 'tool_use') {\n const toolBlock = block as { id: string; name: string; input: unknown }\n // Skip the tool call if the partial stream already emitted it.\n if (streamedToolCallIds.has(toolBlock.id)) continue\n yield* emitToolUse(toolBlock)\n }\n }\n }\n\n function* handleUser(message: SdkUserMessage): Generator<AdapterYieldChunk> {\n const content = message.message.content\n if (typeof content === 'string') return\n for (const block of content) {\n if (block.type !== 'tool_result') continue\n const toolResult = block as {\n tool_use_id: string\n content?: SdkToolResultContent\n is_error?: boolean\n }\n if (syntheticOutputToolIds.has(toolResult.tool_use_id)) {\n syntheticOutputToolIds.delete(toolResult.tool_use_id)\n continue\n }\n unresolvedToolCalls.delete(toolResult.tool_use_id)\n yield {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId: toolResult.tool_use_id,\n messageId: genId(),\n model,\n timestamp: now(),\n content: stringifyToolResultContent(toolResult.content),\n ...(toolResult.is_error === true && { state: 'output-error' as const }),\n }\n }\n }\n\n function* handleResult(\n message: SdkResultMessage,\n ): Generator<AdapterYieldChunk> {\n yield* closePartialText()\n yield* closePartialReasoning()\n yield* closePartialToolUses()\n yield* synthesizeUnresolvedResults()\n\n const usage = buildUsage(message.usage, message.total_cost_usd)\n if (ctx.expectStructuredOutput === true) {\n const fromResult = isUsefulStructuredObject(message.structured_output)\n ? message.structured_output\n : undefined\n const fromTool = isUsefulStructuredObject(capturedStructuredOutput)\n ? capturedStructuredOutput\n : undefined\n let fromText: unknown\n if (fromResult === undefined && fromTool === undefined) {\n const raw = assistantTextForHarvest || message.result || ''\n if (raw.trim() !== '') {\n try {\n fromText = parseJsonFromAssistantText(raw)\n } catch {\n fromText = undefined\n }\n }\n }\n const object = fromResult ?? fromTool ?? fromText\n if (isUsefulStructuredObject(object)) {\n yield* emitStructuredOutput(object)\n }\n }\n if (message.subtype === 'success') {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: now(),\n finishReason: 'stop',\n ...(usage !== undefined && { usage }),\n }\n } else if (message.subtype === 'error_max_turns') {\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp: now(),\n finishReason: 'length',\n ...(usage !== undefined && { usage }),\n }\n } else {\n const errorMessage =\n message.errors && message.errors.length > 0\n ? message.errors.join('; ')\n : `Claude Code run failed: ${message.subtype}`\n yield {\n type: EventType.RUN_ERROR,\n model,\n timestamp: now(),\n message: errorMessage,\n code: message.subtype,\n error: { message: errorMessage, code: message.subtype },\n }\n }\n }\n\n function* handleStreamEvent(\n message: SdkPartialAssistantMessage,\n ): Generator<AdapterYieldChunk> {\n const event = message.event\n if (event.type === 'message_start') {\n partialMessageId = event.message.id ?? genId()\n streamedMessageIds.add(partialMessageId)\n } else if (event.type === 'content_block_start') {\n const block = event.content_block\n const partialBlockType = block.type\n partialBlockTypes.set(event.index, partialBlockType)\n partialIsStructuredOutput =\n ctx.expectStructuredOutput === true &&\n block.type === 'tool_use' &&\n block.name === SYNTHETIC_STRUCTURED_OUTPUT_TOOL\n if (partialIsStructuredOutput) {\n partialStructuredJson = ''\n if (typeof block.id === 'string') {\n syntheticOutputToolIds.add(block.id)\n }\n if ('input' in block) {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n block.input,\n )\n }\n }\n if (partialBlockType === 'text') {\n partialTextMessageId = partialMessageId ?? genId()\n partialTextContent = ''\n if (!partialTextStarted) {\n partialTextStarted = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n role: 'assistant',\n }\n }\n } else if (partialBlockType === 'thinking') {\n partialReasoningId = genId()\n yield {\n type: EventType.REASONING_START,\n messageId: partialReasoningId,\n model,\n timestamp: now(),\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: partialReasoningId,\n role: 'reasoning' as const,\n model,\n timestamp: now(),\n }\n } else if (\n partialBlockType === 'tool_use' &&\n !partialIsStructuredOutput &&\n typeof block.id === 'string' &&\n typeof block.name === 'string'\n ) {\n const name = stripMcpPrefix(block.name)\n partialToolCalls.set(event.index, { id: block.id, name, args: '' })\n streamedToolCallIds.add(block.id)\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: block.id,\n toolCallName: name,\n model,\n timestamp: now(),\n ...(partialMessageId !== null && {\n parentMessageId: partialMessageId,\n }),\n }\n }\n } else if (event.type === 'content_block_delta') {\n if (\n event.delta.type === 'text_delta' &&\n partialTextStarted &&\n partialTextMessageId &&\n typeof event.delta.text === 'string'\n ) {\n partialTextContent += event.delta.text\n assistantTextForHarvest += event.delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: partialTextMessageId,\n model,\n timestamp: now(),\n delta: event.delta.text,\n content: partialTextContent,\n }\n } else if (\n event.delta.type === 'input_json_delta' &&\n partialIsStructuredOutput &&\n typeof event.delta.partial_json === 'string'\n ) {\n partialStructuredJson += event.delta.partial_json\n } else if (\n event.delta.type === 'thinking_delta' &&\n partialReasoningId &&\n typeof event.delta.thinking === 'string'\n ) {\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: partialReasoningId,\n delta: event.delta.thinking,\n model,\n timestamp: now(),\n }\n } else if (\n event.delta.type === 'input_json_delta' &&\n typeof event.delta.partial_json === 'string'\n ) {\n const toolCall = partialToolCalls.get(event.index)\n if (toolCall) {\n toolCall.args += event.delta.partial_json\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: toolCall.id,\n model,\n timestamp: now(),\n delta: event.delta.partial_json,\n }\n }\n }\n } else if (event.type === 'content_block_stop') {\n const partialBlockType = partialBlockTypes.get(event.index)\n partialBlockTypes.delete(event.index)\n if (partialIsStructuredOutput && partialStructuredJson !== '') {\n try {\n capturedStructuredOutput = rememberStructuredOutput(\n capturedStructuredOutput,\n JSON.parse(partialStructuredJson),\n )\n } catch {\n // Incomplete JSON; the complete assistant tool_use may still arrive.\n }\n }\n if (partialBlockType === 'text') {\n yield* closePartialText()\n } else if (partialBlockType === 'thinking') {\n yield* closePartialReasoning()\n } else if (partialBlockType === 'tool_use') {\n yield* closePartialToolUse(event.index)\n }\n partialIsStructuredOutput = false\n partialStructuredJson = ''\n }\n }\n\n try {\n for await (const sdkMessage of sdkMessages) {\n ctx.onSdkMessage?.(sdkMessage)\n\n if (sdkMessage.type === 'system' && sdkMessage.subtype === 'init') {\n yield* startRun()\n ctx.onSessionId?.(sdkMessage.session_id)\n yield {\n type: EventType.CUSTOM,\n model,\n timestamp: now(),\n name: SESSION_ID_EVENT,\n value: {\n sessionId: sdkMessage.session_id,\n model: sdkMessage.model,\n tools: sdkMessage.tools,\n skills: sdkMessage.skills ?? [],\n },\n }\n continue\n }\n\n // Anything before init still needs RUN_STARTED first.\n yield* startRun()\n\n if (sdkMessage.type === 'stream_event') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleStreamEvent(sdkMessage)\n } else if (sdkMessage.type === 'assistant') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleAssistant(sdkMessage)\n } else if (sdkMessage.type === 'user') {\n if (sdkMessage.parent_tool_use_id !== null) continue\n yield* handleUser(sdkMessage)\n } else if (sdkMessage.type === 'result') {\n yield* handleResult(sdkMessage)\n }\n // All other SDK message types (status, hooks, notifications, ...) are\n // harness-internal and intentionally ignored.\n }\n } catch (error) {\n // The run is dying (abort or SDK failure). Close any half-streamed tool\n // calls, then pair every started tool call with a synthetic result so the\n // next request's pending-tool-call scan doesn't try to execute them. Then\n // let the adapter surface the error as RUN_ERROR.\n yield* closePartialToolUses(true)\n yield* synthesizeUnresolvedResults()\n throw error\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,mBAAmB;;AAGhC,IAAa,0BAA0B;AAEvC,IAAM,qBAAqB,QAAQ,wBAAwB;;;;;;AAO3D,IAAa,mCAAmC;;;;;;AA2BhD,SAAgB,eAAe,MAAsB;CACnD,OAAO,KAAK,WAAW,kBAAkB,IACrC,KAAK,MAAM,mBAAmB,MAAM,IACpC;AACN;AAEA,SAAS,yBAAyB,OAAyB;CACzD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS;AAEhC;AAEA,SAAS,yBAAyB,S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C9B,OAAO,sBAAsB;QACxB,IAAI,qBAAqB,YAC9B,OAAO,oBAAoB,MAAM,KAAK;GAExC,4BAA4B;GAC5B,wBAAwB;EAC1B;CACF;CAEA,IAAI;EACF,WAAW,MAAM,cAAc,aAAa;GAC1C,IAAI,eAAe,UAAU;GAE7B,IAAI,WAAW,SAAS,YAAY,WAAW,YAAY,QAAQ;IACjE,OAAO,SAAS;IAChB,IAAI,cAAc,WAAW,UAAU;IACvC,MAAM;KACJ,MAAM,UAAU;KAChB;KACA,WAAW,IAAI;KACf,MAAM;KACN,OAAO;MACL,WAAW,WAAW;MACtB,OAAO,WAAW;MAClB,OAAO,WAAW;MAClB,QAAQ,WAAW,UAAU,CAAC;KAChC;IACF;IACA;GACF;GAGA,OAAO,SAAS;GAEhB,IAAI,WAAW,SAAS,gBAAgB;IACtC,IAAI,WAAW,uBAAuB,MAAM;IAC5C,OAAO,kBAAkB,UAAU;GACrC,OAAO,IAAI,WAAW,SAAS,aAAa;IAC1C,IAAI,WAAW,uBAAuB,MAAM;IAC5C,OAAO,gBAAgB,UAAU;GACnC,OAAO,IAAI,WAAW,SAAS,QAAQ;IACrC,IAAI,WAAW,uBAAuB,MAAM;IAC5C,OAAO,WAAW,UAAU;GAC9B,OAAO,IAAI,WAAW,SAAS,UAC7B,OAAO,aAAa,UAAU;EAIlC;CACF,SAAS,OAAO;EAKd,OAAO,qBAAqB,IAAI;EAChC,OAAO,4BAA4B;EACnC,MAAM;CACR;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-claude-code",
3
- "version": "0.9.2",
3
+ "version": "1.0.0",
4
4
  "description": "Claude Code harness adapter for TanStack AI — run Claude Code as a chat backend with local tool execution and stateful sessions.",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -41,14 +41,14 @@
41
41
  "src"
42
42
  ],
43
43
  "peerDependencies": {
44
- "@tanstack/ai": "^0.71.0",
45
- "@tanstack/ai-sandbox": "^0.5.25"
44
+ "@tanstack/ai": "^1.0.0",
45
+ "@tanstack/ai-sandbox": "^1.0.0"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@vitest/coverage-v8": "4.1.10",
49
- "@tanstack/ai": "0.71.0",
50
- "@tanstack/ai-sandbox": "0.5.25",
51
- "@tanstack/ai-sandbox-local-process": "0.2.6"
49
+ "@tanstack/ai": "1.0.0",
50
+ "@tanstack/ai-sandbox": "1.0.0",
51
+ "@tanstack/ai-sandbox-local-process": "1.0.0"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "vite build",
@@ -24,7 +24,6 @@ import {
24
24
  nodeHttpBridgeProvisioner,
25
25
  resolveApproval,
26
26
  resolveDurableRunId,
27
- resolveDurableThreadId,
28
27
  spawnNdjson,
29
28
  } from '@tanstack/ai-sandbox'
30
29
  import { buildPrompt } from '../messages/prompt'
@@ -473,17 +472,7 @@ export class ClaudeCodeTextAdapter<
473
472
  adapter: 'claude-code',
474
473
  fallback: () => this.generateId(),
475
474
  })
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
- })
475
+ const threadId = options.threadId
487
476
  // Surfaces custom events from bridged tools (e.g. code mode console logs)
488
477
  // on this run's live output stream.
489
478
  channel = createBridgeEventChannel({ model: this.model, threadId, runId })
@@ -526,6 +515,7 @@ export class ClaudeCodeTextAdapter<
526
515
  : undefined) ?? nodeHttpBridgeProvisioner
527
516
  bridge = await provisioner.provision(tools, {
528
517
  provider: sandbox.provider,
518
+ threadId,
529
519
  context: options.context,
530
520
  emitCustomEvent: channel.emitCustomEvent,
531
521
  ...(permission !== undefined ? { permission } : {}),
@@ -237,7 +237,6 @@ export async function* translateSdkStream(
237
237
  type: EventType.TOOL_CALL_END,
238
238
  toolCallId: toolCall.id,
239
239
  toolCallName: toolCall.name,
240
- toolName: toolCall.name,
241
240
  model,
242
241
  timestamp: now(),
243
242
  input,
@@ -297,7 +296,6 @@ export async function* translateSdkStream(
297
296
  type: EventType.TOOL_CALL_START,
298
297
  toolCallId: block.id,
299
298
  toolCallName,
300
- toolName: toolCallName,
301
299
  model,
302
300
  timestamp: now(),
303
301
  }
@@ -313,7 +311,6 @@ export async function* translateSdkStream(
313
311
  type: EventType.TOOL_CALL_END,
314
312
  toolCallId: block.id,
315
313
  toolCallName,
316
- toolName: toolCallName,
317
314
  model,
318
315
  timestamp: now(),
319
316
  input: block.input ?? {},
@@ -563,7 +560,6 @@ export async function* translateSdkStream(
563
560
  type: EventType.TOOL_CALL_START,
564
561
  toolCallId: block.id,
565
562
  toolCallName: name,
566
- toolName: name,
567
563
  model,
568
564
  timestamp: now(),
569
565
  ...(partialMessageId !== null && {