import * as DocumentText from "../../provider/DocumentText.ts";
import {
compactDynamicToolOutput,
mcpToolResultOutput,
toolOutputImages,
} from "@t3tools/shared/toolOutput";
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
import {
dynamicToolTitle,
formatReadToolLabel,
formatSearchToolLabel,
} from "@t3tools/shared/toolActivity";
import { field, text } from "../unknownField.ts";
import { mergeWorkflowAgentMetadata, type WorkflowAgentMetadata } from "../workflowAgentAnswers.ts";
import {
initialWorkflowAgentTranscriptCursor,
readWorkflowAgentTranscript,
type WorkflowAgentTranscriptCursor,
} from "../workflowAgentTranscript.ts";
import {
CLAUDE_WORKFLOW_TASK_TYPE,
hasClaudeWorkflowSnapshot,
mergeClaudeWorkflowProgress,
parseClaudeWorkflowRunHandles,
} from "./claudeWorkflowProgress.ts";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
import {
addClaudeLedgerUsage,
claudeLedgerDelta,
claudeModelLedger,
claudeReportedContextWindows,
normalizeClaudeTurnTokenUsage,
type ClaudeLedgerUsage,
type ClaudeModelLedger,
} from "../../provider/ClaudeTurnTokenUsage.ts";
import { toMcpElicitationResponse } from "../../provider/CodexMcpElicitation.ts";
import {
type CanUseTool,
type ElicitationRequest,
type ElicitationResult,
forkSession as forkClaudeSession,
type EffortLevel,
type ForkSessionOptions,
type ForkSessionResult,
getSessionMessages,
getSubagentMessages,
type HookCallback,
type McpServerStatus as ClaudeMcpServerStatus,
query,
resolveSettings as resolveClaudeSettings,
type Options as ClaudeQueryOptions,
type PermissionMode,
type PermissionResult,
type PermissionUpdate,
type Query as ClaudeQuery,
type Settings as ClaudeSdkSettings,
type SpawnOptions as ClaudeSpawnOptions,
type SpawnedProcess as ClaudeSpawnedProcess,
type SDKAssistantMessage,
type SDKAPIRetryMessage,
type SDKMessage,
type SDKRateLimitInfo,
type SDKResultMessage,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import type {
AskUserQuestionInput,
WebSearchOutput,
} from "@anthropic-ai/claude-agent-sdk/sdk-tools";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI.
import * as NodeChildProcess from "node:child_process";
import * as NodeUtil from "node:util";
import { parseCliArgs } from "@t3tools/shared/cliArgs";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import {
claudeMcpToolName,
claudeMcpToolNamePart,
claudeMcpToolPrefix,
MCP_APP_OUTPUT_KEY,
mcpAppToolResourceUri,
} from "@t3tools/shared/mcpApp";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import {
CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
formatClaudeResumeCompactionQuestion,
} from "@t3tools/shared/claudeCompaction";
import {
type ChatAttachment,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
ClaudeSettings,
TrimmedNonEmptyString,
defaultInstanceIdForDriver,
isCompactionCommandMessage,
type ModelSelection,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
OrchestrationV2ProviderGoal,
type OrchestrationV2PlanArtifact,
type OrchestrationV2PlanStep,
type OrchestrationV2PendingBackgroundTask,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2UserInputQuestion,
type OrchestrationV2Subagent,
type OrchestrationV2AppThread,
type OrchestrationV2SubagentWorkflow,
type OrchestrationV2WorkflowRunHandles,
type OrchestrationV2TurnItem,
type OrchestrationV2WebSearchResult,
type ProviderApprovalDecision,
type ProviderApprovalFullAccessOverride,
type ProviderApprovalOption,
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderUserInputAnswers,
type ProviderThreadId,
type RunId,
type ThreadId,
resolveIdleCompaction,
} from "@t3tools/contracts";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
import * as Predicate from "effect/Predicate";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
import {
planClaudeSkillDispatch,
type ClaudeSkillTarget,
} from "../../provider/Drivers/ClaudeSkillDispatch.ts";
import {
claudeLaunchArgDirectories,
discoverClaudeSkills,
} from "../../provider/Drivers/ClaudeSkills.ts";
import {
compileClaudeModelSelection,
type CompiledClaudeModelSelection,
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
import {
claudeSignedOutMessage,
makeClaudeEnvironment,
mergeClaudeProcessEnvironment,
resolveClaudeHomePath,
} from "../../provider/Drivers/ClaudeHome.ts";
import {
BUNDLED_CLAUDE_MODEL_CATALOG,
resolveClaudeCatalogContextWindowTokens,
type ClaudeModelCatalog,
getClaudeCatalogModelCapabilities,
resolveClaudeModelSlug,
scopeClaudeModelCatalog,
} from "../../provider/ClaudeModelCatalog.ts";
import {
boundProviderEventForLogging,
shouldPersistProviderEvent,
} from "../../provider/EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
claudeRateLimitEventToUpdate,
type ClaudeScopedLimitNames,
} from "../../provider/claudeUsageLimits.ts";
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
import {
T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
T3_CODE_ORCHESTRATION_INSTRUCTIONS,
} from "@t3tools/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import {
mcpToolPresentation,
normalizeMcpText,
} from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import {
makeProviderFailure,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriverCreateInput,
} from "@t3tools/provider-core/server/adapterDriver";
import {
type BackgroundWorkReport,
backgroundWorkNotification,
} from "@t3tools/provider-core/server/notification";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent");
const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const;
interface ClaudeCacheCreation {
readonly ephemeral_1h_input_tokens: number;
readonly ephemeral_5m_input_tokens: number;
}
function claudePromptCacheTtlMs(
cacheCreation: ClaudeCacheCreation | null | undefined,
): number | undefined {
if (!cacheCreation) return undefined;
if (cacheCreation.ephemeral_1h_input_tokens > 0) return 60 * 60_000;
if (cacheCreation.ephemeral_5m_input_tokens > 0) return 5 * 60_000;
return undefined;
}
// Claude caps the window at the model's context, so a setting at or above it never applies.
// Below that, Claude compacts 33,000 tokens short of the window: Claude Code 2.1.305's
// getContextUsage reports a 150,000 window as a 117,000 threshold, for every catalog model.
const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000;
function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number | null) {
const windowTokens = Number(autoCompactWindow);
return windowTokens > 0 && (maxTokens === null || windowTokens < maxTokens)
? { autoCompactThreshold: windowTokens - CLAUDE_AUTO_COMPACT_RESERVE_TOKENS }
: {};
}
function claudeMessageInputTokens(usage: {
readonly input_tokens: number;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
}): number {
return (
usage.input_tokens +
(usage.cache_creation_input_tokens ?? 0) +
(usage.cache_read_input_tokens ?? 0)
);
}
export function claudeProviderTurnTokenUsage(
usage: {
readonly input_tokens: number;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
readonly cache_creation?: ClaudeCacheCreation | null;
readonly output_tokens: number;
},
maxTokens: number | null,
updatedAt: string,
autoCompactWindow = "",
requestedAt?: DateTime.Utc,
) {
const inputTokens = claudeMessageInputTokens(usage);
const outputTokens = usage.output_tokens;
const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation);
// The cache lifetime starts with the request, not when its response ends.
const promptCacheExpiresAt =
promptCacheTtlMs === undefined || requestedAt === undefined
? undefined
: DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs }));
return {
usedTokens: inputTokens + outputTokens,
maxTokens,
inputTokens,
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
outputTokens,
reasoningOutputTokens: 0,
...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }),
...claudeAutoCompactThreshold(autoCompactWindow, maxTokens),
...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }),
updatedAt,
};
}
type ClaudeMessageUsage = Parameters<typeof claudeProviderTurnTokenUsage>[0];
// message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them.
function mergeClaudeStreamUsage(
current: ClaudeMessageUsage,
delta: {
readonly input_tokens?: number | null;
readonly cache_creation_input_tokens?: number | null;
readonly cache_read_input_tokens?: number | null;
readonly output_tokens: number;
},
): ClaudeMessageUsage {
return {
...current,
input_tokens: delta.input_tokens ?? current.input_tokens,
cache_creation_input_tokens:
delta.cache_creation_input_tokens ?? current.cache_creation_input_tokens ?? null,
cache_read_input_tokens:
delta.cache_read_input_tokens ?? current.cache_read_input_tokens ?? null,
output_tokens: delta.output_tokens,
};
}
export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER);
const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
// The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server.
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
// Claude can consume a subagent result before the launching turn ends, leaving
// its notification with no native wake turn to answer the continuation.
const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
// Claude Code flushes transcript writes every 100 ms, so a workflow member's
// reply can land after the progress frame that settles it. Its transcript
// stays the source of its answer this long after it settles.
const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
// A steer waits at most this long, from its request, for its foreground
// subagents to move to the background before it is sent.
const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
// How long a Stop waits for the CLI to exit before the user is offered Force stop.
const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
// Matches the stderr tail the SDK keeps for a CLI it spawns itself.
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
// The process group is killed on exit, so its stderr closes promptly.
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
const CLAUDE_ROOT_REFUSAL =
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
const CLAUDE_GROUP_WATCH_SCRIPT = [
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
'exec "$@" 3<&-',
].join("\n");
/**
* Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for
* setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on
* EOF from a pipe only this server holds, including when the server crashes.
*/
export function spawnClaudeProcessGroup(
options: ClaudeSpawnOptions,
onExit?: () => void,
onStderr: (text: string) => void = () => {},
onStderrClose: () => void = () => {},
): ClaudeSpawnedProcess {
const child = NodeChildProcess.spawn(
"/bin/sh",
["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
{
cwd: options.cwd,
env: options.env,
signal: options.signal,
stdio: ["pipe", "pipe", "pipe", "pipe"],
detached: true,
},
);
// Always drained, so a chatty CLI never blocks on a full stderr pipe.
child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose);
child.once("exit", () => {
try {
signalProcessGroup(child.pid ?? 0, "SIGKILL");
} catch {}
onExit?.();
});
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
return child as ClaudeSpawnedProcess;
}
export const ClaudeProviderCapabilitiesV2 = {
sessions: {
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: false,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: false,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
activeSteeringInterruptsTools: true,
supportsSteeringByInterruptRestart: false,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: false,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: false,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: false,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: true,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: false,
emitsSubagentLifecycle: true,
canWaitForSubagents: false,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: true,
acceptsDeveloperContext: true,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: false,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
runtimePolicy: {
enforcement: "native",
},
} satisfies OrchestrationV2ProviderCapabilities;
const CLAUDE_CODE_PRESET_TOOLS = {
type: "preset",
preset: "claude_code",
} satisfies NonNullable<ClaudeQueryOptions["tools"]>;
export type ClaudeAgentSdkQueryToolList = ReadonlyArray<string>;
export interface ClaudeAgentSdkQueryPresetTools {
readonly type: "preset";
readonly preset: "claude_code";
}
export type ClaudeAgentSdkQueryTools = ClaudeAgentSdkQueryToolList | ClaudeAgentSdkQueryPresetTools;
export const CLAUDE_READ_ONLY_ALLOWED_TOOLS = ["Read", "Glob", "Grep"] as const;
function claudeAgentSdkQueryToolsForSdk(
tools: ClaudeAgentSdkQueryTools,
): NonNullable<ClaudeQueryOptions["tools"]> {
if (isClaudeAgentSdkQueryToolList(tools)) {
return [...tools];
}
return { type: tools.type, preset: tools.preset };
}
function isClaudeAgentSdkQueryToolList(
tools: ClaudeAgentSdkQueryTools,
): tools is ClaudeAgentSdkQueryToolList {
return Array.isArray(tools);
}
type ClaudeAgentSdkThreadIdentity =
| {
readonly sessionId: string;
readonly resume?: never;
}
| {
readonly sessionId?: never;
readonly resume: string;
};
export type ClaudeAgentSdkQueryOptions = Omit<
ClaudeQueryOptions,
"maxTurns" | "model" | "permissionMode" | "resume" | "sessionId" | "tools"
> & {
readonly model: string;
readonly tools: NonNullable<ClaudeQueryOptions["tools"]>;
readonly permissionMode: NonNullable<ClaudeQueryOptions["permissionMode"]>;
} & ClaudeAgentSdkThreadIdentity;
export interface ClaudeAgentSdkQueryOpenInput {
readonly options: ClaudeAgentSdkQueryOptions;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
export interface ClaudeAgentSdkQuerySession {
readonly messages: Stream.Stream<SDKMessage, ClaudeAgentSdkQueryRunnerError>;
readonly offer: (
message: SDKUserMessage,
onQueued?: () => void,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly setModel: (model: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly applyFlagSettings: (
settings: ClaudeFlagSettings,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly setPermissionMode: (
mode: PermissionMode,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly stopTask: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly backgroundTasks: (
toolUseId: string,
) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
readonly mcpServerStatus: Effect.Effect<
ReadonlyArray<ClaudeMcpServerStatus>,
ClaudeAgentSdkQueryRunnerError
>;
readonly readMcpResource: (input: {
readonly server: string;
readonly uri: string;
}) => Effect.Effect<
{ readonly contents: ReadonlyArray<unknown> },
ClaudeAgentSdkQueryRunnerError
>;
/** Runs an MCP tool without a model turn and returns the server's raw `CallToolResult`. */
readonly callMcpTool: (input: {
readonly tool: string;
readonly arguments: Record<string, unknown>;
}) => Effect.Effect<unknown, ClaudeAgentSdkQueryRunnerError>;
readonly listPermissionRules: Effect.Effect<
ReadonlyArray<ClaudePermissionRule>,
ClaudeAgentSdkQueryRunnerError
>;
readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
}
type ClaudeQueryStreamExit = Exit.Exit<void, ClaudeAgentSdkQueryRunnerError>;
export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAgentSdkQueryRunnerError>()(
"ClaudeAgentSdkQueryRunnerError",
{
method: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Claude Agent SDK query failed.";
}
}
export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRootRefusalError>()(
"ClaudeCodeRootRefusalError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Claude Code exited before it started: ${CLAUDE_ROOT_REFUSAL}`;
}
}
class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
"ClaudeMcpRegistrationTimeoutError",
{},
) {
override get message(): string {
return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
}
}
export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError<ClaudeBackgroundWorkBlocksQueryReplacementError>()(
"ClaudeBackgroundWorkBlocksQueryReplacementError",
{},
) {
override get message(): string {
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.";
}
}
export class ClaudeAppendSystemPromptFileError extends Schema.TaggedError<ClaudeAppendSystemPromptFileError>()(
"ClaudeAppendSystemPromptFileError",
{
path: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
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.`;
}
}
export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedError<ClaudeAppendSystemPromptMissingValueError>()(
"ClaudeAppendSystemPromptMissingValueError",
{ flag: Schema.Literals(["--append-system-prompt", "--append-system-prompt-file"]) },
) {
override get message(): string {
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.`;
}
}
export class ClaudeSettingsLaunchArgError extends Schema.TaggedError<ClaudeSettingsLaunchArgError>()(
"ClaudeSettingsLaunchArgError",
{
path: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
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.`;
}
}
export interface ClaudeAgentSdkQueryRunnerShape {
readonly allocateSessionId: Effect.Effect<string, ClaudeAgentSdkQueryRunnerError>;
readonly open: (
input: ClaudeAgentSdkQueryOpenInput,
) => Effect.Effect<ClaudeAgentSdkQuerySession, ClaudeAgentSdkQueryRunnerError>;
readonly forkSession: (
input: ClaudeAgentSdkSessionForkInput,
) => Effect.Effect<
ForkSessionResult & { readonly headMessageId?: string },
ClaudeAgentSdkQueryRunnerError
>;
readonly subagentLaunchToolUseId: (
input: ClaudeAgentSdkSubagentLookupInput,
) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
readonly assertComplete: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
}
export class ClaudeAgentSdkQueryRunner extends Context.Service<
ClaudeAgentSdkQueryRunner,
ClaudeAgentSdkQueryRunnerShape
>()("t3/orchestration-v2/Adapters/ClaudeAdapterV2/ClaudeAgentSdkQueryRunner") {}
export interface ClaudeAgentSdkSessionForkInput {
readonly sessionId: string;
readonly options: ForkSessionOptions;
readonly environment: NodeJS.ProcessEnv;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
export interface ClaudeAgentSdkSubagentLookupInput {
readonly sessionId: string;
readonly agentId: string;
readonly dir: string | null;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError);
const isProviderAdapterRuntimeRequestResponseError = Schema.is(
ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
);
const isProviderAdapterRollbackThreadError = Schema.is(
ProviderAdapter.ProviderAdapterRollbackThreadError,
);
function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRunnerError {
return isClaudeAgentSdkQueryRunnerError(cause)
? cause
: new ClaudeAgentSdkQueryRunnerError({ cause, method });
}
function closeClaudeQuery(queryRuntime: ClaudeQuery) {
return Effect.try({
try: () => queryRuntime.close(),
catch: (cause) => queryRunnerError(cause, "close"),
});
}
// 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.
async function sendClaudeControlRequest(
queryRuntime: ClaudeQuery,
request: {
readonly subtype: "mcp_call" | "list_permission_rules";
readonly [key: string]: unknown;
},
): Promise<unknown> {
const send: unknown = Reflect.get(queryRuntime, "request");
if (typeof send !== "function") {
throw new Error(`This Claude Agent SDK cannot send ${request.subtype}.`);
}
const reply: unknown = await Reflect.apply(send, queryRuntime, [request]);
return Predicate.isObject(reply) ? reply.response : undefined;
}
const ClaudePermissionRules = Schema.Struct({
state: Schema.Struct({
rules: Schema.Array(
Schema.Struct({
behavior: Schema.Literals(["allow", "deny", "ask"]),
rule: Schema.String,
notInEffect: Schema.optional(Schema.Boolean),
}),
),
errors: Schema.optional(Schema.Array(Schema.Unknown)),
}),
});
export type ClaudePermissionRule = (typeof ClaudePermissionRules.Type)["state"]["rules"][number];
const decodeClaudePermissionRules = Schema.decodeUnknownEffect(ClaudePermissionRules);
// Without these, tools carry no `_meta.ui` and a model-shaped result would reach the app.
const CLAUDE_MCP_APP_CAPABILITIES = [
"mcp_tool_ui_meta_v1",
"mcp_read_resource_v1",
"mcp_call_result_not_for_model_v1",
] as const;
// Captured inline, unlike Codex's shared app-server: a slow read delays only this session's stream, and only this long.
const CLAUDE_MCP_APP_CAPTURE_TIMEOUT = "20 seconds";
function claudeSupportsMcpApps(capabilities: ReadonlySet<string>): boolean {
return CLAUDE_MCP_APP_CAPABILITIES.every((capability) => capabilities.has(capability));
}
// Claude Code routes `mcp__a__b__tool` to server `a` even when `a__b` is connected, so either prefix is ambiguous.
function claudeMcpServerPrefixOverlaps(
statuses: ReadonlyArray<ClaudeMcpServerStatus>,
server: string,
): boolean {
const prefix = claudeMcpToolPrefix(server);
return statuses.some((status) => {
if (status.name === server) return false;
const other = claudeMcpToolPrefix(status.name);
return other.startsWith(prefix) || prefix.startsWith(other);
});
}
function findClaudeMcpTool(
statuses: ReadonlyArray<ClaudeMcpServerStatus>,
toolName: string,
):
| { readonly server: string; readonly tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number] }
| undefined {
const matches = statuses.flatMap((status) => {
if (status.status !== "connected") return [];
const prefix = claudeMcpToolPrefix(status.name);
if (!toolName.startsWith(prefix)) return [];
return (status.tools ?? [])
.filter((tool) => `${prefix}${claudeMcpToolNamePart(tool.name)}` === toolName)
.map((tool) => ({ server: status.name, tool }));
});
const [match, ...others] = matches;
return match === undefined ||
others.length > 0 ||
claudeMcpServerPrefixOverlaps(statuses, match.server)
? undefined
: match;
}
// Only this adapter writes app references. Claude's normalised tool names cannot tie one in raw MCP output to its server.
function withoutForgedMcpApp(output: ClaudeNativeToolOutput): ClaudeNativeToolOutput {
const value = claudeNativeToolOutputValue(output);
return compactDynamicToolOutput(value)?.[MCP_APP_OUTPUT_KEY] === undefined
? output
: { type: "structured_tool_use_result", value: { result: value } };
}
/**
* Deliberately broader than Claude's matcher: Claude also matches rules against server aliases T3
* can't list, and an alias may contain `__`, so any `mcp__` rule or wildcard may cover any MCP tool.
* A false match only refuses a card's call, or asks first.
*/
function claudeRulesMayCoverMcpTools(
rules: ReadonlyArray<ClaudePermissionRule>,
behaviors: ReadonlyArray<ClaudePermissionRule["behavior"]>,
): boolean {
return rules.some((entry) => {
const name = entry.rule.split("(", 1)[0] ?? entry.rule;
return (
behaviors.includes(entry.behavior) &&
entry.notInEffect !== true &&
(name.startsWith("mcp__") || name.includes("*"))
);
});
}
/**
* Claude reports `annotations` as `readOnly`/`destructive`/`openWorld`; apps expect MCP's `*Hint` names.
* Card calls skip Claude's permission check, so `readOnlyHint`, which skips T3's prompt, needs readable
* rules (null when not) with no ask or deny rule that may cover the tool.
*/
function claudeMcpToolForApps(
tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number],
rules: ReadonlyArray<ClaudePermissionRule> | null,
) {
const annotations = tool.annotations ?? {};
const readOnlyHint =
annotations.readOnly !== true ||
(rules !== null && !claudeRulesMayCoverMcpTools(rules, ["ask", "deny"]))
? annotations.readOnly
: undefined;
return {
name: tool.name,
...(tool.description === undefined ? {} : { description: tool.description }),
// The CLI reports no input schemas; apps require one in `hostContext.toolInfo.tool`.
inputSchema: { type: "object" },
...(tool._meta === undefined ? {} : { _meta: tool._meta }),
annotations: {
...(readOnlyHint === undefined ? {} : { readOnlyHint }),
...(annotations.destructive === undefined
? {}
: { destructiveHint: annotations.destructive }),
...(annotations.openWorld === undefined ? {} : { openWorldHint: annotations.openWorld }),
},
};
}
/** A model-turn MCP `tool_use_result` flattens text `content` to a string; app calls return MCP's raw `CallToolResult`. */
function claudeMcpCallToolResult(
value: unknown,
): ProviderAdapter.ProviderAdapterV2McpCallToolResult {
const record = Predicate.isObject(value) && !Array.isArray(value) ? value : undefined;
const content = record === undefined ? value : record.content;
return {
content:
typeof content === "string"
? [{ type: "text", text: content }]
: Array.isArray(content)
? content
: [],
...(record?.structuredContent === undefined
? {}
: { structuredContent: record.structuredContent }),
...(record?.isError === true ? { isError: true } : {}),
...(record?._meta === undefined ? {} : { _meta: record._meta }),
};
}
// Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption.
export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {
return { [Symbol.asyncIterator]: () => queryRuntime };
}
export interface ClaudeAgentSdkLoggedQueryOptions {
readonly model: ClaudeAgentSdkQueryOptions["model"];
readonly tools: ClaudeAgentSdkQueryOptions["tools"];
readonly permissionMode: ClaudeAgentSdkQueryOptions["permissionMode"];
readonly sessionId?: string;
readonly resume?: string;
readonly resumeSessionAt?: ClaudeAgentSdkQueryOptions["resumeSessionAt"];
readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
readonly settingKeys?: ReadonlyArray<string>;
readonly effort?: ClaudeAgentSdkQueryOptions["effort"];
readonly includePartialMessages?: true;
readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"];
readonly hasExtraArgs?: true;
readonly allowDangerouslySkipPermissions?: true;
readonly hasCanUseTool?: true;
readonly hasEnvironment?: true;
readonly hasMcpServers?: true;
}
export type ClaudeAgentSdkProtocolLogEvent =
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.open";
readonly options: ClaudeAgentSdkLoggedQueryOptions;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "prompt.offer";
readonly message: SDKUserMessage;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.set_model";
readonly model: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.apply_flag_settings";
readonly settings: ClaudeFlagSettings;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.set_permission_mode";
readonly mode: PermissionMode;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.stop_task";
readonly taskId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.background_tasks";
readonly toolUseId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.interrupt";
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.close";
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "session.fork";
readonly sessionId: string;
readonly options: ForkSessionOptions;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: {
readonly type: "session.forked";
readonly sessionId: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "subagent.lookup";
readonly sessionId: string;
readonly agentId: string;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: {
readonly type: "subagent.found";
readonly toolUseId: string | null;
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: SDKMessage;
};
export type ClaudeAgentSdkProtocolLogger = (
event: ClaudeAgentSdkProtocolLogEvent,
) => Effect.Effect<void>;
export function loggedClaudeQueryOptions(
options: ClaudeAgentSdkQueryOptions,
): ClaudeAgentSdkLoggedQueryOptions {
return {
model: options.model,
tools: options.tools,
permissionMode: options.permissionMode,
...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
...(options.resume === undefined ? {} : { resume: options.resume }),
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
// Settings can carry the user's --settings values, such as an env block with credentials.
...(typeof options.settings === "object" && options.settings !== null
? { settingKeys: Object.keys(options.settings) }
: {}),
...(options.effort === undefined ? {} : { effort: options.effort }),
...(options.includePartialMessages === true ? { includePartialMessages: true } : {}),
...(options.pathToClaudeCodeExecutable === undefined
? {}
: { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }),
...(options.extraArgs === undefined ? {} : { hasExtraArgs: true }),
...(options.allowDangerouslySkipPermissions === true
? { allowDangerouslySkipPermissions: true }
: {}),
...(options.canUseTool === undefined ? {} : { hasCanUseTool: true }),
...(options.env === undefined ? {} : { hasEnvironment: true }),
...(options.mcpServers === undefined ? {} : { hasMcpServers: true }),
};
}
function makeClaudeAgentSdkProtocolLogger(input: {
readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}): ClaudeAgentSdkProtocolLogger | undefined {
const { nativeEventLogger } = input;
if (nativeEventLogger === undefined) {
return undefined;
}
return (event) => {
if (!shouldPersistProviderEvent("native", event)) return Effect.void;
return nativeEventLogger
.write(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
kind: "protocol",
providerSessionId: input.providerSessionId,
event: boundProviderEventForLogging(event),
},
input.threadId,
)
.pipe(Effect.ignore);
};
}
const encodeClaudeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
),
);
const claudeConfigDirOf = (
path: Path.Path,
environment: NodeJS.ProcessEnv,
homeDirectory: string,
) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude"));
// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
// worker so concurrent providers keep the server's environment.
const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
readonly method: "forkSession";
readonly sessionId: string;
readonly options?: ForkSessionOptions;
readonly environment: NodeJS.ProcessEnv;
}) {
const path = yield* Path.Path;
const fromSource = import.meta.url.endsWith(".ts");
// A single executable hosts the worker itself; it has no sibling script.
const workerArguments = (yield* HostProcess.IsExecutable)
? ["__claude-history"]
: [
...(fromSource ? ["--experimental-strip-types"] : []),
yield* path.fromFileUrl(
new URL(
fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs",
import.meta.url,
),
),
];
const executablePath = yield* HostProcess.ExecutablePath;
const result = yield* spawnAndCollect(
executablePath,
ChildProcess.make(
executablePath,
[...workerArguments, input.method, input.sessionId, encodeClaudeJson(input.options ?? {})],
{
env: {
...input.environment,
ELECTRON_RUN_AS_NODE: "1",
},
},
),
).pipe(Effect.timeout("30 seconds"));
if (result.code !== 0) {
return yield* new ClaudeAgentSdkQueryRunnerError({
method: input.method,
cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
});
}
return result.stdout;
});
const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
input: ClaudeAgentSdkSessionForkInput,
) {
return yield* runClaudeWorker({ ...input, method: "forkSession" }).pipe(
Effect.flatMap(decodeClaudeHistoryFork),
);
});
export const layerQueryRunner: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
| ChildProcessSpawner.ChildProcessSpawner
| SecureRandom.SecureRandom
| Path.Path
| PortScanner.PortDiscovery
| ProviderEventLoggers.ProviderEventLoggers
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const random = yield* SecureRandom.SecureRandom;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const hostEnvironment = yield* HostProcess.Environment;
const portDiscovery = yield* PortScanner.PortDiscovery;
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: random.uuidV4(),
open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(
function* (input: ClaudeAgentSdkQueryOpenInput) {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
providerSessionId: input.providerSessionId,
});
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
protocolLogger === undefined ? Effect.void : protocolLogger(event);
// A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
const prompt = Stream.fromQueue(promptQueue).pipe(
Stream.catchCause((cause) =>
Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
),
Stream.toAsyncIterable,
);
// Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
const { mcpServers, ...sdkOptions } = input.options;
// Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
const queryOptions = {
...sdkOptions,
env: {
...(sdkOptions.env ?? hostEnvironment),
[PortScanner.AGENT_THREAD_ENV]: input.threadId,
},
};
// The SDK can prepend a scope wrapper to native binaries; script entries run through node.
const binaryPath = queryOptions.pathToClaudeCodeExecutable;
const launch =
binaryPath === undefined ||
CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
? undefined
: yield* agentScope.wrap({
command: binaryPath,
args: [],
name: "claude",
threadId: input.threadId,
env: queryOptions.env,
});
const options =
launch === undefined || launch.args.length === 0
? queryOptions
: {
...queryOptions,
pathToClaudeCodeExecutable: launch.command,
executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
};
const unit = launch?.unit;
const stopScope =
unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
// Only a CLI that fails before its first message explains itself on
// stderr. The known root refusal becomes a curated failure; any other
// stderr can hold private text, so it stays out of turn failures.
let stderrTail = "";
let stderrClosed: Promise<void> = Promise.resolve();
let answered = false;
const appendStderr = (text: string) => {
if (answered) return;
stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
};
const spawnProcess =
options.spawnClaudeCodeProcess ??
((spawnOptions: ClaudeSpawnOptions) => {
if (platform !== "win32") {
// Node can report "exit" before it has read the stderr the CLI wrote.
let stderrDone = () => {};
stderrClosed = new Promise((resolve) => (stderrDone = resolve));
return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone);
}
const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
cwd: spawnOptions.cwd,
env: spawnOptions.env,
signal: spawnOptions.signal,
windowsHide: true,
stdio: ["pipe", "pipe", "pipe"],
});
child.stderr
.setEncoding("utf8")
.on("data", (chunk: string) => options.stderr?.(chunk));
return child;
});
let spawnedProcess: ClaudeSpawnedProcess | undefined;
let processExited = false;
let processExit: Promise<void> | undefined;
const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
const child = spawnProcess(spawnOptions);
spawnedProcess = child;
// A spawn that fails emits only "error".
const releaseAgent = portDiscovery.trackAgent();
child.once("exit", releaseAgent);
child.on("error", releaseAgent);
processExited = child.exitCode !== null || child.signalCode != null;
processExit = new Promise<void>((resolve) => {
if (processExited) resolve();
else
child.once("exit", () => {
processExited = true;
resolve();
});
});
return child;
};
const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
Effect.try({
try: () =>
query({
prompt,
options: { ...options, spawnClaudeCodeProcess },
}),
catch: (cause) => queryRunnerError(cause, "query"),
}).pipe(
Effect.tap((queryRuntime) =>
restore(
Effect.gen(function* () {
if (mcpServers !== undefined) {
// Errors and mcp_status can echo headers; log only server names.
const failed = yield* Effect.tryPromise({
try: () => queryRuntime.setMcpServers(mcpServers),
catch: (cause) => queryRunnerError(cause, "setMcpServers"),
}).pipe(
Effect.map((result) => Object.keys(result.errors)),
Effect.orElseSucceed(() => Object.keys(mcpServers)),
Effect.timeoutOrElse({
duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
orElse: () =>
Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
threadId: input.threadId,
providerSessionId: input.providerSessionId,
}).pipe(
Effect.andThen(
Effect.fail(
queryRunnerError(
new ClaudeMcpRegistrationTimeoutError(),
"setMcpServers",
),
),
),
),
}),
);
if (failed.length > 0) {
yield* Effect.logWarning(
"orchestration-v2.claude-mcp-servers-unavailable",
{
threadId: input.threadId,
servers: failed,
},
);
}
}
yield* logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.open",
options: loggedClaudeQueryOptions(input.options),
},
});
}),
).pipe(
Effect.onError(() =>
Queue.shutdown(promptQueue).pipe(
// SDK disposal can return before process exit; await the owned child's exit before retrying.
Effect.andThen(
Effect.tryPromise({
try: async () => {
if (spawnedProcess !== undefined && !processExited) {
spawnedProcess.kill("SIGKILL");
}
await processExit;
},
catch: (cause) => queryRunnerError(cause, "close"),
}).pipe(Effect.timeout("10 seconds")),
),
Effect.ensuring(
Effect.tryPromise({
try: () => queryRuntime[Symbol.asyncDispose](),
catch: (cause) => queryRunnerError(cause, "close"),
}).pipe(Effect.orDie),
),
Effect.orDie,
),
),
),
),
),
);
return {
messages: Stream.fromAsyncIterable(
claudeQueryMessages(queryRuntime),
(cause) => cause,
).pipe(
Stream.catch((cause) =>
Stream.fromEffect(
Effect.gen(function* () {
if (!answered) {
yield* Effect.promise(() => stderrClosed).pipe(
Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
);
}
const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
return yield* queryRunnerError(
refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : cause,
"fromAsyncIterable",
);
}),
),
),
Stream.tap(() =>
Effect.sync(() => {
answered = true;
}),
),
Stream.tap((message) =>
logProtocolEvent({
direction: "incoming",
stage: "decoded",
payload: message,
}),
),
),
offer: (message, onQueued) =>
Effect.uninterruptibleMask((restore) =>
restore(Queue.offer(promptQueue, message)).pipe(
Effect.tap(() => Effect.sync(() => onQueued?.())),
),
).pipe(
Effect.asVoid,
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "prompt.offer",
message,
},
}),
),
),
setModel: (model) =>
Effect.tryPromise({
try: () => queryRuntime.setModel(model),
catch: (cause) => queryRunnerError(cause, "setModel"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.set_model",
model,
},
}),
),
),
applyFlagSettings: (settings) =>
Effect.tryPromise({
try: () => queryRuntime.applyFlagSettings(settings),
catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.apply_flag_settings",
settings,
},
}),
),
),
setPermissionMode: (mode) =>
Effect.tryPromise({
try: () => queryRuntime.setPermissionMode(mode),
catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.set_permission_mode",
mode,
},
}),
),
),
stopTask: (taskId) =>
Effect.tryPromise({
try: () => queryRuntime.stopTask(taskId),
catch: (cause) => queryRunnerError(cause, "stopTask"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: { type: "query.stop_task", taskId },
}),
),
),
backgroundTasks: (toolUseId) =>
Effect.tryPromise({
try: () => queryRuntime.backgroundTasks(toolUseId),
catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: { type: "query.background_tasks", toolUseId },
}),
),
),
mcpServerStatus: Effect.tryPromise({
try: () => queryRuntime.mcpServerStatus(),
catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
}),
readMcpResource: ({ server, uri }) =>
Effect.tryPromise({
try: () => queryRuntime.readMcpResource(server, uri),
catch: (cause) => queryRunnerError(cause, "readMcpResource"),
}),
callMcpTool: (call) =>
Effect.tryPromise({
try: () =>
sendClaudeControlRequest(queryRuntime, {
subtype: "mcp_call",
tool: call.tool,
arguments: call.arguments,
result_not_for_model: true,
}),
catch: (cause) => queryRunnerError(cause, "callMcpTool"),
}),
listPermissionRules: Effect.tryPromise({
try: () =>
sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
}).pipe(
Effect.flatMap(decodeClaudePermissionRules),
// A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
Effect.filterOrFail(
({ state }) => (state.errors ?? []).length === 0,
({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
),
Effect.map(({ state }) => state.rules),
Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
),
interrupt: Effect.tryPromise({
try: () => queryRuntime.interrupt(),
catch: (cause) => queryRunnerError(cause, "interrupt"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.interrupt",
},
}),
),
),
close: Queue.shutdown(promptQueue).pipe(
Effect.andThen(closeClaudeQuery(queryRuntime)),
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.close",
},
}),
),
),
} satisfies ClaudeAgentSdkQuerySession;
},
// Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID.
(effect, input) =>
effect.pipe(
Effect.retry({
times: 1,
while: (error) =>
input.options.resume !== undefined &&
isClaudeMcpRegistrationTimeoutError(error.cause),
}),
),
),
forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
input: ClaudeAgentSdkSessionForkInput,
) {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
providerSessionId: input.providerSessionId,
});
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
protocolLogger === undefined ? Effect.void : protocolLogger(event);
yield* logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "session.fork",
sessionId: input.sessionId,
options: input.options,
},
});
const hostEnvironment = yield* HostProcess.Environment;
const homeDirectory = yield* HostProcess.HomeDirectory;
const usesHostConfig =
claudeConfigDirOf(path, input.environment, homeDirectory) ===
claudeConfigDirOf(path, hostEnvironment, homeDirectory);
const fork: Effect.Effect<
ForkSessionResult & { readonly headMessageId?: string },
unknown
> = usesHostConfig
? Effect.tryPromise({
try: () => forkClaudeSession(input.sessionId, input.options),
catch: (cause) => queryRunnerError(cause, "forkSession"),
})
: forkClaudeSessionInWorker(input).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(Path.Path, path),
);
const result = yield* fork.pipe(
Effect.mapError((cause) => queryRunnerError(cause, "forkSession")),
);
yield* logProtocolEvent({
direction: "incoming",
stage: "decoded",
payload: {
type: "session.forked",
sessionId: result.sessionId,
},
});
// The SDK remaps copied UUIDs. Capture the inherited head before the
// fork's first run appends messages.
const headMessageId = usesHostConfig
? yield* Effect.tryPromise({
try: () =>
getSessionMessages(
result.sessionId,
input.options.dir === undefined ? {} : { dir: input.options.dir },
),
catch: (cause) => queryRunnerError(cause, "getSessionMessages"),
}).pipe(
Effect.map((messages) => messages.at(-1)?.uuid),
Effect.orElseSucceed(() => undefined),
)
: result.headMessageId;
return headMessageId === undefined ? result : { ...result, headMessageId };
}),
subagentLaunchToolUseId: Effect.fn("ClaudeAgentSdkQueryRunner.subagentLaunchToolUseId")(
function* (input: ClaudeAgentSdkSubagentLookupInput) {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
providerSessionId: input.providerSessionId,
});
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
protocolLogger === undefined ? Effect.void : protocolLogger(event);
yield* logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "subagent.lookup",
sessionId: input.sessionId,
agentId: input.agentId,
},
});
const messages = yield* Effect.tryPromise({
try: () =>
getSubagentMessages(input.sessionId, input.agentId, {
...(input.dir === null ? {} : { dir: input.dir }),
limit: 1,
}),
catch: (cause) => queryRunnerError(cause, "getSubagentMessages"),
});
const toolUseId = messages[0]?.parent_tool_use_id ?? null;
yield* logProtocolEvent({
direction: "incoming",
stage: "decoded",
payload: { type: "subagent.found", toolUseId },
});
return toolUseId;
},
),
assertComplete: Effect.void,
});
}),
);
type ClaudeFlagSettings = Parameters<ClaudeQuery["applyFlagSettings"]>[0];
/** Thinking requires a new process. Clearing effort also requires one to reload user settings instead of model defaults. */
function canApplyClaudeSelectionLive(
live: CompiledClaudeModelSelection,
next: CompiledClaudeModelSelection,
): boolean {
return (
live.settings.alwaysThinkingEnabled === next.settings.alwaysThinkingEnabled &&
(next.effort !== undefined || live.effort === undefined)
);
}
function claudeLiveSelectionFlagSettings(
selection: CompiledClaudeModelSelection,
): ClaudeFlagSettings {
return {
...(selection.effort === undefined ? {} : { effortLevel: selection.effort as EffortLevel }),
fastMode: selection.settings.fastMode ?? null,
ultracode: selection.settings.ultracode ?? null,
};
}
// A delegated child is its own SDK session, so Claude Code gives it the main-conversation cache
// TTL. When the user sets Claude's subagentPromptCacheTtl, the child follows it like a native
// subagent would. An explicit CLAUDE_CODE_PROMPT_CACHE_TTL on the instance still wins.
export function claudeQueryEnvironment(
environment: NodeJS.ProcessEnv,
appThread: Pick<OrchestrationV2AppThread, "lineage">,
subagentPromptCacheTtl: "5m" | "1h" | undefined,
): NodeJS.ProcessEnv {
if (
appThread.lineage.relationshipToParent !== "subagent" ||
subagentPromptCacheTtl === undefined ||
environment.CLAUDE_CODE_PROMPT_CACHE_TTL !== undefined
) {
return environment;
}
return { ...environment, CLAUDE_CODE_PROMPT_CACHE_TTL: subagentPromptCacheTtl };
}
// Claude Code's auto tool search sends every MCP schema in full while they fit under a share of the
// context window, which T3's tools do on 1M models. auto:0 already means on and auto:100 off.
export function claudeToolSearchOverride(value: string | undefined): "true" | undefined {
if (value === undefined) return undefined;
if (value === "auto") return "true";