mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +00:00
feat(agent): integrate sandboxed bash tool and sandbox settings
This commit is contained in:
@@ -85,9 +85,7 @@ describe('DatabaseSessionManager', () => {
|
||||
type: 'message',
|
||||
message: {
|
||||
role: 'toolResult',
|
||||
content: [
|
||||
{ type: 'image', data: '__S3_DATA__' },
|
||||
],
|
||||
content: [{ type: 'image', data: '__S3_DATA__' }],
|
||||
details: { sourceKeys: ['key1'] },
|
||||
},
|
||||
}
|
||||
@@ -110,8 +108,10 @@ describe('DatabaseSessionManager', () => {
|
||||
const context = manager.buildSessionContext()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const reInjectedMessage = context.messages[0] as any
|
||||
|
||||
expect(reInjectedMessage.content[0].data).toBe(Buffer.from('fake-image-data').toString('base64'))
|
||||
|
||||
expect(reInjectedMessage.content[0].data).toBe(
|
||||
Buffer.from('fake-image-data').toString('base64'),
|
||||
)
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(expect.any(String), 'key1')
|
||||
})
|
||||
|
||||
@@ -143,4 +143,19 @@ describe('DatabaseSessionManager', () => {
|
||||
expect(context.messages[0].content).toBe('M1')
|
||||
expect(context.messages[1].content).toBe('M2')
|
||||
})
|
||||
|
||||
it('handles skill environment variables', async () => {
|
||||
const manager = await DatabaseSessionManager.create({ agentId })
|
||||
const envs = { TEST_VAR: 'test_value', OTHER_VAR: 'other_value' }
|
||||
|
||||
manager.addSkillEnvs(envs)
|
||||
expect(manager.getSkillEnvs()).toEqual(envs)
|
||||
|
||||
manager.addSkillEnvs({ TEST_VAR: 'new_value', NEW_VAR: 'new' })
|
||||
expect(manager.getSkillEnvs()).toEqual({
|
||||
TEST_VAR: 'new_value',
|
||||
OTHER_VAR: 'other_value',
|
||||
NEW_VAR: 'new',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export class DatabaseSessionManager extends (SessionManager as any) {
|
||||
private dbSessionId: string
|
||||
private skillEnvs: Record<string, string> = {}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private writeQueue: Promise<any> = Promise.resolve()
|
||||
|
||||
@@ -13,6 +14,14 @@ export class DatabaseSessionManager extends (SessionManager as any) {
|
||||
this.dbSessionId = sessionId
|
||||
}
|
||||
|
||||
addSkillEnvs(envs: Record<string, string>) {
|
||||
this.skillEnvs = { ...this.skillEnvs, ...envs }
|
||||
}
|
||||
|
||||
getSkillEnvs() {
|
||||
return this.skillEnvs
|
||||
}
|
||||
|
||||
static async create(params: {
|
||||
agentId: string
|
||||
userId?: string
|
||||
@@ -46,7 +55,10 @@ export class DatabaseSessionManager extends (SessionManager as any) {
|
||||
if (item.type === 'image' && item.data === '__S3_DATA__' && sourceKeys[keyIdx]) {
|
||||
const key = sourceKeys[keyIdx]
|
||||
try {
|
||||
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
const { buffer } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
item.data = buffer.toString('base64')
|
||||
} catch (err) {
|
||||
console.error(`Failed to re-inject image data for key ${key}:`, err)
|
||||
|
||||
+105
-2
@@ -10,14 +10,17 @@ import {
|
||||
SessionManager,
|
||||
SettingsManager,
|
||||
defineTool,
|
||||
createBashTool,
|
||||
} from '@mariozechner/pi-coding-agent'
|
||||
import { Type, type TSchema } from '@sinclair/typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { DatabaseSessionManager } from './database-session-manager'
|
||||
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
|
||||
import { readSkillTool } from './tools/read-skill'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { Usage } from '@/services/ai/provider/provider'
|
||||
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
||||
import { spawn } from 'node:child_process'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type Tool = any
|
||||
@@ -37,6 +40,12 @@ export class AgentExecutor {
|
||||
})
|
||||
}
|
||||
|
||||
private async getSandbox(teamId: string) {
|
||||
return this.prismaClient.sandbox.findUnique({
|
||||
where: { teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
@@ -163,6 +172,95 @@ export class AgentExecutor {
|
||||
cwd: process.cwd(),
|
||||
})
|
||||
|
||||
const sandbox = await this.getSandbox(teamId)
|
||||
const allowedDomains = sandbox?.allowedDomains || [
|
||||
'github.com',
|
||||
'api.github.com',
|
||||
'raw.githubusercontent.com',
|
||||
]
|
||||
|
||||
// Initialize SandboxManager for this session
|
||||
await SandboxManager.initialize({
|
||||
network: {
|
||||
allowedDomains,
|
||||
deniedDomains: [],
|
||||
},
|
||||
filesystem: {
|
||||
allowWrite: ['.pi', '/tmp'],
|
||||
denyRead: ['*'], // Deny everything else
|
||||
denyWrite: [],
|
||||
allowRead: ['.pi', '/tmp'],
|
||||
},
|
||||
})
|
||||
|
||||
const sandboxedBash = createBashTool(process.cwd(), {
|
||||
operations: {
|
||||
async exec(command, cwd, { onData, signal, timeout }) {
|
||||
const wrappedCommand = await SandboxManager.wrapWithSandbox(command)
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn('bash', ['-c', wrappedCommand], {
|
||||
cwd,
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...process.env,
|
||||
...sessionManager.getSkillEnvs(),
|
||||
},
|
||||
})
|
||||
|
||||
let timedOut = false
|
||||
let timeoutHandle: NodeJS.Timeout | undefined
|
||||
|
||||
if (timeout !== undefined && timeout > 0) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
timedOut = true
|
||||
if (child.pid) {
|
||||
try {
|
||||
process.kill(-child.pid, 'SIGKILL')
|
||||
} catch {
|
||||
child.kill('SIGKILL')
|
||||
}
|
||||
}
|
||||
}, timeout * 1000)
|
||||
}
|
||||
|
||||
child.stdout?.on('data', onData)
|
||||
child.stderr?.on('data', onData)
|
||||
|
||||
child.on('error', (err) => {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
reject(err)
|
||||
})
|
||||
|
||||
const onAbort = () => {
|
||||
if (child.pid) {
|
||||
try {
|
||||
process.kill(-child.pid, 'SIGKILL')
|
||||
} catch {
|
||||
child.kill('SIGKILL')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signal?.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
|
||||
if (signal?.aborted) {
|
||||
reject(new Error('aborted'))
|
||||
} else if (timedOut) {
|
||||
reject(new Error(`timeout:${timeout}`))
|
||||
} else {
|
||||
resolve({ exitCode: code })
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const { session } = await createAgentSession({
|
||||
cwd: process.cwd(),
|
||||
agentDir,
|
||||
@@ -172,7 +270,12 @@ export class AgentExecutor {
|
||||
resourceLoader,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
sessionManager: sessionManager as any as SessionManager,
|
||||
customTools: [analyzeAssetMediaTool, readSkillTool, ...tools],
|
||||
customTools: [
|
||||
analyzeAssetMediaTool,
|
||||
createReadSkillTool(sessionManager),
|
||||
sandboxedBash,
|
||||
...tools,
|
||||
],
|
||||
})
|
||||
const content: (TextContent | ImageContent)[] = []
|
||||
|
||||
|
||||
@@ -36,7 +36,10 @@ describe('analyzeAssetMediaTool', () => {
|
||||
const buffer = Buffer.from([
|
||||
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
|
||||
])
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'application/octet-stream' })
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer,
|
||||
contentType: 'application/octet-stream',
|
||||
})
|
||||
|
||||
const result = await analyzeAssetMediaTool.execute(
|
||||
'1',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { readSkillTool } from './read-skill'
|
||||
import { createReadSkillTool } from './read-skill'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import * as fs from 'fs'
|
||||
|
||||
@@ -18,11 +18,17 @@ vi.mock('adm-zip', () => {
|
||||
describe('readSkillTool', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const mockSessionManager = {
|
||||
addSkillEnvs: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return error if skill not found', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const readSkillTool = createReadSkillTool(mockSessionManager as any)
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: 'non-existent' },
|
||||
@@ -54,6 +60,8 @@ describe('readSkillTool', () => {
|
||||
return ''
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const readSkillTool = createReadSkillTool(mockSessionManager as any)
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: skill.id },
|
||||
@@ -102,8 +110,13 @@ describe('readSkillTool', () => {
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({ buffer: Buffer.from('zipdata'), contentType: 'application/zip' })
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: Buffer.from('zipdata'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const readSkillTool = createReadSkillTool(mockSessionManager as any)
|
||||
const result = await readSkillTool.execute(
|
||||
'1',
|
||||
{ skillId: skill.id },
|
||||
|
||||
@@ -5,97 +5,115 @@ import { defineTool } from '@mariozechner/pi-coding-agent'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import AdmZip from 'adm-zip'
|
||||
import type { DatabaseSessionManager } from '../database-session-manager'
|
||||
|
||||
const readSkillSchema = Type.Object({
|
||||
skillId: Type.String({ description: 'The ID of the skill to read' }),
|
||||
})
|
||||
|
||||
export const readSkillTool = defineTool<typeof readSkillSchema, { skillId: string }>({
|
||||
name: 'read_skill',
|
||||
label: 'Read Agent Skill',
|
||||
description: 'Downloads and reads an agent skill to understand how to use it.',
|
||||
parameters: readSkillSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
try {
|
||||
const skill = await prisma.skill.findUnique({
|
||||
where: { id: params.skillId },
|
||||
})
|
||||
|
||||
if (!skill) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
|
||||
const hashFile = path.join(skillDir, '.hash')
|
||||
let needsDownload = true
|
||||
|
||||
if (fs.existsSync(hashFile)) {
|
||||
const localHash = fs.readFileSync(hashFile, 'utf8')
|
||||
if (localHash === skill.hash) {
|
||||
needsDownload = false
|
||||
}
|
||||
}
|
||||
|
||||
if (needsDownload) {
|
||||
if (fs.existsSync(skillDir)) {
|
||||
fs.rmSync(skillDir, { recursive: true, force: true })
|
||||
}
|
||||
fs.mkdirSync(skillDir, { recursive: true })
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: skill.assetId },
|
||||
export const createReadSkillTool = (sessionManager: DatabaseSessionManager) =>
|
||||
defineTool<typeof readSkillSchema, { skillId: string }>({
|
||||
name: 'read_skill',
|
||||
label: 'Read Agent Skill',
|
||||
description: 'Downloads and reads an agent skill to understand how to use it.',
|
||||
parameters: readSkillSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
try {
|
||||
const skill = await prisma.skill.findUnique({
|
||||
where: { id: params.skillId },
|
||||
})
|
||||
|
||||
if (!asset || !asset.key) {
|
||||
throw new Error('Skill asset not found or has no key')
|
||||
if (!skill) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
const { buffer: zipBuffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
|
||||
// Capture environment variables if present in config
|
||||
const config = skill.config as unknown as PrismaJson.SkillConfig
|
||||
if (config?.environmentVariables && Array.isArray(config.environmentVariables)) {
|
||||
const envs: Record<string, string> = {}
|
||||
for (const envVar of config.environmentVariables) {
|
||||
const value = process.env[envVar.name] || envVar.default
|
||||
if (value !== undefined) {
|
||||
envs[envVar.name] = value
|
||||
}
|
||||
}
|
||||
sessionManager.addSkillEnvs(envs)
|
||||
}
|
||||
|
||||
const zip = new AdmZip(zipBuffer)
|
||||
zip.extractAllTo(skillDir, true)
|
||||
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
|
||||
const hashFile = path.join(skillDir, '.hash')
|
||||
let needsDownload = true
|
||||
|
||||
fs.writeFileSync(hashFile, skill.hash)
|
||||
}
|
||||
if (fs.existsSync(hashFile)) {
|
||||
const localHash = fs.readFileSync(hashFile, 'utf8')
|
||||
if (localHash === skill.hash) {
|
||||
needsDownload = false
|
||||
}
|
||||
}
|
||||
|
||||
// Read SKILL.md
|
||||
let skillMdPath = path.join(skillDir, 'SKILL.md')
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
skillMdPath = path.join(skillDir, 'skill.md')
|
||||
}
|
||||
if (needsDownload) {
|
||||
if (fs.existsSync(skillDir)) {
|
||||
fs.rmSync(skillDir, { recursive: true, force: true })
|
||||
}
|
||||
fs.mkdirSync(skillDir, { recursive: true })
|
||||
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: skill.assetId },
|
||||
})
|
||||
|
||||
if (!asset || !asset.key) {
|
||||
throw new Error('Skill asset not found or has no key')
|
||||
}
|
||||
|
||||
const { buffer: zipBuffer } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
asset.key,
|
||||
)
|
||||
|
||||
const zip = new AdmZip(zipBuffer)
|
||||
zip.extractAllTo(skillDir, true)
|
||||
|
||||
fs.writeFileSync(hashFile, skill.hash)
|
||||
}
|
||||
|
||||
// Read SKILL.md
|
||||
let skillMdPath = path.join(skillDir, 'SKILL.md')
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
skillMdPath = path.join(skillDir, 'skill.md')
|
||||
}
|
||||
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
|
||||
},
|
||||
],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
|
||||
return {
|
||||
content: [{ type: 'text', text: skillMdContent }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
|
||||
text: `Error reading skill ${params.skillId}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
},
|
||||
],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
|
||||
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
|
||||
return {
|
||||
content: [{ type: 'text', text: skillMdContent }],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Error reading skill ${params.skillId}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
},
|
||||
],
|
||||
details: { skillId: params.skillId },
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@/workflow/workflow-utils'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
|
||||
Reference in New Issue
Block a user