2026-05-20 22:43:31 +08:00
|
|
|
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
2026-05-21 11:50:09 +08:00
|
|
|
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'
|
2026-05-20 22:43:31 +08:00
|
|
|
import { Type, type TSchema } from '@sinclair/typebox'
|
|
|
|
|
import * as fs from 'fs'
|
|
|
|
|
import * as path from 'path'
|
2026-05-21 11:50:09 +08:00
|
|
|
import { DatabaseSessionStorage } from './database-session-storage'
|
2026-05-20 22:43:31 +08:00
|
|
|
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
|
2026-05-30 18:50:12 +08:00
|
|
|
import { createCreateFileTool } from './tools/create-file'
|
|
|
|
|
import { createCreateFolderTool } from './tools/create-folder'
|
|
|
|
|
import { createCreateVersionTool } from './tools/create-version'
|
|
|
|
|
import { createListAssetsTool } from './tools/list-assets'
|
2026-05-20 22:43:31 +08:00
|
|
|
import { createReadSkillTool } from './tools/read-skill'
|
|
|
|
|
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
|
|
|
|
|
|
|
|
|
export interface CreateAgentSessionParams {
|
|
|
|
|
agentId: string
|
|
|
|
|
providerName: string
|
|
|
|
|
modelId: string
|
|
|
|
|
systemPrompt: string
|
|
|
|
|
teamSkills: Array<{ id: string; name: string; description?: string | null }>
|
|
|
|
|
allowedDomains: string[]
|
2026-05-20 22:52:54 +08:00
|
|
|
sessionId?: string
|
|
|
|
|
userId?: string
|
2026-05-21 11:50:09 +08:00
|
|
|
customTools?: AgentTool[]
|
2026-05-20 22:43:31 +08:00
|
|
|
providers: Array<{
|
|
|
|
|
name: string
|
2026-05-21 11:50:09 +08:00
|
|
|
config: PrismaJson.ProviderConfig
|
2026-05-20 22:43:31 +08:00
|
|
|
models: Array<{
|
|
|
|
|
modelId: string
|
|
|
|
|
name: string | null
|
2026-05-21 11:50:09 +08:00
|
|
|
config: PrismaJson.ModelConfig
|
2026-05-20 22:43:31 +08:00
|
|
|
}>
|
|
|
|
|
}>
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function createAgentSession(params: CreateAgentSessionParams) {
|
|
|
|
|
const {
|
|
|
|
|
agentId,
|
|
|
|
|
providerName,
|
|
|
|
|
modelId,
|
|
|
|
|
systemPrompt,
|
|
|
|
|
teamSkills,
|
|
|
|
|
allowedDomains,
|
2026-05-20 22:52:54 +08:00
|
|
|
sessionId,
|
|
|
|
|
userId,
|
2026-05-20 22:43:31 +08:00
|
|
|
customTools = [],
|
|
|
|
|
} = params
|
|
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
const storage = await DatabaseSessionStorage.create({
|
2026-05-20 22:52:54 +08:00
|
|
|
agentId,
|
|
|
|
|
userId,
|
|
|
|
|
sessionId,
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
})
|
2026-05-21 11:50:09 +08:00
|
|
|
const session = new Session(storage)
|
2026-05-20 22:52:54 +08:00
|
|
|
|
2026-05-20 22:43:31 +08:00
|
|
|
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
|
|
|
|
|
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
|
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
// 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)
|
2026-05-20 22:43:31 +08:00
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
if (!dbProvider || !dbModel) return undefined
|
|
|
|
|
|
|
|
|
|
// Model contains complex internal types from pi-ai
|
2026-05-20 22:43:31 +08:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2026-05-21 11:50:09 +08:00
|
|
|
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,
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-20 22:43:31 +08:00
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
// 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
|
2026-05-20 22:43:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2026-05-21 11:50:09 +08:00
|
|
|
const model = getModelFromDb(providerName, modelId) || (getModel as any)(providerName, modelId)
|
2026-05-20 22:43:31 +08:00
|
|
|
|
|
|
|
|
const piDir = path.join(process.cwd(), '.pi')
|
|
|
|
|
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
|
|
|
|
|
|
|
|
|
const allowWrite = [piDir, '/tmp']
|
|
|
|
|
|
|
|
|
|
// SandboxManager.initialize is a global operation that applies to the entire process.
|
|
|
|
|
await SandboxManager.initialize({
|
|
|
|
|
network: {
|
|
|
|
|
allowedDomains,
|
|
|
|
|
deniedDomains: [],
|
|
|
|
|
},
|
|
|
|
|
filesystem: {
|
|
|
|
|
allowWrite,
|
|
|
|
|
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
|
|
|
|
|
denyRead: ['~/.ssh', '~/.aws', '~/.gnupg'],
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
const skillEnvs: Record<string, string> = {}
|
|
|
|
|
const onEnvsAdded = (envs: Record<string, string>) => {
|
|
|
|
|
Object.assign(skillEnvs, envs)
|
|
|
|
|
}
|
2026-05-20 22:43:31 +08:00
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs)
|
|
|
|
|
const readSkill = createReadSkillTool(onEnvsAdded)
|
|
|
|
|
|
2026-05-30 17:09:18 +08:00
|
|
|
const systemTools: AgentTool[] = []
|
|
|
|
|
if (userId) {
|
|
|
|
|
systemTools.push(
|
|
|
|
|
createListAssetsTool(userId),
|
|
|
|
|
createCreateFolderTool(userId),
|
|
|
|
|
createCreateFileTool(userId),
|
|
|
|
|
createCreateVersionTool(userId),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
const harness = new AgentHarness({
|
|
|
|
|
env: new NodeExecutionEnv({ cwd: process.cwd() }),
|
|
|
|
|
session,
|
2026-05-20 22:43:31 +08:00
|
|
|
model,
|
2026-05-21 11:50:09 +08:00
|
|
|
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
|
|
|
|
|
},
|
2026-05-30 17:09:18 +08:00
|
|
|
tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...systemTools, ...customTools],
|
2026-05-20 22:43:31 +08:00
|
|
|
})
|
|
|
|
|
|
2026-05-21 11:50:09 +08:00
|
|
|
return { session, harness }
|
2026-05-20 22:43:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface AutofillField {
|
|
|
|
|
id: string
|
|
|
|
|
config: PrismaJson.FieldConfig
|
|
|
|
|
description?: string | null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
|
|
|
|
const properties: Record<string, TSchema> = {}
|
|
|
|
|
for (const f of fields) {
|
|
|
|
|
let schema: TSchema
|
|
|
|
|
switch (f.config.type) {
|
|
|
|
|
case 'text':
|
|
|
|
|
case 'longText':
|
|
|
|
|
schema = Type.String()
|
|
|
|
|
break
|
|
|
|
|
case 'number':
|
|
|
|
|
case 'rating':
|
|
|
|
|
schema = Type.Number()
|
|
|
|
|
break
|
|
|
|
|
case 'toggle':
|
|
|
|
|
schema = Type.Boolean()
|
|
|
|
|
break
|
|
|
|
|
case 'select':
|
|
|
|
|
schema = Type.String({
|
|
|
|
|
enum: f.config.select?.options?.map((o) => o.id) || [],
|
|
|
|
|
})
|
|
|
|
|
break
|
|
|
|
|
default:
|
|
|
|
|
schema = Type.String()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (f.description) {
|
|
|
|
|
schema.description = f.description
|
|
|
|
|
}
|
|
|
|
|
properties[f.id] = schema
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Type.Object(properties)
|
|
|
|
|
}
|