From db04df88f19910b058e02f3e095e090789a03872 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 16:56:06 +0800 Subject: [PATCH 1/2] feat(agent): add download_asset tool and prompt instructions --- packages/agent/src/index.ts | 3 + .../agent/src/tools/download-asset.test.ts | 168 ++++++++++++++++++ packages/agent/src/tools/download-asset.ts | 114 ++++++++++++ .../agent-chat-prompt-builder.test.ts | 8 + .../workflows/agent-chat-prompt-builder.ts | 2 + 5 files changed, 295 insertions(+) create mode 100644 packages/agent/src/tools/download-asset.test.ts create mode 100644 packages/agent/src/tools/download-asset.ts diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 75cf1cee..8a66c766 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -17,6 +17,7 @@ import { createAnalyzeImageTool } from './tools/analyze-image' import { createCreateFileTool } from './tools/create-file' import { createCreateFolderTool } from './tools/create-folder' import { createCreateVersionTool } from './tools/create-version' +import { createDownloadAssetTool } from './tools/download-asset' import { createListAssetsTool } from './tools/list-assets' import { createReadPdfPagesTool } from './tools/read-pdf-pages' import { createReadSkillTool } from './tools/read-skill' @@ -263,6 +264,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { createCreateFolderTool(userId), createCreateFileTool(userId), createCreateVersionTool(userId), + createDownloadAssetTool(userId), ) } @@ -305,6 +307,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { '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) { diff --git a/packages/agent/src/tools/download-asset.test.ts b/packages/agent/src/tools/download-asset.test.ts new file mode 100644 index 00000000..e2d1b0e5 --- /dev/null +++ b/packages/agent/src/tools/download-asset.test.ts @@ -0,0 +1,168 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { createDownloadAssetTool } from './download-asset' +import { prisma, type Asset } from '@shumai/db' +import { s3Service } from '@shumai/core/src/s3/s3' +import { authzService } from '@shumai/core/src/authz/authz' +import * as fs from 'fs' +import * as path from 'path' + +vi.mock('@shumai/db', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + prisma: { + asset: { + findUnique: vi.fn(), + }, + }, + } +}) + +vi.mock('@shumai/core/src/s3/s3', () => ({ + s3Service: { + getObject: vi.fn(), + }, +})) + +vi.mock('@shumai/core/src/authz/authz', () => ({ + authzService: { + hasPermission: vi.fn(), + }, + Permission: { Read: 'Read' }, + ResourceType: { Asset: 'asset' }, +})) + +describe('downloadAssetTool', () => { + const piDir = path.join(process.cwd(), '.pi') + const createdFiles: string[] = [] + + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + for (const f of createdFiles) { + if (fs.existsSync(f)) { + fs.unlinkSync(f) + } + } + createdFiles.length = 0 + }) + + it('should throw authorization error if user ID is empty', async () => { + const tool = createDownloadAssetTool('') + await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow( + 'User ID is required for authorization.', + ) + }) + + it('should throw error if asset not found', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue(null) + + const tool = createDownloadAssetTool('user-1') + await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow( + 'Asset with ID asset-1 not found.', + ) + }) + + it('should download proxy image to .pi directory when imageTranscodes is present', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-img-1', + name: 'sample_photo.jpg', + storageKey: { key: 'raw/sample_photo.jpg' }, + media: { + proxyType: 'image', + imageTranscodes: [{ key: 'proxy/sample_photo.webp' }], + }, + } as unknown as Asset) + + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('fake-proxy-image-bytes'), + contentType: 'image/webp', + } as unknown as { buffer: Buffer; contentType: string }) + + const tool = createDownloadAssetTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-img-1' }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'Read', + type: 'asset', + id: 'asset-img-1', + }) + + expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/sample_photo.webp') + + const expectedPath = path.join(piDir, 'asset-img-1_sample_photo.jpg') + createdFiles.push(expectedPath) + + expect(fs.existsSync(expectedPath)).toBe(true) + expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-proxy-image-bytes') + + expect(result.details.filePath).toBe(path.join('.pi', 'asset-img-1_sample_photo.jpg')) + expect(result.details.contentType).toBe('image/webp') + expect((result.content[0] as { type: 'text'; text: string }).text).toContain( + 'Remember to delete this temporary file when finished.', + ) + }) + + it('should download proxy video to .pi directory when videoTranscodes is present', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-vid-1', + name: 'video_test.mov', + storageKey: { key: 'raw/video_test.mov' }, + media: { + proxyType: 'video', + videoTranscodes: [{ key: 'proxy/video_test.mp4' }], + }, + } as unknown as Asset) + + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('fake-video-bytes'), + contentType: 'video/mp4', + } as unknown as { buffer: Buffer; contentType: string }) + + const tool = createDownloadAssetTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-vid-1' }) + + expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/video_test.mp4') + + const expectedPath = path.join(piDir, 'asset-vid-1_video_test.mov') + createdFiles.push(expectedPath) + + expect(fs.existsSync(expectedPath)).toBe(true) + expect(result.details.size).toBe(Buffer.from('fake-video-bytes').length) + }) + + it('should download proxy pdf to .pi directory when pdfTranscode is present', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-pdf-1', + name: 'doc.pdf', + storageKey: { key: 'raw/doc.pdf' }, + media: { + proxyType: 'pdf', + pdfTranscode: { key: 'proxy/doc.pdf' }, + }, + } as unknown as Asset) + + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('fake-pdf-bytes'), + contentType: 'application/pdf', + } as unknown as { buffer: Buffer; contentType: string }) + + const tool = createDownloadAssetTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-pdf-1' }) + + expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/doc.pdf') + + const expectedPath = path.join(piDir, 'asset-pdf-1_doc.pdf') + createdFiles.push(expectedPath) + + expect(fs.existsSync(expectedPath)).toBe(true) + expect(result.details.contentType).toBe('application/pdf') + }) +}) diff --git a/packages/agent/src/tools/download-asset.ts b/packages/agent/src/tools/download-asset.ts new file mode 100644 index 00000000..ecc3a663 --- /dev/null +++ b/packages/agent/src/tools/download-asset.ts @@ -0,0 +1,114 @@ +import { Type } from '@sinclair/typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { prisma, type User } from '@shumai/db' +import { s3Service } from '@shumai/core/src/s3/s3' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { sanitizeFilename } from '@shumai/core/src/utils/filename' +import * as fs from 'fs' +import * as path from 'path' + +const downloadAssetSchema = Type.Object({ + assetId: Type.String({ + description: + 'The asset ID of the workspace asset to download to local disk. This parameter is required.', + }), +}) + +export function createDownloadAssetTool(userId: string): AgentTool { + return { + name: 'download_asset', + label: 'Download Asset', + description: + 'Downloads a workspace asset (proxy version if available) to the local .pi directory for processing with local scripts or bash commands. Remember to delete the temporary downloaded file when finished.', + parameters: downloadAssetSchema, + execute: async (_toolCallId, params) => { + const assetId = params.assetId + + if (!userId) { + throw new Error('User ID is required for authorization.') + } + + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Read, + type: ResourceType.Asset, + id: assetId, + }) + + const asset = await prisma.asset.findUnique({ + where: { id: assetId }, + include: { storageKey: true }, + }) + + if (!asset) { + throw new Error(`Asset with ID ${assetId} not found.`) + } + + let mediaKey = asset.storageKey?.key + + if (asset.media) { + const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo + if ( + mediaInfo.proxyType === 'image' || + (mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0) + ) { + if (mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0) { + mediaKey = mediaInfo.imageTranscodes[0].key || mediaKey + } + } else if ( + mediaInfo.proxyType === 'video' || + (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) || + mediaInfo.videoPreview?.key + ) { + if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) { + mediaKey = mediaInfo.videoTranscodes[0].key || mediaKey + } else if (mediaInfo.videoPreview?.key) { + mediaKey = mediaInfo.videoPreview.key + } + } else if (mediaInfo.proxyType === 'pdf' || mediaInfo.pdfTranscode?.key) { + if (mediaInfo.pdfTranscode?.key) { + mediaKey = mediaInfo.pdfTranscode.key + } + } else if (mediaInfo.original?.key) { + mediaKey = mediaInfo.original.key || mediaKey + } + } + + if (!mediaKey) { + throw new Error(`No media content found for asset ${assetId}.`) + } + + const piDir = path.join(process.cwd(), '.pi') + if (!fs.existsSync(piDir)) { + fs.mkdirSync(piDir, { recursive: true }) + } + + const safeName = sanitizeFilename(asset.name || 'file') + const filename = `${asset.id}_${safeName}` + const targetFilePath = path.join(piDir, filename) + const relativePath = path.join('.pi', filename) + + const bucket = process.env.S3_BUCKET || 'shumai' + const { buffer, contentType } = await s3Service.getObject(bucket, mediaKey) + + fs.writeFileSync(targetFilePath, buffer) + + return { + content: [ + { + type: 'text', + text: `Downloaded asset "${asset.name}" (ID: ${assetId}) to "${relativePath}". Remember to delete this temporary file when finished.`, + }, + ], + details: { + assetId, + name: asset.name, + filePath: relativePath, + absolutePath: targetFilePath, + contentType: contentType || 'application/octet-stream', + size: buffer.length, + }, + } + }, + } +} diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts index fb49c65b..452ddc73 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -161,4 +161,12 @@ describe('AgentChatPromptBuilder', () => { expect(result).toContain('User Info:\nName: Alice\nRole: owner') }) + + it('should build prompt with download_asset tool instruction', () => { + const builder = new AgentChatPromptBuilder('a1') + const result = builder.build() + + expect(result).toContain("call the 'download_asset' tool with assetId") + expect(result).toContain('remember to delete the temporary downloaded file.') + }) }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts index e219f2c6..f37b77e8 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -174,6 +174,8 @@ export class AgentChatPromptBuilder { } } + instruction += `\n\nIf you need a local file on disk to run bash commands or scripts (e.g. processing or combining assets), call the 'download_asset' tool with assetId. After finishing the job, remember to delete the temporary downloaded file.` + if (this.userInfo) { instruction += `\n\nUser Info:\nName: ${this.userInfo.name}\nRole: ${this.userInfo.role}` } From 9ba61b3d3e994b7fccbaad76a01c9911b054f517 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 17:15:12 +0800 Subject: [PATCH 2/2] refactor(agent): simplify download_asset prompt instruction in prompt builder --- packages/agent/src/workflows/agent-chat-prompt-builder.test.ts | 3 +-- packages/agent/src/workflows/agent-chat-prompt-builder.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts index 452ddc73..ff0a2b14 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -166,7 +166,6 @@ describe('AgentChatPromptBuilder', () => { const builder = new AgentChatPromptBuilder('a1') const result = builder.build() - expect(result).toContain("call the 'download_asset' tool with assetId") - expect(result).toContain('remember to delete the temporary downloaded file.') + expect(result).toContain("call the 'download_asset' tool with assetId.") }) }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts index f37b77e8..e7b44dab 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -174,7 +174,7 @@ export class AgentChatPromptBuilder { } } - instruction += `\n\nIf you need a local file on disk to run bash commands or scripts (e.g. processing or combining assets), call the 'download_asset' tool with assetId. After finishing the job, remember to delete the temporary downloaded file.` + instruction += `\n\nIf you need a local file on disk to run bash commands or scripts (e.g. processing or combining assets), call the 'download_asset' tool with assetId.` if (this.userInfo) { instruction += `\n\nUser Info:\nName: ${this.userInfo.name}\nRole: ${this.userInfo.role}`