Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions src/main/claude/claude-agent-sdk-process-spawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function sdkOptions(overrides: Partial<SdkSpawnOptions> = {}): SdkSpawnOptions {
describe('claude agent SDK process spawn', () => {
it('routes the SDK spawn through Orca and retains the pid the lease adjudicates on', () => {
const process = fakeSpawn()
const spawn = createClaudeCodeProcessSpawn(process.spawnImpl)
const spawn = createClaudeCodeProcessSpawn(process.spawnImpl, 'win32')

expect(spawn.pid).toBeUndefined()
expect(spawn.child).toBeNull()
Expand All @@ -52,15 +52,49 @@ describe('claude agent SDK process spawn', () => {
expect(child).toBe(process.child)
expect(spawn.child).toBe(process.child)
expect(spawn.pid).toBe(4321)
// Windows has no supervisor: Claude itself is the child.
expect(spawn.supervised).toBe(false)
expect(process.specs[0]).toEqual({
program: '/usr/local/bin/claude',
args: ['--output-format', 'stream-json'],
cwd: '/work/repo',
env: { PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one' },
detached: false,
stdio: ['pipe', 'pipe', 'pipe']
})
})

it.each(['darwin', 'linux'] as const)(
'starts Claude under the provider supervisor on %s, which is then the pid the lease records',
(platform) => {
const process = fakeSpawn()
const spawn = createClaudeCodeProcessSpawn(process.spawnImpl, platform)
spawn.spawn(sdkOptions())

const [spec] = process.specs
if (!spec) {
throw new Error('the spawner never built a spec')
}
expect(spawn.supervised).toBe(true)
expect(spawn.pid).toBe(4321)
expect(spec.program).toBe(globalThis.process.execPath)
expect(spec.args?.[0]).toBe('-e')
expect(spec.detached).toBe(true)
expect(spec.cwd).toBe('/work/repo')
const supervisorSpec = JSON.parse(
Buffer.from(String(spec.env?.ORCA_PROVIDER_SUPERVISOR_SPEC), 'base64').toString()
)
expect(supervisorSpec).toMatchObject({
command: '/usr/local/bin/claude',
args: ['--output-format', 'stream-json'],
cwd: '/work/repo',
ownerPid: globalThis.process.pid
})
// The supervisor passes its env to Claude minus its own two keys.
expect(spec.env).toMatchObject({ PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one' })
}
)

it('keeps the child out of the SDK abort path so exit proof stays Orca-owned', () => {
const process = fakeSpawn()
const controller = new AbortController()
Expand All @@ -86,7 +120,7 @@ describe('claude agent SDK process spawn', () => {

it('hands a Windows .cmd shim to Orca\u2019s argument encoder', () => {
const process = fakeSpawn()
createClaudeCodeProcessSpawn(process.spawnImpl).spawn(
createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn(
sdkOptions({
command: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd',
args: ['--setting-sources=user,project,local', '--session-id', 'a b&c']
Expand Down
35 changes: 29 additions & 6 deletions src/main/claude/claude-agent-sdk-process-spawn.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk'
import { spawnProcess } from '../../shared/child-process/run-process'
import { createProviderSpawnSpec } from '../codex/codex-app-server-posix-supervisor'

/** Derived rather than imported: only src/shared/child-process may name node:child_process. */
type ClaudeCodeChild = ReturnType<typeof spawnProcess>
Expand All @@ -11,8 +12,13 @@ export type ClaudeCodeProcessSpawn = {
spawn: (options: ClaudeAgentSdkSpawnOptions) => ClaudeCodeChild
/** The retained child, so Orca keeps its own tree-kill and exit-proof ladder. Null until the SDK spawns. */
readonly child: ClaudeCodeChild | null
/** Ownership proof: the durable lease adjudicates on this pid plus start time plus the spawn token. */
/**
* Ownership proof: the durable lease adjudicates on this pid plus start time plus the spawn
* token. On POSIX it is the provider supervisor's, which outlives Claude by construction.
*/
readonly pid: number | undefined
/** Whether the child is the POSIX supervisor, whose SIGTERM stops Claude and then itself. */
readonly supervised: boolean
readonly stderrTail: string
}

Expand All @@ -31,21 +37,37 @@ function definedEnv(env: Record<string, string | undefined>): Record<string, str
*
* Two independent reasons: the SDK's `SpawnedProcess` has no pid, and Orca's
* spawner is the only path that encodes `.cmd` arguments safely on Windows.
*
* On POSIX Claude runs under the provider supervisor, so an Orca that dies stops
* it instead of leaving it to finish its turn, tools and edits included, with
* nobody watching. Windows has no supervisor and spawns Claude directly.
*/
export function createClaudeCodeProcessSpawn(
spawnImpl: typeof spawnProcess = spawnProcess
spawnImpl: typeof spawnProcess = spawnProcess,
platform: NodeJS.Platform = process.platform
): ClaudeCodeProcessSpawn {
let child: ClaudeCodeChild | null = null
let stderrTail = ''
const supervised = platform !== 'win32'
return {
spawn: (options) => {
const spec = createProviderSpawnSpec(
{
command: options.command,
args: [...options.args],
...(options.cwd === undefined ? {} : { cwd: options.cwd })
},
definedEnv(options.env),
platform
)
Comment on lines +54 to +62

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Tools survive supervisor escalation If Orca dies while Claude is running a Bash tool and Claude ignores SIGTERM, the supervisor eventually SIGKILLs only Claude’s process group. The tool runs in a separate group, so it can continue working unwatched after Claude exits. The SIGTERM-ignoring test checks Claude’s exit but does not check the tool; the owner-death test checks the tool only when Claude handles SIGTERM.

// Why `options.signal` is dropped: it would let the SDK kill the child outside
// Orca's ladder, and close() may never report an exit it did not observe.
const spawned = spawnImpl({
program: options.command,
args: [...options.args],
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
env: definedEnv(options.env),
program: spec.program,
args: spec.args,
cwd: spec.cwd,
env: spec.env,
detached: spec.detached,
stdio: ['pipe', 'pipe', 'pipe']
})
child = spawned
Expand All @@ -62,6 +84,7 @@ export function createClaudeCodeProcessSpawn(
get pid() {
return child?.pid
},
supervised,
get stderrTail() {
return stderrTail
}
Expand Down
72 changes: 72 additions & 0 deletions src/main/claude/claude-child-exit-proof-ladder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from 'vitest'
import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../codex/codex-app-server-posix-supervisor'
import type { ClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'
import { proveClaudeChildExitWithReaper } from './claude-child-exit-proof-ladder'

function fakeTree(): ClaudeChildTreeReaper & { reap: ReturnType<typeof vi.fn> } {
return {
capture: vi.fn(async () => {}),
refresh: vi.fn(async () => {}),
reap: vi.fn(async () => 'exited' as const),
treeVerdict: 'exited'
}
}

/** A root that leaves only once a SIGTERM has had `stopMs` to act, the way a supervisor does. */
function rootStoppedBySigterm(stopMs: number) {
let exited = false
let settle = (): void => {}
const exitPromise = new Promise<void>((resolve) => {
settle = resolve
})
const kill = vi.fn((signal?: NodeJS.Signals | number) => {
if (signal === 'SIGTERM') {
setTimeout(() => {
exited = true
settle()
}, stopMs)
}
return true
})
const stdin = { end: vi.fn() }
return {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The ladder reads only pid, kill and stdin.end from its child.
child: { pid: 4321, kill, stdin } as unknown as Parameters<
typeof proveClaudeChildExitWithReaper
>[0]['child'],
kill,
stdin,
exitPromise,
exited: () => exited
}
}

describe('Claude child exit proof ladder', () => {
it('stops a supervised child with SIGTERM and waits out the supervisor stop before forcing', async () => {
// Slower than the unsupervised 1.5 s grace, still inside the supervisor's own bound.
const root = rootStoppedBySigterm(PROVIDER_SUPERVISOR_MAX_STOP_MS - 500)
const tree = fakeTree()

await expect(
proveClaudeChildExitWithReaper({ ...root, supervised: true, tree }, () => tree)
).resolves.toBe(true)

expect(root.stdin.end).toHaveBeenCalled()
expect(root.kill).toHaveBeenCalledWith('SIGTERM')
// Forcing here would SIGKILL the supervisor mid-stop and orphan Claude in its own group.
expect(root.kill).not.toHaveBeenCalledWith('SIGKILL')
expect(tree.reap).not.toHaveBeenCalled()
}, 10_000)

it('never signals an unsupervised child for the graceful stop', async () => {
const root = rootStoppedBySigterm(0)
const tree = fakeTree()

await proveClaudeChildExitWithReaper({ ...root, tree }, () => tree)

// On Windows a direct SIGTERM is TerminateProcess: stdin end stays the only graceful rung.
expect(root.stdin.end).toHaveBeenCalled()
expect(root.kill).not.toHaveBeenCalledWith('SIGTERM')
expect(tree.reap).toHaveBeenCalled()
}, 10_000)
})
17 changes: 15 additions & 2 deletions src/main/claude/claude-child-exit-proof-ladder.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,45 @@
import type { SpawnedProcess } from '../../shared/child-process/run-process'
import { waitForProcessExitUntil } from '../codex/codex-process-exit-deadline'
import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../codex/codex-app-server-posix-supervisor'
import type { ClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'

const GRACEFUL_EXIT_MS = 1_500
// A signalled supervisor escalates on its own; forcing it sooner kills it and orphans Claude.
export const SUPERVISED_GRACEFUL_EXIT_MS = PROVIDER_SUPERVISOR_MAX_STOP_MS + 500
const FORCED_EXIT_MS = 1_000

export type ClaudeChildExitProofInput = {
child: Pick<SpawnedProcess, 'pid' | 'kill' | 'stdin'>
exitPromise: Promise<void>
exited: () => boolean
tree?: ClaudeChildTreeReaper
/** The child is the POSIX provider supervisor: SIGTERM stops Claude, which reaps its tools. */
supervised?: boolean
}

export async function proveClaudeChildExitWithReaper(
input: ClaudeChildExitProofInput,
createTree: () => ClaudeChildTreeReaper
): Promise<boolean> {
const tree = input.tree ?? createTree()
// Arm before stdin closes: only a live root can identify its descendants.
// Arm before the stop: only a live root can identify its descendants.
await tree.capture()
try {
input.child.stdin?.end()
} catch {
// The reap below still owns the process.
}
// Stdin end alone lets Claude finish its turn, tools and edits included; a close is a stop.
// Windows has no supervisor, and a direct SIGTERM there is TerminateProcess.
if (input.supervised && !input.exited()) {
input.child.kill('SIGTERM')
}
let reaped = false
if (!input.exited()) {
await waitForProcessExitUntil(input.exitPromise, GRACEFUL_EXIT_MS)
await waitForProcessExitUntil(
input.exitPromise,
input.supervised ? SUPERVISED_GRACEFUL_EXIT_MS : GRACEFUL_EXIT_MS
)
if (!input.exited()) {
reaped = true
await tree.refresh?.()
Expand Down
3 changes: 3 additions & 0 deletions src/main/claude/claude-child-root-termination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ type RootTerminationInput = {
* nothing. A probe here could only let an unreadable process table cost the tree
* the one fallback that still works once every table read has failed.
*
* On POSIX the root is the provider supervisor, killed only after its own stop had
* its whole bound; Claude, in its own group, is reached by the descendant kill.
*
* False means no signal was sent, because the root had already left.
*/
export function terminateClaudeRoot(input: RootTerminationInput): boolean {
Expand Down
101 changes: 70 additions & 31 deletions src/main/claude/claude-stream-json-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,18 @@ async function open(
return connection
}

function launchedArgv(spec: ProcessSpec | undefined): string[] {
const supervised = spec?.env?.ORCA_PROVIDER_SUPERVISOR_SPEC
if (!supervised) {
return [spec?.program ?? '', ...(spec?.args ?? [])]
}
const launch: unknown = JSON.parse(Buffer.from(supervised, 'base64').toString())
if (!launch || typeof launch !== 'object' || !('command' in launch) || !('args' in launch)) {
return []
}
return [String(launch.command), ...(Array.isArray(launch.args) ? launch.args.map(String) : [])]
}

function childEnv(): Record<string, string | undefined> {
return (spawned.at(-1)?.env ?? {}) as Record<string, string | undefined>
}
Expand Down Expand Up @@ -195,8 +207,9 @@ describe('Claude stream-json connection', () => {
const report = await until(() => readReportSafely(scenario), 'the scripted CLI report')
expect(report.argv[0]).toBe(FAKE_CLI)
// The .mjs fixture makes the SDK run it under node; a real CLI path is the program
// itself. Either way the resolved path is what Orca's spawner is asked to execute.
expect([spawned.at(-1)?.program, ...(spawned.at(-1)?.args ?? [])]).toContain(FAKE_CLI)
// itself. Either way the resolved path is what Orca's spawner is asked to execute,
// through the POSIX supervisor's spec where there is one.
expect(launchedArgv(spawned.at(-1))).toContain(FAKE_CLI)
expect(report.argv).toContain('--replay-user-messages')
expect(report.argv).toContain(`--session-id=${SESSION_ID}`)
})
Expand Down Expand Up @@ -636,37 +649,63 @@ describe('Claude stream-json connection', () => {
20_000
)

it('settles a spawn error followed by close as processless and closes idempotently', async () => {
const scenario = scriptScenario([HOLD_OPEN])
const missingCli = join(scenario.cwd, 'claude-that-does-not-exist')
let fault: Error | null = null
let exit: Error | null = null
const connection = await open(
{ ...launchFor(scenario), pathToClaudeCodeExecutable: missingCli },
{
onFault: (error) => {
fault = error
},
onExit: (error) => {
exit = error
it.skipIf(process.platform === 'win32')(
'reports a missing CLI under the supervisor as a root exit that names the spawn error',
async () => {
const scenario = scriptScenario([HOLD_OPEN])
const missingCli = join(scenario.cwd, 'claude-that-does-not-exist')
let exit: Error | null = null
const connection = await open(
{ ...launchFor(scenario), pathToClaudeCodeExecutable: missingCli },
{
onExit: (error) => {
exit = error
}
}
}
)
)

await until(
() => (connection.exitVerdict.root === 'processless' ? connection.exitVerdict : null),
'the processless spawn settlement'
)
expect(connection.pid).toBeUndefined()
expect(fault).toBeInstanceOf(Error)
expect(exit).toBeNull()
await expect(Promise.all([connection.close(), connection.close()])).resolves.toEqual([
true,
true
])
await expect(connection.close()).resolves.toBe(true)
expect(connection.exitVerdict).toEqual({ root: 'processless', tree: 'exited' })
})
const reported = await until(() => exit, 'the supervised spawn failure')
// The supervisor spawned, so this is its exit; only its stderr can say why.
expect(reported.message).toMatch(/\(code 127\).*ENOENT/s)
// A first-hand root exit, which releases the lease like a processless start did.
expect(connection.exitVerdict.root).toBe('exited')
}
)

it.skipIf(process.platform !== 'win32')(
'settles a spawn error followed by close as processless and closes idempotently',
async () => {
const scenario = scriptScenario([HOLD_OPEN])
const missingCli = join(scenario.cwd, 'claude-that-does-not-exist')
let fault: Error | null = null
let exit: Error | null = null
const connection = await open(
{ ...launchFor(scenario), pathToClaudeCodeExecutable: missingCli },
{
onFault: (error) => {
fault = error
},
onExit: (error) => {
exit = error
}
}
)

await until(
() => (connection.exitVerdict.root === 'processless' ? connection.exitVerdict : null),
'the processless spawn settlement'
)
expect(connection.pid).toBeUndefined()
expect(fault).toBeInstanceOf(Error)
expect(exit).toBeNull()
await expect(Promise.all([connection.close(), connection.close()])).resolves.toEqual([
true,
true
])
await expect(connection.close()).resolves.toBe(true)
expect(connection.exitVerdict).toEqual({ root: 'processless', tree: 'exited' })
}
)

it('does not treat a child error event as first-hand root exit proof', async () => {
const scenario = scriptScenario([HOLD_OPEN])
Expand Down
Loading
Loading