refactor(cli): delegate runner processes to Execa

This commit is contained in:
yiling
2026-11-18 00:14:05 +08:00
parent 17f14390be
commit 82107f83c6
7 changed files with 162 additions and 237 deletions
+1
View File
@@ -13,6 +13,7 @@
"@shumai/operations": "workspace:*",
"@shumai/tableprinter": "workspace:*",
"commander": "15.0.0",
"execa": "10.2.1",
"hono": "4.13.5",
"ulid": "3.0.2",
"ws": "8.22.2",
+47
View File
@@ -107,6 +107,53 @@ describe('runner bash execution', () => {
await expect(readFile(path.join(cwd, 'unwanted'))).rejects.toThrow()
})
it('finishes draining after a timely root exit even if a background process holds the pipes', async () => {
const source = `const {spawn} = require('node:child_process'); const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {detached: true, stdio: ['ignore', 1, 2]}); console.log(child.pid); child.unref()`
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`
const result = await shell.run(
{ ...request(`${quote(process.execPath)} -e ${quote(source)}`), timeoutSec: 0.5 },
new AbortController().signal,
() => {},
)
const pid = Number((await readFile(path.join(cwd, '.pi/logs/bash-test.log'), 'utf8')).trim())
try {
expect(result).toMatchObject({ exitCode: 0, timedOut: false, aborted: false })
expect(result.error).toBeUndefined()
} finally {
if (pid > 0) process.kill(pid, 'SIGKILL')
}
})
it('reports launch failure without including command text or skill secrets', async () => {
shell.environment.shell = path.join(cwd, 'missing-shell')
const result = await shell.run(
request('echo private-command'),
new AbortController().signal,
() => {},
)
expect(result).toMatchObject({
exitCode: null,
signal: null,
error: 'Command execution failed (ENOENT).',
})
expect(result.error).not.toContain('private-command')
})
it('terminates a running process if the output consumer fails', async () => {
let pid = 0
const result = await shell.run(
request('printf "%s\\n" "$$"; sleep 30'),
new AbortController().signal,
(_stream, data) => {
pid = Number(data.trim())
throw new Error('Output consumer failed')
},
)
expect(result.error).toBe('Output consumer failed')
expect(pid).toBeGreaterThan(0)
expect(() => process.kill(pid, 0)).toThrow()
})
it('rejects invalid timeouts and caps runaway output', async () => {
expect(
await shell.run(
+72 -108
View File
@@ -1,6 +1,5 @@
import { spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import path from 'node:path'
import { execa } from 'execa'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
@@ -87,8 +86,9 @@ export class RunnerShell {
const log = await this.files.createWriter(logPath)
try {
const windows = process.platform === 'win32'
let args = windows ? ['/d', '/s', '/c', message.command] : ['-c', message.command]
let executable = this.environment.shell
let args: string[] = []
let executable = message.command
let shell: string | false = this.environment.shell
let env = commandEnv(message.env)
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
@@ -103,13 +103,14 @@ export class RunnerShell {
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
executable,
this.environment.shell,
undefined,
signal,
this.files.cwd,
{ commandId: message.executionId, commandText: message.command },
)
;[executable, ...args] = wrapped.argv
shell = false
if (windows) {
// SRT's broker starts a fresh sandbox-user environment. Explicit skill
// values belong in its child overlay, never in the broker's startup env.
@@ -124,120 +125,83 @@ export class RunnerShell {
} else env = commandEnv()
}
if (signal.aborted) return { ...result, aborted: true }
const nativeWindows = windows && !this.srtPath
const child = spawn(
nativeWindows ? message.command : executable,
nativeWindows ? [] : args,
{
cwd: this.files.cwd,
env,
detached: !windows,
windowsHide: true,
shell: nativeWindows ? executable : false,
stdio: ['ignore', 'pipe', 'pipe'],
},
)
// Bun can change child.pid after exit; retain the actual process group ID.
const processGroupId = child.pid
let termination: Promise<void> | undefined
const kill = () => {
if (!processGroupId || processGroupId <= 0) return
if (windows) {
if (child.exitCode !== null || child.signalCode !== null) return
termination ??= new Promise<void>((resolve) => {
const taskkill = spawn(
path.win32.join(
process.env.SystemRoot ?? 'C:\\Windows',
'System32',
'taskkill.exe',
),
['/pid', String(processGroupId), '/t', '/f'],
{ windowsHide: true, stdio: 'ignore', env: commandEnv(), timeout: 5000 },
)
taskkill.once('error', () => {
child.kill('SIGKILL')
resolve()
})
taskkill.once('close', (code) => {
if (code !== 0) child.kill('SIGKILL')
resolve()
})
})
return
}
try {
process.kill(-processGroupId, 'SIGKILL')
} catch (error) {
if (!(
error instanceof Error &&
'code' in error &&
(error.code === 'ESRCH' ||
(error.code === 'EPERM' && (child.exitCode !== null || child.signalCode !== null)))
))
throw error
}
}
const onAbort = () => {
result.aborted = true
kill()
}
signal.addEventListener('abort', onAbort, { once: true })
const timer = setTimeout(() => {
result.timedOut = true
kill()
}, timeout * 1000)
const deadline = Date.now() + Math.ceil(timeout * 1000)
const child = execa(executable, args, {
cwd: this.files.cwd,
env,
extendEnv: false,
shell,
stdin: 'ignore',
buffer: false,
reject: false,
stripFinalNewline: false,
verbose: 'none',
windowsHide: true,
killDescendants: true,
killSignal: 'SIGKILL',
cancelSignal: signal,
timeout: Math.ceil(timeout * 1000),
})
let bytes = 0
let writes = Promise.resolve()
let drainTimer: ReturnType<typeof setTimeout> | undefined
let drainExpired = false
let exitedWithinDeadline = false
child.nodeChildProcess.once('exit', (exitCode) => {
exitedWithinDeadline = exitCode !== null && Date.now() < deadline
// Execa cleans up descendants where the OS still permits it. Bound
// draining if a background child keeps inherited output pipes open.
child.kill('SIGKILL')
drainTimer = setTimeout(() => {
drainExpired = true
child.stdout.destroy()
child.stderr.destroy()
}, 1000)
})
try {
await new Promise<void>((resolve, reject) => {
child.once('error', reject)
child.once('exit', (code, exitSignal) => {
clearTimeout(timer)
result.exitCode = code
result.signal = exitSignal
if (nativeWindows) {
// A background process can inherit pipes after cmd.exe exits.
// Plain Windows execution has no job object; bound output draining.
drainTimer = setTimeout(() => {
child.stdout.destroy()
child.stderr.destroy()
}, 1000)
} else kill()
})
child.once('close', () => resolve())
for (const stream of ['stdout', 'stderr'] as const) {
child[stream].setEncoding('utf8')
child[stream].on('error', reject)
child[stream].on('data', (data: string) => {
const readers = (['stdout', 'stderr'] as const).map(async (stream) => {
child[stream].setEncoding('utf8')
try {
for await (const data of child[stream]) {
bytes += Buffer.byteLength(data)
if (bytes > MAX_OUTPUT_BYTES) {
if (!result.error) {
result.error = 'Command exceeded the 64 MiB output limit.'
kill()
}
return
}
child[stream].pause()
writes = writes
.then(async () => {
await log.write(data)
output(stream, data)
child[stream].resume()
})
.catch(reject)
})
if (bytes > MAX_OUTPUT_BYTES)
throw new Error('Command exceeded the 64 MiB output limit.')
await (writes = writes.then(async () => {
await log.write(data)
output(stream, data)
}))
}
} catch (error) {
if (
drainExpired &&
error instanceof Error &&
'code' in error &&
error.code === 'ERR_STREAM_PREMATURE_CLOSE'
)
return
result.error ??= error instanceof Error ? error.message : 'Output streaming failed.'
child.kill('SIGKILL')
}
if (signal.aborted) onAbort()
})
const [completed] = await Promise.all([child, Promise.all(readers)])
await writes
result.exitCode = completed.exitCode ?? null
result.signal = completed.signal ?? null
// Execa's timeout includes stream draining. Report the command's
// runtime, so a timely exit does not become a timeout while draining.
result.timedOut = completed.timedOut && !exitedWithinDeadline
result.aborted = completed.isCanceled
if (
completed.failed &&
completed.exitCode === undefined &&
!result.timedOut &&
!result.aborted &&
!completed.signal
)
result.error = `Command execution failed (${completed.code ?? 'unknown error'}).`
result.fullOutputPath = logPath
} finally {
clearTimeout(timer)
clearTimeout(drainTimer)
signal.removeEventListener('abort', onAbort)
kill()
await termination
}
} finally {
await log.close()
-122
View File
@@ -1,122 +0,0 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { PassThrough } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
vi.mock('node:child_process', async (importOriginal) => ({
...(await importOriginal<typeof import('node:child_process')>()),
spawn: vi.fn(),
}))
class CommandProcess extends EventEmitter {
pid = 12345
exitCode: number | null = null
signalCode: NodeJS.Signals | null = null
stdout = new PassThrough()
stderr = new PassThrough()
kill = vi.fn(() => {
this.finish(null, 'SIGKILL')
return true
})
constructor() {
super()
let closed = 0
for (const stream of [this.stdout, this.stderr])
stream.once('close', () => {
if (++closed === 2) this.emit('close')
})
}
finish(code: number | null, signal: NodeJS.Signals | null = null, keepPipes = false) {
this.exitCode = code
this.signalCode = signal
this.emit('exit', code, signal)
if (!keepPipes) {
this.stdout.end()
this.stderr.end()
}
}
}
describe('Windows runner process lifecycle', () => {
let cwd: string
let shell: RunnerShell
let child: CommandProcess
let killedWhileRunning: boolean
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-windows-shell-'))
vi.stubGlobal('process', { ...process, platform: 'win32' })
vi.stubEnv('SystemRoot', 'C:\\Windows')
child = new CommandProcess()
killedWhileRunning = false
vi.mocked(spawn).mockImplementation((executable) => {
if (String(executable).endsWith('taskkill.exe')) {
killedWhileRunning = child.exitCode === null && child.signalCode === null
const killer = new EventEmitter()
setImmediate(() => {
child.finish(null, 'SIGKILL')
killer.emit('close', 0)
})
return killer as ChildProcess
}
return child as unknown as ChildProcess
})
shell = new RunnerShell(new RunnerFiles(cwd))
})
afterEach(async () => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.clearAllMocks()
await rm(cwd, { recursive: true, force: true })
})
const request = { type: 'exec.start' as const, executionId: 'windows', command: 'echo hello' }
it('uses Node shell launching and drains inherited pipes after the root exits', async () => {
const running = shell.run(
{ ...request, timeoutSec: 0.2 },
new AbortController().signal,
() => {},
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(spawn).toHaveBeenCalledWith(
'echo hello',
[],
expect.objectContaining({
shell: 'C:\\Windows\\System32\\cmd.exe',
detached: false,
}),
)
child.stdout.write('before exit')
child.finish(7, null, true)
const result = await running
expect(result).toMatchObject({ exitCode: 7, timedOut: false, aborted: false })
expect(child.stdout.destroyed && child.stderr.destroyed).toBe(true)
expect(await readFile(path.join(cwd, result.fullOutputPath!), 'utf8')).toBe('before exit')
expect(spawn).toHaveBeenCalledTimes(1)
})
it.each(['timeout', 'cancel'] as const)(
'terminates a live Windows process tree on %s',
async (kind) => {
const controller = new AbortController()
const running = shell.run({ ...request, timeoutSec: 0.2 }, controller.signal, () => {})
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
if (kind === 'cancel') controller.abort()
const result = await running
expect(result).toMatchObject({ timedOut: kind === 'timeout', aborted: kind === 'cancel' })
expect(killedWhileRunning).toBe(true)
expect(spawn).toHaveBeenCalledWith(
'C:\\Windows\\System32\\taskkill.exe',
['/pid', '12345', '/t', '/f'],
expect.objectContaining({ timeout: 5000, windowsHide: true }),
)
},
)
})