feat(runner): replace server-side bash sandbox with remote runner (#530)

* feat(runner): replace server-side bash sandbox with remote runner

* fix(runner): address review findings for output bounds, key rotation, defaults, and generated uploads

* chore(docker): remove sandbox privileges and env vars from remaining compose files

* feat(cli): add runner start with bundled SRT sandboxing (#535)

* refactor(agent): expose runner bash without skill gating

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

* refactor(cli): remove runner Python dependency

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

* refactor(cli): delegate runner processes to Execa

* chore(cli): upgrade @anthropic-ai/sandbox-runtime to 0.0.83

* feat(cli): discover Bash for Windows runners

Use Pi-style Bash discovery and launch behavior, exercise the packaged CLI shell, and wait for pending ZIP metadata reads before closing cancelled downloads.

* fix(runner): enforce ownership and safe reconnects

Gate dispatch on reconciliation, retain cancellations across disconnects, and stop replaced clients. Guard the single-server runner topology with a database lease. Restage missing generated inputs, report signal exits, and bound generated-file cleanup.

* feat(webui): add Korean translations for agent runners

* feat(cli): add runner event logging and --verbose flag (#536)

* feat(cli): add runner event logging and --verbose flag

* fix(cli): log runner capacity rejections accurately and use monotonic duration
This commit is contained in:
Yiling-J
2026-11-18 15:58:57 +08:00
committed by GitHub
parent eea844320d
commit 4ac274cdd4
121 changed files with 11600 additions and 5503 deletions
+12 -14
View File
@@ -1,12 +1,9 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { s3Service } from '@shumai/core/src/s3/s3'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateImageTool } from './generate-image'
@@ -45,13 +42,9 @@ describe('generate_image tool', () => {
google: { apiKey: 'mock-google-key' },
}
const piDir = path.join(process.cwd(), '.pi')
beforeEach(() => {
vi.restoreAllMocks()
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined)
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
})
afterEach(() => {
@@ -68,7 +61,7 @@ describe('generate_image tool', () => {
expect(modelDesc).toContain('azure:dall-e-3')
})
it('generates an image successfully and writes to .pi directory', async () => {
it('generates an image successfully and saves to temporary storage with .pi/generated path', async () => {
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
const mockBuffer = Buffer.from('fake-image-png-content')
@@ -76,7 +69,7 @@ describe('generate_image tool', () => {
buffer: mockBuffer,
mimeType: 'image/png',
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const putSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
const result = await invokeTool(
tool,
@@ -105,14 +98,19 @@ describe('generate_image tool', () => {
}),
)
const expectedPath = path.join(piDir, 'test_city.png')
expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer)
expect(putSpy).toHaveBeenCalledWith(
expect.any(String),
expect.stringMatching(/^temp\/generated\/.+\/test_city\.png$/),
mockBuffer,
mockBuffer.length,
'image/png',
)
const textContent = result.content[0]
expect(textContent.type).toBe('text')
if (textContent.type === 'text') {
expect(textContent.text).toContain('Successfully generated image')
expect(textContent.text).toContain('.pi/test_city.png')
expect(textContent.text).toMatch(/\.pi\/generated\/.+\/test_city\.png/)
}
expect(result.details).toMatchObject({
fileName: 'test_city.png',
+8 -12
View File
@@ -1,9 +1,9 @@
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { s3Service } from '@shumai/core/src/s3/s3'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -138,27 +138,23 @@ export function createGenerateImageTool(
seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined,
})
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) {
fs.mkdirSync(piDir, { recursive: true })
}
const safeMime = mimeType || 'image/png'
let ext = '.png'
if (safeMime.includes('jpeg') || safeMime.includes('jpg')) ext = '.jpg'
else if (safeMime.includes('webp')) ext = '.webp'
const genId = ulid()
let filename: string
if (p.outputFileName) {
const safe = sanitizeFilename(p.outputFileName)
filename = safe.includes('.') ? safe : `${safe}${ext}`
} else {
filename = `generated_image_${ulid()}${ext}`
filename = `generated_image_${genId}${ext}`
}
const targetPath = path.join(piDir, filename)
const relativePath = path.join('.pi', filename)
fs.writeFileSync(targetPath, buffer)
const storageKey = `temp/generated/${genId}/${filename}`
const relativePath = `.pi/generated/${genId}/${filename}`
await s3Service.putObject(storageBucket(), storageKey, buffer, buffer.length, safeMime)
return {
output: [
@@ -170,7 +166,7 @@ export function createGenerateImageTool(
details: {
fileName: filename,
filePath: relativePath,
absolutePath: targetPath,
storageKey,
size: buffer.length,
mimeType,
provider: modelConfig.provider,
+11 -13
View File
@@ -1,12 +1,9 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { s3Service } from '@shumai/core/src/s3/s3'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateVideoTool } from './generate-video'
@@ -45,13 +42,9 @@ describe('generate_video tool', () => {
google: { apiKey: 'mock-google-key' },
}
const piDir = path.join(process.cwd(), '.pi')
beforeEach(() => {
vi.restoreAllMocks()
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined)
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
})
afterEach(() => {
@@ -76,7 +69,7 @@ describe('generate_video tool', () => {
buffer: mockBuffer,
mimeType: 'video/mp4',
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const putSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
const result = await invokeTool(
tool,
@@ -115,14 +108,19 @@ describe('generate_video tool', () => {
}),
)
const expectedPath = path.join(piDir, 'test_nature.mp4')
expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer)
expect(putSpy).toHaveBeenCalledWith(
expect.any(String),
expect.stringMatching(/^temp\/generated\/.+\/test_nature\.mp4$/),
mockBuffer,
mockBuffer.length,
'video/mp4',
)
const textContent = result.content[0]
expect(textContent.type).toBe('text')
if (textContent.type === 'text') {
expect(textContent.text).toContain('Successfully generated video')
expect(textContent.text).toContain('.pi/test_nature.mp4')
expect(textContent.text).toMatch(/\.pi\/generated\/.+\/test_nature\.mp4/)
}
expect(result.details).toMatchObject({
fileName: 'test_nature.mp4',
+9 -12
View File
@@ -1,9 +1,9 @@
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { s3Service } from '@shumai/core/src/s3/s3'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -262,22 +262,19 @@ export function createGenerateVideoTool(
seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined,
})
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) {
fs.mkdirSync(piDir, { recursive: true })
}
const genId = ulid()
let filename: string
if (p.outputFileName) {
const safe = sanitizeFilename(p.outputFileName)
filename = safe.endsWith('.mp4') ? safe : `${safe}.mp4`
} else {
filename = `generated_video_${ulid()}.mp4`
filename = `generated_video_${genId}.mp4`
}
const targetPath = path.join(piDir, filename)
const relativePath = path.join('.pi', filename)
fs.writeFileSync(targetPath, buffer)
const safeMime = mimeType || 'video/mp4'
const storageKey = `temp/generated/${genId}/${filename}`
const relativePath = `.pi/generated/${genId}/${filename}`
await s3Service.putObject(storageBucket(), storageKey, buffer, buffer.length, safeMime)
return {
output: [
@@ -289,7 +286,7 @@ export function createGenerateVideoTool(
details: {
fileName: filename,
filePath: relativePath,
absolutePath: targetPath,
storageKey,
size: buffer.length,
mimeType,
provider: modelConfig.provider,
+50 -101
View File
@@ -2,21 +2,39 @@ import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('@shumai/core/src/s3/s3')
vi.mock('fs')
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createReadSkillTool } from './read-skill'
function makeSkillZipBuffer(skillMdContent: string): Buffer {
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from(skillMdContent, 'utf-8'))
return zip.toBuffer()
}
describe('readSkillTool', () => {
setupTestDbHooks()
beforeEach(() => {
beforeEach(async () => {
vi.clearAllMocks()
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
storageKey: { create: { key: 'skills/skill.zip' } },
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service.getObject return value
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# Content'),
contentType: 'application/zip',
})
})
it('should throw error if skill not found', async () => {
@@ -26,7 +44,7 @@ describe('readSkillTool', () => {
).rejects.toThrow('not found')
})
it('should read skill from cache if hash matches', async () => {
it('should read SKILL.md directly from the skill zip in storage', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
@@ -37,12 +55,10 @@ describe('readSkillTool', () => {
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'match-hash'
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
return ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# Test Skill Content'),
contentType: 'application/zip',
})
const readSkillTool = createReadSkillTool(undefined, () => {})
@@ -50,10 +66,10 @@ describe('readSkillTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
expect(s3Service.getObject).not.toHaveBeenCalled()
expect(s3Service.getObject).toHaveBeenCalled()
})
it('should download and extract skill if cache missing or hash mismatch', async () => {
it('should read nested SKILL.md inside zip archive', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
@@ -64,31 +80,8 @@ describe('readSkillTool', () => {
},
})
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
storageKey: { create: { key: 'skills/skill.zip' } },
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return false
if (path.toString().endsWith('SKILL.md')) return true
return true
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
return ''
})
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from('# Extracted Content'))
zip.addFile('nested/SKILL.md', Buffer.from('# Extracted Content'))
const zipBuffer = zip.toBuffer()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
@@ -103,7 +96,6 @@ describe('readSkillTool', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
expect(s3Service.getObject).toHaveBeenCalled()
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
})
describe('environment variables', () => {
@@ -133,14 +125,6 @@ describe('readSkillTool', () => {
delete process.env.CONFIGURED_VAR
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash1'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
@@ -168,14 +152,6 @@ describe('readSkillTool', () => {
process.env.OVERRIDDEN_VAR = 'host-val'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash2'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
@@ -203,14 +179,6 @@ describe('readSkillTool', () => {
process.env.FALLBACK_VAR = 'host-val'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash3'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
@@ -238,14 +206,6 @@ describe('readSkillTool', () => {
process.env.FALLBACK_VAR_UNDEF = 'host-val2'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash4'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
@@ -285,12 +245,10 @@ describe('readSkillTool', () => {
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash-owner'
if (path.toString().endsWith('SKILL.md')) return '# Owner Skill'
return ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# Owner Skill'),
contentType: 'application/zip',
})
const ownerTool = createReadSkillTool(ownerUser.id, () => {})
@@ -356,12 +314,10 @@ describe('readSkillTool', () => {
data: { projectId: project.id, teamMemberId: projEditorTm.id, role: 'editor' },
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'proj-editor-hash'
if (path.toString().endsWith('SKILL.md')) return '# Editor Project Skill Content'
return ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# Editor Project Skill Content'),
contentType: 'application/zip',
})
const projEditorTool = createReadSkillTool(
@@ -395,19 +351,16 @@ describe('readSkillTool', () => {
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'cb-hash'
if (path.toString().endsWith('SKILL.md')) return '# Callback Skill'
return ''
})
const onSkillLoaded = vi.fn()
const readSkillTool = createReadSkillTool(undefined, () => {}, onSkillLoaded)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(onSkillLoaded).toHaveBeenCalledTimes(1)
expect(onSkillLoaded).toHaveBeenCalledWith({
id: skill.id,
assetId: 'asset1',
hash: 'cb-hash',
})
})
it('should not invoke onSkillLoaded when loading is denied', async () => {
@@ -469,12 +422,10 @@ describe('readSkillTool', () => {
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'enabled-agent-hash'
if (path.toString().endsWith('SKILL.md')) return '# Enabled For Agent Skill'
return ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# Enabled For Agent Skill'),
contentType: 'application/zip',
})
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id])
@@ -500,12 +451,10 @@ describe('readSkillTool', () => {
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'no-filter-hash'
if (path.toString().endsWith('SKILL.md')) return '# No Filter Skill'
return ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: makeSkillZipBuffer('# No Filter Skill'),
contentType: 'application/zip',
})
const readSkillTool = createReadSkillTool(undefined, () => {})
+3 -3
View File
@@ -17,7 +17,7 @@ const ROLE_HIERARCHY: Record<string, number> = {
export const createReadSkillTool = (
userId: string | undefined,
onEnvsAdded: (envs: Record<string, string>) => void,
onSkillLoaded?: () => Promise<void> | void,
onSkillLoaded?: (skill: { id: string; assetId: string; hash: string }) => Promise<void> | void,
enabledSkillIds?: string[],
projectId?: string,
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
@@ -67,8 +67,8 @@ export const createReadSkillTool = (
// Retrieve skill content using agentService
const skillMdContent = await agentService.getSkillContent(params.skillId)
// Notify that a skill was successfully loaded (e.g. to enable restricted tools)
await onSkillLoaded?.()
// Notify that a skill was successfully loaded (e.g. to stage the skill on the runner)
await onSkillLoaded?.({ id: skill.id, assetId: skill.assetId, hash: skill.hash })
return {
output: [{ type: 'text', text: skillMdContent }],
@@ -0,0 +1,311 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { runnerService } from '@shumai/core/src/runner'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createRunnerBashTool } from './runner-bash'
vi.mock('@shumai/core/src/runner', () => ({
runnerService: {
requireOnlineRunner: vi.fn(),
isRunnerConnected: vi.fn(),
ensureSkillOnRunner: vi.fn(),
ensureGeneratedFileOnRunner: vi.fn(),
exec: vi.fn(),
},
}))
describe('createRunnerBashTool', () => {
const mockTeamId = 'team-1'
const mockRunner = {
id: 'runner-1',
teamId: mockTeamId,
name: 'Local Mac Mini',
keyPrefix: 'shm_rn_12345678',
isDefault: true,
status: 'connected' as const,
createdAt: '2026-11-14T00:00:00.000Z',
updatedAt: '2026-11-14T00:00:00.000Z',
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(runnerService.requireOnlineRunner).mockResolvedValue(mockRunner)
vi.mocked(runnerService.isRunnerConnected).mockReturnValue(true)
vi.mocked(runnerService.ensureSkillOnRunner).mockResolvedValue('.pi/skills/skill-1')
vi.mocked(runnerService.ensureGeneratedFileOnRunner).mockResolvedValue(
'.pi/generated/gen1/input.png',
)
})
const createMockSignal = () => new AbortController().signal
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('should execute a command on the runner with injected env vars', async () => {
const tool = createRunnerBashTool(
{ TEST_ENV: 'test-value' },
{
teamId: mockTeamId,
agentRunnerId: null,
},
)
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
opts.onOutput?.('hello output', 'stdout')
return {
executionId: 'exec-1',
output: 'hello output',
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
}
})
const onUpdate = createMockOnUpdate()
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'echo hello' }, signal, onUpdate)
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null)
expect(runnerService.exec).toHaveBeenCalledWith(
'runner-1',
expect.objectContaining({
command: 'echo hello',
env: { TEST_ENV: 'test-value' },
collectOutput: false,
}),
)
expect(result.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('hello output') }),
)
expect(onUpdate).toHaveBeenCalled()
})
it('should stage loaded skills and inputFiles before executing', async () => {
const loadedSkills = [{ id: 'skill-1', assetId: 'asset-1', hash: 'hash-1' }]
const tool = createRunnerBashTool(
{},
{
teamId: mockTeamId,
agentRunnerId: 'runner-pinned',
getLoadedSkills: () => loadedSkills,
},
)
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1',
output: '',
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
})
await invokeTool(
tool,
'1',
{
command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4',
inputFiles: ['.pi/generated/gen1/input.png'],
},
createMockSignal(),
)
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, 'runner-pinned')
expect(runnerService.ensureSkillOnRunner).toHaveBeenCalledWith('runner-1', loadedSkills[0])
expect(runnerService.ensureGeneratedFileOnRunner).toHaveBeenCalledWith(
'runner-1',
'.pi/generated/gen1/input.png',
)
})
it('allows editor commands without a source classification', async () => {
const tool = createRunnerBashTool(
{},
{
teamId: mockTeamId,
role: 'editor',
},
)
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
opts.onOutput?.('skill output', 'stdout')
return {
executionId: 'exec-1',
output: 'skill output',
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
}
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'echo skill' }, signal)
expect(result.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('skill output') }),
)
})
it('should handle runner execution errors', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected'))
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'fail' }, signal, createMockOnUpdate()),
).rejects.toThrow('Runner disconnected')
})
it('should handle non-zero exit codes', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1',
output: '',
exitCode: 1,
signal: null,
timedOut: false,
aborted: false,
})
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'exit 1' }, signal, createMockOnUpdate()),
).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 })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
opts.onOutput?.('output before timeout\n', 'stdout')
return {
executionId: 'exec-1',
output: 'output before timeout\n',
exitCode: null,
signal: 'SIGKILL',
timedOut: true,
aborted: false,
}
})
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'sleep 10', timeout: 2 },
signal,
createMockOnUpdate(),
)
await expect(executePromise).rejects.toThrow(/output before timeout/)
await expect(executePromise).rejects.toThrow(/timed out after 2 seconds/)
})
it('should handle abort signals', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1',
output: '',
exitCode: null,
signal: 'SIGKILL',
timedOut: false,
aborted: true,
})
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'long-run' }, signal, createMockOnUpdate()),
).rejects.toThrow(/aborted/)
})
it('should truncate output exceeding max lines (2000 lines) and report runner log file path', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const lines: string[] = []
for (let i = 1; i <= 3000; i++) {
lines.push(`line-${i}`)
}
const chunk = lines.join('\n') + '\n'
opts.onOutput?.(chunk, 'stdout')
return {
executionId: 'exec1',
output: chunk,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
fullOutputPath: '.pi/logs/bash-exec1.log',
}
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'generate lines' }, signal)
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
expect(text).toContain('line-3000')
expect(text).toContain(
'[Showing lines 1001-3000 of 3000. Full output: .pi/logs/bash-exec1.log]',
)
expect(result.details?.truncation).toMatchObject({
truncated: true,
truncatedBy: 'lines',
totalLines: 3000,
outputLines: 2000,
})
expect(result.details?.fullOutputPath).toBe('.pi/logs/bash-exec1.log')
})
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const longLine = 'a'.repeat(60000)
opts.onOutput?.(longLine, 'stdout')
return {
executionId: 'exec2',
output: longLine,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
fullOutputPath: '.pi/logs/bash-exec2.log',
}
})
const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'long single line' }, signal)
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
expect(text).toMatch(
/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output: \.pi\/logs\/bash-exec2\.log/,
)
})
})
+243
View File
@@ -0,0 +1,243 @@
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { runnerService } from '@shumai/core/src/runner'
import type { TeamMemberRole } from '@shumai/db'
import type { RunnerEnvironment } from '@shumai/dtos'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
DEFAULT_MAX_BYTES,
DEFAULT_MAX_LINES,
formatSize,
type TruncationResult,
} from '../utils/truncate'
const BashParameters = Type.Object({
command: Type.String({ description: "The command to execute using the runner's shell." }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
inputFiles: Type.Optional(
Type.Union([
Type.Array(Type.String(), {
description:
'Optional list of generated file paths (e.g. ".pi/generated/<id>/<filename>") to stage into the runner workspace before executing the command.',
}),
Type.Null(),
]),
),
})
export type BashDetails = {
exitCode: number | null
truncation?: TruncationResult
fullOutputPath?: string
}
export interface LoadedSkillRef {
id: string
assetId: string
hash: string
}
export interface RunnerBashOptions {
teamId?: string
agentRunnerId?: string | null
runnerId?: string
userId?: string
role?: TeamMemberRole | null
environment?: RunnerEnvironment
getLoadedSkills?: () => Iterable<LoadedSkillRef>
}
export const createRunnerBashTool = (
skillEnvs: Record<string, string> = {},
options?: RunnerBashOptions,
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
description: `Execute a shell command on the configured runner. ${options?.environment ? `Runner OS: ${options.environment.platform}. Shell: ${options.environment.shell}. Use syntax and programs compatible with this environment.` : 'The runner reports its OS and shell when connected.'} Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
{ command, timeout, inputFiles },
api,
context,
): Promise<AgentToolResult<BashDetails>> => {
const signal = context.abortSignal
if (options?.teamId) {
await quotaService.checkQuota(
{
teamId: options.teamId,
userId: options.userId,
role: options.role,
resource: 'agent_bash_call_count',
resourceData: { command },
},
1,
)
}
let targetRunnerId: string
if (options?.runnerId) {
if (!runnerService.isRunnerConnected(options.runnerId)) {
throw new Error(
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
)
}
targetRunnerId = options.runnerId
} else if (options?.teamId) {
const runner = await runnerService.requireOnlineRunner(
options.teamId,
options.agentRunnerId,
)
targetRunnerId = runner.id
} else {
throw new Error('No runner configured for this session.')
}
// Ensure any loaded skills in this session are extracted on the runner before executing bash
if (options?.getLoadedSkills) {
for (const skill of options.getLoadedSkills()) {
await runnerService.ensureSkillOnRunner(targetRunnerId, skill)
}
}
// Stage any explicitly requested generated files (.pi/generated/<id>/<file>) onto the runner
if (inputFiles && Array.isArray(inputFiles)) {
for (const filePath of inputFiles) {
await runnerService.ensureGeneratedFileOnRunner(targetRunnerId, filePath)
}
}
const output = new OutputAccumulator({
tempFilePrefix: 'shumai-bash',
disableTempFile: true,
})
let acceptingOutput = true
await api.details({ exitCode: null }, context)
const handleData = (data: Buffer) => {
if (!acceptingOutput) return
output.append(data)
api.output(data)
}
const finishOutput = async () => {
acceptingOutput = false
output.finish()
const snapshot = output.snapshot({ persistIfTruncated: false })
await output.closeTempFile()
return snapshot
}
const formatOutput = (
snapshot: Awaited<ReturnType<typeof finishOutput>>,
runnerLogPath: string,
emptyText = '(no output)',
) => {
const truncation = snapshot.truncation
let text = snapshot.content || emptyText
let details: BashDetails | undefined
if (truncation.truncated) {
details = { exitCode: null, truncation, fullOutputPath: runnerLogPath }
const startLine = truncation.totalLines - truncation.outputLines + 1
const endLine = truncation.totalLines
if (truncation.lastLinePartial) {
const lastLineSize = formatSize(output.getLastLineBytes())
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${runnerLogPath}]`
} else if (truncation.truncatedBy === 'lines') {
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${runnerLogPath}]`
} else {
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${runnerLogPath}]`
}
}
return { text, details }
}
const appendStatus = (text: string, status: string) => `${text ? `${text}\n\n` : ''}${status}`
const execResult = await runnerService.exec(targetRunnerId, {
command,
timeoutSec: timeout,
env: skillEnvs,
signal,
collectOutput: false,
onOutput: (chunk) => handleData(Buffer.from(chunk, 'utf-8')),
})
const snapshot = await finishOutput()
const runnerLogPath =
execResult.fullOutputPath || `.pi/logs/bash-${execResult.executionId}.log`
const { text: outputText, details: truncationDetails } = formatOutput(snapshot, runnerLogPath)
if (options?.teamId) {
try {
await quotaService.consumeQuota(
{
teamId: options.teamId,
userId: options.userId,
role: options.role,
resource: 'agent_bash_call_count',
resourceData: { command },
},
1,
)
} catch (err) {
logger.error({ err }, 'Failed to record quota usage for bash command')
}
}
if (signal?.aborted || execResult.aborted) {
logger.error({ command, outputText }, 'Bash command aborted')
throw new Error(appendStatus(outputText, 'Command aborted'))
}
if (execResult.timedOut) {
logger.error({ timeout, command, outputText }, 'Bash command timed out')
throw new Error(appendStatus(outputText, `Bash command timed out after ${timeout} seconds`))
}
if (execResult.error) {
logger.error(
{ error: execResult.error, command, outputText },
'Bash command encountered runner error',
)
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 },
'Bash command exited with failure code',
)
throw new Error(
appendStatus(outputText, `Bash command exited with code ${execResult.exitCode}`),
)
}
return {
output: [
{
type: 'text',
text: outputText,
},
],
details: {
exitCode: execResult.exitCode,
...(truncationDetails ?? {}),
},
}
},
}
}
@@ -1,376 +0,0 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { readFile } from 'node:fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
vi.mock('@anthropic-ai/sandbox-runtime')
vi.mock('node:child_process')
describe('createSandboxedBashTool', () => {
const mockCwd = '/mock/cwd'
const mockSessionManager = {
getSkillEnvs: vi.fn(),
}
beforeEach(() => {
vi.clearAllMocks()
mockSessionManager.getSkillEnvs.mockReturnValue({ TEST_ENV: 'test-value' })
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SandboxManager.wrapWithSandbox is a mocked async function from a 3rd party library
;(SandboxManager.wrapWithSandbox as any).mockImplementation(
async (cmd: string) => `sandboxed-${cmd}`,
)
})
const createMockSignal = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- signal needs to be partially compatible with AbortSignal but we need to emit events for testing
const signal = new EventEmitter() as any
signal.addEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.on(event, cb)
})
signal.removeEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.off(event, cb)
})
signal.aborted = false
return signal
}
const createMockOnUpdate = () => vi.fn()
it('should execute a command in the sandbox with injected env vars', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockStderr = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: mockStderr,
pid: 123,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const onUpdate = createMockOnUpdate()
const signal = createMockSignal()
// pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?)
const executePromise = invokeTool(
tool,
'1',
{ command: 'echo hello', source: 'user' },
signal,
onUpdate,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
'echo hello',
undefined,
undefined,
undefined,
{ commandId: '1' },
)
expect(spawn).toHaveBeenCalledWith(
'bash',
['-c', 'sandboxed-echo hello'],
expect.objectContaining({
env: expect.objectContaining({
TEST_ENV: 'test-value',
}),
}),
)
// Simulate stdout data
mockStdout.emit('data', Buffer.from('hello output'))
mockChild.emit('close', 0)
const result = await executePromise
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
expect((result as any).content[0].text).toContain('hello output')
})
it('should block user-requested commands when restrictedUser is enabled', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true })
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/not permitted for your role/)
expect(spawn).not.toHaveBeenCalled()
expect(SandboxManager.wrapWithSandbox).not.toHaveBeenCalled()
})
it('should allow skill-requested commands when restrictedUser is enabled', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true })
const mockStdout = new EventEmitter()
const mockStderr = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: mockStderr,
pid: 124,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
'echo skill',
undefined,
undefined,
undefined,
{ commandId: '1' },
)
mockStdout.emit('data', Buffer.from('skill output'))
mockChild.emit('close', 0)
const result = await executePromise
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
expect((result as any).content[0].text).toContain('skill output')
})
it('should handle process errors', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = new EventEmitter()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'fail', source: 'user' },
signal,
createMockOnUpdate(),
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
mockChild.emit('error', new Error('spawn failed'))
await expect(executePromise).rejects.toThrow('spawn failed')
})
it('should handle non-zero exit codes', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 1,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'exit 1', source: 'user' },
signal,
createMockOnUpdate(),
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
mockChild.emit('close', 1)
await expect(executePromise).rejects.toThrow(/exited with code 1/)
})
it('should handle timeouts', async () => {
vi.useFakeTimers()
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 456,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'sleep 10', timeout: 2, source: 'user' },
signal,
createMockOnUpdate(),
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
await vi.advanceTimersByTimeAsync(2100)
expect(killSpy).toHaveBeenCalledWith(-456, 'SIGKILL')
mockChild.emit('close', null)
await expect(executePromise).rejects.toThrow(/timed out/)
vi.useRealTimers()
killSpy.mockRestore()
})
it('should handle abort signals', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 789,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'long-run', source: 'user' },
signal,
createMockOnUpdate(),
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
signal.aborted = true
signal.emit('abort')
expect(killSpy).toHaveBeenCalledWith(-789, 'SIGKILL')
mockChild.emit('close', null)
await expect(executePromise).rejects.toThrow(/aborted/)
killSpy.mockRestore()
})
it('should truncate output exceeding max lines (2000 lines) and persist full output to temp file', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockStderr = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: mockStderr,
pid: 101,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'generate lines', source: 'user' },
signal,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
const lines: string[] = []
for (let i = 1; i <= 3000; i++) {
lines.push(`line-${i}`)
}
mockStdout.emit('data', Buffer.from(lines.join('\n') + '\n'))
mockChild.emit('close', 0)
const result = await executePromise
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
const text = (result as any).content[0].text
expect(text).toContain('line-3000')
expect(text).toContain('[Showing lines 1001-3000 of 3000. Full output:')
expect(result.details?.truncation).toMatchObject({
truncated: true,
truncatedBy: 'lines',
totalLines: 3000,
outputLines: 2000,
})
expect(result.details?.fullOutputPath).toBeDefined()
const fileContent = await readFile(result.details!.fullOutputPath!, 'utf-8')
expect(fileContent).toContain('line-1\nline-2')
expect(fileContent).toContain('line-2999\nline-3000')
})
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: new EventEmitter(),
pid: 102,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'long single line', source: 'user' },
signal,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
const longLine = 'a'.repeat(60000)
mockStdout.emit('data', Buffer.from(longLine))
mockChild.emit('close', 0)
const result = await executePromise
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
const text = (result as any).content[0].text
expect(text).toMatch(/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output:/)
})
it('should preserve truncated output when a command times out', async () => {
vi.useFakeTimers()
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: new EventEmitter(),
pid: 103,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type boolean
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = invokeTool(
tool,
'1',
{ command: 'slow', timeout: 1, source: 'user' },
signal,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
mockStdout.emit('data', Buffer.from('output before timeout\n'))
await vi.advanceTimersByTimeAsync(1100)
mockChild.emit('close', null)
await expect(executePromise).rejects.toThrow(/output before timeout/)
await expect(executePromise).rejects.toThrow(/timed out after 1 seconds/)
vi.useRealTimers()
killSpy.mockRestore()
})
})
-260
View File
@@ -1,260 +0,0 @@
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import type { TeamMemberRole } from '@shumai/db'
import { spawn } from 'node:child_process'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
DEFAULT_MAX_BYTES,
DEFAULT_MAX_LINES,
formatSize,
type TruncationResult,
} from '../utils/truncate'
const BashSource = Type.String({
enum: ['user', 'skill'],
description:
'Indicates who requested this bash command. Set to "user" when the end user directly ' +
'requested the command. Set to "skill" when the command is required by a skill you loaded ' +
'via the read_skill tool. Users without the owner role can only execute commands with ' +
'source="skill"; source="user" will be blocked.',
})
const BashParameters = Type.Object({
command: Type.String({ description: 'The bash command to execute.' }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
source: BashSource,
})
export type BashDetails = {
exitCode: number | null
truncation?: TruncationResult
fullOutputPath?: string
}
export interface SandboxedBashOptions {
teamId?: string
userId?: string
role?: TeamMemberRole | null
getBlockedHost?: (commandId?: string) => string
clearBlockedHost?: () => void
/**
* When true, the tool only allows commands requested by a loaded skill (source="skill").
* Commands requested directly by the end user (source="user") are blocked.
*/
restrictedUser?: boolean
}
export const createSandboxedBashTool = (
cwd: string,
skillEnvs: Record<string, string> = {},
options?: SandboxedBashOptions,
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`,
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
{ command, timeout, source },
api,
context,
): Promise<AgentToolResult<BashDetails>> => {
const toolCallId = api.callId
const signal = context.abortSignal
if (options?.restrictedUser && source !== 'skill') {
throw new Error(
'Bash commands requested directly by the user (source="user") are not permitted for your role. ' +
'Only commands required by a loaded skill (source="skill") can be executed.',
)
}
if (options?.teamId) {
await quotaService.checkQuota(
{
teamId: options.teamId,
userId: options.userId,
role: options.role,
resource: 'agent_bash_call_count',
resourceData: { command },
},
1,
)
}
options?.clearBlockedHost?.()
const wrappedCommand = await sandboxService.wrapCommand(command, { commandId: toolCallId })
const output = new OutputAccumulator({ tempFilePrefix: 'shumai-bash' })
let acceptingOutput = true
await api.details({ exitCode: null }, context)
const handleData = (data: Buffer) => {
if (!acceptingOutput) return
output.append(data)
api.output(data)
}
const finishOutput = async () => {
acceptingOutput = false
output.finish()
const snapshot = output.snapshot({ persistIfTruncated: true })
await output.closeTempFile()
return snapshot
}
const formatOutput = (
snapshot: Awaited<ReturnType<typeof finishOutput>>,
emptyText = '(no output)',
) => {
const truncation = snapshot.truncation
let text = snapshot.content || emptyText
let details: BashDetails | undefined
if (truncation.truncated) {
details = { exitCode: null, truncation, fullOutputPath: snapshot.fullOutputPath }
const startLine = truncation.totalLines - truncation.outputLines + 1
const endLine = truncation.totalLines
if (truncation.lastLinePartial) {
const lastLineSize = formatSize(output.getLastLineBytes())
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`
} else if (truncation.truncatedBy === 'lines') {
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`
} else {
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`
}
}
return { text, details }
}
const appendStatus = (text: string, status: string) => `${text ? `${text}\n\n` : ''}${status}`
return new Promise((resolve, reject) => {
const child = spawn('bash', ['-c', wrappedCommand], {
cwd,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
PATH: process.env.PATH || '',
HOME: process.env.HOME || '',
...skillEnvs,
},
})
let timedOut = false
let timeoutHandle: NodeJS.Timeout | undefined
if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => {
timedOut = true
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL')
} catch {
child.kill('SIGKILL')
}
}
}, timeout * 1000)
}
child.stdout?.on('data', handleData)
child.stderr?.on('data', handleData)
const onAbort = () => {
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL')
} catch {
child.kill('SIGKILL')
}
}
}
signal?.addEventListener('abort', onAbort, { once: true })
child.on('error', async (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle)
signal?.removeEventListener('abort', onAbort)
const snapshot = await finishOutput()
logger.error(
{ err, command, content: snapshot.content },
'Sandboxed bash command encountered process error',
)
reject(err)
})
child.on('close', async (code) => {
if (timeoutHandle) clearTimeout(timeoutHandle)
signal?.removeEventListener('abort', onAbort)
const blocked = options?.getBlockedHost?.(toolCallId)
const snapshot = await finishOutput()
const { text: outputText, details: truncationDetails } = formatOutput(snapshot)
if (options?.teamId) {
try {
await quotaService.consumeQuota(
{
teamId: options.teamId,
userId: options.userId,
role: options.role,
resource: 'agent_bash_call_count',
resourceData: { command },
},
1,
)
} catch (err) {
logger.error({ err }, 'Failed to record quota usage for bash command')
}
}
if (signal?.aborted) {
logger.error({ command, outputText }, 'Sandboxed bash command aborted')
reject(new Error(appendStatus(outputText, 'Command aborted')))
} else if (timedOut) {
logger.error({ timeout, command, outputText }, 'Sandboxed bash command timed out')
reject(
new Error(
appendStatus(
outputText,
`Sandboxed bash command timed out after ${timeout} seconds`,
),
),
)
} else if (blocked) {
reject(
new Error(
`Network request to ${blocked} is blocked, please ask admin to allow it in sandbox settings.`,
),
)
} else if (code !== 0 && code !== null) {
logger.error(
{ exitCode: code, command, outputText },
'Sandboxed bash command exited with failure code',
)
reject(
new Error(
appendStatus(outputText, `Sandboxed bash command exited with code ${code}`),
),
)
} else {
resolve({
output: [
{
type: 'text',
text: outputText,
},
],
details: {
exitCode: code,
...(truncationDetails ?? {}),
},
})
}
})
})
},
}
}