mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 22:29:23 +00:00
feat(cli): add runner start with optional SRT sandboxing
This commit is contained in:
@@ -86,6 +86,29 @@ 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` and Python 3, 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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```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.
|
||||
|
||||
See [Agent Runners](../../docs/using-shumai/agent-sandbox.mdx) for configuration, Docker usage, limits, and security boundaries.
|
||||
|
||||
## Usage
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
"commander": "15.0.0",
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"ws": "8.22.2",
|
||||
"zod": "4.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"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,20 @@ export function createProgram(options: ProgramOptions = {}): Command {
|
||||
extensions: cliExtensions,
|
||||
})
|
||||
|
||||
program
|
||||
.command('runner')
|
||||
.description('Connect a local bash 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.',
|
||||
)
|
||||
.action(startRunner)
|
||||
|
||||
program
|
||||
.command('upload')
|
||||
.description('Upload a local file or folder to a parent folder.')
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
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 () => {
|
||||
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,307 @@
|
||||
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',
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { commandEnv, resolveRunnerConfig } from './config'
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('runner configuration', () => {
|
||||
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,62 @@
|
||||
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.')
|
||||
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 }
|
||||
}
|
||||
|
||||
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
|
||||
export function commandEnv(extra: Record<string, string> = {}): 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(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
|
||||
env[key] = value
|
||||
}
|
||||
return env
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createServer, type Server } from 'node:http'
|
||||
import {
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
rename,
|
||||
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',
|
||||
])('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('keeps writes on the opened directory when a command replaces it with a symlink', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/work'), { recursive: true })
|
||||
await mkdir(path.join(cwd, 'outside'))
|
||||
const writer = await files.createWriter('.pi/work/safe.txt')
|
||||
await rename(path.join(cwd, '.pi/work'), path.join(cwd, '.pi/held'))
|
||||
await symlink(path.join(cwd, 'outside'), path.join(cwd, '.pi/work'))
|
||||
await writer.write('safe contents')
|
||||
await writer.close()
|
||||
expect(await readFile(path.join(cwd, '.pi/held/safe.txt'), 'utf8')).toBe('safe contents')
|
||||
await expect(readFile(path.join(cwd, 'outside/safe.txt'))).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!))).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,228 @@
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
RunnerFileDownloadMessage,
|
||||
RunnerFileUploadMessage,
|
||||
RunnerFileStatMessage,
|
||||
RunnerToServerMessage,
|
||||
} from '@shumai/dtos'
|
||||
import { findExecutable, spawnFileHelper } from './filesystem'
|
||||
|
||||
export type FileMessage =
|
||||
RunnerFileDownloadMessage | RunnerFileUploadMessage | RunnerFileStatMessage
|
||||
const metadataSchema = z.object({
|
||||
exists: z.boolean().optional(),
|
||||
isFile: z.boolean().optional(),
|
||||
size: z.number().optional(),
|
||||
name: z.string().optional(),
|
||||
cached: z.boolean().optional(),
|
||||
ready: z.boolean().optional(),
|
||||
})
|
||||
|
||||
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 {
|
||||
private python?: Promise<string>
|
||||
constructor(readonly cwd: string) {}
|
||||
|
||||
async initialize() {
|
||||
await (this.python ??= findExecutable('python3'))
|
||||
}
|
||||
|
||||
private async helper(operation: string, relative: string, expectedHash = '') {
|
||||
await this.initialize()
|
||||
const child = spawnFileHelper(await this.python!, this.cwd, operation, relative, expectedHash)
|
||||
const control = child.stdio[3]
|
||||
if (!(control instanceof Writable)) throw new Error('Missing filesystem commit channel.')
|
||||
control.on('error', () => {})
|
||||
if (operation === 'read' || operation === 'stat') control.end()
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
// Binary reads are consumed by fetch, all other operations return small JSON metadata.
|
||||
if (operation !== 'read')
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
stdout = (stdout + chunk.toString()).slice(-8192)
|
||||
})
|
||||
let firstLine: (value: string) => void
|
||||
const ready = new Promise<string>((resolve) => {
|
||||
firstLine = resolve
|
||||
})
|
||||
child.stderr.on('data', (chunk: Buffer) => {
|
||||
stderr = (stderr + chunk.toString()).slice(-8192)
|
||||
if (stderr.includes('\n')) firstLine(stderr.split('\n')[0]!)
|
||||
})
|
||||
// A failed helper must not produce an unhandled EPIPE while HTTP is still streaming.
|
||||
child.stdin.on('error', () => {})
|
||||
const done = new Promise<z.infer<typeof metadataSchema>>((resolve, reject) => {
|
||||
child.once('error', (error) => {
|
||||
firstLine('')
|
||||
reject(error)
|
||||
})
|
||||
child.once('close', (code) => {
|
||||
firstLine(stderr)
|
||||
if (code !== 0)
|
||||
reject(new Error(stderr.trim().split('\n').at(-1) || 'Runner file operation failed.'))
|
||||
else if (operation === 'read') resolve({})
|
||||
else {
|
||||
try {
|
||||
resolve(metadataSchema.parse(JSON.parse(stdout)))
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
void done.catch(() => {})
|
||||
let stopping = false
|
||||
const stop = () => {
|
||||
if (stopping || child.exitCode !== null || child.signalCode !== null) return
|
||||
stopping = true
|
||||
control.end()
|
||||
child.stdin.destroy()
|
||||
child.kill('SIGTERM')
|
||||
const fallback = setTimeout(() => child.kill('SIGKILL'), 5000)
|
||||
void done.finally(() => clearTimeout(fallback)).catch(() => {})
|
||||
}
|
||||
return { child, done, ready, stop, commit: () => control.end('1') }
|
||||
}
|
||||
|
||||
async createWriter(relative: string, expectedHash = '') {
|
||||
const task = await this.helper('write', relative, expectedHash)
|
||||
try {
|
||||
const metadata = metadataSchema.parse(JSON.parse(await task.ready))
|
||||
if (!metadata.ready) throw new Error('Runner file writer did not initialize.')
|
||||
} catch (error) {
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
throw error
|
||||
}
|
||||
return {
|
||||
async write(data: string) {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
task.child.stdin.write(data, (error) => {
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
}),
|
||||
)
|
||||
},
|
||||
async close() {
|
||||
task.child.stdin.end()
|
||||
task.commit()
|
||||
return await task.done
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async handle(message: FileMessage, signal: AbortSignal): Promise<RunnerToServerMessage> {
|
||||
try {
|
||||
if (message.type === 'file.stat') {
|
||||
const task = await this.helper('stat', message.srcPath)
|
||||
task.child.stdin.end()
|
||||
const result = await task.done
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: result.exists ?? false,
|
||||
...result,
|
||||
}
|
||||
}
|
||||
if (message.type === 'file.download') {
|
||||
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 task = await this.helper(
|
||||
message.extractZip ? 'extract' : 'write',
|
||||
message.destPath,
|
||||
message.expectedHash,
|
||||
)
|
||||
const abort = () => {
|
||||
task.stop()
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
try {
|
||||
if (signal.aborted) signal.throwIfAborted()
|
||||
await pipeline(response.body, task.child.stdin, { signal })
|
||||
signal.throwIfAborted()
|
||||
task.commit()
|
||||
return {
|
||||
type: 'file.download.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
...(await task.done),
|
||||
}
|
||||
} catch (error) {
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
throw error
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
return await this.upload(message, signal)
|
||||
} 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,
|
||||
signal: AbortSignal,
|
||||
): Promise<RunnerToServerMessage> {
|
||||
const task = await this.helper('read', message.srcPath)
|
||||
task.child.stdin.end()
|
||||
const abort = () => {
|
||||
task.stop()
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
try {
|
||||
const info = metadataSchema.parse(JSON.parse(await task.ready))
|
||||
if (!info.isFile || info.size === undefined) throw new Error('Invalid upload file.')
|
||||
const response = await fetch(transferUrl(message.url), {
|
||||
method: 'PUT',
|
||||
body: Readable.toWeb(task.child.stdout) as unknown as ReadableStream<Uint8Array>,
|
||||
...{ 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}).`)
|
||||
await task.done
|
||||
return {
|
||||
type: 'file.upload.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
size: info.size,
|
||||
name: info.name,
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort)
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { constants } from 'node:fs'
|
||||
import { access, realpath } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { commandEnv } from './config'
|
||||
|
||||
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.`)
|
||||
}
|
||||
|
||||
// Node has no portable openat API. This small, isolated Python helper uses directory
|
||||
// descriptors for every workspace access, so concurrent shell symlink swaps cannot
|
||||
// redirect host-side transfers or logs outside the workspace. No network or credentials.
|
||||
const FILESYSTEM_HELPER = String.raw`
|
||||
import os, sys, stat, json, hashlib, tempfile, zipfile, secrets, signal
|
||||
MAX = 256 * 1024 * 1024
|
||||
FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
def cancelled(signum, frame): raise InterruptedError('File transfer aborted.')
|
||||
signal.signal(signal.SIGTERM, cancelled)
|
||||
root = os.open(sys.argv[1], FLAGS)
|
||||
operation, relative = sys.argv[2:4]
|
||||
def components(value):
|
||||
parts = value.split('/')
|
||||
if chr(92) in value or chr(0) in value or any(not p or p in ('.', '..') or ':' in p for p in parts):
|
||||
raise ValueError('Invalid workspace path.')
|
||||
return parts
|
||||
def parent_at(base, parts, create=False):
|
||||
current = os.dup(base)
|
||||
try:
|
||||
for part in parts[:-1]:
|
||||
if create:
|
||||
try: os.mkdir(part, 0o700, dir_fd=current)
|
||||
except FileExistsError: pass
|
||||
following = os.open(part, FLAGS, dir_fd=current)
|
||||
os.close(current)
|
||||
current = following
|
||||
return current, parts[-1]
|
||||
except BaseException:
|
||||
os.close(current)
|
||||
raise
|
||||
def remove_at(parent, name):
|
||||
try: info = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
||||
except FileNotFoundError: return
|
||||
if stat.S_ISDIR(info.st_mode):
|
||||
child = os.open(name, FLAGS, dir_fd=parent)
|
||||
try:
|
||||
for entry in os.listdir(child): remove_at(child, entry)
|
||||
finally: os.close(child)
|
||||
os.rmdir(name, dir_fd=parent)
|
||||
else: os.unlink(name, dir_fd=parent)
|
||||
def commit():
|
||||
if os.read(3, 1) != b'1': raise InterruptedError('File transfer was not committed.')
|
||||
def publish_directory(parent, temporary, name):
|
||||
backup = '.shumai-' + secrets.token_hex(16)
|
||||
backed_up = False
|
||||
published = False
|
||||
mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
|
||||
try:
|
||||
try:
|
||||
os.rename(name, backup, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
backed_up = True
|
||||
except FileNotFoundError: pass
|
||||
try:
|
||||
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
published = True
|
||||
except BaseException:
|
||||
if backed_up:
|
||||
os.rename(backup, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
backed_up = False
|
||||
raise
|
||||
finally:
|
||||
try: signal.pthread_sigmask(signal.SIG_SETMASK, mask)
|
||||
finally:
|
||||
if backed_up and published: remove_at(parent, backup)
|
||||
def copy_input(destination, expected):
|
||||
digest, size = hashlib.sha256(), 0
|
||||
while True:
|
||||
chunk = sys.stdin.buffer.read(65536)
|
||||
if not chunk: break
|
||||
size += len(chunk)
|
||||
if size > MAX: raise ValueError('Download exceeds 256 MiB.')
|
||||
digest.update(chunk)
|
||||
destination.write(chunk)
|
||||
if expected and digest.hexdigest() != expected: raise ValueError('Downloaded file hash does not match.')
|
||||
return size
|
||||
try:
|
||||
parts = components(relative)
|
||||
if parts[0] != '.pi' or len(parts) < 2: raise ValueError('File paths must stay inside .pi/.')
|
||||
parent, name = parent_at(root, parts, operation in ('write', 'extract'))
|
||||
try:
|
||||
if operation in ('stat', 'read'):
|
||||
try: fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
||||
except FileNotFoundError:
|
||||
if operation != 'stat': raise
|
||||
print(json.dumps({'exists': False}))
|
||||
sys.exit(0)
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
metadata = {'exists': True, 'isFile': stat.S_ISREG(info.st_mode), 'size': info.st_size, 'name': name}
|
||||
if operation == 'stat': print(json.dumps(metadata))
|
||||
else:
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX: raise ValueError('Upload must be a regular file no larger than 256 MiB.')
|
||||
print(json.dumps(metadata), file=sys.stderr, flush=True)
|
||||
with os.fdopen(os.dup(fd), 'rb') as source:
|
||||
remaining = info.st_size
|
||||
while remaining:
|
||||
chunk = source.read(min(65536, remaining))
|
||||
if not chunk: raise ValueError('File changed during upload.')
|
||||
sys.stdout.buffer.write(chunk)
|
||||
remaining -= len(chunk)
|
||||
finally: os.close(fd)
|
||||
else:
|
||||
# A private sibling staging entry is published only after validation.
|
||||
temporary = '.shumai-' + secrets.token_hex(16)
|
||||
try:
|
||||
if operation == 'extract':
|
||||
os.mkdir(temporary, 0o700, dir_fd=parent)
|
||||
target = os.open(temporary, FLAGS, dir_fd=parent)
|
||||
try:
|
||||
with tempfile.TemporaryFile() as archive:
|
||||
size = copy_input(archive, sys.argv[4])
|
||||
archive.seek(0)
|
||||
with zipfile.ZipFile(archive) as zip:
|
||||
entries = zip.infolist()
|
||||
if len(entries) > 10000: raise ValueError('ZIP contains too many entries.')
|
||||
if sum(entry.file_size for entry in entries) > MAX: raise ValueError('Extracted ZIP exceeds 256 MiB.')
|
||||
for entry in entries:
|
||||
mode = entry.external_attr >> 16
|
||||
kind = stat.S_IFMT(mode)
|
||||
if kind not in (0, stat.S_IFREG, stat.S_IFDIR): raise ValueError('ZIP links and special files are forbidden.')
|
||||
entry_parent, entry_name = parent_at(target, components(entry.filename.rstrip('/')), True)
|
||||
try:
|
||||
if entry.is_dir():
|
||||
try: os.mkdir(entry_name, 0o700, dir_fd=entry_parent)
|
||||
except FileExistsError: pass
|
||||
else:
|
||||
fd = os.open(entry_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600 | (mode & 0o155), dir_fd=entry_parent)
|
||||
with os.fdopen(fd, 'wb') as output, zip.open(entry) as source:
|
||||
copied = 0
|
||||
while True:
|
||||
chunk = source.read(65536)
|
||||
if not chunk: break
|
||||
copied += len(chunk)
|
||||
if copied > entry.file_size: raise ValueError('Invalid ZIP entry size.')
|
||||
output.write(chunk)
|
||||
finally: os.close(entry_parent)
|
||||
finally: os.close(target)
|
||||
commit()
|
||||
publish_directory(parent, temporary, name)
|
||||
elif operation == 'write':
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
||||
print(json.dumps({'ready': True}), file=sys.stderr, flush=True)
|
||||
with os.fdopen(fd, 'wb') as output: size = copy_input(output, sys.argv[4])
|
||||
else: raise ValueError('Unknown file operation.')
|
||||
if operation == 'write':
|
||||
commit()
|
||||
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
print(json.dumps({'size': size, 'cached': False}))
|
||||
finally: remove_at(parent, temporary)
|
||||
finally: os.close(parent)
|
||||
except FileNotFoundError:
|
||||
if operation == 'stat': print(json.dumps({'exists': False}))
|
||||
else: print('File or directory not found.', file=sys.stderr); sys.exit(1)
|
||||
except BaseException as error:
|
||||
if isinstance(error, SystemExit): raise
|
||||
print(str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
finally: os.close(root)
|
||||
`
|
||||
|
||||
export function spawnFileHelper(
|
||||
python: string,
|
||||
cwd: string,
|
||||
operation: string,
|
||||
relative: string,
|
||||
expectedHash = '',
|
||||
) {
|
||||
return spawn(python, ['-I', '-c', FILESYSTEM_HELPER, cwd, operation, relative, expectedHash], {
|
||||
env: commandEnv(),
|
||||
stdio: ['pipe', 'pipe', 'pipe', 'pipe'],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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 { 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))
|
||||
})
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const request = (command: string, executionId = 'test') => ({
|
||||
type: 'exec.start' as const,
|
||||
executionId,
|
||||
command,
|
||||
})
|
||||
|
||||
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('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 capture = path.join(cwd, 'captured.json')
|
||||
const json = JSON.stringify({
|
||||
network: { allowedDomains: [] },
|
||||
filesystem: { allowWrite: ['.pi'] },
|
||||
})
|
||||
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}`)
|
||||
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',
|
||||
)
|
||||
})
|
||||
|
||||
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 },
|
||||
)
|
||||
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
|
||||
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('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(
|
||||
'JSON object',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
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 { RunnerFiles } from './files'
|
||||
import { findExecutable } from './filesystem'
|
||||
|
||||
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
|
||||
const MAX_TIMEOUT_SEC = 3600
|
||||
|
||||
export class RunnerShell {
|
||||
private settings?: string
|
||||
private srtExecutable?: string
|
||||
|
||||
constructor(
|
||||
private readonly files: RunnerFiles,
|
||||
private readonly srtPath?: string,
|
||||
) {}
|
||||
|
||||
async initialize() {
|
||||
await this.files.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.'}`,
|
||||
)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
let settingsDir: string | undefined
|
||||
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 args = ['--noprofile', '--norc', '-c', message.command]
|
||||
let executable = '/bin/bash'
|
||||
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()
|
||||
}
|
||||
const child = spawn(executable, args, {
|
||||
cwd: this.files.cwd,
|
||||
env,
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
// Bun can change child.pid after exit; retain the actual process group ID.
|
||||
const processGroupId = child.pid
|
||||
const kill = () => {
|
||||
if (!processGroupId || processGroupId <= 0) return
|
||||
try {
|
||||
process.kill(-processGroupId, 'SIGKILL')
|
||||
} catch (error) {
|
||||
if (!(
|
||||
error instanceof Error &&
|
||||
'code' in error &&
|
||||
(error.code === 'ESRCH' ||
|
||||
(error.code === 'EPERM' && (child.exitCode !== null || child.signalCode !== null)))
|
||||
))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const onAbort = () => {
|
||||
result.aborted = true
|
||||
kill()
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
const timer = setTimeout(() => {
|
||||
result.timedOut = true
|
||||
kill()
|
||||
}, timeout * 1000)
|
||||
let bytes = 0
|
||||
let writes = Promise.resolve()
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('exit', (code, exitSignal) => {
|
||||
result.exitCode = code
|
||||
result.signal = exitSignal
|
||||
kill()
|
||||
})
|
||||
child.once('close', () => resolve())
|
||||
for (const stream of ['stdout', 'stderr'] as const) {
|
||||
child[stream].setEncoding('utf8')
|
||||
child[stream].on('error', reject)
|
||||
child[stream].on('data', (data: string) => {
|
||||
bytes += Buffer.byteLength(data)
|
||||
if (bytes > MAX_OUTPUT_BYTES) {
|
||||
if (!result.error) {
|
||||
result.error = 'Command exceeded the 64 MiB output limit.'
|
||||
kill()
|
||||
}
|
||||
return
|
||||
}
|
||||
child[stream].pause()
|
||||
writes = writes
|
||||
.then(async () => {
|
||||
await log.write(data)
|
||||
output(stream, data)
|
||||
child[stream].resume()
|
||||
})
|
||||
.catch(reject)
|
||||
})
|
||||
}
|
||||
if (signal.aborted) onAbort()
|
||||
})
|
||||
await writes
|
||||
result.fullOutputPath = logPath
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
kill()
|
||||
}
|
||||
} finally {
|
||||
await log.close()
|
||||
}
|
||||
} catch (error) {
|
||||
result.error = error instanceof Error ? error.message : 'Command execution failed.'
|
||||
} finally {
|
||||
if (settingsDir) await rm(settingsDir, { recursive: true, force: true })
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user