From 39d45a1dc77d980650405c55dd2380ba553f8173 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 17:09:18 +0800 Subject: [PATCH 01/15] feat(agent): implement secure database-backed agent tools and comments context --- .../migration.sql | 2 + prisma/schema.prisma | 1 + src/agent/index.ts | 16 +- src/agent/tools/create-file.ts | 46 ++ src/agent/tools/create-folder.ts | 46 ++ src/agent/tools/create-version.ts | 47 ++ src/agent/tools/list-assets.ts | 61 +++ src/agent/tools/utils.ts | 35 ++ src/generated/prisma/enums.ts | 3 +- src/generated/prisma/internal/class.ts | 2 +- src/prisma-json-types.ts | 7 + src/workflow/activities/db.test.ts | 162 +++++++ src/workflow/activities/db.ts | 418 +++++++++++++++++- src/workflow/local-executor.ts | 4 + src/workflow/workflows/agent-chat.test.ts | 6 + src/workflow/workflows/agent-chat.ts | 10 + src/workflow/workflows/agent-tool-call.ts | 52 +++ src/workflow/workflows/index.ts | 1 + 18 files changed, 915 insertions(+), 4 deletions(-) create mode 100644 prisma/migrations/20260530090320_add_agent_tool_call/migration.sql create mode 100644 src/agent/tools/create-file.ts create mode 100644 src/agent/tools/create-folder.ts create mode 100644 src/agent/tools/create-version.ts create mode 100644 src/agent/tools/list-assets.ts create mode 100644 src/agent/tools/utils.ts create mode 100644 src/workflow/workflows/agent-tool-call.ts diff --git a/prisma/migrations/20260530090320_add_agent_tool_call/migration.sql b/prisma/migrations/20260530090320_add_agent_tool_call/migration.sql new file mode 100644 index 00000000..2ddda983 --- /dev/null +++ b/prisma/migrations/20260530090320_add_agent_tool_call/migration.sql @@ -0,0 +1,2 @@ +-- AlterEnum +ALTER TYPE "WorkflowTaskType" ADD VALUE 'agent_tool_call'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a8555bae..d27a54f3 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -104,6 +104,7 @@ enum WorkflowTaskType { chat ai_embedding query_embedding_for_search + agent_tool_call } enum WorkflowTaskStatus { diff --git a/src/agent/index.ts b/src/agent/index.ts index d480b770..7e8b20cd 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -9,6 +9,10 @@ import { DatabaseSessionStorage } from './database-session-storage' import { analyzeAssetMediaTool } from './tools/analyze-asset-media' import { createReadSkillTool } from './tools/read-skill' import { createSandboxedBashTool } from './tools/sandboxed-bash' +import { createListAssetsTool } from './tools/list-assets' +import { createCreateFolderTool } from './tools/create-folder' +import { createCreateFileTool } from './tools/create-file' +import { createCreateVersionTool } from './tools/create-version' export interface CreateAgentSessionParams { agentId: string @@ -128,6 +132,16 @@ 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, @@ -157,7 +171,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { return undefined }, - tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...customTools], + tools: [analyzeAssetMediaTool, readSkill, sandboxedBash, ...systemTools, ...customTools], }) return { session, harness } diff --git a/src/agent/tools/create-file.ts b/src/agent/tools/create-file.ts new file mode 100644 index 00000000..16723228 --- /dev/null +++ b/src/agent/tools/create-file.ts @@ -0,0 +1,46 @@ +import { Type } from '@sinclair/typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { executeAgentToolWorkflow } from './utils' + +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 { + 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 result = await executeAgentToolWorkflow({ + toolName: 'create_file', + 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 file: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + details: {}, + } + } + }, + } +} diff --git a/src/agent/tools/create-folder.ts b/src/agent/tools/create-folder.ts new file mode 100644 index 00000000..5c5bad2e --- /dev/null +++ b/src/agent/tools/create-folder.ts @@ -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 { + 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: {}, + } + } + }, + } +} diff --git a/src/agent/tools/create-version.ts b/src/agent/tools/create-version.ts new file mode 100644 index 00000000..0728e12a --- /dev/null +++ b/src/agent/tools/create-version.ts @@ -0,0 +1,47 @@ +import { Type } from '@sinclair/typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { executeAgentToolWorkflow } from './utils' + +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 { + 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 result = await executeAgentToolWorkflow({ + toolName: 'create_version', + 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 file version: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + details: {}, + } + } + }, + } +} diff --git a/src/agent/tools/list-assets.ts b/src/agent/tools/list-assets.ts new file mode 100644 index 00000000..f3564e25 --- /dev/null +++ b/src/agent/tools/list-assets.ts @@ -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 { + 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: {}, + } + } + }, + } +} diff --git a/src/agent/tools/utils.ts b/src/agent/tools/utils.ts new file mode 100644 index 00000000..a0bcff6d --- /dev/null +++ b/src/agent/tools/utils.ts @@ -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 + userId: string + assetId: string +}): Promise { + 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 | null + const errorMsg = (output?.error as string) || 'Workflow task failed' + throw new Error(errorMsg) + } + + return completedTask.output +} diff --git a/src/generated/prisma/enums.ts b/src/generated/prisma/enums.ts index 7271359f..8b73dda3 100644 --- a/src/generated/prisma/enums.ts +++ b/src/generated/prisma/enums.ts @@ -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] diff --git a/src/generated/prisma/internal/class.ts b/src/generated/prisma/internal/class.ts index 4f868077..56ab337a 100644 --- a/src/generated/prisma/internal/class.ts +++ b/src/generated/prisma/internal/class.ts @@ -22,7 +22,7 @@ const config: runtime.GetPrismaClientConfig = { "clientVersion": "7.7.0", "engineVersion": "75cbdc1eb7150937890ad5465d861175c6624711", "activeProvider": "postgresql", - "inlineSchema": "generator client {\n provider = \"prisma-client\"\n output = \"../src/generated/prisma\"\n binaryTargets = [\"native\", \"linux-musl-openssl-3.0.x\"]\n previewFeatures = [\"postgresqlExtensions\"]\n}\n\ngenerator json {\n provider = \"prisma-json-types-generator\"\n allowAny = false\n}\n\ndatasource db {\n provider = \"postgresql\"\n extensions = [vector]\n}\n\n// ----------------------------------------------------------------------\n// Enums\n// ----------------------------------------------------------------------\n\nenum UserType {\n human\n agent\n}\n\nenum AssetType {\n folder\n file\n share\n root\n attachment\n version_stack\n share_root\n symlink\n}\n\nenum AssetStatus {\n uploading\n uploaded\n processing\n processed\n trashed\n pending_purge\n}\n\nenum StorageKeyStatus {\n active\n purging\n}\n\nenum InviteRole {\n editor\n reviewer\n}\n\nenum MetadataFieldScope {\n SYSTEM\n TEAM\n PROJECT\n}\n\nenum NotificationType {\n comment_created\n reply_created\n mention\n successful_file_uploaded\n metadata_field_updated_status\n new_user_join_team\n new_user_join_project\n}\n\nenum ProjectMemberRole {\n owner\n editor\n reviewer\n}\n\nenum TaskType {\n upload\n}\n\nenum TaskStatus {\n pending\n uploading\n completed\n failed\n}\n\nenum TeamMemberRole {\n owner\n editor\n reviewer\n}\n\nenum TeamMemberScope {\n team\n project\n}\n\nenum WorkflowTaskType {\n transcode\n ai_metadata_autofill\n chat\n ai_embedding\n query_embedding_for_search\n}\n\nenum WorkflowTaskStatus {\n pending\n processing\n completed\n failed\n}\n\n// ----------------------------------------------------------------------\n// Models\n// ----------------------------------------------------------------------\n\nmodel User {\n id String @id @default(ulid())\n type UserType @default(human)\n name String\n email String @unique\n emailVerified Boolean @default(false) @map(\"email_verified\")\n image String?\n password String?\n /// [AgentSettings]\n agentSettings Json? @map(\"agent_settings\")\n guestEmail String? @map(\"guest_email\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assets Asset[] @relation(\"UserToAsset\")\n authTokens AuthToken[] @relation(\"UserToAuthToken\")\n tasks Task[] @relation(\"UserToTask\")\n teamMembers TeamMember[] @relation(\"UserToTeamMember\")\n comments AssetComment[] @relation(\"UserToAssetComment\")\n createdInvites Invite[] @relation(\"UserToInvite\")\n createdNotifications Notification[] @relation(\"UserToCreatedNotification\")\n notifications Notification[] @relation(\"UserToNotification\")\n sessions Session[]\n accounts Account[]\n agent Agent?\n agentSessions AgentSession[]\n userMetadata UserMetadata[] @relation(\"UserToUserMetadata\")\n\n @@map(\"users\")\n}\n\nmodel Session {\n id String @id @default(ulid())\n expiresAt DateTime @map(\"expires_at\")\n token String @unique\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n ipAddress String? @map(\"ip_address\")\n userAgent String? @map(\"user_agent\")\n userId String @map(\"user_id\")\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"sessions\")\n}\n\nmodel Account {\n id String @id @default(ulid())\n accountId String @map(\"account_id\")\n providerId String @map(\"provider_id\")\n userId String @map(\"user_id\")\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n accessToken String? @map(\"access_token\")\n refreshToken String? @map(\"refresh_token\")\n idToken String? @map(\"id_token\")\n accessTokenExpiresAt DateTime? @map(\"access_token_expires_at\")\n refreshTokenExpiresAt DateTime? @map(\"refresh_token_expires_at\")\n scope String?\n password String?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@map(\"accounts\")\n}\n\nmodel Verification {\n id String @id @default(ulid())\n identifier String\n value String\n expiresAt DateTime @map(\"expires_at\")\n createdAt DateTime? @default(now()) @map(\"created_at\")\n updatedAt DateTime? @updatedAt @map(\"updated_at\")\n\n @@map(\"verifications\")\n}\n\nmodel AuthToken {\n id String @id @default(ulid())\n accessToken String @unique @map(\"access_token\")\n refreshToken String @unique @map(\"refresh_token\")\n accessTokenExpiresAt DateTime @map(\"access_token_expires_at\")\n refreshTokenExpiresAt DateTime @map(\"refresh_token_expires_at\")\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToAuthToken\", fields: [userId], references: [id])\n\n @@map(\"auth_tokens\")\n}\n\nmodel Team {\n id String @id @default(ulid())\n name String\n /// [Settings]\n settings Json? @default(\"{}\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n rootFolderId String? @unique @map(\"root_folder_id\")\n rootFolder Asset? @relation(\"TeamToRootFolder\", fields: [rootFolderId], references: [id])\n\n members TeamMember[] @relation(\"TeamToTeamMember\")\n projects Project[] @relation(\"TeamToProject\")\n metadataFields MetadataField[] @relation(\"TeamToMetadataField\")\n invites Invite[] @relation(\"TeamToInvite\")\n notifications Notification[] @relation(\"TeamToNotification\")\n userMetadata UserMetadata[] @relation(\"TeamToUserMetadata\")\n providers Provider[] @relation(\"TeamToProvider\")\n skills Skill[] @relation(\"TeamToSkill\")\n sandbox Sandbox? @relation(\"TeamToSandbox\")\n agents Agent[] @relation(\"TeamToAgent\")\n\n @@map(\"teams\")\n}\n\nmodel Sandbox {\n id String @id @default(ulid())\n allowedDomains String[] @default([\"npmjs.org\", \"*.npmjs.org\", \"registry.npmjs.org\", \"registry.yarnpkg.com\", \"pypi.org\", \"*.pypi.org\", \"github.com\", \"*.github.com\", \"api.github.com\", \"raw.githubusercontent.com\"])\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @unique @map(\"team_id\")\n team Team @relation(\"TeamToSandbox\", fields: [teamId], references: [id], onDelete: Cascade)\n\n @@map(\"sandboxes\")\n}\n\nmodel Skill {\n id String @id @default(ulid())\n name String\n description String?\n /// [SkillConfig]\n config Json? @default(\"{}\")\n assetId String @map(\"asset_id\")\n hash String @map(\"hash\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToSkill\", fields: [teamId], references: [id], onDelete: Cascade)\n\n agentSkills AgentSkill[]\n\n @@unique([teamId, name])\n @@map(\"skills\")\n}\n\nmodel TeamMember {\n id String @id @default(ulid())\n role TeamMemberRole\n scope TeamMemberScope @default(team)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToTeamMember\", fields: [teamId], references: [id])\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToTeamMember\", fields: [userId], references: [id], onDelete: Cascade)\n\n projectMembers ProjectMember[] @relation(\"TeamMemberToProjectMember\")\n lastReadNotificationId String? @unique @map(\"last_read_notification_id\")\n lastReadNotification Notification? @relation(\"TeamMemberToLastReadNotification\", fields: [lastReadNotificationId], references: [id])\n\n @@unique([teamId, userId], name: \"teamIdUserId\")\n @@map(\"team_members\")\n}\n\nmodel Project {\n id String @id @default(ulid())\n name String\n coverImageKey String? @map(\"cover_image_key\")\n /// [MetadataOverrides]\n metadataOverrides Json? @map(\"metadata_overrides\")\n enableNotification Boolean @default(true) @map(\"enable_notification\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToProject\", fields: [teamId], references: [id])\n\n rootFolderId String? @unique @map(\"root_folder_id\")\n rootFolder Asset? @relation(\"ProjectToRootFolder\", fields: [rootFolderId], references: [id])\n\n shareRootId String? @unique @map(\"share_root_id\")\n shareRoot Asset? @relation(\"ProjectToShareRoot\", fields: [shareRootId], references: [id])\n\n members ProjectMember[] @relation(\"ProjectToProjectMember\")\n assets Asset[] @relation(\"ProjectToAsset\")\n metadataFields MetadataField[] @relation(\"ProjectToMetadataField\")\n invites Invite[] @relation(\"ProjectToInvite\")\n notifications Notification[] @relation(\"ProjectToNotification\")\n shareLinks ShareLink[] @relation(\"ProjectToShareLink\")\n collections Collection[] @relation(\"ProjectToCollection\")\n\n @@index([createdAt])\n @@index([updatedAt])\n @@map(\"projects\")\n}\n\nmodel ProjectMember {\n id String @id @default(ulid())\n role ProjectMemberRole\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToProjectMember\", fields: [projectId], references: [id], onDelete: Cascade)\n\n teamMemberId String @map(\"team_member_id\")\n teamMember TeamMember @relation(\"TeamMemberToProjectMember\", fields: [teamMemberId], references: [id])\n\n @@unique([projectId, teamMemberId], name: \"projectIdTeamMemberId\")\n @@map(\"project_members\")\n}\n\nmodel ShareLink {\n id String @id @default(ulid())\n name String\n expireAt DateTime? @map(\"expire_at\")\n password String?\n isDisabled Boolean @default(false) @map(\"is_disabled\")\n defaultSortOrder String? @map(\"default_sort_order\")\n /// [ShareLinkFieldVisibility]\n fieldVisibility Json? @map(\"field_visibility\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToShareLink\", fields: [projectId], references: [id], onDelete: Cascade)\n\n rootFolderId String @unique @map(\"root_folder_id\")\n rootFolder Asset @relation(\"ShareLinkToRootFolder\", fields: [rootFolderId], references: [id])\n\n @@map(\"share_links\")\n}\n\nmodel Asset {\n id String @id @default(ulid())\n name String @default(\"\")\n nameNgram String[] @default([]) @map(\"name_ngram\")\n type AssetType\n mediaType String? @map(\"media_type\")\n fileCount Int @default(0) @map(\"file_count\")\n sizeByte Int @default(0) @map(\"size_byte\")\n status AssetStatus\n transcodeTaskId String? @map(\"transcode_task_id\")\n /// [MediaInfo]\n media Json?\n isDeleted Boolean @default(false) @map(\"is_deleted\")\n deletedAt DateTime? @map(\"deleted_at\")\n sortIndex String? @map(\"sort_index\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n parentId String? @map(\"parent_id\")\n parent Asset? @relation(\"AssetChildren\", fields: [parentId], references: [id])\n children Asset[] @relation(\"AssetChildren\")\n\n targetId String? @map(\"target_id\")\n target Asset? @relation(\"SymlinkTarget\", fields: [targetId], references: [id])\n symlinks Asset[] @relation(\"SymlinkTarget\")\n\n storageKeyId String? @map(\"storage_key_id\")\n storageKey StorageKey? @relation(fields: [storageKeyId], references: [id])\n\n metadataValues AssetMetadataValue[] @relation(\"AssetToMetadataValues\")\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToAsset\", fields: [creatorId], references: [id])\n\n taskId String? @map(\"task_id\")\n task Task? @relation(\"TaskToAsset\", fields: [taskId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToAsset\", fields: [projectId], references: [id])\n\n comments AssetComment[] @relation(\"AssetToComment\")\n commentAttachments AssetCommentAttachment[] @relation(\"AssetToCommentAttachment\")\n notifications Notification[] @relation(\"AssetToNotification\")\n embeddings AssetEmbedding[] @relation(\"AssetToEmbedding\")\n\n teamRootFolder Team? @relation(\"TeamToRootFolder\")\n projectRootFolder Project? @relation(\"ProjectToRootFolder\")\n projectShareRoot Project? @relation(\"ProjectToShareRoot\")\n shareLinkRootFolder ShareLink? @relation(\"ShareLinkToRootFolder\")\n\n @@unique([parentId, targetId], name: \"parentIdTargetId\")\n @@index([type])\n @@index([status])\n @@index([createdAt])\n @@index([updatedAt])\n @@index([sortIndex])\n @@index([isDeleted])\n @@index([deletedAt])\n @@index([name], name: \"assets_name_idx\")\n @@index([nameNgram], type: Gin)\n @@map(\"assets\")\n}\n\nmodel StorageKey {\n id String @id @default(ulid())\n key String @unique\n status StorageKeyStatus @default(active)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n assets Asset[]\n\n @@map(\"storage_keys\")\n}\n\nmodel AssetMetadataValue {\n id String @id @default(ulid())\n assetId String @map(\"asset_id\")\n fieldKey String @map(\"field_key\") // key from MetadataField\n\n stringValue String? @map(\"string_value\")\n numberValue Float? @map(\"number_value\")\n booleanValue Boolean? @map(\"boolean_value\")\n jsonValue Json? @map(\"json_value\")\n dateValue DateTime? @map(\"date_value\")\n\n asset Asset @relation(\"AssetToMetadataValues\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@unique([assetId, fieldKey])\n @@index([numberValue])\n @@index([stringValue])\n @@index([booleanValue])\n @@index([dateValue])\n @@index([jsonValue], type: Gin)\n @@map(\"asset_metadata_values\")\n}\n\nmodel AssetComment {\n id String @id @default(ulid())\n message String?\n /// [AnnotationList]\n annotation Json?\n second Float?\n sessionId String? @map(\"session_id\")\n session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToComment\", fields: [assetId], references: [id], onDelete: Cascade)\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToAssetComment\", fields: [creatorId], references: [id])\n\n replyToId String? @map(\"reply_to_id\")\n replyTo AssetComment? @relation(\"CommentReplies\", fields: [replyToId], references: [id], onDelete: Cascade)\n replies AssetComment[] @relation(\"CommentReplies\")\n\n attachments AssetCommentAttachment[] @relation(\"CommentToAttachment\")\n\n @@map(\"asset_comments\")\n}\n\nmodel AssetCommentAttachment {\n id String @id @default(ulid())\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n commentId String @map(\"comment_id\")\n comment AssetComment @relation(\"CommentToAttachment\", fields: [commentId], references: [id], onDelete: Cascade)\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToCommentAttachment\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@map(\"asset_comment_attachments\")\n}\n\nmodel AssetEmbedding {\n id String @id @default(ulid())\n embedding Unsupported(\"vector(1536)\")?\n startTime Float? @map(\"start_time\")\n endTime Float? @map(\"end_time\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToEmbedding\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@index([embedding], name: \"AssetEmbedding_embedding_idx\")\n @@map(\"asset_embeddings\")\n}\n\nmodel Invite {\n id String @id @default(ulid())\n code String @unique\n role InviteRole?\n used Boolean @default(false)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToInvite\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToInvite\", fields: [projectId], references: [id], onDelete: Cascade)\n\n inviterId String @map(\"inviter_id\")\n inviter User @relation(\"UserToInvite\", fields: [inviterId], references: [id])\n\n @@map(\"invites\")\n}\n\nmodel MetadataField {\n id String @id @default(ulid())\n key String @unique\n scope MetadataFieldScope?\n /// [FieldConfig]\n config Json?\n readOnly Boolean @default(false) @map(\"read_only\")\n aiAutofill Boolean @default(false) @map(\"ai_autofill\")\n description String @default(\"\")\n\n teamId String? @map(\"team_id\")\n team Team? @relation(\"TeamToMetadataField\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToMetadataField\", fields: [projectId], references: [id], onDelete: Cascade)\n\n @@map(\"metadata_fields\")\n}\n\nmodel Notification {\n id String @id @default(ulid())\n type NotificationType?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToNotification\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToNotification\", fields: [projectId], references: [id], onDelete: Cascade)\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToCreatedNotification\", fields: [creatorId], references: [id])\n\n assetId String? @map(\"asset_id\")\n asset Asset? @relation(\"AssetToNotification\", fields: [assetId], references: [id], onDelete: Cascade)\n\n taskId String? @map(\"task_id\")\n task Task? @relation(\"TaskToNotification\", fields: [taskId], references: [id])\n\n userId String? @map(\"user_id\")\n user User? @relation(\"UserToNotification\", fields: [userId], references: [id])\n\n readByMembers TeamMember? @relation(\"TeamMemberToLastReadNotification\")\n\n @@map(\"notifications\")\n}\n\nmodel SystemSettings {\n id String @id @default(ulid())\n key String @unique\n /// [SystemSettingsValue]\n value Json?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@index([key])\n @@map(\"system_settings\")\n}\n\nmodel Task {\n id String @id @default(ulid())\n type TaskType?\n status TaskStatus @default(pending)\n name String?\n total Int?\n uploaded Int @default(0)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToTask\", fields: [creatorId], references: [id])\n\n assets Asset[] @relation(\"TaskToAsset\")\n notifications Notification[] @relation(\"TaskToNotification\")\n\n @@map(\"tasks\")\n}\n\nmodel WorkflowTask {\n id String @id @default(ulid())\n uid String @default(uuid()) @db.Uuid\n teamId String? @map(\"team_id\")\n projectId String? @map(\"project_id\")\n assetId String @map(\"asset_id\")\n type WorkflowTaskType?\n status WorkflowTaskStatus?\n /// [WorkflowTaskPayload]\n payload Json?\n /// [WorkflowTaskOutput]\n output Json?\n heartbeat DateTime?\n inputTokens Int @default(0) @map(\"input_tokens\")\n outputTokens Int @default(0) @map(\"output_tokens\")\n model String?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@index([status, heartbeat])\n @@index([assetId, type])\n @@index([teamId])\n @@index([projectId])\n @@index([type])\n @@map(\"workflow_tasks\")\n}\n\nenum AgentType {\n chat\n autofill\n embedding\n}\n\nmodel Agent {\n id String @id\n user User @relation(fields: [id], references: [id], onDelete: Cascade)\n type AgentType\n enabled Boolean @default(true)\n soul String? @db.Text\n providerId String? @map(\"provider_id\")\n provider Provider? @relation(\"ProviderToAgent\", fields: [providerId], references: [id], onDelete: SetNull)\n modelId String? @map(\"model_id\")\n modelRef Model? @relation(\"ModelToAgent\", fields: [modelId], references: [id], onDelete: SetNull)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToAgent\", fields: [teamId], references: [id], onDelete: Cascade)\n\n /// [AgentConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n agentSessions AgentSession[]\n skills AgentSkill[]\n\n @@map(\"agents\")\n}\n\nmodel AgentSkill {\n id String @id @default(ulid())\n agentId String @map(\"agent_id\")\n agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)\n skillId String @map(\"skill_id\")\n skill Skill @relation(fields: [skillId], references: [id], onDelete: Cascade)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@unique([agentId, skillId])\n @@map(\"agent_skills\")\n}\n\nmodel AgentSession {\n id String @id @default(ulid())\n agentId String @map(\"agent_id\")\n agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)\n userId String? @map(\"user_id\")\n user User? @relation(fields: [userId], references: [id], onDelete: SetNull)\n cwd String\n leafId String? @map(\"leaf_id\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n entries AgentSessionEntry[]\n comments AssetComment[]\n\n @@map(\"agent_sessions\")\n}\n\nmodel AgentSessionEntry {\n id String @id // Uses ULID generated by pi-coding-agent\n sessionId String @map(\"session_id\")\n session AgentSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)\n /// [PiSessionEntry]\n entry Json\n\n @@index([sessionId])\n @@map(\"agent_session_entries\")\n}\n\nmodel UserMetadata {\n id String @id @default(ulid())\n key String\n /// [UserMetadataValue]\n value Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToUserMetadata\", fields: [userId], references: [id], onDelete: Cascade)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToUserMetadata\", fields: [teamId], references: [id], onDelete: Cascade)\n\n @@unique([userId, teamId, key], name: \"userIdTeamIdKey\")\n @@map(\"user_metadata\")\n}\n\nmodel Model {\n id String @id @default(ulid())\n modelId String @map(\"model_id\")\n name String @default(\"\")\n /// [ModelConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n providerId String @map(\"provider_id\")\n provider Provider @relation(\"ProviderToModel\", fields: [providerId], references: [id], onDelete: Cascade)\n\n agents Agent[] @relation(\"ModelToAgent\")\n\n @@unique([providerId, modelId])\n @@map(\"models\")\n}\n\nmodel Provider {\n id String @id @default(ulid())\n name String\n isBuiltin Boolean @default(false) @map(\"is_builtin\")\n /// [ProviderConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToProvider\", fields: [teamId], references: [id], onDelete: Cascade)\n\n models Model[] @relation(\"ProviderToModel\")\n agents Agent[] @relation(\"ProviderToAgent\")\n\n @@unique([teamId, name])\n @@map(\"providers\")\n}\n\nmodel Collection {\n id String @id @default(ulid())\n name String\n /// [CollectionFilter]\n filter Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToCollection\", fields: [projectId], references: [id], onDelete: Cascade)\n\n @@index([projectId, createdAt(sort: Desc)])\n @@map(\"collections\")\n}\n", + "inlineSchema": "generator client {\n provider = \"prisma-client\"\n output = \"../src/generated/prisma\"\n binaryTargets = [\"native\", \"linux-musl-openssl-3.0.x\"]\n previewFeatures = [\"postgresqlExtensions\"]\n}\n\ngenerator json {\n provider = \"prisma-json-types-generator\"\n allowAny = false\n}\n\ndatasource db {\n provider = \"postgresql\"\n extensions = [vector]\n}\n\n// ----------------------------------------------------------------------\n// Enums\n// ----------------------------------------------------------------------\n\nenum UserType {\n human\n agent\n}\n\nenum AssetType {\n folder\n file\n share\n root\n attachment\n version_stack\n share_root\n symlink\n}\n\nenum AssetStatus {\n uploading\n uploaded\n processing\n processed\n trashed\n pending_purge\n}\n\nenum StorageKeyStatus {\n active\n purging\n}\n\nenum InviteRole {\n editor\n reviewer\n}\n\nenum MetadataFieldScope {\n SYSTEM\n TEAM\n PROJECT\n}\n\nenum NotificationType {\n comment_created\n reply_created\n mention\n successful_file_uploaded\n metadata_field_updated_status\n new_user_join_team\n new_user_join_project\n}\n\nenum ProjectMemberRole {\n owner\n editor\n reviewer\n}\n\nenum TaskType {\n upload\n}\n\nenum TaskStatus {\n pending\n uploading\n completed\n failed\n}\n\nenum TeamMemberRole {\n owner\n editor\n reviewer\n}\n\nenum TeamMemberScope {\n team\n project\n}\n\nenum WorkflowTaskType {\n transcode\n ai_metadata_autofill\n chat\n ai_embedding\n query_embedding_for_search\n agent_tool_call\n}\n\nenum WorkflowTaskStatus {\n pending\n processing\n completed\n failed\n}\n\n// ----------------------------------------------------------------------\n// Models\n// ----------------------------------------------------------------------\n\nmodel User {\n id String @id @default(ulid())\n type UserType @default(human)\n name String\n email String @unique\n emailVerified Boolean @default(false) @map(\"email_verified\")\n image String?\n password String?\n /// [AgentSettings]\n agentSettings Json? @map(\"agent_settings\")\n guestEmail String? @map(\"guest_email\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assets Asset[] @relation(\"UserToAsset\")\n authTokens AuthToken[] @relation(\"UserToAuthToken\")\n tasks Task[] @relation(\"UserToTask\")\n teamMembers TeamMember[] @relation(\"UserToTeamMember\")\n comments AssetComment[] @relation(\"UserToAssetComment\")\n createdInvites Invite[] @relation(\"UserToInvite\")\n createdNotifications Notification[] @relation(\"UserToCreatedNotification\")\n notifications Notification[] @relation(\"UserToNotification\")\n sessions Session[]\n accounts Account[]\n agent Agent?\n agentSessions AgentSession[]\n userMetadata UserMetadata[] @relation(\"UserToUserMetadata\")\n\n @@map(\"users\")\n}\n\nmodel Session {\n id String @id @default(ulid())\n expiresAt DateTime @map(\"expires_at\")\n token String @unique\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n ipAddress String? @map(\"ip_address\")\n userAgent String? @map(\"user_agent\")\n userId String @map(\"user_id\")\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"sessions\")\n}\n\nmodel Account {\n id String @id @default(ulid())\n accountId String @map(\"account_id\")\n providerId String @map(\"provider_id\")\n userId String @map(\"user_id\")\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n accessToken String? @map(\"access_token\")\n refreshToken String? @map(\"refresh_token\")\n idToken String? @map(\"id_token\")\n accessTokenExpiresAt DateTime? @map(\"access_token_expires_at\")\n refreshTokenExpiresAt DateTime? @map(\"refresh_token_expires_at\")\n scope String?\n password String?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@map(\"accounts\")\n}\n\nmodel Verification {\n id String @id @default(ulid())\n identifier String\n value String\n expiresAt DateTime @map(\"expires_at\")\n createdAt DateTime? @default(now()) @map(\"created_at\")\n updatedAt DateTime? @updatedAt @map(\"updated_at\")\n\n @@map(\"verifications\")\n}\n\nmodel AuthToken {\n id String @id @default(ulid())\n accessToken String @unique @map(\"access_token\")\n refreshToken String @unique @map(\"refresh_token\")\n accessTokenExpiresAt DateTime @map(\"access_token_expires_at\")\n refreshTokenExpiresAt DateTime @map(\"refresh_token_expires_at\")\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToAuthToken\", fields: [userId], references: [id])\n\n @@map(\"auth_tokens\")\n}\n\nmodel Team {\n id String @id @default(ulid())\n name String\n /// [Settings]\n settings Json? @default(\"{}\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n rootFolderId String? @unique @map(\"root_folder_id\")\n rootFolder Asset? @relation(\"TeamToRootFolder\", fields: [rootFolderId], references: [id])\n\n members TeamMember[] @relation(\"TeamToTeamMember\")\n projects Project[] @relation(\"TeamToProject\")\n metadataFields MetadataField[] @relation(\"TeamToMetadataField\")\n invites Invite[] @relation(\"TeamToInvite\")\n notifications Notification[] @relation(\"TeamToNotification\")\n userMetadata UserMetadata[] @relation(\"TeamToUserMetadata\")\n providers Provider[] @relation(\"TeamToProvider\")\n skills Skill[] @relation(\"TeamToSkill\")\n sandbox Sandbox? @relation(\"TeamToSandbox\")\n agents Agent[] @relation(\"TeamToAgent\")\n\n @@map(\"teams\")\n}\n\nmodel Sandbox {\n id String @id @default(ulid())\n allowedDomains String[] @default([\"npmjs.org\", \"*.npmjs.org\", \"registry.npmjs.org\", \"registry.yarnpkg.com\", \"pypi.org\", \"*.pypi.org\", \"github.com\", \"*.github.com\", \"api.github.com\", \"raw.githubusercontent.com\"])\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @unique @map(\"team_id\")\n team Team @relation(\"TeamToSandbox\", fields: [teamId], references: [id], onDelete: Cascade)\n\n @@map(\"sandboxes\")\n}\n\nmodel Skill {\n id String @id @default(ulid())\n name String\n description String?\n /// [SkillConfig]\n config Json? @default(\"{}\")\n assetId String @map(\"asset_id\")\n hash String @map(\"hash\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToSkill\", fields: [teamId], references: [id], onDelete: Cascade)\n\n agentSkills AgentSkill[]\n\n @@unique([teamId, name])\n @@map(\"skills\")\n}\n\nmodel TeamMember {\n id String @id @default(ulid())\n role TeamMemberRole\n scope TeamMemberScope @default(team)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToTeamMember\", fields: [teamId], references: [id])\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToTeamMember\", fields: [userId], references: [id], onDelete: Cascade)\n\n projectMembers ProjectMember[] @relation(\"TeamMemberToProjectMember\")\n lastReadNotificationId String? @unique @map(\"last_read_notification_id\")\n lastReadNotification Notification? @relation(\"TeamMemberToLastReadNotification\", fields: [lastReadNotificationId], references: [id])\n\n @@unique([teamId, userId], name: \"teamIdUserId\")\n @@map(\"team_members\")\n}\n\nmodel Project {\n id String @id @default(ulid())\n name String\n coverImageKey String? @map(\"cover_image_key\")\n /// [MetadataOverrides]\n metadataOverrides Json? @map(\"metadata_overrides\")\n enableNotification Boolean @default(true) @map(\"enable_notification\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToProject\", fields: [teamId], references: [id])\n\n rootFolderId String? @unique @map(\"root_folder_id\")\n rootFolder Asset? @relation(\"ProjectToRootFolder\", fields: [rootFolderId], references: [id])\n\n shareRootId String? @unique @map(\"share_root_id\")\n shareRoot Asset? @relation(\"ProjectToShareRoot\", fields: [shareRootId], references: [id])\n\n members ProjectMember[] @relation(\"ProjectToProjectMember\")\n assets Asset[] @relation(\"ProjectToAsset\")\n metadataFields MetadataField[] @relation(\"ProjectToMetadataField\")\n invites Invite[] @relation(\"ProjectToInvite\")\n notifications Notification[] @relation(\"ProjectToNotification\")\n shareLinks ShareLink[] @relation(\"ProjectToShareLink\")\n collections Collection[] @relation(\"ProjectToCollection\")\n\n @@index([createdAt])\n @@index([updatedAt])\n @@map(\"projects\")\n}\n\nmodel ProjectMember {\n id String @id @default(ulid())\n role ProjectMemberRole\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToProjectMember\", fields: [projectId], references: [id], onDelete: Cascade)\n\n teamMemberId String @map(\"team_member_id\")\n teamMember TeamMember @relation(\"TeamMemberToProjectMember\", fields: [teamMemberId], references: [id])\n\n @@unique([projectId, teamMemberId], name: \"projectIdTeamMemberId\")\n @@map(\"project_members\")\n}\n\nmodel ShareLink {\n id String @id @default(ulid())\n name String\n expireAt DateTime? @map(\"expire_at\")\n password String?\n isDisabled Boolean @default(false) @map(\"is_disabled\")\n defaultSortOrder String? @map(\"default_sort_order\")\n /// [ShareLinkFieldVisibility]\n fieldVisibility Json? @map(\"field_visibility\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToShareLink\", fields: [projectId], references: [id], onDelete: Cascade)\n\n rootFolderId String @unique @map(\"root_folder_id\")\n rootFolder Asset @relation(\"ShareLinkToRootFolder\", fields: [rootFolderId], references: [id])\n\n @@map(\"share_links\")\n}\n\nmodel Asset {\n id String @id @default(ulid())\n name String @default(\"\")\n nameNgram String[] @default([]) @map(\"name_ngram\")\n type AssetType\n mediaType String? @map(\"media_type\")\n fileCount Int @default(0) @map(\"file_count\")\n sizeByte Int @default(0) @map(\"size_byte\")\n status AssetStatus\n transcodeTaskId String? @map(\"transcode_task_id\")\n /// [MediaInfo]\n media Json?\n isDeleted Boolean @default(false) @map(\"is_deleted\")\n deletedAt DateTime? @map(\"deleted_at\")\n sortIndex String? @map(\"sort_index\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n parentId String? @map(\"parent_id\")\n parent Asset? @relation(\"AssetChildren\", fields: [parentId], references: [id])\n children Asset[] @relation(\"AssetChildren\")\n\n targetId String? @map(\"target_id\")\n target Asset? @relation(\"SymlinkTarget\", fields: [targetId], references: [id])\n symlinks Asset[] @relation(\"SymlinkTarget\")\n\n storageKeyId String? @map(\"storage_key_id\")\n storageKey StorageKey? @relation(fields: [storageKeyId], references: [id])\n\n metadataValues AssetMetadataValue[] @relation(\"AssetToMetadataValues\")\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToAsset\", fields: [creatorId], references: [id])\n\n taskId String? @map(\"task_id\")\n task Task? @relation(\"TaskToAsset\", fields: [taskId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToAsset\", fields: [projectId], references: [id])\n\n comments AssetComment[] @relation(\"AssetToComment\")\n commentAttachments AssetCommentAttachment[] @relation(\"AssetToCommentAttachment\")\n notifications Notification[] @relation(\"AssetToNotification\")\n embeddings AssetEmbedding[] @relation(\"AssetToEmbedding\")\n\n teamRootFolder Team? @relation(\"TeamToRootFolder\")\n projectRootFolder Project? @relation(\"ProjectToRootFolder\")\n projectShareRoot Project? @relation(\"ProjectToShareRoot\")\n shareLinkRootFolder ShareLink? @relation(\"ShareLinkToRootFolder\")\n\n @@unique([parentId, targetId], name: \"parentIdTargetId\")\n @@index([type])\n @@index([status])\n @@index([createdAt])\n @@index([updatedAt])\n @@index([sortIndex])\n @@index([isDeleted])\n @@index([deletedAt])\n @@index([name], name: \"assets_name_idx\")\n @@index([nameNgram], type: Gin)\n @@map(\"assets\")\n}\n\nmodel StorageKey {\n id String @id @default(ulid())\n key String @unique\n status StorageKeyStatus @default(active)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n assets Asset[]\n\n @@map(\"storage_keys\")\n}\n\nmodel AssetMetadataValue {\n id String @id @default(ulid())\n assetId String @map(\"asset_id\")\n fieldKey String @map(\"field_key\") // key from MetadataField\n\n stringValue String? @map(\"string_value\")\n numberValue Float? @map(\"number_value\")\n booleanValue Boolean? @map(\"boolean_value\")\n jsonValue Json? @map(\"json_value\")\n dateValue DateTime? @map(\"date_value\")\n\n asset Asset @relation(\"AssetToMetadataValues\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@unique([assetId, fieldKey])\n @@index([numberValue])\n @@index([stringValue])\n @@index([booleanValue])\n @@index([dateValue])\n @@index([jsonValue], type: Gin)\n @@map(\"asset_metadata_values\")\n}\n\nmodel AssetComment {\n id String @id @default(ulid())\n message String?\n /// [AnnotationList]\n annotation Json?\n second Float?\n sessionId String? @map(\"session_id\")\n session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToComment\", fields: [assetId], references: [id], onDelete: Cascade)\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToAssetComment\", fields: [creatorId], references: [id])\n\n replyToId String? @map(\"reply_to_id\")\n replyTo AssetComment? @relation(\"CommentReplies\", fields: [replyToId], references: [id], onDelete: Cascade)\n replies AssetComment[] @relation(\"CommentReplies\")\n\n attachments AssetCommentAttachment[] @relation(\"CommentToAttachment\")\n\n @@map(\"asset_comments\")\n}\n\nmodel AssetCommentAttachment {\n id String @id @default(ulid())\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n commentId String @map(\"comment_id\")\n comment AssetComment @relation(\"CommentToAttachment\", fields: [commentId], references: [id], onDelete: Cascade)\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToCommentAttachment\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@map(\"asset_comment_attachments\")\n}\n\nmodel AssetEmbedding {\n id String @id @default(ulid())\n embedding Unsupported(\"vector(1536)\")?\n startTime Float? @map(\"start_time\")\n endTime Float? @map(\"end_time\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n assetId String @map(\"asset_id\")\n asset Asset @relation(\"AssetToEmbedding\", fields: [assetId], references: [id], onDelete: Cascade)\n\n @@index([embedding], name: \"AssetEmbedding_embedding_idx\")\n @@map(\"asset_embeddings\")\n}\n\nmodel Invite {\n id String @id @default(ulid())\n code String @unique\n role InviteRole?\n used Boolean @default(false)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToInvite\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToInvite\", fields: [projectId], references: [id], onDelete: Cascade)\n\n inviterId String @map(\"inviter_id\")\n inviter User @relation(\"UserToInvite\", fields: [inviterId], references: [id])\n\n @@map(\"invites\")\n}\n\nmodel MetadataField {\n id String @id @default(ulid())\n key String @unique\n scope MetadataFieldScope?\n /// [FieldConfig]\n config Json?\n readOnly Boolean @default(false) @map(\"read_only\")\n aiAutofill Boolean @default(false) @map(\"ai_autofill\")\n description String @default(\"\")\n\n teamId String? @map(\"team_id\")\n team Team? @relation(\"TeamToMetadataField\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToMetadataField\", fields: [projectId], references: [id], onDelete: Cascade)\n\n @@map(\"metadata_fields\")\n}\n\nmodel Notification {\n id String @id @default(ulid())\n type NotificationType?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToNotification\", fields: [teamId], references: [id])\n\n projectId String? @map(\"project_id\")\n project Project? @relation(\"ProjectToNotification\", fields: [projectId], references: [id], onDelete: Cascade)\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToCreatedNotification\", fields: [creatorId], references: [id])\n\n assetId String? @map(\"asset_id\")\n asset Asset? @relation(\"AssetToNotification\", fields: [assetId], references: [id], onDelete: Cascade)\n\n taskId String? @map(\"task_id\")\n task Task? @relation(\"TaskToNotification\", fields: [taskId], references: [id])\n\n userId String? @map(\"user_id\")\n user User? @relation(\"UserToNotification\", fields: [userId], references: [id])\n\n readByMembers TeamMember? @relation(\"TeamMemberToLastReadNotification\")\n\n @@map(\"notifications\")\n}\n\nmodel SystemSettings {\n id String @id @default(ulid())\n key String @unique\n /// [SystemSettingsValue]\n value Json?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@index([key])\n @@map(\"system_settings\")\n}\n\nmodel Task {\n id String @id @default(ulid())\n type TaskType?\n status TaskStatus @default(pending)\n name String?\n total Int?\n uploaded Int @default(0)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n creatorId String? @map(\"creator_id\")\n creator User? @relation(\"UserToTask\", fields: [creatorId], references: [id])\n\n assets Asset[] @relation(\"TaskToAsset\")\n notifications Notification[] @relation(\"TaskToNotification\")\n\n @@map(\"tasks\")\n}\n\nmodel WorkflowTask {\n id String @id @default(ulid())\n uid String @default(uuid()) @db.Uuid\n teamId String? @map(\"team_id\")\n projectId String? @map(\"project_id\")\n assetId String @map(\"asset_id\")\n type WorkflowTaskType?\n status WorkflowTaskStatus?\n /// [WorkflowTaskPayload]\n payload Json?\n /// [WorkflowTaskOutput]\n output Json?\n heartbeat DateTime?\n inputTokens Int @default(0) @map(\"input_tokens\")\n outputTokens Int @default(0) @map(\"output_tokens\")\n model String?\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@index([status, heartbeat])\n @@index([assetId, type])\n @@index([teamId])\n @@index([projectId])\n @@index([type])\n @@map(\"workflow_tasks\")\n}\n\nenum AgentType {\n chat\n autofill\n embedding\n}\n\nmodel Agent {\n id String @id\n user User @relation(fields: [id], references: [id], onDelete: Cascade)\n type AgentType\n enabled Boolean @default(true)\n soul String? @db.Text\n providerId String? @map(\"provider_id\")\n provider Provider? @relation(\"ProviderToAgent\", fields: [providerId], references: [id], onDelete: SetNull)\n modelId String? @map(\"model_id\")\n modelRef Model? @relation(\"ModelToAgent\", fields: [modelId], references: [id], onDelete: SetNull)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToAgent\", fields: [teamId], references: [id], onDelete: Cascade)\n\n /// [AgentConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n agentSessions AgentSession[]\n skills AgentSkill[]\n\n @@map(\"agents\")\n}\n\nmodel AgentSkill {\n id String @id @default(ulid())\n agentId String @map(\"agent_id\")\n agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)\n skillId String @map(\"skill_id\")\n skill Skill @relation(fields: [skillId], references: [id], onDelete: Cascade)\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n @@unique([agentId, skillId])\n @@map(\"agent_skills\")\n}\n\nmodel AgentSession {\n id String @id @default(ulid())\n agentId String @map(\"agent_id\")\n agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)\n userId String? @map(\"user_id\")\n user User? @relation(fields: [userId], references: [id], onDelete: SetNull)\n cwd String\n leafId String? @map(\"leaf_id\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n entries AgentSessionEntry[]\n comments AssetComment[]\n\n @@map(\"agent_sessions\")\n}\n\nmodel AgentSessionEntry {\n id String @id // Uses ULID generated by pi-coding-agent\n sessionId String @map(\"session_id\")\n session AgentSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)\n /// [PiSessionEntry]\n entry Json\n\n @@index([sessionId])\n @@map(\"agent_session_entries\")\n}\n\nmodel UserMetadata {\n id String @id @default(ulid())\n key String\n /// [UserMetadataValue]\n value Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n userId String @map(\"user_id\")\n user User @relation(\"UserToUserMetadata\", fields: [userId], references: [id], onDelete: Cascade)\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToUserMetadata\", fields: [teamId], references: [id], onDelete: Cascade)\n\n @@unique([userId, teamId, key], name: \"userIdTeamIdKey\")\n @@map(\"user_metadata\")\n}\n\nmodel Model {\n id String @id @default(ulid())\n modelId String @map(\"model_id\")\n name String @default(\"\")\n /// [ModelConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n providerId String @map(\"provider_id\")\n provider Provider @relation(\"ProviderToModel\", fields: [providerId], references: [id], onDelete: Cascade)\n\n agents Agent[] @relation(\"ModelToAgent\")\n\n @@unique([providerId, modelId])\n @@map(\"models\")\n}\n\nmodel Provider {\n id String @id @default(ulid())\n name String\n isBuiltin Boolean @default(false) @map(\"is_builtin\")\n /// [ProviderConfig]\n config Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n teamId String @map(\"team_id\")\n team Team @relation(\"TeamToProvider\", fields: [teamId], references: [id], onDelete: Cascade)\n\n models Model[] @relation(\"ProviderToModel\")\n agents Agent[] @relation(\"ProviderToAgent\")\n\n @@unique([teamId, name])\n @@map(\"providers\")\n}\n\nmodel Collection {\n id String @id @default(ulid())\n name String\n /// [CollectionFilter]\n filter Json\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n projectId String @map(\"project_id\")\n project Project @relation(\"ProjectToCollection\", fields: [projectId], references: [id], onDelete: Cascade)\n\n @@index([projectId, createdAt(sort: Desc)])\n @@map(\"collections\")\n}\n", "runtimeDataModel": { "models": {}, "enums": {}, diff --git a/src/prisma-json-types.ts b/src/prisma-json-types.ts index 957d4b9b..f2367ced 100644 --- a/src/prisma-json-types.ts +++ b/src/prisma-json-types.ts @@ -245,11 +245,18 @@ declare global { queryEmbeddingForSearch?: { text: string } + agentToolCall?: AgentToolCallPayload } // ---------------------------------------------------------------------- // Task Spec & Payload // ---------------------------------------------------------------------- + export interface AgentToolCallPayload { + toolName: string + args: Record + userId: string + } + export interface TaskSpec { videoStrategy?: VideoTranscodeStrategy thumbnail?: boolean diff --git a/src/workflow/activities/db.test.ts b/src/workflow/activities/db.test.ts index 75e7f4fb..879124c4 100644 --- a/src/workflow/activities/db.test.ts +++ b/src/workflow/activities/db.test.ts @@ -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) + } + } + }) + }) }) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 0fa9a41c..142d4e11 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -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 = { + '.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 { + 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 { + 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> + >( + 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, + }) + } +} diff --git a/src/workflow/local-executor.ts b/src/workflow/local-executor.ts index d6c4f264..675c596a 100644 --- a/src/workflow/local-executor.ts +++ b/src/workflow/local-executor.ts @@ -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}`) } diff --git a/src/workflow/workflows/agent-chat.test.ts b/src/workflow/workflows/agent-chat.test.ts index 5c64a1e1..4106c8b1 100644 --- a/src/workflow/workflows/agent-chat.test.ts +++ b/src/workflow/workflows/agent-chat.test.ts @@ -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', diff --git a/src/workflow/workflows/agent-chat.ts b/src/workflow/workflows/agent-chat.ts index 5e5cc8c7..38ccd744 100644 --- a/src/workflow/workflows/agent-chat.ts +++ b/src/workflow/workflows/agent-chat.ts @@ -20,6 +20,7 @@ export async function agentChat(task: WorkflowTask): Promise { getAgentWorkerQueueActivity, deleteCommentActivity, initializeAgentSessionActivity, + getAssetPathContextActivity, } = getActivities() let placeholderCommentId: string | undefined @@ -99,7 +100,16 @@ export async function agentChat(task: WorkflowTask): Promise { } } + 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)}` diff --git a/src/workflow/workflows/agent-tool-call.ts b/src/workflow/workflows/agent-tool-call.ts new file mode 100644 index 00000000..89cc7c24 --- /dev/null +++ b/src/workflow/workflows/agent-tool-call.ts @@ -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 { + 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 diff --git a/src/workflow/workflows/index.ts b/src/workflow/workflows/index.ts index 8af4e7e1..691bdf18 100644 --- a/src/workflow/workflows/index.ts +++ b/src/workflow/workflows/index.ts @@ -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' From 64bdccaa8adb452090c1b75bb7b113d305865845 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 17:24:35 +0800 Subject: [PATCH 02/15] fix(ui): resolve comments and fields sidebar overflow and restore scrolling --- src/ui/components/file-viewer-right-sidebar.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/components/file-viewer-right-sidebar.tsx b/src/ui/components/file-viewer-right-sidebar.tsx index e94535de..33b5476a 100644 --- a/src/ui/components/file-viewer-right-sidebar.tsx +++ b/src/ui/components/file-viewer-right-sidebar.tsx @@ -341,7 +341,7 @@ export function FileViewerRightSidebar({ - +
{comments.map((comment) => (
@@ -419,7 +419,7 @@ export function FileViewerRightSidebar({ )} - + {sortedFields && sortedFields.length > 0 && (
{sortedFields.map((field) => ( From 2362d050a48c2eafe560b48263eac5497b0b9b2c Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 18:42:55 +0800 Subject: [PATCH 03/15] fix(agent): populate userId in agent workflow chat task payloads --- src/services/asset/asset.test.ts | 4 ++++ src/services/asset/asset.ts | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/services/asset/asset.test.ts b/src/services/asset/asset.test.ts index 3f84df46..27672976 100644 --- a/src/services/asset/asset.test.ts +++ b/src/services/asset/asset.test.ts @@ -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 () => { diff --git a/src/services/asset/asset.ts b/src/services/asset/asset.ts index 626d584c..2539e8cc 100644 --- a/src/services/asset/asset.ts +++ b/src/services/asset/asset.ts @@ -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, }, }, }, From 2fe66a74e3d74e72e8422522687b638f1f6c9de0 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 18:50:12 +0800 Subject: [PATCH 04/15] feat(agent): update agent system prompt with platform instructions and file system constraints --- src/agent/index.ts | 8 ++++---- src/workflow/activities/agent.ts | 10 +++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/agent/index.ts b/src/agent/index.ts index 7e8b20cd..57f1197a 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -7,12 +7,12 @@ 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' -import { createListAssetsTool } from './tools/list-assets' -import { createCreateFolderTool } from './tools/create-folder' -import { createCreateFileTool } from './tools/create-file' -import { createCreateVersionTool } from './tools/create-version' export interface CreateAgentSessionParams { agentId: string diff --git a/src/workflow/activities/agent.ts b/src/workflow/activities/agent.ts index ff92830e..81fbbae6 100644 --- a/src/workflow/activities/agent.ts +++ b/src/workflow/activities/agent.ts @@ -62,7 +62,15 @@ 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 (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}` } From 2e685ceccb505a58a509502ff359f14e7e6e6c2a Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 19:03:13 +0800 Subject: [PATCH 05/15] perf(workflow): optimize getMimeType to read first 4100 bytes instead of whole file --- src/workflow/activities/db.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 142d4e11..507aebc3 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -630,9 +630,15 @@ export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParam function getMimeType(filePath: string): string { try { - const buffer = fs.readFileSync(filePath) - const detected = detectSupportedMimeType(new Uint8Array(buffer)) - if (detected) return detected + 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 S3 detection errors and fallback to extension mapping */ } From ff5196a5177bf44c311812a6ffc5d8fb5cbd4937 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 19:24:04 +0800 Subject: [PATCH 06/15] fix(agent): pre-upload files in agent tools before database workflow execution to ensure worker isolation --- src/agent/tools/create-file.ts | 53 +++++++++++++++- src/agent/tools/create-version.ts | 53 +++++++++++++++- src/workflow/activities/db.test.ts | 13 +++- src/workflow/activities/db.ts | 97 ++++++------------------------ 4 files changed, 133 insertions(+), 83 deletions(-) diff --git a/src/agent/tools/create-file.ts b/src/agent/tools/create-file.ts index 16723228..bea55f35 100644 --- a/src/agent/tools/create-file.ts +++ b/src/agent/tools/create-file.ts @@ -1,6 +1,40 @@ 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' + +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 = { + '.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({ @@ -20,9 +54,26 @@ export function createCreateFileTool(userId: string): AgentTool { 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) + + // Pre-upload the file to S3 + const s3Key = await s3Service.uploadFile(absolutePath, mimeType) + const result = await executeAgentToolWorkflow({ toolName: 'create_file', - args: params, + args: { + parent: params.parent, + s3Key, + name: path.basename(absolutePath), + size: fileSize, + contentType: mimeType, + }, userId, assetId: params.parent, }) diff --git a/src/agent/tools/create-version.ts b/src/agent/tools/create-version.ts index 0728e12a..677891c5 100644 --- a/src/agent/tools/create-version.ts +++ b/src/agent/tools/create-version.ts @@ -1,6 +1,40 @@ 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' + +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 = { + '.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({ @@ -21,9 +55,26 @@ export function createCreateVersionTool(userId: string): AgentTool { 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) + + // Pre-upload the file to S3 + const s3Key = await s3Service.uploadFile(absolutePath, mimeType) + const result = await executeAgentToolWorkflow({ toolName: 'create_version', - args: params, + args: { + parent: params.parent, + s3Key, + name: path.basename(absolutePath), + size: fileSize, + contentType: mimeType, + }, userId, assetId: params.parent, }) diff --git a/src/workflow/activities/db.test.ts b/src/workflow/activities/db.test.ts index 879124c4..2fbdb952 100644 --- a/src/workflow/activities/db.test.ts +++ b/src/workflow/activities/db.test.ts @@ -14,6 +14,7 @@ import { executeAgentToolActivity, } from './db' import type { SessionTreeEntry } from '@earendil-works/pi-agent-core' +import { s3Service } from '@/services/s3/s3' describe('Database Activities', () => { setupTestDbHooks() @@ -408,12 +409,16 @@ describe('Database Activities', () => { 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, - path: tempFilePath, + s3Key, + name: 'temp_test_file.txt', + size: fs.statSync(tempFilePath).size, + contentType: 'text/plain', }, userId: user.id, }) @@ -446,12 +451,16 @@ describe('Database Activities', () => { 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, - path: versionTempPath, + s3Key: s3KeyV2, + name: 'temp_version_file.txt', + size: fs.statSync(versionTempPath).size, + contentType: 'text/plain', }, userId: user.id, }) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 507aebc3..6f9febaf 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -6,15 +6,11 @@ import { metadataService } from '@/services/metadata/metadata' import { UpdateAssetMetadataRequest } from '@/dtos/metadata' 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 @@ -628,43 +624,6 @@ export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParam // Agent System Tools & Context Activities // ========================================== -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 S3 detection errors and fallback to extension mapping */ - } - - const ext = path.extname(filePath).toLowerCase() - const mimeTypes: Record = { - '.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) @@ -836,10 +795,13 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): case 'create_file': { const parent = args.parent - const filePath = args.path - if (!parent || !filePath) { + 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 and path parameters are required', + message: 'parent, s3Key, name, size, and contentType parameters are required', nonRetryable: true, }) } @@ -852,25 +814,12 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): 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), + name, type: 'file', parentId: parent, - key, + key: s3Key, sizeByte: fileSize, contentType: mimeType, creatorId: userId, @@ -896,10 +845,13 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): case 'create_version': { const parent = args.parent // parent file id - const filePath = args.path - if (!parent || !filePath) { + 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 and path parameters are required', + message: 'parent, s3Key, name, size, and contentType parameters are required', nonRetryable: true, }) } @@ -923,29 +875,16 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): 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), + name, type: 'file', parentId: stackId, - key, + key: s3Key, sizeByte: fileSize, contentType: mimeType, creatorId: userId, @@ -998,10 +937,10 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): // 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), + name, type: 'file', parentId: folderParentId, - key, + key: s3Key, sizeByte: fileSize, contentType: mimeType, creatorId: userId, From a8df6b382ddbc7abc02d802d8df6e7885ada8f8b Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 30 May 2026 23:23:25 +0800 Subject: [PATCH 07/15] feat(agent): add local write filesystem constraints to agent system prompt --- src/workflow/activities/agent.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/workflow/activities/agent.ts b/src/workflow/activities/agent.ts index 81fbbae6..fb795d8e 100644 --- a/src/workflow/activities/agent.ts +++ b/src/workflow/activities/agent.ts @@ -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: { @@ -65,7 +65,9 @@ async function executeAgentPrompt(params: { 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.` +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}` From c2fbd3ed531db9c98d970fbbf6fb617c5df39b1e Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 09:38:18 +0800 Subject: [PATCH 08/15] fix(agent): trigger post-upload transcode and AI workflows for agent-created assets --- src/services/upload/upload.ts | 139 ++++++++++++++++------------- src/workflow/activities/db.test.ts | 82 +++++++++++++++++ src/workflow/activities/db.ts | 52 ++++++++++- 3 files changed, 211 insertions(+), 62 deletions(-) diff --git a/src/services/upload/upload.ts b/src/services/upload/upload.ts index 21d72400..3b960fd7 100644 --- a/src/services/upload/upload.ts +++ b/src/services/upload/upload.ts @@ -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 { + 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( diff --git a/src/workflow/activities/db.test.ts b/src/workflow/activities/db.test.ts index 2fbdb952..e4ae528a 100644 --- a/src/workflow/activities/db.test.ts +++ b/src/workflow/activities/db.test.ts @@ -485,5 +485,87 @@ describe('Database Activities', () => { } } }) + + 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') + }) }) }) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 6f9febaf..9ccc6281 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -8,6 +8,7 @@ import { WorkflowTaskStatus, AssetStatus, Prisma, AssetType } from '@/generated/ 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' @@ -814,6 +815,24 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): 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, @@ -833,6 +852,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): }) // 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 { @@ -859,7 +886,7 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): // 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 + 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}`, @@ -867,6 +894,13 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): }) } + 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, @@ -916,6 +950,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): // 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 { @@ -957,6 +999,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): // 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 { From 975a0cfcdae9f3ef2b17faee60d16cf163b0a31b Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 10:02:05 +0800 Subject: [PATCH 09/15] feat(agent): add structured error logging to sandboxed-bash tool --- src/agent/tools/sandboxed-bash.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/agent/tools/sandboxed-bash.ts b/src/agent/tools/sandboxed-bash.ts index fe4bc465..b3ac78e7 100644 --- a/src/agent/tools/sandboxed-bash.ts +++ b/src/agent/tools/sandboxed-bash.ts @@ -2,6 +2,7 @@ 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' +import { logger } from '@/logger' const BashParameters = Type.Object({ command: Type.String({ description: 'The bash command to execute.' }), @@ -81,6 +82,7 @@ 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 +91,13 @@ 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 From c3cce15d7add20767986dd246b41afb5dd55d2dd Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 10:20:20 +0800 Subject: [PATCH 10/15] feat(agent): format available skills as standard XML with absolute path locations --- src/agent/index.test.ts | 33 +++++++++++++++++++++++ src/agent/index.ts | 45 ++++++++++++++++++++++++++----- src/agent/tools/sandboxed-bash.ts | 10 +++++-- 3 files changed, 80 insertions(+), 8 deletions(-) create mode 100644 src/agent/index.test.ts diff --git a/src/agent/index.test.ts b/src/agent/index.test.ts new file mode 100644 index 00000000..8bf07085 --- /dev/null +++ b/src/agent/index.test.ts @@ -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 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('') + expect(result).toContain('') + expect(result).toContain('Deploy & Test') + expect(result).toContain( + 'Deploys code <deploy> and "runs" tests.', + ) + expect(result).toContain(`${expectedLocation}`) + expect(result).toContain('') + expect(result).toContain('') + }) +}) diff --git a/src/agent/index.ts b/src/agent/index.ts index 57f1197a..90ae238c 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -149,12 +149,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { systemPrompt: async () => { let prompt = systemPrompt if (teamSkills.length > 0) { - prompt += '\n\nAvailable Skills:\n' - for (const s of teamSkills) { - prompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n` - } - prompt += - '\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.' + prompt += formatSkillsForPrompt(teamSkills) } return prompt }, @@ -216,3 +211,41 @@ export function fieldsToTypeBoxSchema(fields: AutofillField[]) { return Type.Object(properties) } + +function escapeXml(str: string): string { + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +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.', + '', + '', + ] + + for (const skill of skills) { + const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md') + lines.push(' ') + lines.push(` ${escapeXml(skill.name)}`) + lines.push(` ${escapeXml(skill.description || 'No description')}`) + lines.push(` ${escapeXml(filePath)}`) + lines.push(' ') + } + + lines.push('') + + return lines.join('\n') +} diff --git a/src/agent/tools/sandboxed-bash.ts b/src/agent/tools/sandboxed-bash.ts index b3ac78e7..b5e6c57d 100644 --- a/src/agent/tools/sandboxed-bash.ts +++ b/src/agent/tools/sandboxed-bash.ts @@ -82,7 +82,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') + logger.error( + { err, command, stdout, stderr }, + 'Sandboxed bash command encountered process error', + ) reject(err) }) @@ -97,7 +100,10 @@ export const createSandboxedBashTool = ( 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') + 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 From 3f5b56472648ca7a1469fbbfbd14abed5b00d375 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 10:48:06 +0800 Subject: [PATCH 11/15] fix(agent): upload files and versions using compliant S3 keys --- src/agent/tools/create-file.ts | 6 ++++-- src/agent/tools/create-version.ts | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/agent/tools/create-file.ts b/src/agent/tools/create-file.ts index bea55f35..a6c4f427 100644 --- a/src/agent/tools/create-file.ts +++ b/src/agent/tools/create-file.ts @@ -5,6 +5,7 @@ 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 { @@ -62,8 +63,9 @@ export function createCreateFileTool(userId: string): AgentTool Date: Sun, 31 May 2026 10:56:52 +0800 Subject: [PATCH 12/15] fix(agent): assign lower sortIndex to newer versions to ensure they are marked as latest --- src/workflow/activities/db.test.ts | 73 ++++++++++++++++++++++++++++++ src/workflow/activities/db.ts | 15 ++---- 2 files changed, 78 insertions(+), 10 deletions(-) diff --git a/src/workflow/activities/db.test.ts b/src/workflow/activities/db.test.ts index e4ae528a..413e7511 100644 --- a/src/workflow/activities/db.test.ts +++ b/src/workflow/activities/db.test.ts @@ -567,5 +567,78 @@ describe('Database Activities', () => { 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) + }) }) }) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts index 9ccc6281..47d9b623 100644 --- a/src/workflow/activities/db.ts +++ b/src/workflow/activities/db.ts @@ -625,11 +625,6 @@ export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParam // Agent System Tools & Context Activities // ========================================== -function generateSortIndex(previous?: string | null): string { - if (!previous) return generateKeyBetween(null, null) - return generateKeyBetween(previous, null) -} - export async function getAssetPathContextActivity(assetId: string): Promise { const parts: { name: string; id: string }[] = [] let currentId: string | null = assetId @@ -924,12 +919,12 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): creatorId: userId, }) - // Generate sort index for new version inside the stack - const lastChild = await prisma.asset.findFirst({ + // 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: 'desc' }, + orderBy: { sortIndex: 'asc' }, }) - const newSortIndex = generateSortIndex(lastChild?.sortIndex) + const newSortIndex = generateKeyBetween(null, firstChild?.sortIndex || null) await prisma.$transaction(async (tx) => { // Assign sort index @@ -992,7 +987,7 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams): // eslint-disable-next-line @typescript-eslint/no-explicit-any const txVersionStackService = new VersionStackService(tx as any) await txVersionStackService.createVersionStack({ - fileIds: [parentFile.id, newFile.id], + fileIds: [newFile.id, parentFile.id], projectId: parentFile.projectId!, creatorId: userId, }) From be7dc450513b3394a0e0fc914afc2558a9e59513 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 12:55:45 +0800 Subject: [PATCH 13/15] feat(agent): restrict sandbox filesystem access and update system prompt instructions --- src/agent/index.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/agent/index.ts b/src/agent/index.ts index 90ae238c..d1a1ecb0 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -5,6 +5,7 @@ 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 * as os from 'os' import { DatabaseSessionStorage } from './database-session-storage' import { analyzeAssetMediaTool } from './tools/analyze-asset-media' import { createCreateFileTool } from './tools/create-file' @@ -109,7 +110,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({ @@ -118,9 +119,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) { deniedDomains: [], }, filesystem: { + allowRead: [piDir], + denyRead: [os.homedir(), '.env', '.env.*', '*.pem', '*.key'], allowWrite, denyWrite: ['.env', '.env.*', '*.pem', '*.key'], - denyRead: ['~/.ssh', '~/.aws', '~/.gnupg'], }, }) @@ -148,6 +150,18 @@ export async function createAgentSession(params: CreateAgentSessionParams) { 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 (`< 0) { prompt += formatSkillsForPrompt(teamSkills) } From b53c40cbded43803128488dd837c22da261f5fe8 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 19:11:27 +0800 Subject: [PATCH 14/15] update --- .pi/data.txt | 10 ---- .pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/.hash | 1 - .../01KS4NE3PN9VF3H0CRPHJSH4E9/SKILL.md | 54 ------------------- .../01KS4NE3PN9VF3H0CRPHJSH4E9/_meta.json | 6 --- src/agent/index.ts | 5 +- src/agent/tools/sandboxed-bash.ts | 5 +- 6 files changed, 5 insertions(+), 76 deletions(-) delete mode 100644 .pi/data.txt delete mode 100644 .pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/.hash delete mode 100644 .pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/SKILL.md delete mode 100644 .pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/_meta.json diff --git a/.pi/data.txt b/.pi/data.txt deleted file mode 100644 index 0aae377d..00000000 --- a/.pi/data.txt +++ /dev/null @@ -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 diff --git a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/.hash b/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/.hash deleted file mode 100644 index 5f479691..00000000 --- a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/.hash +++ /dev/null @@ -1 +0,0 @@ -6c49ce20d801d83fe10da4ad9cf51eac571100c0e3173d552de878f8e7bf612d \ No newline at end of file diff --git a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/SKILL.md b/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/SKILL.md deleted file mode 100644 index 3f9bdb08..00000000 --- a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/SKILL.md +++ /dev/null @@ -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¤t_weather=true" -``` - -Find coordinates for a city, then query. Returns JSON with temp, windspeed, weathercode. - -Docs: https://open-meteo.com/en/docs diff --git a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/_meta.json b/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/_meta.json deleted file mode 100644 index 125d1a04..00000000 --- a/.pi/skills/01KS4NE3PN9VF3H0CRPHJSH4E9/_meta.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "ownerId": "kn70pywhg0fyz996kpa8xj89s57yhv26", - "slug": "weather", - "version": "1.0.0", - "publishedAt": 1767545394459 -} diff --git a/src/agent/index.ts b/src/agent/index.ts index d1a1ecb0..f930cf67 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -4,8 +4,8 @@ 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 * as os from 'os' +import * as path from 'path' import { DatabaseSessionStorage } from './database-session-storage' import { analyzeAssetMediaTool } from './tools/analyze-asset-media' import { createCreateFileTool } from './tools/create-file' @@ -119,8 +119,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { deniedDomains: [], }, filesystem: { - allowRead: [piDir], - denyRead: [os.homedir(), '.env', '.env.*', '*.pem', '*.key'], + denyRead: ['.env', '.env.*', '*.pem', '*.key'], allowWrite, denyWrite: ['.env', '.env.*', '*.pem', '*.key'], }, diff --git a/src/agent/tools/sandboxed-bash.ts b/src/agent/tools/sandboxed-bash.ts index b5e6c57d..fbcf4b83 100644 --- a/src/agent/tools/sandboxed-bash.ts +++ b/src/agent/tools/sandboxed-bash.ts @@ -1,8 +1,8 @@ +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' -import { logger } from '@/logger' const BashParameters = Type.Object({ command: Type.String({ description: 'The bash command to execute.' }), @@ -37,7 +37,8 @@ export const createSandboxedBashTool = ( detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { - ...process.env, + PATH: process.env.PATH || '', + HOME: process.env.HOME || '', ...skillEnvs, }, }) From 81d7e2b845c6e46a948904aef9e8b23b8ebeafcd Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 31 May 2026 19:16:38 +0800 Subject: [PATCH 15/15] chore(agent): remove unused os import from index.ts --- src/agent/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/agent/index.ts b/src/agent/index.ts index f930cf67..019f474f 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -4,7 +4,6 @@ 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 os from 'os' import * as path from 'path' import { DatabaseSessionStorage } from './database-session-storage' import { analyzeAssetMediaTool } from './tools/analyze-asset-media'