mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 10:26:57 +00:00
refactor(cli): remove runner Python dependency
This commit is contained in:
+1
-1
@@ -8,7 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
- **cli**: Start a remote bash runner with `shumai-cli runner start`, with optional sandboxing through an SRT JSON configuration file.
|
||||
- **cli**: Run remote bash commands and exchange files with `shumai-cli runner start`, with optional sandboxing through an SRT JSON configuration file.
|
||||
- **agent**: Support binding external Runners per team so agents can execute shell commands and exchange files securely over WebSocket without requiring a built-in server sandbox, and allow assigning a default or dedicated Runner per agent in Team Settings.
|
||||
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
|
||||
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ export SHUMAI_ALLOW_DELETE="true"
|
||||
|
||||
## Agent runner
|
||||
|
||||
Create a runner in **Settings → Agent Runners** and copy its one-time key. On a macOS or Linux machine with `/bin/bash` and Python 3, start it in an existing dedicated workspace:
|
||||
Create a runner in **Settings → Agent Runners** and copy its one-time key. On a macOS or Linux machine with `/bin/bash`, start it in an existing dedicated workspace:
|
||||
|
||||
```sh
|
||||
export SHUMAI_API_SERVER="https://shumai.example.com"
|
||||
|
||||
@@ -15,11 +15,13 @@
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"ws": "8.22.2",
|
||||
"yauzl": "3.4.0",
|
||||
"zod": "4.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yauzl": "3.4.0",
|
||||
"adm-zip": "0.6.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { constants } from 'node:fs'
|
||||
import { access, realpath } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
export async function findExecutable(name: string): Promise<string> {
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
|
||||
if (!directory) continue
|
||||
const candidate = path.resolve(directory, name)
|
||||
try {
|
||||
await access(candidate, constants.X_OK)
|
||||
return await realpath(candidate)
|
||||
} catch {
|
||||
// Try the next PATH entry.
|
||||
}
|
||||
}
|
||||
throw new Error(`${name} is required on the runner machine and must be available on PATH.`)
|
||||
}
|
||||
@@ -1,16 +1,6 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createServer, type Server } from 'node:http'
|
||||
import {
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from 'node:fs/promises'
|
||||
import { mkdtemp, mkdir, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import AdmZip from 'adm-zip'
|
||||
@@ -214,18 +204,6 @@ describe('runner workspace file transfers', () => {
|
||||
await expect(readFile(path.join(cwd, '.pi/skills/bad/link'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('keeps writes on the opened directory when a command replaces it with a symlink', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/work'), { recursive: true })
|
||||
await mkdir(path.join(cwd, 'outside'))
|
||||
const writer = await files.createWriter('.pi/work/safe.txt')
|
||||
await rename(path.join(cwd, '.pi/work'), path.join(cwd, '.pi/held'))
|
||||
await symlink(path.join(cwd, 'outside'), path.join(cwd, '.pi/work'))
|
||||
await writer.write('safe contents')
|
||||
await writer.close()
|
||||
expect(await readFile(path.join(cwd, '.pi/held/safe.txt'), 'utf8')).toBe('safe contents')
|
||||
await expect(readFile(path.join(cwd, 'outside/safe.txt'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('preserves executable script permissions and rejects oversized ZIP entries', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('run.sh', Buffer.from('#!/bin/sh\necho executable\n'))
|
||||
@@ -308,7 +286,9 @@ describe('runner workspace file transfers', () => {
|
||||
name.startsWith('.shumai-'),
|
||||
)
|
||||
expect(temporary).toBeDefined()
|
||||
expect((await readdir(path.join(cwd, '.pi/skills', temporary!))).length).toBeGreaterThan(0)
|
||||
expect(
|
||||
(await readdir(path.join(cwd, '.pi/skills', temporary!, 'extracted'))).length,
|
||||
).toBeGreaterThan(0)
|
||||
},
|
||||
{ interval: 5, timeout: 5000 },
|
||||
)
|
||||
|
||||
+199
-148
@@ -1,24 +1,37 @@
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { on } from 'node:events'
|
||||
import { constants, createWriteStream } from 'node:fs'
|
||||
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { Readable, Transform } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import { z } from 'zod'
|
||||
import yauzl from 'yauzl'
|
||||
import type {
|
||||
RunnerFileDownloadMessage,
|
||||
RunnerFileUploadMessage,
|
||||
RunnerFileStatMessage,
|
||||
RunnerToServerMessage,
|
||||
} from '@shumai/dtos'
|
||||
import { findExecutable, spawnFileHelper } from './filesystem'
|
||||
|
||||
const MAX_FILE_BYTES = 256 * 1024 * 1024
|
||||
const MAX_ZIP_ENTRIES = 10_000
|
||||
export type FileMessage =
|
||||
RunnerFileDownloadMessage | RunnerFileUploadMessage | RunnerFileStatMessage
|
||||
const metadataSchema = z.object({
|
||||
exists: z.boolean().optional(),
|
||||
isFile: z.boolean().optional(),
|
||||
size: z.number().optional(),
|
||||
name: z.string().optional(),
|
||||
cached: z.boolean().optional(),
|
||||
ready: z.boolean().optional(),
|
||||
})
|
||||
|
||||
function pathParts(value: string): string[] {
|
||||
const parts = value.split('/')
|
||||
if (
|
||||
value.includes('\\') ||
|
||||
value.includes('\0') ||
|
||||
parts.some((part) => !part || part === '.' || part === '..' || part.includes(':'))
|
||||
)
|
||||
throw new Error('Invalid workspace path.')
|
||||
return parts
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
function transferUrl(address: string): URL {
|
||||
const url = new URL(address)
|
||||
@@ -28,146 +41,74 @@ function transferUrl(address: string): URL {
|
||||
}
|
||||
|
||||
export class RunnerFiles {
|
||||
private python?: Promise<string>
|
||||
constructor(readonly cwd: string) {}
|
||||
|
||||
async initialize() {
|
||||
await (this.python ??= findExecutable('python3'))
|
||||
/** Basic workspace validation. Concurrent hostile filesystem mutation is outside v1's scope. */
|
||||
private async resolve(relative: string, createParents = false): Promise<string> {
|
||||
const parts = pathParts(relative)
|
||||
if (parts[0] !== '.pi' || parts.length < 2) throw new Error('File paths must stay inside .pi/.')
|
||||
let current = this.cwd
|
||||
for (let index = 0; index < parts.length; index++) {
|
||||
current = path.join(current, parts[index])
|
||||
const parent = index < parts.length - 1
|
||||
if (parent && createParents) await mkdir(current, { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
const info = await lstat(current)
|
||||
if (info.isSymbolicLink() || (parent && !info.isDirectory()))
|
||||
throw new Error('Workspace paths cannot contain symlinks or non-directory parents.')
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
private async helper(operation: string, relative: string, expectedHash = '') {
|
||||
await this.initialize()
|
||||
const child = spawnFileHelper(await this.python!, this.cwd, operation, relative, expectedHash)
|
||||
const control = child.stdio[3]
|
||||
if (!(control instanceof Writable)) throw new Error('Missing filesystem commit channel.')
|
||||
control.on('error', () => {})
|
||||
if (operation === 'read' || operation === 'stat') control.end()
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
// Binary reads are consumed by fetch, all other operations return small JSON metadata.
|
||||
if (operation !== 'read')
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
stdout = (stdout + chunk.toString()).slice(-8192)
|
||||
})
|
||||
let firstLine: (value: string) => void
|
||||
const ready = new Promise<string>((resolve) => {
|
||||
firstLine = resolve
|
||||
})
|
||||
child.stderr.on('data', (chunk: Buffer) => {
|
||||
stderr = (stderr + chunk.toString()).slice(-8192)
|
||||
if (stderr.includes('\n')) firstLine(stderr.split('\n')[0]!)
|
||||
})
|
||||
// A failed helper must not produce an unhandled EPIPE while HTTP is still streaming.
|
||||
child.stdin.on('error', () => {})
|
||||
const done = new Promise<z.infer<typeof metadataSchema>>((resolve, reject) => {
|
||||
child.once('error', (error) => {
|
||||
firstLine('')
|
||||
reject(error)
|
||||
})
|
||||
child.once('close', (code) => {
|
||||
firstLine(stderr)
|
||||
if (code !== 0)
|
||||
reject(new Error(stderr.trim().split('\n').at(-1) || 'Runner file operation failed.'))
|
||||
else if (operation === 'read') resolve({})
|
||||
else {
|
||||
try {
|
||||
resolve(metadataSchema.parse(JSON.parse(stdout)))
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
void done.catch(() => {})
|
||||
let stopping = false
|
||||
const stop = () => {
|
||||
if (stopping || child.exitCode !== null || child.signalCode !== null) return
|
||||
stopping = true
|
||||
control.end()
|
||||
child.stdin.destroy()
|
||||
child.kill('SIGTERM')
|
||||
const fallback = setTimeout(() => child.kill('SIGKILL'), 5000)
|
||||
void done.finally(() => clearTimeout(fallback)).catch(() => {})
|
||||
}
|
||||
return { child, done, ready, stop, commit: () => control.end('1') }
|
||||
}
|
||||
|
||||
async createWriter(relative: string, expectedHash = '') {
|
||||
const task = await this.helper('write', relative, expectedHash)
|
||||
try {
|
||||
const metadata = metadataSchema.parse(JSON.parse(await task.ready))
|
||||
if (!metadata.ready) throw new Error('Runner file writer did not initialize.')
|
||||
} catch (error) {
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
throw error
|
||||
}
|
||||
async createWriter(relative: string) {
|
||||
const file = await open(
|
||||
await this.resolve(relative, true),
|
||||
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
|
||||
0o600,
|
||||
)
|
||||
return {
|
||||
async write(data: string) {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
task.child.stdin.write(data, (error) => {
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
}),
|
||||
)
|
||||
},
|
||||
async close() {
|
||||
task.child.stdin.end()
|
||||
task.commit()
|
||||
return await task.done
|
||||
write: async (data: string) => {
|
||||
await file.writeFile(data)
|
||||
},
|
||||
close: () => file.close(),
|
||||
}
|
||||
}
|
||||
|
||||
async handle(message: FileMessage, signal: AbortSignal): Promise<RunnerToServerMessage> {
|
||||
try {
|
||||
if (message.type === 'file.stat') {
|
||||
const task = await this.helper('stat', message.srcPath)
|
||||
task.child.stdin.end()
|
||||
const result = await task.done
|
||||
signal.throwIfAborted()
|
||||
if (message.type === 'file.download')
|
||||
return {
|
||||
type: 'file.download.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
...(await this.download(message, signal)),
|
||||
}
|
||||
const filename = await this.resolve(message.srcPath)
|
||||
if (message.type === 'file.upload') return await this.upload(message, filename, signal)
|
||||
try {
|
||||
const info = await lstat(filename)
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: result.exists ?? false,
|
||||
...result,
|
||||
exists: true,
|
||||
isFile: info.isFile(),
|
||||
size: info.size,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: false,
|
||||
}
|
||||
}
|
||||
if (message.type === 'file.download') {
|
||||
const response = await fetch(transferUrl(message.url), { signal, redirect: 'error' })
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel()
|
||||
throw new Error(`Download failed (HTTP ${response.status}).`)
|
||||
}
|
||||
const task = await this.helper(
|
||||
message.extractZip ? 'extract' : 'write',
|
||||
message.destPath,
|
||||
message.expectedHash,
|
||||
)
|
||||
const abort = () => {
|
||||
task.stop()
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
try {
|
||||
if (signal.aborted) signal.throwIfAborted()
|
||||
await pipeline(response.body, task.child.stdin, { signal })
|
||||
signal.throwIfAborted()
|
||||
task.commit()
|
||||
return {
|
||||
type: 'file.download.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
...(await task.done),
|
||||
}
|
||||
} catch (error) {
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
throw error
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
return await this.upload(message, signal)
|
||||
} catch (error) {
|
||||
const result = {
|
||||
executionId: message.executionId,
|
||||
@@ -187,20 +128,26 @@ export class RunnerFiles {
|
||||
|
||||
private async upload(
|
||||
message: RunnerFileUploadMessage,
|
||||
filename: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<RunnerToServerMessage> {
|
||||
const task = await this.helper('read', message.srcPath)
|
||||
task.child.stdin.end()
|
||||
const abort = () => {
|
||||
task.stop()
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
const file = await open(
|
||||
filename,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
)
|
||||
try {
|
||||
const info = metadataSchema.parse(JSON.parse(await task.ready))
|
||||
if (!info.isFile || info.size === undefined) throw new Error('Invalid upload file.')
|
||||
const info = await file.stat()
|
||||
if (!info.isFile() || info.size > MAX_FILE_BYTES)
|
||||
throw new Error('Upload must be a regular file no larger than 256 MiB.')
|
||||
// Node and Bun declare different DOM stream types for the same fetch-compatible stream.
|
||||
const body = info.size
|
||||
? (Readable.toWeb(
|
||||
file.createReadStream({ autoClose: false, end: info.size - 1 }),
|
||||
) as unknown as ReadableStream<Uint8Array>)
|
||||
: new Uint8Array()
|
||||
const response = await fetch(transferUrl(message.url), {
|
||||
method: 'PUT',
|
||||
body: Readable.toWeb(task.child.stdout) as unknown as ReadableStream<Uint8Array>,
|
||||
body,
|
||||
...{ duplex: 'half' },
|
||||
headers: {
|
||||
'content-type': message.contentType ?? 'application/octet-stream',
|
||||
@@ -211,18 +158,122 @@ export class RunnerFiles {
|
||||
})
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) throw new Error(`Upload failed (HTTP ${response.status}).`)
|
||||
await task.done
|
||||
return {
|
||||
type: 'file.upload.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
size: info.size,
|
||||
name: info.name,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort)
|
||||
task.stop()
|
||||
await task.done.catch(() => {})
|
||||
await file.close()
|
||||
}
|
||||
}
|
||||
|
||||
private async download(message: RunnerFileDownloadMessage, signal: AbortSignal) {
|
||||
const destination = await this.resolve(message.destPath, true)
|
||||
const temporary = await mkdtemp(path.join(path.dirname(destination), '.shumai-'))
|
||||
let preserveBackup = false
|
||||
try {
|
||||
const response = await fetch(transferUrl(message.url), { signal, redirect: 'error' })
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel()
|
||||
throw new Error(`Download failed (HTTP ${response.status}).`)
|
||||
}
|
||||
const hash = createHash('sha256')
|
||||
let size = 0
|
||||
const archive = path.join(temporary, 'download')
|
||||
await pipeline(
|
||||
response.body,
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length
|
||||
if (size > MAX_FILE_BYTES) {
|
||||
callback(new Error('Download exceeds 256 MiB.'))
|
||||
return
|
||||
}
|
||||
hash.update(chunk)
|
||||
callback(null, chunk)
|
||||
},
|
||||
}),
|
||||
createWriteStream(archive, { flags: 'wx', mode: 0o600 }),
|
||||
{ signal },
|
||||
)
|
||||
if (message.expectedHash && hash.digest('hex') !== message.expectedHash)
|
||||
throw new Error('Downloaded file hash does not match.')
|
||||
let source = archive
|
||||
if (message.extractZip) {
|
||||
source = path.join(temporary, 'extracted')
|
||||
await mkdir(source, { mode: 0o700 })
|
||||
await this.extract(archive, source, signal)
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
await this.resolve(message.destPath)
|
||||
if (message.extractZip) {
|
||||
const backup = path.join(temporary, 'previous')
|
||||
let backedUp = false
|
||||
try {
|
||||
await rename(destination, backup)
|
||||
backedUp = true
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
try {
|
||||
await rename(source, destination)
|
||||
} catch (error) {
|
||||
if (backedUp) {
|
||||
preserveBackup = true
|
||||
await rename(backup, destination)
|
||||
preserveBackup = false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else await rename(source, destination)
|
||||
return { size, cached: false }
|
||||
} finally {
|
||||
if (!preserveBackup) await rm(temporary, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async extract(archive: string, directory: string, signal: AbortSignal) {
|
||||
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) =>
|
||||
yauzl.open(
|
||||
archive,
|
||||
{ lazyEntries: true, strictFileNames: true, autoClose: false },
|
||||
(error, opened) => (error ? reject(error) : resolve(opened)),
|
||||
),
|
||||
)
|
||||
let size = 0
|
||||
let count = 0
|
||||
try {
|
||||
const entries = on(zip, 'entry', { close: ['end'], signal }) as AsyncIterable<[yauzl.Entry]>
|
||||
zip.readEntry()
|
||||
for await (const [entry] of entries) {
|
||||
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
|
||||
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
|
||||
const mode = entry.externalFileAttributes >>> 16
|
||||
const kind = mode & 0o170000
|
||||
if (kind && kind !== 0o100000 && kind !== 0o040000)
|
||||
throw new Error('ZIP links and special files are forbidden.')
|
||||
size += entry.uncompressedSize
|
||||
if (size > MAX_FILE_BYTES) throw new Error('Extracted ZIP exceeds 256 MiB.')
|
||||
const destination = path.join(directory, ...parts)
|
||||
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
|
||||
else {
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
|
||||
const input = await new Promise<Readable>((resolve, reject) =>
|
||||
zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream))),
|
||||
)
|
||||
await pipeline(
|
||||
input,
|
||||
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
|
||||
{ signal },
|
||||
)
|
||||
}
|
||||
zip.readEntry()
|
||||
}
|
||||
} finally {
|
||||
zip.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { constants } from 'node:fs'
|
||||
import { access, realpath } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { commandEnv } from './config'
|
||||
|
||||
export async function findExecutable(name: string): Promise<string> {
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
|
||||
if (!directory) continue
|
||||
const candidate = path.resolve(directory, name)
|
||||
try {
|
||||
await access(candidate, constants.X_OK)
|
||||
return await realpath(candidate)
|
||||
} catch {
|
||||
/* Try the next PATH entry. */
|
||||
}
|
||||
}
|
||||
throw new Error(`${name} is required on the runner machine and must be available on PATH.`)
|
||||
}
|
||||
|
||||
// Node has no portable openat API. This small, isolated Python helper uses directory
|
||||
// descriptors for every workspace access, so concurrent shell symlink swaps cannot
|
||||
// redirect host-side transfers or logs outside the workspace. No network or credentials.
|
||||
const FILESYSTEM_HELPER = String.raw`
|
||||
import os, sys, stat, json, hashlib, tempfile, zipfile, secrets, signal
|
||||
MAX = 256 * 1024 * 1024
|
||||
FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
def cancelled(signum, frame): raise InterruptedError('File transfer aborted.')
|
||||
signal.signal(signal.SIGTERM, cancelled)
|
||||
root = os.open(sys.argv[1], FLAGS)
|
||||
operation, relative = sys.argv[2:4]
|
||||
def components(value):
|
||||
parts = value.split('/')
|
||||
if chr(92) in value or chr(0) in value or any(not p or p in ('.', '..') or ':' in p for p in parts):
|
||||
raise ValueError('Invalid workspace path.')
|
||||
return parts
|
||||
def parent_at(base, parts, create=False):
|
||||
current = os.dup(base)
|
||||
try:
|
||||
for part in parts[:-1]:
|
||||
if create:
|
||||
try: os.mkdir(part, 0o700, dir_fd=current)
|
||||
except FileExistsError: pass
|
||||
following = os.open(part, FLAGS, dir_fd=current)
|
||||
os.close(current)
|
||||
current = following
|
||||
return current, parts[-1]
|
||||
except BaseException:
|
||||
os.close(current)
|
||||
raise
|
||||
def remove_at(parent, name):
|
||||
try: info = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
||||
except FileNotFoundError: return
|
||||
if stat.S_ISDIR(info.st_mode):
|
||||
child = os.open(name, FLAGS, dir_fd=parent)
|
||||
try:
|
||||
for entry in os.listdir(child): remove_at(child, entry)
|
||||
finally: os.close(child)
|
||||
os.rmdir(name, dir_fd=parent)
|
||||
else: os.unlink(name, dir_fd=parent)
|
||||
def commit():
|
||||
if os.read(3, 1) != b'1': raise InterruptedError('File transfer was not committed.')
|
||||
def publish_directory(parent, temporary, name):
|
||||
backup = '.shumai-' + secrets.token_hex(16)
|
||||
backed_up = False
|
||||
published = False
|
||||
mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
|
||||
try:
|
||||
try:
|
||||
os.rename(name, backup, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
backed_up = True
|
||||
except FileNotFoundError: pass
|
||||
try:
|
||||
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
published = True
|
||||
except BaseException:
|
||||
if backed_up:
|
||||
os.rename(backup, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
backed_up = False
|
||||
raise
|
||||
finally:
|
||||
try: signal.pthread_sigmask(signal.SIG_SETMASK, mask)
|
||||
finally:
|
||||
if backed_up and published: remove_at(parent, backup)
|
||||
def copy_input(destination, expected):
|
||||
digest, size = hashlib.sha256(), 0
|
||||
while True:
|
||||
chunk = sys.stdin.buffer.read(65536)
|
||||
if not chunk: break
|
||||
size += len(chunk)
|
||||
if size > MAX: raise ValueError('Download exceeds 256 MiB.')
|
||||
digest.update(chunk)
|
||||
destination.write(chunk)
|
||||
if expected and digest.hexdigest() != expected: raise ValueError('Downloaded file hash does not match.')
|
||||
return size
|
||||
try:
|
||||
parts = components(relative)
|
||||
if parts[0] != '.pi' or len(parts) < 2: raise ValueError('File paths must stay inside .pi/.')
|
||||
parent, name = parent_at(root, parts, operation in ('write', 'extract'))
|
||||
try:
|
||||
if operation in ('stat', 'read'):
|
||||
try: fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
||||
except FileNotFoundError:
|
||||
if operation != 'stat': raise
|
||||
print(json.dumps({'exists': False}))
|
||||
sys.exit(0)
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
metadata = {'exists': True, 'isFile': stat.S_ISREG(info.st_mode), 'size': info.st_size, 'name': name}
|
||||
if operation == 'stat': print(json.dumps(metadata))
|
||||
else:
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX: raise ValueError('Upload must be a regular file no larger than 256 MiB.')
|
||||
print(json.dumps(metadata), file=sys.stderr, flush=True)
|
||||
with os.fdopen(os.dup(fd), 'rb') as source:
|
||||
remaining = info.st_size
|
||||
while remaining:
|
||||
chunk = source.read(min(65536, remaining))
|
||||
if not chunk: raise ValueError('File changed during upload.')
|
||||
sys.stdout.buffer.write(chunk)
|
||||
remaining -= len(chunk)
|
||||
finally: os.close(fd)
|
||||
else:
|
||||
# A private sibling staging entry is published only after validation.
|
||||
temporary = '.shumai-' + secrets.token_hex(16)
|
||||
try:
|
||||
if operation == 'extract':
|
||||
os.mkdir(temporary, 0o700, dir_fd=parent)
|
||||
target = os.open(temporary, FLAGS, dir_fd=parent)
|
||||
try:
|
||||
with tempfile.TemporaryFile() as archive:
|
||||
size = copy_input(archive, sys.argv[4])
|
||||
archive.seek(0)
|
||||
with zipfile.ZipFile(archive) as zip:
|
||||
entries = zip.infolist()
|
||||
if len(entries) > 10000: raise ValueError('ZIP contains too many entries.')
|
||||
if sum(entry.file_size for entry in entries) > MAX: raise ValueError('Extracted ZIP exceeds 256 MiB.')
|
||||
for entry in entries:
|
||||
mode = entry.external_attr >> 16
|
||||
kind = stat.S_IFMT(mode)
|
||||
if kind not in (0, stat.S_IFREG, stat.S_IFDIR): raise ValueError('ZIP links and special files are forbidden.')
|
||||
entry_parent, entry_name = parent_at(target, components(entry.filename.rstrip('/')), True)
|
||||
try:
|
||||
if entry.is_dir():
|
||||
try: os.mkdir(entry_name, 0o700, dir_fd=entry_parent)
|
||||
except FileExistsError: pass
|
||||
else:
|
||||
fd = os.open(entry_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600 | (mode & 0o155), dir_fd=entry_parent)
|
||||
with os.fdopen(fd, 'wb') as output, zip.open(entry) as source:
|
||||
copied = 0
|
||||
while True:
|
||||
chunk = source.read(65536)
|
||||
if not chunk: break
|
||||
copied += len(chunk)
|
||||
if copied > entry.file_size: raise ValueError('Invalid ZIP entry size.')
|
||||
output.write(chunk)
|
||||
finally: os.close(entry_parent)
|
||||
finally: os.close(target)
|
||||
commit()
|
||||
publish_directory(parent, temporary, name)
|
||||
elif operation == 'write':
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
||||
print(json.dumps({'ready': True}), file=sys.stderr, flush=True)
|
||||
with os.fdopen(fd, 'wb') as output: size = copy_input(output, sys.argv[4])
|
||||
else: raise ValueError('Unknown file operation.')
|
||||
if operation == 'write':
|
||||
commit()
|
||||
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
print(json.dumps({'size': size, 'cached': False}))
|
||||
finally: remove_at(parent, temporary)
|
||||
finally: os.close(parent)
|
||||
except FileNotFoundError:
|
||||
if operation == 'stat': print(json.dumps({'exists': False}))
|
||||
else: print('File or directory not found.', file=sys.stderr); sys.exit(1)
|
||||
except BaseException as error:
|
||||
if isinstance(error, SystemExit): raise
|
||||
print(str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
finally: os.close(root)
|
||||
`
|
||||
|
||||
export function spawnFileHelper(
|
||||
python: string,
|
||||
cwd: string,
|
||||
operation: string,
|
||||
relative: string,
|
||||
expectedHash = '',
|
||||
) {
|
||||
return spawn(python, ['-I', '-c', FILESYSTEM_HELPER, cwd, operation, relative, expectedHash], {
|
||||
env: commandEnv(),
|
||||
stdio: ['pipe', 'pipe', 'pipe', 'pipe'],
|
||||
})
|
||||
}
|
||||
@@ -23,6 +23,21 @@ describe('runner bash execution', () => {
|
||||
command,
|
||||
})
|
||||
|
||||
it('runs with no executables on PATH when SRT is not requested', async () => {
|
||||
vi.stubEnv('PATH', '')
|
||||
await shell.initialize()
|
||||
let output = ''
|
||||
const result = await shell.run(
|
||||
request('printf no-extra-runtime'),
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
output += data
|
||||
},
|
||||
)
|
||||
expect(result).toMatchObject({ exitCode: 0 })
|
||||
expect(output).toBe('no-extra-runtime')
|
||||
})
|
||||
|
||||
it('streams both outputs, returns the exit code, and saves a log in the runner workspace', async () => {
|
||||
const output: string[] = []
|
||||
const result = await shell.run(
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from 'node:path'
|
||||
import type { RunnerExecResultMessage, RunnerExecStartMessage } from '@shumai/dtos'
|
||||
import { commandEnv } from './config'
|
||||
import { RunnerFiles } from './files'
|
||||
import { findExecutable } from './filesystem'
|
||||
import { findExecutable } from './executable'
|
||||
|
||||
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
|
||||
const MAX_TIMEOUT_SEC = 3600
|
||||
@@ -21,7 +21,6 @@ export class RunnerShell {
|
||||
) {}
|
||||
|
||||
async initialize() {
|
||||
await this.files.initialize()
|
||||
if (!this.srtPath) return
|
||||
// Snapshot once: a command editing the source config cannot weaken later commands.
|
||||
this.settings = await readFile(this.srtPath, 'utf8')
|
||||
|
||||
@@ -45,11 +45,13 @@
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"ws": "8.22.2",
|
||||
"yauzl": "3.4.0",
|
||||
"zod": "4.5.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yauzl": "3.4.0",
|
||||
"adm-zip": "0.6.1",
|
||||
},
|
||||
},
|
||||
@@ -1522,7 +1524,7 @@
|
||||
|
||||
"@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
|
||||
|
||||
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.68.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.68.0", "@typescript-eslint/type-utils": "8.68.0", "@typescript-eslint/utils": "8.68.0", "@typescript-eslint/visitor-keys": "8.68.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.68.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-WASHDpCm6qO5jj9g1a+8NiW5+GCkAyLReR56/4VruYmNgfUmqpxOfZ2Yfb8xGfJPWv5Qi6LSD8sXdces3vbp/Q=="],
|
||||
|
||||
@@ -2984,7 +2986,7 @@
|
||||
|
||||
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
|
||||
|
||||
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
|
||||
|
||||
"yjs": ["yjs@13.6.32", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-lfiJIIC4Xayt5ItynE407ehlE03pCjeOc4hkR4yxxvvNJ4kuiN25B0g+Qp8XagYz361LLL7DCzR5bvFJ81QKtQ=="],
|
||||
|
||||
@@ -3216,6 +3218,10 @@
|
||||
|
||||
"eslint-plugin-react/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
|
||||
|
||||
"extract-zip/@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
|
||||
"extract-zip/yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
|
||||
"foreground-child/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"gaxios/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
|
||||
@@ -3268,8 +3274,6 @@
|
||||
|
||||
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.82", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg=="],
|
||||
@@ -3392,6 +3396,8 @@
|
||||
|
||||
"eslint-plugin-react/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
|
||||
|
||||
"extract-zip/yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"gaxios/https-proxy-agent/agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
|
||||
|
||||
"glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
|
||||
|
||||
@@ -8,7 +8,7 @@ Agents use Shumai's built-in tools without a runner. To execute Bash commands or
|
||||
## Connect a runner
|
||||
|
||||
1. In **Settings → Agent Runners**, create a runner and copy its one-time key. Only team owners can manage runners and rotate their keys.
|
||||
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on a macOS or Linux machine with `/bin/bash` and Python 3.
|
||||
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on a macOS or Linux machine with `/bin/bash`.
|
||||
3. Start it in a dedicated, existing workspace:
|
||||
|
||||
```bash
|
||||
@@ -74,6 +74,6 @@ For development, HTTP is accepted for `localhost`, `127.0.0.1`, `[::1]`, and Doc
|
||||
|
||||
## Limits and lifecycle
|
||||
|
||||
Commands default to 120 seconds and accept a maximum timeout of one hour. Timeout and cancellation terminate the process group. Each command saves up to 64 MiB of output in `.pi/logs`; manage retained logs as part of workspace maintenance. Transfers and extracted archives are limited to 256 MiB. Protocol file operations reject paths outside `.pi`, symlinks, and unsafe archive entries.
|
||||
Commands default to 120 seconds and accept a maximum timeout of one hour. Timeout and cancellation terminate the process group. Each command saves up to 64 MiB of output in `.pi/logs`; manage retained logs as part of workspace maintenance. Transfers and extracted archives are limited to 256 MiB. Protocol file operations reject paths outside `.pi`, existing symlinks, and unsafe archive entries. V1 assumes commands do not deliberately change workspace paths while transfers are running.
|
||||
|
||||
Temporary reconnects reconcile active and recently completed commands without deliberately executing them again. Restarting the runner process does not resume commands from the previous process.
|
||||
|
||||
@@ -8,7 +8,7 @@ description: 连接可选的 Bash 运行器,并在运行器机器上配置沙
|
||||
## 连接运行器
|
||||
|
||||
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
|
||||
2. 在有 `/bin/bash` 和 Python 3 的 macOS 或 Linux 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
|
||||
2. 在有 `/bin/bash` 的 macOS 或 Linux 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
|
||||
3. 在已有的专用工作目录中启动:
|
||||
|
||||
```bash
|
||||
@@ -74,6 +74,6 @@ docker run --rm --init --name shumai-runner \
|
||||
|
||||
## 限制与生命周期
|
||||
|
||||
默认超时 120 秒,最长一小时。超时或取消会终止命令进程组。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、符号链接及不安全的压缩包条目。
|
||||
默认超时 120 秒,最长一小时。超时或取消会终止命令进程组。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、已有符号链接及不安全的压缩包条目。V1 假定命令不会在文件传输期间故意修改工作区路径。
|
||||
|
||||
临时重连会同步执行中及近期完成的命令,避免主动重复执行。重启运行器进程不会恢复旧进程中的命令。
|
||||
|
||||
Reference in New Issue
Block a user