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
-161
View File
@@ -1,161 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { DatabaseSessionManager } from './database-session-manager'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
},
}))
describe('DatabaseSessionManager', () => {
setupTestDbHooks()
let agentId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'Test Agent', email: 'agent@test.com', type: 'agent' },
})
await prisma.agent.create({
data: {
id: user.id,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4o' },
},
})
agentId = user.id
})
it('creates a new session in DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
const sessionId = manager.getDbSessionId()
expect(sessionId).toBeDefined()
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session).toBeDefined()
expect(session?.agentId).toBe(agentId)
})
it('persists message entries to DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'user', content: 'Hello' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(1)
// In simplified schema, type/parentId are part of the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entry = entries[0].entry as any
expect(entry.type).toBe('message')
expect(entry.message.content).toBe('Hello')
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session?.leafId).toBe(entries[0].id)
})
it('loads existing session from DB', async () => {
const manager1 = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msgId = manager1.appendMessage({ role: 'user', content: 'Message 1' } as any)
await manager1.waitForSync()
const sessionId = manager1.getDbSessionId()
const manager2 = await DatabaseSessionManager.create({ agentId, sessionId })
expect(manager2.getDbSessionId()).toBe(sessionId)
expect(manager2.getLeafId()).toBe(msgId)
const context = manager2.buildSessionContext()
expect(context.messages).toHaveLength(1)
expect(context.messages[0].content).toBe('Message 1')
})
it('re-injects image data from S3', async () => {
const session = await prisma.agentSession.create({
data: { agentId, cwd: '/tmp' },
})
const entry = {
id: 'e1',
type: 'message',
message: {
role: 'toolResult',
content: [{ type: 'image', data: '__S3_DATA__' }],
details: { sourceKeys: ['key1'] },
},
}
await prisma.agentSessionEntry.create({
data: {
id: entry.id,
sessionId: session.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: entry as any,
},
})
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-image-data'),
contentType: 'image/png',
})
const manager = await DatabaseSessionManager.create({ agentId, sessionId: session.id })
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(s3Service.getObject).toHaveBeenCalledWith(expect.any(String), 'key1')
})
it('handles branching', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m1Id = manager.appendMessage({ role: 'user', content: 'M1' } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'assistant', content: 'A1' } as any)
await manager.waitForSync()
// Branch from M1
manager.branch(m1Id)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m2Id = manager.appendMessage({ role: 'user', content: 'M2' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(3)
const m2Entry = entries.find((e) => e.id === m2Id)
// parentId is now inside the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((m2Entry?.entry as any).parentId).toBe(m1Id)
const context = manager.buildSessionContext()
expect(context.messages).toHaveLength(2)
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',
})
})
})
-148
View File
@@ -1,148 +0,0 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
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()
private constructor(sessionId: string, cwd: string) {
super(cwd, '', undefined, false) // persist = false, we handle it manually
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
sessionId?: string
cwd?: string
}): Promise<DatabaseSessionManager> {
const sessionId = params.sessionId
const cwd = params.cwd || process.cwd()
if (sessionId) {
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
include: { entries: { orderBy: { id: 'asc' } } },
})
if (!session) {
throw new Error(`Session ${sessionId} not found`)
}
const manager = new DatabaseSessionManager(sessionId, session.cwd)
// Load entries into in-memory SessionManager
for (const e of session.entries) {
const entry = e.entry
// Dynamically re-inject image data if it was stripped
if (entry.type === 'message' && entry.message.role === 'toolResult') {
const msg = entry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
for (const item of msg.content) {
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,
)
item.data = buffer.toString('base64')
} catch (err) {
console.error(`Failed to re-inject image data for key ${key}:`, err)
}
keyIdx++
}
}
}
}
manager._appendEntry(entry, false) // false to avoid re-saving
}
return manager
} else {
const session = await prisma.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: cwd,
},
})
return new DatabaseSessionManager(session.id, cwd)
}
}
// Override _appendEntry to save to database
// Note: we use (manager as any)._appendEntry = ... in static factory if needed,
// but since we extend it, we can just define it here.
// We need to match the signature of the base class.
protected _appendEntry(entry: SessionEntry, shouldSave = true) {
// Call super._appendEntry (which is private, so we use the prototype)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const superAppendEntry = (SessionManager.prototype as any)['_appendEntry']
superAppendEntry.call(this, entry)
if (shouldSave) {
this.saveEntryToDb(entry)
}
}
private saveEntryToDb(entry: SessionEntry) {
this.writeQueue = this.writeQueue.then(async () => {
try {
// Deep clone to avoid stripping data from the in-memory session manager
const strippedEntry = JSON.parse(JSON.stringify(entry)) as SessionEntry
// Strip image data before saving to DB
if (strippedEntry.type === 'message' && strippedEntry.message.role === 'toolResult') {
const msg = strippedEntry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
msg.content.forEach((item) => {
if (item.type === 'image' && sourceKeys[keyIdx]) {
item.data = '__S3_DATA__'
keyIdx++
}
})
}
}
await prisma.agentSessionEntry.create({
data: {
id: strippedEntry.id,
sessionId: this.dbSessionId,
entry: strippedEntry,
},
})
await prisma.agentSession.update({
where: { id: this.dbSessionId },
data: { leafId: strippedEntry.id },
})
} catch (err) {
console.error('Failed to save session entry to DB:', err)
}
})
}
async waitForSync() {
await this.writeQueue
}
getDbSessionId() {
return this.dbSessionId
}
}
+247
View File
@@ -0,0 +1,247 @@
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { s3Service } from '@/services/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi } from 'vitest'
import { DatabaseSessionStorage } from './database-session-storage'
describe('DatabaseSessionStorage', () => {
setupTestDbHooks()
const mockModelConfig: PrismaJson.ModelConfig = {
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
}
const setupTestData = async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const provider = await prisma.provider.create({
data: {
name: 'test-provider',
teamId: team.id,
config: { api: 'openai-responses' },
},
})
const model = await prisma.model.create({
data: {
modelId: 'test-model',
name: 'Test Model',
providerId: provider.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: mockModelConfig as any,
},
})
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test@example.com', type: 'human' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
type: 'chat',
providerId: provider.id,
modelId: model.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: { provider: 'test-provider', model: 'test-model' } as any,
},
})
return { team, user, agent }
}
it('should create and retrieve metadata', async () => {
const { agent, user } = await setupTestData()
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
cwd: '/test/cwd',
})
const metadata = await storage.getMetadata()
expect(metadata.agentId).toBe(agent.id)
expect(metadata.userId).toBe(user.id)
expect(metadata.cwd).toBe('/test/cwd')
expect(metadata.id).toBeDefined()
expect(metadata.createdAt).toBeDefined()
})
it('should manage leafId', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
expect(await storage.getLeafId()).toBeNull()
await storage.setLeafId('entry-1')
expect(await storage.getLeafId()).toBe('entry-1')
await storage.setLeafId(null)
expect(await storage.getLeafId()).toBeNull()
})
it('should append and retrieve entries', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
timestamp: Date.now(),
},
}
await storage.appendEntry(entry)
// Verify leafId was auto-updated
expect(await storage.getLeafId()).toBe('msg-1')
const retrieved = await storage.getEntry('msg-1')
expect(retrieved).toEqual(entry)
const allEntries = await storage.getEntries()
expect(allEntries).toHaveLength(1)
expect(allEntries[0]).toEqual(entry)
})
it('should find entries by type', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'thinking_level_change',
id: 'think-1',
parentId: 'msg-1',
timestamp: new Date().toISOString(),
thinkingLevel: 'high',
})
const messages = await storage.findEntries('message')
expect(messages).toHaveLength(1)
expect(messages[0].id).toBe('msg-1')
const thinkChanges = await storage.findEntries('thinking_level_change')
expect(thinkChanges).toHaveLength(1)
expect(thinkChanges[0].id).toBe('think-1')
})
it('should retrieve path to root', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: 'msg-2',
parentId: 'msg-1',
timestamp: new Date().toISOString(),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
message: {
role: 'assistant',
content: [],
timestamp: Date.now(),
provider: 'p',
model: 'm',
api: 'api',
usage: { input: 0, output: 0 },
} as any,
})
await storage.appendEntry({
type: 'message',
id: 'msg-3',
parentId: 'msg-2',
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
const path = await storage.getPathToRoot('msg-3')
expect(path).toHaveLength(3)
expect(path[0].id).toBe('msg-1')
expect(path[1].id).toBe('msg-2')
expect(path[2].id).toBe('msg-3')
})
it('should strip and reinject image data', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockResolvedValue({
buffer: Buffer.from('reinjected-data'),
contentType: 'image/png',
// S3Object has complex metadata requirements not needed for this test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-1',
toolName: 'tool',
isError: false,
timestamp: Date.now(),
content: [{ type: 'image', data: 'original-base64-data', mimeType: 'image/png' }],
details: {
sourceKeys: ['path/to/image.png'],
},
},
}
await storage.appendEntry(entry)
// Record entry is generic Json
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-1' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const savedEntry = record?.entry as any
expect(savedEntry.message.content[0].data).toBe('__S3_DATA__')
// Verify retrieval reinjects data
const retrieved = await storage.getEntry('msg-1')
expect(getObjectSpy).toHaveBeenCalledWith('shumai', 'path/to/image.png')
// retrieved is a SessionTreeEntry, but we need to access internal message properties for verification
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((retrieved as any).message.content[0].data).toBe(
Buffer.from('reinjected-data').toString('base64'),
)
})
it('should retrieve label', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'label',
id: 'label-1',
targetId: 'target-1',
parentId: null,
timestamp: new Date().toISOString(),
label: 'Test Label',
})
const label = await storage.getLabel('label-1')
expect(label).toBe('Test Label')
})
})
+214
View File
@@ -0,0 +1,214 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import {
type AgentMessage,
type SessionMetadata,
type SessionStorage,
type SessionTreeEntry,
type SessionTreeEntryBase,
} from '@earendil-works/pi-agent-core'
export interface DatabaseSessionMetadata extends SessionMetadata {
agentId: string
userId?: string
cwd: string
}
export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMetadata> {
constructor(private sessionId: string) {}
async getMetadata(): Promise<DatabaseSessionMetadata> {
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
})
if (!session) throw new Error(`Session ${this.sessionId} not found`)
return {
id: session.id,
createdAt: session.createdAt.toISOString(),
agentId: session.agentId,
userId: session.userId || undefined,
cwd: session.cwd,
}
}
async getLeafId(): Promise<string | null> {
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
select: { leafId: true },
})
return session?.leafId || null
}
async setLeafId(leafId: string | null): Promise<void> {
await prisma.agentSession.update({
where: { id: this.sessionId },
data: { leafId },
})
}
async createEntryId(): Promise<string> {
// We can use ULID from prisma or crypto.randomUUID() if needed,
// but the harness expects a string.
// The previous implementation used the entry's own ID.
// Let's use crypto.randomUUID for now or a ULID generator if available.
return crypto.randomUUID()
}
async appendEntry(entry: SessionTreeEntry): Promise<void> {
const strippedEntry = JSON.parse(JSON.stringify(entry))
// Strip image data before saving to DB
if (strippedEntry.type === 'message') {
const msg = strippedEntry.message
if (msg.role === 'toolResult') {
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
msg.content.forEach((item: { type: string; data?: string }) => {
if (item.type === 'image' && sourceKeys[keyIdx]) {
item.data = '__S3_DATA__'
keyIdx++
}
})
}
}
}
await prisma.agentSessionEntry.create({
data: {
id: entry.id,
sessionId: this.sessionId,
// Entry is stored as Json in Prisma and bound to PiSessionEntry via prisma-json-types
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: strippedEntry as any,
},
})
// Auto-update leafId on append
await this.setLeafId(entry.id)
}
async getEntry(id: string): Promise<SessionTreeEntry | undefined> {
const record = await prisma.agentSessionEntry.findUnique({
where: { id },
})
if (!record) return undefined
const entry = record.entry as unknown as SessionTreeEntry
await this.reinjectImageDataAsync(entry)
return entry
}
async findEntries<TType extends SessionTreeEntry['type']>(
type: TType,
): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {
const records = await prisma.agentSessionEntry.findMany({
where: {
sessionId: this.sessionId,
entry: {
path: ['type'],
equals: type,
},
},
orderBy: { id: 'asc' },
})
const entries = records.map((r) => r.entry as unknown as SessionTreeEntry) as Array<
Extract<SessionTreeEntry, { type: TType }>
>
for (const entry of entries) {
await this.reinjectImageDataAsync(entry)
}
return entries
}
async getLabel(id: string): Promise<string | undefined> {
const record = await prisma.agentSessionEntry.findFirst({
where: {
sessionId: this.sessionId,
entry: {
path: ['id'],
equals: id,
},
},
})
// Entry is generic Json
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (record?.entry as any)?.label
}
async getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {
if (!leafId) return []
const entries: SessionTreeEntry[] = []
let currentId: string | null = leafId
while (currentId) {
const record = await prisma.agentSessionEntry.findUnique({
where: { id: currentId },
})
if (!record) break
const entry = record.entry as unknown as SessionTreeEntry
await this.reinjectImageDataAsync(entry)
entries.unshift(entry)
currentId = (entry as SessionTreeEntryBase).parentId
}
return entries
}
async getEntries(): Promise<SessionTreeEntry[]> {
const records = await prisma.agentSessionEntry.findMany({
where: { sessionId: this.sessionId },
orderBy: { id: 'asc' },
})
const entries = records.map((r) => r.entry as unknown as SessionTreeEntry)
for (const entry of entries) {
await this.reinjectImageDataAsync(entry)
}
return entries
}
private async reinjectImageDataAsync(entry: SessionTreeEntry) {
if (entry.type === 'message') {
const msg = entry.message as AgentMessage
if (msg.role === 'toolResult') {
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
for (const item of msg.content) {
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)
item.data = buffer.toString('base64')
} catch (err) {
console.error(`Failed to re-inject image data for key ${key}:`, err)
}
keyIdx++
}
}
}
}
}
}
static async create(params: {
agentId: string
userId?: string
sessionId?: string
cwd?: string
}): Promise<DatabaseSessionStorage> {
if (params.sessionId) {
return new DatabaseSessionStorage(params.sessionId)
} else {
const session = await prisma.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: params.cwd || process.cwd(),
},
})
return new DatabaseSessionStorage(session.id)
}
}
}
+86 -76
View File
@@ -1,18 +1,11 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { getModel } from '@mariozechner/pi-ai'
import {
AuthStorage,
createAgentSession as piCreateAgentSession,
DefaultResourceLoader,
ModelRegistry,
SessionManager,
SettingsManager,
type ToolDefinition,
} from '@mariozechner/pi-coding-agent'
import { AgentHarness, Session, type AgentTool } from '@earendil-works/pi-agent-core'
import { NodeExecutionEnv } from '@earendil-works/pi-agent-core/node'
import { getModel } from '@earendil-works/pi-ai'
import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs'
import * as path from 'path'
import { DatabaseSessionManager } from './database-session-manager'
import { DatabaseSessionStorage } from './database-session-storage'
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
import { createReadSkillTool } from './tools/read-skill'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
@@ -21,20 +14,19 @@ export interface CreateAgentSessionParams {
agentId: string
providerName: string
modelId: string
apiKey?: string
systemPrompt: string
teamSkills: Array<{ id: string; name: string; description?: string | null }>
allowedDomains: string[]
sessionId?: string
userId?: string
customTools?: ToolDefinition[]
customTools?: AgentTool[]
providers: Array<{
name: string
config: Record<string, unknown>
config: PrismaJson.ProviderConfig
models: Array<{
modelId: string
name: string | null
config: Record<string, unknown>
config: PrismaJson.ModelConfig
}>
}>
}
@@ -44,74 +36,71 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
agentId,
providerName,
modelId,
apiKey,
systemPrompt,
teamSkills,
allowedDomains,
sessionId,
userId,
customTools = [],
providers,
} = params
const sessionManager = await DatabaseSessionManager.create({
const storage = await DatabaseSessionStorage.create({
agentId,
userId,
sessionId,
cwd: process.cwd(),
})
const session = new Session(storage)
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
const modelRegistry = ModelRegistry.create(authStorage)
modelRegistry.getAll()
// Helper to construct a Model object from database providers list
const getModelFromDb = (pName: string, mId: string) => {
const dbProvider = params.providers.find((p) => p.name === pName)
const dbModel = dbProvider?.models.find((m) => m.modelId === mId)
for (const p of providers) {
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
const config = {
...p.config,
models: p.models.map((m) => ({
...m.config,
id: m.modelId,
name: m.name || m.modelId,
})),
}
// We cast to any because the third-party library's ProviderConfigInput type expects highly specific properties
// like reasoning, input, and cost on each model config, which are stored dynamically in the database
// and loaded as arbitrary Record<string, unknown> JSON values.
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
modelRegistry.registerProvider(p.name, config as any)
}
let m: any
try {
// Try to get built-in model as template
// eslint-disable-next-line @typescript-eslint/no-explicit-any
m = { ...(getModel as any)(pName, mId) }
} catch {
// Not a built-in model
m = {
id: mId,
name: dbModel.name || mId,
provider: pName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
}
if (apiKey) {
authStorage.set(providerName, { type: 'api_key', key: apiKey })
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
Object.assign(m, dbModel.config)
if (dbModel.name) {
m.name = dbModel.name
}
return m
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const model = (getModel as any)(providerName, modelId)
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
const resourceLoader = new DefaultResourceLoader({
cwd: process.cwd(),
agentDir,
settingsManager,
systemPromptOverride: () => {
let prompt = systemPrompt
if (teamSkills.length > 0) {
prompt += '\n\nAvailable Skills:\n'
for (const s of teamSkills) {
prompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
}
prompt +=
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
}
return prompt
},
noContextFiles: true,
})
await resourceLoader.reload()
const model = getModelFromDb(providerName, modelId) || (getModel as any)(providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
@@ -131,26 +120,47 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
},
})
const sandboxedBash = createSandboxedBashTool(process.cwd(), sessionManager)
const skillEnvs: Record<string, string> = {}
const onEnvsAdded = (envs: Record<string, string>) => {
Object.assign(skillEnvs, envs)
}
const { session } = await piCreateAgentSession({
cwd: process.cwd(),
agentDir,
authStorage,
modelRegistry,
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs)
const readSkill = createReadSkillTool(onEnvsAdded)
const harness = new AgentHarness({
env: new NodeExecutionEnv({ cwd: process.cwd() }),
session,
model,
resourceLoader,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sessionManager: sessionManager as any as SessionManager,
customTools: [
analyzeAssetMediaTool,
createReadSkillTool(sessionManager),
sandboxedBash,
...customTools,
],
systemPrompt: async () => {
let prompt = systemPrompt
if (teamSkills.length > 0) {
prompt += '\n\nAvailable Skills:\n'
for (const s of teamSkills) {
prompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
}
prompt +=
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
}
return prompt
},
getApiKeyAndHeaders: async (targetModel) => {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = params.providers.find((p) => p.name === targetModel.provider)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
},
tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...customTools],
})
return { session, sessionManager }
return { session, harness }
}
export interface AutofillField {
@@ -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,
},
})
}
})
})
},
})
}
}