feat(cli): bundle SRT and use platform-native runner shells

This commit is contained in:
yiling
2026-11-17 23:08:20 +08:00
parent 07e69717e5
commit 17f14390be
31 changed files with 787 additions and 134 deletions
+19 -4
View File
@@ -88,7 +88,7 @@ export SHUMAI_ALLOW_DELETE="true"
## Agent runner
Create a runner in **Settings → Agent Runners** and copy its one-time key. On a macOS or Linux machine with `/bin/bash`, start it in an existing dedicated workspace:
Create a runner in **Settings → Agent Runners** and copy its one-time key. On macOS, Linux, or Windows, start it in an existing dedicated workspace:
```sh
export SHUMAI_API_SERVER="https://shumai.example.com"
@@ -96,16 +96,31 @@ export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
For Windows PowerShell:
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
Use `--url` or `--key` to override those variables. A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
Bash runs with the local user's permissions unless SRT is requested. Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites separately, then pass its native JSON settings:
Commands use `/bin/sh` on macOS/Linux and `cmd.exe` on Windows. The agent receives the runner's OS and shell so it can use the appropriate syntax. Commands run with the local user's permissions unless SRT is requested.
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled with the CLI. Install its platform prerequisites (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then pass its native JSON settings:
```sh
npm install -g @anthropic-ai/sandbox-runtime
shumai-cli runner start --srt sandbox.json
```
SRT settings are snapshotted at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only Bash and its children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The `runner start` command currently supports macOS and Linux; other CLI commands remain available on Windows.
Windows sandboxing uses SRT's alpha Windows support. Run its one-time setup before starting a sandboxed runner (it requests administrator permission):
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT settings are read and validated at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only shell commands and their children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The shared SRT runtime is cleaned up when the runner stops.
See [Agent Runners](../../docs/using-shumai/agent-sandbox.mdx) for configuration, Docker usage, limits, and security boundaries.
+1
View File
@@ -7,6 +7,7 @@
"shumai-cli": "./src/index.ts"
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.82",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
+2 -5
View File
@@ -46,16 +46,13 @@ export function createProgram(options: ProgramOptions = {}): Command {
program
.command('runner')
.description('Connect a local bash runner to Shumai.')
.description('Connect a local command runner to Shumai.')
.command('start')
.description('Run in the foreground using a key created in Settings → Agent Runners.')
.option('--url <url>', 'Shumai server URL (or SHUMAI_API_SERVER).')
.option('--key <key>', 'Runner key (prefer SHUMAI_RUNNER_KEY to avoid shell history).')
.option('--cwd <directory>', 'Runner workspace directory (defaults to the current directory).')
.option(
'--srt <file>',
'Wrap bash commands with locally installed srt using this JSON settings file.',
)
.option('--srt <file>', 'Sandbox commands with bundled SRT using this JSON settings file.')
.action(startRunner)
program
+6
View File
@@ -72,6 +72,12 @@ describe('runner WebSocket client', () => {
const send = (message: unknown) => socket.send(JSON.stringify(message))
it('responds to heartbeat, executes a command once and streams byte offsets', async () => {
expect(messages).toContainEqual(
expect.objectContaining({
type: 'reconcile',
environment: { platform: process.platform, shell: '/bin/sh' },
}),
)
send({ type: 'ping', ts: 123 })
const command = {
type: 'exec.start',
+4
View File
@@ -150,6 +150,7 @@ export class RunnerClient {
}
this.send({
type: 'reconcile',
environment: this.shell.environment,
activeExecutions: [...this.executions]
.filter(([id, execution]) => expected.has(id) && !execution.result)
.map(([executionId, execution]) => ({ executionId, nextOffset: execution.offset })),
@@ -290,6 +291,8 @@ export class RunnerClient {
export async function startRunner(options: RunnerOptions) {
const config = await resolveRunnerConfig(options)
// SRT resolves relative policy paths against the runner workspace.
process.chdir(config.cwd)
const files = new RunnerFiles(config.cwd)
const shell = new RunnerShell(files, config.srt)
await shell.initialize()
@@ -303,5 +306,6 @@ export async function startRunner(options: RunnerOptions) {
} finally {
process.removeListener('SIGINT', shutdown)
process.removeListener('SIGTERM', shutdown)
await shell.close()
}
}
+21 -1
View File
@@ -1,9 +1,29 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { commandEnv, resolveRunnerConfig } from './config'
import { commandEnv, resolveRunnerConfig, runnerShell } from './config'
afterEach(() => vi.unstubAllEnvs())
describe('runner configuration', () => {
it('uses the platform shell without requiring Bash on Windows', () => {
vi.stubEnv('SystemRoot', 'D:\\Windows')
expect(runnerShell('win32')).toBe('D:\\Windows\\System32\\cmd.exe')
expect(runnerShell('linux')).toBe('/bin/sh')
expect(runnerShell('darwin')).toBe('/bin/sh')
})
it('preserves Windows OS settings, normalizes explicit overrides, and excludes credentials', () => {
vi.stubEnv('Path', 'C:\\Windows\\System32')
vi.stubEnv('SystemRoot', 'C:\\Windows')
vi.stubEnv('USERPROFILE', 'C:\\Users\\runner')
const env = commandEnv({ PATH: 'C:\\tools', ['shumai_runner_key']: 'secret' })
expect(env).toMatchObject({
PATH: 'C:\\tools',
SystemRoot: 'C:\\Windows',
USERPROFILE: 'C:\\Users\\runner',
})
expect(env).not.toHaveProperty('Path')
expect(env).not.toHaveProperty('shumai_runner_key')
})
it('uses a dedicated runner key and preserves a server path prefix', async () => {
vi.stubEnv('SHUMAI_API_SERVER', 'https://example.com/shumai/')
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
+19 -6
View File
@@ -41,21 +41,34 @@ export async function resolveRunnerConfig(options: RunnerOptions) {
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/runners/ws`
const cwd = await realpath(path.resolve(options.cwd ?? process.cwd()))
if (!(await stat(cwd)).isDirectory()) throw new CliError('Runner workspace must be a directory.')
if (process.platform === 'win32')
throw new CliError('Runner execution requires macOS or Linux with bash.')
return { url, key: key.trim(), cwd, srt: options.srt ? path.resolve(options.srt) : undefined }
}
export function runnerShell(platform = process.platform): string {
return platform === 'win32'
? path.win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe')
: '/bin/sh'
}
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
export function commandEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
export function commandEnv(extra: Record<string, string> = {}, inherit = true): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {}
for (const [key, value] of Object.entries(process.env)) {
if (/^(PATH|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|LC_.*)$/.test(key)) env[key] = value
for (const [key, value] of Object.entries(inherit ? process.env : {})) {
if (
/^(PATH|PATHEXT|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|TEMP|TMP|SYSTEMROOT|SYSTEMDRIVE|COMSPEC|USERPROFILE|USERNAME|APPDATA|LOCALAPPDATA|PROGRAMDATA|PROGRAMFILES|PROGRAMFILES\(X86\)|LC_.*)$/i.test(
key,
)
)
env[key] = value
}
for (const [key, value] of Object.entries(extra)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Invalid skill environment variable name.')
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key)) continue
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key.toUpperCase())) continue
// Windows treats environment names as case-insensitive.
for (const existing of Object.keys(env)) {
if (existing.toUpperCase() === key.toUpperCase()) delete env[existing]
}
env[key] = value
}
return env
-17
View File
@@ -1,17 +0,0 @@
import { constants } from 'node:fs'
import { access, realpath } from 'node:fs/promises'
import path from 'node:path'
export async function findExecutable(name: string): Promise<string> {
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
if (!directory) continue
const candidate = path.resolve(directory, name)
try {
await access(candidate, constants.X_OK)
return await realpath(candidate)
} catch {
// Try the next PATH entry.
}
}
throw new Error(`${name} is required on the runner machine and must be available on PATH.`)
}
+7
View File
@@ -117,6 +117,13 @@ describe('runner workspace file transfers', () => {
'.pi//file',
'.pi/a:b',
'.pi/a\0b',
'.pi/.. /outside',
'.pi/folder./file',
'.pi/CON.txt',
'.pi/nul .txt',
'.pi/COM1',
'.pi/lpt¹.log',
'.pi/CONOUT$',
])('rejects unsafe protocol path %s', async (srcPath) => {
expect(
await files.handle({ type: 'file.stat', executionId: 'unsafe', srcPath }, signal()),
+9 -1
View File
@@ -23,7 +23,15 @@ function pathParts(value: string): string[] {
if (
value.includes('\\') ||
value.includes('\0') ||
parts.some((part) => !part || part === '.' || part === '..' || part.includes(':'))
parts.some(
(part) =>
!part ||
part === '.' ||
part === '..' ||
part.includes(':') ||
/[. ]$/.test(part) ||
/^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?: *\.|$)/i.test(part),
)
)
throw new Error('Invalid workspace path.')
return parts
+92 -26
View File
@@ -2,6 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
@@ -11,8 +12,16 @@ describe('runner bash execution', () => {
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-shell-test-'))
shell = new RunnerShell(new RunnerFiles(cwd))
vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
vi.spyOn(SandboxManager, 'reset').mockResolvedValue()
vi.spyOn(SandboxManager, 'wrapWithSandboxArgv').mockImplementation(async (command) => ({
argv: ['/bin/sh', '-c', command],
env: process.env,
}))
})
afterEach(async () => {
await shell.close()
vi.restoreAllMocks()
vi.unstubAllEnvs()
await rm(cwd, { recursive: true, force: true })
})
@@ -117,47 +126,45 @@ describe('runner bash execution', () => {
it('uses the exact SRT JSON snapshot and validates SRT before connecting', async () => {
const settings = path.join(cwd, 'sandbox.json')
const capture = path.join(cwd, 'captured.json')
const json = JSON.stringify({
network: { allowedDomains: [] },
filesystem: { allowWrite: ['.pi'] },
})
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
const json = JSON.stringify(config)
await writeFile(settings, json)
await writeFile(
path.join(cwd, 'srt'),
`#!/bin/bash\ncp "$2" '${capture}'\nshift 3\nexec "$@"\n`,
{ mode: 0o700 },
)
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
vi.stubEnv('PATH', '')
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
await writeFile(settings, '{}')
expect(
await shell.run(request('echo sandboxed'), new AbortController().signal, () => {}),
).toMatchObject({ exitCode: 0 })
expect(await readFile(capture, 'utf8')).toBe(json)
vi.stubEnv('PATH', '/missing-srt')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
'required on the runner machine',
expect(SandboxManager.initialize).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining(config),
)
expect(SandboxManager.wrapWithSandboxArgv).toHaveBeenCalledWith(
expect.stringContaining('echo sandboxed'),
'/bin/sh',
undefined,
expect.any(AbortSignal),
cwd,
{ commandId: 'test', commandText: 'echo sandboxed' },
)
expect(SandboxManager.reset).not.toHaveBeenCalled()
})
it('keeps skill PATH and Node startup settings out of the SRT launcher', async () => {
const settings = path.join(cwd, 'sandbox.json')
const marker = path.join(cwd, 'injected')
const evil = path.join(cwd, 'evil.cjs')
await writeFile(settings, '{}')
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
await writeFile(
path.join(cwd, 'srt'),
`#!/usr/bin/env node
const {spawnSync} = require('node:child_process');
const result = spawnSync(process.argv[5], process.argv.slice(6), {stdio: 'inherit'});
process.exit(result.status ?? 1);
`,
{ mode: 0o700 },
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const result = await shell.run(
@@ -172,6 +179,62 @@ process.exit(result.status ?? 1);
await expect(readFile(marker)).rejects.toThrow()
})
it('initializes one sandbox for parallel commands and resets only at shutdown', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const value = "quoted ' value\n$(echo should-not-expand)"
let output = ''
const results = await Promise.all(
['one', 'two'].map((id) =>
shell.run(
{ ...request('printf "%s" "$SKILL_TOKEN"', id), env: { SKILL_TOKEN: value } },
new AbortController().signal,
(_stream, data) => {
output += data
},
),
),
)
expect(results.every((result) => result.exitCode === 0)).toBe(true)
expect(output).toBe(value.repeat(2))
expect(SandboxManager.initialize).toHaveBeenCalledTimes(1)
expect(SandboxManager.reset).not.toHaveBeenCalled()
await shell.close()
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
})
it('fails startup and cleans up if sandbox initialization or execution fails', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
vi.mocked(SandboxManager.initialize).mockRejectedValueOnce(
new Error('Run windows-install first'),
)
await expect(shell.initialize()).rejects.toThrow('windows-install')
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
expect(
await shell.run(request('echo unsafe'), new AbortController().signal, () => {}),
).toHaveProperty('error', 'SRT has not been initialized.')
vi.mocked(SandboxManager.wrapWithSandboxArgv).mockRejectedValueOnce(
new Error('sandbox unavailable'),
)
await expect(shell.initialize()).rejects.toThrow('SRT preflight failed: sandbox unavailable')
})
it('fails closed for missing or malformed SRT settings', async () => {
const settings = path.join(cwd, 'sandbox.json')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
@@ -179,7 +242,10 @@ process.exit(result.status ?? 1);
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
await writeFile(settings, '[]')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
'JSON object',
/object/,
)
await writeFile(settings, JSON.stringify({ network: { allowedDomains: 42 } }))
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
})
+137 -46
View File
@@ -1,19 +1,27 @@
import { spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { RunnerExecResultMessage, RunnerExecStartMessage } from '@shumai/dtos'
import { commandEnv } from './config'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
type RunnerExecResultMessage,
type RunnerExecStartMessage,
} from '@shumai/dtos'
import { commandEnv, runnerShell } from './config'
import { RunnerFiles } from './files'
import { findExecutable } from './executable'
import { loadSandbox } from './srt'
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
const MAX_TIMEOUT_SEC = 3600
export class RunnerShell {
private settings?: string
private srtExecutable?: string
readonly environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: runnerShell(),
})
private sandbox?: Awaited<ReturnType<typeof loadSandbox>>
private initialized = false
private active = 0
constructor(
private readonly files: RunnerFiles,
@@ -22,24 +30,38 @@ export class RunnerShell {
async initialize() {
if (!this.srtPath) return
// Snapshot once: a command editing the source config cannot weaken later commands.
this.settings = await readFile(this.srtPath, 'utf8')
const parsed: unknown = JSON.parse(this.settings)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
throw new Error('SRT settings must be a JSON object.')
this.srtExecutable = await findExecutable('srt')
let diagnostic = ''
const probe = await this.run(
{ type: 'exec.start', executionId: randomUUID(), command: 'true', timeoutSec: 15 },
new AbortController().signal,
(_stream, data) => {
diagnostic = (diagnostic + data).slice(-4096)
},
)
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
throw new Error(
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
// Read and validate once; commands cannot weaken the policy by editing the file.
this.sandbox = await loadSandbox(this.srtPath)
try {
await SandboxManager.initialize(this.sandbox.config)
this.initialized = true
let diagnostic = ''
const probe = await this.run(
{ type: 'exec.start', executionId: randomUUID(), command: 'exit 0', timeoutSec: 15 },
new AbortController().signal,
(_stream, data) => {
diagnostic = (diagnostic + data).slice(-4096)
},
)
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
throw new Error(
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
)
} catch (error) {
await this.close()
throw error
}
}
async close() {
if (!this.sandbox) return
try {
await SandboxManager.reset()
} finally {
await this.sandbox.cleanup()
this.sandbox = undefined
this.initialized = false
}
}
async run(
@@ -55,7 +77,7 @@ export class RunnerShell {
timedOut: false,
aborted: false,
}
let settingsDir: string | undefined
if (this.srtPath) this.active++
try {
if (signal.aborted) return { ...result, aborted: true }
const timeout = message.timeoutSec ?? 120
@@ -64,31 +86,85 @@ export class RunnerShell {
const logPath = `.pi/logs/bash-${message.executionId}.log`
const log = await this.files.createWriter(logPath)
try {
const args = ['--noprofile', '--norc', '-c', message.command]
let executable = '/bin/bash'
const windows = process.platform === 'win32'
let args = windows ? ['/d', '/s', '/c', message.command] : ['-c', message.command]
let executable = this.environment.shell
let env = commandEnv(message.env)
if (this.srtPath && !this.srtExecutable) throw new Error('SRT has not been initialized.')
if (this.settings !== undefined) {
settingsDir = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
const settingsFile = path.join(settingsDir, 'settings.json')
await writeFile(settingsFile, this.settings, { mode: 0o600 })
executable = this.srtExecutable!
const variables = Object.entries(env)
.filter((entry): entry is [string, string] => entry[1] !== undefined)
.map(([key, value]) => `${key}=${value}`)
args.unshift('--settings', settingsFile, '--', '/usr/bin/env', ...variables, '/bin/bash')
env = commandEnv()
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
const skillEnv = commandEnv(message.env, false)
const command = windows
? message.command
: [
...Object.entries(skillEnv).map(
([key, value]) => `export ${key}='${value!.replaceAll("'", "'\\''")}'`,
),
message.command,
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
executable,
undefined,
signal,
this.files.cwd,
{ commandId: message.executionId, commandText: message.command },
)
;[executable, ...args] = wrapped.argv
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.
const separator = args.indexOf('--')
if (separator < 0) throw new Error('SRT returned an invalid Windows launch command.')
args.splice(
separator,
0,
...Object.entries(skillEnv).flatMap(([key, value]) => ['--env', `${key}=${value}`]),
)
env = wrapped.env
} else env = commandEnv()
}
const child = spawn(executable, args, {
cwd: this.files.cwd,
env,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
})
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) {
@@ -112,13 +188,22 @@ export class RunnerShell {
}, timeout * 1000)
let bytes = 0
let writes = Promise.resolve()
let drainTimer: ReturnType<typeof setTimeout> | undefined
try {
await new Promise<void>((resolve, reject) => {
child.once('error', reject)
child.once('exit', (code, exitSignal) => {
clearTimeout(timer)
result.exitCode = code
result.signal = exitSignal
kill()
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) {
@@ -149,16 +234,22 @@ export class RunnerShell {
result.fullOutputPath = logPath
} finally {
clearTimeout(timer)
clearTimeout(drainTimer)
signal.removeEventListener('abort', onAbort)
kill()
await termination
}
} finally {
await log.close()
}
} catch (error) {
result.aborted = signal.aborted
result.error = error instanceof Error ? error.message : 'Command execution failed.'
} finally {
if (settingsDir) await rm(settingsDir, { recursive: true, force: true })
// SRT's temporary mount resources are shared: clean up only after every
// concurrent command has finished, and keep the proxies until shutdown.
if (this.srtPath && --this.active === 0 && this.initialized)
SandboxManager.cleanupAfterCommand()
}
return result
}
+122
View File
@@ -0,0 +1,122 @@
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 }),
)
},
)
})
+2
View File
@@ -0,0 +1,2 @@
// Release builds embed SRT's native helpers through scripts/srt-bundle.ts.
export const bundledSrtVendor: Record<string, string> | undefined = undefined
+59
View File
@@ -0,0 +1,59 @@
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { loadSandbox } from './srt'
describe('runner SRT configuration', () => {
let directory: string
let settings: string
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
beforeEach(async () => {
directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-settings-'))
settings = path.join(directory, 'sandbox.json')
})
afterEach(() => rm(directory, { recursive: true, force: true }))
it('validates upstream settings, supplies packaged helpers, and removes them on cleanup', async () => {
await writeFile(settings, JSON.stringify(config))
const sandbox = await loadSandbox(settings)
const helper = sandbox.config.javaAgentJarPath!
expect(sandbox.config).toMatchObject(config)
expect((await readFile(helper)).subarray(0, 2).toString()).toBe('PK')
if (process.platform === 'linux')
expect(await stat(sandbox.config.seccomp!.applyPath!)).toHaveProperty(
'size',
expect.any(Number),
)
if (process.platform === 'win32')
expect(await stat(sandbox.config.windows!.srtWin!.path!)).toHaveProperty(
'size',
expect.any(Number),
)
await sandbox.cleanup()
await expect(stat(helper)).rejects.toThrow()
})
it('preserves explicit upstream helper paths', async () => {
await writeFile(
settings,
JSON.stringify({
...config,
javaAgentJarPath: '/custom/proxy.jar',
seccomp: { applyPath: '/custom/seccomp' },
windows: { srtWin: { path: 'C:\\custom\\srt-win.exe' } },
}),
)
const sandbox = await loadSandbox(settings)
try {
expect(sandbox.config.javaAgentJarPath).toBe('/custom/proxy.jar')
expect(sandbox.config.seccomp?.applyPath).toBe('/custom/seccomp')
expect(sandbox.config.windows?.srtWin?.path).toBe('C:\\custom\\srt-win.exe')
} finally {
await sandbox.cleanup()
}
})
})
+59
View File
@@ -0,0 +1,59 @@
import { createRequire } from 'node:module'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import {
SandboxRuntimeConfigSchema,
type SandboxRuntimeConfig,
} from '@anthropic-ai/sandbox-runtime'
import { bundledSrtVendor } from './srt-vendor'
/** Load the upstream JSON format and supply the helpers bundled with this CLI. */
export async function loadSandbox(configPath: string) {
const config = SandboxRuntimeConfigSchema.parse(JSON.parse(await readFile(configPath, 'utf8')))
const directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
const cleanup = () => rm(directory, { recursive: true, force: true })
const asset = async (name: string) => {
const encoded = bundledSrtVendor?.[name]
const bytes =
encoded !== undefined
? Buffer.from(encoded, 'base64')
: await readFile(
path.join(
path.dirname(
createRequire(import.meta.url).resolve(
'@anthropic-ai/sandbox-runtime/package.json',
),
),
'vendor',
name,
),
)
const destination = path.join(directory, path.basename(name))
await writeFile(destination, bytes, { mode: 0o500 })
return destination
}
try {
if (process.platform === 'linux' && !config.seccomp?.applyPath) {
config.seccomp = {
...config.seccomp,
applyPath: await asset(`seccomp/${process.arch}/apply-seccomp`),
}
}
if (process.platform === 'win32' && !config.windows?.srtWin?.path) {
config.windows = {
...config.windows,
srtWin: {
...config.windows?.srtWin,
path: await asset(`srt-win/${process.arch}/srt-win.exe`),
},
}
}
if (!config.javaAgentJarPath)
config.javaAgentJarPath = await asset('java-proxy-agent/srt-proxy-agent.jar')
return { config: config satisfies SandboxRuntimeConfig, cleanup }
} catch (error) {
await cleanup()
throw error
}
}