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
-390
View File
@@ -1,390 +0,0 @@
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')
})
})
-270
View File
@@ -1,270 +0,0 @@
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
@@ -1,33 +0,0 @@
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>')
})
})
-287
View File
@@ -1,287 +0,0 @@
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')
}
-61
View File
@@ -1,61 +0,0 @@
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')
})
})
@@ -1,70 +0,0 @@
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')
})
})
-74
View File
@@ -1,74 +0,0 @@
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
@@ -1,99 +0,0 @@
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
@@ -1,46 +0,0 @@
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
@@ -1,100 +0,0 @@
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
@@ -1,61 +0,0 @@
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
@@ -1,264 +0,0 @@
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
@@ -1,55 +0,0 @@
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 },
}
}
},
})
-181
View File
@@ -1,181 +0,0 @@
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
@@ -1,129 +0,0 @@
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
@@ -1,35 +0,0 @@
import { prisma } from '@shumai/db'
import { workflowService } from '@/workflow/workflow'
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
}
+9 -1
View File
@@ -24,7 +24,10 @@ import uploadRoute from '@/api/upload'
import versionStackRoute from '@/api/versionStack'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { assetService } from '@shumai/core/src/asset/asset'
import { workflowService } from '@/workflow/workflow'
import { workflowService } from '@shumai/workflow-core'
import { initAgentWorkflows } from '@shumai/agent'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { initDbWorkflows } from '@shumai/worker-db'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -62,6 +65,11 @@ const apiAppRoute = app.route('/api', apiRoute)
export type AppType = typeof apiAppRoute
export async function run() {
// Initialize workflows and activities for local executor mode
initAgentWorkflows()
initTranscodeWorkflows()
initDbWorkflows()
// Start services
await metadataService.syncSystemFields().catch(console.error)
assetService.startCleanupJob()
+10 -2
View File
@@ -1,7 +1,15 @@
import { workflowService } from '@/workflow/workflow'
import { TaskQueueAgent, TaskQueueTranscode } from '@/workflow/workflow-utils'
import { workflowService } from '@shumai/workflow-core'
import { TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
import { initAgentWorkflows } from '@shumai/agent'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { initDbWorkflows } from '@shumai/worker-db'
export async function run() {
// Initialize workflows and activities
initAgentWorkflows()
initTranscodeWorkflows()
initDbWorkflows()
const domain = process.argv[3]
if (!domain) {
-135
View File
@@ -1,135 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { getMediaInfoActivity, transcodeVideoActivity, updateAssetMediaActivity } from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@/transcode/transcode'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
presign: vi.fn(),
},
}))
vi.mock('@/transcode/transcode', () => ({
transcodeService: {
getVideoInfo: vi.fn(),
getImageInfo: vi.fn(),
transcodeVideo: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
},
}))
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>()
return {
...actual,
readFileSync: vi.fn().mockReturnValue(Buffer.from('fake data')),
}
})
describe('Transcode Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should call getVideoInfo for video assets', async () => {
const asset = await prisma.asset.create({
data: { name: 'v.mp4', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
bitRate: 1000,
frameRate: 30,
hasAudio: true,
videoCodec: 'Advanced Video Coding',
audioCodec: 'MPEG-4 Audio',
audioChannels: 2,
audioSampleRate: 48000,
audioBitDepth: 16,
mimeType: 'video/mp4',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/v.mp4',
mediaType: 'video/mp4',
})
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/v.mp4')
expect(result.duration).toBe(10)
expect(result.metadata?.originalWidth).toBe(1920)
expect(result.metadata?.videoCodec).toBe('Advanced Video Coding')
expect(result.metadata?.audioCodec).toBe('MPEG-4 Audio')
expect(result.metadata?.audioChannels).toBe(2)
expect(result.metadata?.audioSampleRate).toBe(48000)
expect(result.metadata?.audioBitDepth).toBe(16)
})
it('should call getImageInfo for image assets', async () => {
const asset = await prisma.asset.create({
data: { name: 'i.png', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getImageInfo).mockResolvedValue({
originalWidth: 800,
originalHeight: 600,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
mimeType: 'image/png',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/i.png',
mediaType: 'image/png',
})
expect(transcodeService.getImageInfo).toHaveBeenCalledWith('/tmp/i.png')
expect(result.metadata?.originalWidth).toBe(800)
expect(result.metadata?.duration).toBe(0)
})
it('should update asset media field', async () => {
const asset = await prisma.asset.create({
data: {
name: 'v.mp4',
storageKey: { create: { key: 'v.mp4' } },
status: 'uploaded',
type: 'file',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mediaInfo: any = { duration: 123 }
await updateAssetMediaActivity({ assetId: asset.id, mediaInfo })
const updated = await prisma.asset.findUnique({ where: { id: asset.id } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((updated?.media as any).duration).toBe(123)
expect(s3Service.putObject).toHaveBeenCalled()
})
it('should call transcodeService.transcodeVideo', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
await transcodeVideoActivity({
assetKey: 'v.mp4',
filePath: '/tmp/v.mp4',
videoSpec: { resolution: '720p', width: 1280, height: 720 },
duration: 10,
originalFps: 30,
})
expect(transcodeService.transcodeVideo).toHaveBeenCalled()
})
})
-299
View File
@@ -1,299 +0,0 @@
import { prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { ApplicationFailure } from '@temporalio/activity'
import * as path from 'path'
import * as fs from 'fs'
export interface GetMediaInfoActivityParams {
assetId: string
assetKey: string
mediaType: string
}
export async function getMediaInfoActivity(params: {
filePath: string
assetId: string
mediaType: string
}): Promise<PrismaJson.MediaInfo> {
const isVideo = params.mediaType.startsWith('video/')
const isImage = params.mediaType.startsWith('image/')
const mediaInfo: PrismaJson.MediaInfo = {
duration: 0,
filesize: 0,
fps: 0,
frames: 0,
imageTranscodes: [],
videoTranscodes: [],
videoPreview: { width: 0, height: 0 },
finishedAt: new Date().toISOString(),
metadata: null,
mimeType: params.mediaType,
original: {
key: '', // Will be filled by caller or updated later
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
}
if (isVideo) {
const info = await transcodeService.getVideoInfo(params.filePath)
mediaInfo.duration = info.duration
mediaInfo.fps = info.frameRate
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: info.duration,
bitRate: info.bitRate,
frameRate: info.frameRate,
hasAudio: info.hasAudio,
videoCodec: info.videoCodec,
audioCodec: info.audioCodec,
audioChannels: info.audioChannels,
audioSampleRate: info.audioSampleRate,
audioBitDepth: info.audioBitDepth,
format: {},
}
const metadataUpdates: { key: string; value: string | number }[] = [
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'duration', value: info.duration },
{ key: 'bitRate', value: info.bitRate / 1000 },
{ key: 'frame_rate', value: info.frameRate },
]
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
if (info.audioCodec) metadataUpdates.push({ key: 'audio_codec', value: info.audioCodec })
if (info.audioChannels !== undefined)
metadataUpdates.push({ key: 'audio_channels', value: info.audioChannels })
if (info.audioSampleRate !== undefined)
metadataUpdates.push({ key: 'audio_sample_rate', value: info.audioSampleRate })
if (info.audioBitDepth !== undefined)
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
} else if (isImage) {
const info = await transcodeService.getImageInfo(params.filePath)
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
format: {},
}
await metadataService.updateAssetMetadata(
params.assetId,
[
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
],
true,
)
}
return mediaInfo
}
export interface VideoActivityParams {
assetKey: string
filePath: string
videoSpec: PrismaJson.VideoTranscode
duration: number
originalFps: number
}
export async function transcodeVideoActivity(
params: VideoActivityParams,
): Promise<PrismaJson.VideoTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
const key = path.join(path.dirname(params.assetKey), `video-${params.videoSpec.height}p.mp4`)
try {
await s3Service.headObject(bucket, key)
return { ...params.videoSpec, key }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
try {
let targetFps = 0
let disableAudio = false
if (params.videoSpec.resolution === '180p') {
disableAudio = true
targetFps = 24.0
if (params.originalFps > 0 && params.originalFps < 24.0) {
targetFps = params.originalFps
}
if (params.duration * targetFps > 1600) {
targetFps = 1600 / params.duration
}
}
await transcodeService.transcodeVideo({
inputFile: params.filePath,
outputFile,
width: params.videoSpec.width,
height: params.videoSpec.height,
frameRate: targetFps || undefined,
disableAudio,
})
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'video/mp4')
return { ...params.videoSpec, key }
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
}
export interface ImageActivityParams {
assetKey: string
filePath: string
imageSpec: PrismaJson.ImageTranscode
}
export async function transcodeImageActivity(
params: ImageActivityParams,
): Promise<PrismaJson.ImageTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
const key = path.join(path.dirname(params.assetKey), `image-${params.imageSpec.width}p.webp`)
try {
await s3Service.headObject(bucket, key)
return { ...params.imageSpec, key }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const outputFile = path.join(tmpDir, `image-${params.imageSpec.width}p.webp`)
try {
await transcodeService.transcodeImage(
params.filePath,
outputFile,
params.imageSpec.width,
params.imageSpec.quality,
)
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
return { ...params.imageSpec, key }
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
}
export interface GenerateSpriteActivityParams {
assetKey: string
filePath: string
mediaInfo: PrismaJson.MediaInfo
spriteSpec: PrismaJson.SpriteInfo
posterSpec: PrismaJson.PosterInfo
}
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.headObject(bucket, params.spriteSpec.key)
await s3Service.headObject(bucket, params.posterSpec.key)
return { sprite: params.spriteSpec, poster: params.posterSpec }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const spriteFile = path.join(tmpDir, 'sprite.webp')
const posterFile = path.join(tmpDir, 'poster.webp')
try {
await transcodeService.generateSprite(
params.filePath,
spriteFile,
posterFile,
params.mediaInfo.duration,
)
const spriteBuffer = fs.readFileSync(spriteFile)
await s3Service.putObject(
bucket,
params.spriteSpec.key,
spriteBuffer,
spriteBuffer.length,
'image/webp',
)
const posterBuffer = fs.readFileSync(posterFile)
await s3Service.putObject(
bucket,
params.posterSpec.key,
posterBuffer,
posterBuffer.length,
'image/webp',
)
return { sprite: params.spriteSpec, poster: params.posterSpec }
} finally {
if (fs.existsSync(spriteFile)) fs.unlinkSync(spriteFile)
if (fs.existsSync(posterFile)) fs.unlinkSync(posterFile)
}
}
export async function downloadMediaToTmpActivity(params: {
assetKey: string
}): Promise<{ filePath: string; tmpDir: string }> {
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = transcodeService.createTempDir('transcode-')
const filePath = path.join(tmpDir, path.basename(params.assetKey))
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir, { recursive: true })
}
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
return { filePath, tmpDir }
}
export async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
transcodeService.removeDir(params.tmpDir)
}
export interface UpdateAssetMediaActivityParams {
assetId: string
mediaInfo: PrismaJson.MediaInfo
}
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { storageKey: true },
})
const key = asset?.storageKey?.key
if (!asset || !key) {
throw ApplicationFailure.create({
message: 'Asset not found or has no key',
nonRetryable: true,
})
}
const infoKey = path.join(path.dirname(key), 'info.json')
const buffer = Buffer.from(JSON.stringify(params.mediaInfo))
await s3Service.putObject(bucket, infoKey, buffer, buffer.length, 'application/json')
await prisma.asset.update({
where: { id: params.assetId },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: { media: params.mediaInfo as any },
})
}
-230
View File
@@ -1,230 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { transcodeService } from './transcode'
import * as path from 'path'
import * as child_process from 'child_process'
import { WorkflowTask } from '@shumai/db'
import sharp from 'sharp'
// Mock child_process
vi.mock('child_process', () => ({
exec: vi.fn(),
}))
// Mock sharp
vi.mock('sharp', () => {
const mockSharp = {
resize: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
toFile: vi.fn().mockResolvedValue({}),
metadata: vi.fn().mockResolvedValue({ width: 800, height: 600, format: 'png' }),
}
const sharpFunc = vi.fn(() => mockSharp)
return {
default: sharpFunc,
}
})
describe('TranscodeService', () => {
let tempDir: string
beforeEach(() => {
tempDir = transcodeService.createTempDir('transcode-test-')
vi.clearAllMocks()
})
afterEach(() => {
transcodeService.removeDir(tempDir)
})
it('should parse video info correctly from ffprobe output', async () => {
/* eslint-disable @typescript-eslint/naming-convention */
const mockOutput = JSON.stringify({
format: { duration: '10.5', bit_rate: '128000' },
streams: [
{
codec_type: 'video',
codec_name: 'h264',
width: 1920,
height: 1080,
r_frame_rate: '30/1',
tags: {
mime_codec_string: 'avc1.4d401e',
},
},
{
codec_type: 'audio',
codec_name: 'aac',
channels: 2,
sample_rate: '48000',
bits_per_raw_sample: '16',
tags: {
mime_codec_string: 'mp4a.40.2',
},
},
],
})
/* eslint-enable @typescript-eslint/naming-convention */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: mockOutput, stderr: '' })
})
const info = await transcodeService.getVideoInfo('test.mp4')
expect(info.originalWidth).toBe(1920)
expect(info.originalHeight).toBe(1080)
expect(info.duration).toBe(10.5)
expect(info.frameRate).toBe(30)
expect(info.hasAudio).toBe(true)
expect(info.videoCodec).toBe('Advanced Video Coding')
expect(info.audioCodec).toBe('MPEG-4 Audio')
expect(info.audioChannels).toBe(2)
expect(info.audioSampleRate).toBe(48000)
expect(info.audioBitDepth).toBe(16)
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('ffprobe'),
expect.any(Function),
)
})
it('should get image info using sharp', async () => {
const mockMetadata = {
width: 800,
height: 600,
format: 'png',
}
const mockSharp = vi.mocked(sharp())
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockSharp.metadata.mockResolvedValue(mockMetadata as any)
const info = await transcodeService.getImageInfo('test.png')
expect(info.originalWidth).toBe(800)
expect(info.originalHeight).toBe(600)
expect(info.mimeType).toBe('png')
expect(info.duration).toBe(0)
expect(sharp).toHaveBeenCalledWith('test.png')
})
it('should construct correct ffmpeg arguments for video transcoding', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
const outputFile = path.join(tempDir, 'output.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
frameRate: 24,
disableAudio: true,
})
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('scale=w=1280:h=720'),
expect.any(Function),
)
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('fps=24'),
expect.any(Function),
)
// Should NOT have audio maps if disabled
expect(child_process.exec).not.toHaveBeenCalledWith(
expect.stringContaining('-map 0:a?'),
expect.any(Function),
)
})
it('should use sharp for image transcoding', async () => {
const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
expect(sharp).toHaveBeenCalledWith('input.png')
const mockSharp = vi.mocked(sharp).mock.results[0].value
expect(mockSharp.resize).toHaveBeenCalledWith(480, null, expect.any(Object))
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
})
it('should fetch image if input is a URL', async () => {
const mockBuffer = Buffer.from('fake-image-data')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(global as any).fetch = vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(mockBuffer),
})
const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('http://example.com/image.png', outputFile, 480, 80)
expect(global.fetch).toHaveBeenCalledWith('http://example.com/image.png')
expect(sharp).toHaveBeenCalledWith(expect.any(Buffer))
})
it('should use transcodeImage in extractVideoFrames for images', async () => {
const transcodeImageSpy = vi.spyOn(transcodeService, 'transcodeImage').mockResolvedValue()
const result = await transcodeService.extractVideoFrames({
inputFile: 'input.png',
outputDir: tempDir,
numFrames: 1,
frameHeight: 720,
isImage: true,
})
expect(transcodeImageSpy).toHaveBeenCalledWith(
'input.png',
expect.stringContaining('1.webp'),
-1,
80,
720,
)
expect(result).toHaveLength(1)
expect(result[0]).toContain('1.webp')
})
it('should use ffmpeg with libwebp in extractVideoFrames for videos', async () => {
vi.spyOn(transcodeService, 'getVideoInfo').mockResolvedValue({
duration: 10,
originalWidth: 1920,
originalHeight: 1080,
bitRate: 1000,
frameRate: 30,
hasAudio: true,
mimeType: 'video/mp4',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
await transcodeService.extractVideoFrames({
inputFile: 'input.mp4',
outputDir: tempDir,
numFrames: 10,
frameHeight: 720,
isImage: false,
})
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('-c:v libwebp'),
expect.any(Function),
)
})
it('should create transcode tasks correctly', async () => {
const task = (await transcodeService.createVideoTranscodeTask('asset-123', 'proj-123', {
videoStrategy: 'best_match',
thumbnail: true,
})) as WorkflowTask
expect(task.assetId).toBe('asset-123')
expect(task.type).toBe('transcode')
expect(task.status).toBe('pending')
expect(task.payload?.projectId).toBe('proj-123')
expect(task.payload?.transcode?.videoStrategy).toBe('best_match')
})
})
-434
View File
@@ -1,434 +0,0 @@
import { prisma } from '@shumai/db'
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { exec } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { promisify } from 'util'
const execAsync = promisify(exec)
const dataFormatNames: Record<string, string> = {
// additional codecs
apch: 'Apple ProRes 422 High Quality',
apcn: 'Apple ProRes 422 Standard Definition',
apcs: 'Apple ProRes 422 LT',
apco: 'Apple ProRes 422 Proxy',
ap4h: 'Apple ProRes 4444',
jpeg: 'JPEG Image',
// codecs from https://mp4ra.org/
'3gvo': '3GPP Video Orientation',
a3d1: 'Multiview Video Coding',
a3d2: 'Multiview Video Coding',
a3d3: 'Multiview Video Coding',
a3d4: 'Multiview Video Coding',
a3ds: 'Auro-Cx 3D audio',
'ac-3': 'AC-3 audio',
'ac-4': 'AC-4 audio',
alac: 'Apple lossless audio codec',
alaw: 'a-Law',
av01: 'AV1 video',
avc1: 'Advanced Video Coding',
avc2: 'Advanced Video Coding',
avc3: 'Advanced Video Coding',
avc4: 'Advanced Video Coding',
avcp: 'Advanced Video Coding Parameters',
dra1: 'DRA Audio',
drac: 'Dirac Video Coder',
'dts-': 'Dependent base layer for DTS layered audio',
'dts+': 'Enhancement layer for DTS layered audio',
dtsc: 'DTS Coherent Acoustics audio',
dtse: 'DTS Express low bit rate audio, also known as DTS LBR',
dtsh: 'DTS-HD High Resolution Audio',
dtsl: 'DTS-HD Master Audio',
dtsx: 'DTS:X',
dvav: 'AVC-based “Dolby Vision”',
dvhe: 'HEVC-based “Dolby Vision”',
'ec-3': 'Enhanced AC-3 audio',
enca: 'Encrypted/Protected audio',
encf: 'Encrypted/Protected font',
encm: 'Encrypted/Protected metadata stream',
encs: 'Encrypted Systems stream',
enct: 'Encrypted Text',
encv: 'Encrypted/protected video',
fdp: 'File delivery hints',
fLaC: 'Fres Lossless Audio Codec',
g719: 'ITU-T Recommendation G.719 (2008)',
g726: 'ITU-T Recommendation G.726 (1990)',
hev1: 'High Efficiency Video Coding',
hvc1: 'High Efficiency Video Coding',
hvt1: 'High Efficiency Video Coding',
ixse: 'DVB Track Level Index Track',
lhe1: 'Layered High Efficiency Video Coding',
lht1: 'Layered High Efficiency Video Coding',
lhv1: 'Layered High Efficiency Video Coding',
m2ts: 'MPEG-2 transport stream for DMB',
m4ae: 'MPEG-4 Audio Enhancement MP4v1/2',
mett: 'Text timed metadata that is not XML',
metx: 'XML timed metadata',
mha1: 'MPEG-H Audio (single stream, uncapsulated)',
mha2: 'MPEG-H Audio (multi-stream, unencapsulated)',
mhm1: 'MPEG-H Audio (single stream, MHAS encapsulated)',
mhm2: 'MPEG-H Audio (multi-stream, MHAS encapsulated)',
mjp2: 'Motion JPEG 2000',
mlix: 'DVB Movie level index track',
mlpa: 'MLP Audio',
mp4a: 'MPEG-4 Audio',
mp4s: 'MPEG-4 Systems',
mp4v: 'MPEG-4 Visual',
mvc1: 'Multiview coding',
mvc2: 'Multiview coding',
mvc3: 'Multiview coding',
mvc4: 'Multiview coding',
mvd1: 'Multiview coding',
mvd2: 'Multiview coding',
mvd3: 'Multiview coding',
mvd4: 'Multiview coding',
oksd: 'OMA Keys',
// eslint-disable-next-line @typescript-eslint/naming-convention
Opus: 'Opus audio coding',
pm2t: 'Protected MPEG-2 Transport',
prtp: 'Protected RTP Reception',
raw: 'Uncompressed audio',
resv: 'Restricted Video',
rm2t: 'MPEG-2 Transport Reception',
rrtp: 'RTP reception',
rsrp: 'SRTP Reception',
rtmd: 'Real Time Metadata Sample Entry(XAVC Format)',
rtp: 'RTP Hints',
s263: 'ITU H.263 video (3GPP format)',
samr: 'Narrowband AMR voice',
sawb: 'Wideband AMR voice',
sawp: 'Extended AMR-WB (AMR-WB+)',
sevc: 'EVRC Voice',
sm2t: 'MPEG-2 Transport Server',
sqcp: '13K Voice',
srtp: 'SRTP Hints',
ssmv: 'SMV Voice',
STGS: 'Subtitle Sample Entry (HMMP)',
stpp: 'Subtitles (Timed Text)',
svc1: 'Scalable Video Coding',
svc2: 'Scalable Video Coding',
svcM: 'SVC Metadata',
tc64: '64 bit timecode samples',
tmcd: '32 bit timecode samples',
twos: 'Uncompressed 16-bit audio',
tx3g: 'Timed Text stream',
ulaw: 'Samples have been compressed using uLaw 2:1.',
unid: 'Dynamic Range Control (DRC) data',
urim: 'Binary timed metadata identified by URI',
'vc-1': 'SMPTE VC-1',
vp08: 'VP8 video',
vp09: 'VP9 video',
wvtt: 'WebVTT',
}
export interface MediaMetadata {
originalWidth: number
originalHeight: number
duration: number
bitRate: number
frameRate: number
hasAudio: boolean
videoCodec?: string
audioCodec?: string
audioChannels?: number
audioSampleRate?: number
audioBitDepth?: number
mimeType: string
}
export interface TranscodeVideoParams {
inputFile: string
outputFile: string
width: number
height: number
frameRate?: number
disableAudio?: boolean
}
export interface ExtractVideoFramesParams {
inputFile: string
outputDir: string
numFrames: number
frameHeight: number
isImage: boolean
}
export class TranscodeService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
private resolveCodecName(stream: {
/* eslint-disable @typescript-eslint/naming-convention */
codec_name?: string
mime_codec_string?: string
tags?: { mime_codec_string?: string }
/* eslint-enable @typescript-eslint/naming-convention */
}): string | undefined {
const mimeCodec = stream.mime_codec_string || stream.tags?.mime_codec_string
if (mimeCodec && typeof mimeCodec === 'string') {
const shortCodec = mimeCodec.split('.')[0]
if (dataFormatNames[shortCodec]) {
return dataFormatNames[shortCodec]
}
}
return stream.codec_name
}
private safeParseInt(value: string | number | undefined): number | undefined {
if (value === undefined || value === null) return undefined
const parsed = typeof value === 'string' ? parseInt(value, 10) : value
return Number.isFinite(parsed) ? (parsed as number) : undefined
}
async getVideoInfo(inputFile: string): Promise<MediaMetadata> {
const { stdout } = await execAsync(
`ffprobe -v quiet -print_format json -show_format -show_streams "${inputFile}"`,
)
const info = JSON.parse(stdout)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const videoStream = info.streams.find((s: any) => s.codec_type === 'video')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const audioStream = info.streams.find((s: any) => s.codec_type === 'audio')
if (!videoStream) {
throw new Error('No video stream found')
}
const frameRateParts = videoStream.r_frame_rate.split('/')
const frameRate = parseFloat(frameRateParts[0]) / parseFloat(frameRateParts[1])
return {
originalWidth: videoStream.width,
originalHeight: videoStream.height,
duration: parseFloat(info.format.duration),
bitRate: parseFloat(info.format.bit_rate),
frameRate,
hasAudio: !!audioStream,
videoCodec: this.resolveCodecName(videoStream),
audioCodec: audioStream ? this.resolveCodecName(audioStream) : undefined,
audioChannels: audioStream?.channels,
audioSampleRate: this.safeParseInt(audioStream?.sample_rate),
audioBitDepth:
this.safeParseInt(audioStream?.bits_per_raw_sample) ??
this.safeParseInt(audioStream?.bits_per_sample),
mimeType: '',
}
}
async getImageInfo(inputFile: string): Promise<MediaMetadata> {
let input: string | Buffer = inputFile
if (inputFile.startsWith('http')) {
const resp = await fetch(inputFile)
if (!resp.ok) {
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
}
input = Buffer.from(await resp.arrayBuffer())
}
const metadata = await sharp(input).metadata()
return {
originalWidth: metadata.width || 0,
originalHeight: metadata.height || 0,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
mimeType: metadata.format || '',
}
}
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
let filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
if (params.frameRate) {
filterComplex += `,fps=${params.frameRate}`
}
filterComplex += '[vout]'
const args = [
'-i',
`"${params.inputFile}"`,
'-filter_complex',
`"${filterComplex}"`,
'-map',
'[vout]',
]
if (!params.disableAudio) {
args.push('-map', '0:a?')
}
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '23')
if (!params.disableAudio) {
args.push('-c:a', 'aac', '-b:a', '128k')
}
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', `"${params.outputFile}"`)
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async transcodeImage(
inputFile: string,
outputFile: string,
width: number,
quality: number,
height: number | null = null,
): Promise<void> {
let input: string | Buffer = inputFile
if (inputFile.startsWith('http')) {
const resp = await fetch(inputFile)
if (!resp.ok) {
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
}
input = Buffer.from(await resp.arrayBuffer())
}
const sharpInstance = sharp(input)
const w = width > 0 ? width : null
const h = height && height > 0 ? height : null
if (w || h) {
sharpInstance.resize(w, h, {
withoutEnlargement: true,
fit: 'inside',
})
}
await sharpInstance.webp({ quality }).toFile(outputFile)
}
async generateSprite(
inputFile: string,
outputSprite: string,
outputPoster: string,
duration: number,
): Promise<void> {
const spriteFps = 100 / duration
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:720:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
const args = [
'-i',
`"${inputFile}"`,
'-filter_complex',
`"${filterComplex}"`,
'-map',
'[sprite_out]',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'75',
`"${outputSprite}"`,
'-map',
'[thumb_out]',
'-c:v',
'libwebp',
'-q:v',
'75',
'-frames:v',
'1',
'-max_muxing_queue_size',
'1024',
`"${outputPoster}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
const args = [
'-i',
`"${inputFile}"`,
'-vn',
'-acodec',
'libmp3lame',
'-b:a',
bitrate,
`"${outputFile}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
if (params.isImage) {
const outputFile = path.join(params.outputDir, '1.webp')
await this.transcodeImage(params.inputFile, outputFile, -1, 80, params.frameHeight)
return [outputFile]
}
const meta = await this.getVideoInfo(params.inputFile)
const fps = params.numFrames / meta.duration
const outputPattern = path.join(params.outputDir, '%d.webp')
const args = [
'-i',
`"${params.inputFile}"`,
'-vf',
`fps=${fps},scale=-2:${params.frameHeight}`,
'-c:v',
'libwebp',
'-q:v',
'80',
`"${outputPattern}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
const files = fs.readdirSync(params.outputDir)
return files
.filter((f) => f.endsWith('.webp'))
.sort((a, b) => {
const na = parseInt(path.basename(a, '.webp'))
const nb = parseInt(path.basename(b, '.webp'))
return na - nb
})
.map((f) => path.join(params.outputDir, f))
}
createTempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix))
}
removeDir(dir: string): void {
fs.rmSync(dir, { recursive: true, force: true })
}
// --- Task Creation Helpers ---
async createVideoTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId,
transcode: spec,
},
},
})
}
async createImageTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId,
transcode: spec,
},
},
})
}
}
export const transcodeService = new TranscodeService()
-84
View File
@@ -1,84 +0,0 @@
import { prisma } from '@shumai/db'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
type TransactionClient = Omit<
typeof prisma,
'$connect' | '$disconnect' | '$on' | '$transaction' | '$use' | '$extends'
>
export class VideoTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
setStrategy(strategy: PrismaJson.VideoTranscodeStrategy): this {
this.spec.videoStrategy = strategy
return this
}
withSprite(): this {
this.spec.sprite = true
return this
}
withPoster(): this {
this.spec.poster = true
return this
}
async submit(): Promise<string> {
const task = await this.db.workflowTask.create({
data: {
assetId: this.assetId,
teamId: this.teamId,
projectId: this.projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
export class ImageTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
withThumbnail(): this {
this.spec.thumbnail = true
return this
}
async submit(): Promise<string> {
const task = await this.db.workflowTask.create({
data: {
assetId: this.assetId,
teamId: this.teamId,
projectId: this.projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
-242
View File
@@ -1,242 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeMedia } from './transcode'
import {
WorkflowTask,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
} from '@shumai/db'
import * as workflowUtils from '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
describe('Transcode Workflow', () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
updateAssetStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
transcodeVideoActivity: Object.assign(vi.fn(), { _activityName: 'transcodeVideoActivity' }),
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
updateAssetMediaActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetMediaActivity',
}),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
}
beforeEach(() => {
vi.clearAllMocks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.executeActivity as any).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(_queue: string, fn: any, ...args: any[]) => {
if (typeof fn !== 'function') {
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
}
return fn(...args)
},
)
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/video.mp4',
tmpDir: '/tmp',
})
})
it('should process video transcode successfully', async () => {
const task: WorkflowTask = {
id: 'task-1',
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
videoStrategy: 'best_match',
thumbnail: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
storageKey: { key: 'video.mp4' },
mediaType: 'video/mp4',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
mimeType: 'video/mp4',
metadata: { originalWidth: 1920, originalHeight: 1080, duration: 10, frameRate: 30 },
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.transcodeVideoActivity.mockResolvedValue({
key: 'v.mp4',
width: 1920,
height: 1080,
})
mockActivities.transcodeImageActivity.mockResolvedValue({
key: 't.webp',
width: 480,
height: 270,
})
await transcodeMedia(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
status: AssetStatus.processing,
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
mediaInfo: expect.objectContaining({
thumbnail: expect.objectContaining({
key: 't.webp',
}),
}),
})
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
status: AssetStatus.processed,
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1',
status: WorkflowTaskStatus.completed,
})
})
it('should process image transcode and thumbnail successfully', async () => {
const task: WorkflowTask = {
id: 'task-image',
assetId: 'asset-image',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
thumbnail: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-image',
storageKey: { key: 'image.jpg' },
mediaType: 'image/jpeg',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
mimeType: 'image/jpeg',
metadata: { originalWidth: 1000, originalHeight: 1000 },
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.transcodeImageActivity.mockResolvedValue({
key: 't.webp',
width: 480,
height: 480,
format: 'webp',
})
await transcodeMedia(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
status: AssetStatus.processing,
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
mediaInfo: expect.objectContaining({
thumbnail: expect.objectContaining({
key: 't.webp',
width: 480,
height: 480,
}),
}),
})
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
status: AssetStatus.processed,
})
})
it('should handle failures and update task status with error', async () => {
const task: WorkflowTask = {
id: 'task-fail',
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockRejectedValue(new Error('FFmpeg failed'))
await expect(transcodeMedia(task)).rejects.toThrow('FFmpeg failed')
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-fail',
status: WorkflowTaskStatus.failed,
output: { error: 'FFmpeg failed' },
})
})
})
-313
View File
@@ -1,313 +0,0 @@
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure } from '@temporalio/workflow'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueTranscode,
} from '@/workflow/workflow-utils'
export async function transcodeMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
updateAssetStatusActivity,
getAssetActivity,
getMediaInfoActivity,
transcodeVideoActivity,
transcodeImageActivity,
generateSpriteActivity,
updateAssetMediaActivity,
getTranscodeWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
} = getActivities()
let tmpDir: string | undefined
let workerQueue: string | undefined
try {
// 1. Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
await executeActivity(TaskQueueDb, updateAssetStatusActivity, {
assetId: task.assetId,
status: 'processing',
})
// 2. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
const key = asset?.storageKey?.key
if (!asset || !key) {
throw ApplicationFailure.create({
message: 'Asset not found or has no key',
nonRetryable: true,
})
}
// 3. Get Worker-Specific Queue for Transcode
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
// 4. Download Media to Tmp
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const { filePath } = download
tmpDir = download.tmpDir
// 5. Get Media Info
const spec = task.payload?.transcode || {}
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
filePath,
assetId: asset.id,
mediaType: asset.mediaType || '',
})
mediaInfo.original = {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
}
const mimeType = mediaInfo.mimeType
const metadata = mediaInfo.metadata
// 6. Video Transcoding
if (mimeType.startsWith('video/') && metadata) {
const videoResolutions = getTargetVideoResolutions(
spec.videoStrategy || 'best_match',
metadata.originalWidth,
metadata.originalHeight,
)
for (const res of videoResolutions) {
const [width, height] = resolutionToDimensions(
res,
metadata.originalWidth,
metadata.originalHeight,
)
const videoSpec: PrismaJson.VideoTranscode = {
resolution: res,
width,
height,
}
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
assetKey: key,
filePath,
videoSpec,
duration: metadata.duration,
originalFps: metadata.frameRate,
})
if (res === '180p') {
mediaInfo.videoPreview = videoTranscode
} else {
mediaInfo.videoTranscodes.push(videoTranscode)
}
}
// Always keep raw
mediaInfo.videoTranscodes.push({
key: mediaInfo.original?.key,
width: metadata.originalWidth,
height: metadata.originalHeight,
isRaw: true,
})
}
// 7. Image Transcoding
const isImage = mimeType.startsWith('image/')
const isPsd = isMimePsd(mimeType)
if ((isImage || isPsd) && metadata) {
const imageSpec: PrismaJson.ImageTranscode = {
width: metadata.originalWidth,
height: metadata.originalHeight,
quality: 90,
format: 'webp',
}
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec,
})
mediaInfo.imageTranscodes.push(imageTranscode)
}
// 9. System: Thumbnail
if (spec.thumbnail) {
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec: { width: 480, height: 0, quality: 80, format: 'webp' },
})
mediaInfo.thumbnail = thumbTranscode
}
// 10. System: Sprite/Poster (Video only usually)
if (spec.sprite || spec.poster) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const spriteSpec: PrismaJson.SpriteInfo = {
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
frames: 100,
tileX: 10,
tileY: 10,
}
const posterSpec: PrismaJson.PosterInfo = {
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
}
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
assetKey: key,
filePath,
spriteSpec,
posterSpec,
mediaInfo,
})
mediaInfo.sprite = spriteResult.sprite
mediaInfo.poster = spriteResult.poster
}
// 11. Update Asset Media and Status
await executeActivity(TaskQueueDb, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await executeActivity(TaskQueueDb, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
})
// 12. Update Task Status
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`TranscodeMedia 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
} finally {
if (tmpDir && workerQueue) {
try {
await executeActivity(workerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
}
}
}
function isMimePsd(mimeType: string): boolean {
switch (mimeType) {
case 'image/vnd.adobe.photoshop':
case 'image/x-photoshop':
case 'application/x-photoshop':
case 'image/psd':
return true
}
return false
}
const RESOLUTION_LONG_SIDES: Record<string, number> = {
'2160p': 3840,
'1080p': 1920,
'720p': 1280,
'540p': 960,
'360p': 640,
'180p': 320,
}
function resolutionToDimensions(
resolution: string,
originalWidth: number,
originalHeight: number,
): [number, number] {
const targetLongSide = RESOLUTION_LONG_SIDES[resolution]
if (!targetLongSide) return [0, 0]
let width = 0
let height = 0
if (originalWidth >= originalHeight) {
// Landscape or square: width is the long side
width = targetLongSide
height = Math.round(width * (originalHeight / originalWidth))
} else {
// Portrait: height is the long side
height = targetLongSide
width = Math.round(height * (originalWidth / originalHeight))
}
// Ensure even dimensions for H.264
if (width % 2 !== 0) width++
if (height % 2 !== 0) height++
return [width, height]
}
const TARGET_RESOLUTIONS = [
{ name: '2160p', longSide: 3840 },
{ name: '1080p', longSide: 1920 },
{ name: '720p', longSide: 1280 },
{ name: '540p', longSide: 960 },
{ name: '360p', longSide: 640 },
]
function getBestMatchResolution(
originalWidth: number,
originalHeight: number,
): { name: string; longSide: number } {
const rawLongSide = Math.max(originalWidth, originalHeight)
const lower = TARGET_RESOLUTIONS.filter((r) => r.longSide <= rawLongSide)
if (lower.length > 0) {
lower.sort((a, b) => b.longSide - a.longSide)
return lower[0]
}
return TARGET_RESOLUTIONS[TARGET_RESOLUTIONS.length - 1] // 360p (longSide 640)
}
function getTargetVideoResolutions(
strategy: PrismaJson.VideoTranscodeStrategy,
originalWidth: number,
originalHeight: number,
): string[] {
const resolutions = ['180p']
// Normalize legacy strategies for backward compatibility
let normalizedStrategy: string = strategy
const stratStr = strategy as string
if (stratStr === 'single' || stratStr === 'disable') {
normalizedStrategy = 'best_match'
} else if (stratStr === 'full') {
normalizedStrategy = 'all'
}
const bestMatch = getBestMatchResolution(originalWidth, originalHeight)
if (normalizedStrategy === 'best_match') {
resolutions.push(bestMatch.name)
} else if (normalizedStrategy === 'all') {
const bestMatchIndex = TARGET_RESOLUTIONS.findIndex((r) => r.name === bestMatch.name)
if (bestMatchIndex !== -1) {
for (let i = bestMatchIndex; i < TARGET_RESOLUTIONS.length; i++) {
resolutions.push(TARGET_RESOLUTIONS[i].name)
}
}
}
return resolutions
}
export const transcodeWorkflow = transcodeMedia
-109
View File
@@ -1,109 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentChatActivity, autofillAiActivity, type AgentExecutionContext } from './agent'
import * as piAgent from '@/agent'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
import { type DatabaseSessionMetadata } from '@/agent/database-session-storage'
vi.mock('@/agent', async () => {
const actual = await vi.importActual('@/agent')
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
@@ -1,246 +0,0 @@
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
import { DatabaseSessionStorage } from '@/agent/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
@@ -1,61 +0,0 @@
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
@@ -1,261 +0,0 @@
import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@/transcode/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
}
-644
View File
@@ -1,644 +0,0 @@
import { describe, it, expect } from 'vitest'
import { setupTestDbHooks } from '@shumai/db'
import { prisma } from '@shumai/db'
import {
createCommentActivity,
updateCommentActivity,
deleteCommentActivity,
initializeAgentSessionActivity,
getAgentChatContextActivity,
getAgentAutofillContextActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
getAssetPathContextActivity,
executeAgentToolActivity,
} from './db'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { s3Service } from '@shumai/core/src/s3/s3'
describe('Database Activities', () => {
setupTestDbHooks()
it('should support comment CRUD activities (create, update, delete)', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user = await prisma.user.create({
data: { name: 'User One', email: 'user1@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
// 1. Create Comment
const comment = await createCommentActivity({
assetId: file.id,
message: 'Initial comment',
})
expect(comment.id).toBeDefined()
expect(comment.message).toBe('Initial comment')
// 2. Update Comment
const updated = await updateCommentActivity({
commentId: comment.id,
message: 'Updated comment',
})
expect(updated.message).toBe('Updated comment')
// 3. Delete Comment
await deleteCommentActivity(comment.id)
const found = await prisma.assetComment.findUnique({
where: { id: comment.id },
})
expect(found).toBeNull()
})
it('should support multiple comments in the same session without violating unique session_id constraint', async () => {
const team = await prisma.team.create({ data: { name: 't2' } })
const user = await prisma.user.create({
data: { name: 'User Two', email: 'user2@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p2', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file-2',
type: 'file',
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const sessionId = 'test-multi-comment-session'
// 1. Create first agent comment in the session
const c1 = await createCommentActivity({
assetId: file.id,
message: 'Agent comment 1',
sessionId,
agentId: 'default',
})
expect(c1.id).toBeDefined()
expect(c1.sessionId).toBe(sessionId)
// 2. Create second agent comment in the SAME session
const c2 = await createCommentActivity({
assetId: file.id,
message: 'Agent comment 2',
sessionId,
agentId: 'default',
})
expect(c2.id).toBeDefined()
expect(c2.sessionId).toBe(sessionId)
})
it('should initialize a new session with chronological context, prefixed usernames, and resolved user mentions', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user1 = await prisma.user.create({
data: { name: 'User One', email: 'user1@example.com' },
})
const user2 = await prisma.user.create({
data: { name: 'Matt', email: 'matt@example.com' },
})
const agentUser = await prisma.user.create({
data: { id: 'agent-user-id', name: 'Smart Agent', email: 'agent@example.com', type: 'agent' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user1.id,
status: 'uploaded',
},
})
// Create existing comment 1 (User mentioning user2)
const comment1 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: `First comment message for <@${user2.id}>`,
},
})
// Create existing comment 1.5 (Agent)
const commentAgent = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: agentUser.id,
message: 'I am helping',
},
})
// Create triggering comment 2 (Rule 1: no reply, mentions agent)
const comment2 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: 'Hello <@agent-user-id>',
},
})
const sessionId = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'agent-user-id',
userCommentId: comment2.id,
userId: user1.id,
})
expect(sessionId).toBeDefined()
// Verify session entries were populated with comment1 and commentAgent as context
const entries = await prisma.agentSessionEntry.findMany({
where: { sessionId },
orderBy: { id: 'asc' },
})
expect(entries.length).toBe(2)
// Verify User Comment Entry with resolved mention and username prefix
const entryData1 = entries[0].entry as unknown as SessionTreeEntry
expect(entryData1.id).toBeDefined()
expect(entryData1.id).not.toBe(comment1.id)
if (entryData1.type === 'message') {
const msg = entryData1.message as { role: 'user'; content: { type: 'text'; text: string }[] }
expect(msg.content[0].text).toBe('[User One]: First comment message for <@Matt>')
expect(msg.role).toBe('user')
} else {
throw new Error('Expected entry to be a message')
}
// Verify Agent Comment Entry
const entryData2 = entries[1].entry as unknown as SessionTreeEntry
expect(entryData2.id).toBeDefined()
expect(entryData2.id).not.toBe(commentAgent.id)
if (entryData2.type === 'message') {
const msg = entryData2.message as { role: 'user'; content: { type: 'text'; text: string }[] }
expect(msg.content[0].text).toBe('[Agent Message][Smart Agent]: I am helping')
expect(msg.role).toBe('user')
} else {
throw new Error('Expected entry to be a message')
}
})
it('should support context-fetching and embedding database activities', async () => {
const team = await prisma.team.create({ data: { name: 't_ctx' } })
const project = await prisma.project.create({
data: { name: 'p_ctx', teamId: team.id },
})
const sk = await prisma.storageKey.create({ data: { key: 'asset-key' } })
const asset = await prisma.asset.create({
data: {
name: 'test-asset',
type: 'file',
projectId: project.id,
status: 'uploaded',
mediaType: 'image/png',
storageKeyId: sk.id,
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires broad any casting since it is defined as generic Json in Prisma schema
config: { api: 'google', apiKey: 'key' } as any,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
reasoning: false,
input: ['text'],
contextWindow: 1000,
maxTokens: 1000,
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- model config requires broad any casting since it is defined as generic Json in Prisma schema
} as any,
},
})
const botUser = await prisma.user.create({
data: { name: 'Pirate Bot', email: 'bot@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
})
// Test getAgentChatContextActivity
const chatCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: agent.id })
expect(chatCtx.agent.id).toBe(agent.id)
expect(chatCtx.dbProviders.length).toBe(1)
expect(chatCtx.allowedDomains).toEqual([])
// Test getAgentAutofillContextActivity (needs an autofill agent)
const autofillBot = await prisma.user.create({
data: { name: 'Autofill Bot', email: 'autobot@example.com', type: 'agent' },
})
const autofillAgent = await prisma.agent.create({
data: {
id: autofillBot.id,
teamId: team.id,
type: 'autofill',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
const autofillCtx = await getAgentAutofillContextActivity({ teamId: team.id })
expect(autofillCtx.agent.id).toBe(autofillAgent.id)
// Test getEmbeddingContextActivity (needs an embedding agent)
const embeddingBot = await prisma.user.create({
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
})
const embeddingAgent = await prisma.agent.create({
data: {
id: embeddingBot.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: embeddingBot.id, role: 'reviewer' },
})
const embCtx = await getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id })
expect(embCtx.agent.id).toBe(embeddingAgent.id)
expect(embCtx.asset.id).toBe(asset.id)
// Test saveAssetEmbeddingsActivity
const mockEmbedding = Array(1536).fill(0.1)
await saveAssetEmbeddingsActivity({
assetId: asset.id,
embeddings: [{ embedding: mockEmbedding }],
})
const dbEmbeddings = await prisma.assetEmbedding.findMany({
where: { assetId: asset.id },
})
expect(dbEmbeddings.length).toBe(1)
})
describe('Agent System Tools and Path Context Activities', () => {
it('should correctly format getAssetPathContextActivity', async () => {
const team = await prisma.team.create({ data: { name: 'Path Team' } })
const project = await prisma.project.create({
data: { name: 'Path Project', teamId: team.id },
})
const folder1 = await prisma.asset.create({
data: {
name: 'foo',
type: 'folder',
projectId: project.id,
status: 'uploaded',
},
})
const folder2 = await prisma.asset.create({
data: {
name: 'bar',
type: 'folder',
projectId: project.id,
parentId: folder1.id,
status: 'uploaded',
},
})
const file = await prisma.asset.create({
data: {
name: 'z.png',
type: 'file',
projectId: project.id,
parentId: folder2.id,
status: 'uploaded',
},
})
const pathCtx = await getAssetPathContextActivity(file.id)
expect(pathCtx).toContain('Path: foo/bar/z.png')
expect(pathCtx).toContain(`name: foo, id: ${folder1.id}`)
expect(pathCtx).toContain(`name: bar, id: ${folder2.id}`)
expect(pathCtx).toContain(`name: z.png, id: ${file.id}`)
})
it('should correctly list assets, create folders, create files, and create versions', async () => {
const fs = await import('fs')
const path = await import('path')
const team = await prisma.team.create({ data: { name: 'Tool Team' } })
const user = await prisma.user.create({
data: { name: 'Tool User', email: 'tooluser@example.com' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Tool Project', teamId: team.id },
})
const parentFolder = await prisma.asset.create({
data: {
name: 'Parent Folder',
type: 'folder',
projectId: project.id,
status: 'uploaded',
fileCount: 0,
},
})
// 1. Test create_folder via executeAgentToolActivity
const folderResult = await executeAgentToolActivity({
taskId: 'task1',
toolName: 'create_folder',
args: {
parent: parentFolder.id,
name: 'Child Folder',
},
userId: user.id,
})
expect(folderResult.id).toBeDefined()
expect(folderResult.name).toBe('Child Folder')
expect(folderResult.type).toBe('folder')
const updatedParent = await prisma.asset.findUnique({
where: { id: parentFolder.id },
})
expect(updatedParent?.fileCount).toBe(1)
// 2. Test create_file via executeAgentToolActivity
const tempFilePath = path.join(process.cwd(), 'temp_test_file.txt')
fs.writeFileSync(tempFilePath, 'hello Shumai!')
try {
const s3Key = await s3Service.uploadFile(tempFilePath, 'text/plain')
const fileResult = await executeAgentToolActivity({
taskId: 'task2',
toolName: 'create_file',
args: {
parent: parentFolder.id,
s3Key,
name: 'temp_test_file.txt',
size: fs.statSync(tempFilePath).size,
contentType: 'text/plain',
},
userId: user.id,
})
expect(fileResult.id).toBeDefined()
expect(fileResult.name).toBe('temp_test_file.txt')
expect(fileResult.type).toBe('file')
const parentAfterFile = await prisma.asset.findUnique({
where: { id: parentFolder.id },
})
expect(parentAfterFile?.fileCount).toBe(2)
// 3. Test list_assets via executeAgentToolActivity
const listResult = await executeAgentToolActivity({
taskId: 'task3',
toolName: 'list_assets',
args: {
parent: parentFolder.id,
page: 1,
pageSize: 10,
type: 'all',
},
userId: user.id,
})
expect(listResult.assets).toBeDefined()
expect(listResult.assets.length).toBe(2) // folder and file
// 4. Test create_version via executeAgentToolActivity (regular file -> stack)
const versionTempPath = path.join(process.cwd(), 'temp_version_file.txt')
fs.writeFileSync(versionTempPath, 'hello Shumai V2!')
try {
const s3KeyV2 = await s3Service.uploadFile(versionTempPath, 'text/plain')
const versionResult = await executeAgentToolActivity({
taskId: 'task4',
toolName: 'create_version',
args: {
parent: fileResult.id,
s3Key: s3KeyV2,
name: 'temp_version_file.txt',
size: fs.statSync(versionTempPath).size,
contentType: 'text/plain',
},
userId: user.id,
})
expect(versionResult.id).toBeDefined()
expect(versionResult.type).toBe('file')
// Check if parent (the original file) was stacked
const originalFile = await prisma.asset.findUnique({
where: { id: fileResult.id },
include: { parent: true },
})
expect(originalFile?.parentId).toBeDefined()
expect(originalFile?.parent?.type).toBe('version_stack')
} finally {
if (fs.existsSync(versionTempPath)) {
fs.unlinkSync(versionTempPath)
}
}
} finally {
if (fs.existsSync(tempFilePath)) {
fs.unlinkSync(tempFilePath)
}
}
})
it('should trigger post-upload workflows (transcode, AI) when creating file or version via agent tool', async () => {
const team = await prisma.team.create({ data: { name: 'Workflow Team' } })
const user = await prisma.user.create({
data: { name: 'Workflow User', email: 'wfuser@example.com' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Workflow Project', teamId: team.id },
})
const parentFolder = await prisma.asset.create({
data: {
name: 'Parent Folder',
type: 'folder',
projectId: project.id,
status: 'uploaded',
},
})
// Setup agents
const bot1 = await prisma.user.create({
data: { name: 'Autofill Bot', email: 'autobot@example.com', type: 'agent' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: bot1.id, role: 'editor' },
})
await prisma.agent.create({
data: {
user: { connect: { id: bot1.id } },
type: 'autofill',
enabled: true,
team: { connect: { id: team.id } },
config: { provider: 'google', model: 'gemini' },
},
})
const bot2 = await prisma.user.create({
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: bot2.id, role: 'editor' },
})
await prisma.agent.create({
data: {
user: { connect: { id: bot2.id } },
type: 'embedding',
enabled: true,
team: { connect: { id: team.id } },
config: { provider: 'google', model: 'gemini' },
},
})
// Execute create_file with a video file type
const fileResult = await executeAgentToolActivity({
taskId: 'wf-task-1',
toolName: 'create_file',
args: {
parent: parentFolder.id,
s3Key: 'video/some-key.mp4',
name: 'test-video.mp4',
size: 1024 * 1024,
contentType: 'video/mp4',
},
userId: user.id,
})
expect(fileResult.id).toBeDefined()
// Fetch WorkflowTasks created for the asset
const tasks = await prisma.workflowTask.findMany({
where: { assetId: fileResult.id },
})
// Assert post-upload workflows are triggered
expect(tasks.length).toBe(3)
const types = tasks.map((t) => t.type)
expect(types).toContain('transcode')
expect(types).toContain('ai_metadata_autofill')
expect(types).toContain('ai_embedding')
})
it('should assign a lower sortIndex to newer versions so they are correctly marked as latest', async () => {
const team = await prisma.team.create({ data: { name: 'Version Team' } })
const user = await prisma.user.create({
data: { name: 'Version User', email: 'vuser@example.com' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Version Project', teamId: team.id },
})
const parentFolder = await prisma.asset.create({
data: {
name: 'Parent Folder',
type: 'folder',
projectId: project.id,
status: 'uploaded',
},
})
// Create file1 (V1)
const file1 = await prisma.asset.create({
data: {
name: 'file1.txt',
type: 'file',
parentId: parentFolder.id,
projectId: project.id,
status: 'uploaded',
sizeByte: 100,
},
})
// 1. Create file2 (V2) - Creates a new stack
const file2Result = await executeAgentToolActivity({
taskId: 'vstack-task-1',
toolName: 'create_version',
args: {
parent: file1.id,
s3Key: 'file/file2-key/raw',
name: 'file2.txt',
size: 150,
contentType: 'text/plain',
},
userId: user.id,
})
// Fetch from DB to check sortIndex
const updatedFile1 = await prisma.asset.findUnique({ where: { id: file1.id } })
const updatedFile2 = await prisma.asset.findUnique({ where: { id: file2Result.id } })
// Newest version (file2) must have a strictly lower sortIndex than older version (file1)
expect(updatedFile2!.sortIndex! < updatedFile1!.sortIndex!).toBe(true)
// 2. Create file3 (V3) - Appends to existing stack
const file3Result = await executeAgentToolActivity({
taskId: 'vstack-task-2',
toolName: 'create_version',
args: {
parent: file2Result.id,
s3Key: 'file/file3-key/raw',
name: 'file3.txt',
size: 200,
contentType: 'text/plain',
},
userId: user.id,
})
const updatedFile3 = await prisma.asset.findUnique({ where: { id: file3Result.id } })
// Newest version (file3) must have a strictly lower sortIndex than version 2 (file2)
expect(updatedFile3!.sortIndex! < updatedFile2!.sortIndex!).toBe(true)
})
})
})
File diff suppressed because it is too large Load Diff
-13
View File
@@ -1,13 +0,0 @@
import * as transcodeActivities from '@/transcode/activities/transcode'
import * as agentActivities from './agent'
import * as aiActivities from './ai'
import * as dbActivities from './db'
import * as taskActivities from './task'
export const activities = {
...taskActivities,
...aiActivities,
...transcodeActivities,
...agentActivities,
...dbActivities,
}
-68
View File
@@ -1,68 +0,0 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { updateTaskStatusActivity, updateAssetStatusActivity, updateTaskUsageActivity } from './db'
import { WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
describe('Task Activities', () => {
setupTestDbHooks()
it('should update task status', async () => {
const task = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
},
})
await updateTaskStatusActivity({
taskId: task.id,
status: WorkflowTaskStatus.processing,
})
const updated = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(updated?.status).toBe(WorkflowTaskStatus.processing)
})
it('should update asset status', async () => {
const asset = await prisma.asset.create({
data: {
name: 'test.mp4',
storageKey: { create: { key: 'test.mp4' } },
status: 'uploaded',
type: 'file',
},
})
await updateAssetStatusActivity({
assetId: asset.id,
status: AssetStatus.processing,
})
const updated = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(updated?.status).toBe(AssetStatus.processing)
})
it('should update task usage', async () => {
const task = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
},
})
await updateTaskUsageActivity({
taskId: task.id,
inputTokens: 100,
outputTokens: 200,
model: 'gpt-4o',
})
const updated = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(updated?.inputTokens).toBe(100)
expect(updated?.outputTokens).toBe(200)
expect(updated?.model).toBe('gpt-4o')
})
})
-7
View File
@@ -1,7 +0,0 @@
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
return 'transcode_queue'
}
export async function getAgentWorkerQueueActivity(): Promise<string> {
return 'agent_queue'
}
-7
View File
@@ -1,7 +0,0 @@
import { WorkflowTask } from '@shumai/db'
export interface Executor {
submit(task: WorkflowTask): Promise<string>
start(): void
close(): void
}
-353
View File
@@ -1,353 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { workflowService } from './workflow'
import { LocalExecutor, ConcurrencyLimiter } from './local-executor'
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
// Mock the individual workflows
const mocks = {
agentEmbeddingMedia: vi.fn(),
queryEmbeddingForSearch: vi.fn(),
agentAutofillMedia: vi.fn(),
agentChat: vi.fn(),
transcodeMedia: vi.fn(),
}
vi.mock('./workflows/agent-embedding', () => ({
agentEmbeddingMedia: (task: unknown) => mocks.agentEmbeddingMedia(task),
}))
vi.mock('./workflows/query-embedding-for-search', () => ({
queryEmbeddingForSearch: (task: unknown) => mocks.queryEmbeddingForSearch(task),
}))
vi.mock('./workflows/agent-autofill', () => ({
agentAutofillMedia: (task: unknown) => mocks.agentAutofillMedia(task),
}))
vi.mock('./workflows/agent-chat', () => ({
agentChat: (task: unknown) => mocks.agentChat(task),
}))
vi.mock('@/transcode/workflows/transcode', () => ({
transcodeMedia: (task: unknown) => mocks.transcodeMedia(task),
}))
describe('LocalExecutor Integration Tests', () => {
setupTestDbHooks()
let executor: LocalExecutor
beforeEach(() => {
// Get the global executor instance which processes tasks submitted via the Prisma Client Extension
executor = (workflowService as unknown as { executor: LocalExecutor }).executor
vi.clearAllMocks()
})
describe('Heartbeat & Task Status transition', () => {
it('should immediately transition task to processing and set initial heartbeat', async () => {
let resolveChat: (value: unknown) => void = () => {}
const chatPromise = new Promise((resolve) => {
resolveChat = resolve
})
mocks.agentChat.mockImplementationOnce(() => chatPromise)
const task = await prisma.workflowTask.create({
data: {
assetId: 'test-asset',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
})
// Wait briefly for the Prisma Client Extension's async submit (setTimeout 0) to execute and transition task
await new Promise((resolve) => setTimeout(resolve, 50))
const intermediateTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
expect(intermediateTask?.status).toBe(WorkflowTaskStatus.processing)
expect(intermediateTask?.heartbeat).toBeInstanceOf(Date)
// Clean up
resolveChat(undefined)
await new Promise((resolve) => setTimeout(resolve, 50))
})
it('should immediately lock task and start heartbeat updates in database even when queued in limiter', async () => {
let resolveFirstTranscode: (value: unknown) => void = () => {}
const firstTranscodePromise = new Promise((resolve) => {
resolveFirstTranscode = resolve
})
mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise)
mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve())
// 1. Create task 1 (will run immediately and hold the transcode limiter slot)
const task1 = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
},
})
// 2. Create task 2 (will be blocked and queued in memory by transcode limiter)
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'asset-2',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
},
})
// Wait briefly for Prisma Client Extension's async submits to queue task2
await new Promise((resolve) => setTimeout(resolve, 50))
// 3. Verify task 1 is running
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id }))
// 4. Verify task 2 has NOT started executing yet
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
expect.objectContaining({ id: task2.id }),
)
// 5. BUT verify task 2 is already locked in database and has heartbeat set!
const dbTask2 = await prisma.workflowTask.findUnique({
where: { id: task2.id },
})
expect(dbTask2?.status).toBe(WorkflowTaskStatus.processing)
expect(dbTask2?.heartbeat).toBeInstanceOf(Date)
// Clean up
resolveFirstTranscode(undefined)
await new Promise((resolve) => setTimeout(resolve, 50))
})
it('should atomically claim tasks using CAS updateMany to prevent double-execution when tick() runs concurrently', async () => {
mocks.agentChat.mockResolvedValue(undefined)
// Mock submit to prevent automatic execution by the Prisma Client Extension
const submitSpy = vi.spyOn(workflowService, 'submit').mockResolvedValue('dummy-id')
// Create a single pending task (will NOT be run automatically because submit is mocked)
const task = await prisma.workflowTask.create({
data: {
assetId: 'asset-concurrent-test',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
})
// We trigger two ticks concurrently to simulate overlapping polling cycles or multi-replica triggers.
// Both ticks will query the database at approximately the same time.
const tick1 = executor.tick()
const tick2 = executor.tick()
const [promises1, promises2] = await Promise.all([tick1, tick2])
await Promise.all([...promises1, ...promises2])
// Verify that the mock workflow is called EXACTLY ONCE for this task ID,
// proving that one tick successfully claimed the task and the other was atomically blocked.
expect(mocks.agentChat).toHaveBeenCalledTimes(1)
expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: task.id }))
submitSpy.mockRestore()
})
it('should query and retry stale tasks in tick() but ignore non-stale processing tasks', async () => {
mocks.agentChat.mockResolvedValue(undefined)
// 1. Create a stale task (processing, heartbeat 40 seconds ago)
const staleTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-stale',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.processing,
heartbeat: new Date(Date.now() - 40 * 1000),
},
})
// 2. Create a non-stale task (processing, heartbeat 5 seconds ago)
const activeTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-active',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.processing,
heartbeat: new Date(Date.now() - 5 * 1000),
},
})
// Trigger tick manually on the executor and await the returned task promises
const promises = await executor.tick()
await Promise.all(promises)
// The stale task should be picked up and processed (mocks.agentChat called for staleTask)
expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: staleTask.id }))
// The active task should NOT be called
expect(mocks.agentChat).not.toHaveBeenCalledWith(
expect.objectContaining({ id: activeTask.id }),
)
})
})
describe('Concurrency Control', () => {
it('should limit transcode tasks to a concurrency of 1', async () => {
let resolveFirstTranscode: (value: unknown) => void = () => {}
const firstTranscodePromise = new Promise((resolve) => {
resolveFirstTranscode = resolve
})
mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise)
mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve())
const task1 = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'asset-2',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
},
})
// Wait briefly for Prisma Client Extension's async submits to trigger
await new Promise((resolve) => setTimeout(resolve, 50))
// The first task should be actively running
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id }))
// The second task should NOT have started yet because transcode pool limit is 1
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
expect.objectContaining({ id: task2.id }),
)
// Resolve the first task to let the second task execute
resolveFirstTranscode(undefined)
// Wait briefly for the pool queue to process next item
await new Promise((resolve) => setTimeout(resolve, 50))
// The second task should now be running
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task2.id }))
})
it('should limit general tasks to a concurrency of 5 and run them concurrently', async () => {
const activeResolvers: ((value: unknown) => void)[] = []
mocks.agentChat.mockImplementation(() => {
return new Promise((resolve) => {
activeResolvers.push(resolve)
})
})
// Create 7 general workflow tasks (limit is 5)
await Promise.all(
Array.from({ length: 7 }).map((_, i) =>
prisma.workflowTask.create({
data: {
assetId: `asset-chat-${i}`,
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
}),
),
)
// Wait briefly for Prisma Client Extension's async submits to trigger
await new Promise((resolve) => setTimeout(resolve, 100))
// Exactly 5 tasks should be running concurrently
expect(mocks.agentChat).toHaveBeenCalledTimes(5)
// Resolve 2 tasks to let the remaining 2 start
activeResolvers[0](undefined)
activeResolvers[1](undefined)
// Wait briefly for the pool to dequeue
await new Promise((resolve) => setTimeout(resolve, 50))
// Now all 7 tasks should have started
expect(mocks.agentChat).toHaveBeenCalledTimes(7)
// Clean up remaining tasks
activeResolvers.slice(2).forEach((resolve) => resolve(undefined))
await new Promise((resolve) => setTimeout(resolve, 50))
})
})
describe('ConcurrencyLimiter Unit Tests', () => {
it('should not allow concurrency limit violation during microtask race conditions', async () => {
const limiter = new ConcurrencyLimiter(1)
// Task A starts and runs
let resolveA: () => void = () => {}
const promiseA = limiter.run(
() =>
new Promise<void>((resolve) => {
resolveA = resolve
}),
)
// Task B enters and is queued
let resolveB: () => void = () => {}
const promiseB = limiter.run(
() =>
new Promise<void>((resolve) => {
resolveB = resolve
}),
)
// Wait briefly for Task B to queue up
await new Promise((resolve) => setTimeout(resolve, 10))
expect(limiter.getActiveCount()).toBe(1)
expect(limiter.getQueueLength()).toBe(1)
// Complete Task A (schedules Task A's body to resume)
resolveA()
// Wait exactly one microtask tick to let Task A exit and trigger finally block (resolving Task B)
// This positions us in the microtask gap before Task B resumes execution
await Promise.resolve()
// Task C immediately enters the limiter synchronously
let resolveC: () => void = () => {}
const promiseC = limiter.run(
() =>
new Promise<void>((resolve) => {
resolveC = resolve
}),
)
// Under the buggy implementation:
// - Task A's finally block decremented activeCount to 0.
// - Task C sees activeCount = 0 and runs immediately instead of queueing.
// - So queue length would be 0, and Task C is active.
//
// Under the fixed implementation:
// - Task A's finally block transferred the slot to Task B without decrementing activeCount.
// - So activeCount remains 1.
// - Task C sees activeCount = 1 and is correctly queued.
// - So queue length is 1, and Task C is NOT active.
expect(limiter.getActiveCount()).toBe(1)
expect(limiter.getQueueLength()).toBe(1)
// Clean up by resolving the rest in order
// 1. Let Task B resume and run
await new Promise((resolve) => setTimeout(resolve, 10))
resolveB()
// 2. Let Task C resume and run
await new Promise((resolve) => setTimeout(resolve, 10))
resolveC()
await Promise.all([promiseA, promiseB, promiseC])
expect(limiter.getActiveCount()).toBe(0)
expect(limiter.getQueueLength()).toBe(0)
})
})
})
-275
View File
@@ -1,275 +0,0 @@
import { prisma } from '@shumai/db'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { Executor } from './executor'
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 { transcodeMedia } from '@/transcode/workflows/transcode'
import { agentToolCall } from './workflows/agent-tool-call'
import { activities } from './activities/index'
import { logger } from '@/logger'
// Inject local dependencies into global scope for workflow-utils
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(globalThis as any).__localActivities = activities
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(globalThis as any).__localLogger = logger
export class ConcurrencyLimiter {
private activeCount = 0
private queue: (() => void)[] = []
constructor(private readonly limit: number) {}
async run<T>(fn: () => Promise<T>): Promise<T> {
if (this.activeCount >= this.limit) {
await new Promise<void>((resolve) => this.queue.push(resolve))
} else {
this.activeCount++
}
try {
return await fn()
} finally {
const next = this.queue.shift()
if (next) {
next()
} else {
this.activeCount--
}
}
}
// Exposed for testing concurrency status
getActiveCount(): number {
return this.activeCount
}
getQueueLength(): number {
return this.queue.length
}
}
export class LocalExecutor implements Executor {
private interval: Timer | null = null
private processingTasks = new Set<string>()
// 1 concurrency for transcode, 5 for other workflows
private transcodeLimiter = new ConcurrencyLimiter(1)
private generalLimiter = new ConcurrencyLimiter(5)
async submit(task: WorkflowTask): Promise<string> {
if (task.status !== WorkflowTaskStatus.pending) {
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: WorkflowTaskStatus.pending },
})
}
// In tests, we trigger processing immediately using the appropriate limiter
if (process.env.NODE_ENV === 'test') {
setTimeout(async () => {
if (this.processingTasks.has(task.id)) return
this.processingTasks.add(task.id)
// 1. Immediately mark task as processing and set initial heartbeat in DB
// atomically, only if the task is still pending.
try {
const affected = await prisma.workflowTask.updateMany({
where: {
id: task.id,
status: WorkflowTaskStatus.pending,
},
data: {
status: WorkflowTaskStatus.processing,
heartbeat: new Date(),
},
})
if (affected.count === 0) {
this.processingTasks.delete(task.id)
return
}
} catch (err) {
console.error(
`[LocalExecutor] Failed to mark task ${task.id} as processing in submit:`,
err,
)
this.processingTasks.delete(task.id)
return
}
// 2. Start heartbeat updater immediately
const heartbeatInterval = setInterval(async () => {
try {
await prisma.workflowTask.update({
where: { id: task.id },
data: { heartbeat: new Date() },
})
} catch (err) {
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
}
}, 5000)
const limiter =
task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter
limiter
.run(async () => {
try {
await this.processTaskWrapper(task)
} finally {
// 3. Clean up the heartbeat updater and processing set when the task finishes
clearInterval(heartbeatInterval)
this.processingTasks.delete(task.id)
}
})
.catch((err) => {
console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err)
})
}, 0)
}
return task.id
}
start(): void {
if (this.interval) return
this.interval = setInterval(() => this.tick(), 5000)
}
close(): void {
if (this.interval) {
clearInterval(this.interval)
this.interval = null
}
}
// Returns the array of task promises so tests can await them to avoid early rollback.
async tick(): Promise<Promise<void>[]> {
const promises: Promise<void>[] = []
try {
const staleTime = new Date(Date.now() - 30 * 1000)
const tasks = await prisma.workflowTask.findMany({
where: {
OR: [
{ status: WorkflowTaskStatus.pending },
{
status: WorkflowTaskStatus.processing,
heartbeat: { lt: staleTime },
},
],
},
take: 50,
})
for (const task of tasks) {
if (this.processingTasks.has(task.id)) continue
this.processingTasks.add(task.id)
// 1. Immediately mark task as processing and set initial heartbeat in DB
// to guarantee no other ticks/replicas can double-query it.
// We use updateMany to atomically claim it only if it is still pending or stale.
try {
const affected = await prisma.workflowTask.updateMany({
where: {
id: task.id,
OR: [
{ status: WorkflowTaskStatus.pending },
{
status: WorkflowTaskStatus.processing,
heartbeat: { lt: staleTime },
},
],
},
data: {
status: WorkflowTaskStatus.processing,
heartbeat: new Date(),
},
})
if (affected.count === 0) {
this.processingTasks.delete(task.id)
continue
}
} catch (err) {
console.error(`[LocalExecutor] Failed to mark task ${task.id} as processing:`, err)
this.processingTasks.delete(task.id)
continue
}
// 2. Start heartbeat updater immediately so it updates heartbeat
// even while the task is queued waiting for limiter capacity.
const heartbeatInterval = setInterval(async () => {
try {
await prisma.workflowTask.update({
where: { id: task.id },
data: { heartbeat: new Date() },
})
} catch (err) {
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
}
}, 5000)
const limiter =
task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter
const promise = limiter
.run(async () => {
try {
await this.processTaskWrapper(task)
} finally {
// 3. Clean up the heartbeat updater and processing set when the task finishes
clearInterval(heartbeatInterval)
this.processingTasks.delete(task.id)
}
})
.catch((err) => {
console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err)
})
promises.push(promise)
}
} catch (err) {
console.error('Failed to fetch tasks:', err)
}
return promises
}
private async processTaskWrapper(task: WorkflowTask) {
try {
switch (task.type) {
case WorkflowTaskType.ai_embedding:
await agentEmbeddingMedia(task)
break
case WorkflowTaskType.query_embedding_for_search:
await queryEmbeddingForSearch(task)
break
case WorkflowTaskType.ai_metadata_autofill:
await agentAutofillMedia(task)
break
case WorkflowTaskType.chat:
await agentChat(task)
break
case WorkflowTaskType.transcode:
await transcodeMedia(task)
break
case WorkflowTaskType.agent_tool_call:
await agentToolCall(task)
break
default:
console.warn(`Unknown task type: ${task.type}`)
}
} catch (err) {
console.error(`Error in workflow ${task.type} for task ${task.id}:`, err)
try {
await prisma.workflowTask.update({
where: { id: task.id },
data: {
status: WorkflowTaskStatus.failed,
output: { error: err instanceof Error ? err.message : String(err) },
},
})
} catch (updateErr) {
console.error(`Failed to set task ${task.id} to failed:`, updateErr)
}
}
}
}
-65
View File
@@ -1,65 +0,0 @@
import { Connection, Client } from '@temporalio/client'
import { WorkflowTask, WorkflowTaskType } from '@shumai/db'
import { Executor } from './executor'
export const TASK_QUEUE_DB = 'db_queue'
export class TemporalExecutor implements Executor {
private client: Client | null = null
private connection: Connection | null = null
constructor(private address: string = 'localhost:7233') {}
async submit(task: WorkflowTask): Promise<string> {
const client = await this.getClient()
const workflowId = `${task.type}-${task.id}`
let workflowName: string
switch (task.type) {
case WorkflowTaskType.ai_embedding:
workflowName = 'agentEmbeddingWorkflow'
break
case WorkflowTaskType.query_embedding_for_search:
workflowName = 'queryEmbeddingForSearch'
break
case WorkflowTaskType.ai_metadata_autofill:
workflowName = 'agentAutofillWorkflow'
break
case WorkflowTaskType.chat:
workflowName = 'agentChatWorkflow'
break
case WorkflowTaskType.transcode:
workflowName = 'transcodeWorkflow'
break
default:
throw new Error(`Unknown task type: ${task.type}`)
}
const handle = await client.workflow.start(workflowName, {
taskQueue: TASK_QUEUE_DB,
workflowId,
args: [task],
})
return handle.workflowId
}
start(): void {
// Client doesn't need explicit start
}
close(): void {
if (this.connection) {
this.connection.close()
this.connection = null
this.client = null
}
}
private async getClient(): Promise<Client> {
if (this.client) return this.client
this.connection = await Connection.connect({ address: this.address })
this.client = new Client({ connection: this.connection })
return this.client
}
}
-42
View File
@@ -1,42 +0,0 @@
import { describe, it, expect, vi, beforeAll } from 'vitest'
import { getActivities, executeActivity } from './workflow-utils'
describe('workflow-utils executeActivity', () => {
beforeAll(() => {
// Inject mock activities for local execution tests
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(globalThis as any).__localActivities = {
updateTaskStatusActivity: vi.fn(),
}
})
it('should attach _activityName to proxy functions from getActivities', () => {
const { updateTaskStatusActivity } = getActivities()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((updateTaskStatusActivity as any)._activityName).toBe('updateTaskStatusActivity')
})
it('should execute the function and pass arguments in local mode', async () => {
const mockFn = vi.fn().mockResolvedValue('success-result')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(mockFn as any)._activityName = 'mockActivity'
const result = await executeActivity(
'test-queue',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockFn as any,
{ some: 'args' },
)
expect(mockFn).toHaveBeenCalledWith({ some: 'args' })
expect(result).toBe('success-result')
})
it('should throw error if function does not have _activityName', async () => {
const normalFn = async () => {}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await expect(executeActivity('queue', normalFn as any)).rejects.toThrow(
'executeActivity must be called with an activity function obtained from getActivities()',
)
})
})
-148
View File
@@ -1,148 +0,0 @@
// Use type-only imports for activities to avoid bundling them in Temporal workflows
import type { activities } from './activities/index'
import * as wf from '@temporalio/workflow'
/**
* Task queue constants.
*/
export const TaskQueueDb = 'db_queue'
export const TaskQueueAgent = 'agent_queue'
export const TaskQueueTranscode = 'transcode_queue'
/**
* Detects if the current execution is within a Temporal Workflow isolate.
*/
export function isTemporal(): boolean {
try {
// In Temporal TS SDK, workflowInfo() throws if called outside of a workflow context.
wf.workflowInfo()
return true
} catch {
return false
}
}
/**
* A proxy that mimics proxyActivities for local execution.
*/
function localActivitiesProxy(): typeof activities {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const acts = (globalThis as any).__localActivities
if (!acts) {
throw new Error('Local activities not injected into globalThis.__localActivities')
}
return acts
}
/**
* Environment-aware sleep function.
*/
export async function sleep(ms: number): Promise<void> {
if (isTemporal()) {
await wf.sleep(ms)
} else {
await new Promise((resolve) => setTimeout(resolve, ms))
}
}
/**
* Environment-aware activity proxy.
*/
export function getActivities(): typeof activities {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let baseProxy: any
if (isTemporal()) {
baseProxy = wf.proxyActivities<typeof activities>({
startToCloseTimeout: '10 minutes',
})
} else {
baseProxy = localActivitiesProxy()
}
// Wrap the base proxy to attach the activity name to the returned functions
// We use any here because we are dynamically intercepting properties on the proxy
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new Proxy(baseProxy as any, {
get(target, prop) {
if (typeof prop === 'string') {
const original = target[prop]
if (typeof original === 'function') {
// Return a wrapper function that has the _activityName property
const wrapped = (...args: unknown[]) => original(...args)
// We attach a hidden property to track the activity name for executeActivity
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(wrapped as any)._activityName = prop
return wrapped
}
return original
}
return Reflect.get(target, prop)
},
})
}
/**
* Environment-aware logger for workflows and activities.
*/
function getLogger() {
if (isTemporal()) {
return {
debug: (obj: Record<string, unknown>, msg: string) => wf.log.debug(msg, obj),
info: (obj: Record<string, unknown>, msg: string) => wf.log.info(msg, obj),
error: (obj: Record<string, unknown>, msg: string) => wf.log.error(msg, obj),
warn: (obj: Record<string, unknown>, msg: string) => wf.log.warn(msg, obj),
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (globalThis as any).__localLogger || console
}
/**
* Execute an activity on a specific task queue.
* @param queue The task queue to run the activity on
* @param activityFunc The proxy function obtained from `getActivities()`
* @param args The arguments to pass to the activity
*/
export async function executeActivity<TArgs extends unknown[], TRet>(
queue: string,
activityFunc: (...args: TArgs) => Promise<TRet>,
...args: TArgs
): Promise<TRet> {
// We extract the hidden _activityName property attached by getActivities()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const activityName = (activityFunc as any)._activityName
if (!activityName) {
throw new Error(
'executeActivity must be called with an activity function obtained from getActivities()',
)
}
const logger = getLogger()
logger.debug({ queue, activityName }, `Executing activity ${activityName} on queue ${queue}`)
try {
let result: TRet
if (isTemporal()) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handle = wf.proxyActivities<any>({
startToCloseTimeout: '10 minutes',
taskQueue: queue,
})
result = await handle[activityName](...args)
} else {
// For local execution, queue is ignored and we just execute the function
result = await activityFunc(...args)
}
logger.debug(
{ queue, activityName },
`Activity ${activityName} completed successfully on queue ${queue}`,
)
return result
} catch (err) {
logger.error(
{ queue, activityName, err },
`Activity ${activityName} failed on queue ${queue}: ${err instanceof Error ? err.message : String(err)}`,
)
throw err
}
}
-185
View File
@@ -1,185 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { workflowService } from './workflow'
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
listObjects: vi.fn().mockResolvedValue([]),
downloadToFile: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('@/transcode/transcode', () => ({
transcodeService: {
createTempDir: vi.fn().mockReturnValue('/tmp/shumai-test'),
removeDir: vi.fn(),
extractAudio: vi.fn(),
extractVideoFrames: vi.fn().mockResolvedValue([]),
getVideoInfo: vi.fn(),
getImageInfo: vi.fn(),
transcodeVideo: vi.fn(),
transcodeImage: vi.fn(),
generateSprite: vi.fn(),
},
}))
describe('WorkflowService', () => {
beforeEach(async () => {
await prisma.workflowTask.deleteMany()
await prisma.assetComment.deleteMany()
await prisma.asset.deleteMany()
vi.clearAllMocks()
workflowService.start()
})
afterEach(() => {
workflowService.close()
})
it('should process ai_embedding task locally', async () => {
const team = await prisma.team.create({
data: { name: 'Embedding Team' },
})
const project = await prisma.project.create({
data: { name: 'Embedding Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test.png',
storageKey: { create: { key: 'test/test.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
// Note: This might fail if AI providers are not configured, but we want to check the workflow flow.
// In a real test environment, we might mock the AI service.
// However, let's see if it gets to 'failed' or 'completed' depending on the environment.
let finishedTask = null
for (let i = 0; i < 20; i++) {
finishedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (
finishedTask?.status === WorkflowTaskStatus.completed ||
finishedTask?.status === WorkflowTaskStatus.failed
) {
break
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
expect(finishedTask?.status).toBeDefined()
// Even if it fails due to missing API keys, the fact that it's no longer 'pending' means the workflow was triggered.
expect(finishedTask?.status).not.toBe(WorkflowTaskStatus.pending)
}, 15000)
it('should propagate ApplicationFailure correctly in local executor', async () => {
// Creating an ai_embedding task without any embedding agent configured for the team
const team = await prisma.team.create({
data: { name: 'Failure Team' },
})
const project = await prisma.project.create({
data: { name: 'Failure Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test.png',
storageKey: { create: { key: 'test/failure-test.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
let finishedTask = null
for (let i = 0; i < 20; i++) {
finishedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (finishedTask?.status === WorkflowTaskStatus.failed) {
break
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
expect(finishedTask?.status).toBe(WorkflowTaskStatus.failed)
expect((finishedTask?.output as Record<string, unknown>)?.error).toBe(
'embedding feature is disabled or agent not found',
)
}, 15000)
it('should not double-submit the task when executeWait is called', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team' },
})
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test-double.png',
storageKey: { create: { key: 'test/test-double.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const submitSpy = vi.spyOn(workflowService, 'submit')
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
// Wait briefly for the Prisma extension's async import/submit to fire
await new Promise((resolve) => setTimeout(resolve, 100))
expect(submitSpy).toHaveBeenCalledTimes(1)
// Complete the task in the database so executeWait returns immediately
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: 'completed' },
})
await workflowService.executeWait(task)
// Verify it was not submitted a second time by executeWait
expect(submitSpy).toHaveBeenCalledTimes(1)
submitSpy.mockRestore()
})
})
-127
View File
@@ -1,127 +0,0 @@
import { WorkflowTask } from '@shumai/db'
import { Executor } from './executor'
import { LocalExecutor } from './local-executor'
import { TemporalExecutor } from './temporal-executor'
import { prisma, registerWorkflowTrigger } from '@shumai/db'
export class WorkflowService {
private executor: Executor
constructor() {
const type = process.env.WORKFLOW_EXECUTOR || 'local'
if (type === 'temporal') {
this.executor = new TemporalExecutor(process.env.TEMPORAL_ADDRESS)
} else {
this.executor = new LocalExecutor()
}
}
async submit(task: WorkflowTask): Promise<string> {
return this.executor.submit(task)
}
async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise<WorkflowTask> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
const updatedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (!updatedTask) {
throw new Error(`WorkflowTask ${task.id} not found`)
}
if (updatedTask.status === 'completed') {
return updatedTask
}
if (updatedTask.status === 'failed') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const error = (updatedTask.output as any)?.error || 'Workflow task failed'
throw new Error(error)
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
throw new Error('Workflow task timed out')
}
start(): void {
this.executor.start()
}
close(): void {
this.executor.close()
}
// Starts Temporal workers for specific task queues
async startWorkers(queue: string = 'db_queue'): Promise<void> {
const type = process.env.WORKFLOW_EXECUTOR || 'local'
if (type === 'temporal') {
const { Worker, NativeConnection } = await import('@temporalio/worker')
const { activities } = await import('./activities/index')
const connection = await NativeConnection.connect({
address: process.env.TEMPORAL_ADDRESS || 'localhost:7233',
})
// @ts-ignore
const { default: workflowBundle } = await import('./workflows:::workflow')
if (queue === 'db_queue') {
console.log(`Starting Temporal worker for queue: ${queue}`)
const worker = await Worker.create({
connection,
workflowBundle,
activities,
taskQueue: queue,
})
await worker.run()
return
}
// For agent_queue and transcode_queue, use worker-specific unique queues
const crypto = await import('crypto')
const workerId = crypto.randomUUID()
const workerSpecificQueue = `${queue}-${workerId}`
console.log(`Starting Temporal workers for domain: ${queue}`)
console.log(` - Shared queue: ${queue}`)
console.log(` - Worker-specific queue: ${workerSpecificQueue}`)
// Create a specific activities object for the shared worker that ONLY overrides the queue lookup
const sharedActivities: Record<string, unknown> = {}
if (queue === 'agent_queue') {
sharedActivities.getAgentWorkerQueueActivity = async () => workerSpecificQueue
} else if (queue === 'transcode_queue') {
sharedActivities.getTranscodeWorkerQueueActivity = async () => workerSpecificQueue
}
const sharedWorker = await Worker.create({
connection,
workflowBundle,
activities: sharedActivities,
taskQueue: queue,
})
const specificWorker = await Worker.create({
connection,
// No workflows needed for the unique queue
activities,
taskQueue: workerSpecificQueue,
})
await Promise.all([sharedWorker.run(), specificWorker.run()])
} else {
console.log(
`Workflow executor is set to "${type}". Separate worker processes are only needed for "temporal" mode.`,
)
}
}
}
export const workflowService = new WorkflowService()
registerWorkflowTrigger(async (task) => {
await workflowService.submit(task)
})
@@ -1,101 +0,0 @@
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 '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async () => {
const actual = await vi.importActual('@/workflow/workflow-utils')
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()
})
})
-202
View File
@@ -1,202 +0,0 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueAgent,
TaskQueueTranscode,
} from '@/workflow/workflow-utils'
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: 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: '__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) => ({
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
-92
View File
@@ -1,92 +0,0 @@
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 '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async () => {
const actual = await vi.importActual('@/workflow/workflow-utils')
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()
})
})
-209
View File
@@ -1,209 +0,0 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import {
executeActivity,
getActivities,
TaskQueueAgent,
TaskQueueDb,
} from '@/workflow/workflow-utils'
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
@@ -1,79 +0,0 @@
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 '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async () => {
const actual = await vi.importActual('@/workflow/workflow-utils')
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()
})
})
-111
View File
@@ -1,111 +0,0 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils'
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
-52
View File
@@ -1,52 +0,0 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb } from '../workflow-utils'
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
-6
View File
@@ -1,6 +0,0 @@
export * from './agent-embedding'
export * from './agent-autofill'
export * from './agent-chat'
export * from './query-embedding-for-search'
export * from './agent-tool-call'
export * from '@/transcode/workflows/transcode'
@@ -1,48 +0,0 @@
import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueDb } from '../workflow-utils'
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
}
}