mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 02:36:33 +00:00
refactor(agent): expose runner bash without skill gating
This commit is contained in:
+12
-14
@@ -5,7 +5,7 @@ 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 { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { createRunnerBashTool } from './tools/runner-bash'
|
||||
|
||||
const mockProviders: DbProviderInfo[] = [
|
||||
{
|
||||
@@ -92,19 +92,17 @@ describe('Concurrent Runner Sessions', () => {
|
||||
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])
|
||||
const execA = invokeTool(tool, 'call-a', {
|
||||
command: 'echo session-a',
|
||||
source: 'skill',
|
||||
})
|
||||
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',
|
||||
source: 'skill',
|
||||
})
|
||||
await vi.waitFor(() => expect(conn.sent.length).toBe(3))
|
||||
const msgB = JSON.parse(conn.sent[2])
|
||||
@@ -160,10 +158,12 @@ describe('Concurrent Runner Sessions', () => {
|
||||
)
|
||||
|
||||
const [resA, resB] = await Promise.all([execA, execB])
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content blocks
|
||||
expect((resA as any).content[0].text).toContain('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(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)
|
||||
})
|
||||
@@ -202,16 +202,14 @@ describe('Concurrent Runner Sessions', () => {
|
||||
gpuConn.ws,
|
||||
)
|
||||
|
||||
const defaultTool = createSandboxedBashTool(
|
||||
'/mock/cwd',
|
||||
const defaultTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
agentRunnerId: null,
|
||||
},
|
||||
)
|
||||
const gpuTool = createSandboxedBashTool(
|
||||
'/mock/cwd',
|
||||
const gpuTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
@@ -219,8 +217,8 @@ describe('Concurrent Runner Sessions', () => {
|
||||
},
|
||||
)
|
||||
|
||||
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a', source: 'user' })
|
||||
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi', source: 'user' })
|
||||
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')
|
||||
@@ -10,7 +10,6 @@ import { type TSchema } from 'typebox'
|
||||
import { Value } from 'typebox/value'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildRestrictedUserInstructions,
|
||||
createAgentSession,
|
||||
formatSkillsForPrompt,
|
||||
getModelFromDb,
|
||||
@@ -171,20 +170,7 @@ describe('Runner tool availability & skill staging integration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRestrictedUserInstructions', () => {
|
||||
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', () => {
|
||||
describe('createAgentSession runner bash policy', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
afterEach(() => {
|
||||
@@ -262,21 +248,21 @@ describe('createAgentSession bash restriction for non-owner users', () => {
|
||||
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 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)
|
||||
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)(
|
||||
'should exclude the bash tool initially for %s users',
|
||||
'exposes bash immediately for %s users without reading a skill',
|
||||
async (role) => {
|
||||
const { harness } = await setupSession({ role })
|
||||
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)
|
||||
},
|
||||
)
|
||||
@@ -346,7 +332,7 @@ describe('createAgentSession bash restriction for non-owner users', () => {
|
||||
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 skill = await prisma.skill.create({
|
||||
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')
|
||||
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)
|
||||
|
||||
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 skill = await prisma.skill.create({
|
||||
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)
|
||||
})
|
||||
|
||||
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 prompt = await await getAgentPrompt(harness)
|
||||
expect(prompt).toContain('# Restricted User Context')
|
||||
expect(prompt).toContain('source="user" will be rejected')
|
||||
expect(prompt).not.toContain('# Restricted User Context')
|
||||
expect(prompt).not.toContain('source="user" will be rejected')
|
||||
})
|
||||
|
||||
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 (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
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
|
||||
|
||||
@@ -68,7 +68,7 @@ async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<strin
|
||||
if (ctx?.runnerId && !ctx.teamId) {
|
||||
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
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
|
||||
|
||||
@@ -44,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, type LoadedSkillRef } from './tools/sandboxed-bash'
|
||||
import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
|
||||
|
||||
const activeHarnesses = new Set<Harness>()
|
||||
|
||||
@@ -152,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,
|
||||
@@ -203,8 +188,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
getModelFromDb(params.providers, providerName, modelId)
|
||||
|
||||
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,7 +245,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const loadedSkills = new Map<string, LoadedSkillRef>()
|
||||
|
||||
// Restore env variables and loaded skill refs from previously loaded skills in this session
|
||||
let skillLoadedInSession = false
|
||||
if (sessionId) {
|
||||
try {
|
||||
const entries = await agentSessionService.getEntries(record.id)
|
||||
@@ -281,7 +263,6 @@ 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 },
|
||||
@@ -335,23 +316,15 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
|
||||
const runnerBash = createRunnerBashTool(skillEnvs, {
|
||||
teamId,
|
||||
agentRunnerId: agent?.runnerId,
|
||||
userId,
|
||||
role,
|
||||
// Non-owner users can only run bash commands required by a loaded skill
|
||||
restrictedUser: restricted,
|
||||
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 bashIncludedFromStart = hasRunner && (isOwner || skillLoadedInSession)
|
||||
let bashInjected = bashIncludedFromStart
|
||||
const onSkillLoaded = async (skill: LoadedSkillRef) => {
|
||||
loadedSkills.set(skill.id, skill)
|
||||
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(
|
||||
userId,
|
||||
@@ -404,7 +365,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
...(bashIncludedFromStart ? [sandboxedBash] : []),
|
||||
...(hasRunner ? [runnerBash] : []),
|
||||
...systemTools,
|
||||
...customTools,
|
||||
]
|
||||
@@ -472,10 +433,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
return prompt
|
||||
}
|
||||
|
||||
if (restricted) {
|
||||
prompt += `\n\n${buildRestrictedUserInstructions()}`
|
||||
}
|
||||
|
||||
if (hasRunner && !deniedTools.includes('bash')) {
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
|
||||
@@ -67,7 +67,7 @@ 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 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 })
|
||||
|
||||
return {
|
||||
|
||||
+30
-81
@@ -1,8 +1,7 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSandboxedBashTool } from './sandboxed-bash'
|
||||
import { createRunnerBashTool } from './runner-bash'
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
@@ -14,8 +13,7 @@ vi.mock('@shumai/core/src/runner', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createSandboxedBashTool', () => {
|
||||
const mockCwd = '/mock/cwd'
|
||||
describe('createRunnerBashTool', () => {
|
||||
const mockTeamId = 'team-1'
|
||||
const mockRunner = {
|
||||
id: 'runner-1',
|
||||
@@ -38,24 +36,12 @@ describe('createSandboxedBashTool', () => {
|
||||
)
|
||||
})
|
||||
|
||||
const createMockSignal = () => {
|
||||
// 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 createMockSignal = () => new AbortController().signal
|
||||
|
||||
const createMockOnUpdate = () => vi.fn()
|
||||
|
||||
it('should execute a command on the runner with injected env vars', async () => {
|
||||
const tool = createSandboxedBashTool(
|
||||
mockCwd,
|
||||
const tool = createRunnerBashTool(
|
||||
{ TEST_ENV: 'test-value' },
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
@@ -78,13 +64,7 @@ describe('createSandboxedBashTool', () => {
|
||||
const onUpdate = createMockOnUpdate()
|
||||
const signal = createMockSignal()
|
||||
|
||||
const result = await invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'echo hello', source: 'user' },
|
||||
signal,
|
||||
onUpdate,
|
||||
)
|
||||
const result = await invokeTool(tool, '1', { command: 'echo hello' }, signal, onUpdate)
|
||||
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null)
|
||||
expect(runnerService.exec).toHaveBeenCalledWith(
|
||||
@@ -95,15 +75,15 @@ describe('createSandboxedBashTool', () => {
|
||||
collectOutput: false,
|
||||
}),
|
||||
)
|
||||
// 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')
|
||||
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 = createSandboxedBashTool(
|
||||
mockCwd,
|
||||
const tool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
@@ -126,7 +106,6 @@ describe('createSandboxedBashTool', () => {
|
||||
'1',
|
||||
{
|
||||
command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4',
|
||||
source: 'user',
|
||||
inputFiles: ['.pi/generated/gen1/input.png'],
|
||||
},
|
||||
createMockSignal(),
|
||||
@@ -140,31 +119,12 @@ describe('createSandboxedBashTool', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should block user-requested commands when restrictedUser is enabled', async () => {
|
||||
const tool = createSandboxedBashTool(
|
||||
mockCwd,
|
||||
it('allows editor commands without a source classification', async () => {
|
||||
const tool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
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(runnerService.exec).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should allow skill-requested commands when restrictedUser is enabled', async () => {
|
||||
const tool = createSandboxedBashTool(
|
||||
mockCwd,
|
||||
{},
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
restrictedUser: true,
|
||||
role: 'editor',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -181,24 +141,25 @@ describe('createSandboxedBashTool', () => {
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
|
||||
// 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')
|
||||
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 = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected'))
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'fail', source: 'user' }, signal, createMockOnUpdate()),
|
||||
invokeTool(tool, '1', { command: 'fail' }, signal, createMockOnUpdate()),
|
||||
).rejects.toThrow('Runner disconnected')
|
||||
})
|
||||
|
||||
it('should handle non-zero exit codes', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockResolvedValue({
|
||||
executionId: 'exec-1',
|
||||
@@ -211,12 +172,12 @@ describe('createSandboxedBashTool', () => {
|
||||
|
||||
const signal = createMockSignal()
|
||||
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/)
|
||||
})
|
||||
|
||||
it('should handle timeouts', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
opts.onOutput?.('output before timeout\n', 'stdout')
|
||||
@@ -234,7 +195,7 @@ describe('createSandboxedBashTool', () => {
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'sleep 10', timeout: 2, source: 'user' },
|
||||
{ command: 'sleep 10', timeout: 2 },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
@@ -244,7 +205,7 @@ describe('createSandboxedBashTool', () => {
|
||||
})
|
||||
|
||||
it('should handle abort signals', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockResolvedValue({
|
||||
executionId: 'exec-1',
|
||||
@@ -257,12 +218,12 @@ describe('createSandboxedBashTool', () => {
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'long-run', source: 'user' }, signal, createMockOnUpdate()),
|
||||
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 = createSandboxedBashTool(mockCwd, {}, { teamId: mockTeamId })
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
const lines: string[] = []
|
||||
@@ -283,14 +244,8 @@ describe('createSandboxedBashTool', () => {
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(
|
||||
tool,
|
||||
'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
|
||||
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]',
|
||||
@@ -305,7 +260,7 @@ describe('createSandboxedBashTool', () => {
|
||||
})
|
||||
|
||||
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) => {
|
||||
const longLine = 'a'.repeat(60000)
|
||||
@@ -322,14 +277,8 @@ describe('createSandboxedBashTool', () => {
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(
|
||||
tool,
|
||||
'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
|
||||
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/,
|
||||
)
|
||||
+12
-39
@@ -15,19 +15,9 @@ import {
|
||||
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,
|
||||
inputFiles: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Array(Type.String(), {
|
||||
@@ -51,42 +41,30 @@ export interface LoadedSkillRef {
|
||||
hash: string
|
||||
}
|
||||
|
||||
export interface SandboxedBashOptions {
|
||||
export interface RunnerBashOptions {
|
||||
teamId?: string
|
||||
agentRunnerId?: string | null
|
||||
runnerId?: string
|
||||
userId?: string
|
||||
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>
|
||||
}
|
||||
|
||||
export const createSandboxedBashTool = (
|
||||
_cwd: string,
|
||||
export const createRunnerBashTool = (
|
||||
skillEnvs: Record<string, string> = {},
|
||||
options?: SandboxedBashOptions,
|
||||
options?: RunnerBashOptions,
|
||||
): AgentTool<typeof BashParameters, BashDetails> => {
|
||||
return {
|
||||
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,
|
||||
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
|
||||
execute: async (
|
||||
{ command, timeout, source, inputFiles },
|
||||
{ command, timeout, inputFiles },
|
||||
api,
|
||||
context,
|
||||
): Promise<AgentToolResult<BashDetails>> => {
|
||||
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(
|
||||
{
|
||||
@@ -104,7 +82,7 @@ export const createSandboxedBashTool = (
|
||||
if (options?.runnerId) {
|
||||
if (!runnerService.isRunnerConnected(options.runnerId)) {
|
||||
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
|
||||
@@ -211,21 +189,19 @@ export const createSandboxedBashTool = (
|
||||
}
|
||||
|
||||
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'))
|
||||
}
|
||||
|
||||
if (execResult.timedOut) {
|
||||
logger.error({ timeout, command, outputText }, 'Sandboxed bash command timed out')
|
||||
throw new Error(
|
||||
appendStatus(outputText, `Sandboxed bash command timed out after ${timeout} seconds`),
|
||||
)
|
||||
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 },
|
||||
'Sandboxed bash command encountered runner error',
|
||||
'Bash command encountered runner error',
|
||||
)
|
||||
throw new Error(appendStatus(outputText, execResult.error))
|
||||
}
|
||||
@@ -233,13 +209,10 @@ export const createSandboxedBashTool = (
|
||||
if (execResult.exitCode !== 0 && execResult.exitCode !== null) {
|
||||
logger.error(
|
||||
{ exitCode: execResult.exitCode, command, outputText },
|
||||
'Sandboxed bash command exited with failure code',
|
||||
'Bash command exited with failure code',
|
||||
)
|
||||
throw new Error(
|
||||
appendStatus(
|
||||
outputText,
|
||||
`Sandboxed bash command exited with code ${execResult.exitCode}`,
|
||||
),
|
||||
appendStatus(outputText, `Bash command exited with code ${execResult.exitCode}`),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -428,11 +428,11 @@ export class RunnerService {
|
||||
if (!this.isRunnerConnected(resolved.runner.id)) {
|
||||
if (resolved.isBoundToAgent) {
|
||||
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(
|
||||
`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.`,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user