fix(agent): pre-upload files in agent tools before database workflow execution to ensure worker isolation

This commit is contained in:
yiling
2026-05-30 19:24:04 +08:00
parent 2e685ceccb
commit ff5196a517
4 changed files with 133 additions and 83 deletions
+52 -1
View File
@@ -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<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.pdf': 'application/pdf',
}
return mimeTypes[ext] || 'application/octet-stream'
}
const createVersionSchema = Type.Object({
parent: Type.String({
@@ -21,9 +55,26 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
parameters: createVersionSchema,
execute: async (_toolCallId, params) => {
try {
const absolutePath = path.resolve(process.cwd(), params.path)
if (!fs.existsSync(absolutePath)) {
throw new Error(`Local file not found at path: ${params.path}`)
}
const fileSize = fs.statSync(absolutePath).size
const mimeType = getMimeType(absolutePath)
// 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,
})