refactor(monorepo): decouple and split background workflow workers into packages

Splits monolithic workflow workers into four decoupled workspaces under the Bun workspaces monorepo:
- @shumai/workflow-core containing the core execution engine and utilities.
- @shumai/agent containing agent-specific logic, workflows, and activities.
- @shumai/transcode containing transcoding workflows, transcoder, and transcode activities.
- @shumai/worker-db containing database activities.

Introduces a dynamic workflow and activity registration pattern on LocalExecutor to eliminate circular dependencies. Updates worker bootstrapping and test suites to cleanly leverage generic workspace modules.
This commit is contained in:
yiling
2026-06-01 23:29:11 +08:00
parent cb80822637
commit e3f4fa219e
66 changed files with 421 additions and 150 deletions
+109
View File
@@ -0,0 +1,109 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentChatActivity, autofillAiActivity, type AgentExecutionContext } from './agent'
import * as piAgent from '../index'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
import { type DatabaseSessionMetadata } from '../database-session-storage'
vi.mock('../index', async () => {
const actual = await vi.importActual('../index')
return {
...actual,
createAgentSession: vi.fn(),
fieldsToTypeBoxSchema: vi.fn(),
}
})
describe('Agent Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should call agentChatActivity and prompt the harness', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
}),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const res = await agentChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
expect(res.text).toBe('AI response')
expect(res.usage.inputTokens).toBe(10)
expect(res.usage.outputTokens).toBe(20)
expect(piAgent.createAgentSession).toHaveBeenCalled()
})
it('should call autofillAiActivity and run autofill tool', async () => {
const mockHarness = {
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Captured' }],
usage: { input: 5, output: 5 },
}),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
// Simulate tool execution
const params = config as {
customTools: Array<{
name: string
execute: (id: string, args: Record<string, unknown>) => Promise<unknown>
}>
}
const tool = params.customTools.find((t) => t.name === 'autofill_metadata')
if (tool) {
await tool.execute('1', { f1: 'val' })
}
return {
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
harness: mockHarness as unknown as AgentHarness,
}
})
const context = {
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
const res = await autofillAiActivity({
teamId: 't1',
images: [],
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
context,
})
expect(res.text).toBe('{"f1":"val"}')
expect(res.usage.inputTokens).toBe(5)
})
})
+246
View File
@@ -0,0 +1,246 @@
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '../index'
import { DatabaseSessionStorage } from '../database-session-storage'
import type { Prisma, Skill } from '@shumai/db'
import { logger } from '@/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ImageContent } from '@earendil-works/pi-ai'
import { ApplicationFailure } from '@temporalio/activity'
export interface Usage {
inputTokens: number
outputTokens: number
model: string
}
export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{
include: {
provider: true
modelRef: true
}
}>
export type DbProviderWithModels = Prisma.ProviderGetPayload<{
include: {
models: true
}
}>
export interface AgentExecutionContext {
agent: AgentWithProviderAndModel
dbProviders: DbProviderWithModels[]
teamSkills: Skill[]
allowedDomains: string[]
}
async function executeAgentPrompt(params: {
teamId: string
agentId: string
prompt: string
images: string[]
agentsInstruction: string
sessionId?: string
userId?: string
tools?: AgentTool[]
context: AgentExecutionContext
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
const { agent, dbProviders, teamSkills, allowedDomains } = params.context
if (!agent.provider) {
throw ApplicationFailure.create({
message: 'agent has no provider configured',
nonRetryable: true,
})
}
if (!agent.modelRef) {
throw ApplicationFailure.create({
message: 'agent has no model configured',
nonRetryable: true,
})
}
const providerName = agent.provider.name
const modelId = agent.modelRef.modelId
let systemPrompt = `You are the AI assistant for shumai.
shumai is a professional creative collaboration platform similar to frame.io, where users can upload creative files, manage projects, assign tasks, get precise feedback, and share their work. As the agent, your role is to help users use and manage this platform.
shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, or listing assets), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets'). Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform.
If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories.`
if (agent.soul) {
systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}`
}
if (params.agentsInstruction) {
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}`
}
const modelConfig = agent.modelRef?.config
if (modelConfig?.input) {
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
}
const { session, harness } = await createAgentSession({
agentId: params.agentId,
providerName,
modelId,
systemPrompt,
teamSkills: teamSkills.map((s) => ({
id: s.id,
name: s.name,
description: s.description,
})),
allowedDomains,
sessionId: params.sessionId,
userId: params.userId,
customTools: params.tools || [],
providers: dbProviders.map((p) => ({
name: p.name,
config: p.config,
models: p.models.map((m) => ({
modelId: m.modelId,
name: m.name,
config: m.config,
})),
})),
})
const imagesToPass: ImageContent[] = []
if (params.images && params.images.length > 0) {
for (const key of params.images) {
const { buffer, contentType } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
key,
)
imagesToPass.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: contentType,
})
}
}
try {
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
const sessionEntries = await session.getEntries()
sessionEntries.forEach((entry) => {
if (entry.type === 'message') {
const msg = entry.message
if (msg.role === 'toolResult') {
const logMsg = { ...msg, content: undefined }
logger.debug(logMsg, 'agent message')
} else {
logger.debug(msg, 'agent message')
}
}
})
const text = assistantMessage.content
.filter((c) => c.type === 'text')
.map((c) => {
if ('text' in c && typeof c.text === 'string') {
return c.text
}
return ''
})
.join('\n')
const usage: Usage = {
model: modelId,
inputTokens: assistantMessage.usage?.input || 0,
outputTokens: assistantMessage.usage?.output || 0,
}
const storage = session.getStorage()
let sessionId = ''
if (storage instanceof DatabaseSessionStorage) {
sessionId = storage.sessionId
}
return { text, usage, sessionId }
} finally {
// Cleanup handled by agent session if needed
}
}
export interface AgentChatParams {
teamId: string
agentId: string
message: string
imageUrls: string[]
projectId: string
folderId: string
agentsInstruction?: string
sessionId: string
userId?: string
explicitMention?: boolean
context: AgentExecutionContext
}
export async function agentChatActivity(params: AgentChatParams) {
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
const sessionId = params.sessionId
return executeAgentPrompt({
teamId: params.teamId,
agentId: params.agentId,
prompt: cleanMessage,
images: params.imageUrls,
agentsInstruction: params.agentsInstruction || '',
sessionId,
userId: params.userId,
context: params.context,
})
}
export interface AutofillAiParams {
teamId: string
images: string[]
fields: AutofillField[]
context: AgentExecutionContext
}
export async function autofillAiActivity(params: AutofillAiParams) {
const prompt = 'Analyze the provided images and extract metadata.'
const toolSchema = fieldsToTypeBoxSchema(params.fields)
let capturedData: Record<string, unknown> | null = null
const autofillTool: AgentTool = {
name: 'autofill_metadata',
label: 'Autofill Metadata',
description: 'Extract metadata from the images.',
parameters: toolSchema,
execute: async (_toolCallId, toolParams) => {
capturedData = toolParams as Record<string, unknown>
return {
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
details: {},
}
},
}
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
const { agent } = params.context
const { usage, sessionId } = await executeAgentPrompt({
teamId: params.teamId,
agentId: agent.id,
prompt: fullPrompt,
images: params.images,
agentsInstruction: '',
sessionId: undefined,
userId: undefined,
tools: [autofillTool],
context: params.context,
})
return {
text: capturedData ? JSON.stringify(capturedData) : '{}',
usage,
sessionId,
}
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { generateEmbeddingActivity } from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
listObjects: vi.fn(),
},
}))
const mockEmbedContent = vi.fn().mockResolvedValue({
embeddings: [
{
values: [0.1, 0.2, 0.3],
},
],
})
vi.mock('@google/genai', () => {
return {
// eslint-disable-next-line @typescript-eslint/naming-convention
GoogleGenAI: class {
models = {
embedContent: mockEmbedContent,
}
},
}
})
describe('AI Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
process.env.GEMINI_API_KEY = 'test-key'
})
it('should generate image embedding', async () => {
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('test-image'),
contentType: 'image/png',
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting
} as any)
const context = {
agent: { config: { provider: 'google', model: 'gemini' } },
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
}
const res = await generateEmbeddingActivity({
teamId: 't1',
assetId: 'a1',
context,
})
expect(res.embeddings.length).toBe(1)
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
})
})
+261
View File
@@ -0,0 +1,261 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/transcode'
import { exec } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { promisify } from 'util'
import { ApplicationFailure } from '@temporalio/activity'
const execAsync = promisify(exec)
export interface Usage {
inputTokens: number
outputTokens: number
model: string
}
export interface GeneratedEmbedding {
embedding: number[]
startTime?: number
endTime?: number
}
export interface GenerateEmbeddingParams {
teamId: string
assetId: string
context: {
agent: unknown
asset: unknown
}
}
async function generateMultimodalEmbedding(
ai: GoogleGenAI,
buffer: Buffer,
mimeType: string,
): Promise<number[]> {
const response = await ai.models.embedContent({
model: 'gemini-embedding-2',
contents: [
{
inlineData: {
data: buffer.toString('base64'),
mimeType,
},
},
],
config: {
outputDimensionality: 1536,
},
})
const values = response.embeddings?.[0]?.values
if (!values) {
throw new Error('No embedding values returned from gemini-embedding-2')
}
return values
}
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams): Promise<{
embeddings: GeneratedEmbedding[]
usage: Usage
}> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context properties are fetched as JSON from the DB activity
const { asset } = params.context as any
if (!asset.mediaType) {
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
}
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const isImage = asset.mediaType.startsWith('image/')
const isVideo = asset.mediaType.startsWith('video/')
if (!isImage && !isVideo) {
throw ApplicationFailure.create({
message: `unsupported media type for embeddings: ${asset.mediaType}`,
nonRetryable: true,
})
}
const key = asset.storageKey?.key
if (!key) {
throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true })
}
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
const results: GeneratedEmbedding[] = []
if (isImage) {
const embVec = await generateMultimodalEmbedding(ai, data, asset.mediaType)
results.push({ embedding: embVec })
} else if (isVideo) {
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
fs.writeFileSync(tmpFile, data)
try {
const { stdout } = await execAsync(
`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${tmpFile}"`,
)
const duration = parseFloat(stdout.trim())
if (isNaN(duration)) {
throw ApplicationFailure.create({
message: 'failed to parse video duration',
nonRetryable: true,
})
}
const chunkSize = 60.0
for (let start = 0.0; start < duration; start += chunkSize) {
let end = start + chunkSize
if (end > duration) end = duration
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
await execAsync(
`ffmpeg -y -i "${tmpFile}" -ss ${start} -t ${end - start} -c copy "${chunkTmp}"`,
)
const chunkData = fs.readFileSync(chunkTmp)
fs.unlinkSync(chunkTmp)
try {
const embVec = await generateMultimodalEmbedding(ai, chunkData, 'video/mp4')
results.push({ embedding: embVec, startTime: start, endTime: end })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
console.error(
`failed to generate video embedding for chunk ${start}-${end}: ${e.message}`,
)
}
}
} finally {
fs.unlinkSync(tmpFile)
}
}
return {
embeddings: results,
usage,
}
}
export interface GenerateTextEmbeddingParams {
text: string
teamId: string
}
export async function generateTextEmbeddingActivity(params: GenerateTextEmbeddingParams): Promise<{
embedding: number[]
usage: Usage
}> {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const response = await ai.models.embedContent({
model: 'gemini-embedding-2',
contents: [
{
parts: [{ text: params.text }],
role: 'user',
},
],
config: {
outputDimensionality: 1536,
},
})
const values = response.embeddings?.[0]?.values
if (!values) {
throw new Error('No embedding values returned from gemini-embedding-2')
}
return {
embedding: values,
usage,
}
}
export interface ExtractAiMetadataParams {
assetKey: string
filePath: string
type: 'autofill'
isImage: boolean
}
export async function extractAiMetadataActivity(
params: ExtractAiMetadataParams,
): Promise<string[]> {
const bucket = process.env.S3_BUCKET || 'shumai'
const assetDir = path.dirname(params.assetKey)
const aiDir = path.join(assetDir, 'ai_metadata')
const generatedFiles: string[] = []
const tmpDir = path.dirname(params.filePath)
try {
if (params.type === 'autofill') {
const targetKey = path.join(aiDir, '1.webp')
try {
await s3Service.headObject(bucket, targetKey)
const keys = await s3Service.listObjects(bucket, aiDir)
return keys.filter((k) => k.toLowerCase().endsWith('.webp'))
} catch {
// Not found
}
const files = await transcodeService.extractVideoFrames({
inputFile: params.filePath,
outputDir: tmpDir,
numFrames: 30,
frameHeight: 720,
isImage: params.isImage,
})
for (const file of files) {
const name = path.basename(file)
const buffer = fs.readFileSync(file)
const key = path.join(aiDir, name)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
generatedFiles.push(key)
}
}
} finally {
// Files are in tmpDir which will be cleaned up by cleanupTmpDirActivity
}
return generatedFiles
}
@@ -0,0 +1,390 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi } from 'vitest'
import { DatabaseSessionStorage } from './database-session-storage'
import { agentService } from '@shumai/core/src/agent/agent'
import { createAgentSession } from './index'
import * as sandboxedBashModule from './tools/sandboxed-bash'
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,
teamId: team.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(),
message: {
role: 'assistant',
content: [],
timestamp: Date.now(),
provider: 'p',
model: 'm',
api: 'api',
usage: { input: 0, output: 0 },
// AssistantMessage has many internal fields from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} 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 strip and reinject skill content', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const getSkillContentSpy = vi
.spyOn(agentService, 'getSkillContent')
.mockResolvedValue('# Mocked Skill Content')
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-skill',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-2',
toolName: 'read_skill',
isError: false,
timestamp: Date.now(),
content: [{ type: 'text', text: 'original-skill-content' }],
details: {
skillId: 'some-skill-id',
},
},
}
await storage.appendEntry(entry)
// Verify saved entry is stripped
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-skill' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const savedEntry = record?.entry as any
expect(savedEntry.message.content[0].text).toBe('__SKILL_CONTENT__')
// Verify retrieval reinjects data
const retrieved = await storage.getEntry('msg-skill')
expect(getSkillContentSpy).toHaveBeenCalledWith('some-skill-id')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((retrieved as any).message.content[0].text).toBe('# Mocked Skill Content')
})
it('should restore environment variables when resuming session', async () => {
const { agent, user } = await setupTestData()
// 1. Create a session first to get a sessionId
const initialStorage = await DatabaseSessionStorage.create({ agentId: agent.id })
const sessionId = initialStorage.sessionId
// 2. Append a successful read_skill entry
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-skill-env',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-env-1',
toolName: 'read_skill',
isError: false,
timestamp: Date.now(),
content: [{ type: 'text', text: 'skill content' }],
details: {
skillId: 'env-skill-id',
},
},
}
await initialStorage.appendEntry(entry)
// 3. Mock getSkillEnvs to return environment variables
const getSkillEnvsSpy = vi.spyOn(agentService, 'getSkillEnvs').mockResolvedValue({
MOCK_ENV_VAR: 'mocked-value',
})
// 4. Mock agentService.getSkillContent to avoid actual download throws
vi.spyOn(agentService, 'getSkillContent').mockResolvedValue('# Skill')
// 5. Spy on createSandboxedBashTool
const createSandboxedBashToolSpy = vi.spyOn(sandboxedBashModule, 'createSandboxedBashTool')
// 6. Resume the session via createAgentSession
await createAgentSession({
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
systemPrompt: 'Test prompt',
teamSkills: [],
allowedDomains: [],
sessionId: sessionId,
userId: user.id,
providers: [],
})
// 7. Verify skill environment variables are restored.
expect(getSkillEnvsSpy).toHaveBeenCalledWith('env-skill-id')
expect(createSandboxedBashToolSpy).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
MOCK_ENV_VAR: 'mocked-value',
}),
)
})
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')
})
it('should retrieve entries in order', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
// Insert entries out of order (by insertion time) but with ordered IDs
await storage.appendEntry({
type: 'message',
id: '01B',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: '01A',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: '01C',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
const entries = await storage.getEntries()
expect(entries).toHaveLength(3)
expect(entries[0].id).toBe('01A')
expect(entries[1].id).toBe('01B')
expect(entries[2].id).toBe('01C')
})
})
@@ -0,0 +1,270 @@
import { prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { ulid } from 'ulid'
import {
type AgentMessage,
type SessionMetadata,
type SessionStorage,
type SessionTreeEntry,
type SessionTreeEntryBase,
} from '@earendil-works/pi-agent-core'
import { agentService } from '@shumai/core/src/agent/agent'
export interface DatabaseSessionMetadata extends SessionMetadata {
agentId: string
userId?: string
cwd: string
}
export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMetadata> {
constructor(public readonly 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> {
return ulid()
}
async appendEntry(entry: SessionTreeEntry): Promise<void> {
const strippedEntry = structuredClone(entry)
// Strip image data and skill content before saving to DB
if (strippedEntry.type === 'message') {
const msg = strippedEntry.message
if (msg.role === 'toolResult') {
const details = msg.details as { sourceKeys?: string[]; skillId?: string } | undefined
// Strip S3 image data
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++
}
})
}
// Strip skill content
if (msg.toolName === 'read_skill' && !msg.isError) {
if (details?.skillId && Array.isArray(msg.content)) {
msg.content.forEach((item: { type: string; text?: string }) => {
if (
item.type === 'text' &&
item.text &&
!item.text.startsWith('Skill with ID') &&
!item.text.startsWith('Skill downloaded but') &&
!item.text.startsWith('Error reading skill')
) {
item.text = '__SKILL_CONTENT__'
}
})
}
}
}
}
await prisma.agentSessionEntry.create({
data: {
id: entry.id,
sessionId: this.sessionId,
entry: strippedEntry,
},
})
// 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)
await this.reinjectSkillContentAsync(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)
await this.reinjectSkillContentAsync(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 []
// Fetch all entries for this session in a single query to avoid N+1 problem
const records = await prisma.agentSessionEntry.findMany({
where: { sessionId: this.sessionId },
})
// Build a map for fast lookup
const entryMap = new Map<string, SessionTreeEntry>()
for (const record of records) {
entryMap.set(record.id, record.entry as unknown as SessionTreeEntry)
}
const pathEntries: SessionTreeEntry[] = []
let currentId: string | null = leafId
while (currentId) {
const entry = entryMap.get(currentId)
if (!entry) break
pathEntries.unshift(entry)
currentId = (entry as SessionTreeEntryBase).parentId
}
// Only reinject image data (which may involve S3 calls) for the entries in the path
for (const entry of pathEntries) {
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
}
return pathEntries
}
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)
await this.reinjectSkillContentAsync(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++
}
}
}
}
}
}
private async reinjectSkillContentAsync(entry: SessionTreeEntry) {
if (entry.type === 'message') {
const msg = entry.message as AgentMessage
if (msg.role === 'toolResult' && msg.toolName === 'read_skill') {
const details = msg.details as { skillId?: string } | undefined
if (details?.skillId && Array.isArray(msg.content)) {
for (const item of msg.content) {
if (item.type === 'text' && item.text === '__SKILL_CONTENT__') {
try {
const content = await agentService.getSkillContent(details.skillId)
item.text = content
} catch (err) {
console.error(
`Failed to re-inject skill content for skill ${details.skillId}:`,
err,
)
}
}
}
}
}
}
}
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)
}
}
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest'
import { formatSkillsForPrompt } from './index'
import * as path from 'path'
describe('formatSkillsForPrompt', () => {
it('should return empty string if skills array is empty', () => {
expect(formatSkillsForPrompt([])).toBe('')
})
it('should format skills into the XML structure with absolute paths and escaped characters', () => {
const skills = [
{
id: 'skill-1',
name: 'Deploy & Test',
description: 'Deploys code <deploy> and "runs" tests.',
},
]
const expectedLocation = path.join(process.cwd(), '.pi', 'skills', 'skill-1', 'SKILL.md')
const result = formatSkillsForPrompt(skills)
// Verify lines and XML elements
expect(result).toContain('<available_skills>')
expect(result).toContain('<skill>')
expect(result).toContain('<name>Deploy &amp; Test</name>')
expect(result).toContain(
'<description>Deploys code &lt;deploy&gt; and &quot;runs&quot; tests.</description>',
)
expect(result).toContain(`<location>${expectedLocation}</location>`)
expect(result).toContain('</skill>')
expect(result).toContain('</available_skills>')
})
})
+325
View File
@@ -0,0 +1,325 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
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 { agentService } from '@shumai/core/src/agent/agent'
import { DatabaseSessionStorage } from './database-session-storage'
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
import { createCreateFileTool } from './tools/create-file'
import { createCreateFolderTool } from './tools/create-folder'
import { createCreateVersionTool } from './tools/create-version'
import { createListAssetsTool } from './tools/list-assets'
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[]
sessionId?: string
userId?: string
customTools?: AgentTool[]
providers: Array<{
name: string
config: PrismaJson.ProviderConfig
models: Array<{
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}>
}>
}
export async function createAgentSession(params: CreateAgentSessionParams) {
const {
agentId,
providerName,
modelId,
systemPrompt,
teamSkills,
allowedDomains,
sessionId,
userId,
customTools = [],
} = params
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 })
// 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)
if (!dbProvider || !dbModel) return undefined
// Model contains complex internal types from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-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,
}
}
// 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 = getModelFromDb(providerName, modelId) || (getModel as any)(providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const allowWrite = [piDir]
// SandboxManager.initialize is a global operation that applies to the entire process.
await SandboxManager.initialize({
network: {
allowedDomains,
deniedDomains: [],
},
filesystem: {
denyRead: ['.env', '.env.*', '*.pem', '*.key'],
allowWrite,
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
},
})
const skillEnvs: Record<string, string> = {}
const onEnvsAdded = (envs: Record<string, string>) => {
Object.assign(skillEnvs, envs)
}
// Restore env variables from previously loaded skills in this session
if (sessionId) {
try {
const entries = await storage.getEntries()
for (const entry of entries) {
if (
entry.type === 'message' &&
entry.message.role === 'toolResult' &&
entry.message.toolName === 'read_skill' &&
!entry.message.isError
) {
const details = entry.message.details as { skillId?: string } | undefined
if (details?.skillId) {
const envs = await agentService.getSkillEnvs(details.skillId)
onEnvsAdded(envs)
}
}
}
} catch (err) {
console.error('Failed to restore skill environment variables:', err)
}
}
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs)
const readSkill = createReadSkillTool(onEnvsAdded)
const systemTools: AgentTool[] = []
if (userId) {
systemTools.push(
createListAssetsTool(userId),
createCreateFolderTool(userId),
createCreateFileTool(userId),
createCreateVersionTool(userId),
)
}
const harness = new AgentHarness({
env: new NodeExecutionEnv({ cwd: process.cwd() }),
session,
model,
systemPrompt: async () => {
let prompt = systemPrompt
// Sandbox environment restrictions
prompt +=
'\n\n' +
[
'# Sandbox Environment Restrictions',
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
].join('\n')
if (teamSkills.length > 0) {
prompt += formatSkillsForPrompt(teamSkills)
}
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, ...systemTools, ...customTools],
})
return { session, harness }
}
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)
}
function escapeXml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
}
export function formatSkillsForPrompt(
skills: Array<{ id: string; name: string; description?: string | null }>,
): string {
if (skills.length === 0) {
return ''
}
const lines = [
'\n\nThe following skills provide specialized instructions for specific tasks.',
"Use the read_skill tool to load a skill's file when the task matches its description.",
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
'',
'<available_skills>',
]
for (const skill of skills) {
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
lines.push(' <skill>')
lines.push(` <name>${escapeXml(skill.name)}</name>`)
lines.push(` <description>${escapeXml(skill.description || 'No description')}</description>`)
lines.push(` <location>${escapeXml(filePath)}</location>`)
lines.push(' </skill>')
}
lines.push('</available_skills>')
return lines.join('\n')
}
import { registerWorkflow, registerActivities } from '@shumai/workflow-core'
import { WorkflowTaskType } from '@shumai/db'
import { agentEmbeddingMedia } from './workflows/agent-embedding'
import { queryEmbeddingForSearch } from './workflows/query-embedding-for-search'
import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat'
import { agentToolCall } from './workflows/agent-tool-call'
import * as agentActivities from './activities/agent'
import * as aiActivities from './activities/ai'
export function initAgentWorkflows() {
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
registerWorkflow(WorkflowTaskType.query_embedding_for_search, queryEmbeddingForSearch)
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
registerWorkflow(WorkflowTaskType.chat, agentChat)
registerWorkflow(WorkflowTaskType.agent_tool_call, agentToolCall)
registerActivities(agentActivities)
registerActivities(aiActivities)
}
export * from './database-session-storage'
export * from './activities/agent'
export {
type GeneratedEmbedding,
type GenerateEmbeddingParams,
generateEmbeddingActivity,
type GenerateTextEmbeddingParams,
generateTextEmbeddingActivity,
type ExtractAiMetadataParams,
extractAiMetadataActivity,
} from './activities/ai'
export * from './workflows/agent-autofill'
export * from './workflows/agent-chat'
export * from './workflows/agent-embedding'
export * from './workflows/agent-tool-call'
export * from './workflows/query-embedding-for-search'
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest'
import { fieldsToTypeBoxSchema, type AutofillField } from './index'
describe('fieldsToTypeBoxSchema', () => {
it('converts text fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Title', type: 'text' }, description: 'The title' },
{ id: 'f2', config: { name: 'Desc', type: 'longText' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.description).toBe('The title')
expect(schema.properties.f2.type).toBe('string')
})
it('converts numeric fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Price', type: 'number' } },
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('number')
expect(schema.properties.f2.type).toBe('number')
})
it('converts toggle fields', () => {
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('boolean')
})
it('converts select fields with enums', () => {
const fields: AutofillField[] = [
{
id: 'f1',
config: {
name: 'Status',
type: 'select',
select: {
options: [
{ id: 'opt1', displayName: 'Option 1', color: 'red' },
{ id: 'opt2', displayName: 'Option 2', color: 'blue' },
],
},
},
},
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2'])
})
it('defaults to string for unknown types', () => {
const fields: AutofillField[] = [
// @ts-ignore
{ id: 'f1', config: { name: 'Unknown', type: 'invalid' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
})
})
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeAssetMediaTool } from './analyze-asset-media'
import { s3Service } from '@shumai/core/src/s3/s3'
vi.mock('@shumai/core/src/s3/s3')
describe('analyzeAssetMediaTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should analyze media by S3 key and return image content', async () => {
// Mock S3 with WEBP magic bytes
const buffer = Buffer.from([
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'image/webp' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/test.webp' },
undefined,
undefined,
)
expect(result.content[0].type).toBe('image')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('image/webp')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.details as any).sourceKey).toBe('assets/test.webp')
})
it('should infer mimeType from content if S3 response has generic mimeType', async () => {
// Mock S3 with MP4 magic bytes
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',
})
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/no-extension-but-mp4' },
undefined,
undefined,
)
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('video/mp4')
})
it('should return error if S3 getObject fails', async () => {
// Mock S3 failure
vi.mocked(s3Service.getObject).mockRejectedValue(new Error('S3 error'))
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/non-existent' },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const textContent = (result.content[0] as any).text
expect(textContent).toContain('Error analyzing media: S3 error')
})
})
@@ -0,0 +1,74 @@
import { s3Service } from '@shumai/core/src/s3/s3'
import { Type } from '@sinclair/typebox'
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({
key: Type.String({
description:
'The S3 key of the media file to analyze. This MUST be a key obtained from the asset media info.',
}),
})
export interface MediaAnalysisDetails {
sourceKey: string
}
export const analyzeAssetMediaTool: AgentTool<
typeof analyzeAssetMediaSchema,
MediaAnalysisDetails
> = {
name: 'analyze_asset_media',
label: 'Analyze Asset Media',
description:
'Retrieves and views the media content (images/video) by its S3 key. The key must be obtained from the asset media info provided in the context.',
parameters: analyzeAssetMediaSchema,
execute: async (_toolCallId, params) => {
try {
const { key } = params
if (!key) {
return {
content: [{ type: 'text', text: 'S3 key is required.' }],
details: { sourceKey: '' },
}
}
const bucket = process.env.S3_BUCKET || 'shumai'
const { buffer, contentType } = await s3Service.getObject(bucket, key)
const uint8Array = new Uint8Array(buffer)
let mimeType = contentType
if (mimeType === 'application/octet-stream') {
mimeType = detectSupportedMimeType(uint8Array) || 'application/octet-stream'
}
const content: (TextContent | ImageContent)[] = [
{
type: 'image',
data: buffer.toString('base64'),
mimeType,
},
]
return {
content,
details: {
sourceKey: key,
},
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error analyzing media: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { sourceKey: params.key || '' },
}
}
},
}
+99
View File
@@ -0,0 +1,99 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
function getMimeType(filePath: string): string {
try {
const fd = fs.openSync(filePath, 'r')
try {
const buffer = Buffer.alloc(4100)
const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0)
const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead)))
if (detected) return detected
} finally {
fs.closeSync(fd)
}
} catch {
/* Ignore detection errors and fallback to extension mapping */
}
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.pdf': 'application/pdf',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const createFileSchema = Type.Object({
parent: Type.String({
description: 'The parent folder ID under which to create the file. This parameter is required.',
}),
path: Type.String({
description:
'The absolute or relative local path to the file on disk. This parameter is required.',
}),
})
export function createCreateFileTool(userId: string): AgentTool<typeof createFileSchema> {
return {
name: 'create_file',
label: 'Create File',
description: 'Create a new file in a specified parent folder from a local file path.',
parameters: createFileSchema,
execute: async (_toolCallId, params) => {
try {
const absolutePath = path.resolve(process.cwd(), params.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${params.path}`)
}
const fileSize = fs.statSync(absolutePath).size
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `file/${ulid()}/raw`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
toolName: 'create_file',
args: {
parent: params.parent,
s3Key,
name: path.basename(absolutePath),
size: fileSize,
contentType: mimeType,
},
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating file: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+46
View File
@@ -0,0 +1,46 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
const createFolderSchema = Type.Object({
parent: Type.String({
description:
'The parent folder ID under which to create the new folder. This parameter is required.',
}),
name: Type.String({
description: 'The name of the new folder to create. This parameter is required.',
}),
})
export function createCreateFolderTool(userId: string): AgentTool<typeof createFolderSchema> {
return {
name: 'create_folder',
label: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
parameters: createFolderSchema,
execute: async (_toolCallId, params) => {
try {
const result = await executeAgentToolWorkflow({
toolName: 'create_folder',
args: params,
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating folder: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+100
View File
@@ -0,0 +1,100 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@shumai/core/src/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
function getMimeType(filePath: string): string {
try {
const fd = fs.openSync(filePath, 'r')
try {
const buffer = Buffer.alloc(4100)
const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0)
const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead)))
if (detected) return detected
} finally {
fs.closeSync(fd)
}
} catch {
/* Ignore detection errors and fallback to extension mapping */
}
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.pdf': 'application/pdf',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const createVersionSchema = Type.Object({
parent: Type.String({
description:
'The parent file ID for which to create a new version. This parameter is required.',
}),
path: Type.String({
description:
'The absolute or relative local path to the file on disk. This parameter is required.',
}),
})
export function createCreateVersionTool(userId: string): AgentTool<typeof createVersionSchema> {
return {
name: 'create_version',
label: 'Create Version',
description: 'Create a new version of an existing file from a local file path.',
parameters: createVersionSchema,
execute: async (_toolCallId, params) => {
try {
const absolutePath = path.resolve(process.cwd(), params.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${params.path}`)
}
const fileSize = fs.statSync(absolutePath).size
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `file/${ulid()}/raw`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
toolName: 'create_version',
args: {
parent: params.parent,
s3Key,
name: path.basename(absolutePath),
size: fileSize,
contentType: mimeType,
},
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating file version: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+61
View File
@@ -0,0 +1,61 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
const listAssetsSchema = Type.Object({
parent: Type.String({
description: 'The parent folder ID to list assets from. This parameter is required.',
}),
page: Type.Optional(
Type.Number({
description: 'The page number to retrieve, default is 1.',
default: 1,
}),
),
pageSize: Type.Optional(
Type.Number({
description: 'The number of assets per page, default is 20.',
default: 20,
}),
),
type: Type.Optional(
Type.String({
description: "Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'.",
enum: ['file', 'folder', 'all'],
default: 'all',
}),
),
})
export function createListAssetsTool(userId: string): AgentTool<typeof listAssetsSchema> {
return {
name: 'list_assets',
label: 'List Assets',
description: 'List the assets (files and folders) inside a parent folder with pagination.',
parameters: listAssetsSchema,
execute: async (_toolCallId, params) => {
try {
const result = await executeAgentToolWorkflow({
toolName: 'list_assets',
args: params,
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error listing assets: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+264
View File
@@ -0,0 +1,264 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { createReadSkillTool } from './read-skill'
import { s3Service } from '@shumai/core/src/s3/s3'
import * as fs from 'fs'
vi.mock('@shumai/core/src/s3/s3')
vi.mock('fs')
vi.mock('adm-zip', () => {
return {
default: class {
extractAllTo = vi.fn()
},
}
})
describe('readSkillTool', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should return error if skill not found', async () => {
const readSkillTool = createReadSkillTool(() => {})
const result = await readSkillTool.execute(
'1',
{ skillId: 'non-existent' },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toContain('not found')
})
it('should read skill from cache if hash matches', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Test Skill',
assetId: 'asset1',
hash: 'match-hash',
teamId: team.id,
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'match-hash'
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
return ''
})
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()
})
it('should download and extract skill if cache missing or hash mismatch', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'New Skill',
assetId: 'asset1',
hash: 'new-hash',
teamId: team.id,
},
})
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
storageKey: { create: { key: 'skills/skill.zip' } },
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return false
if (path.toString().endsWith('SKILL.md')) return true
return true
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({
buffer: Buffer.from('zipdata'),
contentType: 'application/zip',
})
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')
expect(s3Service.getObject).toHaveBeenCalled()
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
})
describe('environment variables', () => {
let originalEnv: NodeJS.ProcessEnv
beforeEach(() => {
originalEnv = { ...process.env }
})
afterEach(() => {
process.env = originalEnv
})
it('should use user-configured value if it is non-empty', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Skill Env Test 1',
assetId: 'asset1',
hash: 'hash1',
teamId: team.id,
config: {
environmentVariables: [{ name: 'CONFIGURED_VAR', default: 'user-val' }],
},
},
})
delete process.env.CONFIGURED_VAR
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash1'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
CONFIGURED_VAR: 'user-val',
})
})
it('should favor user-configured value even if host environment variable is also defined', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Skill Env Test 2',
assetId: 'asset1',
hash: 'hash2',
teamId: team.id,
config: {
environmentVariables: [{ name: 'OVERRIDDEN_VAR', default: 'user-val' }],
},
},
})
process.env.OVERRIDDEN_VAR = 'host-val'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash2'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
OVERRIDDEN_VAR: 'user-val',
})
})
it('should fall back to host environment variable if user-configured value is empty string', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Skill Env Test 3',
assetId: 'asset1',
hash: 'hash3',
teamId: team.id,
config: {
environmentVariables: [{ name: 'FALLBACK_VAR', default: '' }],
},
},
})
process.env.FALLBACK_VAR = 'host-val'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash3'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR: 'host-val',
})
})
it('should fall back to host environment variable if user-configured value is undefined', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Skill Env Test 4',
assetId: 'asset1',
hash: 'hash4',
teamId: team.id,
config: {
environmentVariables: [{ name: 'FALLBACK_VAR_UNDEF' }],
},
},
})
process.env.FALLBACK_VAR_UNDEF = 'host-val2'
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'hash4'
if (path.toString().endsWith('SKILL.md')) return '# Content'
return ''
})
let capturedEnvs: Record<string, string> = {}
const readSkillTool = createReadSkillTool((envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR_UNDEF: 'host-val2',
})
})
})
})
+55
View File
@@ -0,0 +1,55 @@
import { prisma } from '@shumai/db'
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { agentService } from '@shumai/core/src/agent/agent'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
})
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 using agentService
const envs = await agentService.getSkillEnvs(params.skillId)
onEnvsAdded(envs)
// Retrieve skill content using agentService
const skillMdContent = await agentService.getSkillContent(params.skillId)
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 },
}
}
},
})
@@ -0,0 +1,181 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
vi.mock('@anthropic-ai/sandbox-runtime')
vi.mock('node:child_process')
describe('createSandboxedBashTool', () => {
const mockCwd = '/mock/cwd'
const mockSessionManager = {
getSkillEnvs: vi.fn(),
}
beforeEach(() => {
vi.clearAllMocks()
mockSessionManager.getSkillEnvs.mockReturnValue({ TEST_ENV: 'test-value' })
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SandboxManager.wrapWithSandbox is a mocked async function from a 3rd party library
;(SandboxManager.wrapWithSandbox as any).mockImplementation(
async (cmd: string) => `sandboxed-${cmd}`,
)
})
const createMockSignal = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- signal needs to be partially compatible with AbortSignal but we need to emit events for testing
const signal = new EventEmitter() as any
signal.addEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.on(event, cb)
})
signal.removeEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
signal.off(event, cb)
})
signal.aborted = false
return signal
}
const createMockOnUpdate = () => vi.fn()
it('should execute a command in the sandbox with injected env vars', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockStdout = new EventEmitter()
const mockStderr = new EventEmitter()
const mockChild = Object.assign(new EventEmitter(), {
stdout: mockStdout,
stderr: mockStderr,
pid: 123,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const onUpdate = createMockOnUpdate()
const signal = createMockSignal()
// pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?)
const executePromise = tool.execute('1', { command: 'echo hello' }, signal, onUpdate)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith('echo hello')
expect(spawn).toHaveBeenCalledWith(
'bash',
['-c', 'sandboxed-echo hello'],
expect.objectContaining({
env: expect.objectContaining({
TEST_ENV: 'test-value',
}),
}),
)
// Simulate stdout data
mockStdout.emit('data', Buffer.from('hello output'))
mockChild.emit('close', 0)
const result = await executePromise
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
expect((result as any).content[0].text).toContain('hello output')
})
it('should handle process errors', async () => {
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)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'fail' }, signal, createMockOnUpdate())
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
mockChild.emit('error', new Error('spawn failed'))
await expect(executePromise).rejects.toThrow('spawn failed')
})
it('should handle non-zero exit codes', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 1,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'exit 1' }, signal, createMockOnUpdate())
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
mockChild.emit('close', 1)
await expect(executePromise).rejects.toThrow(/exited with code 1/)
})
it('should handle timeouts', async () => {
vi.useFakeTimers()
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 456,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
'1',
{ command: 'sleep 10', timeout: 2 },
signal,
createMockOnUpdate(),
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
await vi.advanceTimersByTimeAsync(2100)
expect(killSpy).toHaveBeenCalledWith(-456, 'SIGKILL')
mockChild.emit('close', null)
await expect(executePromise).rejects.toThrow(/timed out/)
vi.useRealTimers()
killSpy.mockRestore()
})
it('should handle abort signals', async () => {
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
const mockChild = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
pid: 789,
kill: vi.fn(),
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
;(spawn as any).mockReturnValue(mockChild)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'long-run' }, signal, createMockOnUpdate())
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
signal.aborted = true
signal.emit('abort')
expect(killSpy).toHaveBeenCalledWith(-789, 'SIGKILL')
mockChild.emit('close', null)
await expect(executePromise).rejects.toThrow(/aborted/)
killSpy.mockRestore()
})
})
+129
View File
@@ -0,0 +1,129 @@
import { logger } from '@/logger'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { Type } from '@sinclair/typebox'
import { spawn } from 'node:child_process'
const BashParameters = Type.Object({
command: Type.String({ description: 'The bash command to execute.' }),
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
})
type BashDetails = {
exitCode: number | null
stdout: string
stderr: string
}
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)
return new Promise((resolve, reject) => {
const child = spawn('bash', ['-c', wrappedCommand], {
cwd,
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
PATH: process.env.PATH || '',
HOME: process.env.HOME || '',
...skillEnvs,
},
})
let stdout = ''
let stderr = ''
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', (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)
logger.error(
{ err, command, stdout, stderr },
'Sandboxed bash command encountered process error',
)
reject(err)
})
child.on('close', (code) => {
if (timeoutHandle) clearTimeout(timeoutHandle)
signal?.removeEventListener('abort', onAbort)
if (signal?.aborted) {
logger.error({ command, stdout, stderr }, 'Sandboxed bash command aborted')
reject(new Error('aborted'))
} else if (timedOut) {
logger.error({ timeout, command, stdout, stderr }, 'Sandboxed bash command timed out')
reject(new Error(`bash command timed out after ${timeout} seconds`))
} else if (code !== 0 && code !== null) {
logger.error(
{ exitCode: code, command, stdout, stderr },
'Sandboxed bash command exited with failure code',
)
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,
},
})
}
})
})
},
}
}
+35
View File
@@ -0,0 +1,35 @@
import { prisma } from '@shumai/db'
import { workflowService } from '@shumai/workflow-core'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
export async function executeAgentToolWorkflow(params: {
toolName: string
args: Record<string, unknown>
userId: string
assetId: string
}): Promise<unknown> {
const task = await prisma.workflowTask.create({
data: {
type: WorkflowTaskType.agent_tool_call,
status: WorkflowTaskStatus.pending,
assetId: params.assetId,
payload: {
projectId: 'none',
agentToolCall: {
toolName: params.toolName,
args: params.args,
userId: params.userId,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
if (completedTask.status === WorkflowTaskStatus.failed) {
const output = completedTask.output as Record<string, unknown> | null
const errorMsg = (output?.error as string) || 'Workflow task failed'
throw new Error(errorMsg)
}
return completedTask.output
}
@@ -0,0 +1,101 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentAutofillMedia } from './agent-autofill'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
describe('Agent Autofill Workflow', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should run agent autofill workflow successfully', async () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
extractAiMetadataActivity: Object.assign(vi.fn(), {
_activityName: 'extractAiMetadataActivity',
}),
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
_activityName: 'getProjectAutofillFieldsActivity',
}),
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentAutofillContextActivity',
}),
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
updateAssetMetadataActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetMetadataActivity',
}),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
}
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getAssetActivity.mockResolvedValue({
id: 'a1',
storageKey: { key: 'asset-key' },
project: { id: 'p1', teamId: 't1' },
mediaType: 'image/png',
})
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.png',
tmpDir: '/tmp',
})
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp'])
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
{ id: 'f1', key: 'f1', config: { name: 'F1', type: 'text' } },
])
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.autofillAiActivity.mockResolvedValue({
text: '{"f1":"val"}',
sessionId: 'session-123',
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
return (act as any)(...args)
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_metadata_autofill',
status: 'pending',
assetId: 'a1',
},
})
await agentAutofillMedia(task)
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled()
expect(mockActivities.autofillAiActivity).toHaveBeenCalled()
})
})
@@ -0,0 +1,204 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueAgent,
TaskQueueTranscode,
} from '@shumai/workflow-core'
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
extractAiMetadataActivity,
getProjectAutofillFieldsActivity,
getAgentAutofillContextActivity,
autofillAiActivity,
updateTaskUsageActivity,
updateAssetMetadataActivity,
createCommentActivity,
updateCommentActivity,
getTranscodeWorkerQueueActivity,
getAgentWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let tmpDir: string | undefined
let transcodeWorkerQueue = ''
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__AUTOFILL__',
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
placeholderCommentId = placeholder.id
// 1. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
const key = asset?.storageKey?.key
if (!asset || !asset.project || !key) {
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
}
const teamId = asset.project.teamId
const projectId = asset.project.id
// 2. Prepare Data (Images)
const isImage = asset.mediaType?.startsWith('image/') || false
// Extraction requires FFmpeg, run on Transcode worker
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const { filePath } = download
tmpDir = download.tmpDir
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
assetKey: key,
filePath,
type: 'autofill',
isImage,
})
if (generatedFiles.length === 0) {
// If no images could be extracted, we can't do much
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No images could be extracted for analysis.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 3. Get Project Autofill Fields
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
if (fields.length === 0) {
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No autofill fields defined in project.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 3b. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity(TaskQueueDb, getAgentAutofillContextActivity, {
teamId,
})
// 4. Call AI Service
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
teamId,
images: generatedFiles,
fields: fields.map(
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
id: f.key,
config: f.config as unknown as PrismaJson.FieldConfig,
description: f.description,
}),
),
context,
})
if (aiResult.usage) {
// Update Usage
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// 6. Update Asset Metadata
const result = JSON.parse(aiResult.text)
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
key,
value,
}))
if (metadataUpdates.length > 0) {
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
assetId: asset.id,
metadata: metadataUpdates,
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed successfully.',
sessionId: aiResult.sessionId,
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
} finally {
if (tmpDir && transcodeWorkerQueue) {
try {
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
}
}
}
export const agentAutofillWorkflow = agentAutofillMedia
@@ -0,0 +1,92 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentChat } from './agent-chat'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
describe('Agent Chat Workflow', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should run agent chat workflow successfully', async () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
initializeAgentSessionActivity: Object.assign(vi.fn(), {
_activityName: 'initializeAgentSessionActivity',
}),
getAgentChatContextActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentChatContextActivity',
}),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
agentChatActivity: Object.assign(vi.fn(), { _activityName: 'agentChatActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
getAssetPathContextActivity: Object.assign(vi.fn(), {
_activityName: 'getAssetPathContextActivity',
}),
}
mockActivities.getCommentActivity.mockResolvedValue({
id: 'c1',
message: 'hello',
replyToId: null,
})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.getAssetPathContextActivity.mockResolvedValue(
'Path: foo/bar/z.png\n\nname: foo, id: foo-id',
)
mockActivities.agentChatActivity.mockResolvedValue({
text: 'arr matey!',
sessionId: 'session-123',
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
return (act as any)(...args)
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a1',
payload: {
projectId: 'p1',
agent: { userCommentId: 'c1', agentId: 'b1' },
},
},
})
await agentChat(task)
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled()
expect(mockActivities.agentChatActivity).toHaveBeenCalled()
})
})
+204
View File
@@ -0,0 +1,204 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { executeActivity, getActivities, TaskQueueAgent, TaskQueueDb } from '@shumai/workflow-core'
export async function agentChat(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
getCommentActivity,
getAgentChatContextActivity,
agentChatActivity,
createCommentActivity,
updateCommentActivity,
updateTaskUsageActivity,
getAgentWorkerQueueActivity,
deleteCommentActivity,
initializeAgentSessionActivity,
getAssetPathContextActivity,
} = getActivities()
let placeholderCommentId: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
const payload = task.payload
if (!payload) {
throw ApplicationFailure.create({ message: 'Task payload is missing', nonRetryable: true })
}
const agentId = payload.agent?.agentId
if (!agentId) {
throw ApplicationFailure.create({ message: 'agentId missing in payload', nonRetryable: true })
}
let sessionId = payload.agent?.sessionId
// 1. Get User Comment
const userCommentId = payload.agent?.userCommentId
if (!userCommentId) {
throw ApplicationFailure.create({
message: 'userCommentId missing in payload',
nonRetryable: true,
})
}
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
if (!userComment) {
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
}
// 2. Create Placeholder Comment
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
sessionId: sessionId || 'pending',
agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
// 3. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
}
const teamId = asset.project.teamId
// 4. Initialize Session if missing (Database Activity on db_queue)
if (!sessionId) {
sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, {
teamId,
agentId: agentId,
userCommentId,
userId: payload.agent?.userId,
})
}
// 4b. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
teamId,
agentId: agentId,
})
// 5. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = []
if (userComment?.attachments) {
for (const att of userComment.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
attachmentImageUrls.push(att.asset.storageKey.key)
}
}
}
const pathContext = await executeActivity(
TaskQueueDb,
getAssetPathContextActivity,
task.assetId,
)
let instruction = `The user is discussing an asset with ID: ${asset.id}.`
if (pathContext) {
instruction += `\n\nAsset Path Context:\n${pathContext}`
}
if (asset.media) {
instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}`
}
instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
if (payload.agent?.explicitMention) {
instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.`
} else {
instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.`
}
// 6. Call AI Chat
let folderId = ''
if (asset.type === 'folder') {
folderId = asset.id
} else if (asset.parentId) {
folderId = asset.parentId
}
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
teamId,
agentId: agentId,
message: userComment.message || '',
imageUrls: attachmentImageUrls,
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId,
userId: payload.agent?.userId,
explicitMention: payload.agent?.explicitMention,
context,
})
// 7. Update Placeholder Comment
if (placeholderCommentId) {
if (aiResult.text.trim() === '__NO_REPLY__') {
await executeActivity(TaskQueueDb, deleteCommentActivity, placeholderCommentId)
} else {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
sessionId: aiResult.sessionId,
})
}
}
// 8. Update Usage
if (aiResult.usage) {
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
output: { sessionId: aiResult.sessionId },
})
} catch (err) {
console.error(`AgentChat failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
const errorMessage =
err instanceof Error && err.message.startsWith('AI error:')
? `AI error: ${err.message.substring(9)}`
: 'Sorry, I encountered an error while processing your request.'
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: errorMessage,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const agentChatWorkflow = agentChat
@@ -0,0 +1,79 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentEmbeddingMedia } from './agent-embedding'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
describe('Agent Embedding Workflow', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should run agent embedding workflow successfully', async () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
getEmbeddingContextActivity: Object.assign(vi.fn(), {
_activityName: 'getEmbeddingContextActivity',
}),
generateEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateEmbeddingActivity',
}),
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
_activityName: 'saveAssetEmbeddingsActivity',
}),
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
}
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: { id: 'a1' },
dbProvider: { name: 'google' },
})
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.generateEmbeddingActivity.mockResolvedValue({
embeddings: [{ embedding: [0.1, 0.2] }],
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
return (act as any)(...args)
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled()
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled()
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled()
})
})
@@ -0,0 +1,111 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@shumai/workflow-core'
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getEmbeddingContextActivity,
generateEmbeddingActivity,
saveAssetEmbeddingsActivity,
updateTaskUsageActivity,
createCommentActivity,
updateCommentActivity,
getAgentWorkerQueueActivity,
} = getActivities()
let placeholderCommentId: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__EMBEDDING__',
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
placeholderCommentId = placeholder.id
if (!task.teamId) {
throw ApplicationFailure.create({ message: 'Task has no teamId', nonRetryable: true })
}
// 1. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, {
teamId: task.teamId,
assetId: task.assetId,
})
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
// Call the activity to generate embeddings
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
teamId: task.teamId,
assetId: task.assetId,
context,
})
// Save computed embeddings
if (result.embeddings.length > 0) {
await executeActivity(TaskQueueDb, saveAssetEmbeddingsActivity, {
assetId: task.assetId,
embeddings: result.embeddings,
})
}
// Update Usage
if (result.usage) {
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: result.usage.inputTokens,
outputTokens: result.usage.outputTokens,
model: result.usage.model,
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Embedding completed successfully.',
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const agentEmbeddingWorkflow = agentEmbeddingMedia
@@ -0,0 +1,52 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb } from '@shumai/workflow-core'
export async function agentToolCall(task: WorkflowTask): Promise<void> {
const { updateTaskStatusActivity, executeAgentToolActivity } = getActivities()
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
const payload = task.payload
if (!payload || !payload.agentToolCall) {
throw ApplicationFailure.create({
message: 'Task payload or agentToolCall is missing',
nonRetryable: true,
})
}
const { toolName, args, userId } = payload.agentToolCall
// Execute the database activity on db_queue
const result = await executeActivity(TaskQueueDb, executeAgentToolActivity, {
taskId: task.id,
toolName,
args,
userId,
})
// Update status to completed with output
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
output: result,
})
} catch (err) {
console.error(`AgentToolCall failed for task ${task.id}:`, err)
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const agentToolCallWorkflow = agentToolCall
@@ -0,0 +1,48 @@
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb } from '@shumai/workflow-core'
export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void> {
const { generateTextEmbeddingActivity, updateWorkflowTaskActivity } = getActivities()
const payload = task.payload as PrismaJson.WorkflowTaskPayload | null
const text = payload?.queryEmbeddingForSearch?.text
if (!text) {
throw new Error('Missing text in query_embedding_for_search task payload')
}
try {
// 1. Mark as processing
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
taskId: task.id,
status: 'processing',
heartbeat: true,
})
// 2. Generate embedding
const result = await generateTextEmbeddingActivity({
text,
teamId: task.teamId!,
})
// 3. Save output and complete
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
taskId: task.id,
status: 'completed',
output: { embedding: result.embedding },
inputTokens: result.usage.inputTokens,
outputTokens: result.usage.outputTokens,
model: result.usage.model,
})
} catch (err) {
console.error(`queryEmbeddingForSearch failed for task ${task.id}:`, err)
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
taskId: task.id,
status: 'failed',
output: {
error: err instanceof Error ? err.message : String(err),
},
})
throw err
}
}