mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 09:36:58 +00:00
feat(cli): add runner start with bundled SRT sandboxing (#535)
* refactor(agent): expose runner bash without skill gating * feat(cli): add runner start with optional SRT sandboxing * refactor(cli): remove runner Python dependency * feat(cli): bundle SRT and use platform-native runner shells * refactor(cli): delegate runner processes to Execa
This commit is contained in:
@@ -86,6 +86,44 @@ export SHUMAI_ALLOW_DELETE="true"
|
||||
|
||||
---
|
||||
|
||||
## Agent runner
|
||||
|
||||
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"
|
||||
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.
|
||||
|
||||
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
|
||||
shumai-cli runner start --srt sandbox.json
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Usage
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
@@ -7,13 +7,23 @@
|
||||
"shumai-cli": "./src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.82",
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@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",
|
||||
"yauzl": "3.4.0",
|
||||
"zod": "4.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yauzl": "3.4.0",
|
||||
"adm-zip": "0.6.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { cliExtensions } from './operations/extensions'
|
||||
import { registerOperationCommands } from './operations/generate'
|
||||
import type { Output } from './operations/render'
|
||||
import { version } from '../package.json'
|
||||
import { startRunner } from './runner/client'
|
||||
|
||||
export interface ProgramOptions {
|
||||
callOperation?: CallOperation
|
||||
@@ -43,6 +44,17 @@ export function createProgram(options: ProgramOptions = {}): Command {
|
||||
extensions: cliExtensions,
|
||||
})
|
||||
|
||||
program
|
||||
.command('runner')
|
||||
.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>', 'Sandbox commands with bundled SRT using this JSON settings file.')
|
||||
.action(startRunner)
|
||||
|
||||
program
|
||||
.command('upload')
|
||||
.description('Upload a local file or folder to a parent folder.')
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runnerToServerMessageSchema, type RunnerToServerMessage } from '@shumai/dtos'
|
||||
import { RunnerClient } from './client'
|
||||
import { RunnerFiles } from './files'
|
||||
import { RunnerShell } from './shell'
|
||||
|
||||
describe('runner WebSocket client', () => {
|
||||
let cwd: string
|
||||
let server: WebSocketServer
|
||||
let runner: RunnerClient
|
||||
let running: Promise<void>
|
||||
let socket: WebSocket
|
||||
let messages: RunnerToServerMessage[]
|
||||
let welcomeInFlight: string[]
|
||||
let connections: number
|
||||
beforeEach(async () => {
|
||||
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-client-test-'))
|
||||
messages = []
|
||||
welcomeInFlight = []
|
||||
connections = 0
|
||||
server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve))
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') throw new Error('No WebSocket address')
|
||||
server.on('connection', (connection, request) => {
|
||||
expect(request.headers.authorization).toBe('Bearer runner-key')
|
||||
socket = connection
|
||||
connections++
|
||||
connection.on('message', (raw) =>
|
||||
messages.push(runnerToServerMessageSchema.parse(JSON.parse(raw.toString()))),
|
||||
)
|
||||
connection.send(
|
||||
JSON.stringify({
|
||||
type: 'welcome',
|
||||
runnerId: 'runner',
|
||||
runnerName: 'Test',
|
||||
serverTime: Date.now(),
|
||||
inFlightExecutionIds: welcomeInFlight,
|
||||
}),
|
||||
)
|
||||
})
|
||||
const files = new RunnerFiles(cwd)
|
||||
runner = new RunnerClient(
|
||||
{
|
||||
url: new URL(`ws://127.0.0.1:${address.port}/api/runners/ws`),
|
||||
key: 'runner-key',
|
||||
cwd,
|
||||
srt: undefined,
|
||||
},
|
||||
files,
|
||||
new RunnerShell(files),
|
||||
() => {},
|
||||
)
|
||||
running = runner.run()
|
||||
// Attach an error handler immediately, including for tests exercising terminal errors.
|
||||
void running.catch(() => {})
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
|
||||
)
|
||||
})
|
||||
afterEach(async () => {
|
||||
runner.stop()
|
||||
await running.catch(() => {})
|
||||
for (const connection of server.clients) connection.terminate()
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()))
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
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',
|
||||
executionId: 'one',
|
||||
command: 'printf "世界"; printf "error" >&2',
|
||||
}
|
||||
send(command)
|
||||
send(command)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
|
||||
)
|
||||
expect(messages).toContainEqual({ type: 'pong', ts: 123 })
|
||||
expect(messages.filter((message) => message.type === 'exec.result')).toHaveLength(1)
|
||||
const chunks = messages.filter((message) => message.type === 'exec.output')
|
||||
expect(chunks.map((chunk) => chunk.data).join('')).toContain('世界')
|
||||
let offset = 0
|
||||
for (const chunk of chunks) {
|
||||
expect(chunk.offset).toBe(offset)
|
||||
offset += Buffer.byteLength(chunk.data)
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels an active command through the protocol', async () => {
|
||||
send({ type: 'exec.start', executionId: 'cancel', command: 'echo ready; sleep 30' })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
|
||||
)
|
||||
send({ type: 'exec.cancel', executionId: 'cancel' })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages).toContainEqual(
|
||||
expect.objectContaining({ type: 'exec.result', executionId: 'cancel', aborted: true }),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('reconnects and replays output before completing an in-flight command', async () => {
|
||||
send({
|
||||
type: 'exec.start',
|
||||
executionId: 'reconnect',
|
||||
command: 'echo before; sleep 0.2; echo after',
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
|
||||
)
|
||||
welcomeInFlight = ['reconnect']
|
||||
socket.terminate()
|
||||
messages = []
|
||||
await vi.waitFor(() => expect(connections).toBe(2), { timeout: 5000 })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
|
||||
)
|
||||
const reconciliation = messages.findIndex((message) => message.type === 'reconcile')
|
||||
expect(
|
||||
messages
|
||||
.slice(0, reconciliation)
|
||||
.filter((message) => message.type === 'exec.output')
|
||||
.map((message) => message.data)
|
||||
.join(''),
|
||||
).toContain('after')
|
||||
expect(messages[reconciliation]).toMatchObject({
|
||||
completedExecutions: [expect.objectContaining({ executionId: 'reconnect', exitCode: 0 })],
|
||||
})
|
||||
})
|
||||
|
||||
it('handles file requests and returns a cached result for a duplicate request', async () => {
|
||||
const request = { type: 'file.stat', executionId: 'stat', srcPath: '.pi/missing' }
|
||||
send(request)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
|
||||
)
|
||||
send(request)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.filter((message) => message.type === 'file.stat.result')).toHaveLength(2),
|
||||
)
|
||||
expect(messages.at(-1)).toMatchObject({ ok: true, exists: false })
|
||||
})
|
||||
|
||||
it('stops instead of reconnecting when the runner key is revoked', async () => {
|
||||
socket.close(1008, 'revoked')
|
||||
await expect(running).rejects.toThrow('revoked')
|
||||
expect(connections).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects invalid messages and path-like execution IDs', async () => {
|
||||
send({ type: 'exec.start', executionId: '../escape', command: 'echo unsafe' })
|
||||
await expect(running).rejects.toThrow('invalid runner protocol')
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,311 @@
|
||||
import WebSocket from 'ws'
|
||||
import { setTimeout as delay } from 'node:timers/promises'
|
||||
import {
|
||||
serverToRunnerMessageSchema,
|
||||
type RunnerExecOutputMessage,
|
||||
type RunnerExecResultMessage,
|
||||
type RunnerToServerMessage,
|
||||
type ServerToRunnerMessage,
|
||||
} from '@shumai/dtos'
|
||||
import { CliError } from '../operations/errors'
|
||||
import { resolveRunnerConfig, type RunnerOptions } from './config'
|
||||
import { RunnerFiles, type FileMessage } from './files'
|
||||
import { RunnerShell } from './shell'
|
||||
|
||||
const MAX_REPLAY_BYTES = 1024 * 1024
|
||||
const MAX_COMPLETED = 16
|
||||
const MAX_ACTIVE = 8
|
||||
|
||||
interface Execution {
|
||||
controller: AbortController
|
||||
chunks: RunnerExecOutputMessage[]
|
||||
bytes: number
|
||||
offset: number
|
||||
result?: RunnerExecResultMessage
|
||||
}
|
||||
|
||||
export class RunnerClient {
|
||||
private socket?: WebSocket
|
||||
private ready = false
|
||||
private stopped = new AbortController()
|
||||
private executions = new Map<string, Execution>()
|
||||
private transfers = new Map<string, AbortController>()
|
||||
private completedFiles = new Map<string, RunnerToServerMessage>()
|
||||
private pending = new Set<Promise<void>>()
|
||||
|
||||
constructor(
|
||||
private readonly config: Awaited<ReturnType<typeof resolveRunnerConfig>>,
|
||||
private readonly files: RunnerFiles,
|
||||
private readonly shell: RunnerShell,
|
||||
private readonly log: (message: string) => void = console.error,
|
||||
) {}
|
||||
|
||||
async run(signal?: AbortSignal): Promise<void> {
|
||||
const stop = () => this.stop()
|
||||
signal?.addEventListener('abort', stop, { once: true })
|
||||
if (signal?.aborted) this.stop()
|
||||
let attempt = 0
|
||||
try {
|
||||
while (!this.stopped.signal.aborted) {
|
||||
const wasReady = await this.connect()
|
||||
if (this.stopped.signal.aborted) break
|
||||
attempt = wasReady ? 0 : Math.min(attempt + 1, 5)
|
||||
this.log('Runner disconnected; reconnecting…')
|
||||
await delay(Math.min(1000 * 2 ** attempt, 30_000), undefined, {
|
||||
signal: this.stopped.signal,
|
||||
}).catch(() => {})
|
||||
}
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', stop)
|
||||
this.stop()
|
||||
await Promise.allSettled(this.pending)
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.stopped.abort()
|
||||
this.ready = false
|
||||
this.socket?.terminate()
|
||||
for (const execution of this.executions.values()) execution.controller.abort()
|
||||
for (const transfer of this.transfers.values()) transfer.abort()
|
||||
}
|
||||
|
||||
private connect(): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(this.config.url, {
|
||||
headers: { authorization: `Bearer ${this.config.key}` },
|
||||
handshakeTimeout: 10_000,
|
||||
maxPayload: 1024 * 1024,
|
||||
perMessageDeflate: false,
|
||||
followRedirects: false,
|
||||
})
|
||||
this.socket = socket
|
||||
let welcomed = false
|
||||
let lastMessage = Date.now()
|
||||
const heartbeat = setInterval(() => {
|
||||
if (Date.now() - lastMessage > (welcomed ? 75_000 : 10_000)) socket.terminate()
|
||||
}, 5_000)
|
||||
socket.on('error', () => {
|
||||
/* Close drives reconnect; never print credential-bearing request errors. */
|
||||
})
|
||||
socket.on('unexpected-response', (_request, response) => {
|
||||
response.destroy()
|
||||
socket.terminate()
|
||||
if ([401, 403, 404, 426].includes(response.statusCode ?? 0))
|
||||
reject(
|
||||
new CliError(
|
||||
`Runner connection rejected (HTTP ${response.statusCode}). Check the server URL and runner key.`,
|
||||
),
|
||||
)
|
||||
})
|
||||
socket.on('close', (code) => {
|
||||
clearInterval(heartbeat)
|
||||
this.ready = false
|
||||
if (code === 1008 && !this.stopped.signal.aborted)
|
||||
reject(
|
||||
new CliError('Runner access was revoked or another connection replaced this runner.'),
|
||||
)
|
||||
else resolve(welcomed)
|
||||
})
|
||||
socket.on('message', (raw) => {
|
||||
try {
|
||||
const parsed = serverToRunnerMessageSchema.parse(JSON.parse(raw.toString()))
|
||||
if ('executionId' in parsed && !/^[A-Za-z0-9_-]{1,128}$/.test(parsed.executionId))
|
||||
throw new Error('Invalid execution ID.')
|
||||
lastMessage = Date.now()
|
||||
if (parsed.type === 'welcome') {
|
||||
if (welcomed) throw new Error('Duplicate welcome.')
|
||||
welcomed = true
|
||||
this.ready = true
|
||||
this.reconcile(parsed.inFlightExecutionIds)
|
||||
this.log(`Runner connected: ${parsed.runnerName} (${parsed.runnerId})`)
|
||||
} else {
|
||||
if (!welcomed) throw new Error('Expected welcome before runner requests.')
|
||||
this.handle(parsed)
|
||||
}
|
||||
} catch {
|
||||
reject(new CliError('Server sent an invalid runner protocol message.'))
|
||||
socket.terminate()
|
||||
}
|
||||
})
|
||||
if (this.stopped.signal.aborted) socket.terminate()
|
||||
})
|
||||
}
|
||||
|
||||
private send(message: RunnerToServerMessage) {
|
||||
if (this.ready && this.socket?.readyState === WebSocket.OPEN)
|
||||
this.socket.send(JSON.stringify(message))
|
||||
}
|
||||
|
||||
private reconcile(inFlight: string[]) {
|
||||
const expected = new Set(inFlight)
|
||||
for (const [id, execution] of this.executions) {
|
||||
if (!expected.has(id)) {
|
||||
execution.controller.abort()
|
||||
if (execution.result) this.executions.delete(id)
|
||||
continue
|
||||
}
|
||||
// Replay before results: the server deduplicates chunks by UTF-8 byte offset.
|
||||
for (const chunk of execution.chunks) this.send(chunk)
|
||||
}
|
||||
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 })),
|
||||
completedExecutions: [...this.executions]
|
||||
.filter(([id, execution]) => expected.has(id) && execution.result)
|
||||
.map(([, execution]) => execution.result!),
|
||||
})
|
||||
}
|
||||
|
||||
private handle(message: Exclude<ServerToRunnerMessage, { type: 'welcome' }>) {
|
||||
if (message.type === 'ping') {
|
||||
this.send({ type: 'pong', ts: message.ts })
|
||||
return
|
||||
}
|
||||
if (message.type === 'exec.cancel') {
|
||||
this.executions.get(message.executionId)?.controller.abort()
|
||||
return
|
||||
}
|
||||
if (message.type === 'exec.start') {
|
||||
const previous = this.executions.get(message.executionId)
|
||||
if (previous) {
|
||||
if (previous.result) this.send(previous.result)
|
||||
return
|
||||
}
|
||||
const execution: Execution = {
|
||||
controller: new AbortController(),
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
offset: 0,
|
||||
}
|
||||
this.executions.set(message.executionId, execution)
|
||||
this.track(
|
||||
(async () => {
|
||||
const busy = this.activeCount() > MAX_ACTIVE
|
||||
const result = busy
|
||||
? {
|
||||
type: 'exec.result' as const,
|
||||
executionId: message.executionId,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
error: 'Runner is busy. Try again later.',
|
||||
}
|
||||
: await this.shell.run(message, execution.controller.signal, (stream, data) => {
|
||||
// Small frames keep reconnect replay and WebSocket buffering bounded.
|
||||
for (const part of data.match(/[\s\S]{1,8192}/gu) ?? []) {
|
||||
const chunk: RunnerExecOutputMessage = {
|
||||
type: 'exec.output',
|
||||
executionId: message.executionId,
|
||||
stream,
|
||||
data: part,
|
||||
offset: execution.offset,
|
||||
}
|
||||
const bytes = Buffer.byteLength(part)
|
||||
execution.offset += bytes
|
||||
execution.bytes += bytes
|
||||
execution.chunks.push(chunk)
|
||||
while (execution.bytes > MAX_REPLAY_BYTES) {
|
||||
const removed = execution.chunks.shift()!
|
||||
execution.bytes -= Buffer.byteLength(removed.data)
|
||||
if (!this.ready) execution.controller.abort()
|
||||
}
|
||||
if ((this.socket?.bufferedAmount ?? 0) > MAX_REPLAY_BYTES) {
|
||||
this.ready = false
|
||||
this.socket?.terminate()
|
||||
}
|
||||
this.send(chunk)
|
||||
}
|
||||
})
|
||||
execution.result = result
|
||||
this.send(result)
|
||||
const completed = [...this.executions].filter(([, value]) => value.result)
|
||||
for (const [id] of completed.slice(0, -MAX_COMPLETED)) this.executions.delete(id)
|
||||
})(),
|
||||
)
|
||||
return
|
||||
}
|
||||
this.handleFile(message)
|
||||
}
|
||||
|
||||
private activeCount() {
|
||||
return (
|
||||
[...this.executions.values()].filter((execution) => !execution.result).length +
|
||||
this.transfers.size
|
||||
)
|
||||
}
|
||||
|
||||
private handleFile(message: FileMessage) {
|
||||
const previous = this.completedFiles.get(message.executionId)
|
||||
if (previous) {
|
||||
this.send(previous)
|
||||
return
|
||||
}
|
||||
if (this.transfers.has(message.executionId)) return
|
||||
const controller = new AbortController()
|
||||
this.transfers.set(message.executionId, controller)
|
||||
const timer = setTimeout(() => controller.abort(), 120_000)
|
||||
this.track(
|
||||
(async () => {
|
||||
try {
|
||||
const result =
|
||||
this.activeCount() > MAX_ACTIVE
|
||||
? this.fileBusy(message)
|
||||
: await this.files.handle(message, controller.signal)
|
||||
this.completedFiles.set(message.executionId, result)
|
||||
if (this.completedFiles.size > MAX_COMPLETED)
|
||||
this.completedFiles.delete(this.completedFiles.keys().next().value!)
|
||||
this.send(result)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
this.transfers.delete(message.executionId)
|
||||
}
|
||||
})(),
|
||||
)
|
||||
}
|
||||
|
||||
private fileBusy(message: FileMessage): RunnerToServerMessage {
|
||||
const result = {
|
||||
executionId: message.executionId,
|
||||
ok: false,
|
||||
error: 'Runner is busy. Try again later.',
|
||||
}
|
||||
switch (message.type) {
|
||||
case 'file.download':
|
||||
return { ...result, type: 'file.download.result' }
|
||||
case 'file.upload':
|
||||
return { ...result, type: 'file.upload.result' }
|
||||
case 'file.stat':
|
||||
return { ...result, type: 'file.stat.result', exists: false }
|
||||
}
|
||||
}
|
||||
|
||||
private track(task: Promise<void>) {
|
||||
this.pending.add(task)
|
||||
void task.finally(() => this.pending.delete(task)).catch(() => this.stop())
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
const runner = new RunnerClient(config, files, shell)
|
||||
const controller = new AbortController()
|
||||
const shutdown = () => controller.abort()
|
||||
process.once('SIGINT', shutdown)
|
||||
process.once('SIGTERM', shutdown)
|
||||
try {
|
||||
await runner.run(controller.signal)
|
||||
} finally {
|
||||
process.removeListener('SIGINT', shutdown)
|
||||
process.removeListener('SIGTERM', shutdown)
|
||||
await shell.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
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')
|
||||
const config = await resolveRunnerConfig({})
|
||||
expect(config.url.href).toBe('wss://example.com/shumai/api/runners/ws')
|
||||
expect(config.key).toBe('runner-secret')
|
||||
expect(config.cwd).toBe(process.cwd())
|
||||
})
|
||||
|
||||
it.each([
|
||||
'http://example.com',
|
||||
'ftp://localhost',
|
||||
'https://user:secret@example.com',
|
||||
'https://example.com/?key=secret',
|
||||
'not a URL',
|
||||
])('rejects unsafe server URL %s', async (url) => {
|
||||
await expect(resolveRunnerConfig({ url, key: 'key' })).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('allows the Docker host development address', async () => {
|
||||
expect(
|
||||
(await resolveRunnerConfig({ url: 'http://host.docker.internal:3000', key: 'key' })).url.href,
|
||||
).toBe('ws://host.docker.internal:3000/api/runners/ws')
|
||||
})
|
||||
|
||||
it('does not accept a personal API token in place of a missing runner key', async () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', '')
|
||||
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
|
||||
await expect(resolveRunnerConfig({ url: 'https://example.com' })).rejects.toThrow(
|
||||
'SHUMAI_RUNNER_KEY',
|
||||
)
|
||||
})
|
||||
|
||||
it('inherits only baseline environment and explicit skill variables', () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
|
||||
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
|
||||
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
|
||||
vi.stubEnv('BASH_ENV', '/malicious-startup')
|
||||
expect(
|
||||
commandEnv({ SKILL_TOKEN: 'skill-secret', SHUMAI_RUNNER_KEY: 'injected' }),
|
||||
).toMatchObject({ SKILL_TOKEN: 'skill-secret' })
|
||||
for (const name of ['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY', 'AWS_SECRET_ACCESS_KEY', 'BASH_ENV'])
|
||||
expect(commandEnv()).not.toHaveProperty(name)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import { realpath, stat } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { CliError } from '../operations/errors'
|
||||
|
||||
export interface RunnerOptions {
|
||||
url?: string
|
||||
key?: string
|
||||
cwd?: string
|
||||
srt?: string
|
||||
}
|
||||
|
||||
export async function resolveRunnerConfig(options: RunnerOptions) {
|
||||
const address = options.url ?? process.env.SHUMAI_API_SERVER
|
||||
const key = options.key ?? process.env.SHUMAI_RUNNER_KEY
|
||||
if (!address) throw new CliError('Set SHUMAI_API_SERVER or pass --url.')
|
||||
if (!key?.trim()) throw new CliError('Set SHUMAI_RUNNER_KEY or pass --key with a runner key.')
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(address)
|
||||
} catch {
|
||||
throw new CliError('Invalid Shumai server URL.')
|
||||
}
|
||||
if (
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
!['http:', 'https:'].includes(url.protocol)
|
||||
) {
|
||||
throw new CliError(
|
||||
'Use an http:// or https:// server URL without credentials, query, or fragment.',
|
||||
)
|
||||
}
|
||||
const localHosts = ['localhost', '127.0.0.1', '[::1]', 'host.docker.internal']
|
||||
if (url.protocol === 'http:' && !localHosts.includes(url.hostname)) {
|
||||
throw new CliError(
|
||||
'Remote runners require HTTPS. HTTP is only supported for local development.',
|
||||
)
|
||||
}
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
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.')
|
||||
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> = {}, inherit = true): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {}
|
||||
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.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
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createServer, type Server } from 'node:http'
|
||||
import { mkdtemp, mkdir, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import AdmZip from 'adm-zip'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RunnerFiles } from './files'
|
||||
|
||||
describe('runner workspace file transfers', () => {
|
||||
let cwd: string
|
||||
let files: RunnerFiles
|
||||
let server: Server
|
||||
let url: string
|
||||
let body: Buffer
|
||||
let uploaded: Buffer
|
||||
beforeEach(async () => {
|
||||
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-files-test-'))
|
||||
files = new RunnerFiles(cwd)
|
||||
body = Buffer.from('download contents')
|
||||
uploaded = Buffer.alloc(0)
|
||||
server = createServer(async (request, response) => {
|
||||
if (request.method === 'PUT') {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of request) chunks.push(Buffer.from(chunk))
|
||||
uploaded = Buffer.concat(chunks)
|
||||
response.end()
|
||||
} else if (request.url === '/slow') {
|
||||
const timer = setInterval(() => response.write(Buffer.alloc(65536)), 20)
|
||||
response.once('close', () => clearInterval(timer))
|
||||
} else if (request.url === '/redirect') {
|
||||
response.writeHead(302, { location: '/file' })
|
||||
response.end()
|
||||
} else response.end(body)
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') throw new Error('Missing test HTTP address')
|
||||
url = `http://127.0.0.1:${address.port}`
|
||||
})
|
||||
afterEach(async () => {
|
||||
server.closeAllConnections()
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()))
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const signal = () => new AbortController().signal
|
||||
|
||||
it('downloads, checks SHA-256, stats and uploads actual bytes', async () => {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'download',
|
||||
url,
|
||||
destPath: '.pi/input/data.bin',
|
||||
expectedHash: createHash('sha256').update(body).digest('hex'),
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, size: body.length })
|
||||
expect(await readFile(path.join(cwd, '.pi/input/data.bin'))).toEqual(body)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.stat', executionId: 'stat', srcPath: '.pi/input/data.bin' },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, exists: true, isFile: true, size: body.length })
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.upload', executionId: 'upload', srcPath: '.pi/input/data.bin', url },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, size: body.length, name: 'data.bin' })
|
||||
expect(uploaded).toEqual(body)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.stat', executionId: 'absent', srcPath: '.pi/absent' },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, exists: false })
|
||||
})
|
||||
|
||||
it('does not publish mismatched downloads or follow redirects', async () => {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'bad-hash',
|
||||
url,
|
||||
destPath: '.pi/data',
|
||||
expectedHash: 'bad',
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: false, error: 'Downloaded file hash does not match.' })
|
||||
await expect(readFile(path.join(cwd, '.pi/data'))).rejects.toThrow()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'redirect',
|
||||
url: `${url}/redirect`,
|
||||
destPath: '.pi/data',
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'../secret',
|
||||
'/etc/passwd',
|
||||
'.pi/../secret',
|
||||
'.pi/dir/../../secret',
|
||||
'.pi\\secret',
|
||||
'.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()),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it('rejects parent and final symlinks, including a replaced .pi root', async () => {
|
||||
await mkdir(path.join(cwd, '.pi'))
|
||||
await writeFile(path.join(cwd, 'secret'), 'secret')
|
||||
await symlink(cwd, path.join(cwd, '.pi/escape'))
|
||||
await symlink(path.join(cwd, 'secret'), path.join(cwd, '.pi/link'))
|
||||
for (const srcPath of ['.pi/escape/secret', '.pi/link']) {
|
||||
expect(
|
||||
await files.handle({ type: 'file.upload', executionId: 'symlink', srcPath, url }, signal()),
|
||||
).toHaveProperty('ok', false)
|
||||
}
|
||||
await rm(path.join(cwd, '.pi'), { recursive: true })
|
||||
await symlink(cwd, path.join(cwd, '.pi'))
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.download', executionId: 'root', destPath: '.pi/file', url },
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it('extracts skills and safely replaces old contents', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('SKILL.md', Buffer.from('# Test skill'))
|
||||
zip.addFile('scripts/run.sh', Buffer.from('echo skill'))
|
||||
body = zip.toBuffer()
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: `zip-${attempt}`,
|
||||
url,
|
||||
destPath: '.pi/skills/test',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', true)
|
||||
}
|
||||
expect(await readFile(path.join(cwd, '.pi/skills/test/SKILL.md'), 'utf8')).toBe('# Test skill')
|
||||
})
|
||||
|
||||
it('rejects symlink ZIP entries and zip-slip paths without publishing them', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('link', Buffer.from('/etc/passwd'))
|
||||
const entry = zip.getEntry('link')!
|
||||
entry.header.attr = (0o120777 << 16) >>> 0
|
||||
body = zip.toBuffer()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'zip-link',
|
||||
url,
|
||||
destPath: '.pi/skills/bad',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
const normal = new AdmZip()
|
||||
normal.addFile('aa/secret', Buffer.from('escape'))
|
||||
body = Buffer.from(
|
||||
normal.toBuffer().toString('latin1').replaceAll('aa/secret', '../secret'),
|
||||
'latin1',
|
||||
)
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'zip-slip',
|
||||
url,
|
||||
destPath: '.pi/skills/bad',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
await expect(readFile(path.join(cwd, '.pi/skills/bad/link'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('preserves executable script permissions and rejects oversized ZIP entries', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('run.sh', Buffer.from('#!/bin/sh\necho executable\n'))
|
||||
zip.getEntry('run.sh')!.header.attr = (0o100755 << 16) >>> 0
|
||||
body = zip.toBuffer()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'exec-zip',
|
||||
url,
|
||||
destPath: '.pi/skills/executable',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', true)
|
||||
expect((await stat(path.join(cwd, '.pi/skills/executable/run.sh'))).mode & 0o7777).toBe(0o755)
|
||||
const central = body.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]))
|
||||
body.writeUInt32LE(256 * 1024 * 1024 + 1, central + 24)
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'large-zip',
|
||||
url,
|
||||
destPath: '.pi/skills/large',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: false, error: 'Extracted ZIP exceeds 256 MiB.' })
|
||||
})
|
||||
|
||||
it('cancels a streaming download without publishing partial bytes or leaving staging files', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/input'), { recursive: true })
|
||||
await writeFile(path.join(cwd, '.pi/input/data'), 'original')
|
||||
const controller = new AbortController()
|
||||
const transfer = files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'stream-cancel',
|
||||
url: `${url}/slow`,
|
||||
destPath: '.pi/input/data',
|
||||
},
|
||||
controller.signal,
|
||||
)
|
||||
await vi.waitFor(async () =>
|
||||
expect(
|
||||
(await readdir(path.join(cwd, '.pi/input'))).some((name) => name.startsWith('.shumai-')),
|
||||
).toBe(true),
|
||||
)
|
||||
controller.abort()
|
||||
expect(await transfer).toHaveProperty('ok', false)
|
||||
expect(await readFile(path.join(cwd, '.pi/input/data'), 'utf8')).toBe('original')
|
||||
expect(await readdir(path.join(cwd, '.pi/input'))).toEqual(['data'])
|
||||
})
|
||||
|
||||
it('cancels extraction without deleting the installed skill or leaving staging trees', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/skills/installed'), { recursive: true })
|
||||
await writeFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'original')
|
||||
const zip = new AdmZip()
|
||||
for (let index = 0; index < 2000; index++)
|
||||
zip.addFile(`file-${index}.txt`, Buffer.alloc(32768, 65))
|
||||
body = zip.toBuffer()
|
||||
const controller = new AbortController()
|
||||
const transfer = files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'extract-cancel',
|
||||
url,
|
||||
destPath: '.pi/skills/installed',
|
||||
extractZip: true,
|
||||
},
|
||||
controller.signal,
|
||||
)
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const temporary = (await readdir(path.join(cwd, '.pi/skills'))).find((name) =>
|
||||
name.startsWith('.shumai-'),
|
||||
)
|
||||
expect(temporary).toBeDefined()
|
||||
expect(
|
||||
(await readdir(path.join(cwd, '.pi/skills', temporary!, 'extracted'))).length,
|
||||
).toBeGreaterThan(0)
|
||||
},
|
||||
{ interval: 5, timeout: 5000 },
|
||||
)
|
||||
controller.abort()
|
||||
expect(await transfer).toHaveProperty('ok', false)
|
||||
expect(await readFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'utf8')).toBe('original')
|
||||
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual(['installed'])
|
||||
}, 10000)
|
||||
|
||||
it('handles cancelled transfers and refuses uploads of directories', async () => {
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.download', executionId: 'cancelled', url, destPath: '.pi/data' },
|
||||
controller.signal,
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.upload', executionId: 'directory', url, srcPath: '.pi/transfers' },
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
expect(uploaded).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,287 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { on } from 'node:events'
|
||||
import { constants, createWriteStream } from 'node:fs'
|
||||
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { Readable, Transform } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import yauzl from 'yauzl'
|
||||
import type {
|
||||
RunnerFileDownloadMessage,
|
||||
RunnerFileUploadMessage,
|
||||
RunnerFileStatMessage,
|
||||
RunnerToServerMessage,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
const MAX_FILE_BYTES = 256 * 1024 * 1024
|
||||
const MAX_ZIP_ENTRIES = 10_000
|
||||
export type FileMessage =
|
||||
RunnerFileDownloadMessage | RunnerFileUploadMessage | RunnerFileStatMessage
|
||||
|
||||
function pathParts(value: string): string[] {
|
||||
const parts = value.split('/')
|
||||
if (
|
||||
value.includes('\\') ||
|
||||
value.includes('\0') ||
|
||||
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
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
function transferUrl(address: string): URL {
|
||||
const url = new URL(address)
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
||||
throw new Error('Invalid transfer URL.')
|
||||
return url
|
||||
}
|
||||
|
||||
export class RunnerFiles {
|
||||
constructor(readonly cwd: string) {}
|
||||
|
||||
/** Basic workspace validation. Concurrent hostile filesystem mutation is outside v1's scope. */
|
||||
private async resolve(relative: string, createParents = false): Promise<string> {
|
||||
const parts = pathParts(relative)
|
||||
if (parts[0] !== '.pi' || parts.length < 2) throw new Error('File paths must stay inside .pi/.')
|
||||
let current = this.cwd
|
||||
for (let index = 0; index < parts.length; index++) {
|
||||
current = path.join(current, parts[index])
|
||||
const parent = index < parts.length - 1
|
||||
if (parent && createParents) await mkdir(current, { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
const info = await lstat(current)
|
||||
if (info.isSymbolicLink() || (parent && !info.isDirectory()))
|
||||
throw new Error('Workspace paths cannot contain symlinks or non-directory parents.')
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
async createWriter(relative: string) {
|
||||
const file = await open(
|
||||
await this.resolve(relative, true),
|
||||
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
|
||||
0o600,
|
||||
)
|
||||
return {
|
||||
write: async (data: string) => {
|
||||
await file.writeFile(data)
|
||||
},
|
||||
close: () => file.close(),
|
||||
}
|
||||
}
|
||||
|
||||
async handle(message: FileMessage, signal: AbortSignal): Promise<RunnerToServerMessage> {
|
||||
try {
|
||||
signal.throwIfAborted()
|
||||
if (message.type === 'file.download')
|
||||
return {
|
||||
type: 'file.download.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
...(await this.download(message, signal)),
|
||||
}
|
||||
const filename = await this.resolve(message.srcPath)
|
||||
if (message.type === 'file.upload') return await this.upload(message, filename, signal)
|
||||
try {
|
||||
const info = await lstat(filename)
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: true,
|
||||
isFile: info.isFile(),
|
||||
size: info.size,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: false,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const result = {
|
||||
executionId: message.executionId,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'File operation failed.',
|
||||
}
|
||||
switch (message.type) {
|
||||
case 'file.download':
|
||||
return { ...result, type: 'file.download.result' }
|
||||
case 'file.upload':
|
||||
return { ...result, type: 'file.upload.result' }
|
||||
case 'file.stat':
|
||||
return { ...result, type: 'file.stat.result', exists: false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async upload(
|
||||
message: RunnerFileUploadMessage,
|
||||
filename: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<RunnerToServerMessage> {
|
||||
const file = await open(
|
||||
filename,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
)
|
||||
try {
|
||||
const info = await file.stat()
|
||||
if (!info.isFile() || info.size > MAX_FILE_BYTES)
|
||||
throw new Error('Upload must be a regular file no larger than 256 MiB.')
|
||||
// Node and Bun declare different DOM stream types for the same fetch-compatible stream.
|
||||
const body = info.size
|
||||
? (Readable.toWeb(
|
||||
file.createReadStream({ autoClose: false, end: info.size - 1 }),
|
||||
) as unknown as ReadableStream<Uint8Array>)
|
||||
: new Uint8Array()
|
||||
const response = await fetch(transferUrl(message.url), {
|
||||
method: 'PUT',
|
||||
body,
|
||||
...{ duplex: 'half' },
|
||||
headers: {
|
||||
'content-type': message.contentType ?? 'application/octet-stream',
|
||||
'content-length': String(info.size),
|
||||
},
|
||||
signal,
|
||||
redirect: 'error',
|
||||
})
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) throw new Error(`Upload failed (HTTP ${response.status}).`)
|
||||
return {
|
||||
type: 'file.upload.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
size: info.size,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} finally {
|
||||
await file.close()
|
||||
}
|
||||
}
|
||||
|
||||
private async download(message: RunnerFileDownloadMessage, signal: AbortSignal) {
|
||||
const destination = await this.resolve(message.destPath, true)
|
||||
const temporary = await mkdtemp(path.join(path.dirname(destination), '.shumai-'))
|
||||
let preserveBackup = false
|
||||
try {
|
||||
const response = await fetch(transferUrl(message.url), { signal, redirect: 'error' })
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel()
|
||||
throw new Error(`Download failed (HTTP ${response.status}).`)
|
||||
}
|
||||
const hash = createHash('sha256')
|
||||
let size = 0
|
||||
const archive = path.join(temporary, 'download')
|
||||
await pipeline(
|
||||
response.body,
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length
|
||||
if (size > MAX_FILE_BYTES) {
|
||||
callback(new Error('Download exceeds 256 MiB.'))
|
||||
return
|
||||
}
|
||||
hash.update(chunk)
|
||||
callback(null, chunk)
|
||||
},
|
||||
}),
|
||||
createWriteStream(archive, { flags: 'wx', mode: 0o600 }),
|
||||
{ signal },
|
||||
)
|
||||
if (message.expectedHash && hash.digest('hex') !== message.expectedHash)
|
||||
throw new Error('Downloaded file hash does not match.')
|
||||
let source = archive
|
||||
if (message.extractZip) {
|
||||
source = path.join(temporary, 'extracted')
|
||||
await mkdir(source, { mode: 0o700 })
|
||||
await this.extract(archive, source, signal)
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
await this.resolve(message.destPath)
|
||||
if (message.extractZip) {
|
||||
const backup = path.join(temporary, 'previous')
|
||||
let backedUp = false
|
||||
try {
|
||||
await rename(destination, backup)
|
||||
backedUp = true
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
try {
|
||||
await rename(source, destination)
|
||||
} catch (error) {
|
||||
if (backedUp) {
|
||||
preserveBackup = true
|
||||
await rename(backup, destination)
|
||||
preserveBackup = false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else await rename(source, destination)
|
||||
return { size, cached: false }
|
||||
} finally {
|
||||
if (!preserveBackup) await rm(temporary, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async extract(archive: string, directory: string, signal: AbortSignal) {
|
||||
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) =>
|
||||
yauzl.open(
|
||||
archive,
|
||||
{ lazyEntries: true, strictFileNames: true, autoClose: false },
|
||||
(error, opened) => (error ? reject(error) : resolve(opened)),
|
||||
),
|
||||
)
|
||||
let size = 0
|
||||
let count = 0
|
||||
try {
|
||||
const entries = on(zip, 'entry', { close: ['end'], signal }) as AsyncIterable<[yauzl.Entry]>
|
||||
zip.readEntry()
|
||||
for await (const [entry] of entries) {
|
||||
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
|
||||
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
|
||||
const mode = entry.externalFileAttributes >>> 16
|
||||
const kind = mode & 0o170000
|
||||
if (kind && kind !== 0o100000 && kind !== 0o040000)
|
||||
throw new Error('ZIP links and special files are forbidden.')
|
||||
size += entry.uncompressedSize
|
||||
if (size > MAX_FILE_BYTES) throw new Error('Extracted ZIP exceeds 256 MiB.')
|
||||
const destination = path.join(directory, ...parts)
|
||||
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
|
||||
else {
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
|
||||
const input = await new Promise<Readable>((resolve, reject) =>
|
||||
zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream))),
|
||||
)
|
||||
await pipeline(
|
||||
input,
|
||||
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
|
||||
{ signal },
|
||||
)
|
||||
}
|
||||
zip.readEntry()
|
||||
}
|
||||
} finally {
|
||||
zip.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
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'
|
||||
|
||||
describe('runner bash execution', () => {
|
||||
let cwd: string
|
||||
let shell: RunnerShell
|
||||
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 })
|
||||
})
|
||||
|
||||
const request = (command: string, executionId = 'test') => ({
|
||||
type: 'exec.start' as const,
|
||||
executionId,
|
||||
command,
|
||||
})
|
||||
|
||||
it('runs with no executables on PATH when SRT is not requested', async () => {
|
||||
vi.stubEnv('PATH', '')
|
||||
await shell.initialize()
|
||||
let output = ''
|
||||
const result = await shell.run(
|
||||
request('printf no-extra-runtime'),
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
output += data
|
||||
},
|
||||
)
|
||||
expect(result).toMatchObject({ exitCode: 0 })
|
||||
expect(output).toBe('no-extra-runtime')
|
||||
})
|
||||
|
||||
it('streams both outputs, returns the exit code, and saves a log in the runner workspace', async () => {
|
||||
const output: string[] = []
|
||||
const result = await shell.run(
|
||||
request('printf "hello 世界"; printf "failure" >&2; exit 7'),
|
||||
new AbortController().signal,
|
||||
(stream, data) => output.push(`${stream}:${data}`),
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 7,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
fullOutputPath: '.pi/logs/bash-test.log',
|
||||
})
|
||||
expect(output.join('|')).toContain('stdout:hello 世界')
|
||||
expect(output.join('|')).toContain('stderr:failure')
|
||||
expect(await readFile(path.join(cwd, result.fullOutputPath!), 'utf8')).toContain('hello 世界')
|
||||
})
|
||||
|
||||
it('passes skill env without inheriting runner or unrelated credentials', async () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
|
||||
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
|
||||
let output = ''
|
||||
await shell.run(
|
||||
{
|
||||
...request(
|
||||
'printf "%s|%s|%s" "$SKILL_TOKEN" "$SHUMAI_RUNNER_KEY" "$AWS_SECRET_ACCESS_KEY"',
|
||||
),
|
||||
env: { SKILL_TOKEN: 'skill-secret' },
|
||||
},
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
output += data
|
||||
},
|
||||
)
|
||||
expect(output).toBe('skill-secret||')
|
||||
})
|
||||
|
||||
it('times out and terminates background children', async () => {
|
||||
const result = await shell.run(
|
||||
{ ...request('sleep 30 & echo $!; wait'), timeoutSec: 0.1 },
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
)
|
||||
expect(result).toMatchObject({ timedOut: true, signal: 'SIGKILL' })
|
||||
const pid = Number((await readFile(path.join(cwd, '.pi/logs/bash-test.log'), 'utf8')).trim())
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
})
|
||||
|
||||
it('cancels a running command and never starts an already cancelled one', async () => {
|
||||
const controller = new AbortController()
|
||||
const running = shell.run(request('echo ready; sleep 30'), controller.signal, () =>
|
||||
controller.abort(),
|
||||
)
|
||||
expect(await running).toMatchObject({ aborted: true, signal: 'SIGKILL' })
|
||||
expect(
|
||||
await shell.run(request('touch unwanted', 'cancelled'), controller.signal, () => {}),
|
||||
).toMatchObject({ aborted: true })
|
||||
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(
|
||||
{ ...request('sleep 30'), timeoutSec: -1 },
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
),
|
||||
).toHaveProperty('error')
|
||||
expect(
|
||||
await shell.run(
|
||||
request('head -c 70000000 /dev/zero', 'large'),
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
),
|
||||
).toMatchObject({ error: 'Command exceeded the 64 MiB output limit.' })
|
||||
})
|
||||
|
||||
it('uses the exact SRT JSON snapshot and validates SRT before connecting', async () => {
|
||||
const settings = path.join(cwd, 'sandbox.json')
|
||||
const config = {
|
||||
network: { allowedDomains: [], deniedDomains: [] },
|
||||
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
|
||||
}
|
||||
const json = JSON.stringify(config)
|
||||
await writeFile(settings, json)
|
||||
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(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,
|
||||
JSON.stringify({
|
||||
network: { allowedDomains: [], deniedDomains: [] },
|
||||
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
|
||||
}),
|
||||
)
|
||||
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
|
||||
shell = new RunnerShell(new RunnerFiles(cwd), settings)
|
||||
await shell.initialize()
|
||||
const result = await shell.run(
|
||||
{
|
||||
...request('printf secure'),
|
||||
env: { PATH: '/evil-srt', NODE_OPTIONS: `--require=${evil}` },
|
||||
},
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
)
|
||||
expect(result).toMatchObject({ exitCode: 0 })
|
||||
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()
|
||||
await writeFile(settings, 'invalid json')
|
||||
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(
|
||||
/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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { execa } from 'execa'
|
||||
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 { loadSandbox } from './srt'
|
||||
|
||||
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
|
||||
const MAX_TIMEOUT_SEC = 3600
|
||||
|
||||
export class RunnerShell {
|
||||
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,
|
||||
private readonly srtPath?: string,
|
||||
) {}
|
||||
|
||||
async initialize() {
|
||||
if (!this.srtPath) return
|
||||
// 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(
|
||||
message: RunnerExecStartMessage,
|
||||
signal: AbortSignal,
|
||||
output: (stream: 'stdout' | 'stderr', data: string) => void,
|
||||
): Promise<RunnerExecResultMessage> {
|
||||
const result: RunnerExecResultMessage = {
|
||||
type: 'exec.result',
|
||||
executionId: message.executionId,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}
|
||||
if (this.srtPath) this.active++
|
||||
try {
|
||||
if (signal.aborted) return { ...result, aborted: true }
|
||||
const timeout = message.timeoutSec ?? 120
|
||||
if (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_SEC)
|
||||
throw new Error(`Command timeout must be between 0 and ${MAX_TIMEOUT_SEC} seconds.`)
|
||||
const logPath = `.pi/logs/bash-${message.executionId}.log`
|
||||
const log = await this.files.createWriter(logPath)
|
||||
try {
|
||||
const windows = process.platform === 'win32'
|
||||
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.')
|
||||
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,
|
||||
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.
|
||||
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()
|
||||
}
|
||||
if (signal.aborted) return { ...result, aborted: true }
|
||||
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 {
|
||||
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)
|
||||
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')
|
||||
}
|
||||
})
|
||||
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(drainTimer)
|
||||
}
|
||||
} finally {
|
||||
await log.close()
|
||||
}
|
||||
} catch (error) {
|
||||
result.aborted = signal.aborted
|
||||
result.error = error instanceof Error ? error.message : 'Command execution failed.'
|
||||
} finally {
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// Release builds embed SRT's native helpers through scripts/srt-bundle.ts.
|
||||
export const bundledSrtVendor: Record<string, string> | undefined = undefined
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user