@@ -123,6 +123,7 @@ import * as Context from "effect/Context";
123123import * as SecureRandom from "effect/crypto/SecureRandom" ;
124124import * as DateTime from "effect/DateTime" ;
125125import * as Deferred from "effect/Deferred" ;
126+ import * as Duration from "effect/Duration" ;
126127import * as Effect from "effect/Effect" ;
127128import * as Equal from "effect/Equal" ;
128129import * as Exit from "effect/Exit" ;
@@ -338,6 +339,13 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
338339const BACKGROUND_MOVE_TIMEOUT_MS = 5_000 ;
339340// How long a Stop waits for the CLI to exit before the user is offered Force stop.
340341const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000 ;
342+ // Matches the stderr tail the SDK keeps for a CLI it spawns itself.
343+ const CLAUDE_STDERR_TAIL_LENGTH = 2_048 ;
344+ // The process group is killed on exit, so its stderr closes promptly.
345+ const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration . seconds ( 1 ) ;
346+ // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
347+ const CLAUDE_ROOT_REFUSAL =
348+ "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons" ;
341349
342350const CLAUDE_GROUP_WATCH_SCRIPT = [
343351 "{ 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 = [
352360export function spawnClaudeProcessGroup (
353361 options : ClaudeSpawnOptions ,
354362 onExit ?: ( ) => void ,
363+ onStderr : ( text : string ) => void = ( ) => { } ,
364+ onStderrClose : ( ) => void = ( ) => { } ,
355365) : ClaudeSpawnedProcess {
356366 const child = NodeChildProcess . spawn (
357367 "/bin/sh" ,
@@ -360,10 +370,12 @@ export function spawnClaudeProcessGroup(
360370 cwd : options . cwd ,
361371 env : options . env ,
362372 signal : options . signal ,
363- stdio : [ "pipe" , "pipe" , "ignore " , "pipe" ] ,
373+ stdio : [ "pipe" , "pipe" , "pipe " , "pipe" ] ,
364374 detached : true ,
365375 } ,
366376 ) ;
377+ // Always drained, so a chatty CLI never blocks on a full stderr pipe.
378+ child . stderr ?. setEncoding ( "utf8" ) . on ( "data" , onStderr ) . once ( "close" , onStderrClose ) ;
367379 child . once ( "exit" , ( ) => {
368380 try {
369381 signalProcessGroup ( child . pid ?? 0 , "SIGKILL" ) ;
@@ -558,6 +570,17 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAge
558570 }
559571}
560572
573+ export class ClaudeCodeRootRefusalError extends Schema . TaggedError < ClaudeCodeRootRefusalError > ( ) (
574+ "ClaudeCodeRootRefusalError" ,
575+ {
576+ cause : Schema . Defect ( ) ,
577+ } ,
578+ ) {
579+ override get message ( ) : string {
580+ return `Claude Code exited before it started: ${ CLAUDE_ROOT_REFUSAL } ` ;
581+ }
582+ }
583+
561584class ClaudeMcpRegistrationTimeoutError extends Schema . TaggedError < ClaudeMcpRegistrationTimeoutError > ( ) (
562585 "ClaudeMcpRegistrationTimeoutError" ,
563586 { } ,
@@ -1009,10 +1032,25 @@ export const layerQueryRunner: Layer.Layer<
10091032 const unit = launch ?. unit ;
10101033 const stopScope =
10111034 unit === undefined ? undefined : ( ) => void runFork ( agentScope . stop ( unit ) ) ;
1035+ // Only a CLI that fails before its first message explains itself on
1036+ // stderr. The known root refusal becomes a curated failure; any other
1037+ // stderr can hold private text, so it stays out of turn failures.
1038+ let stderrTail = "" ;
1039+ let stderrClosed : Promise < void > = Promise . resolve ( ) ;
1040+ let answered = false ;
1041+ const appendStderr = ( text : string ) => {
1042+ if ( answered ) return ;
1043+ stderrTail = ( stderrTail + text ) . slice ( - CLAUDE_STDERR_TAIL_LENGTH ) ;
1044+ } ;
10121045 const spawnProcess =
10131046 options . spawnClaudeCodeProcess ??
10141047 ( ( spawnOptions : ClaudeSpawnOptions ) => {
1015- if ( platform !== "win32" ) return spawnClaudeProcessGroup ( spawnOptions , stopScope ) ;
1048+ if ( platform !== "win32" ) {
1049+ // Node can report "exit" before it has read the stderr the CLI wrote.
1050+ let stderrDone = ( ) => { } ;
1051+ stderrClosed = new Promise ( ( resolve ) => ( stderrDone = resolve ) ) ;
1052+ return spawnClaudeProcessGroup ( spawnOptions , stopScope , appendStderr , stderrDone ) ;
1053+ }
10161054 const child = NodeChildProcess . spawn ( spawnOptions . command , spawnOptions . args , {
10171055 cwd : spawnOptions . cwd ,
10181056 env : spawnOptions . env ,
@@ -1132,9 +1170,31 @@ export const layerQueryRunner: Layer.Layer<
11321170 ) ;
11331171
11341172 return {
1135- messages : Stream . fromAsyncIterable ( claudeQueryMessages ( queryRuntime ) , ( cause ) =>
1136- queryRunnerError ( cause , "fromAsyncIterable" ) ,
1173+ messages : Stream . fromAsyncIterable (
1174+ claudeQueryMessages ( queryRuntime ) ,
1175+ ( cause ) => cause ,
11371176 ) . pipe (
1177+ Stream . catch ( ( cause ) =>
1178+ Stream . fromEffect (
1179+ Effect . gen ( function * ( ) {
1180+ if ( ! answered ) {
1181+ yield * Effect . promise ( ( ) => stderrClosed ) . pipe (
1182+ Effect . timeoutOption ( CLAUDE_STDERR_DRAIN_TIMEOUT ) ,
1183+ ) ;
1184+ }
1185+ const refusedRoot = ! answered && stderrTail . includes ( CLAUDE_ROOT_REFUSAL ) ;
1186+ return yield * queryRunnerError (
1187+ refusedRoot ? new ClaudeCodeRootRefusalError ( { cause } ) : cause ,
1188+ "fromAsyncIterable" ,
1189+ ) ;
1190+ } ) ,
1191+ ) ,
1192+ ) ,
1193+ Stream . tap ( ( ) =>
1194+ Effect . sync ( ( ) => {
1195+ answered = true ;
1196+ } ) ,
1197+ ) ,
11381198 Stream . tap ( ( message ) =>
11391199 logProtocolEvent ( {
11401200 direction : "incoming" ,
@@ -5031,6 +5091,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
50315091 }
50325092 } ) ;
50335093 const requestedContinuations = yield * Ref . make ( new Set < string > ( ) ) ;
5094+ const absorbedWakes = yield * Ref . make ( new Set < string > ( ) ) ;
50345095 const heldProposedPlansByToolUseId = new Map < string , string > ( ) ;
50355096 const runtimeContext = yield * Effect . context < never > ( ) ;
50365097 const runPromise = Effect . runPromiseWith ( runtimeContext ) ;
@@ -5466,6 +5527,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54665527 yield * endClaudeMonitorTasks ( ( _taskId , task ) => task . nativeThreadId === nativeThreadId ) ;
54675528 } ) ;
54685529
5530+ const forgetAbsorbedWake = ( nativeThreadId : string ) =>
5531+ Ref . update ( absorbedWakes , ( current ) => {
5532+ if ( ! current . has ( nativeThreadId ) ) return current ;
5533+ const updated = new Set ( current ) ;
5534+ updated . delete ( nativeThreadId ) ;
5535+ return updated ;
5536+ } ) ;
5537+
54695538 const clearWakeStateForNativeThread =
54705539 /* Provider events include streaming deltas; avoid a span for each update. */
54715540 Effect . fnUntraced ( function * ( nativeThreadId : string ) {
@@ -5486,8 +5555,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54865555 updated . delete ( nativeThreadId ) ;
54875556 return updated ;
54885557 } ) ;
5558+ yield * forgetAbsorbedWake ( nativeThreadId ) ;
54895559 } ) ;
54905560
5561+ // Claude runs one root turn at a time, so a user turn's result also ends a wake turn it
5562+ // folded in. The continuation replays that wake's buffered frames but gets no result of its own.
5563+ const markAbsorbedWake = Effect . fnUntraced ( function * ( nativeThreadId : string ) {
5564+ const messages = ( yield * Ref . get ( wakeBuffers ) ) . get ( nativeThreadId ) ?. messages ?? [ ] ;
5565+ const lastResult = messages . findLastIndex ( ( entry ) => entry . type === "result" ) ;
5566+ if ( ! messages . slice ( lastResult + 1 ) . some ( isClaudeRootTurnFrame ) ) return ;
5567+ yield * Ref . update ( absorbedWakes , ( current ) => new Set ( current ) . add ( nativeThreadId ) ) ;
5568+ } ) ;
5569+
54915570 // The SDK emits no initial roster; reset roster and wake eligibility when opening a live query.
54925571 const resetBackgroundTaskStateForNativeThreadProcess = Effect . fnUntraced ( function * (
54935572 nativeThreadId : string ,
@@ -8070,6 +8149,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
80708149 if ( message . type === "result" ) {
80718150 bufferedResultArrivals . set ( message , yield * DateTime . now ) ;
80728151 }
8152+ if ( isClaudeRootTurnFrame ( message ) ) {
8153+ yield * forgetAbsorbedWake ( wakeInput . nativeThreadId ) ;
8154+ }
80738155 yield * Ref . update ( wakeBuffers , ( current ) => {
80748156 const existing = current . get ( wakeInput . nativeThreadId ) ;
80758157 const updated = new Map ( current ) ;
@@ -9518,6 +9600,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
95189600 next . delete ( context . providerTurnId ) ;
95199601 return next ;
95209602 } ) ;
9603+ if ( ! isClaudeProviderContinuationTurn ( context . input ) ) {
9604+ yield * markAbsorbedWake ( liveQuery . nativeThreadId ) ;
9605+ }
95219606 const usageLimited =
95229607 context . authenticationFailureMessage === undefined &&
95239608 ( context . rejectedRateLimitTypes . size > 0 ||
@@ -10815,6 +10900,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1081510900 updated . delete ( nativeThreadId ) ;
1081610901 return updated ;
1081710902 } ) ;
10903+ const wakeAbsorbed = ( yield * Ref . get ( absorbedWakes ) ) . has ( nativeThreadId ) ;
10904+ yield * forgetAbsorbedWake ( nativeThreadId ) ;
1081810905 if ( drained . length === 0 ) {
1081910906 const completedAt = yield * DateTime . now ;
1082010907 yield * finalizeActiveTurn ( { context, status : "completed" , completedAt } ) ;
@@ -10883,7 +10970,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1088310970 yield * handleSdkMessage ( { query : querySession . query , message : lastResult } ) ;
1088410971 return ;
1088510972 }
10886- if ( hasOpaqueTaskNotification && ! context . nativeWakeStarted ) {
10973+ if ( wakeAbsorbed || ( hasOpaqueTaskNotification && ! context . nativeWakeStarted ) ) {
1088710974 const completedAt = yield * DateTime . now ;
1088810975 yield * finalizeActiveTurn ( { context, status : "completed" , completedAt } ) ;
1088910976 } else if ( ! context . nativeWakeStarted ) {
0 commit comments