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

This commit is contained in:
yiling
2026-11-17 23:08:20 +08:00
parent 07e69717e5
commit 17f14390be
31 changed files with 787 additions and 134 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **cli**: Run remote bash commands and exchange files with `shumai-cli runner start`, with optional sandboxing through an SRT JSON configuration file.
- **cli**: Run remote shell commands and exchange files with `shumai-cli runner start` on macOS, Linux, and Windows, with bundled SRT sandboxing enabled through a 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.
+19 -4
View File
@@ -88,7 +88,7 @@ export SHUMAI_ALLOW_DELETE="true"
## Agent runner
Create a runner in **Settings → Agent Runners** and copy its one-time key. On a macOS or Linux machine with `/bin/bash`, start it in an existing dedicated workspace:
Create a runner in **Settings → Agent Runners** and copy its one-time key. On macOS, Linux, or Windows, start it in an existing dedicated workspace:
```sh
export SHUMAI_API_SERVER="https://shumai.example.com"
@@ -96,16 +96,31 @@ export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
For Windows PowerShell:
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
Use `--url` or `--key` to override those variables. A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
Bash runs with the local user's permissions unless SRT is requested. Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites separately, then pass its native JSON settings:
Commands use `/bin/sh` on macOS/Linux and `cmd.exe` on Windows. The agent receives the runner's OS and shell so it can use the appropriate syntax. Commands run with the local user's permissions unless SRT is requested.
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled with the CLI. Install its platform prerequisites (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then pass its native JSON settings:
```sh
npm install -g @anthropic-ai/sandbox-runtime
shumai-cli runner start --srt sandbox.json
```
SRT settings are snapshotted at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only Bash and its children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The `runner start` command currently supports macOS and Linux; other CLI commands remain available on Windows.
Windows sandboxing uses SRT's alpha Windows support. Run its one-time setup before starting a sandboxed runner (it requests administrator permission):
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT settings are read and validated at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only shell commands and their children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The shared SRT runtime is cleaned up when the runner stops.
See [Agent Runners](../../docs/using-shumai/agent-sandbox.mdx) for configuration, Docker usage, limits, and security boundaries.
+1
View File
@@ -7,6 +7,7 @@
"shumai-cli": "./src/index.ts"
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.82",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
+2 -5
View File
@@ -46,16 +46,13 @@ export function createProgram(options: ProgramOptions = {}): Command {
program
.command('runner')
.description('Connect a local bash runner to Shumai.')
.description('Connect a local command runner to Shumai.')
.command('start')
.description('Run in the foreground using a key created in Settings → Agent Runners.')
.option('--url <url>', 'Shumai server URL (or SHUMAI_API_SERVER).')
.option('--key <key>', 'Runner key (prefer SHUMAI_RUNNER_KEY to avoid shell history).')
.option('--cwd <directory>', 'Runner workspace directory (defaults to the current directory).')
.option(
'--srt <file>',
'Wrap bash commands with locally installed srt using this JSON settings file.',
)
.option('--srt <file>', 'Sandbox commands with bundled SRT using this JSON settings file.')
.action(startRunner)
program
+6
View File
@@ -72,6 +72,12 @@ describe('runner WebSocket client', () => {
const send = (message: unknown) => socket.send(JSON.stringify(message))
it('responds to heartbeat, executes a command once and streams byte offsets', async () => {
expect(messages).toContainEqual(
expect.objectContaining({
type: 'reconcile',
environment: { platform: process.platform, shell: '/bin/sh' },
}),
)
send({ type: 'ping', ts: 123 })
const command = {
type: 'exec.start',
+4
View File
@@ -150,6 +150,7 @@ export class RunnerClient {
}
this.send({
type: 'reconcile',
environment: this.shell.environment,
activeExecutions: [...this.executions]
.filter(([id, execution]) => expected.has(id) && !execution.result)
.map(([executionId, execution]) => ({ executionId, nextOffset: execution.offset })),
@@ -290,6 +291,8 @@ export class RunnerClient {
export async function startRunner(options: RunnerOptions) {
const config = await resolveRunnerConfig(options)
// SRT resolves relative policy paths against the runner workspace.
process.chdir(config.cwd)
const files = new RunnerFiles(config.cwd)
const shell = new RunnerShell(files, config.srt)
await shell.initialize()
@@ -303,5 +306,6 @@ export async function startRunner(options: RunnerOptions) {
} finally {
process.removeListener('SIGINT', shutdown)
process.removeListener('SIGTERM', shutdown)
await shell.close()
}
}
+21 -1
View File
@@ -1,9 +1,29 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { commandEnv, resolveRunnerConfig } from './config'
import { commandEnv, resolveRunnerConfig, runnerShell } from './config'
afterEach(() => vi.unstubAllEnvs())
describe('runner configuration', () => {
it('uses the platform shell without requiring Bash on Windows', () => {
vi.stubEnv('SystemRoot', 'D:\\Windows')
expect(runnerShell('win32')).toBe('D:\\Windows\\System32\\cmd.exe')
expect(runnerShell('linux')).toBe('/bin/sh')
expect(runnerShell('darwin')).toBe('/bin/sh')
})
it('preserves Windows OS settings, normalizes explicit overrides, and excludes credentials', () => {
vi.stubEnv('Path', 'C:\\Windows\\System32')
vi.stubEnv('SystemRoot', 'C:\\Windows')
vi.stubEnv('USERPROFILE', 'C:\\Users\\runner')
const env = commandEnv({ PATH: 'C:\\tools', ['shumai_runner_key']: 'secret' })
expect(env).toMatchObject({
PATH: 'C:\\tools',
SystemRoot: 'C:\\Windows',
USERPROFILE: 'C:\\Users\\runner',
})
expect(env).not.toHaveProperty('Path')
expect(env).not.toHaveProperty('shumai_runner_key')
})
it('uses a dedicated runner key and preserves a server path prefix', async () => {
vi.stubEnv('SHUMAI_API_SERVER', 'https://example.com/shumai/')
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
+19 -6
View File
@@ -41,21 +41,34 @@ export async function resolveRunnerConfig(options: RunnerOptions) {
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/runners/ws`
const cwd = await realpath(path.resolve(options.cwd ?? process.cwd()))
if (!(await stat(cwd)).isDirectory()) throw new CliError('Runner workspace must be a directory.')
if (process.platform === 'win32')
throw new CliError('Runner execution requires macOS or Linux with bash.')
return { url, key: key.trim(), cwd, srt: options.srt ? path.resolve(options.srt) : undefined }
}
export function runnerShell(platform = process.platform): string {
return platform === 'win32'
? path.win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe')
: '/bin/sh'
}
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
export function commandEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
export function commandEnv(extra: Record<string, string> = {}, inherit = true): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {}
for (const [key, value] of Object.entries(process.env)) {
if (/^(PATH|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|LC_.*)$/.test(key)) env[key] = value
for (const [key, value] of Object.entries(inherit ? process.env : {})) {
if (
/^(PATH|PATHEXT|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|TEMP|TMP|SYSTEMROOT|SYSTEMDRIVE|COMSPEC|USERPROFILE|USERNAME|APPDATA|LOCALAPPDATA|PROGRAMDATA|PROGRAMFILES|PROGRAMFILES\(X86\)|LC_.*)$/i.test(
key,
)
)
env[key] = value
}
for (const [key, value] of Object.entries(extra)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Invalid skill environment variable name.')
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key)) continue
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key.toUpperCase())) continue
// Windows treats environment names as case-insensitive.
for (const existing of Object.keys(env)) {
if (existing.toUpperCase() === key.toUpperCase()) delete env[existing]
}
env[key] = value
}
return env
-17
View File
@@ -1,17 +0,0 @@
import { constants } from 'node:fs'
import { access, realpath } from 'node:fs/promises'
import path from 'node:path'
export async function findExecutable(name: string): Promise<string> {
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
if (!directory) continue
const candidate = path.resolve(directory, name)
try {
await access(candidate, constants.X_OK)
return await realpath(candidate)
} catch {
// Try the next PATH entry.
}
}
throw new Error(`${name} is required on the runner machine and must be available on PATH.`)
}
+7
View File
@@ -117,6 +117,13 @@ describe('runner workspace file transfers', () => {
'.pi//file',
'.pi/a:b',
'.pi/a\0b',
'.pi/.. /outside',
'.pi/folder./file',
'.pi/CON.txt',
'.pi/nul .txt',
'.pi/COM1',
'.pi/lpt¹.log',
'.pi/CONOUT$',
])('rejects unsafe protocol path %s', async (srcPath) => {
expect(
await files.handle({ type: 'file.stat', executionId: 'unsafe', srcPath }, signal()),
+9 -1
View File
@@ -23,7 +23,15 @@ function pathParts(value: string): string[] {
if (
value.includes('\\') ||
value.includes('\0') ||
parts.some((part) => !part || part === '.' || part === '..' || part.includes(':'))
parts.some(
(part) =>
!part ||
part === '.' ||
part === '..' ||
part.includes(':') ||
/[. ]$/.test(part) ||
/^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?: *\.|$)/i.test(part),
)
)
throw new Error('Invalid workspace path.')
return parts
+92 -26
View File
@@ -2,6 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
@@ -11,8 +12,16 @@ describe('runner bash execution', () => {
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-shell-test-'))
shell = new RunnerShell(new RunnerFiles(cwd))
vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
vi.spyOn(SandboxManager, 'reset').mockResolvedValue()
vi.spyOn(SandboxManager, 'wrapWithSandboxArgv').mockImplementation(async (command) => ({
argv: ['/bin/sh', '-c', command],
env: process.env,
}))
})
afterEach(async () => {
await shell.close()
vi.restoreAllMocks()
vi.unstubAllEnvs()
await rm(cwd, { recursive: true, force: true })
})
@@ -117,47 +126,45 @@ describe('runner bash execution', () => {
it('uses the exact SRT JSON snapshot and validates SRT before connecting', async () => {
const settings = path.join(cwd, 'sandbox.json')
const capture = path.join(cwd, 'captured.json')
const json = JSON.stringify({
network: { allowedDomains: [] },
filesystem: { allowWrite: ['.pi'] },
})
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
const json = JSON.stringify(config)
await writeFile(settings, json)
await writeFile(
path.join(cwd, 'srt'),
`#!/bin/bash\ncp "$2" '${capture}'\nshift 3\nexec "$@"\n`,
{ mode: 0o700 },
)
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
vi.stubEnv('PATH', '')
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
await writeFile(settings, '{}')
expect(
await shell.run(request('echo sandboxed'), new AbortController().signal, () => {}),
).toMatchObject({ exitCode: 0 })
expect(await readFile(capture, 'utf8')).toBe(json)
vi.stubEnv('PATH', '/missing-srt')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
'required on the runner machine',
expect(SandboxManager.initialize).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining(config),
)
expect(SandboxManager.wrapWithSandboxArgv).toHaveBeenCalledWith(
expect.stringContaining('echo sandboxed'),
'/bin/sh',
undefined,
expect.any(AbortSignal),
cwd,
{ commandId: 'test', commandText: 'echo sandboxed' },
)
expect(SandboxManager.reset).not.toHaveBeenCalled()
})
it('keeps skill PATH and Node startup settings out of the SRT launcher', async () => {
const settings = path.join(cwd, 'sandbox.json')
const marker = path.join(cwd, 'injected')
const evil = path.join(cwd, 'evil.cjs')
await writeFile(settings, '{}')
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
await writeFile(
path.join(cwd, 'srt'),
`#!/usr/bin/env node
const {spawnSync} = require('node:child_process');
const result = spawnSync(process.argv[5], process.argv.slice(6), {stdio: 'inherit'});
process.exit(result.status ?? 1);
`,
{ mode: 0o700 },
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const result = await shell.run(
@@ -172,6 +179,62 @@ process.exit(result.status ?? 1);
await expect(readFile(marker)).rejects.toThrow()
})
it('initializes one sandbox for parallel commands and resets only at shutdown', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
await shell.initialize()
const value = "quoted ' value\n$(echo should-not-expand)"
let output = ''
const results = await Promise.all(
['one', 'two'].map((id) =>
shell.run(
{ ...request('printf "%s" "$SKILL_TOKEN"', id), env: { SKILL_TOKEN: value } },
new AbortController().signal,
(_stream, data) => {
output += data
},
),
),
)
expect(results.every((result) => result.exitCode === 0)).toBe(true)
expect(output).toBe(value.repeat(2))
expect(SandboxManager.initialize).toHaveBeenCalledTimes(1)
expect(SandboxManager.reset).not.toHaveBeenCalled()
await shell.close()
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
})
it('fails startup and cleans up if sandbox initialization or execution fails', async () => {
const settings = path.join(cwd, 'sandbox.json')
await writeFile(
settings,
JSON.stringify({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}),
)
shell = new RunnerShell(new RunnerFiles(cwd), settings)
vi.mocked(SandboxManager.initialize).mockRejectedValueOnce(
new Error('Run windows-install first'),
)
await expect(shell.initialize()).rejects.toThrow('windows-install')
expect(SandboxManager.reset).toHaveBeenCalledTimes(1)
expect(
await shell.run(request('echo unsafe'), new AbortController().signal, () => {}),
).toHaveProperty('error', 'SRT has not been initialized.')
vi.mocked(SandboxManager.wrapWithSandboxArgv).mockRejectedValueOnce(
new Error('sandbox unavailable'),
)
await expect(shell.initialize()).rejects.toThrow('SRT preflight failed: sandbox unavailable')
})
it('fails closed for missing or malformed SRT settings', async () => {
const settings = path.join(cwd, 'sandbox.json')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
@@ -179,7 +242,10 @@ process.exit(result.status ?? 1);
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
await writeFile(settings, '[]')
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
'JSON object',
/object/,
)
await writeFile(settings, JSON.stringify({ network: { allowedDomains: 42 } }))
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
})
+137 -46
View File
@@ -1,19 +1,27 @@
import { spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { RunnerExecResultMessage, RunnerExecStartMessage } from '@shumai/dtos'
import { commandEnv } from './config'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
type RunnerExecResultMessage,
type RunnerExecStartMessage,
} from '@shumai/dtos'
import { commandEnv, runnerShell } from './config'
import { RunnerFiles } from './files'
import { findExecutable } from './executable'
import { loadSandbox } from './srt'
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
const MAX_TIMEOUT_SEC = 3600
export class RunnerShell {
private settings?: string
private srtExecutable?: string
readonly environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: runnerShell(),
})
private sandbox?: Awaited<ReturnType<typeof loadSandbox>>
private initialized = false
private active = 0
constructor(
private readonly files: RunnerFiles,
@@ -22,24 +30,38 @@ export class RunnerShell {
async initialize() {
if (!this.srtPath) return
// Snapshot once: a command editing the source config cannot weaken later commands.
this.settings = await readFile(this.srtPath, 'utf8')
const parsed: unknown = JSON.parse(this.settings)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
throw new Error('SRT settings must be a JSON object.')
this.srtExecutable = await findExecutable('srt')
let diagnostic = ''
const probe = await this.run(
{ type: 'exec.start', executionId: randomUUID(), command: 'true', timeoutSec: 15 },
new AbortController().signal,
(_stream, data) => {
diagnostic = (diagnostic + data).slice(-4096)
},
)
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
throw new Error(
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
// Read and validate once; commands cannot weaken the policy by editing the file.
this.sandbox = await loadSandbox(this.srtPath)
try {
await SandboxManager.initialize(this.sandbox.config)
this.initialized = true
let diagnostic = ''
const probe = await this.run(
{ type: 'exec.start', executionId: randomUUID(), command: 'exit 0', timeoutSec: 15 },
new AbortController().signal,
(_stream, data) => {
diagnostic = (diagnostic + data).slice(-4096)
},
)
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
throw new Error(
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
)
} catch (error) {
await this.close()
throw error
}
}
async close() {
if (!this.sandbox) return
try {
await SandboxManager.reset()
} finally {
await this.sandbox.cleanup()
this.sandbox = undefined
this.initialized = false
}
}
async run(
@@ -55,7 +77,7 @@ export class RunnerShell {
timedOut: false,
aborted: false,
}
let settingsDir: string | undefined
if (this.srtPath) this.active++
try {
if (signal.aborted) return { ...result, aborted: true }
const timeout = message.timeoutSec ?? 120
@@ -64,31 +86,85 @@ export class RunnerShell {
const logPath = `.pi/logs/bash-${message.executionId}.log`
const log = await this.files.createWriter(logPath)
try {
const args = ['--noprofile', '--norc', '-c', message.command]
let executable = '/bin/bash'
const windows = process.platform === 'win32'
let args = windows ? ['/d', '/s', '/c', message.command] : ['-c', message.command]
let executable = this.environment.shell
let env = commandEnv(message.env)
if (this.srtPath && !this.srtExecutable) throw new Error('SRT has not been initialized.')
if (this.settings !== undefined) {
settingsDir = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
const settingsFile = path.join(settingsDir, 'settings.json')
await writeFile(settingsFile, this.settings, { mode: 0o600 })
executable = this.srtExecutable!
const variables = Object.entries(env)
.filter((entry): entry is [string, string] => entry[1] !== undefined)
.map(([key, value]) => `${key}=${value}`)
args.unshift('--settings', settingsFile, '--', '/usr/bin/env', ...variables, '/bin/bash')
env = commandEnv()
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
const skillEnv = commandEnv(message.env, false)
const command = windows
? message.command
: [
...Object.entries(skillEnv).map(
([key, value]) => `export ${key}='${value!.replaceAll("'", "'\\''")}'`,
),
message.command,
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
executable,
undefined,
signal,
this.files.cwd,
{ commandId: message.executionId, commandText: message.command },
)
;[executable, ...args] = wrapped.argv
if (windows) {
// SRT's broker starts a fresh sandbox-user environment. Explicit skill
// values belong in its child overlay, never in the broker's startup env.
const separator = args.indexOf('--')
if (separator < 0) throw new Error('SRT returned an invalid Windows launch command.')
args.splice(
separator,
0,
...Object.entries(skillEnv).flatMap(([key, value]) => ['--env', `${key}=${value}`]),
)
env = wrapped.env
} else env = commandEnv()
}
const child = spawn(executable, args, {
cwd: this.files.cwd,
env,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
})
if (signal.aborted) return { ...result, aborted: true }
const nativeWindows = windows && !this.srtPath
const child = spawn(
nativeWindows ? message.command : executable,
nativeWindows ? [] : args,
{
cwd: this.files.cwd,
env,
detached: !windows,
windowsHide: true,
shell: nativeWindows ? executable : false,
stdio: ['ignore', 'pipe', 'pipe'],
},
)
// Bun can change child.pid after exit; retain the actual process group ID.
const processGroupId = child.pid
let termination: Promise<void> | undefined
const kill = () => {
if (!processGroupId || processGroupId <= 0) return
if (windows) {
if (child.exitCode !== null || child.signalCode !== null) return
termination ??= new Promise<void>((resolve) => {
const taskkill = spawn(
path.win32.join(
process.env.SystemRoot ?? 'C:\\Windows',
'System32',
'taskkill.exe',
),
['/pid', String(processGroupId), '/t', '/f'],
{ windowsHide: true, stdio: 'ignore', env: commandEnv(), timeout: 5000 },
)
taskkill.once('error', () => {
child.kill('SIGKILL')
resolve()
})
taskkill.once('close', (code) => {
if (code !== 0) child.kill('SIGKILL')
resolve()
})
})
return
}
try {
process.kill(-processGroupId, 'SIGKILL')
} catch (error) {
@@ -112,13 +188,22 @@ export class RunnerShell {
}, timeout * 1000)
let bytes = 0
let writes = Promise.resolve()
let drainTimer: ReturnType<typeof setTimeout> | undefined
try {
await new Promise<void>((resolve, reject) => {
child.once('error', reject)
child.once('exit', (code, exitSignal) => {
clearTimeout(timer)
result.exitCode = code
result.signal = exitSignal
kill()
if (nativeWindows) {
// A background process can inherit pipes after cmd.exe exits.
// Plain Windows execution has no job object; bound output draining.
drainTimer = setTimeout(() => {
child.stdout.destroy()
child.stderr.destroy()
}, 1000)
} else kill()
})
child.once('close', () => resolve())
for (const stream of ['stdout', 'stderr'] as const) {
@@ -149,16 +234,22 @@ export class RunnerShell {
result.fullOutputPath = logPath
} finally {
clearTimeout(timer)
clearTimeout(drainTimer)
signal.removeEventListener('abort', onAbort)
kill()
await termination
}
} finally {
await log.close()
}
} catch (error) {
result.aborted = signal.aborted
result.error = error instanceof Error ? error.message : 'Command execution failed.'
} finally {
if (settingsDir) await rm(settingsDir, { recursive: true, force: true })
// SRT's temporary mount resources are shared: clean up only after every
// concurrent command has finished, and keep the proxies until shutdown.
if (this.srtPath && --this.active === 0 && this.initialized)
SandboxManager.cleanupAfterCommand()
}
return result
}
+122
View File
@@ -0,0 +1,122 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { PassThrough } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RunnerFiles } from './files'
import { RunnerShell } from './shell'
vi.mock('node:child_process', async (importOriginal) => ({
...(await importOriginal<typeof import('node:child_process')>()),
spawn: vi.fn(),
}))
class CommandProcess extends EventEmitter {
pid = 12345
exitCode: number | null = null
signalCode: NodeJS.Signals | null = null
stdout = new PassThrough()
stderr = new PassThrough()
kill = vi.fn(() => {
this.finish(null, 'SIGKILL')
return true
})
constructor() {
super()
let closed = 0
for (const stream of [this.stdout, this.stderr])
stream.once('close', () => {
if (++closed === 2) this.emit('close')
})
}
finish(code: number | null, signal: NodeJS.Signals | null = null, keepPipes = false) {
this.exitCode = code
this.signalCode = signal
this.emit('exit', code, signal)
if (!keepPipes) {
this.stdout.end()
this.stderr.end()
}
}
}
describe('Windows runner process lifecycle', () => {
let cwd: string
let shell: RunnerShell
let child: CommandProcess
let killedWhileRunning: boolean
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-windows-shell-'))
vi.stubGlobal('process', { ...process, platform: 'win32' })
vi.stubEnv('SystemRoot', 'C:\\Windows')
child = new CommandProcess()
killedWhileRunning = false
vi.mocked(spawn).mockImplementation((executable) => {
if (String(executable).endsWith('taskkill.exe')) {
killedWhileRunning = child.exitCode === null && child.signalCode === null
const killer = new EventEmitter()
setImmediate(() => {
child.finish(null, 'SIGKILL')
killer.emit('close', 0)
})
return killer as ChildProcess
}
return child as unknown as ChildProcess
})
shell = new RunnerShell(new RunnerFiles(cwd))
})
afterEach(async () => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.clearAllMocks()
await rm(cwd, { recursive: true, force: true })
})
const request = { type: 'exec.start' as const, executionId: 'windows', command: 'echo hello' }
it('uses Node shell launching and drains inherited pipes after the root exits', async () => {
const running = shell.run(
{ ...request, timeoutSec: 0.2 },
new AbortController().signal,
() => {},
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(spawn).toHaveBeenCalledWith(
'echo hello',
[],
expect.objectContaining({
shell: 'C:\\Windows\\System32\\cmd.exe',
detached: false,
}),
)
child.stdout.write('before exit')
child.finish(7, null, true)
const result = await running
expect(result).toMatchObject({ exitCode: 7, timedOut: false, aborted: false })
expect(child.stdout.destroyed && child.stderr.destroyed).toBe(true)
expect(await readFile(path.join(cwd, result.fullOutputPath!), 'utf8')).toBe('before exit')
expect(spawn).toHaveBeenCalledTimes(1)
})
it.each(['timeout', 'cancel'] as const)(
'terminates a live Windows process tree on %s',
async (kind) => {
const controller = new AbortController()
const running = shell.run({ ...request, timeoutSec: 0.2 }, controller.signal, () => {})
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
if (kind === 'cancel') controller.abort()
const result = await running
expect(result).toMatchObject({ timedOut: kind === 'timeout', aborted: kind === 'cancel' })
expect(killedWhileRunning).toBe(true)
expect(spawn).toHaveBeenCalledWith(
'C:\\Windows\\System32\\taskkill.exe',
['/pid', '12345', '/t', '/f'],
expect.objectContaining({ timeout: 5000, windowsHide: true }),
)
},
)
})
+2
View File
@@ -0,0 +1,2 @@
// Release builds embed SRT's native helpers through scripts/srt-bundle.ts.
export const bundledSrtVendor: Record<string, string> | undefined = undefined
+59
View File
@@ -0,0 +1,59 @@
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { loadSandbox } from './srt'
describe('runner SRT configuration', () => {
let directory: string
let settings: string
const config = {
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: ['.pi'], denyWrite: [] },
}
beforeEach(async () => {
directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-settings-'))
settings = path.join(directory, 'sandbox.json')
})
afterEach(() => rm(directory, { recursive: true, force: true }))
it('validates upstream settings, supplies packaged helpers, and removes them on cleanup', async () => {
await writeFile(settings, JSON.stringify(config))
const sandbox = await loadSandbox(settings)
const helper = sandbox.config.javaAgentJarPath!
expect(sandbox.config).toMatchObject(config)
expect((await readFile(helper)).subarray(0, 2).toString()).toBe('PK')
if (process.platform === 'linux')
expect(await stat(sandbox.config.seccomp!.applyPath!)).toHaveProperty(
'size',
expect.any(Number),
)
if (process.platform === 'win32')
expect(await stat(sandbox.config.windows!.srtWin!.path!)).toHaveProperty(
'size',
expect.any(Number),
)
await sandbox.cleanup()
await expect(stat(helper)).rejects.toThrow()
})
it('preserves explicit upstream helper paths', async () => {
await writeFile(
settings,
JSON.stringify({
...config,
javaAgentJarPath: '/custom/proxy.jar',
seccomp: { applyPath: '/custom/seccomp' },
windows: { srtWin: { path: 'C:\\custom\\srt-win.exe' } },
}),
)
const sandbox = await loadSandbox(settings)
try {
expect(sandbox.config.javaAgentJarPath).toBe('/custom/proxy.jar')
expect(sandbox.config.seccomp?.applyPath).toBe('/custom/seccomp')
expect(sandbox.config.windows?.srtWin?.path).toBe('C:\\custom\\srt-win.exe')
} finally {
await sandbox.cleanup()
}
})
})
+59
View File
@@ -0,0 +1,59 @@
import { createRequire } from 'node:module'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import {
SandboxRuntimeConfigSchema,
type SandboxRuntimeConfig,
} from '@anthropic-ai/sandbox-runtime'
import { bundledSrtVendor } from './srt-vendor'
/** Load the upstream JSON format and supply the helpers bundled with this CLI. */
export async function loadSandbox(configPath: string) {
const config = SandboxRuntimeConfigSchema.parse(JSON.parse(await readFile(configPath, 'utf8')))
const directory = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
const cleanup = () => rm(directory, { recursive: true, force: true })
const asset = async (name: string) => {
const encoded = bundledSrtVendor?.[name]
const bytes =
encoded !== undefined
? Buffer.from(encoded, 'base64')
: await readFile(
path.join(
path.dirname(
createRequire(import.meta.url).resolve(
'@anthropic-ai/sandbox-runtime/package.json',
),
),
'vendor',
name,
),
)
const destination = path.join(directory, path.basename(name))
await writeFile(destination, bytes, { mode: 0o500 })
return destination
}
try {
if (process.platform === 'linux' && !config.seccomp?.applyPath) {
config.seccomp = {
...config.seccomp,
applyPath: await asset(`seccomp/${process.arch}/apply-seccomp`),
}
}
if (process.platform === 'win32' && !config.windows?.srtWin?.path) {
config.windows = {
...config.windows,
srtWin: {
...config.windows?.srtWin,
path: await asset(`srt-win/${process.arch}/srt-win.exe`),
},
}
}
if (!config.javaAgentJarPath)
config.javaAgentJarPath = await asset('java-proxy-agent/srt-proxy-agent.jar')
return { config: config satisfies SandboxRuntimeConfig, cleanup }
} catch (error) {
await cleanup()
throw error
}
}
+61
View File
@@ -37,6 +37,7 @@
"shumai-cli": "./src/index.ts",
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.82",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
@@ -482,6 +483,8 @@
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.82", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.25.0" }, "optionalDependencies": { "@microsoft/mxc-sdk": "^1.0.1" }, "bin": { "srt": "dist/cli.js" } }, "sha512-SCPWkuhLw4ieL+06Jp72yFevltS0s2GD1kMOZdSJ6XxeuqTcoyAa1EDwiLxuONp6szNEOD7x02+vYxPa0oAWwg=="],
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.129.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw=="],
"@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.29", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Dtu0gr4dnATZAPwEYbpCsG+MpLM7OAliy2gTepEFQwl1vZ6DL3QMH2FveMa3HLvPsOdhJsPRB3KtxVhph9T75A=="],
@@ -756,6 +759,46 @@
"@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
"@koromix/koffi-android-arm64": ["@koromix/koffi-android-arm64@3.3.7", "", { "os": "android", "cpu": "arm64" }, "sha512-330J8SnMF48DwADEbPYb5gAIM0mo3dZAsLUkuhyEPTPF49h73hRO7LMVXPkUmeXkK/J5Uvgsaem6Lx86Uev3GA=="],
"@koromix/koffi-android-x64": ["@koromix/koffi-android-x64@3.3.7", "", { "os": "android", "cpu": "x64" }, "sha512-CE1LEAsMyChQQNjGVDy56lBEdU70zOOD709mdKtxM6Rn2I7srT8Jyj66kSwnl4gO4+2BlTBXMyEIAEyYiNXNEA=="],
"@koromix/koffi-darwin-arm64": ["@koromix/koffi-darwin-arm64@3.3.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-xg1nqqhHRo6QxxYZJtYhhEGAbkHCQxvjoId3BCkhIJhRLi7+dDBRpLEi8x/5xrhqjCp+c/XhMrkAvxWy0NEYBg=="],
"@koromix/koffi-darwin-x64": ["@koromix/koffi-darwin-x64@3.3.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-8KeSrHrxzj+SEvaSMc1ufpgn66AdtorKGGb8HNJN5A435stXZ35oxg2+rsAyhTduvEZ9DkCuU94A0crA8KQ0UA=="],
"@koromix/koffi-freebsd-arm64": ["@koromix/koffi-freebsd-arm64@3.3.7", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-UTo2xw46ctQdcz55I3b5pP1Gs0mGcYZLGAJg7MpEdr8ZEMmmclTzU/WUwWw/lyj5x2Ld2fscjCt69elqfrUBOQ=="],
"@koromix/koffi-freebsd-ia32": ["@koromix/koffi-freebsd-ia32@3.3.7", "", { "os": "freebsd", "cpu": "ia32" }, "sha512-5vgirS+XISQHzXiad3KYhZYGvuSbAtyrIm2etO118IjpWi87wbKP8xEdf8s4F+vU0HxGs9hcx5a+blwFMe9TFA=="],
"@koromix/koffi-freebsd-x64": ["@koromix/koffi-freebsd-x64@3.3.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-R2POCHtQ46cyhCFtYuq3Uo4MEiMstwLi49fwUgu6Vl38XvqKeje5up5e72LTCXf+ks/y3nua3TYM5oXTBqYAUA=="],
"@koromix/koffi-linux-arm": ["@koromix/koffi-linux-arm@3.3.7", "", { "os": "linux", "cpu": "arm" }, "sha512-zUb+N1CvsRikXKs93jNdHTAVFt3Njr7ShIA8QwOh2IH/8aV8bkQnkt7AOJvOK/uP0CHd7bxn82YgGUAcZW/pVw=="],
"@koromix/koffi-linux-arm64": ["@koromix/koffi-linux-arm64@3.3.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-7ttM8GE2gowelTTyTY0+t79rWaoilZMmW4MYgrIXx5NNShLiHtUNfyGGaNzCd1MD+j+bnNZLJ2lh3lkBS9stfw=="],
"@koromix/koffi-linux-ia32": ["@koromix/koffi-linux-ia32@3.3.7", "", { "os": "linux", "cpu": "ia32" }, "sha512-hM6CtBgyWGkYzXIl+ciCWSCWnYh/6ft2FRi17aw345lK3Syl2OH06PPMxMd+AHkNrnYWT3nyrzl2Rcun9IeAiw=="],
"@koromix/koffi-linux-loong64": ["@koromix/koffi-linux-loong64@3.3.7", "", { "os": "linux", "cpu": "none" }, "sha512-plmvZGrC2F02AIDNx3+QcjU39Y9XVgHAHMOM17HJCmxc3f5VpKO0d7aln3/Re6TchBW1h2ldFgI6pp/7vN7IQQ=="],
"@koromix/koffi-linux-ppc64": ["@koromix/koffi-linux-ppc64@3.3.7", "", { "os": "linux", "cpu": "ppc64" }, "sha512-bmVe2k1v7tiOGcuX22+HIyOT39bRBrIJd2v6qzSN9Er/f7XI61cbJUnFYWdXpYecU2Ww1LDSkgIifcRyfpipqw=="],
"@koromix/koffi-linux-riscv64": ["@koromix/koffi-linux-riscv64@3.3.7", "", { "os": "linux", "cpu": "none" }, "sha512-IG1cp7agL1Od03NrKy8B0UGHomco0sygtWhWIXTTbjkJZkjE9Ic79IWzA5d16XbVtob+247XYBDcaeJJ644Xiw=="],
"@koromix/koffi-linux-x64": ["@koromix/koffi-linux-x64@3.3.7", "", { "os": "linux", "cpu": "x64" }, "sha512-1cxuG2zsO71wB3RwYt6AjJD9xQW0lUVw4TX4e3Q2DeffEqrVtE3g4IbQsnijTcSeZmmec1kDuuk4CSHUfhAEJQ=="],
"@koromix/koffi-openbsd-arm64": ["@koromix/koffi-openbsd-arm64@3.3.7", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-8qqafiMgdmOTEeZsLSnuKdg82Id8IwcxG8MowVtk0zJ4iNObmg2Ygd1dTtWRwpMBW0gfXoodwRdRqnUur3R/aA=="],
"@koromix/koffi-openbsd-ia32": ["@koromix/koffi-openbsd-ia32@3.3.7", "", { "os": "openbsd", "cpu": "ia32" }, "sha512-ZG06vAX5YUyUGAg9brg4maex7uGj1fybhlMrWt5FlocMBlrY05pn84vlCKavHsCficecAVq7yEzU8f+4FC2T7A=="],
"@koromix/koffi-openbsd-x64": ["@koromix/koffi-openbsd-x64@3.3.7", "", { "os": "openbsd", "cpu": "x64" }, "sha512-jnBD84VCXRmOeJniInO8g5xH2XwVnifp2w35+UbAx8coMIS99YAW9uDNg/U7ooJIyL9hfbatfeNkjNhYhhNpKw=="],
"@koromix/koffi-win32-arm64": ["@koromix/koffi-win32-arm64@3.3.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-Sal267u6Mi+UK/Lbu5vECQDtvZCfK57BO1zmc+Tar7Kdy+hHZ8Eqx7SyxTP6js4ofavQ83pVp1SWQqK8XJVpcg=="],
"@koromix/koffi-win32-ia32": ["@koromix/koffi-win32-ia32@3.3.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-kOPimggBxcLjHM/rHOWZp8fyxu+UjeEkWM26Gb9XCnirmM76xDu+GXCSDoBPPqF8s+XkY3NrhUdgfIXcwmWiPA=="],
"@koromix/koffi-win32-x64": ["@koromix/koffi-win32-x64@3.3.7", "", { "os": "win32", "cpu": "x64" }, "sha512-yVrh4Yzyjm+fH7CGIa8Ts+DSGeU8QrwEtECXxNswh3i86hwZTOKkqojaDFAYJov0B3w4BFcjR4TOKkPOB0ZpZA=="],
"@kwsites/file-exists": ["@kwsites/file-exists@1.1.1", "", { "dependencies": { "debug": "^4.1.1" } }, "sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw=="],
"@lexical/a11y": ["@lexical/a11y@0.49.0", "", { "dependencies": { "@lexical/extension": "0.49.0", "@lexical/utils": "0.49.0", "lexical": "0.49.0" }, "peerDependencies": { "typescript": ">=5.2" }, "optionalPeers": ["typescript"] }, "sha512-ypvO0SI9DCzEAjxkRLq+gNzRqfjg632RCkwu16Hk94PCBrEmcDhx5iUGg3SRJC7WnM2wXC/F/SB8yWDEfq7tEw=="],
@@ -826,6 +869,8 @@
"@lix-js/sdk-win32-x64": ["@lix-js/sdk-win32-x64@0.12.3", "", { "os": "win32", "cpu": "x64" }, "sha512-hnxMI7kPS4ngXs0ZVnOve5CmtC4+vaNIyNDi/yWU0rSvxj7mqw/1RCegTrCB7LjxlX4DG+eg9HruXurk9NDjGg=="],
"@microsoft/mxc-sdk": ["@microsoft/mxc-sdk@1.0.1", "", { "dependencies": { "koffi": "^3.2.1", "node-pty": "^1.1.0", "semver": "^7.7.4" } }, "sha512-2cP925G5+lQyKzjBVha8uNtVd7XESgDBtgi1yCYYSo9M3xiFyZWtCO4SWPGTk509rdI6nqjyGcZxvEP3t6l8Hg=="],
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
@@ -894,6 +939,8 @@
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
"@preact/signals-core": ["@preact/signals-core@1.14.4", "", {}, "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA=="],
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
@@ -2282,6 +2329,8 @@
"keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
"koffi": ["koffi@3.3.7", "", { "optionalDependencies": { "@koromix/koffi-android-arm64": "3.3.7", "@koromix/koffi-android-x64": "3.3.7", "@koromix/koffi-darwin-arm64": "3.3.7", "@koromix/koffi-darwin-x64": "3.3.7", "@koromix/koffi-freebsd-arm64": "3.3.7", "@koromix/koffi-freebsd-ia32": "3.3.7", "@koromix/koffi-freebsd-x64": "3.3.7", "@koromix/koffi-linux-arm": "3.3.7", "@koromix/koffi-linux-arm64": "3.3.7", "@koromix/koffi-linux-ia32": "3.3.7", "@koromix/koffi-linux-loong64": "3.3.7", "@koromix/koffi-linux-ppc64": "3.3.7", "@koromix/koffi-linux-riscv64": "3.3.7", "@koromix/koffi-linux-x64": "3.3.7", "@koromix/koffi-openbsd-arm64": "3.3.7", "@koromix/koffi-openbsd-ia32": "3.3.7", "@koromix/koffi-openbsd-x64": "3.3.7", "@koromix/koffi-win32-arm64": "3.3.7", "@koromix/koffi-win32-ia32": "3.3.7", "@koromix/koffi-win32-x64": "3.3.7" }, "hasInstallScript": true }, "sha512-Vrq4UwAE19HPLMou8m7HGCELiTE3l9D+r1nA7XwVHUTNaRdymPM+kzkkD2VGxlyjI2qZTb9tMDaFn7kfZ72v3Q=="],
"konva": ["konva@10.3.2", "", { "peerDependencies": { "canvas": "^3.0.0", "skia-canvas": "^3.0.0" }, "optionalPeers": ["canvas", "skia-canvas"] }, "sha512-A9GLx+Vj0PNnybjNq/St/S8utrksuSKOR8EzO2RTjA0SlmR9JipahcCXWW0vXz/9wjZCwAEtBtJFCUGe5mD/4g=="],
"kysely": ["kysely@0.28.17", "", {}, "sha512-nbD8lB9EB3wNdMhOCdx5Li8DxnLbvKByylRLcJ1h+4SkrowVeECAyZlyiKMThF7xFdRz0jSQ2MoJr+wXux2y0Q=="],
@@ -2440,6 +2489,8 @@
"next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
"node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
"node-emoji": ["node-emoji@2.2.0", "", { "dependencies": { "@sindresorhus/is": "^4.6.0", "char-regex": "^1.0.2", "emojilib": "^2.4.0", "skin-tone": "^2.0.0" } }, "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw=="],
@@ -2448,6 +2499,10 @@
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
"node-forge": ["node-forge@1.4.3", "", {}, "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g=="],
"node-pty": ["node-pty@1.1.0", "", { "dependencies": { "node-addon-api": "^7.1.0" }, "hasInstallScript": true }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
"node-releases": ["node-releases@2.0.54", "", {}, "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ=="],
"nodemailer": ["nodemailer@10.0.10", "", {}, "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A=="],
@@ -3004,6 +3059,10 @@
"@ai-sdk/provider-utils/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
"@anthropic-ai/sandbox-runtime/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.92", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.80", "@aws-sdk/credential-provider-http": "^3.972.82", "@aws-sdk/credential-provider-ini": "^3.973.25", "@aws-sdk/credential-provider-process": "^3.972.80", "@aws-sdk/credential-provider-sso": "^3.973.24", "@aws-sdk/credential-provider-web-identity": "^3.972.86", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-jC3zmOo7Qxlk+oBivvSsS1Ph7sFGm0QfuhqDGbqgRXi4cxUYMG+dWtBwS2XYYXgc8TIVXJiwgQ65sbNpbYupTA=="],
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
@@ -3042,6 +3101,8 @@
"@isaacs/cliui/wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="],
"@microsoft/mxc-sdk/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"@prisma/dev/std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
"@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.10.0", "", { "dependencies": { "@prisma/debug": "7.10.0" } }, "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w=="],
+27 -9
View File
@@ -1,14 +1,14 @@
---
title: Agent Runners
description: Connect an optional Bash runner and configure sandboxing on its machine.
description: Connect an optional command runner and configure sandboxing on its machine.
---
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.
Agents use Shumai's built-in tools without a runner. To execute shell 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
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`.
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on macOS, Linux, or Windows.
3. Start it in a dedicated, existing workspace:
```bash
@@ -17,9 +17,19 @@ export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
On Windows, set the variables in PowerShell:
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
Use 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.
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.
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 run commands immediately without reading a skill first. Disabled-tool policies still apply. An offline runner produces an execution error.
The `bash` tool uses the runner's native shell: `/bin/sh` on macOS/Linux and `cmd.exe` on Windows. The agent receives the OS and shell information and must use compatible commands. Windows does not require Bash or Git.
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.
@@ -27,14 +37,20 @@ Commands start in the workspace directory. Skills, downloaded assets, generated
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.
Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites on the runner machine:
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled as a library in Shumai CLI. Install its platform prerequisites on the runner machine (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then start with its JSON settings:
```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
```
Windows uses SRT's alpha Windows support. Run the one-time setup before starting a sandboxed runner; it requests administrator permission:
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT verifies the setup at startup and reports an error if it is missing. A runner without `--srt` does not need this setup.
The JSON uses upstream SRT settings directly. For example:
```json
@@ -53,9 +69,9 @@ The JSON uses upstream SRT settings directly. For example:
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.
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.
SRT wraps shell commands and their child processes. One shared SRT runtime handles concurrent commands and is reset when the runner stops. 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.
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.
Shumai has no server-side sandbox or domain settings. SRT is initialized 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.
## Runner in Docker
@@ -77,3 +93,5 @@ For development, HTTP is accepted for `localhost`, `127.0.0.1`, `[::1]`, and Doc
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`, existing symlinks, and unsafe archive entries. V1 assumes commands do not deliberately change workspace paths while transfers are running.
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.
Up to eight commands and file transfers can run concurrently in the shared workspace. Additional requests return a busy error. On Windows without SRT, background processes may survive after the command's shell exits; remaining output pipes are closed after one second. Use foreground commands for predictable timeout and cancellation. SRT manages the sandboxed Windows process tree.
+24 -8
View File
@@ -1,14 +1,14 @@
---
title: 智能体运行器
description: 连接可选的 Bash 运行器,并在运行器机器上配置沙箱。
description: 连接可选的命令运行器,并在运行器机器上配置沙箱。
---
智能体无需运行器即可使用内置工具。如需执行 Bash 或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
智能体无需运行器即可使用内置工具。如需执行命令或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
## 连接运行器
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
2. 在有 `/bin/bash` 的 macOS 或 Linux 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
2. 在 macOS、Linux 或 Windows 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
3. 在已有的专用工作目录中启动:
```bash
@@ -17,6 +17,14 @@ export SHUMAI_RUNNER_KEY="your-runner-key"
shumai-cli runner start --cwd /path/to/workspace
```
Windows 用户可在 PowerShell 中设置变量:
```powershell
$env:SHUMAI_API_SERVER = "https://shumai.example.com"
$env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
使用运行器密钥,而非个人 API 令牌。建议通过环境变量传入,避免 `--key` 将密钥留在命令历史中。运行器在前台执行,Ctrl+C 会停止运行器及其活动命令。临时断线后自动重连;密钥撤销或连接被替换时退出。
第一个运行器是团队默认运行器,也可在智能体设置中指定专用运行器。未配置运行器时隐藏 `bash` 和 `download_asset`。配置后,具有智能体使用权限的编辑者和审阅者可立即使用 Bash,无需先读取技能;禁用工具设置仍然生效。运行器离线时执行命令会返回错误。
@@ -27,14 +35,20 @@ shumai-cli runner start --cwd /path/to/workspace
未使用 `--srt` 时,命令具有运行器系统用户的权限。只连接可信 Shumai 服务器,可按需使用独立容器、虚拟机或账号。
在运行器机器上安装 [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) 及其平台依赖:
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) 已作为库内置于 Shumai CLI。安装平台依赖(Linux:bubblewrap、socat 和 ripgrep;macOS:ripgrep)后传入 JSON 配置:
```bash
npm install -g @anthropic-ai/sandbox-runtime
# Linux 还需要 SRT 文档中的平台依赖,包括 bubblewrap、socat 和 ripgrep。
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
```
Windows 使用 SRT 的实验性 Windows 支持。启用沙箱前执行一次初始化;此命令会请求管理员权限:
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT 会在启动时检查安装状态,缺少初始化时返回错误。未使用 `--srt` 的运行器不需要此步骤。`bash` 工具使用运行器的原生 Shell:macOS/Linux 为 `/bin/sh`,Windows 为 `cmd.exe`。智能体会收到系统和 Shell 信息,以生成匹配的命令。Windows 无需安装 Bash 或 Git。
直接使用上游 SRT JSON 格式,例如:
```json
@@ -53,9 +67,9 @@ shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
此例只允许写入 `.pi`,禁止读取所列凭证位置,并禁止命令访问网络。请参考 SRT 文档审查适合自己环境的读取权限和域名规则。相对路径以运行器工作目录为基准。配置在启动时读取并保存快照,修改后需要重启。配置缺失或无效、SRT 依赖缺失、沙箱初始化失败都会阻止启动,不会回退到无沙箱执行。
SRT 只包裹 Bash 及其子进程。运行器 WebSocket 和服务器发起的文件传输在 SRT 外运行。**不会自动将 Shumai 服务器地址添加到允许域名中。** 如果脚本自身需要网络,请在 JSON 中明确允许目标域名。
SRT 只包裹 Shell 命令及其子进程。并发命令共享同一个 SRT 运行时,运行器停止时统一清理。运行器 WebSocket 和服务器发起的文件传输在 SRT 外运行。**不会自动将 Shumai 服务器地址添加到允许域名中。** 如果脚本自身需要网络,请在 JSON 中明确允许目标域名。
Shumai 服务器不管理沙箱和域名规则。只有启用沙箱的运行器需要安装 SRT。在 Docker 中使用 SRT 可能需要为专用运行器容器增加命名空间权限,Shumai 服务器不需要这些权限。
Shumai 服务器不管理沙箱和域名规则。只有启用沙箱的运行器才初始化 SRT。在 Docker 中使用 SRT 可能需要为专用运行器容器增加命名空间权限,Shumai 服务器不需要这些权限。
## Docker 运行器
@@ -77,3 +91,5 @@ docker run --rm --init --name shumai-runner \
默认超时 120 秒,最长一小时。超时或取消会终止命令进程组。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、已有符号链接及不安全的压缩包条目。V1 假定命令不会在文件传输期间故意修改工作区路径。
临时重连会同步执行中及近期完成的命令,避免主动重复执行。重启运行器进程不会恢复旧进程中的命令。
共享工作区最多同时执行八个命令或文件传输,超出时返回繁忙错误。Windows 未启用 SRT 时,后台进程可能在命令 Shell 退出后继续运行,剩余输出管道会在一秒后关闭。请使用前台命令,以确保超时和取消可预测。启用 SRT 时由 SRT 管理 Windows 沙箱进程树。
+3
View File
@@ -319,6 +319,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const runnerBash = createRunnerBashTool(skillEnvs, {
teamId,
agentRunnerId: agent?.runnerId,
environment: resolvedRunner.runner
? runnerService.getRunnerEnvironment(resolvedRunner.runner.id)
: undefined,
userId,
role,
getLoadedSkills: () => loadedSkills.values(),
@@ -40,6 +40,16 @@ describe('createRunnerBashTool', () => {
const createMockOnUpdate = () => vi.fn()
it('tells the agent to use the runner OS and shell syntax', () => {
const tool = createRunnerBashTool(
{},
{ environment: { platform: 'win32', shell: 'C:\\Windows\\System32\\cmd.exe' } },
)
expect(tool.description).toContain('Runner OS: win32')
expect(tool.description).toContain('cmd.exe')
expect(tool.description).toContain('Use syntax and programs compatible with this environment')
})
it('should execute a command on the runner with injected env vars', async () => {
const tool = createRunnerBashTool(
{ TEST_ENV: 'test-value' },
+4 -2
View File
@@ -6,6 +6,7 @@ import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { runnerService } from '@shumai/core/src/runner'
import type { TeamMemberRole } from '@shumai/db'
import type { RunnerEnvironment } from '@shumai/dtos'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
@@ -16,7 +17,7 @@ import {
} from '../utils/truncate'
const BashParameters = Type.Object({
command: Type.String({ description: 'The bash command to execute.' }),
command: Type.String({ description: "The command to execute using the runner's shell." }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
inputFiles: Type.Optional(
Type.Union([
@@ -47,6 +48,7 @@ export interface RunnerBashOptions {
runnerId?: string
userId?: string
role?: TeamMemberRole | null
environment?: RunnerEnvironment
getLoadedSkills?: () => Iterable<LoadedSkillRef>
}
@@ -56,7 +58,7 @@ export const createRunnerBashTool = (
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
description: `Execute a bash command on the configured runner environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
description: `Execute a shell command on the configured runner. ${options?.environment ? `Runner OS: ${options.environment.platform}. Shell: ${options.environment.shell}. Use syntax and programs compatible with this environment.` : 'The runner reports its OS and shell when connected.'} Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
@@ -55,6 +55,41 @@ describe('RunnerService', () => {
})
describe('Key & workspace path helpers', () => {
it('keeps validated OS and shell metadata only for the current connection', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Windows runner' })
const connection = createMockWs()
const authenticated = {
id: runner.id,
teamId,
name: runner.name,
keyHash: hashRunnerKey(key),
}
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
await service.registerConnection(authenticated, connection.ws)
const environment = { platform: 'win32', shell: 'C:\\Windows\\System32\\cmd.exe' }
const reconcile = {
type: 'reconcile',
environment,
activeExecutions: [],
completedExecutions: [],
}
service.handleMessage(runner.id, connection.ws, JSON.stringify(reconcile))
expect(service.getRunnerEnvironment(runner.id)).toEqual(environment)
service.handleMessage(
runner.id,
connection.ws,
JSON.stringify({ ...reconcile, environment: { platform: 'invalid', shell: '' } }),
)
expect(service.getRunnerEnvironment(runner.id)).toEqual(environment)
const replacement = createMockWs()
await service.registerConnection(authenticated, replacement.ws)
service.handleMessage(runner.id, connection.ws, JSON.stringify(reconcile))
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
service.handleMessage(runner.id, replacement.ws, JSON.stringify(reconcile))
service.handleDisconnect(runner.id, replacement.ws)
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
})
it('generates and hashes runner keys', () => {
const { key, keyPrefix, keyHash } = generateRunnerKey()
expect(key).toMatch(/^shm_rn_[0-9a-f]{48}$/)
@@ -599,6 +634,7 @@ describe('RunnerService', () => {
conn2.ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: [{ executionId: startMsg.executionId, nextOffset: 0 }],
completedExecutions: [],
}),
@@ -11,6 +11,7 @@ import {
RunnerFileStatResultMessage,
RunnerFileUploadResultMessage,
RunnerInfo,
RunnerEnvironment,
RunnerToServerMessage,
runnerToServerMessageSchema,
ServerToRunnerMessage,
@@ -42,6 +43,7 @@ interface ActiveRunnerSession {
lastPongAt: number
stagedSkills: Map<string, string>
stagedGeneratedFiles: Set<string>
environment?: RunnerEnvironment
}
interface PendingExecOperation {
@@ -174,6 +176,10 @@ export class RunnerService {
return this.sessions.has(runnerId)
}
getRunnerEnvironment(runnerId: string): RunnerEnvironment | undefined {
return this.sessions.get(runnerId)?.environment
}
// ----------------------------------------------------------------------
// Runner CRUD & Default Runner Invariant
// ----------------------------------------------------------------------
@@ -559,6 +565,7 @@ export class RunnerService {
case 'pong':
break
case 'reconcile':
session.environment = msg.environment
this.handleReconcileMessage(session, msg)
break
case 'exec.output':
+7
View File
@@ -136,8 +136,15 @@ export const runnerExecResultMessageSchema = z.object({
})
export type RunnerExecResultMessage = z.infer<typeof runnerExecResultMessageSchema>
export const runnerEnvironmentSchema = z.object({
platform: z.enum(['darwin', 'linux', 'win32']),
shell: z.string().min(1).max(1024),
})
export type RunnerEnvironment = z.infer<typeof runnerEnvironmentSchema>
export const runnerReconcileMessageSchema = z.object({
type: z.literal('reconcile'),
environment: runnerEnvironmentSchema,
activeExecutions: z.array(
z.object({
executionId: z.string(),
+4 -4
View File
@@ -1703,7 +1703,7 @@
"task_type_restore_asset": "Restore Asset",
"agent_runners": "Agent Runners",
"agent_runners_settings": "Agent Runners",
"runners_description": "Register and manage remote runners that execute bash commands and skills for your agents.",
"runners_description": "Register and manage remote runners that execute shell commands and skills for your agents.",
"runners": "Runners",
"create_runner": "Create Runner",
"create_runner_description": "Register a new runner for your team. You will receive a one-time runner key to connect from shumai-cli.",
@@ -1732,7 +1732,7 @@
"runner_quickstart_command_label": "Quickstart Command",
"runner_quickstart_sandbox_label": "Start with Sandbox (Optional)",
"runner_empty_title": "No runners configured",
"runner_empty_description": "When no runner is configured, the bash and download_asset tools are automatically hidden from agents. Create a runner and start it with shumai-cli to enable bash execution.",
"runner_empty_description": "When no runner is configured, the bash and download_asset tools are automatically hidden from agents. Create a runner and start it with shumai-cli to enable command execution.",
"runner_created_successfully": "Runner created successfully",
"runner_updated_successfully": "Runner updated successfully",
"runner_deleted_successfully": "Runner deleted successfully",
@@ -1743,8 +1743,8 @@
"failed_to_delete_runner": "Failed to delete runner",
"failed_to_rotate_runner_key": "Failed to rotate runner key",
"runner_copied_to_clipboard": "Copied to clipboard",
"agent_runner_label": "Bash Runner",
"agent_runner_description": "Select which runner executes bash commands and downloads workspace assets for this agent.",
"agent_runner_label": "Command Runner",
"agent_runner_description": "Select which runner executes shell commands and downloads workspace assets for this agent.",
"agent_runner_team_default": "Team Default Runner",
"agent_runner_team_default_with_name": "Team Default ({name})",
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners."
+4 -4
View File
@@ -1703,7 +1703,7 @@
"task_type_restore_asset": "恢复归档资产",
"agent_runners": "Agent 运行器",
"agent_runners_settings": "Agent 运行器设置",
"runners_description": "注册并管理为 Agent 执行 Bash 命令和技能的远程运行器。",
"runners_description": "注册并管理为 Agent 执行命令和技能的远程运行器。",
"runners": "运行器",
"create_runner": "创建运行器",
"create_runner_description": "为团队注册一个新的运行器。创建后将生成一次性运行器密钥,用于通过 shumai-cli 连接。",
@@ -1732,7 +1732,7 @@
"runner_quickstart_command_label": "快速启动命令",
"runner_quickstart_sandbox_label": "启用沙箱启动(可选)",
"runner_empty_title": "尚未配置运行器",
"runner_empty_description": "未配置运行器时,Agent 的 bash 和 download_asset 工具将自动隐藏。创建一个运行器并通过 shumai-cli 启动即可启用 Bash 执行能力。",
"runner_empty_description": "未配置运行器时,Agent 的 bash 和 download_asset 工具将自动隐藏。创建一个运行器并通过 shumai-cli 启动即可启用命令执行能力。",
"runner_created_successfully": "运行器创建成功",
"runner_updated_successfully": "运行器更新成功",
"runner_deleted_successfully": "运行器删除成功",
@@ -1743,8 +1743,8 @@
"failed_to_delete_runner": "删除运行器失败",
"failed_to_rotate_runner_key": "轮换运行器密钥失败",
"runner_copied_to_clipboard": "已复制到剪贴板",
"agent_runner_label": "Bash 运行器",
"agent_runner_description": "选择为该 Agent 执行 Bash 命令和下载工作空间资产的运行器。",
"agent_runner_label": "命令运行器",
"agent_runner_description": "选择为该 Agent 执行命令和下载工作空间资产的运行器。",
"agent_runner_team_default": "团队默认运行器",
"agent_runner_team_default_with_name": "团队默认({name})",
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。"
+2
View File
@@ -6,6 +6,7 @@ import { parseArgs } from 'node:util'
import { fileURLToPath } from 'node:url'
import { version } from '../package.json'
import { version as cliVersion } from '../apps/cli/package.json'
import { srtBundlePlugin } from './srt-bundle'
export const cliTargets = {
'darwin-arm64': 'bun-darwin-arm64',
@@ -90,6 +91,7 @@ export async function buildCliRelease(outdir: string, targets = cliTargetNames)
entrypoints: [join(repoRoot, 'apps/cli/src/index.ts')],
target: 'bun',
minify: true,
plugins: [srtBundlePlugin(...target.split('-'))],
compile: {
target: cliTargets[target],
outfile: binary,
+2
View File
@@ -2,6 +2,7 @@ import tailwindPlugin from 'bun-plugin-tailwind'
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { cp, mkdir, readdir, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { srtBundlePlugin } from './srt-bundle'
console.log('\n🚀 Starting NPM packaging build process for all applications...\n')
@@ -521,6 +522,7 @@ async function buildCliPackage() {
outdir: binOutDir,
minify: true,
naming: 'shumai-cli.js',
plugins: [srtBundlePlugin()],
external: [],
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
+36
View File
@@ -0,0 +1,36 @@
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
/** Keep SRT's native helpers available in both standalone binaries and the Node bundle. */
export function srtBundlePlugin(platform?: string, arch?: string): Bun.BunPlugin {
return {
name: 'srt-vendor',
setup(build) {
build.onLoad({ filter: /[/\\]runner[/\\]srt-vendor\.ts$/ }, async () => {
const packageJson = createRequire(
new URL('../apps/cli/package.json', import.meta.url),
).resolve('@anthropic-ai/sandbox-runtime/package.json')
const names = ['java-proxy-agent/srt-proxy-agent.jar']
for (const cpu of arch ? [arch] : ['x64', 'arm64']) {
if (!platform || platform === 'linux') names.push(`seccomp/${cpu}/apply-seccomp`)
if (!platform || platform === 'windows') names.push(`srt-win/${cpu}/srt-win.exe`)
}
const assets = Object.fromEntries(
await Promise.all(
names.map(async (name) => [
name,
(await readFile(path.join(path.dirname(packageJson), 'vendor', name))).toString(
'base64',
),
]),
),
)
return {
contents: `export const bundledSrtVendor = ${JSON.stringify(assets)}`,
loader: 'js',
}
})
},
}
}