mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
feat(agent): implement secure database-backed agent tools and comments context
This commit is contained in:
@@ -10,6 +10,8 @@ import {
|
||||
getAgentAutofillContextActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
getAssetPathContextActivity,
|
||||
executeAgentToolActivity,
|
||||
} from './db'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
|
||||
@@ -315,4 +317,164 @@ describe('Database Activities', () => {
|
||||
})
|
||||
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 fileResult = await executeAgentToolActivity({
|
||||
taskId: 'task2',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: parentFolder.id,
|
||||
path: tempFilePath,
|
||||
},
|
||||
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 versionResult = await executeAgentToolActivity({
|
||||
taskId: 'task4',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileResult.id,
|
||||
path: versionTempPath,
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,8 +4,17 @@ import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-co
|
||||
import { ulid } from 'ulid'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { UpdateAssetMetadataRequest } from '@/dtos/metadata'
|
||||
import { WorkflowTaskStatus, AssetStatus, Prisma } from '@/generated/prisma/client'
|
||||
import { WorkflowTaskStatus, AssetStatus, Prisma, AssetType } from '@/generated/prisma/client'
|
||||
import type { AgentExecutionContext } from './agent'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { VersionStackService } from '@/services/versionStack/versionStack'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { detectSupportedMimeType } from '@/utils/mime'
|
||||
import { paginateQuery, encodeCursor } from '@/services/pagination'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
export interface InitializeAgentSessionParams {
|
||||
teamId: string
|
||||
@@ -614,3 +623,410 @@ export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParam
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Agent System Tools & Context Activities
|
||||
// ==========================================
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
try {
|
||||
const buffer = fs.readFileSync(filePath)
|
||||
const detected = detectSupportedMimeType(new Uint8Array(buffer))
|
||||
if (detected) return detected
|
||||
} catch {
|
||||
/* Ignore S3 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',
|
||||
'.txt': 'text/plain',
|
||||
'.json': 'application/json',
|
||||
'.html': 'text/html',
|
||||
'.css': 'text/css',
|
||||
'.js': 'application/javascript',
|
||||
'.ts': 'application/typescript',
|
||||
'.zip': 'application/zip',
|
||||
}
|
||||
return mimeTypes[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
function generateSortIndex(previous?: string | null): string {
|
||||
if (!previous) return generateKeyBetween(null, null)
|
||||
return generateKeyBetween(previous, null)
|
||||
}
|
||||
|
||||
export async function getAssetPathContextActivity(assetId: string): Promise<string> {
|
||||
const parts: { name: string; id: string }[] = []
|
||||
let currentId: string | null = assetId
|
||||
|
||||
while (currentId) {
|
||||
/* prettier-ignore */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const assetNode: { id: string; name: string; parentId: string | null; type: AssetType } | null = (await prisma.asset.findUnique({ where: { id: currentId }, select: { id: true, name: true, parentId: true, type: true } })) as any
|
||||
if (!assetNode) break
|
||||
|
||||
if (assetNode.name) {
|
||||
parts.unshift({ name: assetNode.name, id: assetNode.id })
|
||||
}
|
||||
|
||||
currentId = assetNode.parentId
|
||||
}
|
||||
|
||||
if (parts.length === 0) return ''
|
||||
|
||||
const pathStr = parts.map((p) => p.name).join('/')
|
||||
let contextStr = `Path: ${pathStr}\n\n`
|
||||
for (const part of parts) {
|
||||
contextStr += `name: ${part.name}, id: ${part.id}\n`
|
||||
}
|
||||
|
||||
return contextStr
|
||||
}
|
||||
|
||||
export interface ExecuteAgentToolParams {
|
||||
taskId: string
|
||||
toolName: string
|
||||
// args are dynamic JSON arguments passed from the agent harness at runtime
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
args: any
|
||||
userId?: string
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export async function executeAgentToolActivity(params: ExecuteAgentToolParams): Promise<any> {
|
||||
const { toolName, args, userId } = params
|
||||
if (!userId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'User ID is required for tool authz',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 1. Fetch User
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } })
|
||||
if (!user) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `User not found: ${userId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Perform Authz and Action based on toolName
|
||||
switch (toolName) {
|
||||
case 'list_assets': {
|
||||
const parent = args.parent
|
||||
if (!parent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent parameter is required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const page = args.page || 1
|
||||
const pageSize = args.pageSize || 20
|
||||
const type = args.type || 'all'
|
||||
|
||||
// We need to list files and folders of parent dir
|
||||
const where: Prisma.AssetWhereInput = {
|
||||
parentId: parent,
|
||||
isDeleted: false,
|
||||
}
|
||||
if (type === 'file') {
|
||||
where.type = { in: ['file', 'version_stack'] }
|
||||
} else if (type === 'folder') {
|
||||
where.type = 'folder'
|
||||
} else {
|
||||
where.type = { in: ['file', 'folder', 'version_stack'] }
|
||||
}
|
||||
|
||||
const limit = pageSize
|
||||
const offset = (page - 1) * limit
|
||||
const after = offset > 0 ? encodeCursor(offset) : undefined
|
||||
|
||||
const { data: assets, pageInfo } = await paginateQuery<
|
||||
Prisma.AssetGetPayload<Record<string, never>>
|
||||
>(
|
||||
async (skip, take) => {
|
||||
return prisma.asset.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' }, // sort desc per ULID default in sorting guidelines!
|
||||
skip,
|
||||
take,
|
||||
})
|
||||
},
|
||||
async () => prisma.asset.count({ where }),
|
||||
{ first: limit, after, includeCount: true },
|
||||
)
|
||||
|
||||
// return asset id, asset name, asset type, asset size (sizeByte or size)
|
||||
const results = assets.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
size: a.sizeByte,
|
||||
}))
|
||||
|
||||
return {
|
||||
assets: results,
|
||||
pageInfo,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_folder': {
|
||||
const parent = args.parent
|
||||
const name = args.name
|
||||
if (!parent || !name) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent and name parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const newFolder = await assetService.createAsset({
|
||||
name,
|
||||
parentId: parent,
|
||||
type: 'folder',
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Increment fileCount of parent folder
|
||||
await prisma.asset.update({
|
||||
where: { id: parent },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFolder.id,
|
||||
name: newFolder.name,
|
||||
type: newFolder.type,
|
||||
size: newFolder.sizeByte,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_file': {
|
||||
const parent = args.parent
|
||||
const filePath = args.path
|
||||
if (!parent || !filePath) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent and path parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Local file not found at path: ${filePath}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const fileSize = fs.statSync(filePath).size
|
||||
const mimeType = getMimeType(filePath)
|
||||
|
||||
// Upload file to S3
|
||||
const key = await s3Service.uploadFile(filePath, mimeType)
|
||||
|
||||
// Create asset via assetService
|
||||
const newFile = await assetService.createAsset({
|
||||
name: path.basename(filePath),
|
||||
type: 'file',
|
||||
parentId: parent,
|
||||
key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Increment fileCount of parent and update ancestor size
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.asset.update({
|
||||
where: { id: parent },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, parent, fileSize)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_version': {
|
||||
const parent = args.parent // parent file id
|
||||
const filePath = args.path
|
||||
if (!parent || !filePath) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent and path parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch parent file and cast to any due to Prisma type resolution limits
|
||||
/* prettier-ignore */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const parentFile = (await prisma.asset.findUnique({ where: { id: parent }, include: { parent: true } })) as any
|
||||
if (!parentFile) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file not found with ID: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check: verify Edit permission on the parent file (resource ID is parent file id)
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Local file not found at path: ${filePath}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const fileSize = fs.statSync(filePath).size
|
||||
const mimeType = getMimeType(filePath)
|
||||
|
||||
// Upload file to S3
|
||||
const key = await s3Service.uploadFile(filePath, mimeType)
|
||||
|
||||
// If already in a version stack
|
||||
if (parentFile.parentId && parentFile.parent?.type === AssetType.version_stack) {
|
||||
const stackId = parentFile.parentId
|
||||
|
||||
// Create the new file asset
|
||||
const newFile = await assetService.createAsset({
|
||||
name: path.basename(filePath),
|
||||
type: 'file',
|
||||
parentId: stackId,
|
||||
key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Generate sort index for new version inside the stack
|
||||
const lastChild = await prisma.asset.findFirst({
|
||||
where: { parentId: stackId },
|
||||
orderBy: { sortIndex: 'desc' },
|
||||
})
|
||||
const newSortIndex = generateSortIndex(lastChild?.sortIndex)
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Assign sort index
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { sortIndex: newSortIndex },
|
||||
})
|
||||
// Increment stack's fileCount and size
|
||||
const updatedStack = await tx.asset.update({
|
||||
where: { id: stackId },
|
||||
data: {
|
||||
fileCount: { increment: 1 },
|
||||
sizeByte: { increment: fileSize },
|
||||
},
|
||||
})
|
||||
// Update ancestors' size of stack's parent
|
||||
if (updatedStack.parentId) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, updatedStack.parentId, fileSize)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
} else {
|
||||
// Parent is a regular file. We must create a new version stack.
|
||||
const folderParentId = parentFile.parentId
|
||||
if (!folderParentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file ${parent} has no parent folder`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Create the new file asset under parent folder first (so that createVersionStack can run on them,
|
||||
// which enforces both files must have same parent initially)
|
||||
const newFile = await assetService.createAsset({
|
||||
name: path.basename(filePath),
|
||||
type: 'file',
|
||||
parentId: folderParentId,
|
||||
key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const txVersionStackService = new VersionStackService(tx as any)
|
||||
await txVersionStackService.createVersionStack({
|
||||
fileIds: [parentFile.id, newFile.id],
|
||||
projectId: parentFile.projectId!,
|
||||
creatorId: userId,
|
||||
})
|
||||
// Update ancestors' size (add size of the new file version)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, folderParentId!, fileSize)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Unsupported tool name: ${toolName}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ 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'
|
||||
|
||||
@@ -250,6 +251,9 @@ export class LocalExecutor implements Executor {
|
||||
case WorkflowTaskType.transcode:
|
||||
await transcodeMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.agent_tool_call:
|
||||
await agentToolCall(task)
|
||||
break
|
||||
default:
|
||||
console.warn(`Unknown task type: ${task.type}`)
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ describe('Agent Chat Workflow', () => {
|
||||
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({
|
||||
@@ -53,6 +56,9 @@ describe('Agent Chat Workflow', () => {
|
||||
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',
|
||||
|
||||
@@ -20,6 +20,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
getAgentWorkerQueueActivity,
|
||||
deleteCommentActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAssetPathContextActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
@@ -99,7 +100,16 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
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)}`
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
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
|
||||
@@ -2,4 +2,5 @@ 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'
|
||||
|
||||
Reference in New Issue
Block a user