refactor(agent): expose runner bash without skill gating

This commit is contained in:
yiling
2026-11-17 16:11:37 +08:00
parent 8edd3008de
commit d801d166bb
9 changed files with 74 additions and 211 deletions
@@ -5,7 +5,7 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createAgentSession, type DbProviderInfo } from './index' import { createAgentSession, type DbProviderInfo } from './index'
import { closeAgentSessions } from './runtime' import { closeAgentSessions } from './runtime'
import { createSandboxedBashTool } from './tools/sandboxed-bash' import { createRunnerBashTool } from './tools/runner-bash'
const mockProviders: DbProviderInfo[] = [ const mockProviders: DbProviderInfo[] = [
{ {
@@ -92,19 +92,17 @@ describe('Concurrent Runner Sessions', () => {
providers: mockProviders, providers: mockProviders,
}) })
const tool = createSandboxedBashTool('/mock/cwd', {}, { teamId: team.id }) const tool = createRunnerBashTool({}, { teamId: team.id })
// Note: registerConnection sends a 'welcome' message first (conn.sent[0]) // Note: registerConnection sends a 'welcome' message first (conn.sent[0])
const execA = invokeTool(tool, 'call-a', { const execA = invokeTool(tool, 'call-a', {
command: 'echo session-a', command: 'echo session-a',
source: 'skill',
}) })
await vi.waitFor(() => expect(conn.sent.length).toBe(2)) await vi.waitFor(() => expect(conn.sent.length).toBe(2))
const msgA = JSON.parse(conn.sent[1]) const msgA = JSON.parse(conn.sent[1])
const execB = invokeTool(tool, 'call-b', { const execB = invokeTool(tool, 'call-b', {
command: 'echo session-b', command: 'echo session-b',
source: 'skill',
}) })
await vi.waitFor(() => expect(conn.sent.length).toBe(3)) await vi.waitFor(() => expect(conn.sent.length).toBe(3))
const msgB = JSON.parse(conn.sent[2]) const msgB = JSON.parse(conn.sent[2])
@@ -160,10 +158,12 @@ describe('Concurrent Runner Sessions', () => {
) )
const [resA, resB] = await Promise.all([execA, execB]) const [resA, resB] = await Promise.all([execA, execB])
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content blocks expect(resA.content).toContainEqual(
expect((resA as any).content[0].text).toContain('out-a') expect.objectContaining({ text: expect.stringContaining('out-a') }),
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content blocks )
expect((resB as any).content[0].text).toContain('out-b') expect(resB.content).toContainEqual(
expect.objectContaining({ text: expect.stringContaining('out-b') }),
)
runnerService.handleDisconnect(runner.id, conn.ws) runnerService.handleDisconnect(runner.id, conn.ws)
}) })
@@ -202,16 +202,14 @@ describe('Concurrent Runner Sessions', () => {
gpuConn.ws, gpuConn.ws,
) )
const defaultTool = createSandboxedBashTool( const defaultTool = createRunnerBashTool(
'/mock/cwd',
{}, {},
{ {
teamId: team.id, teamId: team.id,
agentRunnerId: null, agentRunnerId: null,
}, },
) )
const gpuTool = createSandboxedBashTool( const gpuTool = createRunnerBashTool(
'/mock/cwd',
{}, {},
{ {
teamId: team.id, teamId: team.id,
@@ -219,8 +217,8 @@ describe('Concurrent Runner Sessions', () => {
}, },
) )
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a', source: 'user' }) const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a' })
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi', source: 'user' }) const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi' })
await vi.waitFor(() => { await vi.waitFor(() => {
expect(defaultConn.lastSentJson()?.type).toBe('exec.start') expect(defaultConn.lastSentJson()?.type).toBe('exec.start')
+12 -26
View File
@@ -10,7 +10,6 @@ import { type TSchema } from 'typebox'
import { Value } from 'typebox/value' import { Value } from 'typebox/value'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import { import {
buildRestrictedUserInstructions,
createAgentSession, createAgentSession,
formatSkillsForPrompt, formatSkillsForPrompt,
getModelFromDb, getModelFromDb,
@@ -171,20 +170,7 @@ describe('Runner tool availability & skill staging integration', () => {
}) })
}) })
describe('buildRestrictedUserInstructions', () => { describe('createAgentSession runner bash policy', () => {
it('should describe the restricted user bash rules', () => {
const instructions = buildRestrictedUserInstructions()
expect(instructions).toContain('# Restricted User Context')
expect(instructions).toContain(
'NEVER execute a bash command that the user asks you to run directly',
)
expect(instructions).toContain('loaded via the `read_skill` tool')
expect(instructions).toContain('parameter to "skill"')
expect(instructions).toContain('source="user" will be rejected')
})
})
describe('createAgentSession bash restriction for non-owner users', () => {
setupTestDbHooks() setupTestDbHooks()
afterEach(() => { afterEach(() => {
@@ -262,21 +248,21 @@ describe('createAgentSession bash restriction for non-owner users', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true) expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
}) })
it('should treat a user who is not a team member as restricted (fail-closed)', async () => { it('does not use skill history as authorization for a session', async () => {
const { harness } = await setupSession({ role: 'non-member' }) const { harness } = await setupSession({ role: 'non-member' })
const tools = await getAgentTools(harness) const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(false) expect(tools.some((t) => t.name === 'bash')).toBe(true)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true) expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
const prompt = await await getAgentPrompt(harness) const prompt = await await getAgentPrompt(harness)
expect(prompt).toContain('# Restricted User Context') expect(prompt).not.toContain('# Restricted User Context')
}) })
it.each(['editor', 'reviewer'] as const)( it.each(['editor', 'reviewer'] as const)(
'should exclude the bash tool initially for %s users', 'exposes bash immediately for %s users without reading a skill',
async (role) => { async (role) => {
const { harness } = await setupSession({ role }) const { harness } = await setupSession({ role })
const tools = await getAgentTools(harness) const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(false) expect(tools.some((t) => t.name === 'bash')).toBe(true)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true) expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
}, },
) )
@@ -346,7 +332,7 @@ describe('createAgentSession bash restriction for non-owner users', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true) expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
}) })
it('should inject the bash tool after a skill is loaded via read_skill for restricted users', async () => { it('keeps bash available before and after reading a skill', async () => {
const { team, harness } = await setupSession({ role: 'reviewer' }) const { team, harness } = await setupSession({ role: 'reviewer' })
const skill = await prisma.skill.create({ const skill = await prisma.skill.create({
data: { name: 'Inject Skill', assetId: 'asset1', hash: 'inject-hash', teamId: team.id }, data: { name: 'Inject Skill', assetId: 'asset1', hash: 'inject-hash', teamId: team.id },
@@ -356,14 +342,14 @@ describe('createAgentSession bash restriction for non-owner users', () => {
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill') const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined() expect(readSkillTool).toBeDefined()
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false) expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
await invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined) await invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true) expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
}) })
it('should not inject the bash tool for restricted users when bash is in deniedTools', async () => { it('keeps bash disabled by agent policy after reading a skill', async () => {
const { team, harness } = await setupSession({ role: 'editor', deniedTools: ['bash'] }) const { team, harness } = await setupSession({ role: 'editor', deniedTools: ['bash'] })
const skill = await prisma.skill.create({ const skill = await prisma.skill.create({
data: { name: 'Denied Skill', assetId: 'asset1', hash: 'denied-hash', teamId: team.id }, data: { name: 'Denied Skill', assetId: 'asset1', hash: 'denied-hash', teamId: team.id },
@@ -379,11 +365,11 @@ describe('createAgentSession bash restriction for non-owner users', () => {
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false) expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
}) })
it('should include restricted user instructions in the system prompt for non-owners', async () => { it('omits skill-first bash instructions for editors', async () => {
const { harness } = await setupSession({ role: 'editor' }) const { harness } = await setupSession({ role: 'editor' })
const prompt = await await getAgentPrompt(harness) const prompt = await await getAgentPrompt(harness)
expect(prompt).toContain('# Restricted User Context') expect(prompt).not.toContain('# Restricted User Context')
expect(prompt).toContain('source="user" will be rejected') expect(prompt).not.toContain('source="user" will be rejected')
}) })
it('should not include restricted user instructions in the system prompt for owners', async () => { it('should not include restricted user instructions in the system prompt for owners', async () => {
@@ -29,7 +29,7 @@ async function resolveTargetRunnerId(ctx: AgentOperationContext): Promise<string
if (ctx.runnerId && !ctx.teamId) { if (ctx.runnerId && !ctx.teamId) {
if (!runnerService.isRunnerConnected(ctx.runnerId)) { if (!runnerService.isRunnerConnected(ctx.runnerId)) {
throw new Error( throw new Error(
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.', 'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
) )
} }
return ctx.runnerId return ctx.runnerId
@@ -68,7 +68,7 @@ async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<strin
if (ctx?.runnerId && !ctx.teamId) { if (ctx?.runnerId && !ctx.teamId) {
if (!runnerService.isRunnerConnected(ctx.runnerId)) { if (!runnerService.isRunnerConnected(ctx.runnerId)) {
throw new Error( throw new Error(
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.', 'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
) )
} }
return ctx.runnerId return ctx.runnerId
+3 -46
View File
@@ -44,7 +44,7 @@ import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video' import { createGenerateVideoTool } from './tools/generate-video'
import { createReadSkillTool } from './tools/read-skill' import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread' import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool, type LoadedSkillRef } from './tools/sandboxed-bash' import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
const activeHarnesses = new Set<Harness>() const activeHarnesses = new Set<Harness>()
@@ -152,21 +152,6 @@ export interface CreateAgentSessionParams {
baseDelayMs?: number 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) { export async function createAgentSession(params: CreateAgentSessionParams) {
const { const {
teamId, teamId,
@@ -203,8 +188,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
getModelFromDb(params.providers, providerName, modelId) getModelFromDb(params.providers, providerName, modelId)
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
const isOwner = !userId || role === 'owner'
const restricted = !isOwner
const wrapToolWithQuota = (tool: AgentTool): AgentTool => { const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
const originalExecute = tool.execute const originalExecute = tool.execute
@@ -262,7 +245,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const loadedSkills = new Map<string, LoadedSkillRef>() const loadedSkills = new Map<string, LoadedSkillRef>()
// Restore env variables and loaded skill refs from previously loaded skills in this session // Restore env variables and loaded skill refs from previously loaded skills in this session
let skillLoadedInSession = false
if (sessionId) { if (sessionId) {
try { try {
const entries = await agentSessionService.getEntries(record.id) const entries = await agentSessionService.getEntries(record.id)
@@ -281,7 +263,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
'skillId' in details && 'skillId' in details &&
typeof details.skillId === 'string' typeof details.skillId === 'string'
) { ) {
skillLoadedInSession = true
onEnvsAdded(await agentService.getSkillEnvs(details.skillId)) onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
const dbSkill = await prisma.skill.findUnique({ const dbSkill = await prisma.skill.findUnique({
where: { id: details.skillId }, where: { id: details.skillId },
@@ -335,23 +316,15 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
} }
} }
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, { const runnerBash = createRunnerBashTool(skillEnvs, {
teamId, teamId,
agentRunnerId: agent?.runnerId, agentRunnerId: agent?.runnerId,
userId, userId,
role, role,
// Non-owner users can only run bash commands required by a loaded skill
restrictedUser: restricted,
getLoadedSkills: () => loadedSkills.values(), getLoadedSkills: () => loadedSkills.values(),
}) })
// When a team has no Runner configured in DB, bash and download_asset are omitted.
// 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 registry = createRegistry()
const bashIncludedFromStart = hasRunner && (isOwner || skillLoadedInSession)
let bashInjected = bashIncludedFromStart
const onSkillLoaded = async (skill: LoadedSkillRef) => { const onSkillLoaded = async (skill: LoadedSkillRef) => {
loadedSkills.set(skill.id, skill) loadedSkills.set(skill.id, skill)
if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) { if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) {
@@ -362,18 +335,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
) )
}) })
} }
if (!restricted || !hasRunner || 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 readSkill = createReadSkillTool( const readSkill = createReadSkillTool(
userId, userId,
@@ -404,7 +365,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
...mediaTools, ...mediaTools,
readSkill, readSkill,
readThread, readThread,
...(bashIncludedFromStart ? [sandboxedBash] : []), ...(hasRunner ? [runnerBash] : []),
...systemTools, ...systemTools,
...customTools, ...customTools,
] ]
@@ -472,10 +433,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
return prompt return prompt
} }
if (restricted) {
prompt += `\n\n${buildRestrictedUserInstructions()}`
}
if (hasRunner && !deniedTools.includes('bash')) { if (hasRunner && !deniedTools.includes('bash')) {
prompt += prompt +=
'\n\n' + '\n\n' +
+1 -1
View File
@@ -67,7 +67,7 @@ export const createReadSkillTool = (
// Retrieve skill content using agentService // Retrieve skill content using agentService
const skillMdContent = await agentService.getSkillContent(params.skillId) const skillMdContent = await agentService.getSkillContent(params.skillId)
// Notify that a skill was successfully loaded (e.g. to enable restricted tools and stage skill on runner) // 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 }) await onSkillLoaded?.({ id: skill.id, assetId: skill.assetId, hash: skill.hash })
return { return {
@@ -1,8 +1,7 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils' import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { runnerService } from '@shumai/core/src/runner' import { runnerService } from '@shumai/core/src/runner'
import { EventEmitter } from 'node:events'
import { beforeEach, describe, expect, it, vi } from 'vitest' import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash' import { createRunnerBashTool } from './runner-bash'
vi.mock('@shumai/core/src/runner', () => ({ vi.mock('@shumai/core/src/runner', () => ({
runnerService: { runnerService: {
@@ -14,8 +13,7 @@ vi.mock('@shumai/core/src/runner', () => ({
}, },
})) }))
describe('createSandboxedBashTool', () => { describe('createRunnerBashTool', () => {
const mockCwd = '/mock/cwd'
const mockTeamId = 'team-1' const mockTeamId = 'team-1'
const mockRunner = { const mockRunner = {
id: 'runner-1', id: 'runner-1',
@@ -38,24 +36,12 @@ describe('createSandboxedBashTool', () => {
) )
}) })
const createMockSignal = () => { const createMockSignal = () => new AbortController().signal
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- signal needs to be partially compatible with AbortSignal
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() const createMockOnUpdate = () => vi.fn()
it('should execute a command on the runner with injected env vars', async () => { it('should execute a command on the runner with injected env vars', async () => {
const tool = createSandboxedBashTool( const tool = createRunnerBashTool(
mockCwd,
{ TEST_ENV: 'test-value' }, { TEST_ENV: 'test-value' },
{ {
teamId: mockTeamId, teamId: mockTeamId,
@@ -78,13 +64,7 @@ describe('createSandboxedBashTool', () => {
const onUpdate = createMockOnUpdate() const onUpdate = createMockOnUpdate()
const signal = createMockSignal() const signal = createMockSignal()
const result = await invokeTool( const result = await invokeTool(tool, '1', { command: 'echo hello' }, signal, onUpdate)
tool,
'1',
{ command: 'echo hello', source: 'user' },
signal,
onUpdate,
)
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null) expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null)
expect(runnerService.exec).toHaveBeenCalledWith( expect(runnerService.exec).toHaveBeenCalledWith(
@@ -95,15 +75,15 @@ describe('createSandboxedBashTool', () => {
collectOutput: false, collectOutput: false,
}), }),
) )
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks expect(result.content).toContainEqual(
expect((result as any).content[0].text).toContain('hello output') expect.objectContaining({ text: expect.stringContaining('hello output') }),
)
expect(onUpdate).toHaveBeenCalled() expect(onUpdate).toHaveBeenCalled()
}) })
it('should stage loaded skills and inputFiles before executing', async () => { it('should stage loaded skills and inputFiles before executing', async () => {
const loadedSkills = [{ id: 'skill-1', assetId: 'asset-1', hash: 'hash-1' }] const loadedSkills = [{ id: 'skill-1', assetId: 'asset-1', hash: 'hash-1' }]
const tool = createSandboxedBashTool( const tool = createRunnerBashTool(
mockCwd,
{}, {},
{ {
teamId: mockTeamId, teamId: mockTeamId,
@@ -126,7 +106,6 @@ describe('createSandboxedBashTool', () => {
'1', '1',
{ {
command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4', command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4',
source: 'user',
inputFiles: ['.pi/generated/gen1/input.png'], inputFiles: ['.pi/generated/gen1/input.png'],
}, },
createMockSignal(), createMockSignal(),
@@ -140,31 +119,12 @@ describe('createSandboxedBashTool', () => {
) )
}) })
it('should block user-requested commands when restrictedUser is enabled', async () => { it('allows editor commands without a source classification', async () => {
const tool = createSandboxedBashTool( const tool = createRunnerBashTool(
mockCwd,
{}, {},
{ {
teamId: mockTeamId, teamId: mockTeamId,
restrictedUser: true, role: 'editor',
},
)
const signal = createMockSignal()
await expect(
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/not permitted for your role/)
expect(runnerService.exec).not.toHaveBeenCalled()
})
it('should allow skill-requested commands when restrictedUser is enabled', async () => {
const tool = createSandboxedBashTool(
mockCwd,
{},
{
teamId: mockTeamId,
restrictedUser: true,
}, },
) )
@@ -181,24 +141,25 @@ describe('createSandboxedBashTool', () => {
}) })
const signal = createMockSignal() const signal = createMockSignal()
const result = await invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal) const result = await invokeTool(tool, '1', { command: 'echo skill' }, signal)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks expect(result.content).toContainEqual(
expect((result as any).content[0].text).toContain('skill output') expect.objectContaining({ text: expect.stringContaining('skill output') }),
)
}) })
it('should handle runner execution errors', async () => { it('should handle runner execution errors', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected')) vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected'))
const signal = createMockSignal() const signal = createMockSignal()
await expect( await expect(
invokeTool(tool, '1', { command: 'fail', source: 'user' }, signal, createMockOnUpdate()), invokeTool(tool, '1', { command: 'fail' }, signal, createMockOnUpdate()),
).rejects.toThrow('Runner disconnected') ).rejects.toThrow('Runner disconnected')
}) })
it('should handle non-zero exit codes', async () => { it('should handle non-zero exit codes', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({ vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1', executionId: 'exec-1',
@@ -211,12 +172,12 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal() const signal = createMockSignal()
await expect( await expect(
invokeTool(tool, '1', { command: 'exit 1', source: 'user' }, signal, createMockOnUpdate()), invokeTool(tool, '1', { command: 'exit 1' }, signal, createMockOnUpdate()),
).rejects.toThrow(/exited with code 1/) ).rejects.toThrow(/exited with code 1/)
}) })
it('should handle timeouts', async () => { it('should handle timeouts', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => { vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
opts.onOutput?.('output before timeout\n', 'stdout') opts.onOutput?.('output before timeout\n', 'stdout')
@@ -234,7 +195,7 @@ describe('createSandboxedBashTool', () => {
const executePromise = invokeTool( const executePromise = invokeTool(
tool, tool,
'1', '1',
{ command: 'sleep 10', timeout: 2, source: 'user' }, { command: 'sleep 10', timeout: 2 },
signal, signal,
createMockOnUpdate(), createMockOnUpdate(),
) )
@@ -244,7 +205,7 @@ describe('createSandboxedBashTool', () => {
}) })
it('should handle abort signals', async () => { it('should handle abort signals', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockResolvedValue({ vi.mocked(runnerService.exec).mockResolvedValue({
executionId: 'exec-1', executionId: 'exec-1',
@@ -257,12 +218,12 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal() const signal = createMockSignal()
await expect( await expect(
invokeTool(tool, '1', { command: 'long-run', source: 'user' }, signal, createMockOnUpdate()), invokeTool(tool, '1', { command: 'long-run' }, signal, createMockOnUpdate()),
).rejects.toThrow(/aborted/) ).rejects.toThrow(/aborted/)
}) })
it('should truncate output exceeding max lines (2000 lines) and report runner log file path', async () => { it('should truncate output exceeding max lines (2000 lines) and report runner log file path', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => { vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const lines: string[] = [] const lines: string[] = []
@@ -283,14 +244,8 @@ describe('createSandboxedBashTool', () => {
}) })
const signal = createMockSignal() const signal = createMockSignal()
const result = await invokeTool( const result = await invokeTool(tool, '1', { command: 'generate lines' }, signal)
tool, const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
'1',
{ command: 'generate lines', source: 'user' },
signal,
)
// 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('line-3000')
expect(text).toContain( expect(text).toContain(
'[Showing lines 1001-3000 of 3000. Full output: .pi/logs/bash-exec1.log]', '[Showing lines 1001-3000 of 3000. Full output: .pi/logs/bash-exec1.log]',
@@ -305,7 +260,7 @@ describe('createSandboxedBashTool', () => {
}) })
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => { it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId }) const tool = createRunnerBashTool({}, { teamId: mockTeamId })
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => { vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
const longLine = 'a'.repeat(60000) const longLine = 'a'.repeat(60000)
@@ -322,14 +277,8 @@ describe('createSandboxedBashTool', () => {
}) })
const signal = createMockSignal() const signal = createMockSignal()
const result = await invokeTool( const result = await invokeTool(tool, '1', { command: 'long single line' }, signal)
tool, const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
'1',
{ command: 'long single line', source: 'user' },
signal,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
const text = (result as any).content[0].text
expect(text).toMatch( expect(text).toMatch(
/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output: \.pi\/logs\/bash-exec2\.log/, /Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output: \.pi\/logs\/bash-exec2\.log/,
) )
@@ -15,19 +15,9 @@ import {
type TruncationResult, type TruncationResult,
} from '../utils/truncate' } 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({ const BashParameters = Type.Object({
command: Type.String({ description: 'The bash command to execute.' }), command: Type.String({ description: 'The bash command to execute.' }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })), timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
source: BashSource,
inputFiles: Type.Optional( inputFiles: Type.Optional(
Type.Union([ Type.Union([
Type.Array(Type.String(), { Type.Array(Type.String(), {
@@ -51,42 +41,30 @@ export interface LoadedSkillRef {
hash: string hash: string
} }
export interface SandboxedBashOptions { export interface RunnerBashOptions {
teamId?: string teamId?: string
agentRunnerId?: string | null agentRunnerId?: string | null
runnerId?: string runnerId?: string
userId?: string userId?: string
role?: TeamMemberRole | null role?: TeamMemberRole | null
/**
* 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
getLoadedSkills?: () => Iterable<LoadedSkillRef> getLoadedSkills?: () => Iterable<LoadedSkillRef>
} }
export const createSandboxedBashTool = ( export const createRunnerBashTool = (
_cwd: string,
skillEnvs: Record<string, string> = {}, skillEnvs: Record<string, string> = {},
options?: SandboxedBashOptions, options?: RunnerBashOptions,
): AgentTool<typeof BashParameters, BashDetails> => { ): AgentTool<typeof BashParameters, BashDetails> => {
return { return {
name: 'bash', name: 'bash',
description: `Execute a bash command on the configured runner environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running. 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".`, description: `Execute a bash command on the configured runner environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
parameters: BashParameters, parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' }, outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async ( execute: async (
{ command, timeout, source, inputFiles }, { command, timeout, inputFiles },
api, api,
context, context,
): Promise<AgentToolResult<BashDetails>> => { ): Promise<AgentToolResult<BashDetails>> => {
const signal = context.abortSignal 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) { if (options?.teamId) {
await quotaService.checkQuota( await quotaService.checkQuota(
{ {
@@ -104,7 +82,7 @@ export const createSandboxedBashTool = (
if (options?.runnerId) { if (options?.runnerId) {
if (!runnerService.isRunnerConnected(options.runnerId)) { if (!runnerService.isRunnerConnected(options.runnerId)) {
throw new Error( throw new Error(
'Runner is currently offline. Please start your runner with "shumai runner start" and try again.', 'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
) )
} }
targetRunnerId = options.runnerId targetRunnerId = options.runnerId
@@ -211,21 +189,19 @@ export const createSandboxedBashTool = (
} }
if (signal?.aborted || execResult.aborted) { if (signal?.aborted || execResult.aborted) {
logger.error({ command, outputText }, 'Sandboxed bash command aborted') logger.error({ command, outputText }, 'Bash command aborted')
throw new Error(appendStatus(outputText, 'Command aborted')) throw new Error(appendStatus(outputText, 'Command aborted'))
} }
if (execResult.timedOut) { if (execResult.timedOut) {
logger.error({ timeout, command, outputText }, 'Sandboxed bash command timed out') logger.error({ timeout, command, outputText }, 'Bash command timed out')
throw new Error( throw new Error(appendStatus(outputText, `Bash command timed out after ${timeout} seconds`))
appendStatus(outputText, `Sandboxed bash command timed out after ${timeout} seconds`),
)
} }
if (execResult.error) { if (execResult.error) {
logger.error( logger.error(
{ error: execResult.error, command, outputText }, { error: execResult.error, command, outputText },
'Sandboxed bash command encountered runner error', 'Bash command encountered runner error',
) )
throw new Error(appendStatus(outputText, execResult.error)) throw new Error(appendStatus(outputText, execResult.error))
} }
@@ -233,13 +209,10 @@ export const createSandboxedBashTool = (
if (execResult.exitCode !== 0 && execResult.exitCode !== null) { if (execResult.exitCode !== 0 && execResult.exitCode !== null) {
logger.error( logger.error(
{ exitCode: execResult.exitCode, command, outputText }, { exitCode: execResult.exitCode, command, outputText },
'Sandboxed bash command exited with failure code', 'Bash command exited with failure code',
) )
throw new Error( throw new Error(
appendStatus( appendStatus(outputText, `Bash command exited with code ${execResult.exitCode}`),
outputText,
`Sandboxed bash command exited with code ${execResult.exitCode}`,
),
) )
} }
+2 -2
View File
@@ -428,11 +428,11 @@ export class RunnerService {
if (!this.isRunnerConnected(resolved.runner.id)) { if (!this.isRunnerConnected(resolved.runner.id)) {
if (resolved.isBoundToAgent) { if (resolved.isBoundToAgent) {
throw new Error( throw new Error(
`Runner "${resolved.runner.name}" is currently offline. Please start the runner ("shumai runner start") and try again.`, `Runner "${resolved.runner.name}" is currently offline. Please start the runner ("shumai-cli runner start") and try again.`,
) )
} }
throw new Error( throw new Error(
`Default runner "${resolved.runner.name}" is currently offline. Please start the runner ("shumai runner start") and try again.`, `Default runner "${resolved.runner.name}" is currently offline. Please start the runner ("shumai-cli runner start") and try again.`,
) )
} }