2026-08-04 16:08:04 +08:00
|
|
|
import { describe, it, expect, vi, afterEach } from 'vitest'
|
2026-07-22 16:27:58 +08:00
|
|
|
import {
|
|
|
|
|
formatSkillsForPrompt,
|
|
|
|
|
createAgentSession,
|
|
|
|
|
getModelFromDb,
|
2026-08-04 16:08:04 +08:00
|
|
|
buildRestrictedUserInstructions,
|
2026-07-22 16:27:58 +08:00
|
|
|
type DbProviderInfo,
|
|
|
|
|
} from './index'
|
2026-06-15 09:28:11 +08:00
|
|
|
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
2026-06-15 10:36:01 +08:00
|
|
|
import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime'
|
2026-06-15 09:28:11 +08:00
|
|
|
import { prisma } from '@shumai/db'
|
|
|
|
|
import { setupTestDbHooks } from '@shumai/db/test'
|
2026-05-31 10:20:20 +08:00
|
|
|
import * as path from 'path'
|
2026-06-15 09:28:11 +08:00
|
|
|
import * as childProcess from 'node:child_process'
|
2026-08-04 16:08:04 +08:00
|
|
|
import * as fs from 'fs'
|
2026-06-15 09:28:11 +08:00
|
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
|
let mockSpawn: any = null
|
|
|
|
|
|
|
|
|
|
vi.mock('node:child_process', async () => {
|
|
|
|
|
const actual = (await vi.importActual('node:child_process')) as typeof childProcess
|
|
|
|
|
return {
|
|
|
|
|
...actual,
|
|
|
|
|
spawn: (...args: Parameters<typeof childProcess.spawn>) => {
|
|
|
|
|
if (mockSpawn) {
|
|
|
|
|
return mockSpawn(...args)
|
|
|
|
|
}
|
|
|
|
|
return actual.spawn(...args)
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-05-31 10:20:20 +08:00
|
|
|
|
2026-08-04 16:08:04 +08:00
|
|
|
// Mock fs so tests can stub skill content loading (matching read-skill.test.ts)
|
|
|
|
|
vi.mock('fs')
|
|
|
|
|
|
2026-08-02 14:26:03 +08:00
|
|
|
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,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
|
2026-05-31 10:20:20 +08:00
|
|
|
describe('formatSkillsForPrompt', () => {
|
|
|
|
|
it('should return empty string if skills array is empty', () => {
|
|
|
|
|
expect(formatSkillsForPrompt([])).toBe('')
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should format skills into the XML structure with absolute paths and escaped characters', () => {
|
|
|
|
|
const skills = [
|
|
|
|
|
{
|
|
|
|
|
id: 'skill-1',
|
|
|
|
|
name: 'Deploy & Test',
|
|
|
|
|
description: 'Deploys code <deploy> and "runs" tests.',
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
const expectedLocation = path.join(process.cwd(), '.pi', 'skills', 'skill-1', 'SKILL.md')
|
|
|
|
|
const result = formatSkillsForPrompt(skills)
|
|
|
|
|
|
|
|
|
|
// Verify lines and XML elements
|
|
|
|
|
expect(result).toContain('<available_skills>')
|
|
|
|
|
expect(result).toContain('<skill>')
|
2026-07-21 10:42:01 +08:00
|
|
|
expect(result).toContain('<id>skill-1</id>')
|
2026-05-31 10:20:20 +08:00
|
|
|
expect(result).toContain('<name>Deploy & Test</name>')
|
|
|
|
|
expect(result).toContain(
|
|
|
|
|
'<description>Deploys code <deploy> and "runs" tests.</description>',
|
|
|
|
|
)
|
|
|
|
|
expect(result).toContain(`<location>${expectedLocation}</location>`)
|
|
|
|
|
expect(result).toContain('</skill>')
|
|
|
|
|
expect(result).toContain('</available_skills>')
|
|
|
|
|
})
|
|
|
|
|
})
|
2026-06-15 09:28:11 +08:00
|
|
|
|
|
|
|
|
describe('Sandbox Network isolation integration', () => {
|
|
|
|
|
setupTestDbHooks()
|
|
|
|
|
|
|
|
|
|
it('should register callback that pushes blocked hosts to database and propagates to bash tool', async () => {
|
|
|
|
|
// 1. Create a team
|
|
|
|
|
const team = await prisma.team.create({
|
|
|
|
|
data: { name: 'Test Sandbox Team' },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Ensure agent user and agent exist in database to avoid foreign key violation
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent',
|
|
|
|
|
name: 'Ai Agent',
|
|
|
|
|
email: 'test-agent@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: {
|
|
|
|
|
provider: 'openai',
|
|
|
|
|
model: 'gpt-4',
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// 2. Mock / spy SandboxManager
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
const wrapSpy = vi
|
|
|
|
|
.spyOn(SandboxManager, 'wrapWithSandbox')
|
|
|
|
|
.mockImplementation(async (cmd) => cmd)
|
|
|
|
|
|
|
|
|
|
// 3. Call createAgentSession
|
|
|
|
|
await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-06-15 09:28:11 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// 4. Verify SandboxManager.initialize was called and extract the callback
|
|
|
|
|
expect(initializeSpy).toHaveBeenCalled()
|
|
|
|
|
const callback = initializeSpy.mock.calls[0][1]
|
|
|
|
|
expect(callback).toBeDefined()
|
|
|
|
|
|
|
|
|
|
// 5. Trigger the callback with a blocked host
|
|
|
|
|
const result = await callback!({ host: 'blocked-api.com', port: 443 })
|
|
|
|
|
expect(result).toBe(false) // should always return false to block
|
|
|
|
|
|
|
|
|
|
// 6. Verify it was pushed to database
|
|
|
|
|
const sandbox = await prisma.sandbox.findUnique({
|
|
|
|
|
where: { teamId: team.id },
|
|
|
|
|
})
|
2026-06-15 10:52:53 +08:00
|
|
|
expect(sandbox?.pendingDomains).toContain('blocked-api.com')
|
2026-06-15 09:28:11 +08:00
|
|
|
|
|
|
|
|
// 7. Verify that if the bash tool is run while a domain is blocked, it rejects with correct error
|
|
|
|
|
const sandboxState = { blockedHost: '' }
|
|
|
|
|
const bashTool = createSandboxedBashTool(
|
|
|
|
|
process.cwd(),
|
|
|
|
|
{},
|
|
|
|
|
{
|
|
|
|
|
getBlockedHost: () => sandboxState.blockedHost,
|
|
|
|
|
clearBlockedHost: () => {
|
|
|
|
|
sandboxState.blockedHost = ''
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Mock spawn to simulate process exit and trigger network block
|
|
|
|
|
mockSpawn = () => {
|
2026-06-15 10:52:53 +08:00
|
|
|
sandboxState.blockedHost = 'blocked-api.com'
|
2026-06-15 09:28:11 +08:00
|
|
|
const mockChild = {
|
|
|
|
|
pid: 123,
|
|
|
|
|
stdout: { on: vi.fn() },
|
|
|
|
|
stderr: { on: vi.fn() },
|
|
|
|
|
on: vi.fn((event: string, cb: (code: number) => void) => {
|
|
|
|
|
if (event === 'close') {
|
|
|
|
|
setTimeout(() => cb(1), 10)
|
|
|
|
|
}
|
|
|
|
|
}),
|
|
|
|
|
} as unknown as childProcess.ChildProcess
|
|
|
|
|
return mockChild
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-04 16:08:04 +08:00
|
|
|
const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com', source: 'user' })
|
2026-06-15 09:28:11 +08:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await expect(bashPromise).rejects.toThrow(
|
2026-06-15 10:52:53 +08:00
|
|
|
'Network request to blocked-api.com is blocked, please ask admin to allow it in sandbox settings.',
|
2026-06-15 09:28:11 +08:00
|
|
|
)
|
|
|
|
|
} finally {
|
|
|
|
|
mockSpawn = null
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
wrapSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-06-15 10:36:01 +08:00
|
|
|
|
|
|
|
|
it('should correctly route sandbox callback to the active session when multiple sessions are created sequentially', async () => {
|
|
|
|
|
// 1. Create two teams
|
|
|
|
|
const team1 = await prisma.team.create({
|
|
|
|
|
data: { name: 'Team 1' },
|
|
|
|
|
})
|
|
|
|
|
const team2 = await prisma.team.create({
|
|
|
|
|
data: { name: 'Team 2' },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Ensure agent user and agents exist in database
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'agent-1',
|
|
|
|
|
name: 'Ai Agent 1',
|
|
|
|
|
email: 'agent1@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'agent-2',
|
|
|
|
|
name: 'Ai Agent 2',
|
|
|
|
|
email: 'agent2@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'agent-1',
|
|
|
|
|
teamId: team1.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'openai', model: 'gpt-4' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'agent-2',
|
|
|
|
|
teamId: team2.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'openai', model: 'gpt-4' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Mock SandboxManager.initialize to behave like a process-global singleton
|
|
|
|
|
let registeredCallback: SandboxAskCallback | null = null
|
2026-06-15 15:37:10 +08:00
|
|
|
const initializeSpy = vi
|
|
|
|
|
.spyOn(SandboxManager, 'initialize')
|
|
|
|
|
.mockImplementation(async (config, cb) => {
|
|
|
|
|
if (!registeredCallback) {
|
|
|
|
|
registeredCallback = cb || null
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-06-15 10:36:01 +08:00
|
|
|
const resetSpy = vi.spyOn(SandboxManager, 'reset').mockImplementation(async () => {
|
|
|
|
|
// In the real SandboxManager, reset clears the global initialization promise and servers,
|
|
|
|
|
// which allows subsequent initialize calls to register a new callback.
|
|
|
|
|
registeredCallback = null
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// 2. Call createAgentSession for Session 1
|
|
|
|
|
await createAgentSession({
|
|
|
|
|
teamId: team1.id,
|
|
|
|
|
agentId: 'agent-1',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-06-15 10:36:01 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// 3. Call createAgentSession for Session 2
|
|
|
|
|
await createAgentSession({
|
|
|
|
|
teamId: team2.id,
|
|
|
|
|
agentId: 'agent-2',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-06-15 10:36:01 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
expect(registeredCallback).toBeDefined()
|
|
|
|
|
|
|
|
|
|
// 4. Trigger the globally registered callback (which is from Session 1)
|
|
|
|
|
const result = await registeredCallback!({ host: 'blocked-for-session-2.com', port: 443 })
|
|
|
|
|
expect(result).toBe(false)
|
|
|
|
|
|
|
|
|
|
// 5. Verify that the pending domain was pushed to the DB record of Team 2
|
|
|
|
|
const sandbox2 = await prisma.sandbox.findUnique({
|
|
|
|
|
where: { teamId: team2.id },
|
|
|
|
|
})
|
2026-06-15 10:52:53 +08:00
|
|
|
expect(sandbox2?.pendingDomains).toContain('blocked-for-session-2.com')
|
2026-06-15 10:36:01 +08:00
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
resetSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-06-22 09:58:35 +08:00
|
|
|
|
|
|
|
|
it('should pass thinkingLevel to AgentHarness and default to off', async () => {
|
|
|
|
|
const team = await prisma.team.create({
|
|
|
|
|
data: { name: 'Test Team' },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-1',
|
|
|
|
|
name: 'Agent 1',
|
|
|
|
|
email: 'agent1@test.com',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-1',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'google', model: 'gemini' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-2',
|
|
|
|
|
name: 'Agent 2',
|
|
|
|
|
email: 'agent2@test.com',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-2',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'google', model: 'gemini' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
try {
|
|
|
|
|
// Call createAgentSession with thinkingLevel
|
|
|
|
|
const { harness: harnessHigh } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-1',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-06-22 09:58:35 +08:00
|
|
|
thinkingLevel: 'high',
|
|
|
|
|
})
|
|
|
|
|
expect(harnessHigh.getThinkingLevel()).toBe('high')
|
|
|
|
|
|
|
|
|
|
// Call createAgentSession without thinkingLevel
|
|
|
|
|
const { harness: harnessDefault } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-2',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-06-22 09:58:35 +08:00
|
|
|
})
|
|
|
|
|
expect(harnessDefault.getThinkingLevel()).toBe('off')
|
|
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-07-16 15:12:26 +08:00
|
|
|
|
2026-08-01 09:49:43 +08:00
|
|
|
it('should pass retry configuration to AgentHarness', async () => {
|
|
|
|
|
const team = await prisma.team.create({
|
|
|
|
|
data: { name: 'Test Team Retry' },
|
|
|
|
|
})
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-retry',
|
|
|
|
|
name: 'Agent Retry',
|
|
|
|
|
email: 'agent-retry@test.com',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-retry',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'google', model: 'gemini' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
try {
|
|
|
|
|
const { harness } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-retry',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-08-01 09:49:43 +08:00
|
|
|
maxRetries: 5,
|
|
|
|
|
baseDelayMs: 1500,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// @ts-expect-error accessing private property for verification
|
|
|
|
|
expect(harness.streamOptions?.maxRetries).toBe(5)
|
|
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
2026-07-16 15:12:26 +08:00
|
|
|
it('should filter out denied tools from AgentHarness', async () => {
|
|
|
|
|
const team = await prisma.team.create({
|
|
|
|
|
data: { name: 'Test Team 3' },
|
|
|
|
|
})
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-3',
|
|
|
|
|
name: 'Agent 3',
|
|
|
|
|
email: 'agent3@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-3',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'google', model: 'gemini', deniedTools: ['bash'] },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
try {
|
|
|
|
|
const { harness } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-3',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-07-16 15:12:26 +08:00
|
|
|
})
|
|
|
|
|
const tools = harness.getTools()
|
|
|
|
|
const bashTool = tools.find((t) => t.name === 'bash')
|
|
|
|
|
expect(bashTool).toBeUndefined()
|
|
|
|
|
const readSkillTool = tools.find((t) => t.name === 'read_skill')
|
|
|
|
|
expect(readSkillTool).toBeDefined()
|
|
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
2026-06-15 09:28:11 +08:00
|
|
|
})
|
2026-07-22 16:09:36 +08:00
|
|
|
|
|
|
|
|
describe('getModelFromDb', () => {
|
|
|
|
|
it('should correctly initialize non-built-in model with provider and id', () => {
|
|
|
|
|
const providers: DbProviderInfo[] = [
|
|
|
|
|
{
|
|
|
|
|
name: 'google',
|
|
|
|
|
config: { api: 'google-generative-ai', apiKey: 'GOOGLE_API_KEY' },
|
|
|
|
|
models: [
|
|
|
|
|
{
|
|
|
|
|
modelId: 'non-existent-or-future-model',
|
|
|
|
|
name: 'Future Model',
|
|
|
|
|
config: {
|
|
|
|
|
api: 'google-generative-ai',
|
|
|
|
|
reasoning: false,
|
|
|
|
|
input: ['text'],
|
|
|
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
|
|
|
contextWindow: 8192,
|
|
|
|
|
maxTokens: 4096,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
const model = getModelFromDb(providers, 'google', 'non-existent-or-future-model')
|
|
|
|
|
|
|
|
|
|
expect(model).toBeDefined()
|
|
|
|
|
expect(model?.id).toBe('non-existent-or-future-model')
|
|
|
|
|
expect(model?.provider).toBe('google')
|
|
|
|
|
expect(model?.api).toBe('google-generative-ai')
|
|
|
|
|
})
|
2026-08-02 14:26:03 +08:00
|
|
|
|
|
|
|
|
it('should throw an error when provider or model is not found in database configuration', () => {
|
|
|
|
|
expect(() => getModelFromDb([], 'google', 'non-existent')).toThrow(
|
|
|
|
|
'Provider "google" or model "non-existent" not found in database configuration',
|
|
|
|
|
)
|
|
|
|
|
})
|
2026-07-22 16:09:36 +08:00
|
|
|
})
|
2026-07-28 18:27:32 +08:00
|
|
|
|
|
|
|
|
describe('createAgentSession sandbox options', () => {
|
|
|
|
|
setupTestDbHooks()
|
|
|
|
|
|
|
|
|
|
it('should set enableWeakerNestedSandbox based on ENABLE_WEAKER_NESTED_SANDBOX env var', async () => {
|
|
|
|
|
const team = await prisma.team.create({
|
|
|
|
|
data: { name: 'Test Sandbox Team Env' },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-env',
|
|
|
|
|
name: 'Ai Agent Env',
|
|
|
|
|
email: 'test-agent-env@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'test-agent-env',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: {
|
|
|
|
|
provider: 'openai',
|
|
|
|
|
model: 'gpt-4',
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
vi.spyOn(SandboxManager, 'wrapWithSandbox').mockImplementation(async (cmd) => cmd)
|
|
|
|
|
|
|
|
|
|
// Default should be false when env var is unset
|
|
|
|
|
const oldEnv = process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
|
|
|
|
delete process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
|
|
|
|
await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-env',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-07-28 18:27:32 +08:00
|
|
|
})
|
|
|
|
|
expect(initializeSpy).toHaveBeenCalledWith(
|
|
|
|
|
expect.objectContaining({ enableWeakerNestedSandbox: false }),
|
|
|
|
|
expect.any(Function),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Should be true when env var is 'true'
|
|
|
|
|
process.env.ENABLE_WEAKER_NESTED_SANDBOX = 'true'
|
|
|
|
|
await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'test-agent-env',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
2026-08-02 14:26:03 +08:00
|
|
|
providers: mockProviders,
|
2026-07-28 18:27:32 +08:00
|
|
|
})
|
|
|
|
|
expect(initializeSpy).toHaveBeenLastCalledWith(
|
|
|
|
|
expect.objectContaining({ enableWeakerNestedSandbox: true }),
|
|
|
|
|
expect.any(Function),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if (oldEnv !== undefined) {
|
|
|
|
|
process.env.ENABLE_WEAKER_NESTED_SANDBOX = oldEnv
|
|
|
|
|
} else {
|
|
|
|
|
delete process.env.ENABLE_WEAKER_NESTED_SANDBOX
|
|
|
|
|
}
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
})
|
|
|
|
|
})
|
2026-08-04 16:08:04 +08:00
|
|
|
|
|
|
|
|
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', () => {
|
|
|
|
|
setupTestDbHooks()
|
|
|
|
|
|
|
|
|
|
afterEach(() => {
|
|
|
|
|
vi.restoreAllMocks()
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
type TestHarness = Awaited<ReturnType<typeof createAgentSession>>['harness']
|
|
|
|
|
|
|
|
|
|
async function setupSession(opts: {
|
2026-08-04 16:26:16 +08:00
|
|
|
role: 'owner' | 'editor' | 'reviewer' | 'none' | 'non-member'
|
2026-08-04 16:08:04 +08:00
|
|
|
deniedTools?: string[]
|
|
|
|
|
sessionId?: string
|
|
|
|
|
}): Promise<{ team: { id: string }; userId?: string; harness: TestHarness }> {
|
|
|
|
|
const team = await prisma.team.create({ data: { name: 'Bash Restriction Team' } })
|
|
|
|
|
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'bash-agent',
|
|
|
|
|
name: 'Ai Agent Bash',
|
|
|
|
|
email: 'bash-agent@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'bash-agent',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: {
|
|
|
|
|
provider: 'google',
|
|
|
|
|
model: 'gemini',
|
|
|
|
|
...(opts.deniedTools ? { deniedTools: opts.deniedTools } : {}),
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
let userId: string | undefined
|
2026-08-04 16:26:16 +08:00
|
|
|
if (opts.role === 'non-member') {
|
|
|
|
|
const user = await prisma.user.create({
|
|
|
|
|
data: { name: 'Non Member', email: 'non-member@shumai.ai' },
|
|
|
|
|
})
|
|
|
|
|
userId = user.id // no teamMember record created
|
|
|
|
|
} else if (opts.role !== 'none') {
|
2026-08-04 16:08:04 +08:00
|
|
|
const user = await prisma.user.create({
|
|
|
|
|
data: { name: 'Bash User', email: 'bash-user@shumai.ai' },
|
|
|
|
|
})
|
|
|
|
|
await prisma.teamMember.create({
|
|
|
|
|
data: { teamId: team.id, userId: user.id, role: opts.role },
|
|
|
|
|
})
|
|
|
|
|
userId = user.id
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
try {
|
|
|
|
|
const { harness } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'bash-agent',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
|
|
|
|
providers: mockProviders,
|
|
|
|
|
userId,
|
|
|
|
|
sessionId: opts.sessionId,
|
|
|
|
|
})
|
|
|
|
|
return { team, userId, harness }
|
|
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
it('should include the bash tool from the start for team owners', async () => {
|
|
|
|
|
const { harness } = await setupSession({ role: 'owner' })
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should include the bash tool from the start when there is no user context', async () => {
|
|
|
|
|
const { harness } = await setupSession({ role: 'none' })
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
|
|
|
|
|
})
|
|
|
|
|
|
2026-08-04 16:26:16 +08:00
|
|
|
it('should treat a user who is not a team member as restricted (fail-closed)', async () => {
|
|
|
|
|
const { harness } = await setupSession({ role: 'non-member' })
|
|
|
|
|
const tools = harness.getTools()
|
|
|
|
|
expect(tools.some((t) => t.name === 'bash')).toBe(false)
|
|
|
|
|
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
|
|
|
|
|
// @ts-expect-error accessing private property for verification
|
|
|
|
|
const prompt = await harness.systemPrompt()
|
|
|
|
|
expect(prompt).toContain('# Restricted User Context')
|
|
|
|
|
})
|
|
|
|
|
|
2026-08-04 16:08:04 +08:00
|
|
|
it.each(['editor', 'reviewer'] as const)(
|
|
|
|
|
'should exclude the bash tool initially for %s users',
|
|
|
|
|
async (role) => {
|
|
|
|
|
const { harness } = await setupSession({ role })
|
|
|
|
|
const tools = harness.getTools()
|
|
|
|
|
expect(tools.some((t) => t.name === 'bash')).toBe(false)
|
|
|
|
|
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
it('should include the bash tool from the start when a skill was already loaded earlier in the session', async () => {
|
|
|
|
|
const team = await prisma.team.create({ data: { name: 'Restore Team' } })
|
|
|
|
|
const user = await prisma.user.create({
|
|
|
|
|
data: { name: 'Restore User', email: 'restore@shumai.ai' },
|
|
|
|
|
})
|
|
|
|
|
await prisma.teamMember.create({
|
|
|
|
|
data: { teamId: team.id, userId: user.id, role: 'reviewer' },
|
|
|
|
|
})
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'bash-agent-restore',
|
|
|
|
|
name: 'Ai Agent Restore',
|
|
|
|
|
email: 'bash-agent-restore@shumai.ai',
|
|
|
|
|
type: 'agent',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agent.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'bash-agent-restore',
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
type: 'chat',
|
|
|
|
|
config: { provider: 'google', model: 'gemini' },
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const session = await prisma.agentSession.create({
|
|
|
|
|
data: {
|
|
|
|
|
agentId: 'bash-agent-restore',
|
|
|
|
|
userId: user.id,
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
type: 'chat',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
await prisma.agentSessionEntry.create({
|
|
|
|
|
data: {
|
|
|
|
|
id: 'restore-entry-1',
|
|
|
|
|
sessionId: session.id,
|
|
|
|
|
type: 'message',
|
|
|
|
|
data: {
|
|
|
|
|
message: {
|
|
|
|
|
role: 'toolResult',
|
|
|
|
|
content: [{ type: 'text', text: 'skill content restored' }],
|
|
|
|
|
toolName: 'read_skill',
|
|
|
|
|
isError: false,
|
|
|
|
|
details: { skillId: 'previously-loaded-skill' },
|
|
|
|
|
timestamp: Date.now(),
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
|
|
|
|
try {
|
|
|
|
|
const { harness } = await createAgentSession({
|
|
|
|
|
teamId: team.id,
|
|
|
|
|
agentId: 'bash-agent-restore',
|
|
|
|
|
providerName: 'google',
|
|
|
|
|
modelId: 'gemini',
|
|
|
|
|
systemPrompt: 'prompt',
|
|
|
|
|
teamSkills: [],
|
|
|
|
|
allowedDomains: [],
|
|
|
|
|
providers: mockProviders,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
sessionId: session.id,
|
|
|
|
|
})
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
|
|
|
|
|
} finally {
|
|
|
|
|
initializeSpy.mockRestore()
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should inject the bash tool after a skill is loaded via read_skill for restricted users', 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 },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
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((p: any) => {
|
|
|
|
|
if (p.toString().endsWith('.hash')) return 'inject-hash'
|
|
|
|
|
if (p.toString().endsWith('SKILL.md')) return '# Inject Skill'
|
|
|
|
|
return ''
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
|
|
|
|
|
expect(readSkillTool).toBeDefined()
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false)
|
|
|
|
|
|
|
|
|
|
await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined)
|
|
|
|
|
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should not inject the bash tool for restricted users when bash is in deniedTools', 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 },
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
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((p: any) => {
|
|
|
|
|
if (p.toString().endsWith('.hash')) return 'denied-hash'
|
|
|
|
|
if (p.toString().endsWith('SKILL.md')) return '# Denied Skill'
|
|
|
|
|
return ''
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
|
|
|
|
|
expect(readSkillTool).toBeDefined()
|
|
|
|
|
|
|
|
|
|
await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined)
|
|
|
|
|
|
|
|
|
|
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should include restricted user instructions in the system prompt for non-owners', async () => {
|
|
|
|
|
const { harness } = await setupSession({ role: 'editor' })
|
|
|
|
|
// @ts-expect-error accessing private property for verification
|
|
|
|
|
const prompt = await harness.systemPrompt()
|
|
|
|
|
expect(prompt).toContain('# Restricted User Context')
|
|
|
|
|
expect(prompt).toContain('source="user" will be rejected')
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
it('should not include restricted user instructions in the system prompt for owners', async () => {
|
|
|
|
|
const { harness } = await setupSession({ role: 'owner' })
|
|
|
|
|
// @ts-expect-error accessing private property for verification
|
|
|
|
|
const prompt = await harness.systemPrompt()
|
|
|
|
|
expect(prompt).not.toContain('# Restricted User Context')
|
|
|
|
|
})
|
|
|
|
|
})
|