Compare commits

..
9 Commits
60 changed files with 334 additions and 1848 deletions
+4 -9
View File
@@ -8,14 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
### Fixed
### Changed
## [0.7.0] - 2026-11-18
### Added
- **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.
### Fixed
@@ -24,7 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **agent**: ⚠️ **Breaking Change**: Replaced the built-in server-side Bash sandbox with external Runners and removed the team-level sandbox domain allowlist settings. The Bash tool is now disabled by default. If your Agent or Skills require Bash execution, you'll need to set up and connect an external Runner using shumai-cli. The Shumai CLI includes built-in sandbox support, allowing you to configure filesystem access and network domain allowlists for Bash execution directly on the Runner. See [Agent Runners](https://docs.shumai.one/using-shumai/agent-sandbox) for setup instructions and configuration details. The Docker Compose configuration has also been updated to improve security following the removal of the server-side sandbox. We strongly recommend upgrading to the latest Shumai image and updating your Docker Compose file to apply these security improvements.
- **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.
## [0.6.6] - 2026-11-13
+4 -4
View File
@@ -104,9 +104,9 @@ $env:SHUMAI_RUNNER_KEY = "your-runner-key"
shumai-cli runner start --cwd C:\workspace
```
Use `--url` or `--key` to override those variables. Pass `-v` or `--verbose` to log executed commands, output sizes, and file transfer paths (by default, only lifecycle events, execution IDs, exit status, and durations are printed to stderr). 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.
Use `--url` or `--key` to override those variables. A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
Commands use `/bin/sh` on macOS and Linux. On Windows, the runner checks for Git Bash in the standard installation directories, then for `bash.exe` on PATH, then falls back to `cmd.exe`. It prints the selected shell at startup and reports it to the agent. Commands run with the local user's permissions unless SRT is requested.
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:
@@ -114,7 +114,7 @@ Commands use `/bin/sh` on macOS and Linux. On Windows, the runner checks for Git
shumai-cli runner start --srt sandbox.json
```
Windows sandboxing uses SRT's alpha Windows support. Use Git Bash if your selected shell is the legacy WSL Bash launcher. Run the one-time SRT setup before starting a sandboxed runner (it requests administrator permission):
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
@@ -368,7 +368,7 @@ bun run build:cli --target darwin-arm64 # or darwin-x64, linux-arm64, linux-x64,
bun run test:cli-release
```
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`. Set `--out /absolute/path` on either command to change it. Unix archives require `tar`. Creating Windows archives on Unix also requires `zip`. The test exercises installation, runner shell quoting, authenticated API calls, file transfers, and failure recovery. Install Git Bash to run the quoting check on Windows. With SRT configured, pass `--srt /absolute/path/to/settings.json` to repeat the quoting check in the sandbox.
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`; both commands accept `--out /absolute/path`. Unix archives require `tar`; creating Windows archives on Unix also requires `zip`. The test runs the generated installer against local HTTP fixtures, then authenticates, creates a folder, uploads and downloads random bytes, and checks failure recovery with no runtime on the executable's PATH.
The Native CLI workflow builds and tests each target on a matching runner. The npm release workflow assembles those tested archives, stages a draft GitHub Release, publishes npm packages, then publishes the completed release. Its `validate_only` dispatch input builds and tests without publishing. Published assets are verified and preserved on retries; draft assets can be replaced while resuming a failed run. Prerelease npm packages use the `next` tag and prerelease GitHub Releases do not become latest.
-24
View File
@@ -1,24 +0,0 @@
The Windows Bash discovery and related tests include material adapted from Pi.
https://github.com/earendil-works/pi
MIT License
Copyright (c) 2025 Mario Zechner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+2 -2
View File
@@ -1,13 +1,13 @@
{
"name": "@shumai/cli",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"bin": {
"shumai-cli": "./src/index.ts"
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.83",
"@anthropic-ai/sandbox-runtime": "0.0.82",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
-20
View File
@@ -33,10 +33,8 @@ function setup() {
let stdout = ''
let stderr = ''
const callOperation = vi.fn<CallOperation>()
const startRunner = vi.fn(async () => {})
const program = createProgram({
callOperation,
startRunner,
output: { out: { write: (s) => void (stdout += s) }, isTty: true, columns: 120 },
})
const configure = (cmd: Command) => {
@@ -49,7 +47,6 @@ function setup() {
configure(program)
return {
callOperation,
startRunner,
run: (...argv: string[]) => program.parseAsync(['node', 'shumai-cli', ...argv]),
stdout: () => stdout,
stderr: () => stderr,
@@ -860,23 +857,6 @@ describe('shumai-cli', () => {
})
})
describe('runner start', () => {
it('documents and forwards the -v, --verbose flag', async () => {
const cli = setup()
await expect(cli.run('runner', 'start', '--help')).rejects.toThrow()
expect(cli.stdout()).toContain('-v, --verbose')
await cli.run('runner', 'start')
expect(cli.startRunner).toHaveBeenLastCalledWith({})
await cli.run('runner', 'start', '-v')
expect(cli.startRunner).toHaveBeenLastCalledWith({ verbose: true })
await cli.run('runner', 'start', '--verbose')
expect(cli.startRunner).toHaveBeenLastCalledWith({ verbose: true })
})
})
it('has no upload Operation commands: upload and create-version stream local files', () => {
const program = createProgram({ callOperation: vi.fn<CallOperation>() })
const names = program.commands.map((c) => c.name())
+1 -4
View File
@@ -8,12 +8,10 @@ import { registerOperationCommands } from './operations/generate'
import type { Output } from './operations/render'
import { version } from '../package.json'
import { startRunner } from './runner/client'
import type { RunnerOptions } from './runner/config'
export interface ProgramOptions {
callOperation?: CallOperation
output?: Output
startRunner?: (options: RunnerOptions) => Promise<void>
}
function isDeleteAllowed(): boolean {
@@ -55,8 +53,7 @@ export function createProgram(options: ProgramOptions = {}): Command {
.option('--key <key>', 'Runner key (prefer SHUMAI_RUNNER_KEY to avoid shell history).')
.option('--cwd <directory>', 'Runner workspace directory (defaults to the current directory).')
.option('--srt <file>', 'Sandbox commands with bundled SRT using this JSON settings file.')
.option('-v, --verbose', 'Show command details, output sizes, and file transfer paths.')
.action((opts: RunnerOptions) => (options.startRunner ?? startRunner)(opts))
.action(startRunner)
program
.command('upload')
+12 -289
View File
@@ -1,4 +1,3 @@
import { createServer } from 'node:http'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
@@ -18,21 +17,17 @@ describe('runner WebSocket client', () => {
let messages: RunnerToServerMessage[]
let welcomeInFlight: string[]
let connections: number
let replacePrevious: boolean
let connectRunner: (options?: { verbose?: boolean; log?: (line: string) => void }) => RunnerClient
beforeEach(async () => {
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-client-test-'))
messages = []
welcomeInFlight = []
connections = 0
replacePrevious = false
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')
if (replacePrevious) socket.close(4000, 'Replaced by a newer connection')
socket = connection
connections++
connection.on('message', (raw) =>
@@ -48,22 +43,18 @@ describe('runner WebSocket client', () => {
}),
)
})
connectRunner = (options) => {
const files = new RunnerFiles(cwd)
return new RunnerClient(
{
url: new URL(`ws://127.0.0.1:${address.port}/api/runners/ws`),
key: 'runner-key',
cwd,
srt: undefined,
verbose: options?.verbose ?? false,
},
files,
new RunnerShell(files),
options?.log ?? (() => {}),
)
}
runner = connectRunner()
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(() => {})
@@ -170,277 +161,9 @@ describe('runner WebSocket client', () => {
expect(connections).toBe(1)
})
it('stops the superseded client when a second runner connects with the same key', async () => {
replacePrevious = true
let replaced: unknown
void running.catch((error: unknown) => {
replaced = error
})
const replacement = connectRunner()
const replacementRun = replacement.run()
void replacementRun.catch(() => {})
try {
await vi.waitFor(() => expect(replaced).toBeInstanceOf(Error))
await expect(running).rejects.toThrow('replaced')
expect(connections).toBe(2)
} finally {
replacement.stop()
await replacementRun.catch(() => {})
}
})
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)
})
it('logs compact lifecycle, bash, and transfer summaries in default mode', async () => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose: false, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
send({ type: 'exec.start', executionId: '01JTEST0000A8F2', command: 'printf "hello"' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
)
send({
type: 'exec.start',
executionId: '01JTEST0000TOUT',
command: 'sleep 5',
timeoutSec: 0.1,
})
await vi.waitFor(() =>
expect(
messages.some(
(message) => message.type === 'exec.result' && message.executionId === '01JTEST0000TOUT',
),
).toBe(true),
)
send({ type: 'file.stat', executionId: '01JTEST0000STAT', srcPath: '.pi/missing' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
)
const httpServer = createServer((_request, response) => {
response.end('payload')
})
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve))
try {
const httpAddress = httpServer.address()
if (!httpAddress || typeof httpAddress === 'string') throw new Error('No HTTP address')
send({
type: 'file.download',
executionId: '01JTEST0000C3D9',
url: `http://127.0.0.1:${httpAddress.port}/file`,
destPath: '.pi/assets/file.txt',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.download.result')).toBe(true),
)
} finally {
httpServer.closeAllConnections()
await new Promise<void>((resolve) => httpServer.close(() => resolve()))
}
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Runner connected: Test \(runner\)$/.test(line),
),
).toBe(true)
expect(
logs.some((line) => /^\d{2}:\d{2}:\d{2} INFO {2}Bash started \[a8f2\]$/.test(line)),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash completed \[a8f2\] exit=0 duration=\d+\.\ds$/.test(line),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} WARN {2}Bash timed out \[tout\] duration=\d+\.\ds$/.test(line),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File download completed \[c3d9\] size=7B duration=\d+\.\ds$/.test(
line,
),
),
).toBe(true)
expect(logs.join('\n')).not.toContain('command=')
expect(logs.join('\n')).not.toContain('File stat')
expect(logs.join('\n')).not.toContain('.pi/assets/file.txt')
})
it('logs commands, stream sizes, and file paths in verbose mode', async () => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose: true, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
send({
type: 'exec.start',
executionId: '01JTEST0000B9E1',
command: 'printf "hi"; printf "err" >&2',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
)
send({ type: 'file.stat', executionId: '01JTEST0000B1A4', srcPath: '.pi/missing' })
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
)
const httpServer = createServer((_request, response) => {
response.writeHead(500)
response.end()
})
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve))
try {
const httpAddress = httpServer.address()
if (!httpAddress || typeof httpAddress === 'string') throw new Error('No HTTP address')
send({
type: 'file.download',
executionId: '01JTEST0000E5F1',
url: `http://127.0.0.1:${httpAddress.port}/fail`,
destPath: '.pi/assets/fail.txt',
})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'file.download.result')).toBe(true),
)
} finally {
httpServer.closeAllConnections()
await new Promise<void>((resolve) => httpServer.close(() => resolve()))
}
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash started \[b9e1\] command="printf \\"hi\\"; printf \\"err\\" >&2"$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}Bash completed \[b9e1\] exit=0 duration=\d+\.\ds stdout=2B stderr=3B$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File stat \[b1a4\] path="\.pi\/missing" exists=false$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} INFO {2}File download started \[e5f1\] path="\.pi\/assets\/fail\.txt"$/.test(
line,
),
),
).toBe(true)
expect(
logs.some((line) =>
/^\d{2}:\d{2}:\d{2} WARN {2}File download failed \[e5f1\] path="\.pi\/assets\/fail\.txt" duration=\d+\.\ds error="Download failed \(HTTP 500\)\."$/.test(
line,
),
),
).toBe(true)
})
it.each([false, true])(
'logs a single busy rejection without false starts at capacity (verbose=%s)',
async (verbose) => {
runner.stop()
await running.catch(() => {})
const logs: string[] = []
messages = []
runner = connectRunner({ verbose, log: (line) => logs.push(line) })
running = runner.run()
void running.catch(() => {})
await vi.waitFor(() =>
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
)
for (let index = 0; index < 8; index++) {
send({
type: 'exec.start',
executionId: `01JACTIVE00000${index}`,
command: 'sleep 30',
})
}
await vi.waitFor(() =>
expect(logs.filter((line) => line.includes('Bash started'))).toHaveLength(8),
)
send({
type: 'exec.start',
executionId: '01JBUSYCMD00B123',
command: 'echo rejected',
})
send({
type: 'file.upload',
executionId: '01JBUSYFILE0U456',
srcPath: '.pi/out.bin',
url: 'http://127.0.0.1:9/upload',
})
await vi.waitFor(() => {
expect(messages).toContainEqual(
expect.objectContaining({
type: 'exec.result',
executionId: '01JBUSYCMD00B123',
error: 'Runner is busy. Try again later.',
}),
)
expect(messages).toContainEqual(
expect.objectContaining({
type: 'file.upload.result',
executionId: '01JBUSYFILE0U456',
ok: false,
error: 'Runner is busy. Try again later.',
}),
)
})
const bashLogs = logs.filter((line) => line.includes('[b123]'))
const uploadLogs = logs.filter((line) => line.includes('[u456]'))
expect(bashLogs).toHaveLength(1)
expect(uploadLogs).toHaveLength(1)
if (verbose) {
expect(bashLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}Bash rejected \[b123\] command="echo rejected" error="Runner is busy\. Try again later\."$/,
)
expect(uploadLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}File upload rejected \[u456\] path="\.pi\/out\.bin" error="Runner is busy\. Try again later\."$/,
)
} else {
expect(bashLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}Bash rejected \[b123\] \(runner is busy\)$/,
)
expect(uploadLogs[0]).toMatch(
/^\d{2}:\d{2}:\d{2} WARN {2}File upload rejected \[u456\] \(runner is busy\)$/,
)
}
},
)
})
+54 -204
View File
@@ -1,7 +1,6 @@
import WebSocket from 'ws'
import { setTimeout as delay } from 'node:timers/promises'
import {
RUNNER_REPLACED_CLOSE_CODE,
serverToRunnerMessageSchema,
type RunnerExecOutputMessage,
type RunnerExecResultMessage,
@@ -9,36 +8,19 @@ import {
type ServerToRunnerMessage,
} from '@shumai/dtos'
import { CliError } from '../operations/errors'
import { resolveRunnerConfig, type RunnerConfig, type RunnerOptions } from './config'
import { resolveRunnerConfig, type RunnerOptions } from './config'
import { RunnerFiles, type FileMessage } from './files'
import {
createRunnerLogger,
formatBytes,
formatDuration,
formatLogString,
shortId,
type RunnerLogger,
} from './log'
import { RunnerShell } from './shell'
const MAX_REPLAY_BYTES = 1024 * 1024
const MAX_COMPLETED = 16
const MAX_ACTIVE = 8
const RUNNER_BUSY_ERROR = 'Runner is busy. Try again later.'
const FILE_OPERATION_KINDS: Record<FileMessage['type'], 'download' | 'upload' | 'stat'> = {
'file.download': 'download',
'file.upload': 'upload',
'file.stat': 'stat',
}
interface Execution {
controller: AbortController
chunks: RunnerExecOutputMessage[]
bytes: number
offset: number
startedAt: number
stdoutBytes: number
stderrBytes: number
result?: RunnerExecResultMessage
}
@@ -50,16 +32,13 @@ export class RunnerClient {
private transfers = new Map<string, AbortController>()
private completedFiles = new Map<string, RunnerToServerMessage>()
private pending = new Set<Promise<void>>()
private readonly logger: RunnerLogger
constructor(
private readonly config: RunnerConfig,
private readonly config: Awaited<ReturnType<typeof resolveRunnerConfig>>,
private readonly files: RunnerFiles,
private readonly shell: RunnerShell,
log: (message: string) => void = console.error,
) {
this.logger = createRunnerLogger(log, Boolean(config.verbose))
}
private readonly log: (message: string) => void = console.error,
) {}
async run(signal?: AbortSignal): Promise<void> {
const stop = () => this.stop()
@@ -71,7 +50,7 @@ export class RunnerClient {
const wasReady = await this.connect()
if (this.stopped.signal.aborted) break
attempt = wasReady ? 0 : Math.min(attempt + 1, 5)
this.logger.warn('Runner disconnected; reconnecting…')
this.log('Runner disconnected; reconnecting…')
await delay(Math.min(1000 * 2 ** attempt, 30_000), undefined, {
signal: this.stopped.signal,
}).catch(() => {})
@@ -122,7 +101,7 @@ export class RunnerClient {
socket.on('close', (code) => {
clearInterval(heartbeat)
this.ready = false
if ((code === 1008 || code === RUNNER_REPLACED_CLOSE_CODE) && !this.stopped.signal.aborted)
if (code === 1008 && !this.stopped.signal.aborted)
reject(
new CliError('Runner access was revoked or another connection replaced this runner.'),
)
@@ -139,7 +118,7 @@ export class RunnerClient {
welcomed = true
this.ready = true
this.reconcile(parsed.inFlightExecutionIds)
this.logger.info(`Runner connected: ${parsed.runnerName} (${parsed.runnerId})`)
this.log(`Runner connected: ${parsed.runnerName} (${parsed.runnerId})`)
} else {
if (!welcomed) throw new Error('Expected welcome before runner requests.')
this.handle(parsed)
@@ -196,78 +175,55 @@ export class RunnerClient {
if (previous.result) this.send(previous.result)
return
}
const id = shortId(message.executionId)
if (this.activeCount() >= MAX_ACTIVE) {
const result: RunnerExecResultMessage = {
type: 'exec.result',
executionId: message.executionId,
exitCode: null,
signal: null,
timedOut: false,
error: RUNNER_BUSY_ERROR,
}
this.recordCompletedExecution(message.executionId, result)
this.logger.warn(
this.logger.verbose
? `Bash rejected [${id}] command=${formatLogString(message.command)} error=${formatLogString(RUNNER_BUSY_ERROR)}`
: `Bash rejected [${id}] (runner is busy)`,
)
this.send(result)
return
}
const execution: Execution = {
controller: new AbortController(),
chunks: [],
bytes: 0,
offset: 0,
startedAt: performance.now(),
stdoutBytes: 0,
stderrBytes: 0,
}
this.executions.set(message.executionId, execution)
this.logger.info(
this.logger.verbose
? `Bash started [${id}] command=${formatLogString(message.command)}`
: `Bash started [${id}]`,
)
this.track(
(async () => {
const result = 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
if (stream === 'stdout') execution.stdoutBytes += bytes
else execution.stderrBytes += 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)
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.logExecResult(id, execution, result)
this.send(result)
this.pruneCompletedExecutions()
const completed = [...this.executions].filter(([, value]) => value.result)
for (const [id] of completed.slice(0, -MAX_COMPLETED)) this.executions.delete(id)
})(),
)
return
@@ -275,53 +231,6 @@ export class RunnerClient {
this.handleFile(message)
}
private recordCompletedExecution(executionId: string, result: RunnerExecResultMessage) {
this.executions.set(executionId, {
controller: new AbortController(),
chunks: [],
bytes: 0,
offset: 0,
startedAt: performance.now(),
stdoutBytes: 0,
stderrBytes: 0,
result,
})
this.pruneCompletedExecutions()
}
private pruneCompletedExecutions() {
const completed = [...this.executions].filter(([, value]) => value.result)
for (const [completedId] of completed.slice(0, -MAX_COMPLETED))
this.executions.delete(completedId)
}
private logExecResult(id: string, execution: Execution, result: RunnerExecResultMessage) {
const duration = formatDuration(performance.now() - execution.startedAt)
const sizes = this.logger.verbose
? ` stdout=${formatBytes(execution.stdoutBytes)} stderr=${formatBytes(execution.stderrBytes)}`
: ''
if (result.timedOut) {
const error =
this.logger.verbose && result.error ? ` error=${formatLogString(result.error)}` : ''
this.logger.warn(`Bash timed out [${id}] duration=${duration}${sizes}${error}`)
return
}
if (result.aborted) {
this.logger.info(`Bash cancelled [${id}] duration=${duration}${sizes}`)
return
}
if (result.error) {
const error = this.logger.verbose ? ` error=${formatLogString(result.error)}` : ''
this.logger.warn(`Bash failed [${id}] duration=${duration}${sizes}${error}`)
return
}
if (result.exitCode === null && result.signal) {
this.logger.warn(`Bash killed [${id}] signal=${result.signal} duration=${duration}${sizes}`)
return
}
this.logger.info(`Bash completed [${id}] exit=${result.exitCode} duration=${duration}${sizes}`)
}
private activeCount() {
return (
[...this.executions.values()].filter((execution) => !execution.result).length +
@@ -336,34 +245,19 @@ export class RunnerClient {
return
}
if (this.transfers.has(message.executionId)) return
const id = shortId(message.executionId)
const transferPath = message.type === 'file.download' ? message.destPath : message.srcPath
if (this.activeCount() >= MAX_ACTIVE) {
const result = this.fileBusy(message)
this.recordCompletedFile(message.executionId, result)
const kind = FILE_OPERATION_KINDS[message.type]
this.logger.warn(
this.logger.verbose
? `File ${kind} rejected [${id}] path=${formatLogString(transferPath)} error=${formatLogString(RUNNER_BUSY_ERROR)}`
: `File ${kind} rejected [${id}] (runner is busy)`,
)
this.send(result)
return
}
const controller = new AbortController()
this.transfers.set(message.executionId, controller)
const timer = setTimeout(() => controller.abort(), 120_000)
const startedAt = performance.now()
if (this.logger.verbose && message.type !== 'file.stat') {
const kind = message.type === 'file.download' ? 'download' : 'upload'
this.logger.info(`File ${kind} started [${id}] path=${formatLogString(transferPath)}`)
}
this.track(
(async () => {
try {
const result = await this.files.handle(message, controller.signal)
this.recordCompletedFile(message.executionId, result)
this.logFileResult(id, transferPath, startedAt, result)
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)
@@ -373,52 +267,11 @@ export class RunnerClient {
)
}
private recordCompletedFile(executionId: string, result: RunnerToServerMessage) {
this.completedFiles.set(executionId, result)
if (this.completedFiles.size > MAX_COMPLETED)
this.completedFiles.delete(this.completedFiles.keys().next().value!)
}
private logFileResult(
id: string,
transferPath: string,
startedAt: number,
result: RunnerToServerMessage,
) {
if (result.type === 'file.stat.result') {
if (!this.logger.verbose) return
const pathPart = `path=${formatLogString(transferPath)}`
if (!result.ok) {
this.logger.warn(
`File stat failed [${id}] ${pathPart} error=${formatLogString(result.error ?? 'Unknown error')}`,
)
return
}
const sizePart = result.exists ? ` size=${formatBytes(result.size ?? 0)}` : ''
this.logger.info(`File stat [${id}] ${pathPart} exists=${result.exists}${sizePart}`)
return
}
if (result.type !== 'file.download.result' && result.type !== 'file.upload.result') return
const kind = result.type === 'file.download.result' ? 'download' : 'upload'
const duration = formatDuration(performance.now() - startedAt)
const pathPart = this.logger.verbose ? ` path=${formatLogString(transferPath)}` : ''
if (result.ok) {
this.logger.info(
`File ${kind} completed [${id}]${pathPart} size=${formatBytes(result.size ?? 0)} duration=${duration}`,
)
return
}
const errorPart = this.logger.verbose
? ` error=${formatLogString(result.error ?? 'Unknown error')}`
: ''
this.logger.warn(`File ${kind} failed [${id}]${pathPart} duration=${duration}${errorPart}`)
}
private fileBusy(message: FileMessage): RunnerToServerMessage {
const result = {
executionId: message.executionId,
ok: false,
error: RUNNER_BUSY_ERROR,
error: 'Runner is busy. Try again later.',
}
switch (message.type) {
case 'file.download':
@@ -438,14 +291,11 @@ export class RunnerClient {
export async function startRunner(options: RunnerOptions) {
const config = await resolveRunnerConfig(options)
const files = new RunnerFiles(config.cwd)
const shell = new RunnerShell(files, config.srt)
// 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()
createRunnerLogger(console.error, Boolean(config.verbose)).info(
`Runner shell: ${shell.environment.shell}`,
)
const runner = new RunnerClient(config, files, shell)
const controller = new AbortController()
const shutdown = () => controller.abort()
+8 -3
View File
@@ -1,9 +1,16 @@
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')
@@ -24,8 +31,6 @@ describe('runner configuration', () => {
expect(config.url.href).toBe('wss://example.com/shumai/api/runners/ws')
expect(config.key).toBe('runner-secret')
expect(config.cwd).toBe(process.cwd())
expect(config.verbose).toBe(false)
expect((await resolveRunnerConfig({ verbose: true })).verbose).toBe(true)
})
it.each([
+8 -17
View File
@@ -7,18 +7,9 @@ export interface RunnerOptions {
key?: string
cwd?: string
srt?: string
verbose?: boolean
}
export interface RunnerConfig {
url: URL
key: string
cwd: string
srt?: string
verbose?: boolean
}
export async function resolveRunnerConfig(options: RunnerOptions): Promise<RunnerConfig> {
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.')
@@ -50,13 +41,13 @@ export async function resolveRunnerConfig(options: RunnerOptions): Promise<Runne
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/runners/ws`
const cwd = await realpath(path.resolve(options.cwd ?? process.cwd()))
if (!(await stat(cwd)).isDirectory()) throw new CliError('Runner workspace must be a directory.')
return {
url,
key: key.trim(),
cwd,
srt: options.srt ? path.resolve(options.srt) : undefined,
verbose: Boolean(options.verbose),
}
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. */
-39
View File
@@ -5,7 +5,6 @@ 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 yauzl from 'yauzl'
import { RunnerFiles } from './files'
describe('runner workspace file transfers', () => {
@@ -306,44 +305,6 @@ describe('runner workspace file transfers', () => {
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual(['installed'])
}, 10000)
it('waits for an in-flight ZIP entry read before closing on cancellation', async () => {
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from('skill'))
body = zip.toBuffer()
const controller = new AbortController()
const pendingRead = Promise.withResolvers<() => void>()
const readEntry = yauzl.ZipFile.prototype.readEntry
const read = vi.spyOn(yauzl.ZipFile.prototype, 'readEntry').mockImplementationOnce(function (
this: yauzl.ZipFile,
) {
pendingRead.resolve(() => readEntry.call(this))
})
const close = vi.spyOn(yauzl.ZipFile.prototype, 'close')
try {
const transfer = files.handle(
{
type: 'file.download',
executionId: 'zip-entry-cancel',
url,
destPath: '.pi/skills/new',
extractZip: true,
},
controller.signal,
)
const finishRead = await pendingRead.promise
controller.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
const closedDuringRead = close.mock.calls.length > 0
if (!closedDuringRead) finishRead()
expect(await transfer).toHaveProperty('ok', false)
expect(closedDuringRead).toBe(false)
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual([])
} finally {
read.mockRestore()
close.mockRestore()
}
})
it('handles cancelled transfers and refuses uploads of directories', async () => {
const controller = new AbortController()
controller.abort()
+15 -10
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto'
import { on } from 'node:events'
import { constants, createWriteStream } from 'node:fs'
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
import path from 'node:path'
@@ -243,18 +244,19 @@ export class RunnerFiles {
}
private async extract(archive: string, directory: string, signal: AbortSignal) {
const zip = await yauzl.openPromise(archive, {
lazyEntries: true,
strictFileNames: true,
autoClose: false,
})
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) =>
yauzl.open(
archive,
{ lazyEntries: true, strictFileNames: true, autoClose: false },
(error, opened) => (error ? reject(error) : resolve(opened)),
),
)
let size = 0
let count = 0
try {
signal.throwIfAborted()
// Let each metadata read finish before cancellation can close the ZIP descriptor.
for await (const entry of zip.eachEntry()) {
signal.throwIfAborted()
const entries = on(zip, 'entry', { close: ['end'], signal }) as AsyncIterable<[yauzl.Entry]>
zip.readEntry()
for await (const [entry] of entries) {
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
const mode = entry.externalFileAttributes >>> 16
@@ -267,13 +269,16 @@ export class RunnerFiles {
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
else {
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
const input = await zip.openReadStreamPromise(entry)
const input = await new Promise<Readable>((resolve, reject) =>
zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream))),
)
await pipeline(
input,
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
{ signal },
)
}
zip.readEntry()
}
} finally {
zip.close()
-44
View File
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
createRunnerLogger,
formatBytes,
formatDuration,
formatLogString,
formatTimestamp,
shortId,
} from './log'
describe('runner log helpers', () => {
it('formats timestamps and aligned log levels', () => {
const fixed = new Date(2026, 0, 1, 9, 4, 5)
expect(formatTimestamp(fixed)).toBe('09:04:05')
const lines: string[] = []
const logger = createRunnerLogger(
(line) => lines.push(line),
false,
() => fixed,
)
logger.info('Bash started [a8f2]')
logger.warn('Runner disconnected; reconnecting…')
logger.error('Fatal error')
expect(lines).toEqual([
'09:04:05 INFO Bash started [a8f2]',
'09:04:05 WARN Runner disconnected; reconnecting…',
'09:04:05 ERROR Fatal error',
])
})
it('formats short IDs, durations, byte counts, and single-line quoted strings', () => {
expect(shortId('01JABCDEF1234567890A8F2')).toBe('a8f2')
expect(shortId('one')).toBe('one')
expect(formatDuration(1840)).toBe('1.8s')
expect(formatDuration(-10)).toBe('0.0s')
expect(formatBytes(0)).toBe('0')
expect(formatBytes(512)).toBe('512B')
expect(formatBytes(1536)).toBe('1.5KB')
expect(formatBytes(12 * 1024)).toBe('12KB')
expect(formatBytes(Math.round(2.4 * 1024 * 1024))).toBe('2.4MB')
expect(formatLogString('echo "hi"\nls')).toBe('"echo \\"hi\\"\\nls"')
expect(formatLogString('x'.repeat(210))).toBe(`"${'x'.repeat(200)}…"`)
})
})
-59
View File
@@ -1,59 +0,0 @@
export type RunnerLogLevel = 'INFO' | 'WARN' | 'ERROR'
export interface RunnerLogger {
readonly verbose: boolean
info(message: string): void
warn(message: string): void
error(message: string): void
}
/** Formats a local wall-clock timestamp as HH:MM:SS for runner stderr logs. */
export function formatTimestamp(date = new Date()): string {
const pad = (value: number) => String(value).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
/** Builds a prefixed runner logger writing uniform timestamped lines to stderr. */
export function createRunnerLogger(
write: (message: string) => void = console.error,
verbose = false,
now: () => Date = () => new Date(),
): RunnerLogger {
const emit = (level: RunnerLogLevel, message: string) => {
write(`${formatTimestamp(now())} ${level.padEnd(5)} ${message}`)
}
return {
verbose,
info: (message) => emit('INFO', message),
warn: (message) => emit('WARN', message),
error: (message) => emit('ERROR', message),
}
}
/** Extracts the trailing 4-character tail of an execution ID for compact log labels. */
export function shortId(executionId: string): string {
return executionId.slice(-4).toLowerCase()
}
/** Formats a millisecond duration as seconds with one decimal place (e.g. `1.8s`). */
export function formatDuration(ms: number): string {
return `${(Math.max(0, ms) / 1000).toFixed(1)}s`
}
/** Formats a byte count concisely for runner logs (`0`, `128B`, `12KB`, `2.4MB`). */
export function formatBytes(bytes: number): string {
if (bytes <= 0) return '0'
if (bytes < 1024) return `${bytes}B`
if (bytes < 1024 * 1024) {
const kb = bytes / 1024
return kb < 10 ? `${kb.toFixed(1).replace(/\.0$/, '')}KB` : `${Math.round(kb)}KB`
}
const mb = bytes / (1024 * 1024)
return `${mb.toFixed(1).replace(/\.0$/, '')}MB`
}
/** Formats an arbitrary string (command, path, error) as a bounded single-line JSON string. */
export function formatLogString(value: string, maxLength = 200): string {
const text = value.length > maxLength ? `${value.slice(0, maxLength)}…` : value
return JSON.stringify(text)
}
-106
View File
@@ -1,106 +0,0 @@
import { spawnSync, type SpawnSyncReturns } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resolveRunnerShell } from './shell-config'
vi.mock('node:child_process', () => ({ spawnSync: vi.fn() }))
vi.mock('node:fs', { spy: true })
const access = vi.mocked(accessSync)
const where = vi.mocked(spawnSync)
const gitBash = 'D:\\Program Files\\Git\\bin\\bash.exe'
const gitBashX86 = 'D:\\Program Files (x86)\\Git\\bin\\bash.exe'
function whereResult(stdout = '', status = 0): SpawnSyncReturns<string> {
return { stdout, stderr: '', status, output: [null, stdout, ''], pid: 1, signal: null }
}
function available(...paths: string[]) {
access.mockImplementation((executable) => {
if (!paths.some((path) => executable === path)) throw new Error('File not found')
})
}
beforeEach(() => {
vi.stubEnv('ProgramFiles', 'D:\\Program Files')
vi.stubEnv('ProgramFiles(x86)', 'D:\\Program Files (x86)')
vi.stubEnv('SystemRoot', 'E:\\WinNT')
available()
where.mockReturnValue(whereResult('', 1))
})
afterEach(() => {
vi.resetAllMocks()
vi.unstubAllEnvs()
})
describe('runner shell selection', () => {
it.each(['linux', 'darwin'] as const)('uses /bin/sh on %s', (platform) => {
expect(resolveRunnerShell(platform)).toEqual({
executable: '/bin/sh',
commandTransport: 'shell',
})
expect(where).not.toHaveBeenCalled()
})
it.each([
[gitBash, [gitBash, gitBashX86]],
[gitBashX86, [gitBashX86]],
] as const)('prefers installed Git Bash at %s before PATH', (executable, paths) => {
available(...paths)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
expect(where).not.toHaveBeenCalled()
})
// Adapted from Pi's shell-path-exists.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('accepts a Windows Store Bash alias found on PATH via access(F_OK)', () => {
const alias = 'D:\\Users\\runner\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe'
available(alias)
where.mockReturnValue(whereResult(alias + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable: alias, commandTransport: 'argv' })
expect(access).toHaveBeenCalledWith(alias, constants.F_OK)
expect(where).toHaveBeenCalledWith('E:\\WinNT\\System32\\where.exe', ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
})
it('skips relative and inaccessible PATH results', () => {
const executable = 'D:\\MSYS2\\usr\\bin\\bash.exe'
available(executable)
where.mockReturnValue(
whereResult(['bash.exe', 'D:\\missing\\bash.exe', executable].join('\r\n')),
)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
})
it.each([
['E:\\WinNT', 'E:\\WinNT\\System32\\cmd.exe'],
[undefined, 'C:\\Windows\\System32\\cmd.exe'],
] as const)(
'falls back to cmd.exe when no Bash is available (SystemRoot %s)',
(root, executable) => {
vi.stubEnv('SystemRoot', root)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'shell' })
},
)
// Adapted from Pi's windows-shell-config.test.ts.
it.each([
['D:\\WinNT\\', 'd:/WINNT/System32/BASH.EXE', 'stdin'],
['D:\\WinNT', 'D:\\WinNT\\Sysnative\\bash.exe', 'stdin'],
[undefined, 'E:\\Windows\\System32\\bash.exe', 'stdin'],
['D:\\WinNT', 'D:\\Git\\bin\\bash.exe', 'argv'],
['D:\\WinNT', 'E:\\Windows\\System32\\bash.exe', 'argv'],
['WinNT', 'C:\\Windows\\System32\\bash.exe', 'argv'],
] as const)(
'uses the correct command transport for SystemRoot %s and %s',
(root, executable, commandTransport) => {
vi.stubEnv('SystemRoot', root)
available(executable)
where.mockReturnValue(whereResult(executable + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport })
},
)
})
-64
View File
@@ -1,64 +0,0 @@
import { spawnSync } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { win32 } from 'node:path'
export interface RunnerShellConfig {
executable: string
commandTransport: 'shell' | 'argv' | 'stdin'
}
// Windows Bash discovery and legacy WSL detection adapted from pi-mono.
// See apps/cli/THIRD-PARTY-NOTICES.txt.
function isLegacyWslBashPath(executable: string, systemRoot: string | undefined): boolean {
const normalized = win32.normalize(executable).toLowerCase()
if (systemRoot) {
if (!/^[a-z]:[\\/]/i.test(systemRoot)) return false
return ['System32', 'Sysnative'].some(
(directory) => normalized === win32.join(systemRoot, directory, 'bash.exe').toLowerCase(),
)
}
return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)
}
function shellPathExists(executable: string): boolean {
// access(F_OK) accepts runnable Windows Store aliases that fail an extra stat check.
try {
accessSync(executable, constants.F_OK)
return true
} catch {
return false
}
}
function findWindowsBash(system32: string): string | undefined {
for (const directory of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {
if (!directory || !win32.isAbsolute(directory)) continue
const executable = win32.join(directory, 'Git', 'bin', 'bash.exe')
if (shellPathExists(executable)) return executable
}
// Use the system tool and limit its search to PATH. The workspace may contain a bash.exe.
const found = spawnSync(win32.join(system32, 'where.exe'), ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
if (found.status !== 0 || !found.stdout) return
return found.stdout
.trim()
.split(/\r?\n/)
.find((executable) => win32.isAbsolute(executable) && shellPathExists(executable))
}
export function resolveRunnerShell(platform = process.platform): RunnerShellConfig {
if (platform !== 'win32') return { executable: '/bin/sh', commandTransport: 'shell' }
const systemRoot = process.env.SystemRoot
const system32 = win32.join(systemRoot ?? 'C:\\Windows', 'System32')
const executable = findWindowsBash(system32)
if (!executable) return { executable: win32.join(system32, 'cmd.exe'), commandTransport: 'shell' }
return {
executable,
commandTransport: isLegacyWslBashPath(executable, systemRoot) ? 'stdin' : 'argv',
}
}
+1 -55
View File
@@ -47,57 +47,6 @@ describe('runner bash execution', () => {
expect(output).toBe('no-extra-runtime')
})
// Adapted from Pi's tools.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('sends the complete command over stdin for the legacy Bash launcher', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'stdin',
})
const command = [
'name="Hello, 世界"',
'for choice in "one two" \'three "four"\'; do',
' printf \'%s / %s\\n\' "$name" "$choice"',
'done',
].join('\n')
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('Hello, 世界 / one two\nHello, 世界 / three "four"\n')
})
it('passes a command with shell quoting directly to the selected executable', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'argv',
})
const command = "printf '%s' '$literal \"quotes\"'"
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('$literal "quotes"')
})
it('rejects the legacy WSL launcher before starting SRT', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), path.join(cwd, 'sandbox.json'), {
executable: 'C:\\Windows\\System32\\bash.exe',
commandTransport: 'stdin',
})
await expect(shell.initialize()).rejects.toThrow('SRT cannot run the legacy WSL Bash launcher')
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
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(
@@ -176,10 +125,7 @@ describe('runner bash execution', () => {
})
it('reports launch failure without including command text or skill secrets', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: path.join(cwd, 'missing-shell'),
commandTransport: 'shell',
})
shell.environment.shell = path.join(cwd, 'missing-shell')
const result = await shell.run(
request('echo private-command'),
new AbortController().signal,
+11 -23
View File
@@ -3,20 +3,21 @@ import { execa } from 'execa'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
type RunnerEnvironment,
type RunnerExecResultMessage,
type RunnerExecStartMessage,
} from '@shumai/dtos'
import { commandEnv } from './config'
import { commandEnv, runnerShell } from './config'
import { RunnerFiles } from './files'
import { resolveRunnerShell } from './shell-config'
import { loadSandbox } from './srt'
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
const MAX_TIMEOUT_SEC = 3600
export class RunnerShell {
readonly environment: RunnerEnvironment
readonly environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: runnerShell(),
})
private sandbox?: Awaited<ReturnType<typeof loadSandbox>>
private initialized = false
private active = 0
@@ -24,20 +25,10 @@ export class RunnerShell {
constructor(
private readonly files: RunnerFiles,
private readonly srtPath?: string,
private readonly config = resolveRunnerShell(),
) {
this.environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: config.executable,
})
}
) {}
async initialize() {
if (!this.srtPath) return
if (this.config.commandTransport === 'stdin')
throw new Error(
'SRT cannot run the legacy WSL Bash launcher. Install Git for Windows to use Bash with SRT.',
)
// Read and validate once; commands cannot weaken the policy by editing the file.
this.sandbox = await loadSandbox(this.srtPath)
try {
@@ -95,12 +86,9 @@ export class RunnerShell {
const log = await this.files.createWriter(logPath)
try {
const windows = process.platform === 'win32'
const { commandTransport } = this.config
const useShell = commandTransport === 'shell'
const sendCommandOnStdin = commandTransport === 'stdin'
let executable = useShell ? message.command : this.config.executable
let args = useShell ? [] : sendCommandOnStdin ? ['-s'] : ['-c', message.command]
let shell: string | false = useShell && this.config.executable
let args: string[] = []
let executable = message.command
let shell: string | false = this.environment.shell
let env = commandEnv(message.env)
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
@@ -115,7 +103,7 @@ export class RunnerShell {
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
this.config.executable,
this.environment.shell,
undefined,
signal,
this.files.cwd,
@@ -143,7 +131,7 @@ export class RunnerShell {
env,
extendEnv: false,
shell,
stdin: sendCommandOnStdin ? [Buffer.from(message.command)] : 'ignore',
stdin: 'ignore',
buffer: false,
reject: false,
stripFinalNewline: false,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"dependencies": {
-11
View File
@@ -81,16 +81,6 @@ if (regenCmdIndex !== -1) {
async function run() {
validateArchiveStorageConfig()
const runnerLease = await runnerService.startServerTopology()
runnerLease.addEventListener(
'abort',
() => {
console.error('Lost the runner server lease:', runnerLease.reason)
process.exit(1)
},
{ once: true },
)
runnerLease.throwIfAborted()
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
@@ -232,7 +222,6 @@ async function run() {
await workflowService.shutdownWorkers().catch(() => {})
assetService.stopCleanupJob()
server.stop(true)
await runnerService.stopServerTopology().catch(console.error)
process.exit(0)
}
+67 -17
View File
@@ -32,12 +32,12 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.7.0",
"version": "0.6.6",
"bin": {
"shumai-cli": "./src/index.ts",
},
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.83",
"@anthropic-ai/sandbox-runtime": "0.0.82",
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
@@ -59,7 +59,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -113,7 +113,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.7.0",
"version": "0.6.6",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -125,7 +125,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -145,7 +145,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@earendil-works/chord": "1.5.0",
"@earendil-works/pi-ai": "1.5.0",
@@ -169,7 +169,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@better-auth/mcp": "1.7.12",
"@earendil-works/pi-durable": "1.5.0",
@@ -190,7 +190,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -254,7 +254,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@prisma/adapter-pg": "7.10.0",
"@prisma/client": "7.10.0",
@@ -269,7 +269,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -278,7 +278,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
@@ -294,18 +294,18 @@
},
"packages/operations": {
"name": "@shumai/operations",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"zod": "4.5.4",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.7.0",
"version": "0.6.6",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -316,7 +316,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@base-ui/react": "1.7.0",
"@better-auth/oauth-provider": "1.7.12",
@@ -421,7 +421,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.7.0",
"version": "0.6.6",
"dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*",
@@ -484,7 +484,7 @@
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.83", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.25.0" }, "peerDependencies": { "@microsoft/mxc-sdk": "^1.0.1" }, "optionalPeers": ["@microsoft/mxc-sdk"], "bin": { "srt": "dist/cli.js" } }, "sha512-yEusORnVJrNseF/9fvjVYyk6tr79/aFbIB3T/X8p2puLZdaaiGNeYN50v0CE+1DT70v7XuzKOAnTivh1f5cksA=="],
"@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=="],
@@ -760,6 +760,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=="],
@@ -830,6 +870,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=="],
@@ -2300,6 +2342,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=="],
@@ -2458,6 +2502,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=="],
@@ -2468,6 +2514,8 @@
"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=="],
@@ -3080,6 +3128,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=="],
-17
View File
@@ -3,23 +3,6 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.7.0" description="November 18, 2026">
### Added
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
### Fixed
- **cli**: Fix release publication failing to find staged standalone downloads.
### Changed
- **agent**: ⚠️ **Breaking Change**: Replaced the built-in server-side Bash sandbox with external Runners and removed the team-level sandbox domain allowlist settings. The Bash tool is now disabled by default. If your Agent or Skills require Bash execution, you'll need to set up and connect an external Runner using shumai-cli. The Shumai CLI includes built-in sandbox support, allowing you to configure filesystem access and network domain allowlists for Bash execution directly on the Runner. See [Agent Runners](https://docs.shumai.one/using-shumai/agent-sandbox) for setup instructions and configuration details. The Docker Compose configuration has also been updated to improve security following the removal of the server-side sandbox. We strongly recommend upgrading to the latest Shumai image and updating your Docker Compose file to apply these security improvements.
- **cli**: Show copyable commands and shell configuration instructions when the standalone CLI installation directory is missing from PATH.
</Update>
<Update label="v0.6.6" description="November 13, 2026">
### Added
-2
View File
@@ -72,8 +72,6 @@ When running multiple replicas of the transcode workers or main servers across m
- **Custom Worker ID**: Set `SHUMAI_WORKERS_ID` (or `SHUMAI_WORKER_ID`) if you wish to assign an explicit identifier.
- **Kubernetes**: In Kubernetes Pods, set `POD_NAME` (via Downward API `fieldRef: { fieldPath: metadata.name }`) to provide stable, unique per-pod identity across pod restarts.
Agent runners require a single main server per database. With runners configured, stop the old main server before starting its replacement. For Kubernetes, use a single main server replica with the Recreate deployment strategy. Transcode workers can still scale independently.
---
## Scalable Deployment on Kubernetes & AWS EKS
+1 -5
View File
@@ -5,8 +5,6 @@ description: Connect an optional command runner and configure sandboxing on its
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.
Agent runners require one main Shumai server per database. Multiple main servers can share a database while it has no configured runners. Stop the other main servers before creating a runner. Transcode workers can run separately.
## 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.
@@ -31,12 +29,10 @@ Use a runner key, not a personal API token. Prefer the environment variable over
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 `/bin/sh` on macOS and Linux. On Windows, the runner looks for Git Bash in the standard installation directories, then for `bash.exe` on PATH, and falls back to `cmd.exe`. The runner prints its selected shell at startup and reports it to the agent so it can use compatible syntax. For Bash with SRT on Windows, use Git Bash in place of the legacy WSL Bash launcher.
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.
Everyone with shell access to the same runner can read files left in its workspace, including assets and logs from other projects. Shumai project permissions apply when assets are downloaded. Share a runner only among users who may read all files in that workspace. For separate trust groups, use separate runner accounts or virtual machines and restrict access to the agents bound to each runner.
## 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.
-2
View File
@@ -53,8 +53,6 @@ Worker 根据可配置的并发上限从 PostgreSQL 队列中拉取任务:
- **自定义 Worker ID**:若需显式指定标识符,可设置 `SHUMAI_WORKERS_ID`(或 `SHUMAI_WORKER_ID`)。
- **Kubernetes 环境**:在 Kubernetes Pod 中,可通过 Downward API(`fieldRef: { fieldPath: metadata.name }`)设置 `POD_NAME`,以在 Pod 重启期间保持稳定且唯一的单 Pod 身份标识。
使用智能体运行器时,每个数据库只允许运行一个主服务器。已配置运行器时,请先停止旧主服务器,再启动替换实例。在 Kubernetes 中,主服务器应使用单副本和 Recreate 部署策略。转码 Worker 仍可独立扩展。
---
## 基于 Kubernetes 与 AWS EKS 的弹性扩展部署
+1 -5
View File
@@ -5,8 +5,6 @@ description: 连接可选的命令运行器,并在运行器机器上配置沙
智能体无需运行器即可使用内置工具。如需执行命令或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
每个数据库只支持一台主 Shumai 服务器使用智能体运行器。未配置运行器时,多台主服务器可以共享数据库。创建运行器前,请停止其他主服务器副本。转码 Worker 可以独立运行。
## 连接运行器
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
@@ -33,8 +31,6 @@ shumai-cli runner start --cwd C:\workspace
命令从工作目录启动,技能、下载素材、生成文件和日志位于 `.pi` 中。子进程只继承基础系统环境及明确配置的技能变量,不自动继承运行器密钥、个人 API 令牌或其他任意环境变量。
所有有权在同一运行器执行命令的用户都可以读取工作区中保留的文件,包括其他项目的素材和日志。Shumai 下载素材时会检查项目权限。请仅在有权读取工作区内所有文件的用户之间共享运行器。不同信任范围应使用独立的运行器账号或虚拟机,并限制对应智能体的访问权限。
## 可选 SRT 沙箱
未使用 `--srt` 时,命令具有运行器系统用户的权限。只连接可信 Shumai 服务器,可按需使用独立容器、虚拟机或账号。
@@ -51,7 +47,7 @@ Windows 使用 SRT 的实验性 Windows 支持。启用沙箱前执行一次初
npx @anthropic-ai/sandbox-runtime windows-install
```
SRT 会在启动时检查安装状态,缺少初始化时返回错误。未使用 `--srt` 的运行器不需要此步骤。`bash` 工具在 macOS 和 Linux 上使用 `/bin/sh`。在 Windows 上,运行器先在标准安装目录查找 Git Bash,再在 PATH 中查找 `bash.exe`,找不到时使用 `cmd.exe`。运行器在启动时显示所选 Shell,并将其报告给智能体,让智能体使用匹配的命令语法。在 Windows 上搭配 SRT 使用 Bash 时,请用 Git Bash 代替旧版 WSL Bash 启动器。
SRT 会在启动时检查安装状态,缺少初始化时返回错误。未使用 `--srt` 的运行器不需要此步骤。`bash` 工具使用运行器的原生 Shell:macOS/Linux 为 `/bin/sh`,Windows 为 `cmd.exe`。智能体会收到系统和 Shell 信息,以生成匹配的命令。Windows 无需安装 Bash 或 Git。
直接使用上游 SRT JSON 格式,例如:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -43,19 +43,6 @@ function createMockWs() {
}
}
function reconcile(runnerId: string, ws: RunnerSocket) {
runnerService.handleMessage(
runnerId,
ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: [],
completedExecutions: [],
}),
)
}
describe('Concurrent Runner Sessions', () => {
setupTestDbHooks()
@@ -77,7 +64,6 @@ describe('Concurrent Runner Sessions', () => {
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(runner.id, conn.ws)
await prisma.user.create({
data: {
@@ -215,8 +201,6 @@ describe('Concurrent Runner Sessions', () => {
},
gpuConn.ws,
)
reconcile(defaultRunner.id, defaultConn.ws)
reconcile(gpuRunner.id, gpuConn.ws)
const defaultTool = createRunnerBashTool(
{},
+9 -24
View File
@@ -40,15 +40,15 @@ describe('createRunnerBashTool', () => {
const createMockOnUpdate = () => vi.fn()
it.each(['C:\\Windows\\System32\\cmd.exe', 'C:\\Program Files\\Git\\bin\\bash.exe'])(
'tells the agent to use the runner OS and shell syntax for %s',
(shell) => {
const tool = createRunnerBashTool({}, { environment: { platform: 'win32', shell } })
expect(tool.description).toContain('Runner OS: win32')
expect(tool.description).toContain(shell)
expect(tool.description).toContain('Use syntax and programs compatible with this environment')
},
)
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(
@@ -186,21 +186,6 @@ describe('createRunnerBashTool', () => {
).rejects.toThrow(/exited with code 1/)
})
it('reports signal termination as a command failure', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'signaled',
output: '',
exitCode: null,
signal: 'SIGTERM',
timedOut: false,
aborted: false,
})
await expect(invokeTool(tool, '1', { command: 'command' }, createMockSignal())).rejects.toThrow(
'terminated by SIGTERM',
)
})
it('should handle timeouts', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
-8
View File
@@ -208,14 +208,6 @@ export const createRunnerBashTool = (
throw new Error(appendStatus(outputText, execResult.error))
}
if (execResult.signal) {
logger.error(
{ signal: execResult.signal, command, outputText },
'Bash command was terminated',
)
throw new Error(appendStatus(outputText, 'Bash command terminated by ' + execResult.signal))
}
if (execResult.exitCode !== 0 && execResult.exitCode !== null) {
logger.error(
{ exitCode: execResult.exitCode, command, outputText },
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-27
View File
@@ -8,7 +8,6 @@ import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3'
import * as archiveStorageModule from '@shumai/core/src/s3/archive-storage'
import { uploadService } from '@shumai/core/src/upload/upload'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { AssetService } from './asset'
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
@@ -23,7 +22,6 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
deletePrefix: vi.fn().mockResolvedValue(1),
copyObject: vi.fn().mockResolvedValue(undefined),
getStoragePath: vi.fn((bucket: string, key: string) => `/mock/data/${bucket}/${key}`),
listObjects: vi.fn().mockResolvedValue([]),
},
getStorageBackend: vi.fn().mockReturnValue('local'),
}))
@@ -49,31 +47,6 @@ describe('AssetService', () => {
vi.clearAllMocks()
})
it('checks generated file expiration hourly while continuing regular cleanup', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
const startedAt = Date.now()
const regularCleanup = vi
.spyOn(watermarkService, 'purgeOrphanWatermarkConfigs')
.mockResolvedValue(0)
try {
await assetService.startCleanupJob()
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(1))
expect(s3Service.listObjects).toHaveBeenCalledWith(expect.any(String), 'temp/generated/')
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(regularCleanup).toHaveBeenCalledTimes(2))
expect(s3Service.listObjects).toHaveBeenCalledTimes(1)
vi.setSystemTime(startedAt + 60 * 60 * 1000)
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(2))
} finally {
assetService.stopCleanupJob()
regularCleanup.mockRestore()
vi.useRealTimers()
}
})
const setupBasicAssets = async () => {
const user = await prisma.user.create({
data: {
+1 -7
View File
@@ -1585,9 +1585,7 @@ export class AssetService {
private cleanupJobsRunning = false
async startCleanupJob() {
if (this.cleanupJobsRunning) return
this.cleanupJobsRunning = true
let nextGeneratedCleanupAt = 0
const runCleanup = async () => {
if (!this.cleanupJobsRunning) return
@@ -1596,12 +1594,8 @@ export class AssetService {
await this.expireTrashedAssets()
await this.purgePendingAssets()
await this.purgeUnreferencedStorageKeys()
await this.purgeExpiredGeneratedFiles()
await watermarkService.purgeOrphanWatermarkConfigs()
const now = Date.now()
if (now >= nextGeneratedCleanupAt) {
nextGeneratedCleanupAt = now + 60 * 60 * 1000
await this.purgeExpiredGeneratedFiles()
}
} catch (e: unknown) {
console.error('Error in asset cleanup job:', e)
}
+1 -199
View File
@@ -1,5 +1,4 @@
import { prisma } from '@shumai/db'
import * as advisoryLocks from '@shumai/db/src/advisory-lock'
import { setupTestDbHooks } from '@shumai/db/test'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { s3Service } from '../s3/s3'
@@ -33,24 +32,6 @@ function createMockWs() {
}
}
function reconcile(
service: RunnerService,
runnerId: string,
ws: RunnerSocket,
activeIds: string[] = [],
) {
service.handleMessage(
runnerId,
ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: activeIds.map((executionId) => ({ executionId, nextOffset: 0 })),
completedExecutions: [],
}),
)
}
describe('RunnerService', () => {
setupTestDbHooks()
@@ -68,48 +49,11 @@ describe('RunnerService', () => {
teamId = team.id
})
afterEach(async () => {
afterEach(() => {
service.stopHeartbeatMonitor()
await service.stopServerTopology()
vi.restoreAllMocks()
})
it('allows replicas without runners and enforces a single server while runners exist', async () => {
const replica = new RunnerService()
try {
await service.startServerTopology()
await replica.startServerTopology()
await expect(service.createRunner(teamId, { name: 'Blocked' })).rejects.toMatchObject({
status: 409,
message: expect.stringContaining('single main Shumai server'),
})
expect(await service.listRunners(teamId)).toEqual([])
await replica.stopServerTopology()
const { runner } = await service.createRunner(teamId, { name: 'Exclusive runner' })
await expect(replica.startServerTopology()).rejects.toThrow('single main Shumai server')
await service.stopServerTopology()
await replica.startServerTopology()
await expect(service.startServerTopology()).rejects.toThrow('single main Shumai server')
const acquireLease = advisoryLocks.tryAcquireUpgradeableAdvisoryLock
vi.spyOn(advisoryLocks, 'tryAcquireUpgradeableAdvisoryLock').mockImplementationOnce(
async (lockKey, exclusive) => {
// The newcomer has already looked up the existing runner.
await replica.deleteRunner(teamId, runner.id)
return acquireLease(lockKey, exclusive)
},
)
await service.startServerTopology()
await expect(replica.createRunner(teamId, { name: 'Blocked again' })).rejects.toMatchObject({
status: 409,
})
} finally {
await replica.stopServerTopology()
}
})
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' })
@@ -257,25 +201,6 @@ describe('RunnerService', () => {
})
describe('WebSocket connection lifecycle & eviction', () => {
it('waits for reconciliation before reporting online or dispatching a command', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Handshaking runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
expect(conn.lastSentJson()).toHaveProperty('type', 'welcome')
expect(service.isRunnerConnected(runner.id)).toBe(false)
await expect(service.exec(runner.id, { command: 'echo ready' })).rejects.toThrow(
'Runner is not connected',
)
expect(conn.sent).toHaveLength(1)
reconcile(service, runner.id, conn.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
})
it('evicts existing connection with 4000 when a new connection arrives', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Runner WS' })
const keyHash = hashRunnerKey(key)
@@ -286,7 +211,6 @@ describe('RunnerService', () => {
{ id: runner.id, teamId, name: runner.name, keyHash },
conn1.ws,
)
reconcile(service, runner.id, conn1.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
await service.registerConnection(
@@ -297,7 +221,6 @@ describe('RunnerService', () => {
code: 4000,
reason: 'Replaced by a newer connection',
})
reconcile(service, runner.id, conn2.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
})
@@ -371,7 +294,6 @@ describe('RunnerService', () => {
{ id: r2.runner.id, teamId, name: r2.runner.name, keyHash: hashRunnerKey(r2.key) },
conn2.ws,
)
reconcile(service, r2.runner.id, conn2.ws)
const online = await service.requireOnlineRunner(teamId, r2.runner.id)
expect(online.id).toBe(r2.runner.id)
})
@@ -385,7 +307,6 @@ describe('RunnerService', () => {
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const chunks: Array<{ stream: string; text: string }> = []
const execPromise = service.exec(runner.id, {
@@ -462,7 +383,6 @@ describe('RunnerService', () => {
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const streamed: string[] = []
const noCollectPromise = service.exec(runner.id, {
command: 'yes | head -n 100',
@@ -536,7 +456,6 @@ describe('RunnerService', () => {
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const abortController = new AbortController()
const execPromise = service.exec(runner.id, {
@@ -570,121 +489,6 @@ describe('RunnerService', () => {
expect(res.aborted).toBe(true)
})
it.each([false, true])(
'replays cancellation on reconnect after notifying caller=%s',
async (reported) => {
const { runner, key } = await service.createRunner(teamId, {
name: 'Cancelled while offline',
})
const authenticated = {
id: runner.id,
teamId,
name: runner.name,
keyHash: hashRunnerKey(key),
}
const conn = createMockWs()
await service.registerConnection(authenticated, conn.ws)
reconcile(service, runner.id, conn.ws)
const abort = new AbortController()
const execution = service.exec(runner.id, { command: 'sleep 30', signal: abort.signal })
const { executionId } = conn.lastSentJson()
service.handleDisconnect(runner.id, conn.ws)
abort.abort()
if (reported) await expect(execution).resolves.toMatchObject({ aborted: true })
const reconnected = createMockWs()
await service.registerConnection(authenticated, reconnected.ws)
expect(reconnected.lastSentJson()).toMatchObject({ inFlightExecutionIds: [executionId] })
reconcile(service, runner.id, reconnected.ws, [executionId])
const forwarded = reconnected.lastSentJson()
service.handleMessage(
runner.id,
reconnected.ws,
JSON.stringify({
type: 'exec.result',
executionId,
exitCode: 0,
signal: null,
timedOut: false,
}),
)
expect(forwarded).toEqual({ type: 'exec.cancel', executionId })
await expect(execution).resolves.toMatchObject({ aborted: true })
},
)
it('restages a generated input that was removed from the runner workspace', async () => {
vi.spyOn(s3Service, 'headObject').mockResolvedValue({
key: 'temp/generated/example/input.jpg',
size: 100,
lastModified: new Date(),
contentType: 'image/jpeg',
eTag: 'fixture',
})
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example.com/input.jpg')
const { runner, key } = await service.createRunner(teamId, { name: 'Generated file runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const destPath = '.pi/generated/example/input.jpg'
const acknowledgeDownload = () => {
const download = conn.lastSentJson()
expect(download).toMatchObject({ type: 'file.download', destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.download.result',
executionId: download.executionId,
ok: true,
}),
)
}
const first = service.ensureGeneratedFileOnRunner(runner.id, destPath)
await vi.waitFor(() => expect(conn.lastSentJson()?.type).toBe('file.download'))
acknowledgeDownload()
await expect(first).resolves.toBe(destPath)
const second = service.ensureGeneratedFileOnRunner(runner.id, destPath)
const stat = conn.lastSentJson()
expect(stat).toMatchObject({ type: 'file.stat', srcPath: destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.stat.result',
executionId: stat.executionId,
ok: true,
exists: false,
}),
)
await vi.waitFor(() => expect(conn.lastSentJson()?.type).toBe('file.download'))
acknowledgeDownload()
await expect(second).resolves.toBe(destPath)
const third = service.ensureGeneratedFileOnRunner(runner.id, destPath)
const present = conn.lastSentJson()
expect(present).toMatchObject({ type: 'file.stat', srcPath: destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.stat.result',
executionId: present.executionId,
ok: true,
exists: true,
isFile: true,
}),
)
await expect(third).resolves.toBe(destPath)
expect(conn.lastSentJson()).toEqual(present)
})
it('handles downloadToRunner, uploadFromRunner, statOnRunner, and session caching', async () => {
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example.com/file')
const { runner, key } = await service.createRunner(teamId, { name: 'File Runner' })
@@ -693,7 +497,6 @@ describe('RunnerService', () => {
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
// 1. downloadToRunner
const dlPromise = service.downloadToRunner(runner.id, {
@@ -813,7 +616,6 @@ describe('RunnerService', () => {
{ id: runner.id, teamId, name: runner.name, keyHash },
conn1.ws,
)
reconcile(service, runner.id, conn1.ws)
const execPromise = service.exec(runner.id, { command: 'long-job' })
const startMsg = conn1.lastSentJson()
+102 -131
View File
@@ -12,7 +12,6 @@ import {
RunnerFileUploadResultMessage,
RunnerInfo,
RunnerEnvironment,
RUNNER_REPLACED_CLOSE_CODE,
RunnerToServerMessage,
runnerToServerMessageSchema,
ServerToRunnerMessage,
@@ -27,7 +26,6 @@ import type {
RunnerExecResult,
RunnerSocket,
} from './types'
import { RunnerTopology } from './runner-topology'
const RUNNER_KEY_PREFIX = 'shm_rn_'
const DEFAULT_RECONNECT_GRACE_MS = 30_000
@@ -62,8 +60,6 @@ interface PendingExecOperation {
resolve: (result: RunnerExecResult) => void
reject: (err: Error) => void
timeoutTimer?: ReturnType<typeof setTimeout>
abortTimer?: ReturnType<typeof setTimeout>
cancelRequested?: boolean
cleanupSignal?: () => void
}
@@ -136,23 +132,11 @@ export function validateRunnerWorkspacePath(targetPath: string): string {
export class RunnerService {
private sessions = new Map<string, ActiveRunnerSession>()
private closedSockets = new WeakSet<RunnerSocket>()
private pendingOps = new Map<string, PendingOperation>()
private disconnectGraceTimers = new Map<string, ReturnType<typeof setTimeout>>()
private credentialRevisions = new Map<string, number>()
private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private reconnectGraceMs = DEFAULT_RECONNECT_GRACE_MS
private serverTopology?: RunnerTopology
async startServerTopology(): Promise<AbortSignal> {
this.serverTopology ??= await RunnerTopology.start()
return this.serverTopology.signal
}
async stopServerTopology(): Promise<void> {
await this.serverTopology?.close()
this.serverTopology = undefined
}
setReconnectGraceMs(ms: number): void {
this.reconnectGraceMs = ms
@@ -173,7 +157,7 @@ export class RunnerService {
this.handleDisconnect(runnerId, session.ws, 1001)
continue
}
if (session.environment) this.sendToSession(session, { type: 'ping', ts: now })
this.sendToSession(session, { type: 'ping', ts: now })
}
}, HEARTBEAT_INTERVAL_MS)
if (typeof this.heartbeatTimer.unref === 'function') {
@@ -189,7 +173,7 @@ export class RunnerService {
}
isRunnerConnected(runnerId: string): boolean {
return this.getReadySession(runnerId) !== undefined
return this.sessions.has(runnerId)
}
getRunnerEnvironment(runnerId: string): RunnerEnvironment | undefined {
@@ -219,14 +203,6 @@ export class RunnerService {
}
async createRunner(teamId: string, req: CreateRunnerRequest): Promise<CreateRunnerResponse> {
const create = () => this.persistRunner(teamId, req)
return this.serverTopology ? this.serverTopology.changeRunners(create, true) : create()
}
private async persistRunner(
teamId: string,
req: CreateRunnerRequest,
): Promise<CreateRunnerResponse> {
const name = req.name.trim()
const { key, keyPrefix, keyHash } = generateRunnerKey()
@@ -373,11 +349,6 @@ export class RunnerService {
}
async deleteRunner(teamId: string, runnerId: string): Promise<void> {
const remove = () => this.removeRunner(teamId, runnerId)
await (this.serverTopology ? this.serverTopology.changeRunners(remove) : remove())
}
private async removeRunner(teamId: string, runnerId: string): Promise<void> {
this.bumpCredentialRevision(runnerId)
await prisma.$transaction(async (tx) => {
@@ -501,7 +472,6 @@ export class RunnerService {
},
select: { id: true, teamId: true, name: true },
})
if (this.closedSockets.has(ws)) return
const currentRevision = this.credentialRevisions.get(runner.id) ?? 0
if (!verified || currentRevision !== startRevision) {
try {
@@ -512,13 +482,19 @@ export class RunnerService {
return
}
const existingTimer = this.disconnectGraceTimers.get(runner.id)
if (existingTimer) {
clearTimeout(existingTimer)
this.disconnectGraceTimers.delete(runner.id)
}
const existingSession = this.sessions.get(runner.id)
if (existingSession && existingSession.ws !== ws) {
logger.info({ runnerId: runner.id }, 'Evicting previous runner WebSocket connection')
// Remove from sessions before closing so handleDisconnect is a no-op for the old socket
this.sessions.delete(runner.id)
try {
existingSession.ws.close(RUNNER_REPLACED_CLOSE_CODE, 'Replaced by a newer connection')
existingSession.ws.close(4000, 'Replaced by a newer connection')
} catch {
// Ignore close errors
}
@@ -536,6 +512,19 @@ export class RunnerService {
this.sessions.set(runner.id, session)
this.startHeartbeatMonitor()
await prisma.runner
.update({
where: { id: runner.id },
data: { lastConnectedAt: new Date() },
})
.catch((err) => {
logger.warn({ err, runnerId: runner.id }, 'Failed to update runner lastConnectedAt')
})
if (this.sessions.get(runner.id) !== session) {
return
}
const inFlightExecutionIds = this.getInFlightExecutionIdsForRunner(runner.id)
this.sendToSession(session, {
type: 'welcome',
@@ -576,13 +565,8 @@ export class RunnerService {
case 'pong':
break
case 'reconcile':
if (session.environment) break
this.handleReconcileMessage(session, msg)
session.environment = msg.environment
this.clearDisconnectGraceTimer(runnerId)
void prisma.runner
.update({ where: { id: runnerId }, data: { lastConnectedAt: new Date() } })
.catch((err) => logger.warn({ err, runnerId }, 'Failed to update runner lastConnectedAt'))
this.handleReconcileMessage(session, msg)
break
case 'exec.output':
this.handleExecOutputMessage(runnerId, msg)
@@ -603,7 +587,6 @@ export class RunnerService {
}
handleDisconnect(runnerId: string, ws: RunnerSocket, code?: number): void {
this.closedSockets.add(ws)
const session = this.sessions.get(runnerId)
if (!session || session.ws !== ws) {
return
@@ -625,7 +608,6 @@ export class RunnerService {
}
if (code === 1008 || this.reconnectGraceMs <= 0) {
this.clearDisconnectGraceTimer(runnerId)
this.failPendingOperationsForRunner(
runnerId,
new Error('Runner disconnected while operation was in progress'),
@@ -633,7 +615,6 @@ export class RunnerService {
return
}
if (this.disconnectGraceTimers.has(runnerId)) return
const timer = setTimeout(() => {
this.disconnectGraceTimers.delete(runnerId)
if (!this.isRunnerConnected(runnerId)) {
@@ -655,7 +636,10 @@ export class RunnerService {
// ----------------------------------------------------------------------
async exec(runnerId: string, options: RunnerExecOptions): Promise<RunnerExecResult> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
if (options.signal?.aborted) {
throw new Error('Command aborted before execution started')
@@ -681,22 +665,51 @@ export class RunnerService {
const safetyTimeoutMs = Math.max((timeoutSec + 15) * 1000, 15_000)
const timeoutTimer = setTimeout(() => {
const pending = this.pendingOps.get(executionId)
if (pending?.kind !== 'exec') return
if (!pending) return
this.cleanupPendingOp(executionId)
const currentSession = this.getReadySession(runnerId)
const currentSession = this.sessions.get(runnerId)
if (currentSession) {
this.sendToSession(currentSession, { type: 'exec.cancel', executionId })
}
resolve({
executionId,
output: this.readBufferedExecOutput(pending),
output: pending.kind === 'exec' ? this.readBufferedExecOutput(pending) : '',
exitCode: null,
signal: 'SIGKILL',
timedOut: !pending.cancelRequested,
aborted: pending.cancelRequested ?? false,
timedOut: true,
aborted: false,
})
}, safetyTimeoutMs)
let cleanupSignal: (() => void) | undefined
if (options.signal) {
const onAbort = () => {
const currentSession = this.sessions.get(runnerId)
if (currentSession) {
this.sendToSession(currentSession, { type: 'exec.cancel', executionId })
}
// Give runner a short window to report exec.result, otherwise resolve as aborted
const abortTimer = setTimeout(() => {
const pending = this.pendingOps.get(executionId)
if (!pending) return
this.cleanupPendingOp(executionId)
resolve({
executionId,
output: pending.kind === 'exec' ? this.readBufferedExecOutput(pending) : '',
exitCode: null,
signal: 'SIGKILL',
timedOut: false,
aborted: true,
})
}, 2_000)
if (typeof abortTimer.unref === 'function') {
abortTimer.unref()
}
}
options.signal.addEventListener('abort', onAbort, { once: true })
cleanupSignal = () => options.signal?.removeEventListener('abort', onAbort)
}
const pendingOp: PendingExecOperation = {
kind: 'exec',
executionId,
@@ -711,26 +724,7 @@ export class RunnerService {
resolve,
reject,
timeoutTimer,
}
if (options.signal) {
const signal = options.signal
const onAbort = () => {
pendingOp.cancelRequested = true
// Release the caller after a short grace period. Retain cancellation for reconnects.
pendingOp.abortTimer = setTimeout(() => {
this.reportCancelledExecution(pendingOp)
pendingOp.onOutput = undefined
pendingOp.collectOutput = false
pendingOp.outputChunks = []
pendingOp.bufferedOutputBytes = 0
}, 2_000)
pendingOp.abortTimer.unref?.()
const currentSession = this.getReadySession(runnerId)
if (currentSession)
this.sendToSession(currentSession, { type: 'exec.cancel', executionId })
}
signal.addEventListener('abort', onAbort, { once: true })
pendingOp.cleanupSignal = () => signal.removeEventListener('abort', onAbort)
cleanupSignal,
}
this.pendingOps.set(executionId, pendingOp)
@@ -748,7 +742,10 @@ export class RunnerService {
timeoutMs?: number
},
): Promise<RunnerFileDownloadResultMessage> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
const normalizedDestPath = validateRunnerWorkspacePath(options.destPath)
const executionId = ulid()
@@ -787,7 +784,10 @@ export class RunnerService {
srcPath: string,
timeoutMs = DEFAULT_FILE_OP_TIMEOUT_MS,
): Promise<RunnerFileStatResultMessage> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
const normalizedSrcPath = validateRunnerWorkspacePath(srcPath)
const executionId = ulid()
@@ -826,7 +826,10 @@ export class RunnerService {
timeoutMs?: number
},
): Promise<RunnerFileUploadResultMessage> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
const normalizedSrcPath = validateRunnerWorkspacePath(options.srcPath)
const executionId = ulid()
@@ -863,7 +866,10 @@ export class RunnerService {
runnerId: string,
skill: { id: string; assetId: string; hash: string },
): Promise<string> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
const destPath = `.pi/skills/${skill.id}`
if (session.stagedSkills.get(skill.id) === skill.hash) {
@@ -904,7 +910,10 @@ export class RunnerService {
}
async ensureGeneratedFileOnRunner(runnerId: string, virtualPath: string): Promise<string> {
const session = this.requireReadySession(runnerId)
const session = this.sessions.get(runnerId)
if (!session) {
throw new Error('Runner is not connected')
}
const normalizedPath = validateRunnerWorkspacePath(virtualPath)
if (!normalizedPath.startsWith('.pi/generated/')) {
@@ -914,10 +923,7 @@ export class RunnerService {
}
if (session.stagedGeneratedFiles.has(normalizedPath)) {
const stat = await this.statOnRunner(runnerId, normalizedPath)
if (stat.ok && stat.exists && stat.isFile && this.getReadySession(runnerId) === session) {
return normalizedPath
}
return normalizedPath
}
// Virtual path .pi/generated/<ulid>/<filename> maps to storage key temp/generated/<ulid>/<filename>
@@ -955,54 +961,34 @@ export class RunnerService {
// Internal Helpers
// ----------------------------------------------------------------------
private getReadySession(runnerId: string): ActiveRunnerSession | undefined {
const session = this.sessions.get(runnerId)
return session?.environment ? session : undefined
}
private requireReadySession(runnerId: string): ActiveRunnerSession {
const session = this.getReadySession(runnerId)
if (!session) throw new Error('Runner is not connected')
return session
}
private handleReconcileMessage(
session: ActiveRunnerSession,
msg: Extract<RunnerToServerMessage, { type: 'reconcile' }>,
): void {
const completedIds = new Set<string>()
for (const completed of msg.completedExecutions) {
completedIds.add(completed.executionId)
this.handleExecResultMessage(session.runnerId, completed)
}
const activeIds = new Set(msg.activeExecutions.map((a) => a.executionId))
for (const executionId of activeIds) {
const pending = this.pendingOps.get(executionId)
if (
pending?.runnerId !== session.runnerId ||
pending.kind !== 'exec' ||
pending.cancelRequested
) {
// A timeout or cancellation may have occurred after the welcome snapshot.
this.sendToSession(session, { type: 'exec.cancel', executionId })
}
}
for (const [executionId, pending] of this.pendingOps.entries()) {
if (pending.runnerId !== session.runnerId) continue
if (pending.kind !== 'exec') {
// Re-send idempotent file control operations on reconnect.
this.sendToSession(session, pending.message)
} else if (!activeIds.has(executionId)) {
if (completedIds.has(executionId) || activeIds.has(executionId)) {
continue
}
if (pending.kind === 'exec') {
this.cleanupPendingOp(executionId)
if (pending.cancelRequested) {
this.reportCancelledExecution(pending)
continue
}
pending.reject(
new Error(
`Runner reconnected without active execution ${executionId} (runner process may have restarted)`,
),
)
} else {
// Re-send idempotent file control operations on reconnect
this.sendToSession(session, pending.message)
}
}
}
@@ -1045,8 +1031,8 @@ export class RunnerService {
output: this.readBufferedExecOutput(pending),
exitCode: msg.exitCode,
signal: msg.signal,
timedOut: msg.timedOut && !pending.cancelRequested,
aborted: pending.cancelRequested || (msg.aborted ?? false),
timedOut: msg.timedOut,
aborted: msg.aborted ?? false,
fullOutputPath: msg.fullOutputPath,
error: msg.error,
})
@@ -1147,7 +1133,11 @@ export class RunnerService {
private revokeActiveSession(runnerId: string, reason: string): void {
this.bumpCredentialRevision(runnerId)
this.clearDisconnectGraceTimer(runnerId)
const timer = this.disconnectGraceTimers.get(runnerId)
if (timer) {
clearTimeout(timer)
this.disconnectGraceTimers.delete(runnerId)
}
const session = this.sessions.get(runnerId)
if (session) {
@@ -1162,24 +1152,6 @@ export class RunnerService {
this.failPendingOperationsForRunner(runnerId, new Error(reason))
}
private clearDisconnectGraceTimer(runnerId: string): void {
const timer = this.disconnectGraceTimers.get(runnerId)
if (!timer) return
clearTimeout(timer)
this.disconnectGraceTimers.delete(runnerId)
}
private reportCancelledExecution(pending: PendingExecOperation): void {
pending.resolve({
executionId: pending.executionId,
output: this.readBufferedExecOutput(pending),
exitCode: null,
signal: 'SIGKILL',
timedOut: false,
aborted: true,
})
}
private failPendingOperationsForRunner(runnerId: string, error: Error): void {
for (const [executionId, pending] of this.pendingOps.entries()) {
if (pending.runnerId === runnerId) {
@@ -1196,9 +1168,8 @@ export class RunnerService {
if (pending.timeoutTimer) {
clearTimeout(pending.timeoutTimer)
}
if (pending.kind === 'exec') {
clearTimeout(pending.abortTimer)
pending.cleanupSignal?.()
if (pending.kind === 'exec' && pending.cleanupSignal) {
pending.cleanupSignal()
}
}
@@ -1,76 +0,0 @@
import { HTTPException } from 'hono/http-exception'
import { prisma } from '@shumai/db'
import { tryAcquireUpgradeableAdvisoryLock } from '@shumai/db/src/advisory-lock'
import { logger } from '@shumai/core/src/logger'
const RUNNER_TOPOLOGY_KEY = 'shumai:runner-topology'
const SINGLE_SERVER_REQUIRED =
'Agent runners require a single main Shumai server per database. Stop the other main server replicas.'
async function hasConfiguredRunners() {
return (await prisma.runner.findFirst({ select: { id: true } })) !== null
}
/** Each main server holds a shared lease. A configured runner requires an exclusive lease. */
export class RunnerTopology {
private mutations = Promise.resolve()
private constructor(
private readonly lease: NonNullable<
Awaited<ReturnType<typeof tryAcquireUpgradeableAdvisoryLock>>
>,
) {}
static async start() {
const configured = await hasConfiguredRunners()
let lease = await tryAcquireUpgradeableAdvisoryLock(RUNNER_TOPOLOGY_KEY, configured)
if (!lease && configured) {
// If the last runner was just deleted, the incumbent may now hold a shared lease.
lease = await tryAcquireUpgradeableAdvisoryLock(RUNNER_TOPOLOGY_KEY, false)
}
if (!lease) throw new Error(SINGLE_SERVER_REQUIRED)
try {
// A concurrently stopping server may have changed the catalog.
if (await hasConfiguredRunners()) {
if (!(await lease.tryUpgrade())) throw new Error(SINGLE_SERVER_REQUIRED)
} else {
await lease.downgrade()
}
return new RunnerTopology(lease)
} catch (error) {
await lease.release()
throw error
}
}
get signal() {
return this.lease.signal
}
/** Serialize runner creation and deletion until the exclusive lease can be safely downgraded. */
async changeRunners<T>(operation: () => Promise<T>, adding = false): Promise<T> {
const previous = this.mutations
const finished = Promise.withResolvers<void>()
this.mutations = finished.promise
await previous
try {
if (adding && !(await this.lease.tryUpgrade())) {
throw new HTTPException(409, { message: SINGLE_SERVER_REQUIRED })
}
return await operation()
} finally {
try {
if (this.lease.exclusive && !(await hasConfiguredRunners())) await this.lease.downgrade()
} catch (error) {
logger.warn({ err: error }, 'Failed to downgrade the runner server lease')
} finally {
finished.resolve()
}
}
}
async close() {
await this.mutations
await this.lease.release()
}
}
-44
View File
@@ -717,50 +717,6 @@ describe('S3Service implementations', () => {
expect(keysAll.length).toBe(3)
})
it('lists a nested prefix without scanning unrelated directories', async () => {
await localS3.putObject('test-bucket', 'temp/generated/one.jpg', 'one', 3)
await localS3.putObject('test-bucket', 'files/unrelated.txt', 'abc', 3)
const readDirectory = vi.spyOn(fs.promises, 'readdir')
try {
await expect(localS3.listObjects('test-bucket', 'temp/generated/')).resolves.toEqual([
'temp/generated/one.jpg',
])
expect(readDirectory.mock.calls.map(([directory]) => directory)).toEqual([
path.join(TEST_BASE_PATH, 'test-bucket', 'temp', 'generated'),
])
readDirectory.mockClear()
await expect(localS3.listObjects('test-bucket', 'temp/missing/')).resolves.toEqual([])
expect(readDirectory.mock.calls.map(([directory]) => directory)).not.toContain(
path.join(TEST_BASE_PATH, 'test-bucket'),
)
await expect(localS3.listObjects('test-bucket', 'temp/generated/on')).resolves.toEqual([
'temp/generated/one.jpg',
])
} finally {
readDirectory.mockRestore()
}
})
it('continues listing when a file disappears during a local prefix scan', async () => {
const removedKey = 'temp/generated/removed.jpg'
const remainingKey = 'temp/generated/remaining.jpg'
await localS3.putObject('test-bucket', removedKey, 'old', 3)
await localS3.putObject('test-bucket', remainingKey, 'new', 3)
const stat = fs.promises.stat
const removedPath = path.join(TEST_BASE_PATH, 'test-bucket', removedKey)
const statSpy = vi.spyOn(fs.promises, 'stat').mockImplementation(async (target, options) => {
if (target === removedPath) await fs.promises.unlink(removedPath)
return stat(target, options)
})
try {
await expect(localS3.listObjects('test-bucket', 'temp/generated/')).resolves.toEqual([
remainingKey,
])
} finally {
statSpy.mockRestore()
}
})
it('should handle headObject correctly', async () => {
await localS3.putObject('test-bucket', 'test.txt', 'hello world', 11)
const head = await localS3.headObject('test-bucket', 'test.txt')
+6 -23
View File
@@ -1012,33 +1012,16 @@ export class LocalStorageService implements S3Service {
async listObjects(bucket: string, prefix: string): Promise<string[]> {
const bucketDir = path.join(this.basePath, bucket)
const keys: string[] = []
const directoryPrefix = prefix.slice(0, prefix.lastIndexOf('/') + 1)
const directory = path.join(bucketDir, directoryPrefix.slice(0, -1))
const relativeDirectory = path.relative(bucketDir, directory).split(path.sep).join('/')
if (
directoryPrefix &&
(!relativeDirectory ||
relativeDirectory === '..' ||
relativeDirectory.startsWith('../') ||
relativeDirectory + '/' !== directoryPrefix)
)
return keys
const ignoreMissing = (error: unknown) => {
if (
error instanceof Error &&
'code' in error &&
(error.code === 'ENOENT' || error.code === 'ENOTDIR')
)
return undefined
throw error
if (!fs.existsSync(bucketDir)) {
return keys
}
const walkDir = async (currentDir: string) => {
const files = (await fs.promises.readdir(currentDir).catch(ignoreMissing)) ?? []
const files = await fs.promises.readdir(currentDir)
for (const file of files) {
const fullPath = path.join(currentDir, file)
const stat = await fs.promises.stat(fullPath).catch(ignoreMissing)
if (!stat) continue
const stat = await fs.promises.stat(fullPath)
if (stat.isDirectory()) {
await walkDir(fullPath)
@@ -1054,7 +1037,7 @@ export class LocalStorageService implements S3Service {
}
}
await walkDir(directory)
await walkDir(bucketDir)
return keys
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-65
View File
@@ -39,68 +39,3 @@ export async function acquireAdvisoryLock(key: string, signal?: AbortSignal) {
},
}
}
/** Hold a shared server lease, with a non-blocking upgrade to exclusive ownership. */
export async function tryAcquireUpgradeableAdvisoryLock(key: string, exclusive: boolean) {
const client = await locks.connect()
const lost = new AbortController()
const onError = (error: Error) => lost.abort(error)
client.on('error', onError)
const tryExclusive = async () => {
const result = await client.query<{ acquired: boolean }>(
'SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS acquired',
[key],
)
return result.rows[0]?.acquired === true
}
let acquired = false
try {
if (exclusive && !(await tryExclusive())) return null
const result = await client.query<{ acquired: boolean }>(
'SELECT pg_try_advisory_lock_shared(hashtextextended($1, 0)) AS acquired',
[key],
)
lost.signal.throwIfAborted()
acquired = result.rows[0]?.acquired === true
if (!acquired) return null
} finally {
if (!acquired) {
client.off('error', onError)
client.release(true)
}
}
let released = false
const assertHeld = () => {
if (released) throw new Error('The server lease has been released')
lost.signal.throwIfAborted()
}
return {
signal: lost.signal,
get exclusive() {
return exclusive
},
async tryUpgrade() {
assertHeld()
if (!exclusive) exclusive = await tryExclusive()
return exclusive
},
async downgrade() {
assertHeld()
if (!exclusive) return
await client.query('SELECT pg_advisory_unlock(hashtextextended($1, 0))', [key])
exclusive = false
},
async release() {
if (released) return
released = true
try {
if (!lost.signal.aborted) await client.query('SELECT pg_advisory_unlock_all()')
} finally {
client.off('error', onError)
client.release(true)
}
},
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-2
View File
@@ -48,8 +48,6 @@ export type RotateRunnerKeyResponse = z.infer<typeof rotateRunnerKeyResponseSche
// WebSocket Wire Protocol Schemas
// ----------------------------------------------------------------------
export const RUNNER_REPLACED_CLOSE_CODE = 4000
export const runnerWelcomeMessageSchema = z.object({
type: z.literal('welcome'),
runnerId: z.string(),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"dependencies": {
-10
View File
@@ -262,16 +262,6 @@ describe('Workflow E2E - read_asset', () => {
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
runnerSocket,
)
runnerService.handleMessage(
runner.id,
runnerSocket,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: [],
completedExecutions: [],
}),
)
const video = await createFileAsset(
project.id,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/operations",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
+2 -2
View File
@@ -1703,10 +1703,10 @@
"task_type_restore_asset": "Restore Asset",
"agent_runners": "Agent Runners",
"agent_runners_settings": "Agent Runners",
"runners_description": "Register and manage remote runners. Everyone with shell access to a runner can read files in its workspace, including files from other projects.",
"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 runner for your team and get a one-time key for shumai-cli. Share the runner only with users who may read all files in its workspace.",
"create_runner_description": "Register a new runner for your team. You will receive a one-time runner key to connect from shumai-cli.",
"runner_name": "Runner Name",
"runner_name_placeholder": "e.g. Mac Mini Runner",
"runner_description": "Description (Optional)",
+1 -48
View File
@@ -1630,52 +1630,5 @@
"filter_archived_only": "보관됨",
"filter_not_archived": "보관되지 않음",
"task_type_archive_asset": "에셋 보관",
"task_type_restore_asset": "에셋 복원",
"agent_runners": "에이전트 러너",
"agent_runners_settings": "에이전트 러너 설정",
"runners_description": "원격 러너를 등록하고 관리합니다. 러너에 셸 접근 권한이 있는 사용자는 다른 프로젝트의 파일을 포함해 해당 워크스페이스의 모든 파일을 읽을 수 있습니다.",
"runners": "러너",
"create_runner": "러너 생성",
"create_runner_description": "팀용 러너를 등록하고 shumai-cli에 사용할 일회성 키를 발급받습니다. 워크스페이스의 모든 파일을 읽어도 되는 사용자와만 러너를 공유하세요.",
"runner_name": "러너 이름",
"runner_name_placeholder": "예: Mac Mini 러너",
"runner_description": "설명(선택 사항)",
"runner_description_placeholder": "예: 영상 처리용 로컬 macOS 러너",
"runner_set_as_default": "팀 기본 러너로 설정",
"runner_default_badge": "기본",
"runner_status_connected": "온라인",
"runner_status_disconnected": "오프라인",
"runner_key_prefix_label": "키 접두사",
"runner_last_seen_label": "마지막 연결: {time}",
"runner_never_connected": "연결 기록 없음",
"runner_set_default_action": "기본으로 설정",
"runner_rotate_key_action": "키 순환",
"runner_edit_action": "러너 편집",
"runner_edit_description": "이 러너의 이름 또는 설명을 업데이트합니다.",
"runner_delete_confirm_title": "러너 삭제",
"runner_delete_confirm_description": "\"{name}\" 러너를 삭제하시겠습니까? 활성 연결은 즉시 종료되며, 이 러너에 연결된 에이전트는 팀 기본 러너로 전환됩니다.",
"runner_rotate_key_confirm_title": "러너 키 순환",
"runner_rotate_key_confirm_description": "\"{name}\"의 키를 순환하면 현재 키가 즉시 무효화되고 활성 세션이 연결 해제됩니다. 새 키로 러너를 다시 시작해야 합니다.",
"runner_key_dialog_title": "러너 키 저장",
"runner_key_dialog_description": "지금 이 러너 키를 복사하세요. 보안을 위해 다시 표시되지 않습니다.",
"runner_key_label": "러너 키",
"runner_quickstart_command_label": "빠른 시작 명령",
"runner_quickstart_sandbox_label": "샌드박스로 시작(선택 사항)",
"runner_empty_title": "구성된 러너 없음",
"runner_empty_description": "구성된 러너가 없으면 에이전트에서 bash 및 download_asset 도구가 자동으로 숨겨집니다. 명령 실행을 활성화하려면 러너를 생성하고 shumai-cli로 시작하세요.",
"runner_created_successfully": "러너가 생성되었습니다",
"runner_updated_successfully": "러너가 업데이트되었습니다",
"runner_deleted_successfully": "러너가 삭제되었습니다",
"runner_key_rotated_successfully": "러너 키가 순환되었습니다",
"failed_to_load_runners": "러너를 불러오지 못했습니다",
"failed_to_create_runner": "러너를 생성하지 못했습니다",
"failed_to_update_runner": "러너를 업데이트하지 못했습니다",
"failed_to_delete_runner": "러너를 삭제하지 못했습니다",
"failed_to_rotate_runner_key": "러너 키를 순환하지 못했습니다",
"runner_copied_to_clipboard": "클립보드에 복사되었습니다",
"agent_runner_label": "명령 러너",
"agent_runner_description": "이 에이전트의 셸 명령을 실행하고 워크스페이스 에셋을 다운로드할 러너를 선택합니다.",
"agent_runner_team_default": "팀 기본 러너",
"agent_runner_team_default_with_name": "팀 기본({name})",
"agent_runner_none_configured_warning": "이 팀에 아직 구성된 러너가 없습니다. 팀 설정 → 에이전트 러너에서 러너를 등록할 때까지 bash 및 download_asset 도구를 사용할 수 없습니다."
"task_type_restore_asset": "에셋 복원"
}
+2 -2
View File
@@ -1703,10 +1703,10 @@
"task_type_restore_asset": "恢复归档资产",
"agent_runners": "Agent 运行器",
"agent_runners_settings": "Agent 运行器设置",
"runners_description": "注册并管理远程运行器。有权在同一运行器执行命令的用户可以读取其工作区中的文件,包括其他项目留下的文件。",
"runners_description": "注册并管理为 Agent 执行命令和技能的远程运行器。",
"runners": "运行器",
"create_runner": "创建运行器",
"create_runner_description": "为团队注册运行器并获取用于 shumai-cli 的一次性密钥。请仅在有权读取工作区内所有文件的用户之间共享运行器。",
"create_runner_description": "为团队注册一个新的运行器。创建后将生成一次性运行器密钥,用于通过 shumai-cli 连接。",
"runner_name": "运行器名称",
"runner_name_placeholder": "例如:Mac Mini 运行器",
"runner_description": "描述(可选)",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/webui",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./index.html",
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = '0.7.0'
export const APP_VERSION = '0.6.6'
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/workflow-core",
"version": "0.7.0",
"version": "0.6.6",
"private": true,
"type": "module",
"main": "./src/index.ts",
-2
View File
@@ -81,7 +81,6 @@ export async function assembleCliRelease(outdir: string, targets = cliTargetName
export async function buildCliRelease(outdir: string, targets = cliTargetNames) {
validateCliVersion(version)
if (cliVersion !== version) throw new Error('Root and CLI package versions must match')
const notices = await readFile(join(repoRoot, 'apps/cli/THIRD-PARTY-NOTICES.txt'), 'utf8')
await mkdir(outdir, { recursive: true })
const staging = await mkdtemp(join(outdir, '.build-'))
try {
@@ -92,7 +91,6 @@ export async function buildCliRelease(outdir: string, targets = cliTargetNames)
entrypoints: [join(repoRoot, 'apps/cli/src/index.ts')],
target: 'bun',
minify: true,
banner: '/*\n' + notices + '*/',
plugins: [srtBundlePlugin(...target.split('-'))],
compile: {
target: cliTargets[target],
-2
View File
@@ -521,8 +521,6 @@ async function buildCliPackage() {
target: 'node',
outdir: binOutDir,
minify: true,
banner:
'/*\n' + readFileSync(path.join(rootDir, 'apps/cli/THIRD-PARTY-NOTICES.txt'), 'utf8') + '*/',
naming: 'shumai-cli.js',
plugins: [srtBundlePlugin()],
external: [],
+5 -109
View File
@@ -2,11 +2,10 @@ import assert from 'node:assert/strict'
import { execFile } from 'node:child_process'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join, resolve } from 'node:path'
import { join, resolve } from 'node:path'
import { promisify, parseArgs } from 'node:util'
import { randomBytes } from 'node:crypto'
import { version } from '../package.json'
import { runnerToServerMessageSchema } from '../packages/dtos/src/runner'
import { archiveName, packCliBinary, parseCliTarget, sha256 } from './build-cli'
const execFileAsync = promisify(execFile)
@@ -15,105 +14,8 @@ function assertRecord(value: unknown): asserts value is Record<string, unknown>
assert.ok(value && typeof value === 'object' && !Array.isArray(value))
}
async function testRunnerShell(binary: string, cwd: string, env: NodeJS.ProcessEnv, srt?: string) {
const key = 'fixture-runner-key'
const executionId = srt ? 'srt-shell-quotes' : 'shell-quotes'
let output = ''
let completed = false
let fixtureFailure: unknown
await writeFile(join(cwd, 'runner input.txt'), 'input with spaces\n')
const server = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch(request, server) {
if (new URL(request.url).pathname !== '/api/runners/ws')
return new Response(null, { status: 404 })
if (request.headers.get('authorization') !== 'Bearer ' + key)
return new Response(null, { status: 401 })
if (!server.upgrade(request)) return new Response(null, { status: 426 })
},
websocket: {
open(socket) {
socket.send(
JSON.stringify({
type: 'welcome',
runnerId: 'runner-test',
runnerName: 'Native CLI',
serverTime: Date.now(),
inFlightExecutionIds: [],
}),
)
},
message(socket, raw) {
try {
const message = runnerToServerMessageSchema.parse(JSON.parse(raw.toString()))
if (message.type === 'reconcile') {
assert.equal(message.environment.platform, process.platform)
const shell = basename(message.environment.shell).toLowerCase()
assert.equal(shell, process.platform === 'win32' ? 'bash.exe' : 'sh')
socket.send(
JSON.stringify({
type: 'exec.start',
executionId,
command:
'IFS= read -r line < "runner input.txt"\nprintf \'%s | %s\' "$line" \'$literal "quotes"\'',
timeoutSec: 15,
}),
)
} else if (message.type === 'exec.output') {
assert.equal(message.executionId, executionId)
assert.equal(message.stream, 'stdout')
output += message.data
} else if (message.type === 'exec.result') {
assert.equal(message.executionId, executionId)
assert.equal(message.exitCode, 0, JSON.stringify(message))
assert.equal(output, 'input with spaces | $literal "quotes"')
completed = true
socket.close(1008)
}
} catch (error) {
fixtureFailure ??= error
socket.close(1008)
}
},
},
})
try {
const child = Bun.spawn(
[
binary,
'runner',
'start',
'--cwd',
cwd,
'--url',
server.url.origin,
...(srt ? ['--srt', srt] : []),
],
{
env: {
...env,
...(process.platform === 'win32' || srt ? { PATH: process.env.PATH } : {}),
SHUMAI_RUNNER_KEY: key,
},
signal: AbortSignal.timeout(60_000),
stderr: 'pipe',
stdout: 'ignore',
},
)
const [exitCode, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()])
if (fixtureFailure) throw fixtureFailure
assert.ok(completed, 'Runner did not complete the shell command:\n' + stderr)
assert.equal(exitCode, 1, stderr)
assert.match(stderr, /Runner shell: .+/)
assert.match(stderr, /Runner access was revoked/)
} finally {
server.stop(true)
}
}
/** Exercises the packaged installer and executable against HTTP, without a runtime on PATH. */
export async function testCliRelease(outdir: string, srt?: string) {
export async function testCliRelease(outdir: string) {
const windows = process.platform === 'win32'
const target = parseCliTarget(`${windows ? 'windows' : process.platform}-${process.arch}`)
const bytes = randomBytes(65536)
@@ -298,10 +200,6 @@ export async function testCliRelease(outdir: string, srt?: string) {
await install()
assert.equal((await run(['--version'])).trim(), version)
assert.match(await run(['--help']), /Command line interface/)
const workspace = join(temporary, 'runner workspace')
await mkdir(workspace)
await testRunnerShell(binary, workspace, cliEnv)
if (srt) await testRunnerShell(binary, workspace, cliEnv, srt)
const projects = JSON.parse(await run(['--json', 'project', 'ls'])) as {
data: { id: string }[]
}
@@ -375,7 +273,7 @@ export async function testCliRelease(outdir: string, srt?: string) {
await assert.rejects(install(), /unmanaged installation/)
assert.equal(sha256(await readFile(binary)), installedHash)
console.log(
`PASS ${target}: install, runner shell, API auth, mkdir, upload/download 65536 bytes, upgrade/rollback, and failure preservation`,
`PASS ${target}: install, API auth, mkdir, upload/download 65536 bytes, upgrade/rollback, and failure preservation`,
)
} finally {
server.stop(true)
@@ -384,8 +282,6 @@ export async function testCliRelease(outdir: string, srt?: string) {
}
if (import.meta.main) {
const { values } = parseArgs({
options: { out: { type: 'string', default: 'out/cli-release' }, srt: { type: 'string' } },
})
await testCliRelease(resolve(values.out), values.srt ? resolve(values.srt) : undefined)
const { values } = parseArgs({ options: { out: { type: 'string', default: 'out/cli-release' } } })
await testCliRelease(resolve(values.out))
}