From 678fea9e28b28860b61cb0140c2b165c715bae33 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 15:58:50 +0000 Subject: [PATCH 1/3] test(server): reproduce #16297, Claude Code startup death hides its exit and stderr A Claude CLI that writes to stderr and exits 1 before its first message fails the turn with only "Provider turn failed.", and the stream failure cause carries no trace of the CLI's stderr for the server log. These tests reproduce #16297 and fail on main. Co-Authored-By: Claude Opus 5.5 --- .../ClaudeAgentSdkQueryRunner.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index d0333a1b05597..81581281ad03a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -9,6 +9,7 @@ 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 Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; @@ -16,6 +17,7 @@ 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 Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; @@ -453,6 +455,38 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }), ); + const startupDeathStderr = "error: An internal error occurred (EPERM) at /Users/private-16297"; + + const failStartup = Effect.gen(function* () { + const cli = fakeClaudeCli(`printf '%s\\n' '${startupDeathStderr}' >&2\nexit 1`); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })), + ); + const session = yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner)); + const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit); + if (!Exit.isFailure(exit)) throw new Error("Expected the CLI's exit to fail the stream"); + return exit.cause; + }); + + it.effect("names Claude Code's exit code when it exits before answering", () => + Effect.gen(function* () { + const cause = yield* failStartup; + const { message } = makeProviderFailure({ + cause: Cause.squash(cause), + class: "transport_error", + }); + assert.include(message, "exited"); + assert.include(message, "code 1"); + assert.notInclude(message, "private-16297"); + }), + ); + + it.effect("keeps the CLI's startup stderr for the server log", () => + Effect.gen(function* () { + assert.include(Cause.pretty(yield* failStartup), startupDeathStderr); + }), + ); + // The CLI keeps running its turn after its pipes close, so a server that // crashed would leave it working next to the session it resumes. it.effect("stops the CLI when the server that started it goes away", () => From 0004ae9b87088ab6f9c6c75fa9eae9ef41e0f191 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 28 Oct 2026 00:37:54 +0000 Subject: [PATCH 2/3] fix(server): name Claude Code's exit when it dies before responding A Claude CLI that exited before its first message (for example macOS denying it the project folder with EPERM) failed the turn with only "Provider turn failed.", and its stderr was discarded, so the server log had no reason either. The process-group spawn now pipes and always drains stderr, keeping a 2048-char tail until the first message arrives. A query that fails before answering, after a nonzero exit or a signal, and is not an SDK abort, becomes a curated ClaudeCodeStartupExitError ("Claude Code exited with code 1 before it responded."). The stderr tail rides only in its cause chain, so Cause.pretty in the stream-failure warning shows it while the client message never does. Windows' own spawn feeds the same tail. Fixes pingdotgg/t3code#16297 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 70 ++++++++++++++++--- packages/provider-core/src/server/failure.ts | 1 + 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b66e85e14d7c0..d339469151a58 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -22,6 +22,7 @@ import { import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; import { normalizeClaudeTurnTokenUsage } from "../../provider/ClaudeTurnTokenUsage.ts"; import { + AbortError as ClaudeAbortError, type CanUseTool, forkSession as forkClaudeSession, type EffortLevel, @@ -314,6 +315,8 @@ 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; +// Matches the stderr tail the SDK keeps for a CLI it spawns itself. +const CLAUDE_STDERR_TAIL_LENGTH = 2_048; const CLAUDE_GROUP_WATCH_SCRIPT = [ "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", @@ -328,6 +331,7 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [ export function spawnClaudeProcessGroup( options: ClaudeSpawnOptions, onExit?: () => void, + onStderr?: (text: string) => void, ): ClaudeSpawnedProcess { const child = NodeChildProcess.spawn( "/bin/sh", @@ -336,10 +340,12 @@ export function spawnClaudeProcessGroup( cwd: options.cwd, env: options.env, signal: options.signal, - stdio: ["pipe", "pipe", "ignore", "pipe"], + 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", (text: string) => onStderr?.(text)); child.once("exit", () => { try { signalProcessGroup(child.pid ?? 0, "SIGKILL"); @@ -543,6 +549,21 @@ class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError()( + "ClaudeCodeStartupExitError", + { + exitCode: Schema.NullOr(Schema.Number), + signal: Schema.NullOr(Schema.String), + cause: Schema.Defect(), + }, +) { + override get message(): string { + const exit = this.exitCode === null ? `signal ${this.signal}` : `code ${this.exitCode}`; + return `Claude Code exited with ${exit} before it responded. Check the server log for details.`; + } +} + export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError()( "ClaudeBackgroundWorkBlocksQueryReplacementError", {}, @@ -961,10 +982,18 @@ export const layerQueryRunner: Layer.Layer< const unit = launch?.unit; const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); + // Only a CLI that dies before its first message explains itself on stderr. + let stderrTail = ""; + let answered = false; + const appendStderr = (text: string) => { + if (!answered) stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); + }; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { - if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope); + if (platform !== "win32") { + return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr); + } const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { cwd: spawnOptions.cwd, env: spawnOptions.env, @@ -972,23 +1001,29 @@ export const layerQueryRunner: Layer.Layer< windowsHide: true, stdio: ["pipe", "pipe", "pipe"], }); - child.stderr - .setEncoding("utf8") - .on("data", (chunk: string) => options.stderr?.(chunk)); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { + appendStderr(chunk); + options.stderr?.(chunk); + }); return child; }); let spawnedProcess: ClaudeSpawnedProcess | undefined; let processExited = false; + let exitStatus: { exitCode: number | null; signal: string | null } | undefined; let processExit: Promise | undefined; const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => { const child = spawnProcess(spawnOptions); spawnedProcess = child; processExited = child.exitCode !== null || child.signalCode != null; + if (processExited) { + exitStatus = { exitCode: child.exitCode, signal: child.signalCode ?? null }; + } processExit = new Promise((resolve) => { if (processExited) resolve(); else - child.once("exit", () => { + child.once("exit", (exitCode, signal) => { processExited = true; + exitStatus = { exitCode, signal }; resolve(); }); }); @@ -1080,9 +1115,26 @@ export const layerQueryRunner: Layer.Layer< ); return { - messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => - queryRunnerError(cause, "fromAsyncIterable"), - ).pipe( + messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => { + // An aborted SDK query is a stop T3 asked for, not a CLI that died. + const exit = answered || cause instanceof ClaudeAbortError ? undefined : exitStatus; + const stderr = stderrTail.trim(); + return queryRunnerError( + exit === undefined || exit.exitCode === 0 + ? cause + : new ClaudeCodeStartupExitError({ + ...exit, + cause: stderr === "" ? cause : new Error(`stderr: ${stderr}`, { cause }), + }), + "fromAsyncIterable", + ); + }).pipe( + Stream.tap(() => + Effect.sync(() => { + answered = true; + stderrTail = ""; + }), + ), Stream.tap((message) => logProtocolEvent({ direction: "incoming", diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 48331a10eac26..c48c50b77e0d0 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 "ClaudeCodeStartupExitError": case "ClaudeMcpRegistrationTimeoutError": case "CursorModelUnavailableError": return { known: stringField(cause, "message"), category: categoryMessage() }; From 84fc3470b6927e9d351414ad239fdef0f834d7ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 08:18:09 +0000 Subject: [PATCH 3/3] fix(server): a Claude query that dies before the turn attaches reports why The real app opened the query, the CLI exited before any frame, and the stream's consumer fiber cleared the live query before startTurn claimed it. With no turn to finalize, the exit cause was dropped and startTurn failed with the generic "query ended before the turn could start", so neither the curated exit message nor the stderr reached the client or the server log. Keep the query's failure cause on the live query and attach it to that start error, so failure curation finds ClaudeCodeStartupExitError and the logged cause chain carries the bounded stderr. AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 17 +++++++++++++++-- .../Adapters/ClaudeAdapterV2.ts | 5 +++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 1add2822a01e9..b4edb07753ae4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -11017,10 +11017,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { opened += 1; const sdkMessages = yield* Queue.unbounded(); return { - // The first CLI exits without writing a frame. + // The first CLI dies without writing a frame. messages: opened === 1 - ? Stream.empty.pipe(Stream.ensuring(Deferred.succeed(deadStreamEnded, undefined))) + ? Stream.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "fromAsyncIterable", + cause: new ClaudeAdapterV2.ClaudeCodeRootRefusalError({ + cause: new Error("stderr: startup refusal"), + }), + }), + ).pipe(Stream.ensuring(Deferred.succeed(deadStreamEnded, undefined))) : Stream.fromQueue(sdkMessages), offer: () => Effect.void, setModel: () => Effect.void, @@ -11085,6 +11092,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { Cause.pretty(started.cause), "Claude provider query ended before the turn could start.", ); + // Why the CLI died reaches the turn failure and the server log. + assert.equal( + makeProviderFailure({ cause: started.cause, class: "provider_error" }).message, + new ClaudeAdapterV2.ClaudeCodeRootRefusalError({ cause: undefined }).message, + ); + assert.include(Cause.pretty(started.cause), "stderr: startup refusal"); } const followUp = yield* harness.runtime .startTurn(harness.turnInput("b", 2)) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index d496070d5f27a..bed6ec0cc1ddd 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4481,6 +4481,8 @@ interface ClaudeLiveQueryContext { capabilities: ReadonlySet; permissionMode: PermissionMode; stopping: boolean; + // Why the CLI died before any turn claimed it; the turn start reports it. + exitCause: Cause.Cause | undefined; readonly subagentsFromEarlierProcesses: ReadonlySet; // Subagents this process still ran when a replacement took over; only its exit can end them. handedOffSubagents: ReadonlySet; @@ -11112,6 +11114,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( capabilities: new Set(), permissionMode: queryOptions.permissionMode, stopping: false, + exitCause: undefined, handedOffSubagents: new Set(), subagentsFromEarlierProcesses: new Set( [...(yield* Ref.get(sessionSubagentsByTaskId)).values()].filter( @@ -11182,6 +11185,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.exit, Effect.flatMap( Effect.fnUntraced(function* (exit: ClaudeQueryStreamExit) { + if (exit._tag === "Failure") context.exitCause = exit.cause; const heldContext = yield* Ref.get(activeTurn); if ( (yield* Ref.get(queryContext))?.query === querySession && @@ -11358,6 +11362,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: "Claude provider query ended before the turn could start.", + cause: querySession.exitCause, }); } if (