TypeScript
fix(server): show why Claude refuses full access as root (#23804)
Julius Marmingefd63914c77c8
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 6458137a10c..3f4f4186574 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -123,6 +123,7 @@ 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";@@ -338,6 +339,13 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;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 &",@@ -352,6 +360,8 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions,onExit?: () => void,+ onStderr: (text: string) => void = () => {},+ onStderrClose: () => void = () => {},): ClaudeSpawnedProcess {const child = NodeChildProcess.spawn("/bin/sh",@@ -360,10 +370,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", onStderr).once("close", onStderrClose);child.once("exit", () => {try {signalProcessGroup(child.pid ?? 0, "SIGKILL");@@ -558,6 +570,17 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAge}}+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",{},@@ -1009,10 +1032,25 @@ export const layerQueryRunner: Layer.Layer<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") return spawnClaudeProcessGroup(spawnOptions, stopScope);+ 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,@@ -1132,9 +1170,31 @@ export const layerQueryRunner: Layer.Layer<);return {- messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>- queryRunnerError(cause, "fromAsyncIterable"),+ 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",diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.tsindex 340de961471..5898996e486 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts@@ -17,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";@@ -546,6 +547,47 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro}),);+ const rootRefusal =+ "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";++ const startupFailureMessage = (stderr: string) =>+ Effect.gen(function* () {+ const cli = fakeClaudeCli(`printf '%s\\n' '${stderr}' >&2\nexit 1`);+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })),+ );+ const session = yield* openFakeCli(cli);+ const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit);+ assert.isTrue(Exit.isFailure(exit));+ return Exit.isFailure(exit)+ ? makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message+ : "";+ });++ // Claude Code refuses bypassPermissions as root and explains why only on+ // stderr, so the turn failure has to carry that line.+ it.effect("reports the CLI's root refusal when it exits before answering", () =>+ Effect.gen(function* () {+ assert.include(yield* startupFailureMessage(rootRefusal), rootRefusal);+ }).pipe(Effect.provide(realQueryRunner)),+ );++ // Startup stderr can carry paths, tokens, or settings, so only the known+ // refusal reaches the failure the client shows.+ it.effect("keeps other startup stderr out of the turn failure", () =>+ Effect.gen(function* () {+ const surrounded = yield* startupFailureMessage(+ `token=sk-private-123\n${rootRefusal}\nat /home/private/settings.json`,+ );+ assert.include(surrounded, rootRefusal);+ assert.notInclude(surrounded, "sk-private-123");+ assert.notInclude(surrounded, "/home/private");++ const unknown = yield* startupFailureMessage("token=sk-private-123");+ assert.notInclude(unknown, "sk-private-123");+ }).pipe(Effect.provide(realQueryRunner)),+ );+// 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", () =>diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.tsindex 15762a1aa4b..8927a8c0ae9 100644--- a/packages/provider-core/src/server/failure.ts+++ b/packages/provider-core/src/server/failure.ts@@ -111,6 +111,7 @@ function curatedCauseMessages(cause: unknown): {case "ClaudeAppendSystemPromptMissingValueError":case "ClaudeSettingsLaunchArgError":case "ClaudeMcpRegistrationTimeoutError":+ case "ClaudeCodeRootRefusalError":case "CursorModelUnavailableError":case "CodexGoalObjectiveTooLongError":case "ProviderSetupError":