diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 8b9666ce3d6aa..506999988f5c8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -343,6 +343,7 @@ export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROV 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"; +const CLAUDE_BOOT_TIMEOUT = "5 minutes"; // 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"; @@ -619,10 +620,12 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError()( "ClaudeMcpRegistrationTimeoutError", - {}, + { phase: Schema.Literals(["initialize", "setMcpServers"]) }, ) { 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."; + return this.phase === "initialize" + ? "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs." + : "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs."; } } @@ -1311,6 +1314,31 @@ export const layerQueryRunner: Layer.Layer< restore( Effect.gen(function* () { if (mcpServers !== undefined) { + const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () => + Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", { + threadId: input.threadId, + providerSessionId: input.providerSessionId, + phase, + }).pipe( + Effect.andThen( + Effect.fail( + queryRunnerError( + new ClaudeMcpRegistrationTimeoutError({ phase }), + phase, + ), + ), + ), + ); + // The SDK leaves query() boot unbounded, and it takes about a minute on a host + // with CPUs 12x oversubscribed, so it gets its own, longer deadline. + yield* Effect.promise(() => + queryRuntime.initializationResult().catch(() => undefined), + ).pipe( + Effect.timeoutOrElse({ + duration: CLAUDE_BOOT_TIMEOUT, + orElse: timedOut("initialize"), + }), + ); // Errors and mcp_status can echo headers; log only server names. const failed = yield* Effect.tryPromise({ try: () => queryRuntime.setMcpServers(mcpServers), @@ -1320,20 +1348,7 @@ export const layerQueryRunner: Layer.Layer< 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", - ), - ), - ), - ), + orElse: timedOut("setMcpServers"), }), ); if (failed.length > 0) { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index fd72aceaa5905..4ef527115c8b1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -254,6 +254,7 @@ it.effect("reopens a stalled MCP registration before delivering the resumed prom if (typeof prompt === "string") throw new Error("Expected streaming input"); prompts.push(prompt); return { + initializationResult: async () => ({}), setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, close: prompts.length === 1 ? firstClose : secondClose, [Symbol.asyncDispose]: async () => { @@ -360,6 +361,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", ( cleanupProgress.resolve("retry"); } return { + initializationResult: async () => ({}), setMcpServers: () => { registrationStarted.resolve(); return first @@ -410,6 +412,7 @@ it.effect("stops retrying MCP registration after two timeouts and reports the ca const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; return { + initializationResult: async () => ({}), setMcpServers: () => { started.resolve(); return new Promise(() => {}); @@ -450,6 +453,7 @@ it.effect("cancels a stalled registration without retrying or retaining its prom const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( () => ({ + initializationResult: async () => ({}), setMcpServers: () => { registrationStarted.resolve(); return new Promise(() => {}); @@ -480,6 +484,7 @@ it.effect("does not reuse a fresh session ID after MCP registration times out", const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( () => ({ + initializationResult: async () => ({}), setMcpServers: () => { registrationStarted.resolve(); return new Promise(() => {}); @@ -507,6 +512,55 @@ it.effect("does not reuse a fresh session ID after MCP registration times out", ), ); +it.effect.each([ + ["opens after a slow CLI boot", "120 seconds", true], + ["times out a CLI that never boots", "5 minutes", false], +] as const)("%s", ([, bootWait, boots]) => + Effect.scoped( + Effect.gen(function* () { + const waiting = Promise.withResolvers(); + const booted = Promise.withResolvers(); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + initializationResult: () => { + waiting.resolve(); + return booted.promise; + }, + // The CLI answers control requests only after it has booted. + setMcpServers: async () => { + waiting.resolve(); + await booted.promise; + return { added: ["t3-code"], removed: [], errors: {} }; + }, + close: vi.fn(), + [Symbol.asyncDispose]: async () => {}, + }) 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(() => waiting.promise); + yield* TestClock.adjust(bootWait); + if (boots) booted.resolve(); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, boots ? "Success" : "Failure"); + if (result._tag === "Success") yield* result.success.close; + else + assert.equal( + makeProviderFailure({ + cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, + }).message, + "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.", + ); + }).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");