diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f8cbbdabaf2ef..c466cb5ca8ae2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -534,6 +534,15 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError()( + "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", {}, @@ -603,6 +612,7 @@ export interface ClaudeAgentSdkSubagentLookupInput { } const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError); +const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError); const isProviderAdapterRuntimeRequestResponseError = Schema.is( ProviderAdapter.ProviderAdapterRuntimeRequestResponseError, ); @@ -908,249 +918,310 @@ export const layerQueryRunner: Layer.Layer< allocateSessionId: crypto .randomUUIDv4() .pipe(Effect.mapError((cause) => queryRunnerError(cause, "allocateSessionId"))), - 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); - const promptQueue = yield* Queue.unbounded(); - 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, ...queryOptions } = input.options; - // 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, + 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(); + 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, ...queryOptions } = input.options; + // 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)); + const spawnProcess = + options.spawnClaudeCodeProcess ?? + ((spawnOptions: ClaudeSpawnOptions) => { + if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope); + const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { + cwd: spawnOptions.cwd, + env: spawnOptions.env, + signal: spawnOptions.signal, + windowsHide: true, + stdio: ["pipe", "pipe", "pipe"], }); - 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)); - // Windows has no process groups, so there the SDK spawns the CLI itself. - const spawnClaudeCodeProcess = - options.spawnClaudeCodeProcess ?? - (platform === "win32" - ? undefined - : (spawnOptions: ClaudeSpawnOptions) => - spawnClaudeProcessGroup(spawnOptions, stopScope)); - const queryRuntime = yield* Effect.uninterruptibleMask((restore) => - Effect.try({ - try: () => - query({ - prompt, - options: - spawnClaudeCodeProcess === undefined - ? 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(() => - queryRuntime.setMcpServers(mcpServers), - ).pipe( - Effect.map((result) => Object.keys(result.errors)), - Effect.orElseSucceed(() => Object.keys(mcpServers)), - Effect.timeoutOrElse({ - duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, - orElse: () => - Effect.fail( - queryRunnerError( - "Claude Code did not answer the MCP server registration.", - "setMcpServers", + child.stderr + .setEncoding("utf8") + .on("data", (chunk: string) => options.stderr?.(chunk)); + return child; + }); + let spawnedProcess: ClaudeSpawnedProcess | undefined; + let processExited = false; + let processExit: Promise | undefined; + const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => { + const child = spawnProcess(spawnOptions); + spawnedProcess = child; + processExited = child.exitCode !== null || child.signalCode != null; + processExit = new Promise((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(() => + queryRuntime.setMcpServers(mcpServers), + ).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, - }); + }), + ); + 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( - Effect.andThen(closeClaudeQuery(queryRuntime)), - Effect.ignore, + 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) => - queryRunnerError(cause, "fromAsyncIterable"), - ).pipe( - 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?.())), - ), + return { + messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => + queryRunnerError(cause, "fromAsyncIterable"), ).pipe( - Effect.asVoid, - Effect.tap(() => + Stream.tap((message) => logProtocolEvent({ - direction: "outgoing", + direction: "incoming", stage: "decoded", - payload: { - type: "prompt.offer", - message, - }, + payload: 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, - }, - }), + 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, + }, + }), + ), ), - ), - applyFlagSettings: (settings) => - Effect.tryPromise({ - try: () => queryRuntime.applyFlagSettings(settings), - catch: (cause) => queryRunnerError(cause, "applyFlagSettings"), + 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 }, + }), + ), + ), + interrupt: Effect.tryPromise({ + try: () => queryRuntime.interrupt(), + catch: (cause) => queryRunnerError(cause, "interrupt"), }).pipe( Effect.tap(() => logProtocolEvent({ direction: "outgoing", stage: "decoded", payload: { - type: "query.apply_flag_settings", - settings, + type: "query.interrupt", }, }), ), ), - setPermissionMode: (mode) => - Effect.tryPromise({ - try: () => queryRuntime.setPermissionMode(mode), - catch: (cause) => queryRunnerError(cause, "setPermissionMode"), - }).pipe( + close: Queue.shutdown(promptQueue).pipe( + Effect.andThen(closeClaudeQuery(queryRuntime)), Effect.tap(() => logProtocolEvent({ direction: "outgoing", stage: "decoded", payload: { - type: "query.set_permission_mode", - mode, + type: "query.close", }, }), ), ), - 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 }, - }), - ), - ), - 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), + }), ), - } satisfies ClaudeAgentSdkQuerySession; - }), + ), forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* ( input: ClaudeAgentSdkSessionForkInput, ) { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 5723c488d8889..d0333a1b05597 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -1,25 +1,32 @@ // @effect-diagnostics nodeBuiltinImport:off -- the fake CLI and its leftover child are real processes. import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeStream from "node:stream"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { AgentScope } from "@t3tools/shared/AgentScope"; import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { ClaudeAgentSdkQueryRunner, + type ClaudeAgentSdkQueryOpenInput, layerQueryRunner, spawnClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; @@ -112,6 +119,268 @@ const realQueryRunner = layerQueryRunner.pipe( Layer.provide(NodeServices.layer), ); +const resumedMcpQueryInput = { + threadId: ThreadId.make("thread-restart-registration"), + providerSessionId: ProviderSessionId.make("session-restart-registration"), + options: { + resume: FORK_SESSION_ID, + model: "claude-sonnet-4-6", + tools: [], + permissionMode: "default", + mcpServers: { + "t3-code": { + type: "http", + url: "http://localhost:3773/mcp", + headers: { Authorization: "Bearer test-mcp-credential" }, + }, + }, + }, +} satisfies ClaudeAgentSdkQueryOpenInput; + +it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposalStarted = Promise.withResolvers(); + const finishDisposal = Promise.withResolvers(); + const prompts: AsyncIterable[] = []; + const firstClose = vi.fn(); + const secondClose = vi.fn(); + const firstRegistration = vi.fn(() => { + registrationStarted.resolve(); + return new Promise(() => {}); + }); + const secondRegistration = vi.fn(async () => ({ + added: ["t3-code"], + removed: [], + errors: {}, + })); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => { + assert.notTypeOf(prompt, "string"); + if (typeof prompt === "string") throw new Error("Expected streaming input"); + prompts.push(prompt); + return { + setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, + close: prompts.length === 1 ? firstClose : secondClose, + [Symbol.asyncDispose]: async () => { + firstClose(); + disposalStarted.resolve(); + await finishDisposal.promise; + }, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => disposalStarted.promise); + assert.equal(querySpy.mock.calls.length, 1); + finishDisposal.resolve(); + const session = yield* Fiber.join(opening); + yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); + + assert.equal(firstClose.mock.calls.length, 1); + assert.equal(secondClose.mock.calls.length, 0); + assert.equal(querySpy.mock.calls.length, 2); + for (const [call] of querySpy.mock.calls) { + assert.equal(call.options?.resume, FORK_SESSION_ID); + assert.isUndefined(call.options?.mcpServers); + } + assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]); + const message = { + type: "user", + message: { role: "user", content: "Continue where you left off." }, + parent_tool_use_id: null, + session_id: FORK_SESSION_ID, + } satisfies ClaudeSdk.SDKUserMessage; + yield* session.offer(message); + assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done); + const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next()); + assert.deepEqual(delivered.value, message); + assert.isFalse(delivered.done); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const cleanupProgress = Promise.withResolvers<"kill" | "retry">(); + const events = new NodeEvents.EventEmitter(); + const stdin = new NodeStream.PassThrough(); + const stdout = new NodeStream.PassThrough(); + const child = { + stdin, + stdout, + killed: false, + exitCode: null, + kill: vi.fn(() => { + cleanupProgress.resolve("kill"); + return true; + }), + on: events.on.bind(events), + once: events.once.bind(events), + off: events.off.bind(events), + } satisfies ClaudeSdk.SpawnedProcess; + const signal = yield* Effect.abortSignal; + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { + const first = querySpy.mock.calls.length === 1; + if (first) { + options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal }); + } else { + cleanupProgress.resolve("retry"); + } + return { + setMcpServers: () => { + registrationStarted.resolve(); + return first + ? new Promise(() => {}) + : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); + }, + close: vi.fn(), + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + querySpy.mockRestore(); + stdin.destroy(); + stdout.destroy(); + }), + ); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child }, + }) + .pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + + assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill"); + assert.equal(querySpy.mock.calls.length, 1); + assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]); + if (exits) events.emit("exit", null, "SIGKILL"); + else yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(opening); + assert.equal(Exit.isSuccess(result), exits); + if (Exit.isSuccess(result)) yield* result.value.close; + assert.equal(querySpy.mock.calls.length, exits ? 2 : 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("stops retrying MCP registration after two timeouts and reports the cause", () => + Effect.scoped( + Effect.gen(function* () { + const firstRegistration = Promise.withResolvers(); + const secondRegistration = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { + const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; + return { + setMcpServers: () => { + started.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner + .open(resumedMcpQueryInput) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => firstRegistration.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => secondRegistration.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.equal(querySpy.mock.calls.length, 2); + assert.equal(disposed.mock.calls.length, 2); + assert.equal( + makeProviderFailure({ + cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, + }).message, + "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.", + ); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + setMcpServers: () => { + registrationStarted.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* Fiber.interrupt(opening); + + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + const prompt = querySpy.mock.calls[0]![0].prompt; + if (typeof prompt === "string") throw new Error("Expected streaming input"); + assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("does not reuse a fresh session ID after MCP registration times out", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + setMcpServers: () => { + registrationStarted.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { resume, ...options } = resumedMcpQueryInput.options; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...options, sessionId: resume }, + }) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + function fakeClaudeCli(script: string): string { const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-")); const cli = NodePath.join(dir, "claude"); diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 1fead586062e9..48331a10eac26 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -91,6 +91,7 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeBackgroundWorkBlocksQueryReplacementError": case "ClaudeAppendSystemPromptFileError": case "ClaudeAppendSystemPromptMissingValueError": + case "ClaudeMcpRegistrationTimeoutError": case "CursorModelUnavailableError": return { known: stringField(cause, "message"), category: categoryMessage() }; case "ContextHandoffDeliveryUncertainError":