Merge pull request #44 from shumaiOne/feat/agent-system-tools

feat(agent): implement secure database-backed agent tools and comments context
This commit is contained in:
Yiling-J
2026-05-31 19:21:41 +08:00
committed by GitHub
29 changed files with 1372 additions and 149 deletions
-10
View File
@@ -1,10 +0,0 @@
Beijing: 🌤️ +20°C 50% ↙10km/h
Tokyo: 🌤️ +20°C 50% ↙10km/h
London: 🌤️ +20°C 50% ↙10km/h
New+York: 🌤️ +20°C 50% ↙10km/h
Paris: 🌤️ +20°C 50% ↙10km/h
Sydney: 🌤️ +20°C 50% ↙10km/h
Dubai: 🌤️ +20°C 50% ↙10km/h
Singapore: 🌤️ +20°C 50% ↙10km/h
Moscow: 🌤️ +20°C 50% ↙10km/h
Berlin: 🌤️ +20°C 50% ↙10km/h
@@ -1 +0,0 @@
6c49ce20d801d83fe10da4ad9cf51eac571100c0e3173d552de878f8e7bf612d
@@ -1,54 +0,0 @@
---
name: weather
description: Get current weather and forecasts (no API key required).
homepage: https://wttr.in/:help
metadata: { 'clawdbot': { 'emoji': '🌤️', 'requires': { 'bins': ['curl'] } } }
---
# Weather
Two free services, no API keys needed.
## wttr.in (primary)
Quick one-liner:
```bash
curl -s "wttr.in/London?format=3"
# Output: London: ⛅️ +8°C
```
Compact format:
```bash
curl -s "wttr.in/London?format=%l:+%c+%t+%h+%w"
# Output: London: ⛅️ +8°C 71% ↙5km/h
```
Full forecast:
```bash
curl -s "wttr.in/London?T"
```
Format codes: `%c` condition · `%t` temp · `%h` humidity · `%w` wind · `%l` location · `%m` moon
Tips:
- URL-encode spaces: `wttr.in/New+York`
- Airport codes: `wttr.in/JFK`
- Units: `?m` (metric) `?u` (USCS)
- Today only: `?1` · Current only: `?0`
- PNG: `curl -s "wttr.in/Berlin.png" -o /tmp/weather.png`
## Open-Meteo (fallback, JSON)
Free, no key, good for programmatic use:
```bash
curl -s "https://api.open-meteo.com/v1/forecast?latitude=51.5&longitude=-0.12&current_weather=true"
```
Find coordinates for a city, then query. Returns JSON with temp, windspeed, weathercode.
Docs: https://open-meteo.com/en/docs
@@ -1,6 +0,0 @@
{
"ownerId": "kn70pywhg0fyz996kpa8xj89s57yhv26",
"slug": "weather",
"version": "1.0.0",
"publishedAt": 1767545394459
}
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'agent_tool_call';
+1
View File
@@ -104,6 +104,7 @@ enum WorkflowTaskType {
chat
ai_embedding
query_embedding_for_search
agent_tool_call
}
enum WorkflowTaskStatus {
+33
View File
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest'
import { formatSkillsForPrompt } from './index'
import * as path from 'path'
describe('formatSkillsForPrompt', () => {
it('should return empty string if skills array is empty', () => {
expect(formatSkillsForPrompt([])).toBe('')
})
it('should format skills into the XML structure with absolute paths and escaped characters', () => {
const skills = [
{
id: 'skill-1',
name: 'Deploy & Test',
description: 'Deploys code <deploy> and "runs" tests.',
},
]
const expectedLocation = path.join(process.cwd(), '.pi', 'skills', 'skill-1', 'SKILL.md')
const result = formatSkillsForPrompt(skills)
// Verify lines and XML elements
expect(result).toContain('<available_skills>')
expect(result).toContain('<skill>')
expect(result).toContain('<name>Deploy &amp; Test</name>')
expect(result).toContain(
'<description>Deploys code &lt;deploy&gt; and &quot;runs&quot; tests.</description>',
)
expect(result).toContain(`<location>${expectedLocation}</location>`)
expect(result).toContain('</skill>')
expect(result).toContain('</available_skills>')
})
})
+68 -9
View File
@@ -7,6 +7,10 @@ import * as fs from 'fs'
import * as path from 'path'
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'
@@ -105,7 +109,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const allowWrite = [piDir, '/tmp']
const allowWrite = [piDir]
// SandboxManager.initialize is a global operation that applies to the entire process.
await SandboxManager.initialize({
@@ -114,9 +118,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
deniedDomains: [],
},
filesystem: {
denyRead: ['.env', '.env.*', '*.pem', '*.key'],
allowWrite,
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
denyRead: ['~/.ssh', '~/.aws', '~/.gnupg'],
},
})
@@ -128,19 +132,36 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
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 += '\n\nAvailable Skills:\n'
for (const s of teamSkills) {
prompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
}
prompt +=
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
prompt += formatSkillsForPrompt(teamSkills)
}
return prompt
},
@@ -157,7 +178,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
return undefined
},
tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...customTools],
tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...systemTools, ...customTools],
})
return { session, harness }
@@ -202,3 +223,41 @@ export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
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')
}
+99
View File
@@ -0,0 +1,99 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@/services/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
function getMimeType(filePath: string): string {
try {
const fd = fs.openSync(filePath, 'r')
try {
const buffer = Buffer.alloc(4100)
const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0)
const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead)))
if (detected) return detected
} finally {
fs.closeSync(fd)
}
} catch {
/* Ignore detection errors and fallback to extension mapping */
}
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.pdf': 'application/pdf',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const createFileSchema = Type.Object({
parent: Type.String({
description: 'The parent folder ID under which to create the file. This parameter is required.',
}),
path: Type.String({
description:
'The absolute or relative local path to the file on disk. This parameter is required.',
}),
})
export function createCreateFileTool(userId: string): AgentTool<typeof createFileSchema> {
return {
name: 'create_file',
label: 'Create File',
description: 'Create a new file in a specified parent folder from a local file path.',
parameters: createFileSchema,
execute: async (_toolCallId, params) => {
try {
const absolutePath = path.resolve(process.cwd(), params.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${params.path}`)
}
const fileSize = fs.statSync(absolutePath).size
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `file/${ulid()}/raw`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
toolName: 'create_file',
args: {
parent: params.parent,
s3Key,
name: path.basename(absolutePath),
size: fileSize,
contentType: mimeType,
},
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating file: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+46
View File
@@ -0,0 +1,46 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
const createFolderSchema = Type.Object({
parent: Type.String({
description:
'The parent folder ID under which to create the new folder. This parameter is required.',
}),
name: Type.String({
description: 'The name of the new folder to create. This parameter is required.',
}),
})
export function createCreateFolderTool(userId: string): AgentTool<typeof createFolderSchema> {
return {
name: 'create_folder',
label: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
parameters: createFolderSchema,
execute: async (_toolCallId, params) => {
try {
const result = await executeAgentToolWorkflow({
toolName: 'create_folder',
args: params,
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating folder: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+100
View File
@@ -0,0 +1,100 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
import * as fs from 'fs'
import * as path from 'path'
import { s3Service } from '@/services/s3/s3'
import { detectSupportedMimeType } from '@/utils/mime'
import { ulid } from 'ulid'
function getMimeType(filePath: string): string {
try {
const fd = fs.openSync(filePath, 'r')
try {
const buffer = Buffer.alloc(4100)
const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0)
const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead)))
if (detected) return detected
} finally {
fs.closeSync(fd)
}
} catch {
/* Ignore detection errors and fallback to extension mapping */
}
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.pdf': 'application/pdf',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const createVersionSchema = Type.Object({
parent: Type.String({
description:
'The parent file ID for which to create a new version. This parameter is required.',
}),
path: Type.String({
description:
'The absolute or relative local path to the file on disk. This parameter is required.',
}),
})
export function createCreateVersionTool(userId: string): AgentTool<typeof createVersionSchema> {
return {
name: 'create_version',
label: 'Create Version',
description: 'Create a new version of an existing file from a local file path.',
parameters: createVersionSchema,
execute: async (_toolCallId, params) => {
try {
const absolutePath = path.resolve(process.cwd(), params.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${params.path}`)
}
const fileSize = fs.statSync(absolutePath).size
const mimeType = getMimeType(absolutePath)
// Generate compliant S3 key matching normal file upload format
const s3Key = `file/${ulid()}/raw`
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
const result = await executeAgentToolWorkflow({
toolName: 'create_version',
args: {
parent: params.parent,
s3Key,
name: path.basename(absolutePath),
size: fileSize,
contentType: mimeType,
},
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error creating file version: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+61
View File
@@ -0,0 +1,61 @@
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { executeAgentToolWorkflow } from './utils'
const listAssetsSchema = Type.Object({
parent: Type.String({
description: 'The parent folder ID to list assets from. This parameter is required.',
}),
page: Type.Optional(
Type.Number({
description: 'The page number to retrieve, default is 1.',
default: 1,
}),
),
pageSize: Type.Optional(
Type.Number({
description: 'The number of assets per page, default is 20.',
default: 20,
}),
),
type: Type.Optional(
Type.String({
description: "Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'.",
enum: ['file', 'folder', 'all'],
default: 'all',
}),
),
})
export function createListAssetsTool(userId: string): AgentTool<typeof listAssetsSchema> {
return {
name: 'list_assets',
label: 'List Assets',
description: 'List the assets (files and folders) inside a parent folder with pagination.',
parameters: listAssetsSchema,
execute: async (_toolCallId, params) => {
try {
const result = await executeAgentToolWorkflow({
toolName: 'list_assets',
args: params,
userId,
assetId: params.parent,
})
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: result,
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error listing assets: ${error instanceof Error ? error.message : String(error)}`,
},
],
details: {},
}
}
},
}
}
+13 -1
View File
@@ -1,3 +1,4 @@
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'
@@ -36,7 +37,8 @@ export const createSandboxedBashTool = (
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
PATH: process.env.PATH || '',
HOME: process.env.HOME || '',
...skillEnvs,
},
})
@@ -81,6 +83,10 @@ export const createSandboxedBashTool = (
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)
})
@@ -89,10 +95,16 @@ export const createSandboxedBashTool = (
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
+35
View File
@@ -0,0 +1,35 @@
import { prisma } from '@/db'
import { workflowService } from '@/workflow/workflow'
import { WorkflowTaskType, WorkflowTaskStatus } from '@/generated/prisma/client'
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
}
+2 -1
View File
@@ -129,7 +129,8 @@ export const WorkflowTaskType = {
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
query_embedding_for_search: 'query_embedding_for_search'
query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call'
} as const
export type WorkflowTaskType = (typeof WorkflowTaskType)[keyof typeof WorkflowTaskType]
File diff suppressed because one or more lines are too long
+7
View File
@@ -245,11 +245,18 @@ declare global {
queryEmbeddingForSearch?: {
text: string
}
agentToolCall?: AgentToolCallPayload
}
// ----------------------------------------------------------------------
// Task Spec & Payload
// ----------------------------------------------------------------------
export interface AgentToolCallPayload {
toolName: string
args: Record<string, unknown>
userId: string
}
export interface TaskSpec {
videoStrategy?: VideoTranscodeStrategy
thumbnail?: boolean
+4
View File
@@ -907,6 +907,7 @@ describe('AssetService', () => {
expect(p1?.agent?.agentId).toBe(agent.id)
expect(p1?.agent?.sessionId).toBeUndefined()
expect(p1?.agent?.explicitMention).toBe(true)
expect(p1?.agent?.userId).toBe(user.id)
// Rule 2: user mentions agent in reply, and root is not an agent comment
const reply1 = await assetService.createComment({
@@ -925,6 +926,7 @@ describe('AssetService', () => {
expect(p2?.agent?.agentId).toBe(agent.id)
expect(p2?.agent?.sessionId).toBeUndefined()
expect(p2?.agent?.explicitMention).toBe(true)
expect(p2?.agent?.userId).toBe(user.id)
// Create a root user comment
const userRoot = await prisma.assetComment.create({
@@ -981,6 +983,7 @@ describe('AssetService', () => {
expect(p3a?.agent?.agentId).toBe(botUser.id)
expect(p3a?.agent?.sessionId).toBe('test-session-rule3')
expect(p3a?.agent?.explicitMention).toBe(false)
expect(p3a?.agent?.userId).toBe(user.id)
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
const reply3b = await assetService.createComment({
@@ -1008,6 +1011,7 @@ describe('AssetService', () => {
expect(p3b?.agent?.agentId).toBe(botUser.id)
expect(p3b?.agent?.sessionId).toBe('test-session-rule3')
expect(p3b?.agent?.explicitMention).toBe(true)
expect(p3b?.agent?.userId).toBe(user.id)
})
it('updates asset order correctly', async () => {
+2
View File
@@ -1280,6 +1280,7 @@ export class AssetService {
agentId: rootAgentId,
sessionId: rootSessionId || undefined,
explicitMention,
userId: req.userId,
},
},
},
@@ -1314,6 +1315,7 @@ export class AssetService {
userCommentId: comment.id,
agentId: agentId,
explicitMention: true,
userId: req.userId,
},
},
},
+78 -61
View File
@@ -237,83 +237,100 @@ export class UploadService {
if (!team) return
if (!asset.projectId) throw new Error('Asset project ID is missing')
// Ai Tasks
const autofillAgent = await tx.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
await this.triggerPostUploadWorkflows(tx, asset.id, team.id, asset.projectId)
})
}
async triggerPostUploadWorkflows(
tx: Prisma.TransactionClient,
assetId: string,
teamId: string,
projectId: string,
): Promise<void> {
const asset = await tx.asset.findUnique({
where: { id: assetId },
})
if (!asset) throw new Error('Asset not found')
const team = await tx.team.findUnique({
where: { id: teamId },
})
if (!team) throw new Error('Team not found')
// Ai Tasks
const autofillAgent = await tx.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (autofillAgent) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId,
payload: {
projectId,
agent: { agentId: autofillAgent.id },
},
},
})
}
if (autofillAgent) {
// Ai Embedding if enabled via agent
const embeddingAgent = await tx.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (embeddingAgent) {
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_metadata_autofill,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId: asset.projectId,
projectId,
payload: {
projectId: asset.projectId!,
agent: { agentId: autofillAgent.id },
projectId,
agent: { agentId: embeddingAgent.id },
},
},
})
}
}
// Ai Embedding if enabled via agent
const embeddingAgent = await tx.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
if (embeddingAgent) {
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId: asset.projectId,
payload: {
projectId: asset.projectId!,
agent: { agentId: embeddingAgent.id },
},
},
})
}
} else {
const settings = team.settings as PrismaJson.Settings | null
if (isVideo) {
const strategy = settings?.transcode?.videoStrategy || 'best_match'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
.setStrategy(strategy)
.withSprite()
.withPoster()
.submit()
} else if (isImage) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
}
const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
} else {
const settings = team.settings as PrismaJson.Settings | null
if (isVideo) {
const strategy = settings?.transcode?.videoStrategy || 'best_match'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new VideoTranscoder(tx as any, asset.id, team.id, asset.projectId)
.setStrategy(strategy)
.withSprite()
.withPoster()
.submit()
} else if (isImage) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, asset.projectId)
.withThumbnail()
.submit()
}
}
})
}
}
async listUploadTasks(
@@ -341,7 +341,7 @@ export function FileViewerRightSidebar({
</TabsTrigger>
</TabsList>
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
<ScrollArea className="flex-1">
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id}>
@@ -419,7 +419,7 @@ export function FileViewerRightSidebar({
)}
</TabsContent>
<TabsContent value="fields" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-4">
<ScrollArea className="flex-1 px-4">
<ScrollArea className="flex-1 px-4 min-h-0 [&>div>div]:block!">
{sortedFields && sortedFields.length > 0 && (
<div className="space-y-4 pb-4">
{sortedFields.map((field) => (
+12 -2
View File
@@ -1,5 +1,6 @@
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
import { DatabaseSessionStorage } from '@/agent/database-session-storage'
import type { Prisma, Skill } from '@/generated/prisma/client'
import { logger } from '@/logger'
import { s3Service } from '@/services/s3/s3'
import { type AgentTool } from '@earendil-works/pi-agent-core'
@@ -11,7 +12,6 @@ export interface Usage {
outputTokens: number
model: string
}
import type { Prisma, Skill } from '@/generated/prisma/client'
export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{
include: {
@@ -62,7 +62,17 @@ async function executeAgentPrompt(params: {
const providerName = agent.provider.name
const modelId = agent.modelRef.modelId
let systemPrompt = '你是shumai小助手。'
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}`
}
+326
View File
@@ -10,8 +10,11 @@ import {
getAgentAutofillContextActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
getAssetPathContextActivity,
executeAgentToolActivity,
} from './db'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { s3Service } from '@/services/s3/s3'
describe('Database Activities', () => {
setupTestDbHooks()
@@ -315,4 +318,327 @@ 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 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)
})
})
})
+407 -1
View File
@@ -4,8 +4,14 @@ 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 { assetService } from '@/services/asset/asset'
import { VersionStackService } from '@/services/versionStack/versionStack'
import { uploadService } from '@/services/upload/upload'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { paginateQuery, encodeCursor } from '@/services/pagination'
export interface InitializeAgentSessionParams {
teamId: string
@@ -614,3 +620,403 @@ export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParam
},
})
}
// ==========================================
// Agent System Tools & Context Activities
// ==========================================
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 s3Key = args.s3Key as string
const name = args.name as string
const fileSize = args.size as number
const mimeType = args.contentType as string
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
throw ApplicationFailure.create({
message: 'parent, s3Key, name, size, and contentType parameters are required',
nonRetryable: true,
})
}
// Authz check
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: parent,
})
// Fetch parent folder to resolve projectId and teamId
const parentAsset = await prisma.asset.findUnique({
where: { id: parent },
include: { project: true },
})
if (!parentAsset) {
throw ApplicationFailure.create({
message: `Parent folder not found with ID: ${parent}`,
nonRetryable: true,
})
}
if (!parentAsset.projectId || !parentAsset.project?.teamId) {
throw ApplicationFailure.create({
message: `Parent folder ${parent} has no project or team associated`,
nonRetryable: true,
})
}
// Create asset via assetService
const newFile = await assetService.createAsset({
name,
type: 'file',
parentId: parent,
key: s3Key,
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)
// Trigger post-upload transcode and AI workflows
await uploadService.triggerPostUploadWorkflows(
tx,
newFile.id,
parentAsset.project!.teamId,
parentAsset.projectId!,
)
})
return {
id: newFile.id,
name: newFile.name,
type: newFile.type,
size: newFile.sizeByte,
}
}
case 'create_version': {
const parent = args.parent // parent file id
const s3Key = args.s3Key as string
const name = args.name as string
const fileSize = args.size as number
const mimeType = args.contentType as string
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
throw ApplicationFailure.create({
message: 'parent, s3Key, name, size, and contentType 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, project: true } })) as any
if (!parentFile) {
throw ApplicationFailure.create({
message: `Parent file not found with ID: ${parent}`,
nonRetryable: true,
})
}
if (!parentFile.projectId || !parentFile.project?.teamId) {
throw ApplicationFailure.create({
message: `Parent file ${parent} has no project or team associated`,
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 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,
type: 'file',
parentId: stackId,
key: s3Key,
sizeByte: fileSize,
contentType: mimeType,
creatorId: userId,
})
// Generate sort index for new version inside the stack (newest gets the lowest sortIndex)
const firstChild = await prisma.asset.findFirst({
where: { parentId: stackId },
orderBy: { sortIndex: 'asc' },
})
const newSortIndex = generateKeyBetween(null, firstChild?.sortIndex || null)
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)
}
// Trigger post-upload transcode and AI workflows
await uploadService.triggerPostUploadWorkflows(
tx,
newFile.id,
parentFile.project.teamId,
parentFile.projectId,
)
})
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,
type: 'file',
parentId: folderParentId,
key: s3Key,
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: [newFile.id, parentFile.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)
// Trigger post-upload transcode and AI workflows
await uploadService.triggerPostUploadWorkflows(
tx,
newFile.id,
parentFile.project.teamId,
parentFile.projectId!,
)
})
return {
id: newFile.id,
name: newFile.name,
type: newFile.type,
size: newFile.sizeByte,
}
}
}
default:
throw ApplicationFailure.create({
message: `Unsupported tool name: ${toolName}`,
nonRetryable: true,
})
}
}
+4
View File
@@ -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',
+10
View File
@@ -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)}`
+52
View File
@@ -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
+1
View File
@@ -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'