The best way to control Claude Code, Codex and more from any computer or phone

main
ts 15,104 lines 622 KB
Raw
Large file — syntax highlighting disabled.
1 import * as DocumentText from "../../provider/DocumentText.ts";
2 import {
3 compactDynamicToolOutput,
4 mcpToolResultOutput,
5 toolOutputImages,
6 } from "@t3tools/shared/toolOutput";
7 import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
8 import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
9 import {
10 dynamicToolTitle,
11 formatReadToolLabel,
12 formatSearchToolLabel,
13 } from "@t3tools/shared/toolActivity";
14 import { field, text } from "../unknownField.ts";
15 import { mergeWorkflowAgentMetadata, type WorkflowAgentMetadata } from "../workflowAgentAnswers.ts";
16 import {
17 initialWorkflowAgentTranscriptCursor,
18 readWorkflowAgentTranscript,
19 type WorkflowAgentTranscriptCursor,
20 } from "../workflowAgentTranscript.ts";
21 import {
22 CLAUDE_WORKFLOW_TASK_TYPE,
23 hasClaudeWorkflowSnapshot,
24 mergeClaudeWorkflowProgress,
25 parseClaudeWorkflowRunHandles,
26 } from "./claudeWorkflowProgress.ts";
27
28 import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
29 import { pastedUrl } from "@t3tools/shared/oauthCallback";
30 import {
31 addClaudeLedgerUsage,
32 claudeLedgerDelta,
33 claudeModelLedger,
34 claudeReportedContextWindows,
35 normalizeClaudeTurnTokenUsage,
36 type ClaudeLedgerUsage,
37 type ClaudeModelLedger,
38 } from "../../provider/ClaudeTurnTokenUsage.ts";
39 import { toMcpElicitationResponse } from "../../provider/CodexMcpElicitation.ts";
40 import {
41 type CanUseTool,
42 type ElicitationRequest,
43 type ElicitationResult,
44 forkSession as forkClaudeSession,
45 type EffortLevel,
46 type ForkSessionOptions,
47 type ForkSessionResult,
48 getSessionMessages,
49 getSubagentMessages,
50 type HookCallback,
51 type McpServerStatus as ClaudeMcpServerStatus,
52 query,
53 resolveSettings as resolveClaudeSettings,
54 type Options as ClaudeQueryOptions,
55 type PermissionMode,
56 type PermissionResult,
57 type PermissionUpdate,
58 type Query as ClaudeQuery,
59 type Settings as ClaudeSdkSettings,
60 type SpawnOptions as ClaudeSpawnOptions,
61 type SpawnedProcess as ClaudeSpawnedProcess,
62 type SDKAssistantMessage,
63 type SDKAPIRetryMessage,
64 type SDKMessage,
65 type SDKRateLimitInfo,
66 type SDKResultMessage,
67 type SDKUserMessage,
68 } from "@anthropic-ai/claude-agent-sdk";
69 import type {
70 AskUserQuestionInput,
71 WebSearchOutput,
72 } from "@anthropic-ai/claude-agent-sdk/sdk-tools";
73 // @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI.
74 import * as NodeChildProcess from "node:child_process";
75 import * as NodeUtil from "node:util";
76 import { parseCliArgs } from "@t3tools/shared/cliArgs";
77 import { fromLenientJson } from "@t3tools/shared/schemaJson";
78 import {
79 claudeMcpToolName,
80 claudeMcpToolNamePart,
81 claudeMcpToolPrefix,
82 MCP_APP_OUTPUT_KEY,
83 mcpAppToolResourceUri,
84 } from "@t3tools/shared/mcpApp";
85 import { AgentScope } from "@t3tools/shared/AgentScope";
86 import * as ProviderProcesses from "../../process/providerProcesses.ts";
87 import * as SpawnWorker from "../../process/SpawnWorker.ts";
88 import * as HostProcess from "@t3tools/shared/HostProcess";
89 import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
90 import { compareSemverVersions } from "@t3tools/shared/semver";
91 import {
92 CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
93 CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
94 formatClaudeResumeCompactionQuestion,
95 } from "@t3tools/shared/claudeCompaction";
96 import {
97 type ChatAttachment,
98 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
99 ClaudeSettings,
100 TrimmedNonEmptyString,
101 defaultInstanceIdForDriver,
102 isCompactionCommandMessage,
103 parseGoalCommand,
104 type MessageId,
105 type ModelSelection,
106 type OrchestrationV2ConversationMessage,
107 type OrchestrationV2ExecutionNode,
108 type OrchestrationV2ProviderCapabilities,
109 type OrchestrationV2ProviderFailure,
110 OrchestrationV2ProviderGoal,
111 type OrchestrationV2PlanArtifact,
112 type OrchestrationV2PlanStep,
113 type OrchestrationV2PendingBackgroundTask,
114 type OrchestrationV2ProviderRetry,
115 type OrchestrationV2ProviderSession,
116 type OrchestrationV2ProviderThread,
117 type OrchestrationV2ProviderTurn,
118 type OrchestrationV2RuntimeRequest,
119 type OrchestrationV2UserInputQuestion,
120 type OrchestrationV2Subagent,
121 type OrchestrationV2AppThread,
122 type OrchestrationV2SubagentWorkflow,
123 type OrchestrationV2WorkflowRunHandles,
124 type OrchestrationV2TurnItem,
125 type OrchestrationV2WebSearchResult,
126 type ProviderApprovalDecision,
127 type ProviderApprovalFullAccessOverride,
128 ProviderMcpSignInError,
129 type ProviderApprovalOption,
130 ProviderDriverKind,
131 type ProviderInstanceId,
132 type ProviderRequestKind,
133 type ProviderUserInputAnswers,
134 type ProviderThreadId,
135 type RunId,
136 type ThreadId,
137 resolveIdleCompaction,
138 isDelegatedAppThread,
139 } from "@t3tools/contracts";
140
141 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
142 import * as Cause from "effect/Cause";
143 import * as Predicate from "effect/Predicate";
144 import * as Clock from "effect/Clock";
145 import * as Context from "effect/Context";
146 import * as SecureRandom from "effect/crypto/SecureRandom";
147 import * as DateTime from "effect/DateTime";
148 import * as Deferred from "effect/Deferred";
149 import * as Duration from "effect/Duration";
150 import * as Effect from "effect/Effect";
151 import * as Equal from "effect/Equal";
152 import * as Exit from "effect/Exit";
153 import * as Fiber from "effect/Fiber";
154 import * as Schedule from "effect/Schedule";
155 import * as FileSystem from "effect/FileSystem";
156 import * as Layer from "effect/Layer";
157 import * as Option from "effect/Option";
158 import * as Path from "effect/Path";
159 import * as Queue from "effect/Queue";
160 import * as Ref from "effect/Ref";
161 import * as Schema from "effect/Schema";
162 import * as Semaphore from "effect/Semaphore";
163 import * as Stream from "effect/Stream";
164 import * as ChildProcess from "effect/process/ChildProcess";
165 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
166
167 import { resolveAttachmentPath } from "../../attachmentStore.ts";
168 import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";
169 import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
170 import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts";
171 import {
172 planClaudeSkillDispatch,
173 type ClaudeSkillTarget,
174 } from "../../provider/Drivers/ClaudeSkillDispatch.ts";
175 import {
176 claudeLaunchArgDirectories,
177 claudeLaunchArgParseOptions,
178 claudeLaunchArgPluginDirectories,
179 customClaudeApiEndpointHost,
180 discoverClaudeSkills,
181 readClaudeSettingsEnv,
182 } from "../../provider/Drivers/ClaudeSkills.ts";
183 import {
184 compileClaudeModelSelection,
185 type CompiledClaudeModelSelection,
186 } from "../../claudeModelOptions.ts";
187 import * as ServerConfig from "../../config.ts";
188 import * as PortScanner from "../../preview/PortScanner.ts";
189 import * as ProcessRunner from "../../processRunner.ts";
190 import * as ServerSettings from "../../serverSettings.ts";
191 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
192 import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
193 import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
194 import {
195 claudeLocalSettingsDirectory,
196 claudeSignedOutMessage,
197 makeClaudeEnvironment,
198 mergeClaudeProcessEnvironment,
199 resolveClaudeHomePath,
200 } from "../../provider/Drivers/ClaudeHome.ts";
201 import {
202 BUNDLED_CLAUDE_MODEL_CATALOG,
203 resolveClaudeCatalogContextWindowTokens,
204 type ClaudeModelCatalog,
205 getClaudeCatalogModelCapabilities,
206 resolveClaudeModelSlug,
207 resolveClaudeReportedModelSlug,
208 scopeClaudeModelCatalog,
209 } from "../../provider/ClaudeModelCatalog.ts";
210 import {
211 boundProviderEventForLogging,
212 shouldPersistProviderEvent,
213 } from "../../provider/EventNdjsonLogger.ts";
214 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
215 import {
216 claudeRateLimitEventToUpdate,
217 type ClaudeScopedLimitNames,
218 } from "../../provider/claudeUsageLimits.ts";
219 import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
220 import {
221 T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
222 T3_CODE_ORCHESTRATION_INSTRUCTIONS,
223 } from "@t3tools/provider-core/server/orchestrationInstructions";
224 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
225 import {
226 mcpToolPresentation,
227 normalizeMcpText,
228 } from "@t3tools/provider-core/server/mcpToolPresentation";
229 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
230 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
231 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
232 import {
233 makeProviderFailure,
234 makeProviderRetryTurnItem,
235 PROVIDER_RETRY_BUDGET_MS,
236 providerProcessExitGuidance,
237 } from "@t3tools/provider-core/server/failure";
238 import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
239 import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
240 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
241 import {
242 ProviderAdapterDriverCreateError,
243 type ProviderAdapterDriverCreateInput,
244 } from "@t3tools/provider-core/server/adapterDriver";
245 import {
246 type BackgroundWorkReport,
247 backgroundWorkNotification,
248 } from "@t3tools/provider-core/server/notification";
249 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
250 import {
251 makeSubagentChildThread,
252 makeSubagentConversationArtifacts,
253 subagentThreadTitle,
254 } from "@t3tools/provider-core/server/subagentProjection";
255
256 export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent");
257 /** The query exited before the turn attached, so the prompt was never offered. */
258 export const CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL =
259 "Claude provider query ended before the turn could start.";
260 const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const;
261
262 interface ClaudeCacheCreation {
263 readonly ephemeral_1h_input_tokens: number;
264 readonly ephemeral_5m_input_tokens: number;
265 }
266
267 function claudePromptCacheTtlMs(
268 cacheCreation: ClaudeCacheCreation | null | undefined,
269 ): number | undefined {
270 if (!cacheCreation) return undefined;
271 if (cacheCreation.ephemeral_1h_input_tokens > 0) return 60 * 60_000;
272 if (cacheCreation.ephemeral_5m_input_tokens > 0) return 5 * 60_000;
273 return undefined;
274 }
275
276 // Claude caps the window at the model's context, so a setting at or above it never applies.
277 // Below that, Claude compacts 33,000 tokens short of the window: Claude Code 2.1.305's
278 // getContextUsage reports a 150,000 window as a 117,000 threshold, for every catalog model.
279 const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000;
280
281 // Claude Code's isEnvTruthy.
282 function isClaudeEnvTruthy(value: string | undefined): boolean {
283 return value !== undefined && ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
284 }
285
286 function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number | null) {
287 const windowTokens = Number(autoCompactWindow);
288 return windowTokens > 0 && (maxTokens === null || windowTokens < maxTokens)
289 ? { autoCompactThreshold: windowTokens - CLAUDE_AUTO_COMPACT_RESERVE_TOKENS }
290 : {};
291 }
292
293 function claudeMessageInputTokens(usage: {
294 readonly input_tokens: number;
295 readonly cache_creation_input_tokens?: number | null;
296 readonly cache_read_input_tokens?: number | null;
297 }): number {
298 return (
299 usage.input_tokens +
300 (usage.cache_creation_input_tokens ?? 0) +
301 (usage.cache_read_input_tokens ?? 0)
302 );
303 }
304
305 export function claudeProviderTurnTokenUsage(
306 usage: {
307 readonly input_tokens: number;
308 readonly cache_creation_input_tokens?: number | null;
309 readonly cache_read_input_tokens?: number | null;
310 readonly cache_creation?: ClaudeCacheCreation | null;
311 readonly output_tokens: number;
312 },
313 maxTokens: number | null,
314 updatedAt: string,
315 autoCompactWindow = "",
316 requestedAt?: DateTime.Utc,
317 ) {
318 const inputTokens = claudeMessageInputTokens(usage);
319 const outputTokens = usage.output_tokens;
320 const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation);
321 // The cache lifetime starts with the request, not when its response ends.
322 const promptCacheExpiresAt =
323 promptCacheTtlMs === undefined || requestedAt === undefined
324 ? undefined
325 : DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs }));
326 return {
327 usedTokens: inputTokens + outputTokens,
328 maxTokens,
329 inputTokens,
330 cachedInputTokens: usage.cache_read_input_tokens ?? 0,
331 outputTokens,
332 reasoningOutputTokens: 0,
333 ...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }),
334 ...claudeAutoCompactThreshold(autoCompactWindow, maxTokens),
335 ...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }),
336 updatedAt,
337 };
338 }
339
340 type ClaudeMessageUsage = Parameters<typeof claudeProviderTurnTokenUsage>[0];
341
342 // message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them.
343 function mergeClaudeStreamUsage(
344 current: ClaudeMessageUsage,
345 delta: {
346 readonly input_tokens?: number | null;
347 readonly cache_creation_input_tokens?: number | null;
348 readonly cache_read_input_tokens?: number | null;
349 readonly output_tokens: number;
350 },
351 ): ClaudeMessageUsage {
352 return {
353 ...current,
354 input_tokens: delta.input_tokens ?? current.input_tokens,
355 cache_creation_input_tokens:
356 delta.cache_creation_input_tokens ?? current.cache_creation_input_tokens ?? null,
357 cache_read_input_tokens:
358 delta.cache_read_input_tokens ?? current.cache_read_input_tokens ?? null,
359 output_tokens: delta.output_tokens,
360 };
361 }
362 export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER);
363 const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
364 // The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server.
365 const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
366 const CLAUDE_BOOT_TIMEOUT = "5 minutes";
367 // Claude can consume a subagent result before the launching turn ends, leaving
368 // its notification with no native wake turn to answer the continuation.
369 const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
370 // Claude Code flushes transcript writes every 100 ms, so a workflow member's
371 // reply can land after the progress frame that settles it. Its transcript
372 // stays the source of its answer this long after it settles.
373 const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
374 // A steer waits at most this long, from its request, for its foreground
375 // subagents to move to the background before it is sent.
376 const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
377 // How long a Stop waits for the CLI to exit before the user is offered Force stop.
378 const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
379 // Matches the stderr tail the SDK keeps for a CLI it spawns itself.
380 const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
381 // The process group is killed on exit, so its stderr closes promptly.
382 const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
383 // How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
384 const CLAUDE_DESCENDANT_POLL = "1 second";
385 // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
386 const CLAUDE_ROOT_REFUSAL =
387 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
388 // Claude Code's answer to a --resume whose session store is gone, as a result error and on stderr.
389 const CLAUDE_CONVERSATION_NOT_FOUND = "No conversation found with session ID:";
390
391 // fd 4 gates the launch until the server has recorded the process it is about to become.
392 // The shell enters the cwd itself: as a native cwd, a mount that hangs chdir freezes the server.
393 const CLAUDE_GROUP_WATCH_SCRIPT = [
394 "read -r _ <&4 || exit 1",
395 "exec 4<&-",
396 "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
397 'cd -P -- "$1" || exit 125',
398 "shift",
399 'exec "$@" 3<&-',
400 ].join("\n");
401
402 /**
403 * Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for
404 * setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on
405 * EOF from a pipe only this server holds, including when the server crashes. `register` records
406 * the CLI before it may run, so a restarted server can reap it if the watcher did not.
407 */
408 export function spawnClaudeProcessGroup(
409 options: ClaudeSpawnOptions,
410 onExit?: () => void,
411 onStderr: (text: string) => void = () => {},
412 onStderrClose: () => void = () => {},
413 register?: (pid: number) => () => void,
414 ): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
415 // Relative to the server's cwd, as a native cwd is; the `./` keeps CDPATH out of it.
416 const cwd = options.cwd ?? ".";
417 const child = NodeChildProcess.spawn(
418 "/bin/sh",
419 [
420 "-c",
421 CLAUDE_GROUP_WATCH_SCRIPT,
422 "t3-claude",
423 cwd.startsWith("/") ? cwd : `./${cwd}`,
424 options.command,
425 ...options.args,
426 ],
427 {
428 env: options.env,
429 signal: options.signal,
430 stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"],
431 detached: true,
432 },
433 );
434 let forget: (() => void) | undefined;
435 // Always drained, so a chatty CLI never blocks on a full stderr pipe.
436 child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose);
437 child.once("exit", () => {
438 try {
439 signalProcessGroup(child.pid ?? 0, "SIGKILL");
440 } catch {}
441 try {
442 forget?.();
443 } catch {}
444 onExit?.();
445 });
446 const gate = child.stdio[4];
447 if (child.pid !== undefined && gate !== null && gate !== undefined && "end" in gate) {
448 try {
449 forget = register?.(child.pid);
450 gate.on("error", () => child.kill("SIGKILL"));
451 gate.end("ready\n");
452 } catch (cause) {
453 child.kill("SIGKILL");
454 gate.destroy();
455 throw cause;
456 }
457 }
458 // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
459 return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid">;
460 }
461
462 interface ClaudeProcessRow {
463 readonly pid: number;
464 readonly ppid: number;
465 readonly pgid: number;
466 readonly started: string;
467 }
468
469 /** Parses `ps -A -o pid=,ppid=,pgid=,lstart=`; pid plus start time tells a process from a reused pid. */
470 function parseClaudeProcessTable(table: string): ReadonlyArray<ClaudeProcessRow> {
471 return table.split("\n").flatMap((line) => {
472 const [pid, ppid, pgid, ...started] = line.trim().split(/\s+/);
473 const row = {
474 pid: Number(pid),
475 ppid: Number(ppid),
476 pgid: Number(pgid),
477 started: started.join(" "),
478 };
479 return Number.isSafeInteger(row.pid) &&
480 Number.isSafeInteger(row.ppid) &&
481 Number.isSafeInteger(row.pgid) &&
482 row.started
483 ? [row]
484 : [];
485 });
486 }
487
488 // A job leading its own group takes the processes it started since with it.
489 function killClaudeDescendant(row: ClaudeProcessRow) {
490 try {
491 if (row.pgid === row.pid) signalProcessGroup(row.pid, "SIGKILL");
492 else process.kill(row.pid, "SIGKILL");
493 } catch {}
494 }
495
496 function claudeDescendants(
497 rows: ReadonlyArray<ClaudeProcessRow>,
498 rootPids: ReadonlyArray<number>,
499 ): ReadonlyArray<ClaudeProcessRow> {
500 const children = Map.groupBy(rows, (row) => row.ppid);
501 const found: Array<ClaudeProcessRow> = [];
502 const seen = new Set<number>(rootPids);
503 const pending = [...rootPids];
504 for (let parent = pending.pop(); parent !== undefined; parent = pending.pop()) {
505 for (const child of children.get(parent) ?? []) {
506 if (seen.has(child.pid)) continue;
507 seen.add(child.pid);
508 found.push(child);
509 pending.push(child.pid);
510 }
511 }
512 return found;
513 }
514
515 /** What a CLI started, by pid and start time, recorded from each process table read while it runs. */
516 export function makeClaudeDescendantTracker(
517 cliPid: number,
518 readProcessTable: Effect.Effect<ReadonlyArray<ClaudeProcessRow>>,
519 ) {
520 const tracked = new Map<string, ClaudeProcessRow>();
521 const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
522 // The poll, a session close and the exit read one at a time, so each table is newer than all
523 // recorded here, and a pid and start time it no longer lists never run again.
524 const reading = Semaphore.makeUnsafe(1);
525 // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
526 const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(
527 function* (cliRunning: boolean) {
528 const rows = yield* readProcessTable;
529 const running = new Set(rows.map(identity));
530 // `ps -A` lists itself, so no rows is a failed read.
531 if (rows.length === 0) return running;
532 const roots = cliRunning ? [cliPid] : [];
533 for (const [key, row] of tracked) {
534 if (running.has(key)) roots.push(row.pid);
535 else tracked.delete(key);
536 }
537 for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
538 return running;
539 },
540 (effect) => reading.withPermits(1)(effect),
541 );
542 return {
543 tracked: tracked as ReadonlyMap<string, ClaudeProcessRow>,
544 refresh: refresh(true).pipe(Effect.asVoid),
545 /** Reads the table after the CLI exited: what it left that is still the same process. */
546 leftovers: refresh(false).pipe(
547 Effect.map((running) => [...tracked.values()].filter((row) => running.has(identity(row)))),
548 ),
549 };
550 }
551
552 export const ClaudeProviderCapabilitiesV2 = {
553 sessions: {
554 supportsMultipleProviderThreadsPerSession: false,
555 supportsModelSwitchInSession: true,
556 supportsProviderSwitchingViaHandoff: true,
557 supportsRuntimeModeSwitchInSession: false,
558 pendingRequestsSurviveRestart: false,
559 },
560 threads: {
561 canCreateEmptyThread: true,
562 canReadThreadSnapshot: false,
563 canRollbackThread: true,
564 canForkThread: true,
565 canForkFromTurn: true,
566 canForkWhileSourceRunning: true,
567 canForkFromSubagentThread: false,
568 exposesNativeThreadId: true,
569 },
570 turns: {
571 exposesNativeTurnId: false,
572 emitsTurnStarted: true,
573 emitsTurnCompleted: true,
574 supportsInterrupt: true,
575 supportsNativeResume: true,
576 supportsActiveSteering: true,
577 activeSteeringInterruptsTools: false,
578 supportsSteeringByInterruptRestart: false,
579 supportsQueuedMessages: true,
580 terminalStatusQuality: "strong",
581 },
582 streaming: {
583 streamsAssistantText: true,
584 streamsReasoning: true,
585 streamsToolOutput: false,
586 streamsPlanText: false,
587 emitsMessageCompleted: true,
588 },
589 tools: {
590 exposesToolItemIds: true,
591 emitsToolStarted: true,
592 emitsToolCompleted: true,
593 emitsToolOutput: true,
594 supportsMcpTools: true,
595 supportsDynamicToolCallbacks: true,
596 supportsBackgroundWait: true,
597 },
598 approvals: {
599 supportsCommandApproval: true,
600 supportsFileReadApproval: true,
601 supportsFileChangeApproval: true,
602 supportsApplyPatchApproval: false,
603 approvalsHaveNativeRequestIds: true,
604 approvalCallbacksAreLiveOnly: true,
605 approvalsCanOriginateFromSubagents: false,
606 },
607 planning: {
608 emitsPlanUpdated: true,
609 emitsTodoList: true,
610 emitsProposedPlan: true,
611 supportsStructuredQuestions: true,
612 planDeltasHaveItemIds: false,
613 },
614 subagents: {
615 supportsSubagents: true,
616 exposesSubagentThreadIds: false,
617 emitsSubagentLifecycle: true,
618 canWaitForSubagents: false,
619 canCloseSubagents: false,
620 canForkSubagentThread: false,
621 },
622 context: {
623 acceptsSystemContext: true,
624 acceptsDeveloperContext: true,
625 acceptsSyntheticUserContext: true,
626 canGenerateSummaries: true,
627 canConsumeHandoffSummaries: true,
628 supportsDeltaHandoff: true,
629 supportsFullThreadHandoff: true,
630 maxRecommendedHandoffChars: null,
631 },
632 checkpointing: {
633 appCanCheckpointFilesystem: true,
634 supportsNestedCheckpointScopes: true,
635 providerCanRollbackConversation: true,
636 providerRollbackReturnsSnapshot: true,
637 providerCanReadConversationSnapshot: false,
638 },
639 identity: {
640 nativeThreadIds: "strong",
641 nativeTurnIds: "weak",
642 nativeItemIds: "strong",
643 nativeRequestIds: "strong",
644 },
645 runtimePolicy: {
646 enforcement: "native",
647 },
648 } satisfies OrchestrationV2ProviderCapabilities;
649
650 const CLAUDE_CODE_PRESET_TOOLS = {
651 type: "preset",
652 preset: "claude_code",
653 } satisfies NonNullable<ClaudeQueryOptions["tools"]>;
654
655 export type ClaudeAgentSdkQueryToolList = ReadonlyArray<string>;
656 export interface ClaudeAgentSdkQueryPresetTools {
657 readonly type: "preset";
658 readonly preset: "claude_code";
659 }
660 export type ClaudeAgentSdkQueryTools = ClaudeAgentSdkQueryToolList | ClaudeAgentSdkQueryPresetTools;
661
662 export const CLAUDE_READ_ONLY_ALLOWED_TOOLS = ["Read", "Glob", "Grep"] as const;
663
664 function claudeAgentSdkQueryToolsForSdk(
665 tools: ClaudeAgentSdkQueryTools,
666 ): NonNullable<ClaudeQueryOptions["tools"]> {
667 if (isClaudeAgentSdkQueryToolList(tools)) {
668 return [...tools];
669 }
670 return { type: tools.type, preset: tools.preset };
671 }
672
673 function isClaudeAgentSdkQueryToolList(
674 tools: ClaudeAgentSdkQueryTools,
675 ): tools is ClaudeAgentSdkQueryToolList {
676 return Array.isArray(tools);
677 }
678
679 type ClaudeAgentSdkThreadIdentity =
680 | {
681 readonly sessionId: string;
682 readonly resume?: never;
683 }
684 | {
685 readonly sessionId?: never;
686 readonly resume: string;
687 };
688
689 export type ClaudeAgentSdkQueryOptions = Omit<
690 ClaudeQueryOptions,
691 "maxTurns" | "model" | "permissionMode" | "resume" | "sessionId" | "tools"
692 > & {
693 readonly model: string;
694 readonly tools: NonNullable<ClaudeQueryOptions["tools"]>;
695 readonly permissionMode: NonNullable<ClaudeQueryOptions["permissionMode"]>;
696 } & ClaudeAgentSdkThreadIdentity;
697
698 export interface ClaudeAgentSdkQueryOpenInput {
699 readonly resume?: true;
700 readonly options: ClaudeAgentSdkQueryOptions;
701 readonly threadId: ThreadId;
702 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
703 }
704
705 export interface ClaudeAgentSdkQuerySession {
706 readonly messages: Stream.Stream<SDKMessage, ClaudeAgentSdkQueryRunnerError>;
707 readonly offer: (
708 message: SDKUserMessage,
709 onQueued?: () => void,
710 ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
711 readonly setModel: (model: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
712 readonly applyFlagSettings: (
713 settings: ClaudeFlagSettings,
714 ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
715 readonly setPermissionMode: (
716 mode: PermissionMode,
717 ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
718 readonly renameSession: (title: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
719 readonly stopTask: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
720 readonly backgroundTasks: (
721 toolUseId: string,
722 ) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
723 readonly mcpServerStatus: Effect.Effect<
724 ReadonlyArray<ClaudeMcpServerStatus>,
725 ClaudeAgentSdkQueryRunnerError
726 >;
727 readonly readMcpResource: (input: {
728 readonly server: string;
729 readonly uri: string;
730 }) => Effect.Effect<
731 { readonly contents: ReadonlyArray<unknown> },
732 ClaudeAgentSdkQueryRunnerError
733 >;
734 /** Starts an MCP server's sign-in. The CLI never opens a browser; null means none is needed. */
735 readonly mcpAuthenticate: (
736 server: string,
737 ) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
738 /** Finishes it with the address the browser was sent to; the CLI checks its state. */
739 readonly mcpSubmitOAuthCallbackUrl: (input: {
740 readonly server: string;
741 readonly callbackUrl: string;
742 }) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
743 readonly reconnectMcpServer: (
744 server: string,
745 ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
746 /** Runs an MCP tool without a model turn and returns the server's raw `CallToolResult`. */
747 readonly callMcpTool: (input: {
748 readonly tool: string;
749 readonly arguments: Record<string, unknown>;
750 }) => Effect.Effect<unknown, ClaudeAgentSdkQueryRunnerError>;
751 readonly listPermissionRules: Effect.Effect<
752 ReadonlyArray<ClaudePermissionRule>,
753 ClaudeAgentSdkQueryRunnerError
754 >;
755 readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
756 readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
757 }
758
759 type ClaudeQueryStreamExit = Exit.Exit<void, ClaudeAgentSdkQueryRunnerError>;
760
761 export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAgentSdkQueryRunnerError>()(
762 "ClaudeAgentSdkQueryRunnerError",
763 {
764 method: Schema.String,
765 cause: Schema.Defect(),
766 },
767 ) {
768 override get message(): string {
769 return "Claude Agent SDK query failed.";
770 }
771 }
772
773 export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRootRefusalError>()(
774 "ClaudeCodeRootRefusalError",
775 {
776 cause: Schema.Defect(),
777 },
778 ) {
779 override get message(): string {
780 return `Claude Code exited before it started: ${CLAUDE_ROOT_REFUSAL}`;
781 }
782 }
783
784 export class ClaudeConversationNotFoundError extends Schema.TaggedError<ClaudeConversationNotFoundError>()(
785 "ClaudeConversationNotFoundError",
786 {
787 cause: Schema.Defect(),
788 },
789 ) {
790 override get message(): string {
791 return "Claude Code could not find this conversation to resume. Send the message again to continue in a new Claude session with this thread's history.";
792 }
793 }
794
795 export class ClaudeCodeStartupExitError extends Schema.TaggedError<ClaudeCodeStartupExitError>()(
796 "ClaudeCodeStartupExitError",
797 {
798 status: Schema.String,
799 guidance: Schema.String,
800 cause: Schema.Defect(),
801 },
802 ) {
803 override get message(): string {
804 return `${this.status} before it started. ${this.guidance}`;
805 }
806 }
807
808 class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
809 "ClaudeMcpRegistrationTimeoutError",
810 { phase: Schema.Literals(["initialize", "setMcpServers"]) },
811 ) {
812 override get message(): string {
813 return this.phase === "initialize"
814 ? "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs."
815 : "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
816 }
817 }
818
819 export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError<ClaudeBackgroundWorkBlocksQueryReplacementError>()(
820 "ClaudeBackgroundWorkBlocksQueryReplacementError",
821 {},
822 ) {
823 override get message(): string {
824 return "Claude is still running background agents or commands, and this model or setting change would end them. Wait for them to finish, or press Stop, then send the message again.";
825 }
826 }
827
828 export class ClaudeAppendSystemPromptFileError extends Schema.TaggedError<ClaudeAppendSystemPromptFileError>()(
829 "ClaudeAppendSystemPromptFileError",
830 {
831 path: Schema.String,
832 cause: Schema.optional(Schema.Defect()),
833 },
834 ) {
835 override get message(): string {
836 return `Claude could not read the --append-system-prompt-file launch argument at ${this.path}. Fix the path in the Claude launch arguments, then send the message again.`;
837 }
838 }
839
840 export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedError<ClaudeAppendSystemPromptMissingValueError>()(
841 "ClaudeAppendSystemPromptMissingValueError",
842 { flag: Schema.Literals(["--append-system-prompt", "--append-system-prompt-file"]) },
843 ) {
844 override get message(): string {
845 return `The ${this.flag} launch argument has no ${this.flag === "--append-system-prompt" ? "text" : "file path"}. Add it after the flag in the Claude launch arguments, then send the message again.`;
846 }
847 }
848
849 export class ClaudeSettingsLaunchArgError extends Schema.TaggedError<ClaudeSettingsLaunchArgError>()(
850 "ClaudeSettingsLaunchArgError",
851 {
852 path: Schema.optional(Schema.String),
853 cause: Schema.optional(Schema.Defect()),
854 },
855 ) {
856 override get message(): string {
857 return `Claude could not read the --settings launch argument${this.path === undefined ? "" : ` at ${this.path}`} as a JSON object. Fix it in the Claude launch arguments, then send the message again.`;
858 }
859 }
860
861 export interface ClaudeAgentSdkQueryRunnerShape {
862 readonly allocateSessionId: Effect.Effect<string, ClaudeAgentSdkQueryRunnerError>;
863 readonly open: (
864 input: ClaudeAgentSdkQueryOpenInput,
865 ) => Effect.Effect<ClaudeAgentSdkQuerySession, ClaudeAgentSdkQueryRunnerError>;
866 readonly forkSession: (
867 input: ClaudeAgentSdkSessionForkInput,
868 ) => Effect.Effect<
869 ForkSessionResult & { readonly headMessageId?: string },
870 ClaudeAgentSdkQueryRunnerError
871 >;
872 readonly subagentLaunchToolUseId: (
873 input: ClaudeAgentSdkSubagentLookupInput,
874 ) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
875 /** The model a subagent's transcript says it ran on. */
876 readonly subagentModel: (
877 input: ClaudeAgentSdkSubagentLookupInput,
878 ) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
879 readonly assertComplete: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
880 }
881
882 export class ClaudeAgentSdkQueryRunner extends Context.Service<
883 ClaudeAgentSdkQueryRunner,
884 ClaudeAgentSdkQueryRunnerShape
885 >()("t3/orchestration-v2/Adapters/ClaudeAdapterV2/ClaudeAgentSdkQueryRunner") {}
886
887 export interface ClaudeAgentSdkSessionForkInput {
888 readonly sessionId: string;
889 readonly options: ForkSessionOptions;
890 readonly environment: NodeJS.ProcessEnv;
891 readonly threadId: ThreadId;
892 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
893 }
894
895 export interface ClaudeAgentSdkSubagentLookupInput {
896 readonly sessionId: string;
897 readonly agentId: string;
898 readonly dir: string | null;
899 readonly threadId: ThreadId;
900 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
901 }
902
903 const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
904
905 const isClaudeConversationNotFound = (cause: Cause.Cause<ClaudeAgentSdkQueryRunnerError>) => {
906 const error = Cause.squash(cause);
907 return (
908 isClaudeAgentSdkQueryRunnerError(error) &&
909 Predicate.isTagged(error.cause, "ClaudeConversationNotFoundError")
910 );
911 };
912 const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError);
913 const isProviderAdapterRuntimeRequestResponseError = Schema.is(
914 ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
915 );
916 const isProviderAdapterRollbackThreadError = Schema.is(
917 ProviderAdapter.ProviderAdapterRollbackThreadError,
918 );
919
920 function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRunnerError {
921 return isClaudeAgentSdkQueryRunnerError(cause)
922 ? cause
923 : new ClaudeAgentSdkQueryRunnerError({ cause, method });
924 }
925
926 const CLAUDE_PROCESS_EXIT_ERROR_CLASSES: ReadonlySet<unknown> = new Set([
927 "process_killed_by_signal",
928 "process_exited_nonzero",
929 ]);
930
931 // The SDK's exit Error appends Claude's stderr tail to `message`; `telemetryMessage` omits it.
932 function claudeProcessExit(
933 sdkError: unknown,
934 ): { readonly status: string; readonly code: string } | undefined {
935 if (typeof sdkError !== "object" || sdkError === null) return undefined;
936 const { errorClass, telemetryMessage } = sdkError as Record<string, unknown>;
937 return typeof errorClass === "string" &&
938 CLAUDE_PROCESS_EXIT_ERROR_CLASSES.has(errorClass) &&
939 typeof telemetryMessage === "string"
940 ? { status: telemetryMessage, code: errorClass }
941 : undefined;
942 }
943
944 function claudeProcessExitFailure(
945 cause: Cause.Cause<ClaudeAgentSdkQueryRunnerError>,
946 ): { readonly message: string; readonly code: string } | undefined {
947 const error = Cause.squash(cause);
948 const exit = claudeProcessExit(isClaudeAgentSdkQueryRunnerError(error) ? error.cause : error);
949 return exit === undefined ? undefined : { message: `${exit.status}.`, code: exit.code };
950 }
951
952 function closeClaudeQuery(queryRuntime: ClaudeQuery) {
953 return Effect.try({
954 try: () => queryRuntime.close(),
955 catch: (cause) => queryRunnerError(cause, "close"),
956 });
957 }
958
959 // SDK 0.3.316 types `mcp_call` and `list_permission_rules` but has no Query method for them; its own readMcpResource sends control requests this way.
960 async function sendClaudeControlRequest(
961 queryRuntime: ClaudeQuery,
962 request: {
963 readonly subtype:
964 | "mcp_call"
965 | "list_permission_rules"
966 | "rename_session"
967 | "mcp_authenticate"
968 | "mcp_oauth_callback_url";
969 readonly [key: string]: unknown;
970 },
971 ): Promise<unknown> {
972 const send: unknown = Reflect.get(queryRuntime, "request");
973 if (typeof send !== "function") {
974 throw new Error(`This Claude Agent SDK cannot send ${request.subtype}.`);
975 }
976 const reply: unknown = await Reflect.apply(send, queryRuntime, [request]);
977 return Predicate.isObject(reply) ? reply.response : undefined;
978 }
979
980 const decodeClaudeMcpAuthenticateReply = Schema.decodeUnknownEffect(
981 Schema.Struct({
982 authUrl: Schema.optional(Schema.String),
983 requiresUserAction: Schema.optional(Schema.Boolean),
984 }),
985 );
986
987 const ClaudePermissionRules = Schema.Struct({
988 state: Schema.Struct({
989 rules: Schema.Array(
990 Schema.Struct({
991 behavior: Schema.Literals(["allow", "deny", "ask"]),
992 rule: Schema.String,
993 notInEffect: Schema.optional(Schema.Boolean),
994 }),
995 ),
996 errors: Schema.optional(Schema.Array(Schema.Unknown)),
997 }),
998 });
999 export type ClaudePermissionRule = (typeof ClaudePermissionRules.Type)["state"]["rules"][number];
1000 const decodeClaudePermissionRules = Schema.decodeUnknownEffect(ClaudePermissionRules);
1001
1002 // Without these, tools carry no `_meta.ui` and a model-shaped result would reach the app.
1003 const CLAUDE_MCP_APP_CAPABILITIES = [
1004 "mcp_tool_ui_meta_v1",
1005 "mcp_read_resource_v1",
1006 "mcp_call_result_not_for_model_v1",
1007 ] as const;
1008 // Captured inline, unlike Codex's shared app-server: a slow read delays only this session's stream, and only this long.
1009 const CLAUDE_MCP_APP_CAPTURE_TIMEOUT = "20 seconds";
1010
1011 function claudeSupportsMcpApps(capabilities: ReadonlySet<string>): boolean {
1012 return CLAUDE_MCP_APP_CAPABILITIES.every((capability) => capabilities.has(capability));
1013 }
1014
1015 // Claude Code routes `mcp__a__b__tool` to server `a` even when `a__b` is connected, so either prefix is ambiguous.
1016 function claudeMcpServerPrefixOverlaps(
1017 statuses: ReadonlyArray<ClaudeMcpServerStatus>,
1018 server: string,
1019 ): boolean {
1020 const prefix = claudeMcpToolPrefix(server);
1021 return statuses.some((status) => {
1022 if (status.name === server) return false;
1023 const other = claudeMcpToolPrefix(status.name);
1024 return other.startsWith(prefix) || prefix.startsWith(other);
1025 });
1026 }
1027
1028 function findClaudeMcpTool(
1029 statuses: ReadonlyArray<ClaudeMcpServerStatus>,
1030 toolName: string,
1031 ):
1032 | { readonly server: string; readonly tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number] }
1033 | undefined {
1034 const matches = statuses.flatMap((status) => {
1035 if (status.status !== "connected") return [];
1036 const prefix = claudeMcpToolPrefix(status.name);
1037 if (!toolName.startsWith(prefix)) return [];
1038 return (status.tools ?? [])
1039 .filter((tool) => `${prefix}${claudeMcpToolNamePart(tool.name)}` === toolName)
1040 .map((tool) => ({ server: status.name, tool }));
1041 });
1042 const [match, ...others] = matches;
1043 return match === undefined ||
1044 others.length > 0 ||
1045 claudeMcpServerPrefixOverlaps(statuses, match.server)
1046 ? undefined
1047 : match;
1048 }
1049
1050 // Only this adapter writes app references. Claude's normalised tool names cannot tie one in raw MCP output to its server.
1051 function withoutForgedMcpApp(output: ClaudeNativeToolOutput): ClaudeNativeToolOutput {
1052 const value = claudeNativeToolOutputValue(output);
1053 return compactDynamicToolOutput(value)?.[MCP_APP_OUTPUT_KEY] === undefined
1054 ? output
1055 : { type: "structured_tool_use_result", value: { result: value } };
1056 }
1057
1058 /**
1059 * Deliberately broader than Claude's matcher: Claude also matches rules against server aliases T3
1060 * can't list, and an alias may contain `__`, so any `mcp__` rule or wildcard may cover any MCP tool.
1061 * A false match only refuses a card's call, or asks first.
1062 */
1063 function claudeRulesMayCoverMcpTools(
1064 rules: ReadonlyArray<ClaudePermissionRule>,
1065 behaviors: ReadonlyArray<ClaudePermissionRule["behavior"]>,
1066 ): boolean {
1067 return rules.some((entry) => {
1068 const name = entry.rule.split("(", 1)[0] ?? entry.rule;
1069 return (
1070 behaviors.includes(entry.behavior) &&
1071 entry.notInEffect !== true &&
1072 (name.startsWith("mcp__") || name.includes("*"))
1073 );
1074 });
1075 }
1076
1077 /**
1078 * Claude reports `annotations` as `readOnly`/`destructive`/`openWorld`; apps expect MCP's `*Hint` names.
1079 * Card calls skip Claude's permission check, so `readOnlyHint`, which skips T3's prompt, needs readable
1080 * rules (null when not) with no ask or deny rule that may cover the tool.
1081 */
1082 function claudeMcpToolForApps(
1083 tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number],
1084 rules: ReadonlyArray<ClaudePermissionRule> | null,
1085 ) {
1086 const annotations = tool.annotations ?? {};
1087 const readOnlyHint =
1088 annotations.readOnly !== true ||
1089 (rules !== null && !claudeRulesMayCoverMcpTools(rules, ["ask", "deny"]))
1090 ? annotations.readOnly
1091 : undefined;
1092 return {
1093 name: tool.name,
1094 ...(tool.description === undefined ? {} : { description: tool.description }),
1095 // The CLI reports no input schemas; apps require one in `hostContext.toolInfo.tool`.
1096 inputSchema: { type: "object" },
1097 ...(tool._meta === undefined ? {} : { _meta: tool._meta }),
1098 annotations: {
1099 ...(readOnlyHint === undefined ? {} : { readOnlyHint }),
1100 ...(annotations.destructive === undefined
1101 ? {}
1102 : { destructiveHint: annotations.destructive }),
1103 ...(annotations.openWorld === undefined ? {} : { openWorldHint: annotations.openWorld }),
1104 },
1105 };
1106 }
1107
1108 /** A model-turn MCP `tool_use_result` flattens text `content` to a string; app calls return MCP's raw `CallToolResult`. */
1109 function claudeMcpCallToolResult(
1110 value: unknown,
1111 ): ProviderAdapter.ProviderAdapterV2McpCallToolResult {
1112 const record = Predicate.isObject(value) && !Array.isArray(value) ? value : undefined;
1113 const content = record === undefined ? value : record.content;
1114 return {
1115 content:
1116 typeof content === "string"
1117 ? [{ type: "text", text: content }]
1118 : Array.isArray(content)
1119 ? content
1120 : [],
1121 ...(record?.structuredContent === undefined
1122 ? {}
1123 : { structuredContent: record.structuredContent }),
1124 ...(record?.isError === true ? { isError: true } : {}),
1125 ...(record?._meta === undefined ? {} : { _meta: record._meta }),
1126 };
1127 }
1128
1129 // Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption.
1130 export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {
1131 return { [Symbol.asyncIterator]: () => queryRuntime };
1132 }
1133
1134 export interface ClaudeAgentSdkLoggedQueryOptions {
1135 readonly model: ClaudeAgentSdkQueryOptions["model"];
1136 readonly tools: ClaudeAgentSdkQueryOptions["tools"];
1137 readonly permissionMode: ClaudeAgentSdkQueryOptions["permissionMode"];
1138 readonly sessionId?: string;
1139 readonly resume?: string;
1140 readonly resumeSessionAt?: ClaudeAgentSdkQueryOptions["resumeSessionAt"];
1141 readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
1142 readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
1143 readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
1144 readonly settingKeys?: ReadonlyArray<string>;
1145 readonly effort?: ClaudeAgentSdkQueryOptions["effort"];
1146 readonly includePartialMessages?: true;
1147 readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"];
1148 readonly hasExtraArgs?: true;
1149 readonly allowDangerouslySkipPermissions?: true;
1150 readonly hasCanUseTool?: true;
1151 readonly hasEnvironment?: true;
1152 readonly hasMcpServers?: true;
1153 }
1154
1155 export type ClaudeAgentSdkProtocolLogEvent =
1156 | {
1157 readonly direction: "outgoing";
1158 readonly stage: "decoded";
1159 readonly payload: {
1160 readonly type: "query.open";
1161 readonly options: ClaudeAgentSdkLoggedQueryOptions;
1162 };
1163 }
1164 | {
1165 readonly direction: "outgoing";
1166 readonly stage: "decoded";
1167 readonly payload: {
1168 readonly type: "prompt.offer";
1169 readonly message: SDKUserMessage;
1170 };
1171 }
1172 | {
1173 readonly direction: "outgoing";
1174 readonly stage: "decoded";
1175 readonly payload: {
1176 readonly type: "query.set_model";
1177 readonly model: string;
1178 };
1179 }
1180 | {
1181 readonly direction: "outgoing";
1182 readonly stage: "decoded";
1183 readonly payload: {
1184 readonly type: "query.apply_flag_settings";
1185 readonly settings: ClaudeFlagSettings;
1186 };
1187 }
1188 | {
1189 readonly direction: "outgoing";
1190 readonly stage: "decoded";
1191 readonly payload: {
1192 readonly type: "query.set_permission_mode";
1193 readonly mode: PermissionMode;
1194 };
1195 }
1196 | {
1197 readonly direction: "outgoing";
1198 readonly stage: "decoded";
1199 readonly payload: {
1200 readonly type: "query.rename_session";
1201 readonly title: string;
1202 };
1203 }
1204 | {
1205 readonly direction: "outgoing";
1206 readonly stage: "decoded";
1207 readonly payload: {
1208 readonly type: "query.stop_task";
1209 readonly taskId: string;
1210 };
1211 }
1212 | {
1213 readonly direction: "outgoing";
1214 readonly stage: "decoded";
1215 readonly payload: {
1216 readonly type: "query.background_tasks";
1217 readonly toolUseId: string;
1218 };
1219 }
1220 | {
1221 readonly direction: "outgoing";
1222 readonly stage: "decoded";
1223 readonly payload: {
1224 readonly type: "query.interrupt";
1225 };
1226 }
1227 | {
1228 readonly direction: "outgoing";
1229 readonly stage: "decoded";
1230 readonly payload: {
1231 readonly type: "query.close";
1232 };
1233 }
1234 | {
1235 readonly direction: "outgoing";
1236 readonly stage: "decoded";
1237 readonly payload: {
1238 readonly type: "session.fork";
1239 readonly sessionId: string;
1240 readonly options: ForkSessionOptions;
1241 };
1242 }
1243 | {
1244 readonly direction: "incoming";
1245 readonly stage: "decoded";
1246 readonly payload: {
1247 readonly type: "session.forked";
1248 readonly sessionId: string;
1249 };
1250 }
1251 | {
1252 readonly direction: "outgoing";
1253 readonly stage: "decoded";
1254 readonly payload: {
1255 readonly type: "subagent.lookup";
1256 readonly sessionId: string;
1257 readonly agentId: string;
1258 };
1259 }
1260 | {
1261 readonly direction: "incoming";
1262 readonly stage: "decoded";
1263 readonly payload: {
1264 readonly type: "subagent.found";
1265 readonly toolUseId: string | null;
1266 };
1267 }
1268 | {
1269 readonly direction: "incoming";
1270 readonly stage: "decoded";
1271 readonly payload: SDKMessage;
1272 };
1273
1274 export type ClaudeAgentSdkProtocolLogger = (
1275 event: ClaudeAgentSdkProtocolLogEvent,
1276 ) => Effect.Effect<void>;
1277
1278 export function loggedClaudeQueryOptions(
1279 options: ClaudeAgentSdkQueryOptions,
1280 ): ClaudeAgentSdkLoggedQueryOptions {
1281 return {
1282 model: options.model,
1283 tools: options.tools,
1284 permissionMode: options.permissionMode,
1285 ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
1286 ...(options.resume === undefined ? {} : { resume: options.resume }),
1287 ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
1288 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
1289 ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
1290 ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
1291 // Settings can carry the user's --settings values, such as an env block with credentials.
1292 ...(typeof options.settings === "object" && options.settings !== null
1293 ? { settingKeys: Object.keys(options.settings) }
1294 : {}),
1295 ...(options.effort === undefined ? {} : { effort: options.effort }),
1296 ...(options.includePartialMessages === true ? { includePartialMessages: true } : {}),
1297 ...(options.pathToClaudeCodeExecutable === undefined
1298 ? {}
1299 : { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }),
1300 ...(options.extraArgs === undefined ? {} : { hasExtraArgs: true }),
1301 ...(options.allowDangerouslySkipPermissions === true
1302 ? { allowDangerouslySkipPermissions: true }
1303 : {}),
1304 ...(options.canUseTool === undefined ? {} : { hasCanUseTool: true }),
1305 ...(options.env === undefined ? {} : { hasEnvironment: true }),
1306 ...(options.mcpServers === undefined ? {} : { hasMcpServers: true }),
1307 };
1308 }
1309
1310 function makeClaudeAgentSdkProtocolLogger(input: {
1311 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
1312 readonly threadId: ThreadId;
1313 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
1314 }): ClaudeAgentSdkProtocolLogger | undefined {
1315 const { nativeEventLogger } = input;
1316 if (nativeEventLogger === undefined) {
1317 return undefined;
1318 }
1319
1320 return (event) => {
1321 if (!shouldPersistProviderEvent("native", event)) return Effect.void;
1322 return nativeEventLogger
1323 .write(
1324 {
1325 provider: CLAUDE_PROVIDER,
1326 protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
1327 kind: "protocol",
1328 providerSessionId: input.providerSessionId,
1329 event: boundProviderEventForLogging(event),
1330 },
1331 input.threadId,
1332 )
1333 .pipe(Effect.ignore);
1334 };
1335 }
1336
1337 const encodeClaudeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
1338 const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
1339 Schema.fromJsonString(
1340 Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
1341 ),
1342 );
1343
1344 const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect(
1345 Schema.fromJsonString(
1346 Schema.Array(
1347 Schema.Struct({
1348 type: Schema.String,
1349 uuid: Schema.String,
1350 message: Schema.Struct({ content: Schema.Unknown }),
1351 }),
1352 ),
1353 ),
1354 );
1355
1356 // Claude's interactive reply-on-resume removes native abort rows before querying the saved history.
1357 export function claudeResumeSessionAt(
1358 messages: ReadonlyArray<{
1359 readonly type: string;
1360 readonly uuid: string;
1361 readonly message: { readonly content: unknown };
1362 }>,
1363 ): string | undefined {
1364 let end = messages.length;
1365 let toolInterrupted = false;
1366 while (end > 0) {
1367 const message = messages[end - 1]!;
1368 const content = message.message.content;
1369 const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
1370 if (message.type !== "user" || !Array.isArray(blocks) || blocks.length === 0) break;
1371 const stop = blocks.every(
1372 (block: unknown) =>
1373 Predicate.isObject(block) &&
1374 block.type === "text" &&
1375 (block.text === "[Request interrupted by user]" ||
1376 block.text === "[Request interrupted by user for tool use]"),
1377 );
1378 if (stop) {
1379 toolInterrupted ||= blocks.some(
1380 (block: unknown) =>
1381 Predicate.isObject(block) && block.text === "[Request interrupted by user for tool use]",
1382 );
1383 end--;
1384 continue;
1385 }
1386 if (
1387 toolInterrupted &&
1388 blocks.every(
1389 (block: unknown) =>
1390 Predicate.isObject(block) &&
1391 block.type === "tool_result" &&
1392 block.is_error === true &&
1393 typeof block.content === "string" &&
1394 block.content.startsWith("The user doesn't want to proceed with this tool use."),
1395 )
1396 ) {
1397 end--;
1398 continue;
1399 }
1400 break;
1401 }
1402 return end === messages.length ? undefined : messages[end - 1]?.uuid;
1403 }
1404
1405 const claudeConfigDirOf = (
1406 path: Path.Path,
1407 environment: NodeJS.ProcessEnv,
1408 homeDirectory: string,
1409 ) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude"));
1410
1411 // The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
1412 // worker so concurrent providers keep the server's environment.
1413 const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
1414 readonly method: "forkSession" | "getSessionMessages";
1415 readonly sessionId: string;
1416 readonly options?: ForkSessionOptions;
1417 readonly environment: NodeJS.ProcessEnv;
1418 }) {
1419 const path = yield* Path.Path;
1420 const fromSource = import.meta.url.endsWith(".ts");
1421 // A single executable hosts the worker itself; it has no sibling script.
1422 const workerArguments = (yield* HostProcess.IsExecutable)
1423 ? ["__claude-history"]
1424 : [
1425 ...(fromSource ? ["--experimental-strip-types"] : []),
1426 yield* path.fromFileUrl(
1427 new URL(
1428 fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs",
1429 import.meta.url,
1430 ),
1431 ),
1432 ];
1433 const executablePath = yield* HostProcess.ExecutablePath;
1434 const result = yield* spawnAndCollect(
1435 executablePath,
1436 ChildProcess.make(
1437 executablePath,
1438 [...workerArguments, input.method, input.sessionId, encodeClaudeJson(input.options ?? {})],
1439 {
1440 env: {
1441 ...input.environment,
1442 ELECTRON_RUN_AS_NODE: "1",
1443 },
1444 },
1445 ),
1446 // Complete session histories have no status-probe size limit; stderr stays bounded.
1447 input.method === "getSessionMessages"
1448 ? { maxStdoutBytes: Number.POSITIVE_INFINITY }
1449 : undefined,
1450 ).pipe(Effect.timeout("30 seconds"));
1451 if (result.code !== 0) {
1452 return yield* new ClaudeAgentSdkQueryRunnerError({
1453 method: input.method,
1454 cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
1455 });
1456 }
1457 return result.stdout;
1458 });
1459
1460 const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
1461 input: ClaudeAgentSdkSessionForkInput,
1462 ) {
1463 return yield* runClaudeWorker({ ...input, method: "forkSession" }).pipe(
1464 Effect.flatMap(decodeClaudeHistoryFork),
1465 );
1466 });
1467
1468 const CLAUDE_CAN_USE_TOOL_SHADOWED_WARNING = "CLAUDE_SDK_CAN_USE_TOOL_SHADOWED";
1469
1470 // query() warns when canUseTool meets bypassPermissions or bare allowedTools. T3 installs
1471 // canUseTool in every mode on purpose (AskUserQuestion, ask rules), so it is per-session noise.
1472 export function withoutClaudeCanUseToolShadowedWarning<A>(run: () => A): A {
1473 const emitWarning = process.emitWarning;
1474 process.emitWarning = function (this: NodeJS.Process, ...args: Parameters<typeof emitWarning>) {
1475 const [, options] = args;
1476 if (typeof options === "object" && options.code === CLAUDE_CAN_USE_TOOL_SHADOWED_WARNING) {
1477 return;
1478 }
1479 return Reflect.apply(emitWarning, this, args);
1480 } as typeof emitWarning;
1481 try {
1482 return run();
1483 } finally {
1484 process.emitWarning = emitWarning;
1485 }
1486 }
1487
1488 export const layerQueryRunner: Layer.Layer<
1489 ClaudeAgentSdkQueryRunner,
1490 never,
1491 | ChildProcessSpawner.ChildProcessSpawner
1492 | SecureRandom.SecureRandom
1493 | Path.Path
1494 | PortScanner.PortDiscovery
1495 | ProviderEventLoggers.ProviderEventLoggers
1496 > = Layer.effect(
1497 ClaudeAgentSdkQueryRunner,
1498 Effect.gen(function* () {
1499 const random = yield* SecureRandom.SecureRandom;
1500 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1501 const path = yield* Path.Path;
1502 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
1503 const agentScope = yield* AgentScope;
1504 const providerProcesses = yield* ProviderProcesses.ProviderProcesses;
1505 const platform = yield* HostProcess.Platform;
1506 const runFork = Effect.runForkWith(yield* Effect.context<never>());
1507 const hostEnvironment = yield* HostProcess.Environment;
1508 const portDiscovery = yield* PortScanner.PortDiscovery;
1509 const processRunner = yield* ProcessRunner.make();
1510 const readProcessTable = processRunner
1511 .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })
1512 .pipe(
1513 Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
1514 Effect.orElseSucceed(() => []),
1515 );
1516 // Without an agent scope, a job that left the CLI's group escapes the group kill and is
1517 // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
1518 // still the same process (pid and start time) is stopped after it exits.
1519 const trackDescendants = (cliPid: number) => {
1520 const tracker = makeClaudeDescendantTracker(cliPid, readProcessTable);
1521 const stop = tracker.leftovers.pipe(
1522 Effect.map((rows) => {
1523 for (const row of rows) killClaudeDescendant(row);
1524 }),
1525 );
1526 return { refresh: tracker.refresh, stop };
1527 };
1528
1529 // The open span below is the tracing boundary for both attempts.
1530 const openQuery = Effect.fnUntraced(function* (input: ClaudeAgentSdkQueryOpenInput) {
1531 const protocolLogger = makeClaudeAgentSdkProtocolLogger({
1532 nativeEventLogger,
1533 threadId: input.threadId,
1534 providerSessionId: input.providerSessionId,
1535 });
1536 const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
1537 protocolLogger === undefined ? Effect.void : protocolLogger(event);
1538 // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
1539 const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
1540 const prompt = Stream.fromQueue(promptQueue).pipe(
1541 Stream.catchCause((cause) =>
1542 Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
1543 ),
1544 Stream.toAsyncIterable,
1545 );
1546 // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
1547 const { mcpServers, ...sdkOptions } = input.options;
1548 // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
1549 let resumeSessionAt = sdkOptions.resumeSessionAt;
1550 if (input.resume && sdkOptions.resume !== undefined) {
1551 const messages = yield* runClaudeWorker({
1552 method: "getSessionMessages",
1553 sessionId: sdkOptions.resume,
1554 options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
1555 environment: sdkOptions.env ?? hostEnvironment,
1556 }).pipe(
1557 Effect.flatMap(decodeClaudeHistoryMessages),
1558 Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
1559 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1560 Effect.provideService(Path.Path, path),
1561 );
1562 const boundary =
1563 resumeSessionAt === undefined
1564 ? messages.length
1565 : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
1566 resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
1567 }
1568 const queryOptions = {
1569 ...sdkOptions,
1570 ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
1571 env: {
1572 ...(sdkOptions.env ?? hostEnvironment),
1573 ...(input.resume
1574 ? {
1575 CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
1576 CLAUDE_CODE_RESUME_REASON: "user_resume",
1577 }
1578 : {}),
1579 [PortScanner.AGENT_THREAD_ENV]: input.threadId,
1580 },
1581 };
1582 // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
1583 const binaryPath = queryOptions.pathToClaudeCodeExecutable;
1584 const launch =
1585 binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
1586 ? undefined
1587 : yield* agentScope.wrap({
1588 command: binaryPath,
1589 args: [],
1590 name: "claude",
1591 threadId: input.threadId,
1592 env: queryOptions.env,
1593 });
1594 const options =
1595 launch === undefined || launch.args.length === 0
1596 ? queryOptions
1597 : {
1598 ...queryOptions,
1599 pathToClaudeCodeExecutable: launch.command,
1600 executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
1601 };
1602 const unit = launch?.unit;
1603 const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
1604 // Only a CLI that fails before its first message explains itself on
1605 // stderr. The known root refusal becomes a curated failure; any other
1606 // stderr can hold private text, so it stays out of turn failures.
1607 let stderrTail = "";
1608 let stderrClosed: Promise<void> = Promise.resolve();
1609 let answered = false;
1610 let conversationMissing = false;
1611 const appendStderr = (text: string) => {
1612 if (answered) return;
1613 stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
1614 };
1615 let refreshDescendants: Effect.Effect<void> = Effect.void;
1616 const spawnProcess =
1617 options.spawnClaudeCodeProcess ??
1618 ((spawnOptions: ClaudeSpawnOptions) => {
1619 if (platform !== "win32") {
1620 // Node can report "exit" before it has read the stderr the CLI wrote.
1621 let stderrDone = () => {};
1622 stderrClosed = new Promise((resolve) => (stderrDone = resolve));
1623 const child = spawnClaudeProcessGroup(
1624 spawnOptions,
1625 stopScope,
1626 appendStderr,
1627 stderrDone,
1628 providerProcesses.register,
1629 );
1630 if (unit === undefined && child.pid !== undefined) {
1631 const tracker = trackDescendants(child.pid);
1632 const polling = runFork(
1633 tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
1634 );
1635 child.once("exit", () =>
1636 runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
1637 );
1638 refreshDescendants = tracker.refresh;
1639 }
1640 return child;
1641 }
1642 const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, {
1643 cwd: spawnOptions.cwd,
1644 env: spawnOptions.env,
1645 signal: spawnOptions.signal,
1646 windowsHide: true,
1647 });
1648 child.stderr.setEncoding("utf8").on("data", (chunk: string) => options.stderr?.(chunk));
1649 return child;
1650 });
1651 let spawnedProcess: ClaudeSpawnedProcess | undefined;
1652 let processExited = false;
1653 let processExit: Promise<void> | undefined;
1654 const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
1655 const child = spawnProcess(spawnOptions);
1656 spawnedProcess = child;
1657 // A spawn that fails emits only "error".
1658 const releaseAgent = portDiscovery.trackAgent();
1659 child.once("exit", releaseAgent);
1660 child.on("error", releaseAgent);
1661 processExited = child.exitCode !== null || child.signalCode != null;
1662 processExit = new Promise<void>((resolve) => {
1663 if (processExited) resolve();
1664 else
1665 child.once("exit", () => {
1666 processExited = true;
1667 resolve();
1668 });
1669 });
1670 return child;
1671 };
1672 const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
1673 Effect.try({
1674 try: () =>
1675 withoutClaudeCanUseToolShadowedWarning(() =>
1676 query({
1677 prompt,
1678 options: { ...options, spawnClaudeCodeProcess },
1679 }),
1680 ),
1681 catch: (cause) => queryRunnerError(cause, "query"),
1682 }).pipe(
1683 Effect.tap((queryRuntime) =>
1684 restore(
1685 Effect.gen(function* () {
1686 if (mcpServers !== undefined) {
1687 const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
1688 Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1689 threadId: input.threadId,
1690 providerSessionId: input.providerSessionId,
1691 phase,
1692 }).pipe(
1693 Effect.andThen(
1694 Effect.fail(
1695 queryRunnerError(new ClaudeMcpRegistrationTimeoutError({ phase }), phase),
1696 ),
1697 ),
1698 );
1699 // The SDK leaves query() boot unbounded, and it takes about a minute on a host
1700 // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
1701 yield* Effect.promise(() =>
1702 queryRuntime.initializationResult().catch(() => undefined),
1703 ).pipe(
1704 Effect.timeoutOrElse({
1705 duration: CLAUDE_BOOT_TIMEOUT,
1706 orElse: timedOut("initialize"),
1707 }),
1708 );
1709 // Errors and mcp_status can echo headers; log only server names.
1710 const failed = yield* Effect.tryPromise({
1711 try: () => queryRuntime.setMcpServers(mcpServers),
1712 catch: (cause) => queryRunnerError(cause, "setMcpServers"),
1713 }).pipe(
1714 Effect.map((result) => Object.keys(result.errors)),
1715 Effect.orElseSucceed(() => Object.keys(mcpServers)),
1716 Effect.timeoutOrElse({
1717 duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
1718 orElse: timedOut("setMcpServers"),
1719 }),
1720 );
1721 if (failed.length > 0) {
1722 yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", {
1723 threadId: input.threadId,
1724 servers: failed,
1725 });
1726 }
1727 }
1728 yield* logProtocolEvent({
1729 direction: "outgoing",
1730 stage: "decoded",
1731 payload: {
1732 type: "query.open",
1733 options: loggedClaudeQueryOptions(input.options),
1734 },
1735 });
1736 }),
1737 ).pipe(
1738 Effect.onError(() =>
1739 Queue.shutdown(promptQueue).pipe(
1740 // SDK disposal can return before process exit; await the owned child's exit before retrying.
1741 Effect.andThen(
1742 Effect.tryPromise({
1743 try: async () => {
1744 if (spawnedProcess !== undefined && !processExited) {
1745 spawnedProcess.kill("SIGKILL");
1746 }
1747 await processExit;
1748 },
1749 catch: (cause) => queryRunnerError(cause, "close"),
1750 }).pipe(Effect.timeout("10 seconds")),
1751 ),
1752 Effect.ensuring(
1753 Effect.tryPromise({
1754 try: () => queryRuntime[Symbol.asyncDispose](),
1755 catch: (cause) => queryRunnerError(cause, "close"),
1756 }).pipe(Effect.orDie),
1757 ),
1758 Effect.orDie,
1759 ),
1760 ),
1761 ),
1762 ),
1763 ),
1764 );
1765
1766 return {
1767 messages: Stream.fromAsyncIterable(
1768 claudeQueryMessages(queryRuntime),
1769 (cause) => cause,
1770 ).pipe(
1771 Stream.catch((cause) =>
1772 Stream.fromEffect(
1773 Effect.gen(function* () {
1774 if (!answered) {
1775 yield* Effect.promise(() => stderrClosed).pipe(
1776 Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
1777 );
1778 }
1779 const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
1780 const startupExit = answered ? undefined : claudeProcessExit(cause);
1781 if (startupExit !== undefined) {
1782 // The turn failure omits this output, so the log is the only place it is kept.
1783 yield* Effect.logWarning("orchestration-v2.claude-startup-exit", {
1784 threadId: input.threadId,
1785 status: startupExit.status,
1786 stderr: stderrTail,
1787 });
1788 }
1789 return yield* queryRunnerError(
1790 refusedRoot
1791 ? new ClaudeCodeRootRefusalError({ cause })
1792 : conversationMissing ||
1793 (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
1794 ? new ClaudeConversationNotFoundError({ cause })
1795 : startupExit !== undefined
1796 ? new ClaudeCodeStartupExitError({
1797 status: startupExit.status,
1798 guidance: providerProcessExitGuidance(stderrTail),
1799 cause,
1800 })
1801 : cause,
1802 "fromAsyncIterable",
1803 );
1804 }),
1805 ),
1806 ),
1807 Stream.tap((message) =>
1808 Effect.sync(() => {
1809 answered = true;
1810 if (
1811 message.type === "result" &&
1812 message.subtype !== "success" &&
1813 message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
1814 ) {
1815 conversationMissing = true;
1816 }
1817 }),
1818 ),
1819 Stream.tap((message) =>
1820 logProtocolEvent({
1821 direction: "incoming",
1822 stage: "decoded",
1823 payload: message,
1824 }),
1825 ),
1826 ),
1827 offer: (message, onQueued) =>
1828 Effect.uninterruptibleMask((restore) =>
1829 restore(Queue.offer(promptQueue, message)).pipe(
1830 Effect.tap(() => Effect.sync(() => onQueued?.())),
1831 ),
1832 ).pipe(
1833 Effect.asVoid,
1834 Effect.tap(() =>
1835 logProtocolEvent({
1836 direction: "outgoing",
1837 stage: "decoded",
1838 payload: {
1839 type: "prompt.offer",
1840 message,
1841 },
1842 }),
1843 ),
1844 ),
1845 setModel: (model) =>
1846 Effect.tryPromise({
1847 try: () => queryRuntime.setModel(model),
1848 catch: (cause) => queryRunnerError(cause, "setModel"),
1849 }).pipe(
1850 Effect.tap(() =>
1851 logProtocolEvent({
1852 direction: "outgoing",
1853 stage: "decoded",
1854 payload: {
1855 type: "query.set_model",
1856 model,
1857 },
1858 }),
1859 ),
1860 ),
1861 applyFlagSettings: (settings) =>
1862 Effect.tryPromise({
1863 try: () => queryRuntime.applyFlagSettings(settings),
1864 catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
1865 }).pipe(
1866 Effect.tap(() =>
1867 logProtocolEvent({
1868 direction: "outgoing",
1869 stage: "decoded",
1870 payload: {
1871 type: "query.apply_flag_settings",
1872 settings,
1873 },
1874 }),
1875 ),
1876 ),
1877 setPermissionMode: (mode) =>
1878 Effect.tryPromise({
1879 try: () => queryRuntime.setPermissionMode(mode),
1880 catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
1881 }).pipe(
1882 Effect.tap(() =>
1883 logProtocolEvent({
1884 direction: "outgoing",
1885 stage: "decoded",
1886 payload: {
1887 type: "query.set_permission_mode",
1888 mode,
1889 },
1890 }),
1891 ),
1892 ),
1893 renameSession: (title) =>
1894 Effect.tryPromise({
1895 try: () =>
1896 sendClaudeControlRequest(queryRuntime, {
1897 subtype: "rename_session",
1898 title,
1899 source: "host",
1900 }),
1901 catch: (cause) => queryRunnerError(cause, "renameSession"),
1902 }).pipe(
1903 Effect.asVoid,
1904 Effect.tap(() =>
1905 logProtocolEvent({
1906 direction: "outgoing",
1907 stage: "decoded",
1908 payload: {
1909 type: "query.rename_session",
1910 title,
1911 },
1912 }),
1913 ),
1914 ),
1915 stopTask: (taskId) =>
1916 Effect.tryPromise({
1917 try: () => queryRuntime.stopTask(taskId),
1918 catch: (cause) => queryRunnerError(cause, "stopTask"),
1919 }).pipe(
1920 Effect.tap(() =>
1921 logProtocolEvent({
1922 direction: "outgoing",
1923 stage: "decoded",
1924 payload: { type: "query.stop_task", taskId },
1925 }),
1926 ),
1927 ),
1928 backgroundTasks: (toolUseId) =>
1929 Effect.tryPromise({
1930 try: () => queryRuntime.backgroundTasks(toolUseId),
1931 catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
1932 }).pipe(
1933 Effect.tap(() =>
1934 logProtocolEvent({
1935 direction: "outgoing",
1936 stage: "decoded",
1937 payload: { type: "query.background_tasks", toolUseId },
1938 }),
1939 ),
1940 ),
1941 mcpServerStatus: Effect.tryPromise({
1942 try: () => queryRuntime.mcpServerStatus(),
1943 catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
1944 }),
1945 readMcpResource: ({ server, uri }) =>
1946 Effect.tryPromise({
1947 try: () => queryRuntime.readMcpResource(server, uri),
1948 catch: (cause) => queryRunnerError(cause, "readMcpResource"),
1949 }),
1950 mcpAuthenticate: (server) =>
1951 Effect.tryPromise({
1952 try: () =>
1953 sendClaudeControlRequest(queryRuntime, {
1954 subtype: "mcp_authenticate",
1955 serverName: server,
1956 }),
1957 catch: (cause) => queryRunnerError(cause, "mcpAuthenticate"),
1958 }).pipe(
1959 Effect.flatMap(decodeClaudeMcpAuthenticateReply),
1960 Effect.map((reply) =>
1961 reply.requiresUserAction === true && reply.authUrl !== undefined
1962 ? reply.authUrl
1963 : null,
1964 ),
1965 Effect.mapError((cause) => queryRunnerError(cause, "mcpAuthenticate")),
1966 ),
1967 mcpSubmitOAuthCallbackUrl: ({ server, callbackUrl }) =>
1968 Effect.tryPromise({
1969 try: () =>
1970 sendClaudeControlRequest(queryRuntime, {
1971 subtype: "mcp_oauth_callback_url",
1972 serverName: server,
1973 callbackUrl,
1974 }),
1975 catch: (cause) => queryRunnerError(cause, "mcpSubmitOAuthCallbackUrl"),
1976 }).pipe(Effect.asVoid),
1977 reconnectMcpServer: (server) =>
1978 Effect.tryPromise({
1979 try: () => queryRuntime.reconnectMcpServer(server),
1980 catch: (cause) => queryRunnerError(cause, "reconnectMcpServer"),
1981 }),
1982 callMcpTool: (call) =>
1983 Effect.tryPromise({
1984 try: () =>
1985 sendClaudeControlRequest(queryRuntime, {
1986 subtype: "mcp_call",
1987 tool: call.tool,
1988 arguments: call.arguments,
1989 result_not_for_model: true,
1990 }),
1991 catch: (cause) => queryRunnerError(cause, "callMcpTool"),
1992 }),
1993 listPermissionRules: Effect.tryPromise({
1994 try: () => sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
1995 catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
1996 }).pipe(
1997 Effect.flatMap(decodeClaudePermissionRules),
1998 // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
1999 Effect.filterOrFail(
2000 ({ state }) => (state.errors ?? []).length === 0,
2001 ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
2002 ),
2003 Effect.map(({ state }) => state.rules),
2004 Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
2005 ),
2006 interrupt: Effect.tryPromise({
2007 try: () => queryRuntime.interrupt(),
2008 catch: (cause) => queryRunnerError(cause, "interrupt"),
2009 }).pipe(
2010 Effect.tap(() =>
2011 logProtocolEvent({
2012 direction: "outgoing",
2013 stage: "decoded",
2014 payload: {
2015 type: "query.interrupt",
2016 },
2017 }),
2018 ),
2019 ),
2020 // A job started since the last poll is recorded before the CLI is told to exit.
2021 close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
2022 Effect.andThen(Queue.shutdown(promptQueue)),
2023 Effect.andThen(closeClaudeQuery(queryRuntime)),
2024 Effect.tap(() =>
2025 logProtocolEvent({
2026 direction: "outgoing",
2027 stage: "decoded",
2028 payload: {
2029 type: "query.close",
2030 },
2031 }),
2032 ),
2033 ),
2034 } satisfies ClaudeAgentSdkQuerySession;
2035 });
2036
2037 return ClaudeAgentSdkQueryRunner.of({
2038 allocateSessionId: random.uuidV4(),
2039 open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
2040 input: ClaudeAgentSdkQueryOpenInput,
2041 ) {
2042 // A fresh ID may already have a transcript, so a fresh session retries under a new ID;
2043 // the adapter adopts it from the init message, as it does after /clear.
2044 return yield* openQuery(input).pipe(
2045 Effect.catchIf(
2046 (error) => isClaudeMcpRegistrationTimeoutError(error.cause),
2047 Effect.fnUntraced(function* () {
2048 const { resume, ...options } = input.options;
2049 if (resume !== undefined) return yield* openQuery(input);
2050 const sessionId = yield* random.uuidV4();
2051 return yield* openQuery({ ...input, options: { ...options, sessionId } });
2052 }),
2053 ),
2054 );
2055 }),
2056 forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
2057 input: ClaudeAgentSdkSessionForkInput,
2058 ) {
2059 const protocolLogger = makeClaudeAgentSdkProtocolLogger({
2060 nativeEventLogger,
2061 threadId: input.threadId,
2062 providerSessionId: input.providerSessionId,
2063 });
2064 const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
2065 protocolLogger === undefined ? Effect.void : protocolLogger(event);
2066 yield* logProtocolEvent({
2067 direction: "outgoing",
2068 stage: "decoded",
2069 payload: {
2070 type: "session.fork",
2071 sessionId: input.sessionId,
2072 options: input.options,
2073 },
2074 });
2075 const hostEnvironment = yield* HostProcess.Environment;
2076 const homeDirectory = yield* HostProcess.HomeDirectory;
2077 const usesHostConfig =
2078 claudeConfigDirOf(path, input.environment, homeDirectory) ===
2079 claudeConfigDirOf(path, hostEnvironment, homeDirectory);
2080 const fork: Effect.Effect<
2081 ForkSessionResult & { readonly headMessageId?: string },
2082 unknown
2083 > = usesHostConfig
2084 ? Effect.tryPromise({
2085 try: () => forkClaudeSession(input.sessionId, input.options),
2086 catch: (cause) => queryRunnerError(cause, "forkSession"),
2087 })
2088 : forkClaudeSessionInWorker(input).pipe(
2089 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
2090 Effect.provideService(Path.Path, path),
2091 );
2092 const result = yield* fork.pipe(
2093 Effect.mapError((cause) => queryRunnerError(cause, "forkSession")),
2094 );
2095 yield* logProtocolEvent({
2096 direction: "incoming",
2097 stage: "decoded",
2098 payload: {
2099 type: "session.forked",
2100 sessionId: result.sessionId,
2101 },
2102 });
2103 // The SDK remaps copied UUIDs. Capture the inherited head before the
2104 // fork's first run appends messages.
2105 const headMessageId = usesHostConfig
2106 ? yield* Effect.tryPromise({
2107 try: () =>
2108 getSessionMessages(
2109 result.sessionId,
2110 input.options.dir === undefined ? {} : { dir: input.options.dir },
2111 ),
2112 catch: (cause) => queryRunnerError(cause, "getSessionMessages"),
2113 }).pipe(
2114 Effect.map((messages) => messages.at(-1)?.uuid),
2115 Effect.orElseSucceed(() => undefined),
2116 )
2117 : result.headMessageId;
2118 return headMessageId === undefined ? result : { ...result, headMessageId };
2119 }),
2120 subagentLaunchToolUseId: Effect.fn("ClaudeAgentSdkQueryRunner.subagentLaunchToolUseId")(
2121 function* (input: ClaudeAgentSdkSubagentLookupInput) {
2122 const protocolLogger = makeClaudeAgentSdkProtocolLogger({
2123 nativeEventLogger,
2124 threadId: input.threadId,
2125 providerSessionId: input.providerSessionId,
2126 });
2127 const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
2128 protocolLogger === undefined ? Effect.void : protocolLogger(event);
2129 yield* logProtocolEvent({
2130 direction: "outgoing",
2131 stage: "decoded",
2132 payload: {
2133 type: "subagent.lookup",
2134 sessionId: input.sessionId,
2135 agentId: input.agentId,
2136 },
2137 });
2138 const messages = yield* Effect.tryPromise({
2139 try: () =>
2140 getSubagentMessages(input.sessionId, input.agentId, {
2141 ...(input.dir === null ? {} : { dir: input.dir }),
2142 limit: 1,
2143 }),
2144 catch: (cause) => queryRunnerError(cause, "getSubagentMessages"),
2145 });
2146 const toolUseId = messages[0]?.parent_tool_use_id ?? null;
2147 yield* logProtocolEvent({
2148 direction: "incoming",
2149 stage: "decoded",
2150 payload: { type: "subagent.found", toolUseId },
2151 });
2152 return toolUseId;
2153 },
2154 ),
2155 subagentModel: Effect.fn("ClaudeAgentSdkQueryRunner.subagentModel")(function* (
2156 input: ClaudeAgentSdkSubagentLookupInput,
2157 ) {
2158 const messages = yield* Effect.tryPromise({
2159 try: () =>
2160 getSubagentMessages(
2161 input.sessionId,
2162 input.agentId,
2163 input.dir === null ? {} : { dir: input.dir },
2164 ),
2165 catch: (cause) => queryRunnerError(cause, "getSubagentMessages"),
2166 });
2167 return (
2168 messages
2169 .toReversed()
2170 .flatMap((message) =>
2171 message.type === "assistant" ? [text(field(message.message, "model"))] : [],
2172 )
2173 .find((model) => model !== undefined) ?? null
2174 );
2175 }),
2176 assertComplete: Effect.void,
2177 });
2178 }),
2179 );
2180
2181 type ClaudeFlagSettings = Parameters<ClaudeQuery["applyFlagSettings"]>[0];
2182
2183 /** Thinking requires a new process. Clearing effort also requires one to reload user settings instead of model defaults. */
2184 function canApplyClaudeSelectionLive(
2185 live: CompiledClaudeModelSelection,
2186 next: CompiledClaudeModelSelection,
2187 ): boolean {
2188 return (
2189 live.settings.alwaysThinkingEnabled === next.settings.alwaysThinkingEnabled &&
2190 (next.effort !== undefined || live.effort === undefined) &&
2191 live.pinnedAlias === next.pinnedAlias
2192 );
2193 }
2194
2195 function claudeLiveSelectionFlagSettings(
2196 selection: CompiledClaudeModelSelection,
2197 ): ClaudeFlagSettings {
2198 return {
2199 ...(selection.effort === undefined ? {} : { effortLevel: selection.effort as EffortLevel }),
2200 fastMode: selection.settings.fastMode ?? null,
2201 ultracode: selection.settings.ultracode ?? null,
2202 };
2203 }
2204
2205 // A delegated child is its own SDK session, so Claude Code gives it the main-conversation cache
2206 // TTL. When the user sets Claude's subagentPromptCacheTtl, the child follows it like a native
2207 // subagent would. A resumed session's first request otherwise goes out before its MCP servers
2208 // connect, and Claude Code tells the agent they disconnected. Explicit instance values still win.
2209 export function claudeQueryEnvironment(
2210 environment: NodeJS.ProcessEnv,
2211 appThread: Pick<OrchestrationV2AppThread, "lineage">,
2212 subagentPromptCacheTtl: "5m" | "1h" | undefined,
2213 resume = false,
2214 ): NodeJS.ProcessEnv {
2215 const promptCacheTtl =
2216 appThread.lineage.relationshipToParent === "subagent" &&
2217 subagentPromptCacheTtl !== undefined &&
2218 environment.CLAUDE_CODE_PROMPT_CACHE_TTL === undefined
2219 ? subagentPromptCacheTtl
2220 : undefined;
2221 const blockingMcpConnect = resume && environment.MCP_CONNECTION_NONBLOCKING === undefined;
2222 if (promptCacheTtl === undefined && !blockingMcpConnect) {
2223 return environment;
2224 }
2225 return {
2226 ...environment,
2227 ...(promptCacheTtl === undefined ? {} : { CLAUDE_CODE_PROMPT_CACHE_TTL: promptCacheTtl }),
2228 ...(blockingMcpConnect ? { MCP_CONNECTION_NONBLOCKING: "0" } : {}),
2229 };
2230 }
2231
2232 // Claude Code's auto tool search sends every MCP schema in full while they fit under a share of the
2233 // context window, which T3's tools do on 1M models. auto:0 already means on and auto:100 off.
2234 export function claudeToolSearchOverride(value: string | undefined): "true" | undefined {
2235 if (value === undefined) return undefined;
2236 if (value === "auto") return "true";
2237 if (!value.startsWith("auto:")) return undefined;
2238 const percent = parseClaudeInteger(value.slice("auto:".length));
2239 // Claude Code treats an unparsable auto:N as auto, and clamps N to 0..100.
2240 if (Number.isNaN(percent)) return "true";
2241 const clamped = Math.min(100, Math.max(0, percent));
2242 return clamped > 0 && clamped < 100 ? "true" : undefined;
2243 }
2244
2245 // Claude Code 2.1.310's integer parsing for auto:N. Scientific notation counts only when it is an
2246 // integer, grouped digits (1_000, 1,000, or 1 000) are joined, and anything else uses parseInt.
2247 const CLAUDE_SCIENTIFIC_INTEGER = /^[+-]?(\d+(\.\d*)?|\.\d+)[eE][+-]?\d+$/;
2248 const CLAUDE_GROUPED_INTEGER = /^[+-]?\d{1,3}([_,\u00A0\u202F ])\d{3}(?:\1\d{3})*$/;
2249 function parseClaudeInteger(text: string): number {
2250 const value = text.trim();
2251 if (value.length <= 32 && CLAUDE_SCIENTIFIC_INTEGER.test(value)) {
2252 const number = Number(value);
2253 return Number.isInteger(number) ? number : Number.NaN;
2254 }
2255 if (value.length <= 32 && CLAUDE_GROUPED_INTEGER.test(value)) {
2256 return Number.parseInt(value.replace(/[_,\u00A0\u202F ]/g, ""), 10);
2257 }
2258 return Number.parseInt(value, 10);
2259 }
2260
2261 // Claude Code defers MCP tools behind ToolSearch, so the agent only finds
2262 // t3_background_wait when the system prompt says when to reach for it.
2263 const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
2264
2265 ### Background work you wait on
2266
2267 To wait for a background command or Monitor you started (tests, a build), call \`t3_background_wait\` with its task ID before you end your turn. Do not mark work you leave running, or PRs. T3 MCP tools are deferred: load one with ToolSearch before you call it.
2268 `;
2269
2270 // Claude 5.1+ returns text written before a tool call as a progress update, which the API
2271 // returns only as a summary.
2272 const CLAUDE_SEND_TO_USER_INSTRUCTIONS = `
2273 ### Text the user must read mid-turn
2274
2275 Text you write before a tool call may reach the user only as a one-line summary. When the user must read something in full before your turn ends, such as a draft, a code block, or what a question you're about to ask refers to, send it with \`send_to_user\`. Put everything else in your final reply.
2276 `;
2277
2278 // Native subagents start from their task, not this session's system prompt.
2279 const subagentDeviceInstructions: HookCallback = () =>
2280 Promise.resolve({
2281 hookSpecificOutput: {
2282 hookEventName: "SubagentStart",
2283 additionalContext: T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
2284 },
2285 });
2286
2287 export function makeClaudeQueryOptions(input: {
2288 readonly modelSelection: ModelSelection;
2289 readonly modelCatalog?: ClaudeModelCatalog;
2290 readonly nativeThreadId: string;
2291 readonly title?: string;
2292 readonly resume: boolean;
2293 readonly resumeSessionAt?: string;
2294 readonly cwd: string | null;
2295 readonly attachmentsDir?: string;
2296 readonly settings?: ClaudeSettings;
2297 readonly promptSuggestions?: boolean;
2298 readonly sdkSettings?: string | ClaudeSdkSettings;
2299 readonly environment?: NodeJS.ProcessEnv;
2300 readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
2301 /** The thread's T3 MCP session holds the `device` capability. */
2302 readonly deviceToolsAvailable?: boolean;
2303 readonly tools?: ClaudeAgentSdkQueryTools;
2304 readonly allowedTools?: ReadonlyArray<string>;
2305 readonly disallowedTools?: ReadonlyArray<string>;
2306 readonly permissionMode?: PermissionMode;
2307 readonly canUseTool?: CanUseTool;
2308 readonly onUserDialog?: ClaudeQueryOptions["onUserDialog"];
2309 readonly onElicitation?: ClaudeQueryOptions["onElicitation"];
2310 readonly onStop?: HookCallback;
2311 readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"];
2312 readonly allowDangerouslySkipPermissions?: boolean;
2313 readonly appendSystemPromptFileText?: string;
2314 // Flag settings, because a user's settings.json env beats the process env in Claude Code.
2315 readonly toolSearchOverride?: "true";
2316 }): ClaudeAgentSdkQueryOptions {
2317 const compiledSelection = compileClaudeModelSelection(input.modelSelection, input.modelCatalog);
2318 const {
2319 // claudeLaunchArgDirectories reads every --add-dir into additionalDirectories.
2320 "add-dir": _launchArgAddDir,
2321 // claudeLaunchArgPluginDirectories reads every --plugin-dir into plugins.
2322 "plugin-dir": launchArgPluginDir,
2323 "permission-mode": launchArgPermissionMode,
2324 "dangerously-skip-permissions": launchArgSkipPermissions,
2325 "append-system-prompt": launchArgAppendSystemPrompt,
2326 "append-system-prompt-file": _launchArgAppendSystemPromptFile,
2327 // The SDK replaces this flag with options.settings, so it arrives read as sdkSettings.
2328 settings: _launchArgSettings,
2329 ...extraArgs
2330 } = input.settings === undefined
2331 ? {}
2332 : parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags;
2333 // Claude Code overwrites its CLI append text with the SDK's initialize
2334 // appendSystemPrompt, so launch-argument text has to travel in that value.
2335 // The CLI puts file text before inline text and trims one trailing newline.
2336 const launchAppendSystemPrompt = [
2337 input.appendSystemPromptFileText?.replace(/\r?\n$/, ""),
2338 launchArgAppendSystemPrompt,
2339 ].filter((text): text is string => typeof text === "string" && text.length > 0);
2340 const requestThinkingSummaries =
2341 compiledSelection.settings.alwaysThinkingEnabled !== false &&
2342 extraArgs["thinking-display"] !== "omitted";
2343 if (requestThinkingSummaries && extraArgs["thinking-display"] === undefined) {
2344 extraArgs["thinking-display"] = "summarized";
2345 }
2346 const pluginDirectories =
2347 input.settings === undefined ? [] : claudeLaunchArgPluginDirectories(input.settings.launchArgs);
2348 // A bare --plugin-dir still reaches Claude, which reports the missing path.
2349 if (launchArgPluginDir === null) extraArgs["plugin-dir"] = null;
2350 const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume
2351 ? { resume: input.nativeThreadId }
2352 : { sessionId: input.nativeThreadId };
2353 const selectedTools = input.tools ?? CLAUDE_CODE_PRESET_TOOLS;
2354 const selectionSettings =
2355 Object.keys(compiledSelection.settings).length === 0
2356 ? undefined
2357 : (compiledSelection.settings as ClaudeSdkSettings);
2358 const querySettings =
2359 selectionSettings === undefined
2360 ? input.sdkSettings
2361 : typeof input.sdkSettings === "object" && input.sdkSettings !== null
2362 ? ({ ...input.sdkSettings, ...selectionSettings } as ClaudeSdkSettings)
2363 : selectionSettings;
2364 const autoCompactWindow =
2365 input.settings?.autoCompactWindow === undefined || input.settings.autoCompactWindow.length === 0
2366 ? undefined
2367 : input.settings.autoCompactWindow;
2368 const compactQuerySettings =
2369 autoCompactWindow === undefined
2370 ? querySettings
2371 : ({
2372 ...(typeof querySettings === "object" && querySettings !== null ? querySettings : {}),
2373 autoCompactWindow: Number(autoCompactWindow),
2374 } as ClaudeSdkSettings);
2375 // Claude Code expands a bare alias to its own model, so a custom model with an alias's name
2376 // pins the alias to itself.
2377 const aliasOverrideEnv =
2378 compiledSelection.pinnedAlias === undefined
2379 ? undefined
2380 : {
2381 [`ANTHROPIC_DEFAULT_${compiledSelection.pinnedAlias.toUpperCase()}_MODEL`]:
2382 compiledSelection.pinnedAlias,
2383 };
2384 // A settings file path cannot take extra keys, so it goes through unchanged.
2385 const effectiveQuerySettings =
2386 (input.toolSearchOverride === undefined &&
2387 aliasOverrideEnv === undefined &&
2388 autoCompactWindow === undefined) ||
2389 typeof compactQuerySettings === "string"
2390 ? compactQuerySettings
2391 : ({
2392 ...compactQuerySettings,
2393 env: {
2394 ...compactQuerySettings?.env,
2395 ...aliasOverrideEnv,
2396 // Claude Code ranks this env var above the autoCompactWindow setting.
2397 ...(autoCompactWindow === undefined
2398 ? {}
2399 : { CLAUDE_CODE_AUTO_COMPACT_WINDOW: autoCompactWindow }),
2400 ...(input.toolSearchOverride === undefined
2401 ? {}
2402 : { ENABLE_TOOL_SEARCH: input.toolSearchOverride }),
2403 },
2404 } as ClaudeSdkSettings);
2405 const deviceInstructions = input.mcpServers !== undefined && input.deviceToolsAvailable === true;
2406 const options: ClaudeAgentSdkQueryOptions = {
2407 model: compiledSelection.apiModelId,
2408 // T3 names threads; a supplied title skips Claude's redundant naming request.
2409 ...(input.title === undefined ? {} : { title: input.title }),
2410 tools: claudeAgentSdkQueryToolsForSdk(selectedTools),
2411 permissionMode:
2412 (launchArgPermissionMode as PermissionMode | null | undefined) ??
2413 (launchArgSkipPermissions === null || launchArgSkipPermissions === "true"
2414 ? "bypassPermissions"
2415 : (input.permissionMode ?? "default")),
2416 includePartialMessages: true,
2417 promptSuggestions: input.promptSuggestions === true,
2418 ...(compiledSelection.effort === undefined
2419 ? {}
2420 : {
2421 effort: compiledSelection.effort as NonNullable<ClaudeQueryOptions["effort"]>,
2422 }),
2423 ...threadIdentity,
2424 ...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),
2425 ...(input.allowedTools === undefined ? {} : { allowedTools: [...input.allowedTools] }),
2426 ...(input.disallowedTools === undefined ? {} : { disallowedTools: [...input.disallowedTools] }),
2427 ...(input.canUseTool === undefined ? {} : { canUseTool: input.canUseTool }),
2428 ...(input.allowDangerouslySkipPermissions === true
2429 ? { allowDangerouslySkipPermissions: true }
2430 : {}),
2431 ...(requestThinkingSummaries
2432 ? {
2433 thinking: { type: "adaptive" as const, display: "summarized" as const },
2434 settings:
2435 typeof effectiveQuerySettings === "string"
2436 ? effectiveQuerySettings
2437 : {
2438 ...effectiveQuerySettings,
2439 showThinkingSummaries: true,
2440 },
2441 }
2442 : effectiveQuerySettings === undefined
2443 ? {}
2444 : { settings: effectiveQuerySettings }),
2445 ...(input.onUserDialog === undefined ? {} : { onUserDialog: input.onUserDialog }),
2446 ...(input.onElicitation === undefined ? {} : { onElicitation: input.onElicitation }),
2447 ...(input.supportedDialogKinds === undefined
2448 ? {}
2449 : { supportedDialogKinds: input.supportedDialogKinds }),
2450 ...(input.settings?.binaryPath
2451 ? { pathToClaudeCodeExecutable: input.settings.binaryPath }
2452 : {}),
2453 ...(input.environment === undefined ? {} : { env: input.environment }),
2454 ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),
2455 systemPrompt: {
2456 type: "preset" as const,
2457 preset: "claude_code" as const,
2458 append: [
2459 buildRuntimeInstructions({ harness: "Claude Code" }) +
2460 (input.mcpServers === undefined
2461 ? ""
2462 : T3_CODE_ORCHESTRATION_INSTRUCTIONS +
2463 CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS +
2464 CLAUDE_SEND_TO_USER_INSTRUCTIONS +
2465 (deviceInstructions
2466 ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n`
2467 : "")),
2468 ...launchAppendSystemPrompt,
2469 ].join("\n\n"),
2470 },
2471 ...(deviceInstructions || input.onStop !== undefined
2472 ? {
2473 hooks: {
2474 ...(deviceInstructions
2475 ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] }
2476 : {}),
2477 ...(input.onStop === undefined ? {} : { Stop: [{ hooks: [input.onStop] }] }),
2478 },
2479 }
2480 : {}),
2481 ...(pluginDirectories.length === 0
2482 ? {}
2483 : { plugins: pluginDirectories.map((path) => ({ type: "local" as const, path })) }),
2484 ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
2485 };
2486 const additionalDirectories = [
2487 ...(input.cwd === null ? [] : [input.cwd]),
2488 ...(input.attachmentsDir === undefined ? [] : [input.attachmentsDir]),
2489 ...claudeLaunchArgDirectories(input.settings?.launchArgs),
2490 ];
2491 const withDirectories =
2492 additionalDirectories.length === 0 ? options : { ...options, additionalDirectories };
2493 return input.cwd === null ? withDirectories : { ...withDirectories, cwd: input.cwd };
2494 }
2495
2496 /**
2497 * Checks the append launch arguments the way the Claude CLI would and reads the
2498 * file (leading ~ expanded) relative to the thread's cwd. makeClaudeQueryOptions
2499 * folds these flags out of extraArgs, so a value the CLI would have rejected has
2500 * to be rejected here or it silently disappears.
2501 */
2502 const readClaudeAppendSystemPromptFile = Effect.fnUntraced(function* (input: {
2503 readonly settings: ClaudeSettings | undefined;
2504 readonly cwd: string | null;
2505 readonly fileSystem: FileSystem.FileSystem;
2506 readonly path: Path.Path;
2507 }) {
2508 if (input.settings === undefined) return undefined;
2509 const flags = parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags;
2510 // parseCliArgs gives null for a flag with no following value. An explicit
2511 // `--append-system-prompt ""` is a value the CLI accepts, so it stays.
2512 if (flags["append-system-prompt"] === null) {
2513 return yield* new ClaudeAppendSystemPromptMissingValueError({
2514 flag: "--append-system-prompt",
2515 });
2516 }
2517 const file = flags["append-system-prompt-file"];
2518 if (file === undefined) return undefined;
2519 // `--append-system-prompt-file=` is "" and names no file either.
2520 if (file === null || file === "") {
2521 return yield* new ClaudeAppendSystemPromptMissingValueError({
2522 flag: "--append-system-prompt-file",
2523 });
2524 }
2525 const filePath = input.path.resolve(
2526 input.cwd ?? ".",
2527 expandHomePath(file, yield* HostProcess.HomeDirectory),
2528 );
2529 return yield* input.fileSystem
2530 .readFileString(filePath)
2531 .pipe(
2532 Effect.mapError((cause) => new ClaudeAppendSystemPromptFileError({ path: filePath, cause })),
2533 );
2534 });
2535
2536 const decodeClaudeLaunchArgSettings = Schema.decodeUnknownEffect(
2537 fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)),
2538 );
2539
2540 /**
2541 * Reads the --settings launch argument: a value starting with a brace is inline
2542 * JSON, anything else is a file path that expands a leading ~ and is otherwise
2543 * relative to the thread's cwd (the project or its worktree).
2544 * makeClaudeQueryOptions merges the result beneath T3's own settings.
2545 */
2546 export const readClaudeLaunchArgSettings = Effect.fn("ClaudeAdapterV2.readLaunchArgSettings")(
2547 function* (input: {
2548 readonly settings: ClaudeSettings | undefined;
2549 readonly cwd: string | null;
2550 readonly fileSystem: FileSystem.FileSystem;
2551 readonly path: Path.Path;
2552 }) {
2553 if (input.settings === undefined) return undefined;
2554 const value = parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags
2555 .settings;
2556 if (value === undefined) return undefined;
2557 const trimmed = value?.trim() ?? "";
2558 if (trimmed.length === 0) return yield* new ClaudeSettingsLaunchArgError({});
2559 // The CLI also wants a closing brace, but then malformed JSON, secrets included, would
2560 // become the file path in the error message.
2561 if (trimmed.startsWith("{")) {
2562 return (yield* decodeClaudeLaunchArgSettings(trimmed).pipe(
2563 Effect.mapError((cause) => new ClaudeSettingsLaunchArgError({ cause })),
2564 )) as ClaudeSdkSettings;
2565 }
2566 const filePath = input.path.resolve(
2567 input.cwd ?? ".",
2568 expandHomePath(trimmed, yield* HostProcess.HomeDirectory),
2569 );
2570 return (yield* input.fileSystem.readFileString(filePath).pipe(
2571 Effect.flatMap(decodeClaudeLaunchArgSettings),
2572 Effect.mapError((cause) => new ClaudeSettingsLaunchArgError({ path: filePath, cause })),
2573 )) as ClaudeSdkSettings;
2574 },
2575 );
2576
2577 export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*";
2578
2579 // Keep in sync with OrchestratorToolkit Tool.Readonly annotations; ClaudeAdapterV2.test.ts checks this.
2580 export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
2581 "mcp__t3-code__orchestrator_capabilities",
2582 "mcp__t3-code__list_scheduled_tasks",
2583 "mcp__t3-code__t3_background_wait",
2584 "mcp__t3-code__t3_thread_list",
2585 "mcp__t3-code__t3_thread_wait",
2586 "mcp__t3-code__t3_worktree_status",
2587 "mcp__t3-code__t3_worktree_list",
2588 "mcp__t3-code__t3_project_list",
2589 "mcp__t3-code__t3_project_read",
2590 "mcp__t3-code__t3_thread_search",
2591 "mcp__t3-code__t3_preview_list",
2592 "mcp__t3-code__t3_environment_read",
2593 "mcp__t3-code__t3_environment_links",
2594 "mcp__t3-code__t3_theme_read",
2595 "mcp__t3-code__html_preview",
2596 "mcp__t3-code__html_render",
2597 "mcp__t3-code__send_to_user",
2598 "mcp__t3-code__t3_submit_output",
2599 ];
2600
2601 // request_secret can wait an hour; exceed Claude's default 60 s timeout.
2602 export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000;
2603
2604 // allowedTools pre-approves calls; tools controls availability. Pre-approve T3 tools for headless modes,
2605 // limited to annotated read-only tools in read-only sandboxes.
2606
2607 export function claudeMcpQueryOverrides(input: {
2608 readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
2609 readonly readOnlySandbox: boolean;
2610 readonly allowedTools?: ReadonlyArray<string>;
2611 }): {
2612 readonly allowedTools?: ReadonlyArray<string>;
2613 readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
2614 } {
2615 const session = input.mcpSession;
2616 if (session === undefined) {
2617 return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
2618 }
2619 const mcpAllowedTools = input.readOnlySandbox
2620 ? CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS
2621 : [CLAUDE_T3_MCP_TOOL_WILDCARD];
2622 return {
2623 allowedTools: Array.from(new Set([...(input.allowedTools ?? []), ...mcpAllowedTools])),
2624 mcpServers: {
2625 "t3-code": {
2626 type: "http",
2627 url: session.endpoint,
2628 headers: {
2629 Authorization: session.authorizationHeader,
2630 },
2631 timeout: CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
2632 },
2633 },
2634 };
2635 }
2636
2637 function providerSession(input: {
2638 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
2639 readonly providerInstanceId: ProviderInstanceId;
2640 readonly cwd: string | null;
2641 readonly model: string;
2642 readonly now: DateTime.Utc;
2643 }): OrchestrationV2ProviderSession {
2644 return {
2645 id: input.providerSessionId,
2646 driver: CLAUDE_PROVIDER,
2647 providerInstanceId: input.providerInstanceId,
2648 status: "ready",
2649 cwd: input.cwd ?? process.cwd(),
2650 model: input.model,
2651 capabilities: ClaudeProviderCapabilitiesV2,
2652 createdAt: input.now,
2653 updatedAt: input.now,
2654 lastError: null,
2655 };
2656 }
2657
2658 function textFromClaudeContent(content: SDKAssistantMessage["message"]["content"]): string {
2659 return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
2660 }
2661
2662 // Claude 5.1+ emits at most one pre-tool text block as thinking; treat only a second consecutive thinking block as text.
2663 function claudeWritesUpdatesAsThinking(model: string): boolean {
2664 const match = /claude-[a-z]+-(\d+)(?:-(\d{1,2}))?(?!\d)/u.exec(model);
2665 if (match === null) return false;
2666 const major = Number(match[1]);
2667 return major > 5 || (major === 5 && Number(match[2] ?? 0) >= 1);
2668 }
2669
2670 // In SDK mode, /goal appears only in transcripts: command output names it and Stop hooks report unmet checks.
2671 const CLAUDE_GOAL_SET_PREFIX = "Goal set: ";
2672 const CLAUDE_GOAL_ACTIVE = /^Goal active: ([\s\S]+?) \((?:not yet evaluated|(\d+) turns?)\)/u;
2673
2674 function nextClaudeGoal(
2675 current: OrchestrationV2ProviderGoal | null,
2676 message: SDKMessage,
2677 ): OrchestrationV2ProviderGoal | null | undefined {
2678 // The CLI drops a goal on a context-limit, auth, or billing failure and reports it only here.
2679 if (
2680 message.type === "system" &&
2681 message.subtype === "informational" &&
2682 message.content.startsWith("Goal cleared after an unrecoverable error (")
2683 ) {
2684 return null;
2685 }
2686 if (message.type === "assistant") {
2687 if (message.parent_tool_use_id !== null || message.message.model !== "<synthetic>") {
2688 return undefined;
2689 }
2690 const text = textFromClaudeContent(message.message.content).trim();
2691 if (text.startsWith(CLAUDE_GOAL_SET_PREFIX)) {
2692 const objective = text.slice(CLAUDE_GOAL_SET_PREFIX.length).trim();
2693 return objective.length === 0 ? undefined : { objective, status: "active", checks: 0 };
2694 }
2695 if (text.startsWith("Goal cleared: ") || text.startsWith("No goal set")) return null;
2696 const active = CLAUDE_GOAL_ACTIVE.exec(text);
2697 if (active?.[1] === undefined) return undefined;
2698 return {
2699 ...(current?.objective === active[1] ? current : {}),
2700 objective: active[1],
2701 status: "active",
2702 checks: Number(active[2] ?? 0),
2703 };
2704 }
2705 if (
2706 message.type !== "user" ||
2707 message.parent_tool_use_id !== null ||
2708 message.isSynthetic !== true ||
2709 current === null
2710 ) {
2711 return undefined;
2712 }
2713 const prefix = `Stop hook feedback:\n[${current.objective}]: `;
2714 const content = message.message.content;
2715 const text =
2716 typeof content === "string"
2717 ? content
2718 : content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
2719 if (!text.startsWith(prefix)) return undefined;
2720 return {
2721 ...current,
2722 status: "active",
2723 checks: (current.checks ?? 0) + 1,
2724 lastCheck: text.slice(prefix.length).trim(),
2725 };
2726 }
2727
2728 /** The CLI confirms a goal change as a synthetic reply; the goal row shows that change instead. */
2729 function isClaudeGoalAcknowledgement(message: SDKMessage): boolean {
2730 if (
2731 message.type !== "assistant" ||
2732 message.parent_tool_use_id !== null ||
2733 message.message.model !== "<synthetic>"
2734 ) {
2735 return false;
2736 }
2737 const text = textFromClaudeContent(message.message.content).trim();
2738 return text.startsWith(CLAUDE_GOAL_SET_PREFIX) || text.startsWith("Goal cleared: ");
2739 }
2740
2741 const providerGoalsEqual = Schema.toEquivalence(Schema.NullOr(OrchestrationV2ProviderGoal));
2742
2743 function normalizeClaudeResultText(text: string): string {
2744 return text.replace(/\s+/g, " ").trim();
2745 }
2746
2747 function assistantTextFromSdkMessage(
2748 message: SDKMessage,
2749 ): { readonly nativeItemId: string; readonly text: string } | null {
2750 if (message.type !== "assistant") {
2751 return null;
2752 }
2753 return {
2754 nativeItemId: message.uuid,
2755 text: textFromClaudeContent(message.message.content),
2756 };
2757 }
2758
2759 function resultTextFromSdkMessage(
2760 message: SDKMessage,
2761 ): { readonly nativeItemId: string; readonly text: string } | null {
2762 if (message.type !== "result" || message.subtype !== "success") {
2763 return null;
2764 }
2765 return {
2766 nativeItemId: message.uuid,
2767 text: message.result,
2768 };
2769 }
2770
2771 function normalizeClaudeSessionTitle(title: string | null | undefined): string | null {
2772 if (title === null || title === undefined) return null;
2773 const trimmed = title.trim();
2774 return trimmed.length > 0 ? trimmed : null;
2775 }
2776
2777 function makeProviderThread(input: {
2778 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
2779 readonly providerInstanceId: ProviderInstanceId;
2780 readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
2781 readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
2782 readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
2783 readonly nativeThreadId: string;
2784 readonly forkedFrom?: NonNullable<OrchestrationV2ProviderThread["forkedFrom"]>;
2785 readonly nativeMetadata?: NonNullable<OrchestrationV2ProviderThread["nativeMetadata"]>;
2786 readonly now: DateTime.Utc;
2787 }): OrchestrationV2ProviderThread {
2788 return {
2789 id: input.idAllocator.derive.providerThread({
2790 driver: CLAUDE_PROVIDER,
2791 nativeThreadId: input.nativeThreadId,
2792 }),
2793 driver: CLAUDE_PROVIDER,
2794 providerInstanceId: input.providerInstanceId,
2795 providerSessionId: input.providerSessionId,
2796 appThreadId: input.appThreadId,
2797 ownerNodeId: input.ownerNodeId ?? null,
2798 nativeThreadRef: {
2799 driver: CLAUDE_PROVIDER,
2800 nativeId: input.nativeThreadId,
2801 strength: "strong",
2802 },
2803 nativeConversationHeadRef: null,
2804 status: "idle",
2805 firstRunOrdinal: null,
2806 lastRunOrdinal: null,
2807 handoffIds: [],
2808 forkedFrom: input.forkedFrom ?? null,
2809 ...(input.nativeMetadata === undefined ? {} : { nativeMetadata: input.nativeMetadata }),
2810 createdAt: input.now,
2811 updatedAt: input.now,
2812 };
2813 }
2814
2815 const decodeClaudeTranscriptLine = Schema.decodeUnknownOption(
2816 Schema.fromJsonString(Schema.Struct({ type: Schema.String })),
2817 );
2818
2819 const isClaudeConversationLine = (line: string): boolean =>
2820 Option.match(decodeClaudeTranscriptLine(line), {
2821 onNone: () => false,
2822 onSome: (entry) => entry.type === "user" || entry.type === "assistant",
2823 });
2824
2825 const getNativeThreadId = Effect.fnUntraced(function* (
2826 providerThread: OrchestrationV2ProviderThread,
2827 ) {
2828 const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
2829 if (nativeThreadId === undefined || nativeThreadId === null) {
2830 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2831 driver: CLAUDE_PROVIDER,
2832 detail: `Provider thread ${providerThread.id} is missing a native Claude session id.`,
2833 });
2834 }
2835 return nativeThreadId;
2836 });
2837
2838 const isSyntheticClaudeTurnId = (nativeTurnId: string): boolean => nativeTurnId.startsWith("turn:");
2839
2840 const claudeTurnCursor = (turn: OrchestrationV2ProviderTurn): string | null => {
2841 const ref = turn.nativeTurnRef;
2842 return ref !== null &&
2843 ref.driver === CLAUDE_PROVIDER &&
2844 ref.nativeId !== null &&
2845 !isSyntheticClaudeTurnId(ref.nativeId)
2846 ? ref.nativeId
2847 : null;
2848 };
2849
2850 const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
2851 turn.status === "completed" ||
2852 turn.status === "interrupted" ||
2853 turn.status === "failed" ||
2854 turn.status === "cancelled";
2855
2856 const getNativeConversationHeadId = Effect.fnUntraced(function* (
2857 providerThread: OrchestrationV2ProviderThread,
2858 ) {
2859 const nativeHeadRef = providerThread.nativeConversationHeadRef;
2860 if (nativeHeadRef === null) {
2861 return undefined;
2862 }
2863 if (nativeHeadRef.driver !== CLAUDE_PROVIDER) {
2864 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2865 driver: CLAUDE_PROVIDER,
2866 detail: `Provider thread ${providerThread.id} has a non-Claude native conversation head reference.`,
2867 });
2868 }
2869 if (nativeHeadRef.nativeId === null) {
2870 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2871 driver: CLAUDE_PROVIDER,
2872 detail: `Provider thread ${providerThread.id} has a Claude native conversation head reference without a native id.`,
2873 });
2874 }
2875 return nativeHeadRef.nativeId;
2876 });
2877
2878 const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpToMessageId")(
2879 function* (input: ProviderAdapter.ProviderAdapterV2ForkThreadInput) {
2880 if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) {
2881 return undefined;
2882 }
2883
2884 const sourceTurns = input.sourceProviderTurns
2885 .filter((turn) => turn.providerThreadId === input.sourceProviderThread.id)
2886 .toSorted((left, right) => left.ordinal - right.ordinal);
2887 const boundaryIndex = sourceTurns.findIndex((turn) => turn.id === input.providerTurnId);
2888 if (boundaryIndex < 0) {
2889 return yield* new ProviderAdapter.ProviderAdapterForkThreadError({
2890 driver: CLAUDE_PROVIDER,
2891 providerThreadId: input.sourceProviderThread.id,
2892 cause: `Cannot fork Claude thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`,
2893 });
2894 }
2895
2896 const boundaryNativeId = sourceTurns[boundaryIndex]?.nativeTurnRef?.nativeId;
2897 if (
2898 boundaryNativeId !== undefined &&
2899 boundaryNativeId !== null &&
2900 !isSyntheticClaudeTurnId(boundaryNativeId)
2901 ) {
2902 return boundaryNativeId;
2903 }
2904
2905 // The head only marks this boundary when no later turn, finished or still running, wrote after it.
2906 if (sourceTurns.length === boundaryIndex + 1) {
2907 // Rollback pins the head but leaves the rolled-back turns in Claude's transcript.
2908 return yield* getNativeConversationHeadId(input.sourceProviderThread);
2909 }
2910
2911 return yield* new ProviderAdapter.ProviderAdapterForkThreadError({
2912 driver: CLAUDE_PROVIDER,
2913 providerThreadId: input.sourceProviderThread.id,
2914 cause: `Cannot fork Claude thread from prior provider turn ${input.providerTurnId}: no SDK assistant message cursor was recorded for that turn.`,
2915 });
2916 },
2917 );
2918
2919 const resolveClaudeRollbackResumeSessionAt = Effect.fn(
2920 "ClaudeAdapterV2.resolveRollbackResumeSessionAt",
2921 )(function* (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) {
2922 switch (input.target.type) {
2923 case "thread_start":
2924 return input.providerThread.nativeMetadata?.forkHeadMessageId ?? null;
2925 case "provider_turn": {
2926 const target = input.target;
2927 if (target.providerTurn.providerThreadId !== input.providerThread.id) {
2928 return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({
2929 driver: CLAUDE_PROVIDER,
2930 providerThreadId: input.providerThread.id,
2931 cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: target turn belongs to provider thread ${target.providerTurn.providerThreadId}.`,
2932 });
2933 }
2934
2935 const cursor = claudeTurnCursor(target.providerTurn);
2936 if (cursor !== null) {
2937 return cursor;
2938 }
2939
2940 const providerTurnsAfterTarget = input.providerThreadTurns.filter(
2941 (turn) => turn.ordinal > target.providerTurn.ordinal && isTerminalProviderTurn(turn),
2942 );
2943 if (providerTurnsAfterTarget.length === 0) {
2944 return null;
2945 }
2946
2947 // Only compaction can be omitted without dropping a retained user prompt.
2948 if (target.message !== undefined && isCompactionCommandMessage(target.message)) {
2949 const earlierTurn = input.providerThreadTurns
2950 .filter((turn) => turn.ordinal < target.providerTurn.ordinal)
2951 .toSorted((left, right) => left.ordinal - right.ordinal)
2952 .at(-1);
2953 const earlierCursor = earlierTurn === undefined ? null : claudeTurnCursor(earlierTurn);
2954 if (earlierCursor != null) {
2955 return earlierCursor;
2956 }
2957 }
2958
2959 return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({
2960 driver: CLAUDE_PROVIDER,
2961 providerThreadId: input.providerThread.id,
2962 cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: no SDK assistant message cursor was recorded for that turn.`,
2963 });
2964 }
2965 }
2966 });
2967
2968 type ClaudeUserContent = SDKUserMessage["message"]["content"];
2969 type ClaudeUserContentBlock = Exclude<ClaudeUserContent, string>[number];
2970
2971 const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = [
2972 "image/gif",
2973 "image/jpeg",
2974 "image/png",
2975 "image/webp",
2976 ] as const;
2977 type SupportedClaudeImageMimeType = (typeof SUPPORTED_CLAUDE_IMAGE_MIME_TYPES)[number];
2978 const supportedClaudeImageMimeTypes = new Set<string>(SUPPORTED_CLAUDE_IMAGE_MIME_TYPES);
2979
2980 function isSupportedClaudeImageMimeType(
2981 mimeType: string,
2982 ): mimeType is SupportedClaudeImageMimeType {
2983 return supportedClaudeImageMimeTypes.has(mimeType);
2984 }
2985
2986 export function makeClaudeUserMessage(input: {
2987 readonly text: string;
2988 readonly priority?: SDKUserMessage["priority"];
2989 readonly skills?: ReadonlyMap<string, ClaudeSkillTarget>;
2990 readonly skillMentionsFrom?: number;
2991 readonly uuid?: SDKUserMessage["uuid"];
2992 }): SDKUserMessage {
2993 // Claude expands a skill only when `/name` starts the last text block.
2994 // Keep the whole request before that block; see ClaudeSkillDispatch.
2995 const dispatch =
2996 input.skills === undefined
2997 ? undefined
2998 : planClaudeSkillDispatch(input.text, input.skills, input.skillMentionsFrom);
2999 // Claude runs `/goal` only when it opens the prompt, so a goal stays one block.
3000 const isGoalCommand = parseGoalCommand({ text: input.text }) !== null;
3001 return {
3002 type: "user",
3003 message: {
3004 role: "user",
3005 content: isGoalCommand
3006 ? (dispatch?.leadingText ?? input.text)
3007 : dispatch
3008 ? [
3009 ...(dispatch.leadingText === undefined
3010 ? []
3011 : [{ type: "text" as const, text: dispatch.leadingText }]),
3012 { type: "text" as const, text: dispatch.commandText },
3013 ]
3014 : input.text,
3015 },
3016 parent_tool_use_id: null,
3017 ...(input.priority === undefined ? {} : { priority: input.priority }),
3018 ...(input.uuid === undefined ? {} : { uuid: input.uuid }),
3019 };
3020 }
3021
3022 // Never decode streams just to enforce a provider limit. Only accept an explicit,
3023 // uncompressed page tree whose /Count agrees with the visible page objects.
3024 const estimateClaudePdfPages = (bytes: Buffer): number | null => {
3025 if (bytes.length > 20 * 1024 * 1024 || bytes.subarray(0, 5).toString() !== "%PDF-") return null;
3026 if (!bytes.subarray(-1024).includes("%%EOF")) return null;
3027 let pages = 0;
3028 let count = 0;
3029 let catalog = false;
3030 let pageTree = false;
3031 let previous = "";
3032 const delimiter = (byte: number) =>
3033 byte <= 32 || "()<>[]{}/%".includes(String.fromCharCode(byte));
3034 for (let i = 0; i < bytes.length;) {
3035 const byte = bytes[i]!;
3036 if (byte === 37) {
3037 while (i < bytes.length && bytes[i] !== 10 && bytes[i] !== 13) i++;
3038 continue;
3039 }
3040 if (byte <= 32) {
3041 i++;
3042 continue;
3043 }
3044 if (previous === "/Type" && byte !== 47) return null;
3045 if (previous === "/Kids") {
3046 if (byte !== 91) return null;
3047 previous = "";
3048 }
3049 if (byte === 40) {
3050 let depth = 1;
3051 for (i++; i < bytes.length && depth > 0; i++) {
3052 if (bytes[i] === 92) i++;
3053 else if (bytes[i] === 40) depth++;
3054 else if (bytes[i] === 41) depth--;
3055 }
3056 if (depth !== 0) return null;
3057 previous = "";
3058 continue;
3059 }
3060 if (byte === 60 && bytes[i + 1] !== 60) {
3061 i = bytes.indexOf(62, i + 1);
3062 if (i < 0) return null;
3063 i++;
3064 previous = "";
3065 continue;
3066 }
3067 if (byte === 60 && bytes[i + 1] === 60) {
3068 i += 2;
3069 previous = "";
3070 continue;
3071 }
3072 if (delimiter(byte) && byte !== 47) {
3073 i++;
3074 continue;
3075 }
3076 const start = i++;
3077 while (i < bytes.length && !delimiter(bytes[i]!)) i++;
3078 if (i - start > 64) return null;
3079 const token = bytes.toString("latin1", start, i);
3080 if (token.includes("#") || ["/ObjStm", "/XRef", "/Encrypt", "/Prev"].includes(token))
3081 return null;
3082 if (token === "stream") {
3083 i = bytes.indexOf("endstream", i);
3084 if (i < 0) return null;
3085 i += 9;
3086 previous = "";
3087 continue;
3088 }
3089 if (previous === "/Type") {
3090 if (token === "/Page") pages++;
3091 if (token === "/Catalog") catalog = true;
3092 if (token === "/Pages") pageTree = true;
3093 }
3094 if (previous === "/Count") {
3095 if (!/^[1-9]\d{0,8}$/.test(token)) return null;
3096 let next = i;
3097 while (next < bytes.length) {
3098 if (bytes[next]! <= 32) next++;
3099 else if (bytes[next] === 37) {
3100 while (next < bytes.length && bytes[next] !== 10 && bytes[next] !== 13) next++;
3101 } else break;
3102 }
3103 // A second scalar is an indirect reference, not a direct page count.
3104 if (next < bytes.length && !delimiter(bytes[next]!)) return null;
3105 count = Math.max(count, Number(token));
3106 }
3107 previous = token;
3108 }
3109 return catalog && pageTree && pages > 0 && count === pages ? pages : null;
3110 };
3111
3112 const CLAUDE_ATTACHMENT_MAX_BYTES = 28 * 1024 * 1024;
3113 const CLAUDE_ATTACHMENT_MAX_PAGES = 100;
3114
3115 const makeClaudeAttachmentBudget = (used?: { pagesUsed: number; bytesUsed: number }) => ({
3116 committed: { pages: used?.pagesUsed ?? 0, bytes: used?.bytesUsed ?? 0 },
3117 pending: { pages: 0, bytes: 0 },
3118 compacting: null as { pages: number; bytes: number } | null,
3119 get remainingPages() {
3120 return CLAUDE_ATTACHMENT_MAX_PAGES - this.committed.pages - this.pending.pages;
3121 },
3122 get remainingBytes() {
3123 return CLAUDE_ATTACHMENT_MAX_BYTES - this.committed.bytes - this.pending.bytes;
3124 },
3125 });
3126
3127 const joinFallbackText = (earlier: string, current: string) =>
3128 earlier.length === 0 ? current : current.length === 0 ? earlier : `${earlier}\n\n${current}`;
3129
3130 const reserveClaudePdfBudget = (
3131 budget: ReturnType<typeof makeClaudeAttachmentBudget>,
3132 persist: Effect.Effect<void>,
3133 ) =>
3134 Effect.acquireRelease(
3135 Effect.sync(() => ({
3136 budget,
3137 pages: 0,
3138 bytes: 0,
3139 delivered: false,
3140 refunded: false,
3141 commit() {
3142 if (this.delivered) return;
3143 this.delivered = true;
3144 budget.pending.pages -= this.pages;
3145 budget.pending.bytes -= this.bytes;
3146 budget.committed.pages += this.pages;
3147 budget.committed.bytes += this.bytes;
3148 },
3149 // Claude dropped the message unread, so its files never entered the session.
3150 refund() {
3151 if (!this.delivered || this.refunded) return;
3152 this.refunded = true;
3153 budget.committed.pages -= this.pages;
3154 budget.committed.bytes -= this.bytes;
3155 },
3156 })),
3157 (reservation) =>
3158 Effect.sync(() => {
3159 if (reservation.delivered) return;
3160 budget.pending.pages -= reservation.pages;
3161 budget.pending.bytes -= reservation.bytes;
3162 }).pipe(Effect.andThen(persist)),
3163 );
3164
3165 // MCP app notes are app-written, so they go as quoted user input like Codex's untrusted context.
3166 // A slash command runs only when it opens a plain-text prompt; its note waits for the next turn.
3167 // Returns `message` itself when it adds nothing.
3168 const withClaudeAppContext = (
3169 message: SDKUserMessage,
3170 appContext: NonNullable<ProviderAdapter.ProviderAdapterV2TurnInput["appContext"]>,
3171 reservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>,
3172 ): SDKUserMessage => {
3173 const content = message.message.content;
3174 if (appContext.length === 0 || (typeof content === "string" && content.startsWith("/"))) {
3175 return message;
3176 }
3177 const contextBlocks = appContext.map((entry) => ({
3178 type: "text" as const,
3179 text: `<external_${entry.key}>${entry.text}</external_${entry.key}>`,
3180 }));
3181 const bytes = Buffer.byteLength(encodeClaudeJson(contextBlocks));
3182 reservation.budget.pending.bytes += bytes;
3183 reservation.bytes += bytes;
3184 return {
3185 ...message,
3186 message: {
3187 ...message.message,
3188 content: [
3189 ...contextBlocks,
3190 ...(typeof content === "string" ? [{ type: "text" as const, text: content }] : content),
3191 ],
3192 },
3193 };
3194 };
3195
3196 const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: {
3197 readonly text: string;
3198 readonly attachments: ReadonlyArray<ChatAttachment>;
3199 readonly priority?: SDKUserMessage["priority"];
3200 readonly uuid?: SDKUserMessage["uuid"];
3201 readonly attachmentsDir: string;
3202 readonly fileSystem: FileSystem.FileSystem;
3203 readonly pdfReservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>;
3204 readonly skills?: ReadonlyMap<string, ClaudeSkillTarget>;
3205 readonly skillMentionsFrom?: number;
3206 }) {
3207 if (input.attachments.length === 0) {
3208 const message = makeClaudeUserMessage({
3209 text: input.text,
3210 ...(input.skills === undefined ? {} : { skills: input.skills }),
3211 ...(input.skillMentionsFrom === undefined
3212 ? {}
3213 : { skillMentionsFrom: input.skillMentionsFrom }),
3214 ...(input.priority === undefined ? {} : { priority: input.priority }),
3215 ...(input.uuid === undefined ? {} : { uuid: input.uuid }),
3216 });
3217 const bytes = Buffer.byteLength(encodeClaudeJson(message.message.content));
3218 input.pdfReservation.budget.pending.bytes += bytes;
3219 input.pdfReservation.bytes += bytes;
3220 return message;
3221 }
3222
3223 const textWithAttachmentPaths = yield* providerMessageTextWithAttachmentPaths({
3224 text: input.text,
3225 attachments: input.attachments,
3226 resolveExtractedTextPath: (path) =>
3227 DocumentText.resolveExtractedTextPath(path).pipe(
3228 Effect.provideService(FileSystem.FileSystem, input.fileSystem),
3229 ),
3230 resolveAttachmentPath: (attachment) =>
3231 resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment }),
3232 });
3233
3234 const dispatch =
3235 input.skills === undefined
3236 ? undefined
3237 : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills, input.skillMentionsFrom);
3238 const content: Array<ClaudeUserContentBlock> = [];
3239 // Base64 adds a third to the payload. Leave room below Anthropic's 32 MB
3240 // request limit for text, instructions, and SDK framing. The SDK does not
3241 // expose document/context-window capabilities, so use the 100-page limit
3242 // that also applies to models with less than a 1M-token context window.
3243 if (dispatch?.leadingText !== undefined) {
3244 content.push({ type: "text", text: dispatch.leadingText });
3245 }
3246
3247 // Reserve all text and actual image bytes before considering any document,
3248 // including images that follow it in attachment order.
3249 const images = new Map<number, ClaudeUserContentBlock>();
3250 const textBytes = Buffer.byteLength(
3251 encodeClaudeJson(
3252 dispatch
3253 ? [
3254 ...(dispatch.leadingText === undefined
3255 ? []
3256 : [{ type: "text", text: dispatch.leadingText }]),
3257 { type: "text", text: dispatch.commandText },
3258 ]
3259 : [{ type: "text", text: textWithAttachmentPaths }],
3260 ),
3261 );
3262 input.pdfReservation.budget.pending.bytes += textBytes;
3263 input.pdfReservation.bytes += textBytes;
3264 for (const [index, attachment] of input.attachments.entries()) {
3265 if (attachment.type !== "image") continue;
3266 if (!isSupportedClaudeImageMimeType(attachment.mimeType)) {
3267 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3268 driver: CLAUDE_PROVIDER,
3269 detail: `Unsupported Claude image attachment type '${attachment.mimeType}'`,
3270 });
3271 }
3272 const attachmentPath = resolveAttachmentPath({
3273 attachmentsDir: input.attachmentsDir,
3274 attachment,
3275 });
3276 if (attachmentPath === null) {
3277 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3278 driver: CLAUDE_PROVIDER,
3279 detail: `Invalid attachment id '${attachment.id}'`,
3280 });
3281 }
3282 const bytes = yield* input.fileSystem.readFile(attachmentPath).pipe(
3283 Effect.mapError(
3284 (cause) =>
3285 new ProviderAdapter.ProviderAdapterProtocolError({
3286 driver: CLAUDE_PROVIDER,
3287 detail: `Failed to read attachment '${attachment.id}'`,
3288 reason: "attachment_unreadable",
3289 payload: cause,
3290 }),
3291 ),
3292 );
3293 const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
3294 if (retainedBytes > input.pdfReservation.budget.remainingBytes) continue;
3295 input.pdfReservation.budget.pending.bytes += retainedBytes;
3296 input.pdfReservation.bytes += retainedBytes;
3297 const block: ClaudeUserContentBlock = {
3298 type: "image",
3299 source: {
3300 type: "base64",
3301 media_type: attachment.mimeType,
3302 data: Buffer.from(bytes).toString("base64"),
3303 },
3304 };
3305 images.set(index, block);
3306 }
3307 for (const [index, attachment] of input.attachments.entries()) {
3308 if (attachment.type === "file") {
3309 if (
3310 input.pdfReservation.budget.remainingPages <= 0 ||
3311 attachment.mimeType.toLowerCase().split(";", 1)[0]?.trim() !== "application/pdf" ||
3312 ("source" in attachment && attachment.source?._tag === "pasted-text")
3313 )
3314 continue;
3315 const attachmentPath = resolveAttachmentPath({
3316 attachmentsDir: input.attachmentsDir,
3317 attachment,
3318 });
3319 if (attachmentPath === null) continue;
3320 const remainingBytes = Math.min(
3321 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
3322 20 * 1024 * 1024,
3323 Math.floor(((input.pdfReservation.budget.remainingBytes - 1024) * 3) / 4),
3324 );
3325 const info = yield* input.fileSystem
3326 .stat(attachmentPath)
3327 .pipe(Effect.orElseSucceed(() => null));
3328 if (info?.type !== "File" || Number(info.size) > remainingBytes || remainingBytes <= 0)
3329 continue;
3330 const bytes = yield* input.fileSystem
3331 .stream(attachmentPath, { bytesToRead: remainingBytes + 1 })
3332 .pipe(
3333 Stream.runCollect,
3334 Effect.map((chunks) => Buffer.concat(chunks)),
3335 Effect.orElseSucceed(() => null),
3336 );
3337 if (bytes === null || bytes.length > remainingBytes) continue;
3338 const pageCount = estimateClaudePdfPages(bytes);
3339 if (pageCount === null) {
3340 yield* Effect.logDebug("Claude PDF page count is unknown; keeping attachment path-only.");
3341 continue;
3342 }
3343 const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
3344 if (
3345 pageCount <= 0 ||
3346 pageCount > input.pdfReservation.budget.remainingPages ||
3347 retainedBytes > input.pdfReservation.budget.remainingBytes
3348 )
3349 continue;
3350 input.pdfReservation.budget.pending.pages += pageCount;
3351 input.pdfReservation.pages += pageCount;
3352 const block: ClaudeUserContentBlock = {
3353 type: "document",
3354 source: { type: "base64", media_type: "application/pdf", data: bytes.toString("base64") },
3355 };
3356 input.pdfReservation.budget.pending.bytes += retainedBytes;
3357 input.pdfReservation.bytes += retainedBytes;
3358 content.push(block);
3359 continue;
3360 }
3361 const image = images.get(index);
3362 if (image !== undefined) content.push(image);
3363 }
3364
3365 // Images must precede the command block for skill expansion.
3366 if (dispatch) {
3367 content.push({ type: "text", text: dispatch.commandText });
3368 } else if (textWithAttachmentPaths.length > 0) {
3369 content.push({ type: "text", text: textWithAttachmentPaths });
3370 }
3371
3372 return {
3373 type: "user",
3374 message: {
3375 role: "user",
3376 content,
3377 },
3378 parent_tool_use_id: null,
3379 ...(input.priority === undefined ? {} : { priority: input.priority }),
3380 ...(input.uuid === undefined ? {} : { uuid: input.uuid }),
3381 } satisfies SDKUserMessage;
3382 });
3383
3384 export function isClaudePromptUuid(value: string): value is NonNullable<SDKUserMessage["uuid"]> {
3385 return /^[^-]+-[^-]+-[^-]+-[^-]+-[^-]+$/.test(value);
3386 }
3387
3388 type ClaudeAssistantContentBlock = SDKAssistantMessage["message"]["content"][number];
3389 type ClaudeToolUseContentBlock = Extract<
3390 ClaudeAssistantContentBlock,
3391 {
3392 readonly id: string;
3393 readonly name: string;
3394 readonly input: unknown;
3395 }
3396 >;
3397 type ClaudeAssistantToolResultContentBlock = Extract<
3398 ClaudeAssistantContentBlock,
3399 {
3400 readonly tool_use_id: string;
3401 }
3402 >;
3403 type ClaudeUserToolResultContentBlock = Extract<
3404 ClaudeUserContentBlock,
3405 {
3406 readonly tool_use_id: string;
3407 }
3408 >;
3409 type ClaudeToolResultContentBlock =
3410 | ClaudeAssistantToolResultContentBlock
3411 | ClaudeUserToolResultContentBlock;
3412 type ClaudeTypedToolResultContentBlock = Exclude<
3413 ClaudeToolResultContentBlock,
3414 { readonly type: "mcp_tool_result" | "tool_result" }
3415 >;
3416 type ClaudeTypedToolResultContent = ClaudeTypedToolResultContentBlock["content"];
3417 type ClaudeToolResultOutput =
3418 | Extract<ClaudeToolResultContentBlock, { readonly type: "tool_result" }>["content"]
3419 | Extract<ClaudeToolResultContentBlock, { readonly type: "mcp_tool_result" }>["content"]
3420 | ClaudeTypedToolResultContent;
3421
3422 function assertNever(value: never): never {
3423 throw new Error(`Unhandled Claude SDK variant: ${jsonStringifyForTool(value)}`);
3424 }
3425
3426 const ClaudeRuntimeSandboxPolicyKind = Schema.Struct({
3427 type: Schema.Literals(["dangerFullAccess", "externalSandbox", "readOnly", "workspaceWrite"]),
3428 });
3429 type ClaudeRuntimeSandboxPolicy = typeof ClaudeRuntimeSandboxPolicyKind.Type;
3430 type ClaudeRuntimeSandboxPolicyKindName = ClaudeRuntimeSandboxPolicy["type"];
3431 const isClaudeRuntimeSandboxPolicyKind = Schema.is(ClaudeRuntimeSandboxPolicyKind);
3432
3433 const ClaudeRuntimeReadOnlyFullAccessSandboxPolicy = Schema.Struct({
3434 type: Schema.Literal("readOnly"),
3435 access: Schema.Struct({
3436 type: Schema.Literal("fullAccess"),
3437 }),
3438 });
3439 const isClaudeRuntimeReadOnlyFullAccessSandboxPolicy = Schema.is(
3440 ClaudeRuntimeReadOnlyFullAccessSandboxPolicy,
3441 );
3442
3443 function sandboxPolicyKindForClaudeRuntimePolicy(
3444 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
3445 ): ClaudeRuntimeSandboxPolicyKindName | undefined {
3446 return runtimePolicy.sandboxPolicy !== undefined &&
3447 isClaudeRuntimeSandboxPolicyKind(runtimePolicy.sandboxPolicy)
3448 ? runtimePolicy.sandboxPolicy.type
3449 : undefined;
3450 }
3451
3452 function readOnlyPolicyAllowsGlobalReads(
3453 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
3454 ): boolean {
3455 return (
3456 runtimePolicy.sandboxPolicy !== undefined &&
3457 isClaudeRuntimeReadOnlyFullAccessSandboxPolicy(runtimePolicy.sandboxPolicy)
3458 );
3459 }
3460
3461 function permissionModeForClaudeRuntimePolicy(
3462 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
3463 ): PermissionMode {
3464 if (runtimePolicy.interactionMode === "plan") {
3465 return "plan";
3466 }
3467 if (runtimePolicy.approvalPolicy === "never") {
3468 switch (sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy)) {
3469 case "readOnly":
3470 return "dontAsk";
3471 case "dangerFullAccess":
3472 case "externalSandbox":
3473 return "bypassPermissions";
3474 case "workspaceWrite":
3475 case undefined:
3476 return runtimePolicy.runtimeMode === "approval-required"
3477 ? "dontAsk"
3478 : runtimePolicy.runtimeMode === "auto-accept-edits"
3479 ? "acceptEdits"
3480 : "bypassPermissions";
3481 }
3482 }
3483 if (runtimePolicy.approvalPolicy !== undefined && runtimePolicy.approvalPolicy !== "never") {
3484 return "default";
3485 }
3486
3487 switch (sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy)) {
3488 case "readOnly":
3489 return "dontAsk";
3490 case "dangerFullAccess":
3491 return runtimePolicy.runtimeMode === "approval-required" ? "default" : "bypassPermissions";
3492 case "externalSandbox":
3493 case "workspaceWrite":
3494 case undefined:
3495 break;
3496 }
3497
3498 switch (runtimePolicy.runtimeMode) {
3499 case "approval-required":
3500 return "default";
3501 case "auto-accept-edits":
3502 return "acceptEdits";
3503 case "auto":
3504 return "auto";
3505 case "full-access":
3506 return "bypassPermissions";
3507 }
3508 }
3509
3510 export interface ClaudeRuntimeQueryPolicy {
3511 readonly permissionMode: PermissionMode;
3512 readonly tools?: ClaudeAgentSdkQueryTools;
3513 readonly allowedTools?: ReadonlyArray<string>;
3514 readonly allowDangerouslySkipPermissions?: true;
3515 readonly installPermissionCallback: boolean;
3516 }
3517
3518 interface ClaudeBypassAvailability {
3519 readonly bypassDisabled: boolean;
3520 readonly autoDisabled: boolean;
3521 }
3522
3523 const CLAUDE_BYPASS_FULLY_AVAILABLE: ClaudeBypassAvailability = {
3524 bypassDisabled: false,
3525 autoDisabled: false,
3526 };
3527
3528 export function claudeRuntimeQueryPolicyForRuntimePolicy(
3529 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
3530 availability: ClaudeBypassAvailability = CLAUDE_BYPASS_FULLY_AVAILABLE,
3531 ): ClaudeRuntimeQueryPolicy {
3532 const requestedMode = permissionModeForClaudeRuntimePolicy(runtimePolicy);
3533 const downgraded = requestedMode === "bypassPermissions" && availability.bypassDisabled;
3534 const permissionMode = downgraded
3535 ? availability.autoDisabled
3536 ? "default"
3537 : "auto"
3538 : requestedMode;
3539 const readOnlyTools =
3540 sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy) === "readOnly"
3541 ? CLAUDE_READ_ONLY_ALLOWED_TOOLS
3542 : undefined;
3543 const allowedTools =
3544 readOnlyTools !== undefined && readOnlyPolicyAllowsGlobalReads(runtimePolicy)
3545 ? readOnlyTools
3546 : undefined;
3547 // acceptEdits approves edits before the callback; the callback must ask for everything else.
3548 const installPermissionCallback =
3549 downgraded ||
3550 (runtimePolicy.approvalPolicy === undefined
3551 ? runtimePolicy.runtimeMode === "approval-required" ||
3552 runtimePolicy.runtimeMode === "auto-accept-edits"
3553 : runtimePolicy.approvalPolicy !== "never");
3554
3555 if (permissionMode === "plan") {
3556 return {
3557 permissionMode,
3558 ...(readOnlyTools === undefined ? {} : { tools: readOnlyTools }),
3559 ...(allowedTools === undefined ? {} : { allowedTools }),
3560 // Claude routes Plan-mode writes to the callback even in Auto or Full access.
3561 installPermissionCallback: true,
3562 };
3563 }
3564
3565 return {
3566 permissionMode,
3567 ...(readOnlyTools === undefined ? {} : { tools: readOnlyTools }),
3568 ...(allowedTools === undefined ? {} : { allowedTools }),
3569 ...(permissionMode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : {}),
3570 installPermissionCallback,
3571 };
3572 }
3573
3574 const ClaudeBypassSettings = Schema.StructWithRest(
3575 Schema.Struct({
3576 disableAutoMode: Schema.optionalKey(Schema.Literals(["disable", false])),
3577 permissions: Schema.optionalKey(
3578 Schema.StructWithRest(
3579 Schema.Struct({
3580 disableBypassPermissionsMode: Schema.optionalKey(Schema.Literals(["disable", false])),
3581 disableAutoMode: Schema.optionalKey(Schema.Literals(["disable", false])),
3582 }),
3583 [Schema.Record(Schema.String, Schema.Unknown)],
3584 ),
3585 ),
3586 }),
3587 [Schema.Record(Schema.String, Schema.Unknown)],
3588 );
3589 const decodeClaudeBypassSettings = Schema.decodeUnknownEffect(
3590 fromLenientJson(ClaudeBypassSettings),
3591 );
3592 const decodeClaudeLaunchArgBypassSettings = Schema.decodeUnknownEffect(ClaudeBypassSettings);
3593
3594 function claudeSdkBypassSettings(settings: typeof ClaudeBypassSettings.Type) {
3595 const { disableAutoMode, permissions, ...rest } = settings;
3596 const {
3597 disableBypassPermissionsMode,
3598 disableAutoMode: nestedAutoMode,
3599 ...permissionRest
3600 } = permissions ?? {};
3601 return {
3602 ...rest,
3603 ...(disableAutoMode === "disable" ? { disableAutoMode } : {}),
3604 ...(permissions
3605 ? {
3606 permissions: {
3607 ...permissionRest,
3608 ...(disableBypassPermissionsMode === "disable" ? { disableBypassPermissionsMode } : {}),
3609 ...(nestedAutoMode === "disable" ? { disableAutoMode: nestedAutoMode } : {}),
3610 },
3611 }
3612 : {}),
3613 };
3614 }
3615
3616 // --settings travels to the SDK as options.settings, whose type only allows "disable".
3617 // Shapes the schema rejects keep their current pass-through; resolveBypassAvailability
3618 // already treats them as a bypass failure.
3619 const decodeClaudeLaunchArgBypassSettingsOption = Schema.decodeUnknownOption(ClaudeBypassSettings);
3620 function claudeSdkLaunchArgSettings(settings: ClaudeSdkSettings): ClaudeSdkSettings {
3621 const decoded = decodeClaudeLaunchArgBypassSettingsOption(settings);
3622 return Option.isNone(decoded)
3623 ? settings
3624 : (claudeSdkBypassSettings(decoded.value) as ClaudeSdkSettings);
3625 }
3626
3627 const ClaudePromptCacheTtl = Schema.Literals(["5m", "1h"]);
3628 const decodeClaudePromptCacheTtl = Schema.decodeUnknownOption(ClaudePromptCacheTtl);
3629 const decodeClaudeSubagentCacheSettings = Schema.decodeUnknownEffect(
3630 fromLenientJson(
3631 Schema.StructWithRest(
3632 Schema.Struct({ subagentPromptCacheTtl: Schema.optionalKey(ClaudePromptCacheTtl) }),
3633 [Schema.Record(Schema.String, Schema.Unknown)],
3634 ),
3635 ),
3636 );
3637 const decodeClaudeCompactSettings = Schema.decodeUnknownEffect(
3638 Schema.fromJsonString(
3639 Schema.Struct({
3640 autoCompactEnabled: Schema.optionalKey(Schema.Unknown),
3641 autoCompactWindow: Schema.optionalKey(Schema.Unknown),
3642 modelSettings: Schema.optionalKey(Schema.Unknown),
3643 }),
3644 ),
3645 );
3646 const decodeClaudeCompactWindow = Schema.decodeUnknownOption(Schema.Int);
3647 const decodeClaudeEnvSettings = Schema.decodeUnknownEffect(
3648 fromLenientJson(
3649 Schema.StructWithRest(
3650 Schema.Struct({ env: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)) }),
3651 [Schema.Record(Schema.String, Schema.Unknown)],
3652 ),
3653 ),
3654 );
3655
3656 function claudeBypassAvailability(
3657 settings: typeof ClaudeBypassSettings.Type,
3658 ): ClaudeBypassAvailability {
3659 return {
3660 bypassDisabled: settings.permissions?.disableBypassPermissionsMode === "disable",
3661 autoDisabled:
3662 settings.disableAutoMode === "disable" || settings.permissions?.disableAutoMode === "disable",
3663 };
3664 }
3665
3666 function requiresClaudeApproval(context: ActiveClaudeTurnContext): boolean {
3667 // CLI-forwarded requests need a person's decision even under bypass (ask rules,
3668 // safety checks, or settings fallback). Do not wait for queued init/status updates.
3669 const policy = context.queryPolicy;
3670 return policy.installPermissionCallback || policy.permissionMode === "bypassPermissions";
3671 }
3672
3673 function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string {
3674 return JSON.stringify({
3675 permissionMode: policy.permissionMode,
3676 tools: policy.tools,
3677 allowedTools: policy.allowedTools,
3678 allowDangerouslySkipPermissions: policy.allowDangerouslySkipPermissions,
3679 installPermissionCallback: policy.installPermissionCallback,
3680 });
3681 }
3682
3683 // Live-query reuse must include MCP pre-approvals, which can differ for the same policy key.
3684 export function claudeEffectiveQueryPolicyKey(
3685 queryPolicy: ClaudeRuntimeQueryPolicy,
3686 mcpOverrides: {
3687 readonly allowedTools?: ReadonlyArray<string>;
3688 readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
3689 },
3690 ): string {
3691 return JSON.stringify({
3692 runtimePolicy: claudeRuntimeQueryPolicyKey({
3693 ...queryPolicy,
3694 ...(mcpOverrides.allowedTools === undefined
3695 ? {}
3696 : { allowedTools: mcpOverrides.allowedTools }),
3697 }),
3698 mcpServers: mcpOverrides.mcpServers,
3699 });
3700 }
3701
3702 type ClaudeToolItemType = Extract<
3703 OrchestrationV2TurnItem["type"],
3704 "command_execution" | "file_change" | "dynamic_tool" | "web_search"
3705 >;
3706
3707 interface ClaudeToolClassification {
3708 readonly normalizedName: string;
3709 readonly itemType: ClaudeToolItemType;
3710 readonly requestKind: ProviderRequestKind;
3711 }
3712
3713 function normalizedClaudeToolName(toolName: string): string {
3714 return toolName.toLowerCase().replaceAll(/[\s_-]/g, "");
3715 }
3716
3717 const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record<
3718 string,
3719 {
3720 readonly itemType: ClaudeToolItemType;
3721 readonly requestKind: ProviderRequestKind;
3722 }
3723 > = {
3724 agent: { itemType: "dynamic_tool", requestKind: "command" },
3725 bash: { itemType: "command_execution", requestKind: "command" },
3726 edit: { itemType: "file_change", requestKind: "file-change" },
3727 glob: { itemType: "dynamic_tool", requestKind: "file-read" },
3728 grep: { itemType: "dynamic_tool", requestKind: "file-read" },
3729 ls: { itemType: "dynamic_tool", requestKind: "file-read" },
3730 monitor: { itemType: "dynamic_tool", requestKind: "command" },
3731 multiedit: { itemType: "file_change", requestKind: "file-change" },
3732 notebookedit: { itemType: "file_change", requestKind: "file-change" },
3733 read: { itemType: "dynamic_tool", requestKind: "file-read" },
3734 sendmessage: { itemType: "dynamic_tool", requestKind: "command" },
3735 task: { itemType: "dynamic_tool", requestKind: "command" },
3736 taskstop: { itemType: "dynamic_tool", requestKind: "command" },
3737 todowrite: { itemType: "dynamic_tool", requestKind: "command" },
3738 toolsearch: { itemType: "dynamic_tool", requestKind: "command" },
3739 webfetch: { itemType: "web_search", requestKind: "command" },
3740 websearch: { itemType: "web_search", requestKind: "command" },
3741 write: { itemType: "file_change", requestKind: "file-change" },
3742 };
3743
3744 function classifyClaudeNativeTool(toolName: string): ClaudeToolClassification {
3745 const normalizedName = normalizedClaudeToolName(toolName);
3746 const known = CLAUDE_KNOWN_TOOL_CLASSIFICATIONS[normalizedName];
3747 return known === undefined
3748 ? {
3749 normalizedName,
3750 itemType: "dynamic_tool",
3751 requestKind: "command",
3752 }
3753 : {
3754 normalizedName,
3755 ...known,
3756 };
3757 }
3758
3759 function providerRequestKindFromClaudeTool(toolName: string): ProviderRequestKind {
3760 return classifyClaudeNativeTool(toolName).requestKind;
3761 }
3762
3763 function isClaudeWebSearchOutput(output: unknown): output is WebSearchOutput {
3764 return (
3765 typeof output === "object" &&
3766 output !== null &&
3767 typeof Reflect.get(output, "query") === "string" &&
3768 Array.isArray(Reflect.get(output, "results")) &&
3769 typeof Reflect.get(output, "durationSeconds") === "number"
3770 );
3771 }
3772
3773 const ClaudeNativeToolInputRecord = Schema.Record(Schema.String, Schema.Unknown);
3774 type ClaudeNativeToolInputRecord = typeof ClaudeNativeToolInputRecord.Type;
3775 const isClaudeNativeToolInputRecord = Schema.is(ClaudeNativeToolInputRecord);
3776
3777 type ClaudeNativeToolInput =
3778 | {
3779 readonly type: "record";
3780 readonly value: ClaudeNativeToolInputRecord;
3781 }
3782 | {
3783 readonly type: "non_record";
3784 readonly value: unknown;
3785 };
3786
3787 const EMPTY_CLAUDE_NATIVE_TOOL_INPUT = {
3788 type: "record",
3789 value: {},
3790 } satisfies ClaudeNativeToolInput;
3791
3792 function claudeNativeToolInputFromUnknown(input: unknown): ClaudeNativeToolInput {
3793 return isClaudeNativeToolInputRecord(input)
3794 ? { type: "record", value: input }
3795 : { type: "non_record", value: input };
3796 }
3797
3798 function claudeNativeToolInputFromRecord(input: Record<string, unknown>): ClaudeNativeToolInput {
3799 return { type: "record", value: input };
3800 }
3801
3802 function claudeNativeToolInputValue(input: ClaudeNativeToolInput): unknown {
3803 return input.value;
3804 }
3805
3806 function inputRecordValue(input: ClaudeNativeToolInput, key: string): unknown {
3807 return input.type === "record" ? input.value[key] : undefined;
3808 }
3809
3810 function firstStringInputField(
3811 input: ClaudeNativeToolInput,
3812 keys: ReadonlyArray<string>,
3813 ): string | undefined {
3814 for (const key of keys) {
3815 const value = inputRecordValue(input, key);
3816 if (typeof value === "string" && value.trim().length > 0) {
3817 return value.trim();
3818 }
3819 }
3820 return undefined;
3821 }
3822
3823 function jsonStringifyForTool(value: unknown): string {
3824 if (typeof value === "string") {
3825 return value;
3826 }
3827 return JSON.stringify(value) ?? String(value);
3828 }
3829
3830 function commandInputFromClaudeTool(toolName: string, input: ClaudeNativeToolInput): string {
3831 return (
3832 firstStringInputField(input, ["command", "cmd", "script"]) ??
3833 `${toolName}: ${jsonStringifyForTool(claudeNativeToolInputValue(input))}`
3834 );
3835 }
3836
3837 // background_tasks_changed can include subagents already counted by their lifecycle.
3838 const CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS: ReadonlyMap<
3839 string,
3840 Exclude<OrchestrationV2PendingBackgroundTask["kind"], "subagent">
3841 > = new Map([["local_bash", "command"]]);
3842
3843 // Claude Code 2.1.292 defers its goal Stop hook for these subagent types.
3844 // local_bash tasks defer it through the opaque-task roster.
3845 const CLAUDE_GOAL_DEFERRING_TASK_TYPES: ReadonlySet<string> = new Set([
3846 "local_agent",
3847 "remote_agent",
3848 "in_process_teammate",
3849 "local_workflow",
3850 ]);
3851
3852 function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined): boolean {
3853 return typeof taskType === "string" && CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.has(taskType);
3854 }
3855
3856 function claudePendingBackgroundTask(input: {
3857 readonly taskId: string;
3858 readonly taskType: string | null;
3859 // Only the launching Monitor tool distinguishes a local_bash Monitor from background Bash.
3860 readonly startedByMonitor: boolean;
3861 readonly description: string | undefined;
3862 // Undeclared SDK field: the subagent whose own background work this is.
3863 readonly parentTaskId: unknown;
3864 readonly toolUseId: string | undefined;
3865 }): OrchestrationV2PendingBackgroundTask {
3866 return {
3867 taskId: input.taskId,
3868 kind: input.startedByMonitor
3869 ? "monitor"
3870 : ((input.taskType === null
3871 ? undefined
3872 : CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.get(input.taskType)) ?? "background_task"),
3873 ...(input.description !== undefined && input.description.trim().length > 0
3874 ? { description: input.description }
3875 : {}),
3876 ...(typeof input.parentTaskId === "string" && input.parentTaskId.trim().length > 0
3877 ? { parentTaskId: input.parentTaskId }
3878 : {}),
3879 ...(input.toolUseId === undefined ? {} : { nativeItemId: input.toolUseId }),
3880 };
3881 }
3882
3883 function claudeTaskTypeFromSdkMessage(message: SDKMessage): string | null {
3884 if (typeof message !== "object" || message === null) {
3885 return null;
3886 }
3887 const taskType = Reflect.get(message, "task_type");
3888 return typeof taskType === "string" ? taskType : null;
3889 }
3890
3891 function isClaudeNonSubagentTask(message: SDKMessage): boolean {
3892 return isClaudeOpaqueBackgroundTaskType(claudeTaskTypeFromSdkMessage(message));
3893 }
3894
3895 function isClaudeBackgroundTasksChangedMessage(message: SDKMessage): boolean {
3896 return message.type === "system" && (message.subtype as string) === "background_tasks_changed";
3897 }
3898
3899 function isClaudeTurnStartMessage(message: SDKMessage): boolean {
3900 return message.type === "system" && message.subtype === "init";
3901 }
3902
3903 function isClaudeRootTurnFrame(message: SDKMessage): boolean {
3904 return (
3905 isClaudeTurnStartMessage(message) ||
3906 ((message.type === "user" || message.type === "assistant" || message.type === "stream_event") &&
3907 message.parent_tool_use_id == null)
3908 );
3909 }
3910
3911 // One stable id per native thread: a new ScheduleWakeup replaces the pending one.
3912 const CLAUDE_SCHEDULED_WAKEUP_TASK: OrchestrationV2PendingBackgroundTask = {
3913 taskId: "claude-scheduled-wakeup",
3914 kind: "background_task",
3915 description: "Scheduled wakeup",
3916 };
3917
3918 // Claude Code jitters one-shot wakeups early but never before the requested time, which is at
3919 // most 60 s before the minute-rounded scheduledFor it reports; the rest is slack.
3920 const CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS = 120_000;
3921
3922 // The CLI answers a control request such as setModel with a replayed local-command user frame.
3923 // It belongs to no turn, so on an idle session it is not the start of a wake.
3924 function isClaudeLocalCommandEcho(message: SDKMessage): boolean {
3925 if (message.type !== "user" || !("isReplay" in message) || !message.isReplay) return false;
3926 const content = message.message.content;
3927 return typeof content === "string" && content.startsWith("<local-command-stdout>");
3928 }
3929
3930 function claudePendingBackgroundTasksFromRoster(
3931 roster: ReadonlyMap<string, OrchestrationV2PendingBackgroundTask>,
3932 awaitedTaskIds: ReadonlySet<string>,
3933 ): ReadonlyArray<OrchestrationV2PendingBackgroundTask> {
3934 return Array.from(roster.values(), (task) =>
3935 awaitedTaskIds.has(task.taskId) ? { ...task, awaited: true as const } : task,
3936 );
3937 }
3938
3939 function parseClaudeBackgroundTaskEntry(
3940 entry: unknown,
3941 monitorTasks: ReadonlyMap<string, unknown>,
3942 toolUseIds: ReadonlyMap<string, string>,
3943 ): OrchestrationV2PendingBackgroundTask | null {
3944 if (entry === null || typeof entry !== "object") {
3945 return null;
3946 }
3947 const taskId = Reflect.get(entry, "task_id");
3948 if (typeof taskId !== "string" || taskId.length === 0) {
3949 return null;
3950 }
3951 const rawTaskType = Reflect.get(entry, "task_type");
3952 const taskType = typeof rawTaskType === "string" ? rawTaskType : null;
3953 if (!isClaudeOpaqueBackgroundTaskType(taskType)) {
3954 return null;
3955 }
3956 const description = Reflect.get(entry, "description");
3957 return claudePendingBackgroundTask({
3958 taskId,
3959 taskType,
3960 startedByMonitor: monitorTasks.has(taskId),
3961 description: typeof description === "string" ? description : undefined,
3962 parentTaskId: Reflect.get(entry, "parent_task_id"),
3963 toolUseId: toolUseIds.get(taskId),
3964 });
3965 }
3966
3967 function fileNameFromClaudeTool(toolName: string, input: ClaudeNativeToolInput): string {
3968 return (
3969 firstStringInputField(input, ["file_path", "notebook_path", "path", "filename", "fileName"]) ??
3970 `${toolName} result`
3971 );
3972 }
3973
3974 type ClaudeNativeToolOutput =
3975 | {
3976 readonly type: "none";
3977 }
3978 | {
3979 readonly type: "content_block";
3980 readonly value: ClaudeToolResultOutput;
3981 }
3982 | {
3983 readonly type: "structured_tool_use_result";
3984 readonly value: unknown;
3985 readonly fallbackValue?: ClaudeToolResultOutput;
3986 };
3987
3988 const NO_CLAUDE_NATIVE_TOOL_OUTPUT = { type: "none" } satisfies ClaudeNativeToolOutput;
3989
3990 function claudeNativeToolOutputFromToolResult(
3991 toolResult: ClaudeToolResultContentBlock,
3992 ): ClaudeNativeToolOutput {
3993 const value = outputFromClaudeToolResult(toolResult);
3994 return value === undefined ? NO_CLAUDE_NATIVE_TOOL_OUTPUT : { type: "content_block", value };
3995 }
3996
3997 function claudeNativeToolOutputFromStructuredResult(input: {
3998 readonly structuredOutput: unknown;
3999 readonly fallbackValue?: ClaudeToolResultOutput;
4000 }): ClaudeNativeToolOutput {
4001 return {
4002 type: "structured_tool_use_result",
4003 value: input.structuredOutput,
4004 ...(input.fallbackValue === undefined ? {} : { fallbackValue: input.fallbackValue }),
4005 };
4006 }
4007
4008 function claudeNativeToolOutputValue(output: ClaudeNativeToolOutput): unknown | undefined {
4009 switch (output.type) {
4010 case "none":
4011 return undefined;
4012 case "content_block":
4013 return output.value;
4014 case "structured_tool_use_result":
4015 if (toolOutputImages(output.value).length === 0) {
4016 return mcpToolResultOutput({
4017 content: output.fallbackValue,
4018 structuredContent: output.value,
4019 });
4020 }
4021 return output.value;
4022 default:
4023 return assertNever(output);
4024 }
4025 }
4026
4027 function claudeNativeToolOutputText(output: ClaudeNativeToolOutput): string {
4028 const value = claudeNativeToolOutputValue(output);
4029 return typeof value === "string" ? value : value === undefined ? "" : jsonStringifyForTool(value);
4030 }
4031
4032 const decodeClaudeFileEditResult = Schema.decodeUnknownOption(
4033 Schema.Struct({
4034 type: Schema.optional(Schema.String),
4035 filePath: Schema.String,
4036 content: Schema.optional(Schema.String),
4037 structuredPatch: Schema.mutable(
4038 Schema.Array(
4039 Schema.Struct({
4040 oldStart: Schema.Number,
4041 oldLines: Schema.Number,
4042 newStart: Schema.Number,
4043 newLines: Schema.Number,
4044 lines: Schema.mutable(Schema.Array(Schema.String)),
4045 }),
4046 ),
4047 ),
4048 }),
4049 );
4050
4051 function claudeFileChangeText(output: ClaudeNativeToolOutput): string {
4052 const result =
4053 output.type === "structured_tool_use_result"
4054 ? Option.getOrUndefined(decodeClaudeFileEditResult(output.value))
4055 : undefined;
4056 if (result === undefined) return claudeNativeToolOutputText(output);
4057 const patch =
4058 result.structuredPatch.length === 0 && result.type === "create" && result.content !== undefined
4059 ? structuredPatch("/dev/null", result.filePath, "", result.content)
4060 : {
4061 oldFileName: result.filePath,
4062 newFileName: result.filePath,
4063 oldHeader: undefined,
4064 newHeader: undefined,
4065 hunks: result.structuredPatch,
4066 };
4067 return patch.hunks.length === 0 ? "" : formatPatch(patch, FILE_HEADERS_ONLY);
4068 }
4069
4070 function claudeCommandOutputText(output: ClaudeNativeToolOutput): string {
4071 const value = claudeNativeToolOutputValue(output);
4072 if (typeof value === "object" && value !== null) {
4073 const stdout = Reflect.get(value, "stdout");
4074 const stderr = Reflect.get(value, "stderr");
4075 if (typeof stdout === "string" || typeof stderr === "string") {
4076 const out = typeof stdout === "string" && stdout.trim().length > 0 ? stdout : "";
4077 const err = typeof stderr === "string" && stderr.trim().length > 0 ? stderr : "";
4078 // Claude trims each stream's trailing newline, so stderr may need one to start its line.
4079 const text =
4080 out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;
4081 if (text.length > 0) return text;
4082 return output.type === "structured_tool_use_result" && output.fallbackValue !== undefined
4083 ? claudeSubagentResultText({ type: "content_block", value: output.fallbackValue })
4084 : "";
4085 }
4086 }
4087 return claudeNativeToolOutputText(output);
4088 }
4089
4090 // Claude Code wraps a foreground Agent result in notes for the parent model, not the report: the
4091 // tools it used, a hand-back frame that indents each report line by two spaces, and a trailer.
4092 const CLAUDE_TOOLS_USED_NOTE =
4093 /^\s*<tools-used-before-summary>[^<]*<\/tools-used-before-summary>\s*/;
4094 const CLAUDE_HAND_BACK_FRAME =
4095 /^\[Subagent hand-back\] The text below is the final report of a subagent [^\n]* The report follows:\n/;
4096 const CLAUDE_USAGE_TRAILER = /(?:^|\n)<usage>[^<]*<\/usage>\s*$/;
4097 const CLAUDE_AGENT_ID_TRAILER =
4098 /(?:^|\n)agentId: ([\w-]+) \(use SendMessage with to: '\1'[^\n]*\)\s*$/;
4099
4100 function claudeSubagentResultText(output: ClaudeNativeToolOutput): string {
4101 const unwrapped = claudeSubagentRawResultText(output)
4102 .replace(CLAUDE_TOOLS_USED_NOTE, "")
4103 .replace(CLAUDE_USAGE_TRAILER, "")
4104 .replace(CLAUDE_AGENT_ID_TRAILER, "");
4105 const report = unwrapped.replace(CLAUDE_HAND_BACK_FRAME, "");
4106 return report === unwrapped ? report : report.replace(/^ {2}/gm, "");
4107 }
4108
4109 function claudeSubagentRawResultText(output: ClaudeNativeToolOutput): string {
4110 const value = claudeNativeToolOutputValue(output);
4111 const content = Array.isArray(value)
4112 ? value
4113 : typeof value === "object" && value !== null && "content" in value
4114 ? value.content
4115 : undefined;
4116 if (Array.isArray(content)) {
4117 const text = content
4118 .flatMap((part) =>
4119 typeof part === "object" &&
4120 part !== null &&
4121 "type" in part &&
4122 part.type === "text" &&
4123 "text" in part &&
4124 typeof part.text === "string"
4125 ? [part.text]
4126 : [],
4127 )
4128 .join("\n");
4129 if (text.length > 0) {
4130 return text;
4131 }
4132 }
4133 return claudeNativeToolOutputText(output);
4134 }
4135
4136 function isClaudeSubagentAsyncLaunchAck(output: ClaudeNativeToolOutput): boolean {
4137 const value = claudeNativeToolOutputValue(output);
4138 if (typeof value === "object" && value !== null) {
4139 if ("isAsync" in value && value.isAsync === true) {
4140 return true;
4141 }
4142 if ("status" in value && value.status === "async_launched") {
4143 return true;
4144 }
4145 }
4146 // A framed foreground report may itself start with this text; only the bare ACK counts.
4147 return claudeSubagentRawResultText(output)
4148 .replace(CLAUDE_TOOLS_USED_NOTE, "")
4149 .startsWith("Async agent launched successfully.");
4150 }
4151
4152 // Background Agent launches ACK immediately and workflow launches return run handles; only task_notification settles those.
4153 function claudeToolResultSettlesSubagent(
4154 toolResult: ClaudeToolResultContentBlock,
4155 output: ClaudeNativeToolOutput,
4156 ): boolean {
4157 return (
4158 isClaudeToolResultError(toolResult) ||
4159 (parseClaudeWorkflowRunHandles(claudeNativeToolOutputValue(output)) === undefined &&
4160 !isClaudeSubagentAsyncLaunchAck(output))
4161 );
4162 }
4163
4164 function claudeSettledSubagentToolUseIds(messages: ReadonlyArray<SDKMessage>): ReadonlySet<string> {
4165 return new Set(
4166 messages.flatMap((entry) =>
4167 entry.type === "user" && entry.parent_tool_use_id == null
4168 ? claudeToolResultEntriesFromMessage(entry).flatMap(({ toolResult, output }) =>
4169 claudeToolResultSettlesSubagent(toolResult, output) ? [toolResult.tool_use_id] : [],
4170 )
4171 : [],
4172 ),
4173 );
4174 }
4175
4176 function claudeWakeBufferDetail(messages: ReadonlyArray<SDKMessage>): string | null {
4177 return (
4178 messages
4179 .flatMap((entry) =>
4180 entry.type === "system" &&
4181 entry.subtype === "task_notification" &&
4182 typeof entry.summary === "string" &&
4183 entry.summary.length > 0
4184 ? [entry.summary]
4185 : [],
4186 )
4187 .at(-1) ?? null
4188 );
4189 }
4190
4191 const WEB_FETCH_SNIPPET_MAX_CHARS = 8_000;
4192
4193 function webSearchPatternsFromClaudeTool(input: {
4194 readonly toolInput: ClaudeNativeToolInput;
4195 readonly output: ClaudeNativeToolOutput;
4196 }): ReadonlyArray<string> {
4197 const output = claudeNativeToolOutputValue(input.output);
4198 const pattern =
4199 firstStringInputField(input.toolInput, ["query", "url", "pattern"]) ??
4200 (isClaudeWebSearchOutput(output) ? output.query : undefined);
4201 return pattern === undefined || pattern.trim().length === 0 ? [] : [pattern];
4202 }
4203
4204 function webSearchResultsFromClaudeOutput(
4205 output: ClaudeNativeToolOutput,
4206 ): ReadonlyArray<OrchestrationV2WebSearchResult> {
4207 const value = claudeNativeToolOutputValue(output);
4208 if (!isClaudeWebSearchOutput(value)) {
4209 return [];
4210 }
4211
4212 return value.results.flatMap((result) => {
4213 if (typeof result === "string") {
4214 return [];
4215 }
4216 return result.content.map((content) => ({
4217 title: content.title,
4218 url: content.url,
4219 }));
4220 });
4221 }
4222
4223 function summarizeClaudeToolRequest(toolName: string, input: ClaudeNativeToolInput): string {
4224 const command = firstStringInputField(input, ["command", "cmd", "script"]);
4225 if (command !== undefined) {
4226 return `${toolName}: ${command.slice(0, 400)}`;
4227 }
4228 const path = firstStringInputField(input, ["file_path", "path", "filename", "fileName"]);
4229 if (path !== undefined) {
4230 return `${toolName}: ${path.slice(0, 400)}`;
4231 }
4232 const serialized = jsonStringifyForTool(claudeNativeToolInputValue(input));
4233 return serialized.length <= 400
4234 ? `${toolName}: ${serialized}`
4235 : `${toolName}: ${serialized.slice(0, 397)}...`;
4236 }
4237
4238 function outputFromClaudeToolResult(
4239 toolResult: ClaudeToolResultContentBlock,
4240 ): ClaudeToolResultOutput | undefined {
4241 switch (toolResult.type) {
4242 case "tool_result":
4243 return toolResult.content;
4244 case "mcp_tool_result":
4245 return toolResult.content;
4246 case "bash_code_execution_tool_result":
4247 case "code_execution_tool_result":
4248 case "advisor_tool_result":
4249 case "text_editor_code_execution_tool_result":
4250 case "tool_search_tool_result":
4251 case "web_fetch_tool_result":
4252 case "web_search_tool_result":
4253 return toolResult.content;
4254 default:
4255 return assertNever(toolResult);
4256 }
4257 }
4258
4259 function isClaudeTypedToolResultErrorContent(content: ClaudeTypedToolResultContent): boolean {
4260 if (Array.isArray(content)) {
4261 return false;
4262 }
4263
4264 switch (content.type) {
4265 case "advisor_tool_result_error":
4266 case "bash_code_execution_tool_result_error":
4267 case "code_execution_tool_result_error":
4268 case "text_editor_code_execution_tool_result_error":
4269 case "tool_search_tool_result_error":
4270 case "web_fetch_tool_result_error":
4271 case "web_search_tool_result_error":
4272 return true;
4273 default:
4274 return false;
4275 }
4276 }
4277
4278 function isClaudeToolResultError(toolResult: ClaudeToolResultContentBlock): boolean {
4279 switch (toolResult.type) {
4280 case "tool_result":
4281 return toolResult.is_error === true;
4282 case "mcp_tool_result":
4283 return toolResult.is_error;
4284 case "bash_code_execution_tool_result":
4285 case "code_execution_tool_result":
4286 case "advisor_tool_result":
4287 case "text_editor_code_execution_tool_result":
4288 case "tool_search_tool_result":
4289 case "web_fetch_tool_result":
4290 case "web_search_tool_result":
4291 return isClaudeTypedToolResultErrorContent(toolResult.content);
4292 default:
4293 return assertNever(toolResult);
4294 }
4295 }
4296
4297 function toolNameFromClaudeToolResult(toolResult: ClaudeToolResultContentBlock): string {
4298 switch (toolResult.type) {
4299 case "bash_code_execution_tool_result":
4300 return "bash_code_execution";
4301 case "code_execution_tool_result":
4302 return "code_execution";
4303 case "advisor_tool_result":
4304 return "advisor";
4305 case "mcp_tool_result":
4306 return "mcp_tool";
4307 case "text_editor_code_execution_tool_result":
4308 return "text_editor_code_execution";
4309 case "tool_result":
4310 return "tool";
4311 case "tool_search_tool_result":
4312 return "tool_search";
4313 case "web_fetch_tool_result":
4314 return "web_fetch";
4315 case "web_search_tool_result":
4316 return "web_search";
4317 default:
4318 return assertNever(toolResult);
4319 }
4320 }
4321
4322 function isClaudeAssistantToolResultContentBlock(
4323 part: ClaudeAssistantContentBlock,
4324 ): part is ClaudeAssistantToolResultContentBlock {
4325 return "tool_use_id" in part && typeof part.tool_use_id === "string";
4326 }
4327
4328 function isClaudeUserToolResultContentBlock(
4329 part: ClaudeUserContentBlock,
4330 ): part is ClaudeUserToolResultContentBlock {
4331 return "tool_use_id" in part && typeof part.tool_use_id === "string";
4332 }
4333
4334 function isClaudeToolUseContentBlock(
4335 part: ClaudeAssistantContentBlock,
4336 ): part is ClaudeToolUseContentBlock {
4337 return (
4338 "id" in part &&
4339 typeof part.id === "string" &&
4340 "name" in part &&
4341 typeof part.name === "string" &&
4342 "input" in part
4343 );
4344 }
4345
4346 function claudeToolUseBlocksFromAssistantMessage(
4347 message: SDKMessage,
4348 ): ReadonlyArray<ClaudeToolUseContentBlock> {
4349 if (message.type !== "assistant") {
4350 return [];
4351 }
4352 return message.message.content.filter(isClaudeToolUseContentBlock);
4353 }
4354
4355 type ClaudeToolPresentation = ReturnType<typeof mcpToolPresentation>;
4356
4357 function claudeToolPresentationsFromAssistantMessage(
4358 message: SDKMessage,
4359 ): ReadonlyMap<string, ClaudeToolPresentation> {
4360 const presentations = new Map<string, ClaudeToolPresentation>();
4361 const meta = message.type === "assistant" ? Reflect.get(message, "tool_use_meta") : undefined;
4362 if (!Array.isArray(meta)) return presentations;
4363 const toolNames = new Map(
4364 claudeToolUseBlocksFromAssistantMessage(message).map((tool) => [
4365 tool.id,
4366 tool.name.replace(/^mcp__claude_ai_/u, "mcp__"),
4367 ]),
4368 );
4369 for (const entry of meta) {
4370 if (typeof entry !== "object" || entry === null) continue;
4371 const id = normalizeMcpText(Reflect.get(entry, "id"), 512);
4372 if (id === undefined) continue;
4373 presentations.set(
4374 id,
4375 mcpToolPresentation({
4376 toolName: toolNames.get(id),
4377 title: Reflect.get(entry, "display_name"),
4378 serverDisplayName: Reflect.get(entry, "server_display_name"),
4379 iconUrl: Reflect.get(entry, "icon_url"),
4380 }),
4381 );
4382 }
4383 return presentations;
4384 }
4385
4386 function claudeToolResultBlocksFromAssistantMessage(
4387 message: SDKMessage,
4388 ): ReadonlyArray<ClaudeToolResultContentBlock> {
4389 if (message.type !== "assistant") {
4390 return [];
4391 }
4392 return message.message.content.filter(isClaudeAssistantToolResultContentBlock);
4393 }
4394
4395 function claudeToolResultBlocksFromUserMessage(
4396 message: SDKMessage,
4397 ): ReadonlyArray<ClaudeToolResultContentBlock> {
4398 if (message.type !== "user" || typeof message.message.content === "string") {
4399 return [];
4400 }
4401 return message.message.content.filter(isClaudeUserToolResultContentBlock);
4402 }
4403
4404 function claudeToolResultEntriesFromMessage(message: SDKMessage): ReadonlyArray<{
4405 readonly toolResult: ClaudeToolResultContentBlock;
4406 readonly output: ClaudeNativeToolOutput;
4407 }> {
4408 const assistantResults = claudeToolResultBlocksFromAssistantMessage(message).map(
4409 (toolResult) => ({ toolResult, output: claudeNativeToolOutputFromToolResult(toolResult) }),
4410 );
4411 const userResults = claudeToolResultBlocksFromUserMessage(message);
4412 const structuredOutput =
4413 message.type === "user" && userResults.length === 1 ? message.tool_use_result : undefined;
4414 return [
4415 ...assistantResults,
4416 ...userResults.map((toolResult) => ({
4417 toolResult,
4418 output:
4419 structuredOutput === undefined
4420 ? claudeNativeToolOutputFromToolResult(toolResult)
4421 : claudeNativeToolOutputFromStructuredResult({
4422 structuredOutput,
4423 fallbackValue: outputFromClaudeToolResult(toolResult),
4424 }),
4425 })),
4426 ];
4427 }
4428
4429 const ClaudeToolResultMetadata = Schema.Struct({
4430 tool_result_meta: Schema.Array(
4431 Schema.Struct({
4432 id: Schema.String,
4433 non_execution_kind: Schema.optional(Schema.NullOr(Schema.String)),
4434 }),
4435 ),
4436 });
4437 const isClaudeToolResultMetadata = Schema.is(ClaudeToolResultMetadata);
4438
4439 function claudeToolNonExecutionKind(message: SDKMessage, toolUseId: string) {
4440 return isClaudeToolResultMetadata(message)
4441 ? (message.tool_result_meta.find((meta) => meta.id === toolUseId)?.non_execution_kind ??
4442 undefined)
4443 : undefined;
4444 }
4445
4446 function parentToolUseIdFromSdkMessage(message: SDKMessage): string | null {
4447 return message.type === "assistant" || message.type === "user"
4448 ? message.parent_tool_use_id
4449 : null;
4450 }
4451
4452 const CLAUDE_NO_STANDING_GRANT_OPTIONS = [
4453 { decision: "decline", label: "Decline" },
4454 { decision: "accept", label: "Approve" },
4455 ] satisfies ReadonlyArray<ProviderApprovalOption>;
4456
4457 export function claudeApprovalPresentation(input: {
4458 readonly permissionMode: PermissionMode;
4459 readonly prompt: string;
4460 readonly callbackOptions: Pick<
4461 Parameters<CanUseTool>[2],
4462 "decisionReason" | "matchedAskRule" | "suppressAlwaysAllowRule"
4463 >;
4464 }): {
4465 readonly reason?: string;
4466 readonly fullAccessOverride?: ProviderApprovalFullAccessOverride;
4467 readonly options?: ReadonlyArray<ProviderApprovalOption>;
4468 } {
4469 // The reason can carry terminal escapes from the CLI's own prompt renderer.
4470 const reason = NodeUtil.stripVTControlCharacters(
4471 input.callbackOptions.decisionReason ?? "",
4472 ).trim();
4473 // Bypass auto-allows everything it can, so any ask that still reaches the
4474 // callback is one bypass refused. The SDK drops the CLI's decision_reason_type,
4475 // leaving the matched ask rule as the only way to tell the two causes apart.
4476 const fullAccessOverride: ProviderApprovalFullAccessOverride | undefined =
4477 input.permissionMode !== "bypassPermissions"
4478 ? undefined
4479 : input.callbackOptions.matchedAskRule === undefined
4480 ? "provider_check"
4481 : "ask_rule";
4482 return {
4483 ...(reason === "" || reason === input.prompt ? {} : { reason }),
4484 ...(fullAccessOverride === undefined ? {} : { fullAccessOverride }),
4485 ...(input.callbackOptions.suppressAlwaysAllowRule === true
4486 ? { options: CLAUDE_NO_STANDING_GRANT_OPTIONS }
4487 : {}),
4488 };
4489 }
4490
4491 export function permissionResultFromDecision(input: {
4492 readonly toolName: string;
4493 readonly decision: ProviderApprovalDecision;
4494 readonly toolInput: Record<string, unknown>;
4495 readonly toolUseID: string;
4496 readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
4497 readonly feedback?: string;
4498 /** Under an administrator's ceiling, T3 Code's mode is the only one; Claude cannot switch it. */
4499 readonly managedCeiling?: boolean;
4500 }): PermissionResult {
4501 if (input.decision === "accept" || input.decision === "acceptForSession") {
4502 return {
4503 behavior: "allow",
4504 updatedInput: input.toolInput,
4505 toolUseID: input.toolUseID,
4506 decisionClassification:
4507 input.decision === "acceptForSession" ? "user_permanent" : "user_temporary",
4508 ...(input.decision === "acceptForSession"
4509 ? {
4510 updatedPermissions: toSessionPermissionUpdates(
4511 input.toolName,
4512 input.managedCeiling === true
4513 ? input.suggestions?.filter((suggestion) => suggestion.type !== "setMode")
4514 : input.suggestions,
4515 ),
4516 }
4517 : {}),
4518 };
4519 }
4520
4521 const feedback = input.feedback?.trim();
4522 return {
4523 behavior: "deny",
4524 message: feedback
4525 ? `The user declined this tool call and said:\n${feedback}`
4526 : input.decision === "cancel"
4527 ? "User cancelled tool execution."
4528 : "User declined tool execution.",
4529 toolUseID: input.toolUseID,
4530 decisionClassification: "user_reject",
4531 ...(input.decision === "cancel" ? { interrupt: true } : {}),
4532 };
4533 }
4534
4535 function toSessionPermissionUpdates(
4536 toolName: string,
4537 suggestions: ReadonlyArray<PermissionUpdate> | undefined,
4538 ): Array<PermissionUpdate> {
4539 const updates = (suggestions ?? []).map((suggestion): PermissionUpdate => ({
4540 ...suggestion,
4541 destination: "session",
4542 }));
4543 if (updates.length > 0) {
4544 return updates;
4545 }
4546 return [
4547 {
4548 type: "addRules",
4549 rules: [{ toolName }],
4550 behavior: "allow",
4551 destination: "session",
4552 },
4553 ];
4554 }
4555
4556 export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* (
4557 decision: Deferred.Deferred<ClaudeApprovalResponse>,
4558 signal: AbortSignal,
4559 ) {
4560 const cancellation = Effect.callback<ClaudeApprovalResponse>((resume) => {
4561 const abort = () => resume(Effect.succeed({ decision: "cancel" }));
4562 signal.addEventListener("abort", abort, { once: true });
4563 if (signal.aborted) {
4564 abort();
4565 }
4566 return Effect.sync(() => signal.removeEventListener("abort", abort));
4567 });
4568 return yield* Effect.raceFirst(Deferred.await(decision), cancellation);
4569 });
4570
4571 // MCP servers such as Computer Use ask on every call and expect the client to
4572 // remember a session grant, as Codex does. The CLI drops a reply's `_meta.persist`.
4573 const CLAUDE_MCP_ELICITATION_OPTIONS: ReadonlyArray<ProviderApprovalOption> = [
4574 { decision: "cancel", label: "Cancel" },
4575 { decision: "decline", label: "Decline" },
4576 { decision: "acceptForSession", label: "Always allow this session" },
4577 { decision: "accept", label: "Approve" },
4578 ];
4579
4580 type ClaudeMcpElicitationContent = NonNullable<ElicitationResult["content"]>;
4581
4582 const isClaudeMcpElicitationValue = (
4583 value: unknown,
4584 ): value is ClaudeMcpElicitationContent[string] =>
4585 typeof value === "string" ||
4586 typeof value === "number" ||
4587 typeof value === "boolean" ||
4588 (Array.isArray(value) && value.every((item) => typeof item === "string"));
4589
4590 const withoutSchemaDefaults = (schema: Record<string, unknown>): Record<string, unknown> => {
4591 const properties = schema.properties;
4592 if (typeof properties !== "object" || properties === null || Array.isArray(properties)) {
4593 return schema;
4594 }
4595 return {
4596 ...schema,
4597 properties: Object.fromEntries(
4598 Object.entries(properties).map(([key, field]) => [
4599 key,
4600 typeof field === "object" && field !== null
4601 ? Object.fromEntries(Object.entries(field).filter(([name]) => name !== "default"))
4602 : field,
4603 ]),
4604 ),
4605 };
4606 };
4607
4608 // The card collects consent only; schema defaults must never grant unseen permissions.
4609 export function claudeMcpElicitationAcceptance(
4610 request: ElicitationRequest,
4611 ): ElicitationResult | undefined {
4612 if (request.mode === "url" || request.requestedSchema === undefined) return undefined;
4613 const response = toMcpElicitationResponse(
4614 { mode: "form", requestedSchema: withoutSchemaDefaults(request.requestedSchema) },
4615 "accept",
4616 );
4617 // The helper leaves content out when the schema is not a form it can read.
4618 const filled = response.content;
4619 if (
4620 response.action !== "accept" ||
4621 typeof filled !== "object" ||
4622 filled === null ||
4623 Array.isArray(filled)
4624 ) {
4625 return undefined;
4626 }
4627 const content: ClaudeMcpElicitationContent = {};
4628 for (const [key, value] of Object.entries(filled)) {
4629 if (!isClaudeMcpElicitationValue(value)) return undefined;
4630 content[key] = value;
4631 }
4632 return { action: "accept", content };
4633 }
4634
4635 const awaitClaudeUserInputAnswers = Effect.fn("awaitClaudeUserInputAnswers")(function* (
4636 answers: Deferred.Deferred<ProviderUserInputAnswers>,
4637 signal: AbortSignal,
4638 ) {
4639 const cancellation = Effect.callback<ProviderUserInputAnswers>((resume) => {
4640 const abort = () => resume(Effect.succeed({}));
4641 signal.addEventListener("abort", abort, { once: true });
4642 if (signal.aborted) abort();
4643 return Effect.sync(() => signal.removeEventListener("abort", abort));
4644 });
4645 return yield* Effect.raceFirst(Deferred.await(answers), cancellation);
4646 });
4647
4648 /** Exclude CLI-internal "[ede_diagnostic] ..." telemetry from error banners. */
4649 function resultUserFacingError(result: SDKResultMessage): string | undefined {
4650 const errors = "errors" in result && Array.isArray(result.errors) ? result.errors : [];
4651 if (result.subtype === "success" && !result.is_error) {
4652 return undefined;
4653 }
4654 return errors.find(
4655 (error): error is string => typeof error === "string" && !error.startsWith("[ede_diagnostic]"),
4656 );
4657 }
4658
4659 const CONTEXT_WINDOW_FULL_ERROR =
4660 "Claude stopped: the prompt exceeds the model's context window. Run /compact or start a new thread.";
4661
4662 function terminalResultError(
4663 reason: SDKResultMessage["terminal_reason"],
4664 failureHint?: string,
4665 ): string | undefined {
4666 switch (reason) {
4667 case "api_error":
4668 return failureHint ?? "Claude gave up after repeated API errors.";
4669 case "malformed_tool_use_exhausted":
4670 return "Claude gave up after repeated malformed tool calls.";
4671 case "budget_exhausted":
4672 return "Claude stopped: the turn's token budget was exhausted.";
4673 case "structured_output_retry_exhausted":
4674 return "Claude could not produce the requested structured output.";
4675 case "tool_deferred_unavailable":
4676 return "Claude could not resume a deferred tool call: the tool is no longer available.";
4677 case "turn_setup_failed":
4678 return "Claude could not start the turn.";
4679 case "blocking_limit":
4680 // blocking_limit also means context exhaustion; only rate-limit evidence sets the hint.
4681 return failureHint ?? CONTEXT_WINDOW_FULL_ERROR;
4682 case "rapid_refill_breaker":
4683 return "Claude stopped: the context refilled too quickly after compaction.";
4684 case "prompt_too_long":
4685 return CONTEXT_WINDOW_FULL_ERROR;
4686 case "image_error":
4687 return "Claude stopped: an image in the conversation could not be processed.";
4688 case "model_error":
4689 return "Claude stopped: the model returned an error.";
4690 default:
4691 return undefined;
4692 }
4693 }
4694
4695 function isOverloadedResult(result: SDKResultMessage): boolean {
4696 return result.subtype === "success" && result.api_error_status === 529;
4697 }
4698
4699 function terminalStatusFromResult(
4700 message: SDKResultMessage,
4701 failureHint?: string,
4702 ): Extract<
4703 OrchestrationV2ProviderTurn["status"],
4704 "completed" | "interrupted" | "failed" | "cancelled"
4705 > {
4706 // Explicit abort reasons override success envelopes with is_error=false.
4707 if (
4708 message.terminal_reason === "aborted_tools" ||
4709 message.terminal_reason === "aborted_streaming"
4710 ) {
4711 return "interrupted";
4712 }
4713 if (message.subtype === "success") {
4714 // The SDK can report API failures as subtype "success" with is_error set.
4715 return isOverloadedResult(message) ||
4716 message.api_error_status === 429 ||
4717 terminalResultError(message.terminal_reason, failureHint) !== undefined ||
4718 (message.is_error && failureHint !== undefined)
4719 ? "failed"
4720 : "completed";
4721 }
4722 const errorText = message.errors.join("\n").toLowerCase();
4723 if (errorText.includes("interrupt")) {
4724 return "interrupted";
4725 }
4726 if (errorText.includes("cancel")) {
4727 return "cancelled";
4728 }
4729 return "failed";
4730 }
4731
4732 function isClaudeActiveSteeringAbortResult(message: SDKResultMessage): boolean {
4733 return (
4734 message.terminal_reason === "aborted_streaming" || message.terminal_reason === "aborted_tools"
4735 );
4736 }
4737
4738 function isClaudeProviderContinuationTurn(
4739 input: ProviderAdapter.ProviderAdapterV2TurnInput,
4740 ): boolean {
4741 return input.message.createdBy === "agent" && input.message.creationSource === "provider";
4742 }
4743
4744 function isClaudePromptEchoGatedFrame(message: SDKMessage): boolean {
4745 switch (message.type) {
4746 case "assistant":
4747 case "stream_event":
4748 case "user":
4749 return message.parent_tool_use_id === null;
4750 case "result":
4751 return true;
4752 default:
4753 return false;
4754 }
4755 }
4756
4757 function claudeFrameToolUseIds(message: SDKMessage): ReadonlyArray<string> {
4758 const ids: Array<string> = [];
4759 const parent = Reflect.get(message, "parent_tool_use_id");
4760 if (typeof parent === "string") {
4761 ids.push(parent);
4762 }
4763 if (message.type === "system") {
4764 const toolUseId = Reflect.get(message, "tool_use_id");
4765 if (typeof toolUseId === "string") {
4766 ids.push(toolUseId);
4767 }
4768 }
4769 return ids;
4770 }
4771
4772 function claudeEchoedPromptUuids(message: SDKMessage): ReadonlyArray<string> {
4773 const uuids = Reflect.get(message, "user_message_uuids");
4774 if (Array.isArray(uuids)) {
4775 return uuids.filter((uuid): uuid is string => typeof uuid === "string");
4776 }
4777 const uuid = Reflect.get(message, "user_message_uuid");
4778 return typeof uuid === "string" ? [uuid] : [];
4779 }
4780
4781 function claudePromptLifecycle(
4782 message: SDKMessage,
4783 ): { readonly uuid: string; readonly state: string } | null {
4784 const type: unknown = Reflect.get(message, "type");
4785 if (type !== "command_lifecycle") return null;
4786 const uuid: unknown = Reflect.get(message, "command_uuid");
4787 const state: unknown = Reflect.get(message, "state");
4788 return typeof uuid === "string" && typeof state === "string" ? { uuid, state } : null;
4789 }
4790
4791 // Without an echo, non-human origin proves a foreign turn only on CLIs known to echo prompts.
4792 function isClaudeResultForOtherTurn(input: {
4793 readonly message: SDKResultMessage;
4794 readonly promptUuid: string;
4795 readonly steerUuids: ReadonlySet<string>;
4796 readonly promptEchoMode: ClaudeLiveQueryContext["promptEchoMode"];
4797 }): boolean {
4798 const echoed = claudeEchoedPromptUuids(input.message);
4799 if (echoed.length > 0) {
4800 return !echoed.some((uuid) => uuid === input.promptUuid || input.steerUuids.has(uuid));
4801 }
4802 return (
4803 input.promptEchoMode !== "unknown" &&
4804 input.message.origin !== undefined &&
4805 input.message.origin.kind !== "human"
4806 );
4807 }
4808
4809 function isClaudeTaskNotificationOriginResult(message: SDKMessage): message is SDKResultMessage & {
4810 readonly origin: Extract<
4811 NonNullable<SDKResultMessage["origin"]>,
4812 { readonly kind: "task-notification" }
4813 >;
4814 } {
4815 return message.type === "result" && message.origin?.kind === "task-notification";
4816 }
4817
4818 // A session-task lifecycle result: it can precede a wake's real turn and ends no turn.
4819 function isClaudeEmptyTaskNotificationSuccess(message: SDKMessage): boolean {
4820 return (
4821 isClaudeTaskNotificationOriginResult(message) &&
4822 message.subtype === "success" &&
4823 !message.is_error &&
4824 message.num_turns === 0 &&
4825 message.result.length === 0 &&
4826 terminalStatusFromResult(message) === "completed"
4827 );
4828 }
4829
4830 // The CLI throttles unchanged rate_limit_event frames, but repeats this
4831 // undeclared payload on each blocked assistant response.
4832 const isClaudeBlockedAssistantRateLimit = Schema.is(
4833 Schema.Struct({
4834 api_error_params: Schema.Struct({
4835 rate_limit_info: Schema.Struct({
4836 status: Schema.Literal("rejected"),
4837 rateLimitType: Schema.optionalKey(Schema.Unknown),
4838 resetsAt: Schema.optionalKey(Schema.Unknown),
4839 overageStatus: Schema.optionalKey(Schema.String),
4840 isUsingOverage: Schema.optionalKey(Schema.Boolean),
4841 overageInUse: Schema.optionalKey(Schema.Boolean),
4842 }),
4843 }),
4844 }),
4845 );
4846
4847 function claudeUsageLimitResetAt(resetsAt: unknown): string | null {
4848 const resetMs = typeof resetsAt === "number" ? resetsAt * 1000 : NaN;
4849 return Number.isFinite(resetMs) && resetMs > 0 && resetMs < 8.64e15
4850 ? DateTime.formatIso(DateTime.makeUnsafe(resetMs))
4851 : null;
4852 }
4853
4854 function gatewayCooldownResetAt(
4855 cooldown: RegExpExecArray | null,
4856 completedAt: DateTime.Utc,
4857 ): string | undefined {
4858 if (cooldown === null) return undefined;
4859 const seconds =
4860 Number(cooldown[1] ?? 0) * 3_600 + Number(cooldown[2] ?? 0) * 60 + Number(cooldown[3] ?? 0);
4861 const resetMs = DateTime.toEpochMillis(completedAt) + seconds * 1_000;
4862 return seconds > 0 && resetMs < 8.64e15
4863 ? DateTime.formatIso(DateTime.makeUnsafe(resetMs))
4864 : undefined;
4865 }
4866
4867 const CLAUDE_UNSUPPORTED_VERSION_ERROR =
4868 /^API Error: 400 Claude Code (\d+\.\d+\.\d+) does not support this model; version (\d+\.\d+\.\d+) or newer is required\./;
4869
4870 /** The version a gateway sent in place of the session's own, when the session itself meets the requirement. */
4871 function claudeRewrittenVersion(
4872 message: SDKResultMessage,
4873 sessionVersion: string | undefined,
4874 ): string | undefined {
4875 if (message.subtype !== "success" || message.terminal_reason !== "api_error") return undefined;
4876 const [, reported, required] = CLAUDE_UNSUPPORTED_VERSION_ERROR.exec(message.result.trim()) ?? [];
4877 if (reported === undefined || required === undefined || sessionVersion === undefined) {
4878 return undefined;
4879 }
4880 return compareSemverVersions(reported, sessionVersion) < 0 &&
4881 compareSemverVersions(sessionVersion, required) >= 0
4882 ? reported
4883 : undefined;
4884 }
4885
4886 function providerFailureFromResult(
4887 message: SDKResultMessage,
4888 receivedAt: DateTime.Utc,
4889 failureHint?: string,
4890 usageLimited = false,
4891 ): OrchestrationV2ProviderFailure | null {
4892 const gatewayResetAt =
4893 failureHint === undefined &&
4894 message.subtype === "success" &&
4895 message.is_error &&
4896 message.terminal_reason === "api_error" &&
4897 message.api_error_status === 503
4898 ? gatewayCooldownResetAt(
4899 /^API Error: 503 \[[^\]\r\n]+\] \[429\]: \{"type":"error","error":\{"type":"rate_limit_error",[^\r\n]*\} \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec(
4900 message.result,
4901 ),
4902 receivedAt,
4903 )
4904 : undefined;
4905 if (gatewayResetAt !== undefined) {
4906 return makeProviderFailure({
4907 class: "usage_limit",
4908 message: "Claude API rate limit reached. Try again later.",
4909 code: "api_error_429",
4910 retryable: true,
4911 resetAt: gatewayResetAt,
4912 });
4913 }
4914 const failureClass =
4915 (message.subtype === "success" && message.api_error_status === 429) || usageLimited
4916 ? "usage_limit"
4917 : "provider_error";
4918 const listedError = resultUserFacingError(message);
4919 const apiErrorMessage =
4920 message.subtype === "success" &&
4921 message.terminal_reason === "api_error" &&
4922 message.result.trim().startsWith("API Error:")
4923 ? makeProviderFailure({ message: message.result }).message.slice(0, 500)
4924 : undefined;
4925 const structuredError = isOverloadedResult(message)
4926 ? "Claude API is overloaded (529). Try again shortly."
4927 : message.subtype === "success" && message.api_error_status === 429
4928 ? "Claude API rate limit reached. Try again later."
4929 : terminalResultError(message.terminal_reason, failureHint ?? apiErrorMessage);
4930 if (message.subtype !== "success") {
4931 return makeProviderFailure({
4932 message: listedError ?? structuredError ?? message.errors.join("\n"),
4933 code: message.subtype,
4934 class: failureClass,
4935 });
4936 }
4937 if (!message.is_error && structuredError === undefined) {
4938 return null;
4939 }
4940 const apiErrorStatus = message.api_error_status ?? null;
4941 // API-key sessions get no rate_limit_info, so a gateway's 429 carries its reset only as text.
4942 const resetAt =
4943 apiErrorStatus === 429 && message.result.startsWith("API Error:")
4944 ? gatewayCooldownResetAt(
4945 // CLIProxyAPI nests upstream errors in its message; only its own cooldown counts.
4946 message.result.startsWith(
4947 "API Error: Request rejected (429) · All credentials for model ",
4948 )
4949 ? (/^API Error: Request rejected \(429\) · All credentials for model [^\s()]+ are cooling down \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec(
4950 message.result,
4951 ) ??
4952 /^API Error: Request rejected \(429\) · All credentials for model [^\s()]+ are cooling down \(last error: [\s\S]*\) \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)$/.exec(
4953 message.result,
4954 ))
4955 : /\(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec(message.result),
4956 receivedAt,
4957 )
4958 : undefined;
4959 return makeProviderFailure({
4960 message: listedError ?? structuredError ?? failureHint ?? message.result,
4961 code:
4962 apiErrorStatus === null
4963 ? (message.terminal_reason ?? "sdk_result_error")
4964 : `api_error_${apiErrorStatus}`,
4965 class: failureClass,
4966 retryable: apiErrorStatus === 429 || apiErrorStatus === 529 ? true : null,
4967 resetAt: resetAt ?? null,
4968 });
4969 }
4970
4971 function providerFailureFromApiRetry(message: SDKAPIRetryMessage): OrchestrationV2ProviderFailure {
4972 const errorName = message.error.replaceAll("_", " ");
4973 return makeProviderFailure({
4974 message: `Claude API ${errorName}.`,
4975 code:
4976 message.error_status === null
4977 ? message.error
4978 : `api_error_${Math.trunc(message.error_status)}`,
4979 class:
4980 message.error_status === 429
4981 ? "usage_limit"
4982 : message.error_status === null
4983 ? "transport_error"
4984 : "provider_error",
4985 retryable: true,
4986 });
4987 }
4988
4989 function buildAssistantArtifacts(input: {
4990 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
4991 readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;
4992 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
4993 readonly nativeItemId: string;
4994 readonly text: string;
4995 readonly ordinal: number;
4996 readonly status?: "running" | "completed" | "interrupted";
4997 readonly startedAt: DateTime.Utc;
4998 readonly completedAt: DateTime.Utc;
4999 // A streamed message keeps its first timestamp across updates.
5000 readonly createdAt?: DateTime.Utc;
Showing first 5,000 of 15,104 lines. View raw