feat(agent): migrate to pi-agent-core harness and implement DatabaseSessionStorage

This commit is contained in:
yiling
2026-05-21 11:50:09 +08:00
parent e1ef2305db
commit a73a39f2aa
18 changed files with 1044 additions and 1037 deletions
@@ -21,7 +21,6 @@ describe('analyzeAssetMediaTool', () => {
{ key: 'assets/test.webp' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image')
@@ -46,7 +45,6 @@ describe('analyzeAssetMediaTool', () => {
{ key: 'assets/no-extension-but-mp4' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
@@ -63,7 +61,6 @@ describe('analyzeAssetMediaTool', () => {
{ key: 'assets/non-existent' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+5 -5
View File
@@ -1,7 +1,7 @@
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import { ImageContent, TextContent } from '@mariozechner/pi-ai'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
import { detectSupportedMimeType } from '@/utils/mime'
const analyzeAssetMediaSchema = Type.Object({
@@ -15,10 +15,10 @@ export interface MediaAnalysisDetails {
sourceKey: string
}
export const analyzeAssetMediaTool = defineTool<
export const analyzeAssetMediaTool: AgentTool<
typeof analyzeAssetMediaSchema,
MediaAnalysisDetails
>({
> = {
name: 'analyze_asset_media',
label: 'Analyze Asset Media',
description:
@@ -71,4 +71,4 @@ export const analyzeAssetMediaTool = defineTool<
}
}
},
})
}
+30 -72
View File
@@ -18,24 +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 readSkillTool = createReadSkillTool(() => {})
const result = await readSkillTool.execute(
'1',
{ skillId: 'non-existent' },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toContain('not found')
@@ -60,16 +53,9 @@ 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 },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
const readSkillTool = createReadSkillTool(() => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
expect(s3Service.getObject).not.toHaveBeenCalled()
@@ -115,16 +101,8 @@ describe('readSkillTool', () => {
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 },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
const readSkillTool = createReadSkillTool(() => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
@@ -167,18 +145,13 @@ describe('readSkillTool', () => {
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const readSkillTool = createReadSkillTool(mockSessionManager as any)
await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{} as unknown as any,
)
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(mockSessionManager.addSkillEnvs).toHaveBeenCalledWith({
expect(capturedEnvs).toEqual({
CONFIGURED_VAR: 'user-val',
})
})
@@ -207,18 +180,13 @@ describe('readSkillTool', () => {
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const readSkillTool = createReadSkillTool(mockSessionManager as any)
await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{} as unknown as any,
)
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(mockSessionManager.addSkillEnvs).toHaveBeenCalledWith({
expect(capturedEnvs).toEqual({
OVERRIDDEN_VAR: 'user-val',
})
})
@@ -247,18 +215,13 @@ describe('readSkillTool', () => {
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const readSkillTool = createReadSkillTool(mockSessionManager as any)
await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{} as unknown as any,
)
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(mockSessionManager.addSkillEnvs).toHaveBeenCalledWith({
expect(capturedEnvs).toEqual({
FALLBACK_VAR: 'host-val',
})
})
@@ -287,18 +250,13 @@ describe('readSkillTool', () => {
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const readSkillTool = createReadSkillTool(mockSessionManager as any)
await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{} as unknown as any,
)
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(mockSessionManager.addSkillEnvs).toHaveBeenCalledWith({
expect(capturedEnvs).toEqual({
FALLBACK_VAR_UNDEF: 'host-val2',
})
})
+98 -98
View File
@@ -1,122 +1,122 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import { type AgentTool } from '@earendil-works/pi-agent-core'
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 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 },
})
export const createReadSkillTool = (
onEnvsAdded: (envs: Record<string, string>) => void,
): AgentTool<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 },
}
}
// 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 =
envVar.default !== undefined && envVar.default !== null && envVar.default !== ''
? envVar.default
: process.env[envVar.name]
if (value !== undefined) {
envs[envVar.name] = value
}
}
sessionManager.addSkillEnvs(envs)
}
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 },
})
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')
if (!skill) {
return {
content: [{ type: 'text', text: skillMdContent }],
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
details: { skillId: params.skillId },
}
} catch (error) {
}
// 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 =
envVar.default !== undefined && envVar.default !== null && envVar.default !== ''
? envVar.default
: process.env[envVar.name]
if (value !== undefined) {
envs[envVar.name] = value
}
}
onEnvsAdded(envs)
}
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 },
})
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: `Error reading skill ${params.skillId}: ${
error instanceof Error ? error.message : String(error)
}`,
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: `Error reading skill ${params.skillId}: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { skillId: params.skillId },
}
}
},
})
+6 -10
View File
@@ -38,8 +38,7 @@ describe('createSandboxedBashTool', () => {
const createMockOnUpdate = () => vi.fn()
it('should execute a command in the sandbox with injected env vars', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockSessionManager is a partial mock of DatabaseSessionManager
const tool = createSandboxedBashTool(mockCwd, mockSessionManager as any)
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockStderr = new EventEmitter()
@@ -82,8 +81,7 @@ describe('createSandboxedBashTool', () => {
})
it('should handle process errors', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockSessionManager is a partial mock
const tool = createSandboxedBashTool(mockCwd, mockSessionManager as any)
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = new EventEmitter()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
@@ -98,8 +96,7 @@ describe('createSandboxedBashTool', () => {
})
it('should handle non-zero exit codes', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockSessionManager is a partial mock
const tool = createSandboxedBashTool(mockCwd, mockSessionManager as any)
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
@@ -119,8 +116,8 @@ describe('createSandboxedBashTool', () => {
it('should handle timeouts', async () => {
vi.useFakeTimers()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockSessionManager is a partial mock
const tool = createSandboxedBashTool(mockCwd, mockSessionManager as any)
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
@@ -154,8 +151,7 @@ describe('createSandboxedBashTool', () => {
})
it('should handle abort signals', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockSessionManager is a partial mock
const tool = createSandboxedBashTool(mockCwd, mockSessionManager as any)
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
+98 -54
View File
@@ -1,48 +1,54 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { createBashTool } from '@mariozechner/pi-coding-agent'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { Type } from '@sinclair/typebox'
import { spawn } from 'node:child_process'
import type { DatabaseSessionManager } from '../database-session-manager'
export const createSandboxedBashTool = (cwd: string, sessionManager: DatabaseSessionManager) => {
return createBashTool(cwd, {
operations: {
async exec(command, executeCwd, { onData, signal, timeout }) {
const wrappedCommand = await SandboxManager.wrapWithSandbox(command)
return new Promise((resolve, reject) => {
const child = spawn('bash', ['-c', wrappedCommand], {
cwd: executeCwd,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...sessionManager.getSkillEnvs(),
},
})
const BashParameters = Type.Object({
command: Type.String({ description: 'The bash command to execute.' }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
})
let timedOut = false
let timeoutHandle: NodeJS.Timeout | undefined
type BashDetails = {
exitCode: number | null
stdout: string
stderr: string
}
if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => {
timedOut = true
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL')
} catch {
child.kill('SIGKILL')
}
}
}, timeout * 1000)
}
export const createSandboxedBashTool = (
cwd: string,
skillEnvs: Record<string, string> = {},
): AgentTool<typeof BashParameters, BashDetails> => {
return {
name: 'bash',
description: 'Execute a bash command in a sandboxed environment.',
label: 'Executing bash command',
parameters: BashParameters,
execute: async (
toolCallId,
{ command, timeout },
signal,
): Promise<AgentToolResult<BashDetails>> => {
const wrappedCommand = await SandboxManager.wrapWithSandbox(command)
child.stdout?.on('data', onData)
child.stderr?.on('data', onData)
return new Promise((resolve, reject) => {
const child = spawn('bash', ['-c', wrappedCommand], {
cwd,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
...skillEnvs,
},
})
child.on('error', (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle)
reject(err)
})
let stdout = ''
let stderr = ''
let timedOut = false
let timeoutHandle: NodeJS.Timeout | undefined
const onAbort = () => {
if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => {
timedOut = true
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL')
@@ -50,24 +56,62 @@ export const createSandboxedBashTool = (cwd: string, sessionManager: DatabaseSes
child.kill('SIGKILL')
}
}
}
}, timeout * 1000)
}
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 })
}
})
child.stdout?.on('data', (data) => {
stdout += data.toString()
})
},
child.stderr?.on('data', (data) => {
stderr += data.toString()
})
const onAbort = () => {
if (child.pid) {
try {
process.kill(-child.pid, 'SIGKILL')
} catch {
child.kill('SIGKILL')
}
}
}
signal?.addEventListener('abort', onAbort, { once: true })
child.on('error', (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle)
signal?.removeEventListener('abort', onAbort)
reject(err)
})
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(`bash command timed out after ${timeout} seconds`))
} else if (code !== 0 && code !== null) {
reject(new Error(`bash command exited with code ${code}`))
} else {
const output = stdout + stderr
resolve({
content: [
{
type: 'text',
text: output || (code === 0 ? 'Success' : `Failed with exit code ${code}`),
},
],
details: {
exitCode: code,
stdout,
stderr,
},
})
}
})
})
},
})
}
}