mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 12:54:55 +00:00
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:
@@ -66,7 +66,7 @@ export interface AgentExecutionContext {
|
||||
teamSkills: Skill[]
|
||||
mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[]
|
||||
enabledSkillIds: string[]
|
||||
allowedDomains: string[]
|
||||
allowedDomains?: string[]
|
||||
}
|
||||
|
||||
export function formatProjectContextPrompt(
|
||||
@@ -97,7 +97,7 @@ async function executeAgentPrompt(params: {
|
||||
context: AgentExecutionContext
|
||||
attachedAssets?: Array<{ id: string; name: string; type: string }>
|
||||
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const { agent, dbProviders, teamSkills, enabledSkillIds, allowedDomains } = params.context
|
||||
const { agent, dbProviders, teamSkills, enabledSkillIds } = params.context
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -242,7 +242,6 @@ User messages may contain a <context> block detailing the user, active asset loc
|
||||
description: s.description,
|
||||
})),
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId: persistedSessionId,
|
||||
userId: params.userId,
|
||||
projectId: params.projectId,
|
||||
@@ -793,18 +792,12 @@ export const getAgentChatContextActivity = defineStep(
|
||||
})
|
||||
const mcpServers = assignments.map((a) => a.mcpServer)
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills: permittedSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -882,18 +875,12 @@ export const getAgentAutofillContextActivity = defineStep(
|
||||
// Autofill agents currently do not use MCP tools.
|
||||
const mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[] = []
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills: enabledSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { hashRunnerKey, runnerService, type RunnerSocket } from '@shumai/core/src/runner'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createAgentSession, type DbProviderInfo } from './index'
|
||||
import { closeAgentSessions } from './runtime'
|
||||
import { createRunnerBashTool } from './tools/runner-bash'
|
||||
|
||||
const mockProviders: DbProviderInfo[] = [
|
||||
{
|
||||
name: 'google',
|
||||
config: { api: 'google-generative-ai', apiKey: 'GOOGLE_API_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
config: {
|
||||
api: 'google-generative-ai',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 4096,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function createMockWs() {
|
||||
const sent: string[] = []
|
||||
const ws: RunnerSocket = {
|
||||
send: vi.fn((data: string) => {
|
||||
sent.push(data)
|
||||
}),
|
||||
close: vi.fn(),
|
||||
}
|
||||
return {
|
||||
ws,
|
||||
sent,
|
||||
lastSentJson: () => (sent.length > 0 ? JSON.parse(sent[sent.length - 1]) : null),
|
||||
}
|
||||
}
|
||||
|
||||
function reconcile(runnerId: string, ws: RunnerSocket) {
|
||||
runnerService.handleMessage(
|
||||
runnerId,
|
||||
ws,
|
||||
JSON.stringify({
|
||||
type: 'reconcile',
|
||||
environment: { platform: 'linux', shell: '/bin/sh' },
|
||||
activeExecutions: [],
|
||||
completedExecutions: [],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
describe('Concurrent Runner Sessions', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await closeAgentSessions()
|
||||
})
|
||||
|
||||
it('executes concurrent bash commands on the same runner with isolated executionIds', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Concurrent Runner Team' },
|
||||
})
|
||||
const { runner, key } = await runnerService.createRunner(team.id, { name: 'Shared Runner' })
|
||||
const conn = createMockWs()
|
||||
await runnerService.registerConnection(
|
||||
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
|
||||
conn.ws,
|
||||
)
|
||||
reconcile(runner.id, conn.ws)
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
name: 'Agent User',
|
||||
email: 'agent-user@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session A prompt',
|
||||
teamSkills: [],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
const tool = createRunnerBashTool({}, { teamId: team.id })
|
||||
|
||||
// Note: registerConnection sends a 'welcome' message first (conn.sent[0])
|
||||
const execA = invokeTool(tool, 'call-a', {
|
||||
command: 'echo session-a',
|
||||
})
|
||||
await vi.waitFor(() => expect(conn.sent.length).toBe(2))
|
||||
const msgA = JSON.parse(conn.sent[1])
|
||||
|
||||
const execB = invokeTool(tool, 'call-b', {
|
||||
command: 'echo session-b',
|
||||
})
|
||||
await vi.waitFor(() => expect(conn.sent.length).toBe(3))
|
||||
const msgB = JSON.parse(conn.sent[2])
|
||||
|
||||
expect(msgA.executionId).not.toBe(msgB.executionId)
|
||||
|
||||
// Interleave output and completion for A and B
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.output',
|
||||
executionId: msgB.executionId,
|
||||
stream: 'stdout',
|
||||
offset: 0,
|
||||
data: 'out-b',
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.output',
|
||||
executionId: msgA.executionId,
|
||||
stream: 'stdout',
|
||||
offset: 0,
|
||||
data: 'out-a',
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: msgA.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: msgB.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
|
||||
const [resA, resB] = await Promise.all([execA, execB])
|
||||
expect(resA.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('out-a') }),
|
||||
)
|
||||
expect(resB.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('out-b') }),
|
||||
)
|
||||
|
||||
runnerService.handleDisconnect(runner.id, conn.ws)
|
||||
})
|
||||
|
||||
it('routes agent commands to their bound runner or team default runner independently', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Multi Runner Team' },
|
||||
})
|
||||
const { runner: defaultRunner, key: defaultKey } = await runnerService.createRunner(team.id, {
|
||||
name: 'Default Runner',
|
||||
isDefault: true,
|
||||
})
|
||||
const { runner: gpuRunner, key: gpuKey } = await runnerService.createRunner(team.id, {
|
||||
name: 'GPU Runner',
|
||||
isDefault: false,
|
||||
})
|
||||
|
||||
const defaultConn = createMockWs()
|
||||
const gpuConn = createMockWs()
|
||||
await runnerService.registerConnection(
|
||||
{
|
||||
id: defaultRunner.id,
|
||||
teamId: team.id,
|
||||
name: defaultRunner.name,
|
||||
keyHash: hashRunnerKey(defaultKey),
|
||||
},
|
||||
defaultConn.ws,
|
||||
)
|
||||
await runnerService.registerConnection(
|
||||
{
|
||||
id: gpuRunner.id,
|
||||
teamId: team.id,
|
||||
name: gpuRunner.name,
|
||||
keyHash: hashRunnerKey(gpuKey),
|
||||
},
|
||||
gpuConn.ws,
|
||||
)
|
||||
reconcile(defaultRunner.id, defaultConn.ws)
|
||||
reconcile(gpuRunner.id, gpuConn.ws)
|
||||
|
||||
const defaultTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
agentRunnerId: null,
|
||||
},
|
||||
)
|
||||
const gpuTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
agentRunnerId: gpuRunner.id,
|
||||
},
|
||||
)
|
||||
|
||||
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a' })
|
||||
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi' })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(defaultConn.lastSentJson()?.type).toBe('exec.start')
|
||||
expect(gpuConn.lastSentJson()?.type).toBe('exec.start')
|
||||
})
|
||||
|
||||
const defaultMsg = defaultConn.lastSentJson()
|
||||
const gpuMsg = gpuConn.lastSentJson()
|
||||
expect(defaultMsg.command).toBe('uname -a')
|
||||
expect(gpuMsg.command).toBe('nvidia-smi')
|
||||
|
||||
runnerService.handleMessage(
|
||||
defaultRunner.id,
|
||||
defaultConn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: defaultMsg.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
gpuRunner.id,
|
||||
gpuConn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: gpuMsg.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
|
||||
await Promise.all([pDefault, pGpu])
|
||||
runnerService.handleDisconnect(defaultRunner.id, defaultConn.ws)
|
||||
runnerService.handleDisconnect(gpuRunner.id, gpuConn.ws)
|
||||
})
|
||||
})
|
||||
@@ -1,328 +0,0 @@
|
||||
import type { SandboxConfig, SandboxProvider, WrapCommandOptions } from '@shumai/core'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createAgentSession, type DbProviderInfo } from './index'
|
||||
import { closeAgentSessions } from './runtime'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
|
||||
vi.mock('node:child_process')
|
||||
|
||||
class TestSandboxProvider implements SandboxProvider {
|
||||
initialized = false
|
||||
config: SandboxConfig | null = null
|
||||
initializeCalls = 0
|
||||
updateConfigCalls = 0
|
||||
resetCalls = 0
|
||||
wrapCommandCalls: Array<{ command: string; options?: WrapCommandOptions }> = []
|
||||
violationsByCommandId = new Map<string, string>()
|
||||
|
||||
async initialize(config: SandboxConfig): Promise<void> {
|
||||
this.initialized = true
|
||||
this.config = config
|
||||
this.initializeCalls++
|
||||
}
|
||||
|
||||
async wrapCommand(command: string, options?: WrapCommandOptions): Promise<string> {
|
||||
this.wrapCommandCalls.push({ command, options })
|
||||
return `sandboxed-${command}`
|
||||
}
|
||||
|
||||
async updateConfig(config: Partial<SandboxConfig>): Promise<void> {
|
||||
this.updateConfigCalls++
|
||||
if (this.config && config.network) {
|
||||
this.config.network = { ...this.config.network, ...config.network }
|
||||
}
|
||||
}
|
||||
|
||||
async reset(): Promise<void> {
|
||||
this.resetCalls++
|
||||
this.initialized = false
|
||||
this.config = null
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.initialized
|
||||
}
|
||||
|
||||
getBlockedHostForCommand(commandId: string): string | null {
|
||||
return this.violationsByCommandId.get(commandId) ?? null
|
||||
}
|
||||
}
|
||||
|
||||
const mockProviders: DbProviderInfo[] = [
|
||||
{
|
||||
name: 'google',
|
||||
config: { api: 'google-generative-ai', apiKey: 'GOOGLE_API_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
config: {
|
||||
api: 'google-generative-ai',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 4096,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
describe('Concurrent Sandbox Sessions', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let testProvider: TestSandboxProvider
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
testProvider = new TestSandboxProvider()
|
||||
sandboxService.setProvider(testProvider)
|
||||
})
|
||||
|
||||
it('does not reset sandbox when new sessions start while a command is running', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Concurrent Test Team' },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['api.github.com'],
|
||||
},
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
name: 'Agent User',
|
||||
email: 'agent-user@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
// 1. Session A starts and syncs domains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session A prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['api.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(testProvider.initializeCalls).toBe(1)
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
|
||||
// 2. Session A runs a bash command that takes time
|
||||
const tool = createSandboxedBashTool('/mock/cwd')
|
||||
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockStderr = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
pid: 999,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock spawn return value
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const sessionExecutionA = invokeTool(tool, 'call-session-a-1', {
|
||||
command: 'curl https://api.github.com/repos',
|
||||
source: 'skill',
|
||||
})
|
||||
|
||||
// 3. Concurrently, Session B starts with additional allowed domains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session B prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['api.github.com', 'pypi.org'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
// Assert sandbox was hot-reloaded without any reset!
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
expect(testProvider.updateConfigCalls).toBe(1)
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['api.github.com', 'pypi.org'])
|
||||
|
||||
// 4. Concurrently, Session C starts with the same domains (should be no-op, no reset, no updateConfig)
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session C prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['pypi.org', 'api.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
expect(testProvider.updateConfigCalls).toBe(1) // Still 1, no duplicate update
|
||||
|
||||
// 5. Session A's command completes successfully
|
||||
mockStdout.emit('data', Buffer.from('{"status":"ok"}'))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await sessionExecutionA
|
||||
expect(result.details).toEqual(
|
||||
expect.objectContaining({
|
||||
exitCode: 0,
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify command was wrapped with options containing commandId: 'call-session-a-1'
|
||||
expect(testProvider.wrapCommandCalls).toContainEqual({
|
||||
command: 'curl https://api.github.com/repos',
|
||||
options: { commandId: 'call-session-a-1' },
|
||||
})
|
||||
})
|
||||
|
||||
it('isolates blocked host violations per commandId during concurrent execution', async () => {
|
||||
await sandboxService.ensureInitialized({ allowedDomains: ['api.github.com'] })
|
||||
|
||||
// Command 1 and Command 2 run concurrently
|
||||
await sandboxService.wrapCommand('curl http://blocked1.com', { commandId: 'cmd-1' })
|
||||
await sandboxService.wrapCommand('curl http://blocked2.com', { commandId: 'cmd-2' })
|
||||
|
||||
testProvider.violationsByCommandId.set('cmd-1', 'blocked1.com')
|
||||
testProvider.violationsByCommandId.set('cmd-2', 'blocked2.com')
|
||||
|
||||
// Blocked hosts should be accurately isolated
|
||||
expect(sandboxService.getBlockedHost('cmd-1')).toBe('blocked1.com')
|
||||
expect(sandboxService.getBlockedHost('cmd-2')).toBe('blocked2.com')
|
||||
expect(sandboxService.getBlockedHost('cmd-unknown')).toBe('')
|
||||
})
|
||||
|
||||
it('does not reject concurrent allowed command when another command is blocked', async () => {
|
||||
await sandboxService.ensureInitialized({ allowedDomains: ['api.github.com'] })
|
||||
|
||||
const tool = createSandboxedBashTool('/mock/cwd', undefined, {
|
||||
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
|
||||
clearBlockedHost: () => sandboxService.clearBlockedHost(),
|
||||
})
|
||||
|
||||
const childBlocked = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 101,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
const childAllowed = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 102,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
|
||||
let spawnIndex = 0
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock spawn implementation
|
||||
;(spawn as any).mockImplementation(() => {
|
||||
spawnIndex++
|
||||
return spawnIndex === 1 ? childBlocked : childAllowed
|
||||
})
|
||||
|
||||
// Record violation for the blocked command only
|
||||
testProvider.violationsByCommandId.set('call-blocked', 'blocked-target.com')
|
||||
|
||||
const blockedExecution = invokeTool(tool, 'call-blocked', {
|
||||
command: 'curl http://blocked-target.com',
|
||||
source: 'skill',
|
||||
})
|
||||
const allowedExecution = invokeTool(tool, 'call-allowed', {
|
||||
command: 'curl https://api.github.com/data',
|
||||
source: 'skill',
|
||||
})
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalledTimes(2))
|
||||
|
||||
childBlocked.stdout.emit('data', Buffer.from('blocked output'))
|
||||
childBlocked.emit('close', 0)
|
||||
|
||||
childAllowed.stdout.emit('data', Buffer.from('allowed output'))
|
||||
childAllowed.emit('close', 0)
|
||||
|
||||
await expect(blockedExecution).rejects.toThrow(
|
||||
'Network request to blocked-target.com is blocked',
|
||||
)
|
||||
const allowedResult = await allowedExecution
|
||||
expect(allowedResult.details).toEqual(expect.objectContaining({ exitCode: 0 }))
|
||||
})
|
||||
|
||||
it('does not synchronize or overwrite sandbox allowlist when allowedDomains is omitted (e.g. naming sessions)', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Omitted Domains Team' },
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-omitted',
|
||||
name: 'Agent User',
|
||||
email: 'agent-omitted@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-omitted',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
// 1. First session sets allowedDomains to ['*.github.com']
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-omitted',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Main prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['*.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['*.github.com'])
|
||||
const updateCallsBefore = testProvider.updateConfigCalls
|
||||
|
||||
// 2. Utility / naming session runs WITHOUT allowedDomains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-omitted',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Title generator',
|
||||
teamSkills: [],
|
||||
// allowedDomains omitted
|
||||
disableTools: true,
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
// Assert sandbox was NOT touched or overwritten
|
||||
expect(testProvider.updateConfigCalls).toBe(updateCallsBefore)
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['*.github.com'])
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(closeAgentSessions)
|
||||
+245
-883
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,11 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma, type Asset, type StorageKey } from '@shumai/db'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { toAgentTool } from '../operation-tools'
|
||||
import './download-asset'
|
||||
|
||||
@@ -32,18 +32,28 @@ vi.mock('@shumai/core/src/s3/s3', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
requireOnlineRunner: vi.fn(),
|
||||
isRunnerConnected: vi.fn(),
|
||||
downloadToRunner: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/authz/authz')>()
|
||||
return { ...actual, authzService: { hasPermission: vi.fn() } }
|
||||
})
|
||||
|
||||
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
|
||||
type Saved = { filePath: string; absolutePath: string; contentType: string; size: number }
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
type Saved = { filePath: string; contentType: string; size: number }
|
||||
|
||||
function downloadTool(userId = 'user-1') {
|
||||
return toAgentTool(getOperation('download_asset')!, { userId })
|
||||
return toAgentTool(getOperation('download_asset')!, {
|
||||
userId,
|
||||
teamId: 'team-1',
|
||||
runnerId: null,
|
||||
})
|
||||
}
|
||||
|
||||
function textOf(result: { content: unknown[] }): string {
|
||||
@@ -57,10 +67,14 @@ function mockAssets(...assets: Array<Record<string, unknown>>) {
|
||||
)
|
||||
}
|
||||
|
||||
function mockStorage(contentType: string, write = 'bytes') {
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({ size: 1234, contentType } as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, dest) => {
|
||||
await fs.promises.writeFile(dest, write)
|
||||
function mockStorage(contentType: string, size = 11) {
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({ size, contentType } as Head)
|
||||
vi.mocked(runnerService.downloadToRunner).mockResolvedValue({
|
||||
type: 'file.download.result',
|
||||
executionId: 'exec-dl-1',
|
||||
ok: true,
|
||||
size,
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -74,15 +88,19 @@ const photo = {
|
||||
}
|
||||
|
||||
describe('download_asset agent tool', () => {
|
||||
const created: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const file of created.splice(0)) fs.rmSync(file, { force: true })
|
||||
vi.mocked(runnerService.requireOnlineRunner).mockResolvedValue({
|
||||
id: 'runner-1',
|
||||
teamId: 'team-1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected',
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
})
|
||||
})
|
||||
|
||||
it('offers assetIds, proxy, and the agent-only key parameter', () => {
|
||||
@@ -93,35 +111,32 @@ describe('download_asset agent tool', () => {
|
||||
expect(tool.description).toContain('.pi directory')
|
||||
})
|
||||
|
||||
it('saves the web preview into .pi by default, named after the asset', async () => {
|
||||
it('saves the web preview into .pi on the runner by default, named after the asset', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/webp', 'proxy-bytes')
|
||||
mockStorage('image/webp', 11)
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'] })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
|
||||
created.push(expectedPath)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'img-1',
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/img-1/proxy.webp',
|
||||
expectedPath,
|
||||
)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('proxy-bytes')
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith('team-1', null)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'img-1_sample_photo.webp'),
|
||||
})
|
||||
expect(textOf(result)).toBe(
|
||||
[
|
||||
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.join('.pi', 'img-1_sample_photo.webp')}".`,
|
||||
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.posix.join('.pi', 'img-1_sample_photo.webp')}".`,
|
||||
'Remember to delete these temporary files when finished.',
|
||||
].join('\n'),
|
||||
)
|
||||
const details = result.details as { files: Saved[] }
|
||||
expect(details.files[0]).toMatchObject({
|
||||
filePath: path.join('.pi', 'img-1_sample_photo.webp'),
|
||||
filePath: path.posix.join('.pi', 'img-1_sample_photo.webp'),
|
||||
contentType: 'image/webp',
|
||||
size: 11,
|
||||
})
|
||||
@@ -129,17 +144,23 @@ describe('download_asset agent tool', () => {
|
||||
|
||||
it('saves the original with proxy false', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/jpeg')
|
||||
mockStorage('image/jpeg', 1234)
|
||||
|
||||
await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'], proxy: false })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
|
||||
created.push(expectedPath)
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/up-1/sample_photo.jpg',
|
||||
expectedPath,
|
||||
'GET',
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
600,
|
||||
)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'img-1_sample_photo.jpg'),
|
||||
})
|
||||
})
|
||||
|
||||
it('downloads several files and the latest version of a version stack', async () => {
|
||||
@@ -159,16 +180,12 @@ describe('download_asset agent tool', () => {
|
||||
key: null,
|
||||
})
|
||||
|
||||
created.push(
|
||||
path.join(piDir, 'img-1_sample_photo.webp'),
|
||||
path.join(piDir, 'file-v2_banana_pig.webp'),
|
||||
)
|
||||
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
|
||||
where: { parentId: 'stack-1', isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledTimes(2)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledTimes(2)
|
||||
expect(textOf(result)).toContain('Downloaded "banana_pig.webp" (ID: file-v2, proxy')
|
||||
})
|
||||
|
||||
@@ -177,7 +194,7 @@ describe('download_asset agent tool', () => {
|
||||
await expect(invokeTool(downloadTool(), 'call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
|
||||
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
|
||||
)
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks Read on every asset before downloading anything', async () => {
|
||||
@@ -188,7 +205,7 @@ describe('download_asset agent tool', () => {
|
||||
await expect(
|
||||
invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1', 'secret'] }),
|
||||
).rejects.toThrow('Forbidden')
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires assetIds or key', async () => {
|
||||
@@ -240,27 +257,28 @@ describe('download_asset agent tool', () => {
|
||||
type: 'asset',
|
||||
id: 'other-project-asset',
|
||||
})
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('downloads a read_asset artifact into .pi', async () => {
|
||||
it('downloads a read_asset artifact into .pi on the runner', async () => {
|
||||
mockAssets({ id: 'ast-123' })
|
||||
mockStorage('image/webp', 'frame-bytes')
|
||||
mockStorage('image/webp', 11)
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', {
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
|
||||
created.push(expectedPath)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('frame-bytes')
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'shot_5.0s.webp'),
|
||||
})
|
||||
expect(textOf(result)).toBe(
|
||||
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
|
||||
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.posix.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
|
||||
)
|
||||
expect(result.details).toMatchObject({
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
assetId: 'ast-123',
|
||||
size: Buffer.from('frame-bytes').length,
|
||||
size: 11,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -271,24 +289,25 @@ describe('download_asset agent tool', () => {
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
assets: [{ id: 'asset-photo-1' }],
|
||||
} as unknown as StorageKey & { assets: Asset[] })
|
||||
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
size: 8,
|
||||
contentType: 'application/octet-stream',
|
||||
} as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, pngHeader)
|
||||
vi.mocked(runnerService.downloadToRunner).mockResolvedValue({
|
||||
type: 'file.download.result',
|
||||
executionId: 'exec-dl-2',
|
||||
ok: true,
|
||||
size: 8,
|
||||
mimeType: 'image/png',
|
||||
})
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', {
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
})
|
||||
|
||||
created.push(path.join(piDir, 'photo.png'))
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'asset-photo-1' }),
|
||||
)
|
||||
// Falls back to detecting the type from the bytes
|
||||
expect(result.details).toMatchObject({ assetId: 'asset-photo-1', contentType: 'image/png' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,52 +2,66 @@ import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import type { User } from '@shumai/db'
|
||||
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
|
||||
import {
|
||||
registerAgentToolExtension,
|
||||
type AgentOperationContext,
|
||||
type AgentToolExtension,
|
||||
} from '../operation-tools'
|
||||
import { resolveAssetIdFromKey } from '../tools/download-asset'
|
||||
|
||||
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
|
||||
|
||||
/** The agent's sandbox, where downloaded files are saved for local scripts and bash. */
|
||||
function sandboxDir(): string {
|
||||
const dir = path.join(process.cwd(), '.pi')
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
return dir
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
/** Saves a storage object into the sandbox; returns the paths and detected content type. */
|
||||
async function saveToSandbox(key: string, filename: string) {
|
||||
const dir = sandboxDir()
|
||||
const absolutePath = path.join(dir, filename)
|
||||
async function resolveTargetRunnerId(ctx: AgentOperationContext): Promise<string> {
|
||||
if (ctx.runnerId && !ctx.teamId) {
|
||||
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
throw new Error(
|
||||
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
|
||||
)
|
||||
}
|
||||
return ctx.runnerId
|
||||
}
|
||||
const runner = await runnerService.requireOnlineRunner(ctx.teamId || '', ctx.runnerId)
|
||||
return runner.id
|
||||
}
|
||||
|
||||
/** Saves a storage object into the runner's .pi directory; returns the path, size, and content type. */
|
||||
async function saveToRunner(key: string, filename: string, ctx: AgentOperationContext) {
|
||||
const runnerId = await resolveTargetRunnerId(ctx)
|
||||
const bucket = storageBucket()
|
||||
const info = await s3Service.headObject(bucket, key).catch(() => null)
|
||||
await s3Service.downloadToFile(bucket, key, absolutePath)
|
||||
const size = await fs.promises
|
||||
.stat(absolutePath)
|
||||
.then((s) => s.size)
|
||||
.catch(() => info?.size ?? 0)
|
||||
const url = await s3Service.presign(bucket, key, 'GET', false, undefined, false, 600)
|
||||
const filePath = path.posix.join('.pi', filename)
|
||||
const res = await runnerService.downloadToRunner(runnerId, { url, destPath: filePath })
|
||||
if (!res.ok) {
|
||||
throw new Error(res.error || `Failed to download "${filename}" to runner`)
|
||||
}
|
||||
const size = res.size ?? info?.size ?? 0
|
||||
const contentType =
|
||||
info?.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: readFileMimeType(absolutePath)
|
||||
return { absolutePath, filePath: path.join('.pi', filename), size, contentType }
|
||||
res.mimeType && res.mimeType !== 'application/octet-stream'
|
||||
? res.mimeType
|
||||
: info?.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: getFileMimeType(null, filename)
|
||||
return { filePath, size, contentType }
|
||||
}
|
||||
|
||||
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
|
||||
async function downloadKey(key: string, userId: string): Promise<AgentToolResult> {
|
||||
async function downloadKey(key: string, ctx: AgentOperationContext): Promise<AgentToolResult> {
|
||||
const userId = ctx.userId || ''
|
||||
const owningAssetId = await resolveAssetIdFromKey(key)
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
@@ -57,7 +71,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
|
||||
})
|
||||
await assertStorageKeyNotArchived(key)
|
||||
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
|
||||
const saved = await saveToSandbox(key, filename)
|
||||
const saved = await saveToRunner(key, filename, ctx)
|
||||
return {
|
||||
output: [
|
||||
{
|
||||
@@ -69,15 +83,19 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves each file of a download_asset result into the sandbox. */
|
||||
export async function presentDownloadOutput(output: DownloadAssetOutput): Promise<AgentToolResult> {
|
||||
/** Saves each file of a download_asset result into the runner's .pi directory. */
|
||||
export async function presentDownloadOutput(
|
||||
output: DownloadAssetOutput,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult> {
|
||||
const lines: string[] = []
|
||||
const files = []
|
||||
for (const file of output.files) {
|
||||
if (!file.key) throw new Error(`download_asset returned no storage key for ${file.assetId}`)
|
||||
const saved = await saveToSandbox(
|
||||
const saved = await saveToRunner(
|
||||
file.key,
|
||||
`${file.assetId}_${sanitizeFilename(file.name) || 'file'}`,
|
||||
ctx,
|
||||
)
|
||||
lines.push(
|
||||
`Downloaded "${file.name}" (ID: ${file.assetId}, ${file.kind}, ${saved.contentType}, ${formatSize(saved.size)}) to "${saved.filePath}".`,
|
||||
@@ -90,7 +108,7 @@ export async function presentDownloadOutput(output: DownloadAssetOutput): Promis
|
||||
|
||||
const downloadAssetExtension: AgentToolExtension = {
|
||||
description:
|
||||
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the local .pi directory, for processing with local scripts or bash commands. ` +
|
||||
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the runner's .pi directory, for processing with local scripts or bash commands. ` +
|
||||
'By default it saves the web preview version (proxy) when there is one, e.g. the transcoded video or the web image; set proxy to false for the original uploaded file. ' +
|
||||
'A version stack downloads its latest version; folders are not supported. ' +
|
||||
'To download a specific artifact from read_asset (e.g. a frame or page), pass its storage key as "key" instead of assetIds. ' +
|
||||
@@ -116,9 +134,9 @@ const downloadAssetExtension: AgentToolExtension = {
|
||||
throw new Error('Provide either "assetIds" or "key", not both.')
|
||||
}
|
||||
if (!ctx.userId) throw new Error('User ID is required for authorization.')
|
||||
return downloadKey(extra.key, ctx.userId)
|
||||
return downloadKey(extra.key, ctx)
|
||||
},
|
||||
present: (output) => presentDownloadOutput(output as DownloadAssetOutput),
|
||||
present: (output, _extra, ctx) => presentDownloadOutput(output as DownloadAssetOutput, ctx),
|
||||
}
|
||||
|
||||
registerAgentToolExtension('download_asset', downloadAssetExtension)
|
||||
|
||||
@@ -142,7 +142,7 @@ export function createAutofillReadAssetTool(access: {
|
||||
description: readAsset.description,
|
||||
parameters: toToolParameters(op, readAssetExtension),
|
||||
execute: async (params) => {
|
||||
const { input, extra } = splitAgentParams(op, readAssetExtension, params)
|
||||
const { input, extra } = await splitAgentParams(op, readAssetExtension, params)
|
||||
const parsed = readAsset.input.safeParse(input)
|
||||
if (!parsed.success) {
|
||||
throw new Error(`Invalid input for read_asset: ${z.prettifyError(parsed.error)}`)
|
||||
|
||||
@@ -5,18 +5,22 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AuditAction, type AssetInfo } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { Value } from 'typebox/value'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { toAgentTool, type AgentToolOptions } from '../operation-tools'
|
||||
import './upload'
|
||||
|
||||
const ctx = { userId: 'user-1', agentId: 'agent-1', teamId: 'team-1', projectId: 'proj-1' }
|
||||
const ctx = {
|
||||
userId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
runnerId: null,
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
function tool(name: 'create_file' | 'create_version', options: AgentToolOptions = {}) {
|
||||
@@ -55,14 +59,6 @@ const promptField = {
|
||||
}
|
||||
|
||||
describe('create_file and create_version agent tools', () => {
|
||||
const tempFiles: string[] = []
|
||||
const tempFile = (content: string, filename: string): string => {
|
||||
const filePath = path.join(os.tmpdir(), filename)
|
||||
fs.writeFileSync(filePath, content)
|
||||
tempFiles.push(filePath)
|
||||
return filePath
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
vi.spyOn(auditLogService, 'logAction').mockResolvedValue(null)
|
||||
@@ -83,7 +79,6 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.spyOn(assetService, 'createVersion').mockResolvedValue(assetInfo({ name: 'v2' }))
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([promptField] as never)
|
||||
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://storage.example/upload')
|
||||
// Read file streams to the end, as real storage would.
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(async (_bucket, _key, body) => {
|
||||
if (body && typeof body === 'object' && Symbol.asyncIterator in body) {
|
||||
for await (const chunk of body as AsyncIterable<unknown>) void chunk
|
||||
@@ -96,20 +91,46 @@ describe('create_file and create_version agent tools', () => {
|
||||
contentType: 'text/markdown',
|
||||
eTag: '',
|
||||
}))
|
||||
vi.spyOn(s3Service, 'getObject').mockResolvedValue({
|
||||
buffer: Buffer.from('# Generated content'),
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
vi.spyOn(runnerService, 'requireOnlineRunner').mockResolvedValue({
|
||||
id: 'runner-1',
|
||||
teamId: 'team-1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected',
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
})
|
||||
vi.spyOn(runnerService, 'statOnRunner').mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-1',
|
||||
ok: true,
|
||||
exists: true,
|
||||
isFile: true,
|
||||
size: 17,
|
||||
mimeType: 'text/markdown',
|
||||
})
|
||||
vi.spyOn(runnerService, 'uploadFromRunner').mockResolvedValue({
|
||||
type: 'file.upload.result',
|
||||
executionId: 'exec-ul-1',
|
||||
ok: true,
|
||||
size: 17,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const f of tempFiles.splice(0)) fs.rmSync(f, { force: true })
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('uploads a local file to storage and creates the file as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-file.md')
|
||||
|
||||
it('uploads a file from the runner to storage and creates the file as the agent', async () => {
|
||||
const result = await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file.md',
|
||||
} as never)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
@@ -118,16 +139,21 @@ describe('create_file and create_version agent tools', () => {
|
||||
type: ResourceType.Asset,
|
||||
id: 'folder-1',
|
||||
})
|
||||
const [putBucket, key, , size, contentType] = vi.mocked(s3Service.putObject).mock.calls[0]
|
||||
expect(putBucket).toBe(bucket)
|
||||
expect(key).toMatch(/^files\/.+\/agent-create-file\.md$/)
|
||||
expect(size).toBe(Buffer.byteLength('# Hello from disk'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith('team-1', null)
|
||||
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
'.pi/agent-create-file.md',
|
||||
)
|
||||
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
|
||||
srcPath: '.pi/agent-create-file.md',
|
||||
url: 'https://storage.example/upload',
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'agent-create-file.md',
|
||||
key,
|
||||
key: expect.stringMatching(/^files\/.+\/agent-create-file\.md$/),
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
@@ -155,6 +181,90 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to temporary S3 storage when no runner is configured for .pi/generated/', async () => {
|
||||
vi.mocked(runnerService.requireOnlineRunner).mockRejectedValueOnce(
|
||||
new Error('No Runner is configured for this team.'),
|
||||
)
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '.pi/generated/gen123/poster.png',
|
||||
} as never)
|
||||
|
||||
expect(runnerService.statOnRunner).not.toHaveBeenCalled()
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/poster.png')
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
parentId: 'folder-1',
|
||||
name: 'poster.png',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to temporary S3 storage when .pi/generated/ file is not staged on the online runner', async () => {
|
||||
vi.mocked(runnerService.statOnRunner).mockResolvedValueOnce({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-missing',
|
||||
ok: true,
|
||||
exists: false,
|
||||
})
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '.pi/generated/gen123/unstaged.png',
|
||||
} as never)
|
||||
|
||||
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
'.pi/generated/gen123/unstaged.png',
|
||||
)
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/unstaged.png')
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('prefers uploading edited or newly created .pi/generated/ files from the runner over S3', async () => {
|
||||
vi.mocked(s3Service.headObject).mockImplementation(async (_bucket, key) => {
|
||||
if (key === 'temp/generated/gen123/edited.png') {
|
||||
throw new Error('NotFound')
|
||||
}
|
||||
return {
|
||||
key,
|
||||
size: 17,
|
||||
lastModified: new Date(),
|
||||
contentType: 'text/markdown',
|
||||
eTag: '',
|
||||
}
|
||||
})
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '.pi/generated/gen123/edited.png',
|
||||
} as never)
|
||||
|
||||
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
'.pi/generated/gen123/edited.png',
|
||||
)
|
||||
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
|
||||
srcPath: '.pi/generated/gen123/edited.png',
|
||||
url: 'https://storage.example/upload',
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
expect(s3Service.getObject).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads explicit temp/generated/ paths directly from S3 without touching the runner', async () => {
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: 'temp/generated/gen123/direct.png',
|
||||
} as never)
|
||||
|
||||
expect(runnerService.requireOnlineRunner).not.toHaveBeenCalled()
|
||||
expect(runnerService.statOnRunner).not.toHaveBeenCalled()
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/direct.png')
|
||||
})
|
||||
|
||||
it('creates a text file from name and content', async () => {
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
@@ -199,11 +309,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata, including new select options', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-meta.md')
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-meta.md',
|
||||
metadata: { prompt: { newOption: { value: 'Kling' } } },
|
||||
} as never)
|
||||
|
||||
@@ -213,11 +321,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('treats null metadata as omitted', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-null.md')
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-null.md',
|
||||
metadata: null,
|
||||
} as never)
|
||||
|
||||
@@ -225,17 +331,15 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('rejects metadata keys that are not Creation Context fields before uploading', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-bad-meta.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-bad-meta.md',
|
||||
metadata: { status: 'approved' },
|
||||
} as never),
|
||||
).rejects.toThrow(/not allowed: status/)
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -260,14 +364,20 @@ describe('create_file and create_version agent tools', () => {
|
||||
).rejects.toThrow('"name" is required')
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist, without touching storage', async () => {
|
||||
it('fails when the file does not exist on the runner, without touching storage', async () => {
|
||||
vi.mocked(runnerService.statOnRunner).mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-2',
|
||||
ok: true,
|
||||
exists: false,
|
||||
})
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '/nonexistent/file.md',
|
||||
path: '.pi/nonexistent.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
).rejects.toThrow('Local file not found at path: .pi/nonexistent.md')
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -275,10 +385,12 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-file-denied.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', path: filePath } as never),
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '.pi/agent-create-file-denied.md',
|
||||
} as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
@@ -290,6 +402,7 @@ describe('create_file and create_version agent tools', () => {
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -322,19 +435,21 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
describe('create_version', () => {
|
||||
it('uploads a local file and creates a version as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-version.md')
|
||||
|
||||
it('uploads a file from the runner and creates a version as the agent', async () => {
|
||||
const result = await invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-version.md',
|
||||
} as never)
|
||||
|
||||
const key = vi.mocked(s3Service.putObject).mock.calls[0][1]
|
||||
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
|
||||
srcPath: '.pi/agent-create-version.md',
|
||||
url: 'https://storage.example/upload',
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'agent-create-version.md',
|
||||
key,
|
||||
key: expect.stringMatching(/^files\/.+\/agent-create-version\.md$/),
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
@@ -348,11 +463,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-version-meta.md')
|
||||
|
||||
await invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-version-meta.md',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
} as never)
|
||||
|
||||
@@ -365,23 +478,31 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-version-denied.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_version'), 'call-1', { parent: 'file-1', path: filePath } as never),
|
||||
invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: '.pi/agent-create-version-denied.md',
|
||||
} as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist', async () => {
|
||||
vi.mocked(runnerService.statOnRunner).mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-3',
|
||||
ok: true,
|
||||
exists: false,
|
||||
})
|
||||
await expect(
|
||||
invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: '/nonexistent/file.md',
|
||||
path: '.pi/nonexistent.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
).rejects.toThrow('Local file not found at path: .pi/nonexistent.md')
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the agent its own parameters', () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { completeUploadOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { createFile, type StartedUploadOutput } from '@shumai/operations'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type } from 'typebox'
|
||||
import { z } from 'zod'
|
||||
@@ -32,17 +32,126 @@ function setCreationMetadata(schema: ToolParametersSchema, options: AgentToolOpt
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLocalFile(localPath: string): string {
|
||||
const absolutePath = path.resolve(process.cwd(), localPath)
|
||||
if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isFile()) {
|
||||
function resolveGeneratedStorageKey(rawPath: string): {
|
||||
storageKey: string
|
||||
explicitStorageRef: boolean
|
||||
} | null {
|
||||
const cleaned = rawPath.replace(/\\/g, '/').replace(/^\.\//, '')
|
||||
if (cleaned.includes('..')) return null
|
||||
if (cleaned.startsWith('.pi/generated/')) {
|
||||
const rest = cleaned.slice('.pi/generated/'.length)
|
||||
return rest ? { storageKey: `temp/generated/${rest}`, explicitStorageRef: false } : null
|
||||
}
|
||||
if (cleaned.startsWith('temp/generated/')) {
|
||||
const rest = cleaned.slice('temp/generated/'.length)
|
||||
return rest ? { storageKey: cleaned, explicitStorageRef: true } : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeRunnerPath(rawPath: string): string | null {
|
||||
const cleaned = rawPath.replace(/\\/g, '/').replace(/^\.\//, '')
|
||||
if (!cleaned || cleaned.startsWith('/') || cleaned.includes('..')) {
|
||||
return null
|
||||
}
|
||||
const normalized = path.posix.normalize(cleaned)
|
||||
if (normalized.startsWith('..') || normalized.startsWith('/')) {
|
||||
return null
|
||||
}
|
||||
if (normalized === '.pi' || normalized.startsWith('.pi/')) {
|
||||
return normalized
|
||||
}
|
||||
return `.pi/${normalized}`
|
||||
}
|
||||
|
||||
async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<string> {
|
||||
if (ctx?.runnerId && !ctx.teamId) {
|
||||
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
throw new Error(
|
||||
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
|
||||
)
|
||||
}
|
||||
return ctx.runnerId
|
||||
}
|
||||
const runner = await runnerService.requireOnlineRunner(ctx?.teamId || '', ctx?.runnerId)
|
||||
return runner.id
|
||||
}
|
||||
|
||||
async function resolveStorageGeneratedSource(storageKey: string): Promise<{
|
||||
kind: 'generated'
|
||||
storageKey: string
|
||||
name: string
|
||||
contentType: string
|
||||
} | null> {
|
||||
const head = await s3Service.headObject(storageBucket(), storageKey).catch(() => null)
|
||||
if (!head) {
|
||||
return null
|
||||
}
|
||||
const name = path.posix.basename(storageKey)
|
||||
const contentType =
|
||||
head.contentType && head.contentType !== 'application/octet-stream'
|
||||
? head.contentType
|
||||
: getFileMimeType(null, name)
|
||||
return { kind: 'generated', storageKey, name, contentType }
|
||||
}
|
||||
|
||||
async function resolvePathSource(
|
||||
localPath: string,
|
||||
ctx?: AgentOperationContext,
|
||||
): Promise<
|
||||
| { kind: 'generated'; storageKey: string; name: string; contentType: string }
|
||||
| { kind: 'runner'; runnerId: string; runnerPath: string; name: string; contentType: string }
|
||||
> {
|
||||
const generatedRef = resolveGeneratedStorageKey(localPath)
|
||||
if (generatedRef?.explicitStorageRef) {
|
||||
const source = await resolveStorageGeneratedSource(generatedRef.storageKey)
|
||||
if (!source) {
|
||||
throw new Error(`Local file not found at path: ${localPath}`)
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
const runnerPath = normalizeRunnerPath(localPath)
|
||||
if (!runnerPath) {
|
||||
throw new Error(`Local file not found at path: ${localPath}`)
|
||||
}
|
||||
return absolutePath
|
||||
|
||||
let runnerError: unknown
|
||||
try {
|
||||
const runnerId = await resolveTargetRunnerId(ctx)
|
||||
const stat = await runnerService.statOnRunner(runnerId, runnerPath)
|
||||
if (stat.ok && stat.exists && stat.isFile !== false) {
|
||||
const name = path.posix.basename(runnerPath)
|
||||
const contentType =
|
||||
stat.mimeType && stat.mimeType !== 'application/octet-stream'
|
||||
? stat.mimeType
|
||||
: getFileMimeType(null, name)
|
||||
return { kind: 'runner', runnerId, runnerPath, name, contentType }
|
||||
}
|
||||
} catch (err) {
|
||||
if (!generatedRef) {
|
||||
throw err
|
||||
}
|
||||
runnerError = err
|
||||
}
|
||||
|
||||
// Fallback for unstaged generated files stored in temporary S3
|
||||
if (generatedRef) {
|
||||
const source = await resolveStorageGeneratedSource(generatedRef.storageKey)
|
||||
if (source) {
|
||||
return source
|
||||
}
|
||||
if (runnerError) {
|
||||
throw runnerError
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Local file not found at path: ${localPath}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the file straight to the upload's storage key (the agent runs next to storage, so
|
||||
* it doesn't need the upload URL), then completes the upload as the agent.
|
||||
* Transfers the file from either temporary generated storage or the remote runner workspace
|
||||
* into the upload's storage key, then completes the upload as the agent.
|
||||
*/
|
||||
async function uploadAndComplete(
|
||||
raw: unknown,
|
||||
@@ -53,14 +162,29 @@ async function uploadAndComplete(
|
||||
if (!started.key) throw new Error('The upload did not return a storage key')
|
||||
|
||||
if (typeof extra.path === 'string') {
|
||||
const absolutePath = resolveLocalFile(extra.path)
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
fs.createReadStream(absolutePath),
|
||||
fs.statSync(absolutePath).size,
|
||||
readFileMimeType(absolutePath),
|
||||
)
|
||||
const source =
|
||||
(extra.__resolvedSource as Awaited<ReturnType<typeof resolvePathSource>> | undefined) ??
|
||||
(await resolvePathSource(extra.path, ctx))
|
||||
|
||||
if (source.kind === 'generated') {
|
||||
const obj = await s3Service.getObject(storageBucket(), source.storageKey)
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
obj.buffer,
|
||||
obj.buffer.length,
|
||||
source.contentType,
|
||||
)
|
||||
} else {
|
||||
const uploadRes = await runnerService.uploadFromRunner(source.runnerId, {
|
||||
srcPath: source.runnerPath,
|
||||
url: started.uploadUrl,
|
||||
contentType: source.contentType,
|
||||
})
|
||||
if (!uploadRes.ok) {
|
||||
throw new Error(uploadRes.error || `Failed to upload file "${extra.path}" from runner`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const content = Buffer.from(typeof extra.content === 'string' ? extra.content : '', 'utf-8')
|
||||
// The key ends with the file name, which gives the same type as the upload's.
|
||||
@@ -85,7 +209,7 @@ async function uploadAndComplete(
|
||||
const createFileExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new file in a folder. Choose exactly ONE source: ' +
|
||||
'(1) "path" to upload a local file (e.g. one you made in .pi), OR ' +
|
||||
'(1) "path" to upload a file from .pi (e.g. a generated file in .pi/generated/... or a file created in .pi on the runner), OR ' +
|
||||
'(2) "name" and "content" to create a text file with that content. ' +
|
||||
METADATA_HINT,
|
||||
parameterOverrides: z.object({
|
||||
@@ -100,7 +224,9 @@ const createFileExtension: AgentToolExtension = {
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Absolute or relative path of a local file to upload. Omit when using "content".'),
|
||||
.describe(
|
||||
'Path of a file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload. Omit when using "content".',
|
||||
),
|
||||
content: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -108,18 +234,19 @@ const createFileExtension: AgentToolExtension = {
|
||||
}),
|
||||
hiddenParameters: ['contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
async toInput(input, extra, ctx) {
|
||||
const hasPath = typeof extra.path === 'string'
|
||||
const hasContent = typeof extra.content === 'string'
|
||||
if (hasPath === hasContent) {
|
||||
throw new Error('Provide exactly one of "path" (a local file) or "content" (with "name").')
|
||||
}
|
||||
if (hasPath) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
const source = await resolvePathSource(extra.path as string, ctx)
|
||||
extra.__resolvedSource = source
|
||||
return {
|
||||
...input,
|
||||
name: input.name ?? path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
name: input.name ?? source.name,
|
||||
contentType: source.contentType,
|
||||
}
|
||||
}
|
||||
if (typeof input.name !== 'string' || !input.name.trim()) {
|
||||
@@ -132,23 +259,26 @@ const createFileExtension: AgentToolExtension = {
|
||||
|
||||
const createVersionExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new version of an existing file (or version stack) from a local file path. ' +
|
||||
'Create a new version of an existing file (or version stack) from a file path in .pi. ' +
|
||||
'The new version becomes the current one. ' +
|
||||
METADATA_HINT,
|
||||
extraParameters: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe('Absolute or relative path of the local file to upload as the new version.'),
|
||||
.describe(
|
||||
'Path of the file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload as the new version.',
|
||||
),
|
||||
}),
|
||||
hiddenParameters: ['name', 'contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
async toInput(input, extra, ctx) {
|
||||
const source = await resolvePathSource(extra.path as string, ctx)
|
||||
extra.__resolvedSource = source
|
||||
return {
|
||||
...input,
|
||||
name: path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
name: source.name,
|
||||
contentType: source.contentType,
|
||||
}
|
||||
},
|
||||
present: uploadAndComplete,
|
||||
|
||||
@@ -14,7 +14,9 @@ import { Compile } from 'typebox/compile'
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Context for agent-invoked Operations; `via` is always `agent`. */
|
||||
export type AgentOperationContext = Omit<OperationContext, 'via'>
|
||||
export type AgentOperationContext = Omit<OperationContext, 'via'> & {
|
||||
runnerId?: string | null
|
||||
}
|
||||
|
||||
/** Per-session settings for building tools, e.g. schemas that depend on the project. */
|
||||
export interface AgentToolOptions {
|
||||
@@ -23,6 +25,10 @@ export interface AgentToolOptions {
|
||||
* parameter of tools that create files. Undefined when the project has none.
|
||||
*/
|
||||
creationMetadataSchema?: TSchema
|
||||
/**
|
||||
* Operation names to exclude from the built tool list (e.g. `download_asset` when no runner is configured).
|
||||
*/
|
||||
excludeOperations?: string[]
|
||||
}
|
||||
|
||||
/** The JSON Schema of a tool's parameters (an object schema). */
|
||||
@@ -54,7 +60,11 @@ export interface AgentToolExtension {
|
||||
/** Adjust the parameters' JSON Schema for this session (e.g. a project-specific field). */
|
||||
adjustParameters?(schema: ToolParametersSchema, options: AgentToolOptions): void
|
||||
/** Adjust the Operation input using the extra parameters. */
|
||||
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
|
||||
toInput?(
|
||||
input: Record<string, unknown>,
|
||||
extra: Record<string, unknown>,
|
||||
ctx?: AgentOperationContext,
|
||||
): Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/**
|
||||
* Handle an agent-only mode without running the Operation (e.g. a storage key instead of
|
||||
* an asset). Return undefined to run the Operation.
|
||||
@@ -110,11 +120,12 @@ export function toToolParameters(
|
||||
}
|
||||
|
||||
/** Split agent-only parameters from the Operation input. */
|
||||
export function splitAgentParams(
|
||||
export async function splitAgentParams(
|
||||
op: Operation,
|
||||
extension: AgentToolExtension | undefined,
|
||||
params: unknown,
|
||||
): { input: unknown; extra: Record<string, unknown> } {
|
||||
ctx?: AgentOperationContext,
|
||||
): Promise<{ input: unknown; extra: Record<string, unknown> }> {
|
||||
const cleaned = dropNullOptionals(toolInputSchema(op, extension), params)
|
||||
if (!extension?.extraParameters || !cleaned || typeof cleaned !== 'object') {
|
||||
return { input: cleaned, extra: {} }
|
||||
@@ -125,7 +136,10 @@ export function splitAgentParams(
|
||||
for (const [key, value] of Object.entries(cleaned)) {
|
||||
;(extraKeys.has(key) ? extra : input)[key] = value
|
||||
}
|
||||
return { input: extension.toInput ? extension.toInput(input, extra) : input, extra }
|
||||
return {
|
||||
input: extension.toInput ? await extension.toInput(input, extra, ctx) : input,
|
||||
extra,
|
||||
}
|
||||
}
|
||||
|
||||
/** Expose an Operation as a native agent tool that runs through `runOperation`. */
|
||||
@@ -141,7 +155,7 @@ export function toAgentTool(
|
||||
description: extension?.description ?? definition.description,
|
||||
parameters: toToolParameters(op, extension, options),
|
||||
execute: async (params) => {
|
||||
const { input, extra } = splitAgentParams(op, extension, params)
|
||||
const { input, extra } = await splitAgentParams(op, extension, params, ctx)
|
||||
if (extension?.intercept) {
|
||||
const handled = await extension.intercept(input as Record<string, unknown>, extra, ctx)
|
||||
if (handled) return handled
|
||||
@@ -163,5 +177,8 @@ export function buildOperationTools(
|
||||
ctx: AgentOperationContext,
|
||||
options: AgentToolOptions = {},
|
||||
): AgentTool[] {
|
||||
return getOperationsForSurface('agent').map((op) => toAgentTool(op, ctx, options))
|
||||
const excluded = new Set(options.excludeOperations ?? [])
|
||||
return getOperationsForSurface('agent')
|
||||
.filter((op) => !excluded.has(op.definition.name))
|
||||
.map((op) => toAgentTool(op, ctx, options))
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
hook,
|
||||
type ToolRegistration as AgentTool,
|
||||
} from '@earendil-works/pi-durable'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { hydrateRequest } from '@shumai/core/src/agent/session-content'
|
||||
import { agentSessionService } from '@shumai/core/src/agent/session-service'
|
||||
@@ -34,9 +33,9 @@ import { logger } from '@shumai/core/src/logger'
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { QuotaExceededError, quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { DEFAULT_DENIED_TOOLS } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { createAutofillReadAssetTool } from './operation-extensions'
|
||||
@@ -45,7 +44,7 @@ import { createGenerateImageTool } from './tools/generate-image'
|
||||
import { createGenerateVideoTool } from './tools/generate-video'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
|
||||
|
||||
const activeHarnesses = new Set<Harness>()
|
||||
|
||||
@@ -153,21 +152,6 @@ export interface CreateAgentSessionParams {
|
||||
baseDelayMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Security instructions appended to the system prompt when the requesting user is not a team
|
||||
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
|
||||
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
|
||||
*/
|
||||
export function buildRestrictedUserInstructions(): string {
|
||||
return [
|
||||
'# Restricted User Context',
|
||||
'The current user is NOT a team owner. You must follow these security rules:',
|
||||
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
|
||||
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
|
||||
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const {
|
||||
teamId,
|
||||
@@ -177,7 +161,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemPrompt,
|
||||
teamSkills,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
projectId,
|
||||
@@ -202,17 +185,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
})
|
||||
const storage = opened.storage
|
||||
try {
|
||||
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
|
||||
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
||||
|
||||
getModelFromDb(params.providers, providerName, modelId)
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
||||
|
||||
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
|
||||
const isOwner = !userId || role === 'owner'
|
||||
const restricted = !isOwner
|
||||
|
||||
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
|
||||
const originalExecute = tool.execute
|
||||
@@ -262,17 +237,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
if (allowedDomains !== undefined) {
|
||||
await sandboxService.syncAllowedDomains(allowedDomains, teamId)
|
||||
}
|
||||
|
||||
const skillEnvs: Record<string, string> = {}
|
||||
const onEnvsAdded = (envs: Record<string, string>) => {
|
||||
Object.assign(skillEnvs, envs)
|
||||
}
|
||||
|
||||
// Restore env variables from previously loaded skills in this session
|
||||
let skillLoadedInSession = false
|
||||
const loadedSkills = new Map<string, LoadedSkillRef>()
|
||||
|
||||
// Restore env variables and loaded skill refs from previously loaded skills in this session
|
||||
if (sessionId) {
|
||||
try {
|
||||
const entries = await agentSessionService.getEntries(record.id)
|
||||
@@ -291,8 +263,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
'skillId' in details &&
|
||||
typeof details.skillId === 'string'
|
||||
) {
|
||||
skillLoadedInSession = true
|
||||
onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: details.skillId },
|
||||
select: { id: true, assetId: true, hash: true },
|
||||
})
|
||||
if (dbSkill) {
|
||||
loadedSkills.set(dbSkill.id, dbSkill)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,6 +286,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
||||
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
|
||||
|
||||
const resolvedRunner = await runnerService.resolveRunnerForAgent(teamId, agent?.runnerId)
|
||||
const hasRunner = resolvedRunner.hasConfiguredRunner
|
||||
|
||||
const mediaTools: AgentTool[] = []
|
||||
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
|
||||
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
|
||||
@@ -335,42 +316,33 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
|
||||
const runnerBash = createRunnerBashTool(skillEnvs, {
|
||||
teamId,
|
||||
agentRunnerId: agent?.runnerId,
|
||||
environment: resolvedRunner.runner
|
||||
? runnerService.getRunnerEnvironment(resolvedRunner.runner.id)
|
||||
: undefined,
|
||||
userId,
|
||||
role,
|
||||
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
|
||||
clearBlockedHost: () => {
|
||||
sandboxService.clearBlockedHost()
|
||||
},
|
||||
// Non-owner users can only run bash commands required by a loaded skill
|
||||
restrictedUser: restricted,
|
||||
getLoadedSkills: () => loadedSkills.values(),
|
||||
})
|
||||
|
||||
// For non-owner users, the bash tool is not injected initially. It becomes available
|
||||
// only after a skill is successfully loaded via the read_skill tool (or immediately when
|
||||
// a skill was already loaded earlier in this session).
|
||||
const registry = createRegistry()
|
||||
const bashIncludedFromStart = isOwner || skillLoadedInSession
|
||||
let bashInjected = bashIncludedFromStart
|
||||
const onSkillLoaded = async () => {
|
||||
if (bashInjected || deniedTools.includes('bash')) return
|
||||
bashInjected = true
|
||||
registry.install(
|
||||
defineExtension({ name: 'shumai.bash', tools: [wrapToolWithQuota(sandboxedBash)] }),
|
||||
)
|
||||
await session?.configure(
|
||||
{
|
||||
tools: [...enabledTools, wrapToolWithQuota(sandboxedBash)],
|
||||
modelTools: { add: [sandboxedBash] },
|
||||
},
|
||||
piContext,
|
||||
)
|
||||
const onSkillLoaded = async (skill: LoadedSkillRef) => {
|
||||
loadedSkills.set(skill.id, skill)
|
||||
if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) {
|
||||
await runnerService.ensureSkillOnRunner(resolvedRunner.runner.id, skill).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, skillId: skill.id, runnerId: resolvedRunner.runner?.id },
|
||||
'Failed to eagerly stage skill on runner',
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
const readSkill = createReadSkillTool(
|
||||
userId,
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
onSkillLoaded,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
@@ -381,7 +353,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemTools.push(
|
||||
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
|
||||
// reading and downloading assets, creating files and versions, comments and metadata
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
|
||||
...buildOperationTools(
|
||||
{ userId, agentId, teamId, projectId, runnerId: agent?.runnerId },
|
||||
{
|
||||
creationMetadataSchema,
|
||||
excludeOperations: hasRunner ? [] : ['download_asset'],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -390,7 +368,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
...(bashIncludedFromStart ? [sandboxedBash] : []),
|
||||
...(hasRunner ? [runnerBash] : []),
|
||||
...systemTools,
|
||||
...customTools,
|
||||
]
|
||||
@@ -458,22 +436,18 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
return prompt
|
||||
}
|
||||
|
||||
if (restricted) {
|
||||
prompt += `\n\n${buildRestrictedUserInstructions()}`
|
||||
if (hasRunner && !deniedTools.includes('bash')) {
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Runner Environment & Workspace Rules',
|
||||
'Your shell environment (`bash` tool) runs on a dedicated Runner workspace:',
|
||||
'1. **Workspace Directory**: Read and write files inside the `.pi` folder in the current working directory.',
|
||||
'2. **Generated Media Staging**: Files generated by `generate_image` or `generate_video` are returned at virtual paths `.pi/generated/<id>/<filename>`. You can pass those paths directly to `create_file` or `create_version` without using `bash`. If you need to process a generated file inside `bash`, pass its path in the `inputFiles` array parameter of the `bash` tool so it is staged into the runner workspace before the command runs.',
|
||||
'3. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
// Sandbox environment restrictions
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Sandbox Environment Restrictions',
|
||||
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
|
||||
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
|
||||
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
|
||||
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
|
||||
'4. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
|
||||
if (teamSkills.length > 0) {
|
||||
prompt += formatSkillsForPrompt(teamSkills)
|
||||
}
|
||||
@@ -643,13 +617,13 @@ export function formatSkillsForPrompt(
|
||||
const lines = [
|
||||
'\n\nThe following skills provide specialized instructions for specific tasks.',
|
||||
"Use the read_skill tool to load a skill's file when the task matches its description.",
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that relative path in tool commands.',
|
||||
'',
|
||||
'<available_skills>',
|
||||
]
|
||||
|
||||
for (const skill of skills) {
|
||||
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
|
||||
const filePath = path.posix.join('.pi', 'skills', skill.id, 'SKILL.md')
|
||||
lines.push(' <skill>')
|
||||
lines.push(` <id>${escapeXml(skill.id)}</id>`)
|
||||
lines.push(` <name>${escapeXml(skill.name)}</name>`)
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, () => {})
|
||||
|
||||
@@ -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/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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 ?? {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { OutputAccumulator } from './output-accumulator'
|
||||
|
||||
describe('OutputAccumulator', () => {
|
||||
it('does not accumulate rawChunks in memory when disableTempFile is true', () => {
|
||||
const acc = new OutputAccumulator({
|
||||
maxBytes: 1024,
|
||||
maxLines: 50,
|
||||
disableTempFile: true,
|
||||
})
|
||||
|
||||
const chunk = Buffer.from(`${'x'.repeat(2047)}\n`, 'utf-8')
|
||||
for (let i = 0; i < 256; i++) {
|
||||
acc.append(chunk)
|
||||
}
|
||||
acc.finish()
|
||||
|
||||
const internal = acc as unknown as { rawChunks: Buffer[]; tailBytes: number }
|
||||
expect(internal.rawChunks).toEqual([])
|
||||
expect(internal.tailBytes).toBeLessThanOrEqual(1024 * 4)
|
||||
|
||||
const snapshot = acc.snapshot({ persistIfTruncated: false })
|
||||
expect(snapshot.truncation.truncated).toBe(true)
|
||||
expect(snapshot.fullOutputPath).toBeUndefined()
|
||||
expect(Buffer.byteLength(snapshot.content, 'utf-8')).toBeLessThanOrEqual(1024)
|
||||
})
|
||||
})
|
||||
@@ -13,6 +13,7 @@ export interface OutputAccumulatorOptions {
|
||||
maxLines?: number
|
||||
maxBytes?: number
|
||||
tempFilePrefix?: string
|
||||
disableTempFile?: boolean
|
||||
}
|
||||
|
||||
export interface OutputSnapshot {
|
||||
@@ -35,6 +36,7 @@ export class OutputAccumulator {
|
||||
private readonly maxBytes: number
|
||||
private readonly maxRollingBytes: number
|
||||
private readonly tempFilePrefix: string
|
||||
private readonly disableTempFile: boolean
|
||||
private readonly decoder = new TextDecoder()
|
||||
|
||||
private rawChunks: Buffer[] = []
|
||||
@@ -57,6 +59,7 @@ export class OutputAccumulator {
|
||||
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES
|
||||
this.maxRollingBytes = Math.max(this.maxBytes * 2, 1)
|
||||
this.tempFilePrefix = options.tempFilePrefix ?? 'shumai-bash'
|
||||
this.disableTempFile = options.disableTempFile ?? false
|
||||
}
|
||||
|
||||
append(data: Buffer): void {
|
||||
@@ -70,7 +73,7 @@ export class OutputAccumulator {
|
||||
if (this.tempFileStream || this.shouldUseTempFile()) {
|
||||
this.ensureTempFile()
|
||||
this.tempFileStream?.write(data)
|
||||
} else if (data.length > 0) {
|
||||
} else if (!this.disableTempFile && data.length > 0) {
|
||||
this.rawChunks.push(data)
|
||||
}
|
||||
}
|
||||
@@ -202,6 +205,9 @@ export class OutputAccumulator {
|
||||
}
|
||||
|
||||
private shouldUseTempFile(): boolean {
|
||||
if (this.disableTempFile) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
this.totalRawBytes > this.maxBytes ||
|
||||
this.totalDecodedBytes > this.maxBytes ||
|
||||
@@ -210,7 +216,7 @@ export class OutputAccumulator {
|
||||
}
|
||||
|
||||
private ensureTempFile(): void {
|
||||
if (this.tempFilePath) {
|
||||
if (this.disableTempFile || this.tempFilePath) {
|
||||
return
|
||||
}
|
||||
this.tempFilePath = defaultTempFilePath(this.tempFilePrefix)
|
||||
|
||||
Reference in New Issue
Block a user