@tanstack/ai-claude-code 0.8.1 → 0.9.1

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.
@@ -1,7 +1,7 @@
1
1
  import { BaseTextAdapter, StructuredOutputOptions, StructuredOutputResult } from '@tanstack/ai/adapters';
2
2
  import { SandboxHandle } from '@tanstack/ai-sandbox';
3
- import { DefaultMessageMetadataByModality, Modality, AdapterYieldChunk, TextOptions } from '@tanstack/ai';
4
- import { ClaudeCodeModel } from '../model-meta.js';
3
+ import { DefaultMessageMetadataByModality, Modality, AdapterYieldChunk, ReasoningRequest, TextOptions } from '@tanstack/ai';
4
+ import { ClaudeCodeModel, ClaudeCodeModelReasoningByName } from '../model-meta.js';
5
5
  import { ClaudeCodeTextProviderOptions } from '../provider-options.js';
6
6
  export type ClaudeCodePermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
7
7
  export type ClaudeCodeSettingSource = 'user' | 'project' | 'local';
@@ -54,10 +54,25 @@ export interface ClaudeCodeTextConfig {
54
54
  /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */
55
55
  emitDiff?: boolean;
56
56
  }
57
- export declare class ClaudeCodeTextAdapter<TModel extends ClaudeCodeModel> extends BaseTextAdapter<TModel, ClaudeCodeTextProviderOptions, ReadonlyArray<Modality> & readonly ['text'], DefaultMessageMetadataByModality, ReadonlyArray<string>, unknown, never> {
57
+ /** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
58
+ type ResolveReasoning<TModel extends string> = TModel extends keyof ClaudeCodeModelReasoningByName ? ClaudeCodeModelReasoningByName[TModel] : never;
59
+ /**
60
+ * The CLI settings for `chat({ reasoning })`, from the Claude Code docs:
61
+ * - Claude 4.6 and later, and the `opus` and `sonnet` aliases:
62
+ * `--effort <level>`.
63
+ * - an older model (Haiku 4.5): `MAX_THINKING_TOKENS`, the budget (pi's
64
+ * table when the request sets none), or `0` for `off`.
65
+ */
66
+ export declare function claudeCodeReasoning(model: string, request: ReasoningRequest | undefined): {
67
+ args: Array<string>;
68
+ env: Record<string, string>;
69
+ };
70
+ export declare class ClaudeCodeTextAdapter<TModel extends ClaudeCodeModel> extends BaseTextAdapter<TModel, ClaudeCodeTextProviderOptions, ReadonlyArray<Modality> & readonly ['text'], DefaultMessageMetadataByModality, ReadonlyArray<string>, unknown, never, ResolveReasoning<TModel>> {
58
71
  readonly name: "claude-code";
59
72
  readonly requires: readonly [import('@tanstack/ai').Capability<SandboxHandle, "sandbox">];
60
73
  private readonly adapterConfig;
74
+ /** Set after the first `toolChoice: 'required'` warning. */
75
+ private warnedRequired;
61
76
  constructor(config: ClaudeCodeTextConfig, model: TModel);
62
77
  private sandboxFrom;
63
78
  private workdir;
@@ -89,3 +104,4 @@ export declare class ClaudeCodeTextAdapter<TModel extends ClaudeCodeModel> exten
89
104
  * resume through `modelOptions.sessionId`.
90
105
  */
91
106
  export declare function claudeCodeText<TModel extends ClaudeCodeModel>(model: TModel, config?: ClaudeCodeTextConfig): ClaudeCodeTextAdapter<TModel>;
107
+ export {};
@@ -2,9 +2,10 @@ import { buildPrompt } from "../messages/prompt.js";
2
2
  import { translateSdkStream } from "../stream/translate.js";
3
3
  import { mapPolicyToClaudeFlags } from "./policy-map.js";
4
4
  import { projectClaudeWorkspace } from "./projection.js";
5
+ import { CLAUDE_CODE_MODEL_REASONING } from "../model-meta.js";
5
6
  import { CLAUDE_JSON_SCHEMA_PLACEHOLDER, CLAUDE_RUNNER_SOURCE } from "./claude-run-source.js";
6
7
  import { EventType, normalizeSystemPrompts } from "@tanstack/ai";
7
- import { appendOutputSchemaInstruction, toRunErrorRawEvent } from "@tanstack/ai/adapter-internals";
8
+ import { appendOutputSchemaInstruction, reasoningBudget, resolveReasoning, toRunErrorRawEvent } from "@tanstack/ai/adapter-internals";
8
9
  import { BaseTextAdapter } from "@tanstack/ai/adapters";
9
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
11
  //#region src/adapters/text.ts
@@ -32,6 +33,16 @@ function localProcessHomeEnv(provider) {
32
33
  const home = process.env.USERPROFILE;
33
34
  return home ? { HOME: home } : {};
34
35
  }
36
+ /**
37
+ * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only
38
+ * the named tool for `{ type: 'tool', name }`.
39
+ */
40
+ function toolsForChoice(options) {
41
+ const { toolChoice, tools = [] } = options;
42
+ if (toolChoice === "none") return [];
43
+ if (typeof toolChoice === "object") return tools.filter((tool) => tool.name === toolChoice.name);
44
+ return tools;
45
+ }
35
46
  /** Format a host tool-bridge as claude's `--mcp-config` JSON. */
36
47
  function bridgeToMcpConfig(bridge) {
37
48
  return JSON.stringify({ mcpServers: { [bridge.name]: {
@@ -40,10 +51,41 @@ function bridgeToMcpConfig(bridge) {
40
51
  headers: { Authorization: `Bearer ${bridge.token}` }
41
52
  } } });
42
53
  }
54
+ /** The models that take `--effort`. The same list as the Anthropic adapter's adaptive thinking. */
55
+ var EFFORT_MODELS = /^(opus|sonnet)$|opus-4-[6-9]|sonnet-4-[6-9]|opus-5|sonnet-5|fable-5/;
56
+ /**
57
+ * The CLI settings for `chat({ reasoning })`, from the Claude Code docs:
58
+ * - Claude 4.6 and later, and the `opus` and `sonnet` aliases:
59
+ * `--effort <level>`.
60
+ * - an older model (Haiku 4.5): `MAX_THINKING_TOKENS`, the budget (pi's
61
+ * table when the request sets none), or `0` for `off`.
62
+ */
63
+ function claudeCodeReasoning(model, request) {
64
+ const resolved = resolveReasoning(request, CLAUDE_CODE_MODEL_REASONING[model]);
65
+ if (!resolved) return {
66
+ args: [],
67
+ env: {}
68
+ };
69
+ if (EFFORT_MODELS.test(model)) return {
70
+ args: ["--effort", resolved.value],
71
+ env: {}
72
+ };
73
+ const budget = resolved.level === "off" ? 0 : reasoningBudget({
74
+ level: resolved.level,
75
+ summary: resolved.summary,
76
+ ...resolved.budgetTokens !== void 0 ? { budgetTokens: resolved.budgetTokens } : {}
77
+ });
78
+ return {
79
+ args: [],
80
+ env: { MAX_THINKING_TOKENS: String(budget) }
81
+ };
82
+ }
43
83
  var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
44
84
  name = "claude-code";
45
85
  requires = [SandboxCapability];
46
86
  adapterConfig;
87
+ /** Set after the first `toolChoice: 'required'` warning. */
88
+ warnedRequired = false;
47
89
  constructor(config, model) {
48
90
  super({}, model);
49
91
  this.adapterConfig = config;
@@ -81,6 +123,7 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
81
123
  ];
82
124
  if (config.streamPartials !== false) args.push("--include-partial-messages");
83
125
  if (resume !== void 0) args.push("--resume", resume);
126
+ args.push(...claudeCodeReasoning(this.model, options.reasoning).args);
84
127
  const permissionMode = modelOptions?.permissionMode ?? config.permissionMode ?? policyFlags.permissionMode ?? "bypassPermissions";
85
128
  args.push("--permission-mode", permissionMode);
86
129
  const maxTurns = modelOptions?.maxTurns ?? config.maxTurns;
@@ -90,6 +133,8 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
90
133
  if (allowedTools.length > 0) args.push("--allowedTools", [...new Set(allowedTools)].join(","));
91
134
  const disallowedTools = [...modelOptions?.disallowedTools ?? config.disallowedTools ?? [], ...policyFlags.disallowedTools];
92
135
  if (disallowedTools.length > 0) args.push("--disallowedTools", [...new Set(disallowedTools)].join(","));
136
+ const toolChoice = options.toolChoice;
137
+ if (toolChoice === "none" || typeof toolChoice === "object") args.push("--tools", "", "--strict-mcp-config");
93
138
  const systemPrompts = normalizeSystemPrompts(options.systemPrompts).map((prompt) => prompt.content).filter((content) => content.trim() !== "");
94
139
  if (systemPrompts.length > 0) {
95
140
  const joined = systemPrompts.join("\n\n");
@@ -163,6 +208,10 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
163
208
  let cleanupSandbox;
164
209
  const tempFiles = [];
165
210
  try {
211
+ if (options.toolChoice === "required" && !this.warnedRequired) {
212
+ this.warnedRequired = true;
213
+ logger.warn("claude-code: toolChoice 'required' is not supported. The agent decides which tools to call.");
214
+ }
166
215
  const sandbox = this.sandboxFrom(options);
167
216
  cleanupSandbox = sandbox;
168
217
  const cwd = this.workdir(options);
@@ -190,7 +239,8 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
190
239
  toolName: "approval_prompt",
191
240
  resolve: this.buildPermissionResolver(policy, options.approvals, projection?.scripts, approvalRequests, threadId, runId)
192
241
  } : void 0;
193
- if (options.tools !== void 0 && options.tools.length > 0 || permission !== void 0) bridge = await ((options.capabilities ? getToolBridgeProvisioner(options.capabilities, { optional: true }) : void 0) ?? nodeHttpBridgeProvisioner).provision(options.tools ?? [], {
242
+ const tools = toolsForChoice(options);
243
+ if (tools.length > 0 || permission !== void 0) bridge = await ((options.capabilities ? getToolBridgeProvisioner(options.capabilities, { optional: true }) : void 0) ?? nodeHttpBridgeProvisioner).provision(tools, {
194
244
  provider: sandbox.provider,
195
245
  context: options.context,
196
246
  emitCustomEvent: channel.emitCustomEvent,
@@ -249,6 +299,7 @@ var ClaudeCodeTextAdapter = class extends BaseTextAdapter {
249
299
  },
250
300
  ...injectApiKey ? hostClaudeAuthEnv() : {},
251
301
  ...localProcessHomeEnv(sandbox.provider),
302
+ ...claudeCodeReasoning(this.model, options.reasoning).env,
252
303
  ...this.adapterConfig.env
253
304
  },
254
305
  ...options.abortController?.signal ? { signal: options.abortController.signal } : options.request?.signal ? { signal: options.request.signal } : {},
@@ -330,6 +381,6 @@ function claudeCodeText(model, config = {}) {
330
381
  return new ClaudeCodeTextAdapter(config, model);
331
382
  }
332
383
  //#endregion
333
- export { ClaudeCodeTextAdapter, claudeCodeText };
384
+ export { ClaudeCodeTextAdapter, claudeCodeReasoning, claudeCodeText };
334
385
 
335
386
  //# sourceMappingURL=text.js.map
@@ -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 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 {\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 TextOptions,\n} from '@tanstack/ai'\nimport type { ClaudeCodeModel } 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/** 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\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> {\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 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\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\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 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 hasTools = options.tools !== undefined && options.tools.length > 0\n if (hasTools || permission !== undefined) {\n const provisioner =\n (options.capabilities\n ? getToolBridgeProvisioner(options.capabilities, { optional: true })\n : undefined) ?? nodeHttpBridgeProvisioner\n bridge = await provisioner.provision(options.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 ...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":";;;;;;;;;;AAkEA,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;;AAGA,SAAS,kBAAkB,QAAgC;CACzD,OAAO,KAAK,UAAU,EACpB,YAAY,GACT,OAAO,OAAO;EACb,MAAM;EACN,KAAK,OAAO;EACZ,SAAS,EAAE,eAAe,UAAU,OAAO,QAAQ;CACrD,EACF,EACF,CAAC;AACH;AAEA,IAAa,wBAAb,cAEU,gBAQR;CACA,OAAgB;CAGhB,WAA6B,CAAC,iBAAiB;CAE/C;CAEA,YAAY,QAA8B,OAAe;EACvD,MAAM,CAAC,GAA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gB;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"}
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,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,YAAY,QAAQ,CAAC,MAAM;CACnC,IAAI,eAAe,QAAQ,OAAO,CAAC;CACnC,IAAI,OAAO,eAAe,UACxB,OAAO,MAAM,QAAQ,SAAS,KAAK,SAAS,WAAW,IAAI;CAE7D,OAAO;AACT;;AAGA,SAAS,kBAAkB,QAAgC;CACzD,OAAO,KAAK,UAAU,EACpB,YAAY,GACT,OAAO,OAAO;EACb,MAAM;EACN,KAAK,OAAO;EACZ,SAAS,EAAE,eAAe,UAAU,OAAO,QAAQ;CACrD,EACF,EACF,CAAC;AACH;;AASA,IAAM,gBACJ;;;;;;;;AASF,SAAgB,oBACd,OACA,SACs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AA,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"}
package/dist/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { buildPrompt } from "./messages/prompt.js";
2
2
  import { BRIDGED_MCP_SERVER_NAME, SESSION_ID_EVENT, stripMcpPrefix, translateSdkStream } from "./stream/translate.js";
3
- import { ClaudeCodeTextAdapter, claudeCodeText } from "./adapters/text.js";
4
3
  import { CLAUDE_CODE_MODELS } from "./model-meta.js";
4
+ import { ClaudeCodeTextAdapter, claudeCodeText } from "./adapters/text.js";
5
5
  export { BRIDGED_MCP_SERVER_NAME, CLAUDE_CODE_MODELS, ClaudeCodeTextAdapter, SESSION_ID_EVENT, buildPrompt, claudeCodeText, stripMcpPrefix, translateSdkStream };
@@ -1,3 +1,5 @@
1
+ import { ModelReasoning } from '@tanstack/ai';
2
+ import { ModelReasoningCapability } from '@tanstack/ai/adapter-internals';
1
3
  /**
2
4
  * Models known to work with Claude Code. The harness accepts any Anthropic
3
5
  * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),
@@ -8,3 +10,95 @@ export declare const CLAUDE_CODE_MODELS: readonly ["claude-opus-4-8", "claude-op
8
10
  export type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number];
9
11
  /** Any Claude model id accepted by Claude Code; known ids get autocomplete. */
10
12
  export type ClaudeCodeModel = KnownClaudeCodeModel | (string & {});
13
+ declare const CLAUDE_CODE_REASONING: {
14
+ 'claude-opus-4-8': {
15
+ readonly levels: {
16
+ readonly low: "low";
17
+ readonly medium: "medium";
18
+ readonly high: "high";
19
+ readonly xhigh: "xhigh";
20
+ readonly max: "max";
21
+ };
22
+ readonly budget: false;
23
+ };
24
+ 'claude-opus-4-7': {
25
+ readonly levels: {
26
+ readonly low: "low";
27
+ readonly medium: "medium";
28
+ readonly high: "high";
29
+ readonly xhigh: "xhigh";
30
+ readonly max: "max";
31
+ };
32
+ readonly budget: false;
33
+ };
34
+ 'claude-opus-4-6': {
35
+ readonly levels: {
36
+ readonly low: "low";
37
+ readonly medium: "medium";
38
+ readonly high: "high";
39
+ readonly max: "max";
40
+ };
41
+ readonly budget: true;
42
+ };
43
+ 'claude-sonnet-4-6': {
44
+ readonly levels: {
45
+ readonly low: "low";
46
+ readonly medium: "medium";
47
+ readonly high: "high";
48
+ readonly max: "max";
49
+ };
50
+ readonly budget: true;
51
+ };
52
+ 'claude-haiku-4-5': {
53
+ readonly levels: {
54
+ readonly off: "off";
55
+ readonly minimal: "minimal";
56
+ readonly low: "low";
57
+ readonly medium: "medium";
58
+ readonly high: "high";
59
+ };
60
+ readonly budget: true;
61
+ };
62
+ opus: {
63
+ readonly levels: {
64
+ readonly low: "low";
65
+ readonly medium: "medium";
66
+ readonly high: "high";
67
+ readonly xhigh: "xhigh";
68
+ readonly max: "max";
69
+ };
70
+ readonly budget: false;
71
+ };
72
+ sonnet: {
73
+ readonly levels: {
74
+ readonly low: "low";
75
+ readonly medium: "medium";
76
+ readonly high: "high";
77
+ readonly max: "max";
78
+ };
79
+ readonly budget: true;
80
+ };
81
+ haiku: {
82
+ readonly levels: {
83
+ readonly off: "off";
84
+ readonly minimal: "minimal";
85
+ readonly low: "low";
86
+ readonly medium: "medium";
87
+ readonly high: "high";
88
+ };
89
+ readonly budget: true;
90
+ };
91
+ };
92
+ /**
93
+ * Each model's reasoning levels, and whether it takes a token budget, for
94
+ * `chat({ reasoning })`. A model that is not here does not reason.
95
+ */
96
+ export type ClaudeCodeModelReasoningByName = {
97
+ [K in keyof typeof CLAUDE_CODE_REASONING]: ModelReasoningCapability<(typeof CLAUDE_CODE_REASONING)[K]>;
98
+ };
99
+ /**
100
+ * Runtime map from model id to its reasoning data, for the text adapter. An
101
+ * unknown id gives `undefined`: the adapter sends no reasoning field.
102
+ */
103
+ export declare const CLAUDE_CODE_MODEL_REASONING: Readonly<Record<string, ModelReasoning>>;
104
+ export {};
@@ -1,4 +1,33 @@
1
1
  //#region src/model-meta.ts
2
+ var BUDGET_LOW_TO_HIGH_MAX = {
3
+ levels: {
4
+ low: "low",
5
+ medium: "medium",
6
+ high: "high",
7
+ max: "max"
8
+ },
9
+ budget: true
10
+ };
11
+ var BUDGET_OFF_TO_HIGH = {
12
+ levels: {
13
+ off: "off",
14
+ minimal: "minimal",
15
+ low: "low",
16
+ medium: "medium",
17
+ high: "high"
18
+ },
19
+ budget: true
20
+ };
21
+ var EFFORT_LOW_TO_MAX = {
22
+ levels: {
23
+ low: "low",
24
+ medium: "medium",
25
+ high: "high",
26
+ xhigh: "xhigh",
27
+ max: "max"
28
+ },
29
+ budget: false
30
+ };
2
31
  /**
3
32
  * Models known to work with Claude Code. The harness accepts any Anthropic
4
33
  * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),
@@ -15,7 +44,21 @@ var CLAUDE_CODE_MODELS = [
15
44
  "sonnet",
16
45
  "haiku"
17
46
  ];
47
+ /**
48
+ * Runtime map from model id to its reasoning data, for the text adapter. An
49
+ * unknown id gives `undefined`: the adapter sends no reasoning field.
50
+ */
51
+ var CLAUDE_CODE_MODEL_REASONING = {
52
+ "claude-opus-4-8": EFFORT_LOW_TO_MAX,
53
+ "claude-opus-4-7": EFFORT_LOW_TO_MAX,
54
+ "claude-opus-4-6": BUDGET_LOW_TO_HIGH_MAX,
55
+ "claude-sonnet-4-6": BUDGET_LOW_TO_HIGH_MAX,
56
+ "claude-haiku-4-5": BUDGET_OFF_TO_HIGH,
57
+ opus: EFFORT_LOW_TO_MAX,
58
+ sonnet: BUDGET_LOW_TO_HIGH_MAX,
59
+ haiku: BUDGET_OFF_TO_HIGH
60
+ };
18
61
  //#endregion
19
- export { CLAUDE_CODE_MODELS };
62
+ export { CLAUDE_CODE_MODELS, CLAUDE_CODE_MODEL_REASONING };
20
63
 
21
64
  //# sourceMappingURL=model-meta.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["/**\n * Models known to work with Claude Code. The harness accepts any Anthropic\n * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),\n * so this list exists for autocomplete — any string is accepted via the\n * `(string & {})` escape hatch in {@link ClaudeCodeModel}.\n */\nexport const CLAUDE_CODE_MODELS = [\n 'claude-opus-4-8',\n 'claude-opus-4-7',\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n 'opus',\n 'sonnet',\n 'haiku',\n] as const\n\nexport type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number]\n\n/** Any Claude model id accepted by Claude Code; known ids get autocomplete. */\nexport type ClaudeCodeModel = KnownClaudeCodeModel | (string & {})\n"],"mappings":";;;;;;;AAMA,IAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
1
+ {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type { ModelReasoning } from '@tanstack/ai'\nimport type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'\n\n// Reasoning shapes: the levels a model has for `chat({ reasoning })`, and\n// the provider value to send for each. Each model points at one of them.\nconst BUDGET_LOW_TO_HIGH_MAX = {\n levels: { low: 'low', medium: 'medium', high: 'high', max: 'max' },\n budget: true,\n} as const\nconst BUDGET_OFF_TO_HIGH = {\n levels: {\n off: 'off',\n minimal: 'minimal',\n low: 'low',\n medium: 'medium',\n high: 'high',\n },\n budget: true,\n} as const\nconst EFFORT_LOW_TO_MAX = {\n levels: {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n },\n budget: false,\n} as const\n/**\n * Models known to work with Claude Code. The harness accepts any Anthropic\n * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),\n * so this list exists for autocomplete — any string is accepted via the\n * `(string & {})` escape hatch in {@link ClaudeCodeModel}.\n */\nexport const CLAUDE_CODE_MODELS = [\n 'claude-opus-4-8',\n 'claude-opus-4-7',\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n 'opus',\n 'sonnet',\n 'haiku',\n] as const\n\nexport type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number]\n\n/** Any Claude model id accepted by Claude Code; known ids get autocomplete. */\nexport type ClaudeCodeModel = KnownClaudeCodeModel | (string & {})\n\n// Reasoning\n//\n// Each model's data for `chat({ reasoning })`: the levels it has, with the\n// provider value for each, and whether it takes a thinking token budget. The\n// data comes from models.dev. The generator that writes it comes with the model\n// catalog later. Until then, edit these entries by hand.\n\nconst CLAUDE_CODE_REASONING = {\n 'claude-opus-4-8': EFFORT_LOW_TO_MAX,\n 'claude-opus-4-7': EFFORT_LOW_TO_MAX,\n 'claude-opus-4-6': BUDGET_LOW_TO_HIGH_MAX,\n 'claude-sonnet-4-6': BUDGET_LOW_TO_HIGH_MAX,\n 'claude-haiku-4-5': BUDGET_OFF_TO_HIGH,\n opus: EFFORT_LOW_TO_MAX,\n sonnet: BUDGET_LOW_TO_HIGH_MAX,\n haiku: BUDGET_OFF_TO_HIGH,\n} satisfies Partial<Record<KnownClaudeCodeModel, ModelReasoning>>\n\n/**\n * Each model's reasoning levels, and whether it takes a token budget, for\n * `chat({ reasoning })`. A model that is not here does not reason.\n */\nexport type ClaudeCodeModelReasoningByName = {\n [K in keyof typeof CLAUDE_CODE_REASONING]: ModelReasoningCapability<\n (typeof CLAUDE_CODE_REASONING)[K]\n >\n}\n\n/**\n * Runtime map from model id to its reasoning data, for the text adapter. An\n * unknown id gives `undefined`: the adapter sends no reasoning field.\n */\nexport const CLAUDE_CODE_MODEL_REASONING: Readonly<\n Record<string, ModelReasoning>\n> = CLAUDE_CODE_REASONING\n"],"mappings":";AAKA,IAAM,yBAAyB;CAC7B,QAAQ;EAAE,KAAK;EAAO,QAAQ;EAAU,MAAM;EAAQ,KAAK;CAAM;CACjE,QAAQ;AACV;AACA,IAAM,qBAAqB;CACzB,QAAQ;EACN,KAAK;EACL,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CACR;CACA,QAAQ;AACV;AACA,IAAM,oBAAoB;CACxB,QAAQ;EACN,KAAK;EACL,QAAQ;EACR,MAAM;EACN,OAAO;EACP,KAAK;CACP;CACA,QAAQ;AACV;;;;;;;AAOA,IAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAuCA,IAAa,8BAET;CA1BF,mBAAmB;CACnB,mBAAmB;CACnB,mBAAmB;CACnB,qBAAqB;CACrB,oBAAoB;CACpB,MAAM;CACN,QAAQ;CACR,OAAO;AAmBL"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-claude-code",
3
- "version": "0.8.1",
3
+ "version": "0.9.1",
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,13 +41,13 @@
41
41
  "src"
42
42
  ],
43
43
  "peerDependencies": {
44
- "@tanstack/ai": "^0.68.0",
45
- "@tanstack/ai-sandbox": "^0.5.22"
44
+ "@tanstack/ai": "^0.70.0",
45
+ "@tanstack/ai-sandbox": "^0.5.24"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@vitest/coverage-v8": "4.1.10",
49
- "@tanstack/ai": "0.68.0",
50
- "@tanstack/ai-sandbox": "0.5.22",
49
+ "@tanstack/ai": "0.70.0",
50
+ "@tanstack/ai-sandbox": "0.5.24",
51
51
  "@tanstack/ai-sandbox-local-process": "0.2.6"
52
52
  },
53
53
  "scripts": {
@@ -1,6 +1,8 @@
1
1
  import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
2
2
  import {
3
3
  appendOutputSchemaInstruction,
4
+ reasoningBudget,
5
+ resolveReasoning,
4
6
  toRunErrorRawEvent,
5
7
  } from '@tanstack/ai/adapter-internals'
6
8
  import { BaseTextAdapter } from '@tanstack/ai/adapters'
@@ -29,6 +31,7 @@ import { buildPrompt } from '../messages/prompt'
29
31
  import { translateSdkStream } from '../stream/translate'
30
32
  import { mapPolicyToClaudeFlags } from './policy-map'
31
33
  import { projectClaudeWorkspace } from './projection'
34
+ import { CLAUDE_CODE_MODEL_REASONING } from '../model-meta'
32
35
  import {
33
36
  CLAUDE_JSON_SCHEMA_PLACEHOLDER,
34
37
  CLAUDE_RUNNER_SOURCE,
@@ -50,9 +53,13 @@ import type {
50
53
  DefaultMessageMetadataByModality,
51
54
  Modality,
52
55
  AdapterYieldChunk,
56
+ ReasoningRequest,
53
57
  TextOptions,
54
58
  } from '@tanstack/ai'
55
- import type { ClaudeCodeModel } from '../model-meta'
59
+ import type {
60
+ ClaudeCodeModel,
61
+ ClaudeCodeModelReasoningByName,
62
+ } from '../model-meta'
56
63
  import type { ClaudeCodeTextProviderOptions } from '../provider-options'
57
64
  import type { AgentSdkMessage } from '../stream/sdk-types'
58
65
 
@@ -142,6 +149,19 @@ function localProcessHomeEnv(provider: string): Record<string, string> {
142
149
  return home ? { HOME: home } : {}
143
150
  }
144
151
 
152
+ /**
153
+ * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only
154
+ * the named tool for `{ type: 'tool', name }`.
155
+ */
156
+ function toolsForChoice(options: TextOptions<ClaudeCodeTextProviderOptions>) {
157
+ const { toolChoice, tools = [] } = options
158
+ if (toolChoice === 'none') return []
159
+ if (typeof toolChoice === 'object') {
160
+ return tools.filter((tool) => tool.name === toolChoice.name)
161
+ }
162
+ return tools
163
+ }
164
+
145
165
  /** Format a host tool-bridge as claude's `--mcp-config` JSON. */
146
166
  function bridgeToMcpConfig(bridge: HostToolBridge): string {
147
167
  return JSON.stringify({
@@ -155,6 +175,45 @@ function bridgeToMcpConfig(bridge: HostToolBridge): string {
155
175
  })
156
176
  }
157
177
 
178
+ /** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
179
+ type ResolveReasoning<TModel extends string> =
180
+ TModel extends keyof ClaudeCodeModelReasoningByName
181
+ ? ClaudeCodeModelReasoningByName[TModel]
182
+ : never
183
+
184
+ /** The models that take `--effort`. The same list as the Anthropic adapter's adaptive thinking. */
185
+ const EFFORT_MODELS =
186
+ /^(opus|sonnet)$|opus-4-[6-9]|sonnet-4-[6-9]|opus-5|sonnet-5|fable-5/
187
+
188
+ /**
189
+ * The CLI settings for `chat({ reasoning })`, from the Claude Code docs:
190
+ * - Claude 4.6 and later, and the `opus` and `sonnet` aliases:
191
+ * `--effort <level>`.
192
+ * - an older model (Haiku 4.5): `MAX_THINKING_TOKENS`, the budget (pi's
193
+ * table when the request sets none), or `0` for `off`.
194
+ */
195
+ export function claudeCodeReasoning(
196
+ model: string,
197
+ request: ReasoningRequest | undefined,
198
+ ): { args: Array<string>; env: Record<string, string> } {
199
+ const resolved = resolveReasoning(request, CLAUDE_CODE_MODEL_REASONING[model])
200
+ if (!resolved) return { args: [], env: {} }
201
+ if (EFFORT_MODELS.test(model)) {
202
+ return { args: ['--effort', resolved.value], env: {} }
203
+ }
204
+ const budget =
205
+ resolved.level === 'off'
206
+ ? 0
207
+ : reasoningBudget({
208
+ level: resolved.level,
209
+ summary: resolved.summary,
210
+ ...(resolved.budgetTokens !== undefined
211
+ ? { budgetTokens: resolved.budgetTokens }
212
+ : {}),
213
+ })
214
+ return { args: [], env: { MAX_THINKING_TOKENS: String(budget) } }
215
+ }
216
+
158
217
  export class ClaudeCodeTextAdapter<
159
218
  TModel extends ClaudeCodeModel,
160
219
  > extends BaseTextAdapter<
@@ -164,7 +223,8 @@ export class ClaudeCodeTextAdapter<
164
223
  DefaultMessageMetadataByModality,
165
224
  ReadonlyArray<string>,
166
225
  unknown,
167
- never
226
+ never,
227
+ ResolveReasoning<TModel>
168
228
  > {
169
229
  readonly name = 'claude-code' as const
170
230
 
@@ -173,6 +233,9 @@ export class ClaudeCodeTextAdapter<
173
233
 
174
234
  private readonly adapterConfig: ClaudeCodeTextConfig
175
235
 
236
+ /** Set after the first `toolChoice: 'required'` warning. */
237
+ private warnedRequired = false
238
+
176
239
  constructor(config: ClaudeCodeTextConfig, model: TModel) {
177
240
  super({}, model)
178
241
  this.adapterConfig = config
@@ -240,6 +303,7 @@ export class ClaudeCodeTextAdapter<
240
303
 
241
304
  if (config.streamPartials !== false) args.push('--include-partial-messages')
242
305
  if (resume !== undefined) args.push('--resume', resume)
306
+ args.push(...claudeCodeReasoning(this.model, options.reasoning).args)
243
307
 
244
308
  const permissionMode =
245
309
  modelOptions?.permissionMode ??
@@ -267,6 +331,13 @@ export class ClaudeCodeTextAdapter<
267
331
  if (disallowedTools.length > 0) {
268
332
  args.push('--disallowedTools', [...new Set(disallowedTools)].join(','))
269
333
  }
334
+ // `'none'` and a named tool: `--tools ''` turns off every built-in tool,
335
+ // and `--strict-mcp-config` keeps only the bridge, which then has no
336
+ // chat() tool or only the named one (see `toolsForChoice`).
337
+ const toolChoice = options.toolChoice
338
+ if (toolChoice === 'none' || typeof toolChoice === 'object') {
339
+ args.push('--tools', '', '--strict-mcp-config')
340
+ }
270
341
 
271
342
  const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
272
343
  .map((prompt) => prompt.content)
@@ -371,6 +442,13 @@ export class ClaudeCodeTextAdapter<
371
442
  let cleanupSandbox: SandboxHandle | undefined
372
443
  const tempFiles: Array<string> = []
373
444
  try {
445
+ // Claude Code cannot force a tool call.
446
+ if (options.toolChoice === 'required' && !this.warnedRequired) {
447
+ this.warnedRequired = true
448
+ logger.warn(
449
+ "claude-code: toolChoice 'required' is not supported. The agent decides which tools to call.",
450
+ )
451
+ }
374
452
  const sandbox = this.sandboxFrom(options)
375
453
  cleanupSandbox = sandbox
376
454
  const cwd = this.workdir(options)
@@ -440,13 +518,13 @@ export class ClaudeCodeTextAdapter<
440
518
 
441
519
  // Bridge chat()-provided server tools (and/or the permission tool) into
442
520
  // the sandbox over MCP.
443
- const hasTools = options.tools !== undefined && options.tools.length > 0
444
- if (hasTools || permission !== undefined) {
521
+ const tools = toolsForChoice(options)
522
+ if (tools.length > 0 || permission !== undefined) {
445
523
  const provisioner =
446
524
  (options.capabilities
447
525
  ? getToolBridgeProvisioner(options.capabilities, { optional: true })
448
526
  : undefined) ?? nodeHttpBridgeProvisioner
449
- bridge = await provisioner.provision(options.tools ?? [], {
527
+ bridge = await provisioner.provision(tools, {
450
528
  provider: sandbox.provider,
451
529
  context: options.context,
452
530
  emitCustomEvent: channel.emitCustomEvent,
@@ -565,6 +643,7 @@ export class ClaudeCodeTextAdapter<
565
643
  }),
566
644
  ...(injectApiKey ? hostClaudeAuthEnv() : {}),
567
645
  ...localProcessHomeEnv(sandbox.provider),
646
+ ...claudeCodeReasoning(this.model, options.reasoning).env,
568
647
  ...this.adapterConfig.env,
569
648
  },
570
649
  ...(options.abortController?.signal
package/src/model-meta.ts CHANGED
@@ -1,3 +1,32 @@
1
+ import type { ModelReasoning } from '@tanstack/ai'
2
+ import type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'
3
+
4
+ // Reasoning shapes: the levels a model has for `chat({ reasoning })`, and
5
+ // the provider value to send for each. Each model points at one of them.
6
+ const BUDGET_LOW_TO_HIGH_MAX = {
7
+ levels: { low: 'low', medium: 'medium', high: 'high', max: 'max' },
8
+ budget: true,
9
+ } as const
10
+ const BUDGET_OFF_TO_HIGH = {
11
+ levels: {
12
+ off: 'off',
13
+ minimal: 'minimal',
14
+ low: 'low',
15
+ medium: 'medium',
16
+ high: 'high',
17
+ },
18
+ budget: true,
19
+ } as const
20
+ const EFFORT_LOW_TO_MAX = {
21
+ levels: {
22
+ low: 'low',
23
+ medium: 'medium',
24
+ high: 'high',
25
+ xhigh: 'xhigh',
26
+ max: 'max',
27
+ },
28
+ budget: false,
29
+ } as const
1
30
  /**
2
31
  * Models known to work with Claude Code. The harness accepts any Anthropic
3
32
  * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),
@@ -19,3 +48,39 @@ export type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number]
19
48
 
20
49
  /** Any Claude model id accepted by Claude Code; known ids get autocomplete. */
21
50
  export type ClaudeCodeModel = KnownClaudeCodeModel | (string & {})
51
+
52
+ // Reasoning
53
+ //
54
+ // Each model's data for `chat({ reasoning })`: the levels it has, with the
55
+ // provider value for each, and whether it takes a thinking token budget. The
56
+ // data comes from models.dev. The generator that writes it comes with the model
57
+ // catalog later. Until then, edit these entries by hand.
58
+
59
+ const CLAUDE_CODE_REASONING = {
60
+ 'claude-opus-4-8': EFFORT_LOW_TO_MAX,
61
+ 'claude-opus-4-7': EFFORT_LOW_TO_MAX,
62
+ 'claude-opus-4-6': BUDGET_LOW_TO_HIGH_MAX,
63
+ 'claude-sonnet-4-6': BUDGET_LOW_TO_HIGH_MAX,
64
+ 'claude-haiku-4-5': BUDGET_OFF_TO_HIGH,
65
+ opus: EFFORT_LOW_TO_MAX,
66
+ sonnet: BUDGET_LOW_TO_HIGH_MAX,
67
+ haiku: BUDGET_OFF_TO_HIGH,
68
+ } satisfies Partial<Record<KnownClaudeCodeModel, ModelReasoning>>
69
+
70
+ /**
71
+ * Each model's reasoning levels, and whether it takes a token budget, for
72
+ * `chat({ reasoning })`. A model that is not here does not reason.
73
+ */
74
+ export type ClaudeCodeModelReasoningByName = {
75
+ [K in keyof typeof CLAUDE_CODE_REASONING]: ModelReasoningCapability<
76
+ (typeof CLAUDE_CODE_REASONING)[K]
77
+ >
78
+ }
79
+
80
+ /**
81
+ * Runtime map from model id to its reasoning data, for the text adapter. An
82
+ * unknown id gives `undefined`: the adapter sends no reasoning field.
83
+ */
84
+ export const CLAUDE_CODE_MODEL_REASONING: Readonly<
85
+ Record<string, ModelReasoning>
86
+ > = CLAUDE_CODE_REASONING