feat(cli): add runner start with optional SRT sandboxing

This commit is contained in:
yiling
2026-11-17 16:12:03 +08:00
parent d801d166bb
commit 3e992c0e9d
17 changed files with 1867 additions and 56 deletions
+2
View File
@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **cli**: Start a remote bash runner with `shumai-cli runner start`, with optional sandboxing through an SRT JSON configuration file.
- **agent**: Support binding external Runners per team so agents can execute shell commands and exchange files securely over WebSocket without requiring a built-in server sandbox, and allow assigning a default or dedicated Runner per agent in Team Settings.
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
@@ -17,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **agent**: Make bash available to editors and reviewers as soon as a runner is configured, without first reading a skill.
- **agent**: ⚠️ **Behavior Change**: Replace the built-in server-side bash sandbox and domain allowlist settings with external team Runners; agent `bash` and `download_asset` tools are enabled automatically once at least one Runner is configured for the team, while domain and OS-level sandboxing rules move to the Runner side.
- **cli**: Show copyable commands and shell configuration instructions when the standalone CLI installation directory is missing from PATH.
+23
View File
@@ -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]
+6
View File
@@ -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"
}
}
+15
View File
@@ -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.')
+163
View File
@@ -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)
})
})
+307
View File
@@ -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)
}
}
+51
View File
@@ -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)
})
})
+62
View File
@@ -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
}
+338
View File
@@ -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)
})
})
+228
View File
@@ -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(() => {})
}
}
}
+192
View File
@@ -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'],
})
}
+170
View File
@@ -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',
)
})
})
+166
View File
@@ -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
}
}
+22 -2
View File
@@ -44,8 +44,14 @@
"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",
},
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
@@ -1514,7 +1520,7 @@
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
@@ -2964,7 +2970,7 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"ws": ["ws@8.22.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
@@ -3012,10 +3018,16 @@
"@dbos-inc/dbos-sdk/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"@dbos-inc/dbos-sdk/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@earendil-works/chord/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@earendil-works/pi-ai/@google/genai": ["@google/genai@2.21.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"], "hasInstallScript": true }, "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
"@inlang/paraglide-js/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
@@ -3042,6 +3054,8 @@
"@reduxjs/toolkit/reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="],
"@shumai/cli/adm-zip": ["adm-zip@0.6.1", "", {}, "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ=="],
"@shumai/webui/@types/react-dom": ["@types/react-dom@19.2.5", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg=="],
"@smithy/node-http-handler/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
@@ -3210,6 +3224,10 @@
"glob/minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
"happy-dom/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"happy-dom/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"its-fine/@types/react-reconciler": ["@types/react-reconciler@0.28.9", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg=="],
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
@@ -3270,6 +3288,8 @@
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@earendil-works/pi-ai/@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.3.0", "", {}, "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ=="],
+59 -25
View File
@@ -1,45 +1,79 @@
---
title: Agent Sandbox
description: Secure execution environment and network domain restrictions for AI agent scripts.
title: Agent Runners
description: Connect an optional Bash runner and configure sandboxing on its machine.
---
Running automated scripts poses security risks. Shumai resolves this by executing all agent skills inside a secure, isolated **Sandbox** environment.
Agents use Shumai's built-in tools without a runner. To execute Bash commands or download assets into a shell workspace, connect a **runner** on a machine you control. The runner opens an authenticated outbound WebSocket connection; no inbound port is needed.
---
## Connect a runner
## Sandbox Security
1. In **Settings → Agent Runners**, create a runner and copy its one-time key. Only team owners can manage runners and rotate their keys.
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on a macOS or Linux machine with `/bin/bash` and Python 3.
3. Start it in a dedicated, existing workspace:
The sandbox restricts the execution process from accessing the host filesystem, system processes, and internal networks:
```bash
export SHUMAI_API_SERVER="https://shumai.example.com"
export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
- **Isolation**: Scripts run in a virtualized workspace container that prevents them from modifying critical system files or reading other project data.
- **Network Bridging**: External network calls from inside the sandbox are strictly monitored.
Use a runner key, not a personal API token. Prefer the environment variable over `--key` to keep the key out of shell history. The runner stays in the foreground; Ctrl+C stops it and its active commands. Temporary connection losses trigger reconnection. Revoked or replaced connections stop instead of reconnecting.
### File System Restrictions
The first runner becomes the team default. Each agent can use that default or a dedicated runner selected in its settings. Without a configured runner, `bash` and `download_asset` are hidden. With one configured, authorized editors and reviewers can use Bash immediately without reading a skill first. Disabled-tool policies still apply. An offline runner produces an execution error.
To protect your workspace environments and sensitive data, the sandbox enforces strict file-level access controls:
Commands start in the workspace directory. Skills, downloaded assets, generated files, and output logs live under `.pi`. Commands inherit baseline OS settings and explicit skill variables, rather than the runner's full environment, including its runner key and personal API token.
- **Read Access**: The sandbox is allowed to read files within the workspace, with a strict exception for sensitive environment and certificate files. It cannot read: `['.env', '.env.*', '*.pem', '*.key']`.
- **Write Access**: The sandbox is heavily restricted and may only write to the `.pi` folder located in the current working directory (cwd). Even within this allowed directory, the sandbox is explicitly blocked from writing or creating sensitive files matching: `['.env', '.env.*', '*.pem', '*.key']`.
## Optional SRT sandbox
---
Without `--srt`, commands have the runner operating-system user's permissions. Connect only to a trusted Shumai server; use a dedicated container, VM, or account when appropriate.
## Domain Whitelisting
Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites on the runner machine:
By default, Network Sandbox is **disabled** (allowing all outbound network requests). Team Owners can toggle Network Sandbox **ON** in Sandbox Settings to enforce strict domain whitelisting:
```bash
npm install -g @anthropic-ai/sandbox-runtime
# Linux also needs SRT's documented prerequisites, including bubblewrap, socat, and ripgrep.
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
```
### Allowed Domains
The JSON uses upstream SRT settings directly. For example:
A list of domains that sandboxed scripts are permitted to access.
```json
{
"filesystem": {
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
"allowWrite": [".pi"],
"denyWrite": []
},
"network": {
"allowedDomains": [],
"deniedDomains": []
}
}
```
- Default whitelisted domains include standard package registries (like npm or python package hosts) and repository hosts (like `github.com`).
- If a script needs to call an external API (e.g. `api.slack.com`), the administrator must add it to the allowed list.
This example allows writes only in `.pi`, denies reads of the listed credential locations, and blocks command network access. Review read permissions and network rules for your environment using SRT's documentation. Relative filesystem paths use the runner workspace. Settings are snapshotted at startup; restart after changing them. Missing or invalid settings, missing SRT prerequisites, and sandbox initialization failures stop startup. Commands never fall back to unrestricted execution.
### Pending Domains
SRT wraps Bash and its child processes. The runner's WebSocket and server-directed file transfers operate outside SRT. **The Shumai server address is not automatically added to allowed domains.** If a script itself needs network access, explicitly allow its destination in the JSON.
When an agent script attempts to reach a domain that is not currently authorized:
Shumai has no server-side sandbox or domain settings. SRT is installed only on runners that opt into it. SRT in Docker may require namespace permissions on that dedicated runner container; these permissions are not needed by the Shumai server.
1. The network connection is blocked immediately.
2. The target domain is logged and added to the **Pending Domains** list.
3. Admins can review this list and click **Approve** to authorize the domain, or **Reject** to keep it blocked.
## Runner in Docker
![Agent Sandbox Settings](../sandbox.webp)
An ordinary runner can run in its own container without extra capabilities or an exposed port:
```bash
docker run --rm --init --name shumai-runner \
--cap-drop ALL --security-opt no-new-privileges \
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
-v shumai-runner-workspace:/workspace -w /workspace \
node:22-bookworm sh -c \
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
```
For development, HTTP is accepted for `localhost`, `127.0.0.1`, `[::1]`, and Docker's `host.docker.internal`. Remote servers require HTTPS. Avoid mounting sensitive host directories or the Docker socket into the runner workspace.
## Limits and lifecycle
Commands default to 120 seconds and accept a maximum timeout of one hour. Timeout and cancellation terminate the process group. Each command saves up to 64 MiB of output in `.pi/logs`; manage retained logs as part of workspace maintenance. Transfers and extracted archives are limited to 256 MiB. Protocol file operations reject paths outside `.pi`, symlinks, and unsafe archive entries.
Temporary reconnects reconcile active and recently completed commands without deliberately executing them again. Restarting the runner process does not resume commands from the previous process.
+59 -25
View File
@@ -1,45 +1,79 @@
---
title: 智能体沙箱
description: AI 智能体脚本的安全执行环境与网络域名限制规范。
title: 智能体运行器
description: 连接可选的 Bash 运行器,并在运行器机器上配置沙箱。
---
运行自动化脚本存在潜在的安全风险。Shumai 通过在安全且隔离的**沙箱(Sandbox)**环境中执行所有智能体技能来化解这一隐患。
智能体无需运行器即可使用内置工具。如需执行 Bash 或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
---
## 连接运行器
## 沙箱安全机制
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
2. 在有 `/bin/bash` 和 Python 3 的 macOS 或 Linux 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
3. 在已有的专用工作目录中启动:
沙箱严格限制执行进程访问宿主机文件系统、系统进程及内部网络:
```bash
export SHUMAI_API_SERVER="https://shumai.example.com"
export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
- **环境隔离**:脚本在虚拟化的工作区容器中运行,无法篡改系统核心文件或读取其他项目数据。
- **网络桥接管控**:来自沙箱内部的外部网络请求会受到严格监控。
使用运行器密钥,而非个人 API 令牌。建议通过环境变量传入,避免 `--key` 将密钥留在命令历史中。运行器在前台执行,Ctrl+C 会停止运行器及其活动命令。临时断线后自动重连;密钥撤销或连接被替换时退出。
### 文件系统访问限制
第一个运行器是团队默认运行器,也可在智能体设置中指定专用运行器。未配置运行器时隐藏 `bash` 和 `download_asset`。配置后,具有智能体使用权限的编辑者和审阅者可立即使用 Bash,无需先读取技能;禁用工具设置仍然生效。运行器离线时执行命令会返回错误。
为保障工作区环境与敏感数据安全,沙箱实施了严密的文件级访问控制策略:
命令从工作目录启动,技能、下载素材、生成文件和日志位于 `.pi` 中。子进程只继承基础系统环境及明确配置的技能变量,不自动继承运行器密钥、个人 API 令牌或其他任意环境变量。
- **读取权限**:沙箱允许读取工作区内的普通文件,但严格禁止访问敏感环境配置与证书密钥文件。禁止读取的文件模式包括:`['.env', '.env.*', '*.pem', '*.key']`。
- **写入权限**:沙箱的写入权限受到极为严苛的限制,仅允许写入当前工作目录(cwd)下的 `.pi` 文件夹。即便在该受信任的目录内部,沙箱也严禁写入或创建匹配以下模式的敏感文件:`['.env', '.env.*', '*.pem', '*.key']`。
## 可选 SRT 沙箱
---
未使用 `--srt` 时,命令具有运行器系统用户的权限。只连接可信 Shumai 服务器,可按需使用独立容器、虚拟机或账号。
## 域名白名单
在运行器机器上安装 [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) 及其平台依赖:
默认情况下,网络沙箱处于**关闭**状态(允许所有出站网络请求)。团队所有者可在沙箱设置中开启网络沙箱,以强制推行严格的域名白名单管控:
```bash
npm install -g @anthropic-ai/sandbox-runtime
# Linux 还需要 SRT 文档中的平台依赖,包括 bubblewrap、socat 和 ripgrep。
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
```
### 允许的域名 (Allowed Domains)
直接使用上游 SRT JSON 格式,例如:
允许沙箱内脚本正常访问的域名清单。
```json
{
"filesystem": {
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
"allowWrite": [".pi"],
"denyWrite": []
},
"network": {
"allowedDomains": [],
"deniedDomains": []
}
}
```
- 默认白名单包含标准软件包注册表(如 npm、Python 官方源等)以及代码托管平台(如 `github.com`)。
- 若脚本需要调用外部 API(如 `api.slack.com`),管理员须预先将其添加至白名单中。
此例只允许写入 `.pi`,禁止读取所列凭证位置,并禁止命令访问网络。请参考 SRT 文档审查适合自己环境的读取权限和域名规则。相对路径以运行器工作目录为基准。配置在启动时读取并保存快照,修改后需要重启。配置缺失或无效、SRT 依赖缺失、沙箱初始化失败都会阻止启动,不会回退到无沙箱执行。
### 待审批域名 (Pending Domains)
SRT 只包裹 Bash 及其子进程。运行器 WebSocket 和服务器发起的文件传输在 SRT 外运行。**不会自动将 Shumai 服务器地址添加到允许域名中。** 如果脚本自身需要网络,请在 JSON 中明确允许目标域名。
当智能体脚本尝试访问未经授权的域名时:
Shumai 服务器不管理沙箱和域名规则。只有启用沙箱的运行器需要安装 SRT。在 Docker 中使用 SRT 可能需要为专用运行器容器增加命名空间权限,Shumai 服务器不需要这些权限。
1. 网络连接将被即刻拦截。
2. 系统会记录目标域名并将其加入**待审批域名**列表。
3. 管理员可审阅该列表,点击**批准**将其加白,或点击**拒绝**保持拦截。
## Docker 运行器
![智能体沙箱设置](/sandbox.webp)
普通运行器可在独立容器中执行,无需额外权限或暴露端口:
```bash
docker run --rm --init --name shumai-runner \
--cap-drop ALL --security-opt no-new-privileges \
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
-v shumai-runner-workspace:/workspace -w /workspace \
node:22-bookworm sh -c \
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
```
本地开发允许 `localhost`、`127.0.0.1`、`[::1]`、Docker 的 `host.docker.internal` HTTP 地址;远程连接必须使用 HTTPS。不要将敏感宿主机目录或 Docker socket 挂载到运行器工作区。
## 限制与生命周期
默认超时 120 秒,最长一小时。超时或取消会终止命令进程组。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、符号链接及不安全的压缩包条目。
临时重连会同步执行中及近期完成的命令,避免主动重复执行。重启运行器进程不会恢复旧进程中的命令。
@@ -513,7 +513,7 @@ export function RunnerSettings({ teamId }: { teamId: string }) {
<div className="flex items-center gap-2">
<Input
readOnly
value={`shumai runner start --url ${serverOrigin} --key ${revealedKeyData.key}`}
value={`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key}`}
className="font-mono text-xs bg-muted"
/>
<Button
@@ -522,7 +522,7 @@ export function RunnerSettings({ teamId }: { teamId: string }) {
size="icon"
onClick={() =>
handleCopy(
`shumai runner start --url ${serverOrigin} --key ${revealedKeyData.key}`,
`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key}`,
'cmd',
)
}
@@ -543,7 +543,7 @@ export function RunnerSettings({ teamId }: { teamId: string }) {
<div className="flex items-center gap-2">
<Input
readOnly
value={`shumai runner start --url ${serverOrigin} --key ${revealedKeyData.key} --sandbox`}
value={`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key} --srt sandbox.json`}
className="font-mono text-xs bg-muted"
/>
<Button
@@ -552,7 +552,7 @@ export function RunnerSettings({ teamId }: { teamId: string }) {
size="icon"
onClick={() =>
handleCopy(
`shumai runner start --url ${serverOrigin} --key ${revealedKeyData.key} --sandbox`,
`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key} --srt sandbox.json`,
'sandboxCmd',
)
}