feat(asset-download): share download_asset across agent, MCP and CLI

Turn the agent-only download_asset tool into an Operation on all three
surfaces.

- download_asset takes up to 50 file or version stack IDs and returns
  presigned links. proxy (default true) picks the web preview when there
  is one, as the agent always did; proxy: false returns the original.
  Folders are rejected. Read is checked on every ID before anything runs.
- Agent: an extension saves the files into the .pi sandbox and keeps the
  agent-only storage key mode (e.g. frames from read_asset). Agent tool
  extensions gain description, parameterOverrides and intercept.
- CLI: `shumai-cli download <assetId...> [--out <dir>] [--original]`
  streams files to disk without overwriting existing names.
- read_asset's unsupported-type error now names the right way to
  download on each surface (download_asset, or `shumai-cli download`).
- Add the Download Asset toggle to agent settings.
This commit is contained in:
yiling
2026-10-26 22:33:30 +08:00
parent b7dccad6e5
commit bc3368f3e3
40 changed files with 1323 additions and 579 deletions
+1 -3
View File
@@ -20,7 +20,6 @@ import { DatabaseSessionStorage } from './database-session-storage'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { createCreateFileTool } from './tools/create-file'
import { createCreateVersionTool } from './tools/create-version'
import { createDownloadAssetTool } from './tools/download-asset'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
@@ -337,11 +336,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const agentContext = { teamId, agentId }
systemTools.push(
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete,
// read_asset and get_asset_render
// read_asset, get_asset_render, and download_asset
...buildOperationTools({ userId, agentId, teamId, projectId }),
createCreateFileTool(userId, metadataSchema, agentContext),
createCreateVersionTool(userId, metadataSchema, agentContext),
createDownloadAssetTool(userId),
)
}
@@ -0,0 +1,294 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { prisma, type Asset, type StorageKey } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { toAgentTool } from '../operation-tools'
import './download-asset'
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
asset: { findUnique: vi.fn(), findFirst: vi.fn() },
storageKey: { findFirst: vi.fn(), findUnique: vi.fn() },
},
}
})
vi.mock('@shumai/core/src/s3/s3', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/core/src/s3/s3')>()
return {
...actual,
s3Service: {
headObject: vi.fn(),
downloadToFile: vi.fn(),
presign: vi.fn().mockResolvedValue('https://signed.example/file'),
},
}
})
vi.mock('@shumai/core/src/authz/authz', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/core/src/authz/authz')>()
return { ...actual, authzService: { hasPermission: vi.fn() } }
})
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
type Saved = { filePath: string; absolutePath: string; contentType: string; size: number }
const piDir = path.join(process.cwd(), '.pi')
function downloadTool(userId = 'user-1') {
return toAgentTool(getOperation('download_asset')!, { userId })
}
function textOf(result: { content: unknown[] }): string {
return (result.content[0] as { text: string }).text
}
function mockAssets(...assets: Array<Record<string, unknown>>) {
vi.mocked(prisma.asset.findUnique).mockImplementation(
(async (args: { where: { id: string } }) =>
assets.find((a) => a.id === args.where.id) ?? null) as never,
)
}
function mockStorage(contentType: string, write = 'bytes') {
vi.mocked(s3Service.headObject).mockResolvedValue({ size: 1234, contentType } as Head)
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, dest) => {
await fs.promises.writeFile(dest, write)
})
}
const photo = {
id: 'img-1',
name: 'sample_photo.jpg',
type: 'file',
isDeleted: false,
storageKey: { key: 'files/up-1/sample_photo.jpg' },
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/img-1/proxy.webp' }] },
}
describe('download_asset agent tool', () => {
const created: string[] = []
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue()
})
afterEach(() => {
for (const file of created.splice(0)) fs.rmSync(file, { force: true })
})
it('offers assetIds, proxy, and the agent-only key parameter', () => {
const tool = downloadTool()
const schema = tool.parameters as { properties: Record<string, unknown>; required?: string[] }
expect(Object.keys(schema.properties)).toEqual(['assetIds', 'proxy', 'key'])
expect(schema.required ?? []).not.toContain('assetIds')
expect(tool.description).toContain('.pi directory')
})
it('saves the web preview into .pi by default, named after the asset', async () => {
mockAssets(photo)
mockStorage('image/webp', 'proxy-bytes')
const result = await downloadTool().execute('call-1', { assetIds: ['img-1'] })
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
created.push(expectedPath)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'img-1',
})
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/img-1/proxy.webp',
expectedPath,
)
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('proxy-bytes')
expect(textOf(result)).toBe(
[
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.join('.pi', 'img-1_sample_photo.webp')}".`,
'Remember to delete these temporary files when finished.',
].join('\n'),
)
const details = result.details as { files: Saved[] }
expect(details.files[0]).toMatchObject({
filePath: path.join('.pi', 'img-1_sample_photo.webp'),
contentType: 'image/webp',
size: 11,
})
})
it('saves the original with proxy false', async () => {
mockAssets(photo)
mockStorage('image/jpeg')
await downloadTool().execute('call-1', { assetIds: ['img-1'], proxy: false })
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
created.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/up-1/sample_photo.jpg',
expectedPath,
)
})
it('downloads several files and the latest version of a version stack', async () => {
mockAssets(photo, { id: 'stack-1', name: 'banana', type: 'version_stack', isDeleted: false })
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
id: 'file-v2',
name: 'banana_pig.png',
type: 'file',
isDeleted: false,
storageKey: { key: 'files/up-2/banana_pig.png' },
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/file-v2/proxy.webp' }] },
} as unknown as Asset)
mockStorage('image/webp')
const result = await downloadTool().execute('call-1', {
assetIds: ['img-1', 'stack-1'],
key: null,
})
created.push(
path.join(piDir, 'img-1_sample_photo.webp'),
path.join(piDir, 'file-v2_banana_pig.webp'),
)
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
where: { parentId: 'stack-1', isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: { storageKey: true },
})
expect(s3Service.downloadToFile).toHaveBeenCalledTimes(2)
expect(textOf(result)).toContain('Downloaded "banana_pig.webp" (ID: file-v2, proxy')
})
it('rejects folders', async () => {
mockAssets({ id: 'folder-1', name: 'Renders', type: 'folder', isDeleted: false })
await expect(downloadTool().execute('call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
)
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('checks Read on every asset before downloading anything', async () => {
mockAssets(photo)
vi.mocked(authzService.hasPermission).mockImplementation(async ({ id }) => {
if (id === 'secret') throw new Error('Forbidden')
})
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1', 'secret'] }),
).rejects.toThrow('Forbidden')
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('requires assetIds or key', async () => {
await expect(downloadTool().execute('call-1', { assetIds: null, key: null })).rejects.toThrow(
'Invalid input for download_asset',
)
})
it('rejects assetIds and key together', async () => {
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1'], key: 'files/img-1/a.webp' }),
).rejects.toThrow('Provide either "assetIds" or "key", not both.')
})
describe('by storage key', () => {
it('requires a user', async () => {
await expect(
downloadTool('').execute('call-1', { key: 'files/ast-1/shot.webp' }),
).rejects.toThrow('User ID is required for authorization.')
})
it('rejects keys outside files/ and path traversal', async () => {
await expect(downloadTool().execute('call-1', { key: 'avatars/user-1.png' })).rejects.toThrow(
'Invalid storage key format: key must start with "files/"',
)
await expect(
downloadTool().execute('call-1', { key: 'files/../../etc/passwd' }),
).rejects.toThrow('cannot contain ".."')
})
it('rejects keys that belong to no asset', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
await expect(
downloadTool().execute('call-1', { key: 'files/nope/shot.webp' }),
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
})
it('checks Read on the owning asset', async () => {
mockAssets({ id: 'other-project-asset' })
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(
downloadTool().execute('call-1', { key: 'files/other-project-asset/shots/a.webp' }),
).rejects.toThrow('Forbidden')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'other-project-asset',
})
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('downloads a read_asset artifact into .pi', async () => {
mockAssets({ id: 'ast-123' })
mockStorage('image/webp', 'frame-bytes')
const result = await downloadTool().execute('call-1', {
key: 'files/ast-123/screenshots/shot_5.0s.webp',
})
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
created.push(expectedPath)
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('frame-bytes')
expect(textOf(result)).toBe(
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
)
expect(result.details).toMatchObject({
key: 'files/ast-123/screenshots/shot_5.0s.webp',
assetId: 'ast-123',
size: Buffer.from('frame-bytes').length,
})
})
it('resolves original upload keys through the storage key', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
id: 'sk-1',
key: 'files/upload-ulid-456/photo.png',
assets: [{ id: 'asset-photo-1' }],
} as unknown as StorageKey & { assets: Asset[] })
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
vi.mocked(s3Service.headObject).mockResolvedValue({
size: 8,
contentType: 'application/octet-stream',
} as Head)
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, pngHeader)
})
const result = await downloadTool().execute('call-1', {
key: 'files/upload-ulid-456/photo.png',
})
created.push(path.join(piDir, 'photo.png'))
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({ id: 'asset-photo-1' }),
)
// Falls back to detecting the type from the bytes
expect(result.details).toMatchObject({ assetId: 'asset-photo-1', contentType: 'image/png' })
})
})
})
@@ -0,0 +1,124 @@
import * as fs from 'fs'
import * as path from 'path'
import { z } from 'zod'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
import type { User } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { storageBucket } from '@shumai/core/src/asset-read'
import { s3Service } from '@shumai/core/src/s3/s3'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { resolveAssetIdFromKey } from '../tools/download-asset'
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
/** The agent's sandbox, where downloaded files are saved for local scripts and bash. */
function sandboxDir(): string {
const dir = path.join(process.cwd(), '.pi')
fs.mkdirSync(dir, { recursive: true })
return dir
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
/** Saves a storage object into the sandbox; returns the paths and detected content type. */
async function saveToSandbox(key: string, filename: string) {
const dir = sandboxDir()
const absolutePath = path.join(dir, filename)
const bucket = storageBucket()
const info = await s3Service.headObject(bucket, key).catch(() => null)
await s3Service.downloadToFile(bucket, key, absolutePath)
const size = await fs.promises
.stat(absolutePath)
.then((s) => s.size)
.catch(() => info?.size ?? 0)
const contentType =
info?.contentType && info.contentType !== 'application/octet-stream'
? info.contentType
: readFileMimeType(absolutePath)
return { absolutePath, filePath: path.join('.pi', filename), size, contentType }
}
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
async function downloadKey(key: string, userId: string): Promise<AgentToolResult<unknown>> {
const owningAssetId = await resolveAssetIdFromKey(key)
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: owningAssetId,
})
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
const saved = await saveToSandbox(key, filename)
return {
content: [
{
type: 'text',
text: `Downloaded storage key "${key}" to "${saved.filePath}". Remember to delete this temporary file when finished.`,
},
],
details: { key, assetId: owningAssetId, ...saved },
}
}
/** Saves each file of a download_asset result into the sandbox. */
export async function presentDownloadOutput(
output: DownloadAssetOutput,
): Promise<AgentToolResult<unknown>> {
const lines: string[] = []
const files = []
for (const file of output.files) {
if (!file.key) throw new Error(`download_asset returned no storage key for ${file.assetId}`)
const saved = await saveToSandbox(
file.key,
`${file.assetId}_${sanitizeFilename(file.name) || 'file'}`,
)
lines.push(
`Downloaded "${file.name}" (ID: ${file.assetId}, ${file.kind}, ${saved.contentType}, ${formatSize(saved.size)}) to "${saved.filePath}".`,
)
files.push({ assetId: file.assetId, name: file.name, kind: file.kind, ...saved })
}
lines.push(CLEANUP_REMINDER)
return { content: [{ type: 'text', text: lines.join('\n') }], details: { files } }
}
const downloadAssetExtension: AgentToolExtension = {
description:
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the local .pi directory, for processing with local scripts or bash commands. ` +
'By default it saves the web preview version (proxy) when there is one, e.g. the transcoded video or the web image; set proxy to false for the original uploaded file. ' +
'A version stack downloads its latest version; folders are not supported. ' +
'To download a specific artifact from read_asset (e.g. a frame or page), pass its storage key as "key" instead of assetIds. ' +
'Remember to delete the downloaded files when finished.',
parameterOverrides: z.object({
assetIds: downloadAsset.input.shape.assetIds
.optional()
.describe(
`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}). Omit when passing "key".`,
),
}),
extraParameters: z.object({
key: z
.string()
.optional()
.describe(
'Storage S3 key of a specific media artifact to download instead of assetIds, e.g. a screenshot or page key from read_asset.',
),
}),
async intercept(input, extra, ctx) {
if (typeof extra.key !== 'string') return undefined
if (Array.isArray(input.assetIds) && input.assetIds.length > 0) {
throw new Error('Provide either "assetIds" or "key", not both.')
}
if (!ctx.userId) throw new Error('User ID is required for authorization.')
return downloadKey(extra.key, ctx.userId)
},
present: (output) => presentDownloadOutput(output as DownloadAssetOutput),
}
registerAgentToolExtension('download_asset', downloadAssetExtension)
@@ -1,2 +1,3 @@
// Registers agent-specific presentation for Operations. Import once before building tools.
export { createAutofillReadAssetTool, presentReadOutput } from './read-asset'
export { presentDownloadOutput } from './download-asset'
+2 -1
View File
@@ -61,7 +61,7 @@ describe('operation-backed agent tools', () => {
})
describe('tool definitions', () => {
it('keeps the existing tool names and adds list_projects and get_asset_render', () => {
it('keeps the existing tool names and adds the newer Operations', () => {
expect(
buildOperationTools(ctx)
.map((t) => t.name)
@@ -69,6 +69,7 @@ describe('operation-backed agent tools', () => {
).toEqual([
'create_folder',
'delete_asset',
'download_asset',
'get_asset_render',
'list_assets',
'list_projects',
+26 -4
View File
@@ -19,10 +19,27 @@ export type AgentOperationContext = Omit<OperationContext, 'via'>
* and render the output (e.g. as image blocks).
*/
export interface AgentToolExtension {
/** Replaces the Operation description for the agent (e.g. where files end up). */
description?: string
/** Extra parameters only the agent sees; they are removed before the Operation runs. */
extraParameters?: z.ZodObject
/**
* Agent-facing versions of Operation input fields, e.g. a required field made optional
* because an extra parameter can be used instead. The Operation still validates its own
* input when it runs.
*/
parameterOverrides?: z.ZodObject
/** Adjust the Operation input using the extra parameters. */
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
/**
* Handle an agent-only mode without running the Operation (e.g. a storage key instead of
* an asset). Return undefined to run the Operation.
*/
intercept?(
input: Record<string, unknown>,
extra: Record<string, unknown>,
ctx: AgentOperationContext,
): Promise<AgentToolResult<unknown> | undefined>
present(output: unknown, extra: Record<string, unknown>): Promise<AgentToolResult<unknown>>
}
@@ -34,9 +51,10 @@ export function registerAgentToolExtension(name: string, extension: AgentToolExt
}
function toolInputSchema(op: Operation, extension?: AgentToolExtension): z.ZodObject {
return extension?.extraParameters
? op.definition.input.extend(extension.extraParameters.shape)
: op.definition.input
let schema = op.definition.input
if (extension?.parameterOverrides) schema = schema.extend(extension.parameterOverrides.shape)
if (extension?.extraParameters) schema = schema.extend(extension.extraParameters.shape)
return schema
}
/**
@@ -80,10 +98,14 @@ export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentToo
return {
name: definition.name,
label: definition.title,
description: definition.description,
description: extension?.description ?? definition.description,
parameters: toToolParameters(op, extension),
execute: async (_toolCallId, params) => {
const { input, extra } = splitAgentParams(op, extension, params)
if (extension?.intercept) {
const handled = await extension.intercept(input as Record<string, unknown>, extra, ctx)
if (handled) return handled
}
const output = await runOperation(op, { ...ctx, via: 'agent' }, input)
if (extension) {
return extension.present(output, extra)
+3 -331
View File
@@ -1,14 +1,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
createDownloadAssetTool,
resolveAssetIdFromKey,
resolveS3MediaBuffer,
} from './download-asset'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { resolveAssetIdFromKey, resolveS3MediaBuffer } from './download-asset'
import { prisma, type Asset, type StorageKey } 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<typeof import('@shumai/db')>()
@@ -43,333 +37,11 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
ResourceType: { Asset: 'asset' },
}))
describe('downloadAssetTool', () => {
const piDir = path.join(process.cwd(), '.pi')
const createdFiles: string[] = []
describe('download-asset storage key helpers', () => {
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', key: null })).rejects.toThrow(
'User ID is required for authorization.',
)
})
it('should throw error if both assetId and key are null', async () => {
const tool = createDownloadAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: null, key: null })).rejects.toThrow(
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
)
})
it('should throw error if both assetId and key are provided', async () => {
const tool = createDownloadAssetTool('user-1')
await expect(
tool.execute('call-1', { assetId: 'asset-1', key: 'files/path/file.png' }),
).rejects.toThrow(
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
)
})
describe('Download by assetId', () => {
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', key: null })).rejects.toThrow(
'Asset with ID asset-1 not found.',
)
})
it('should download proxy image to .pi directory when downloading by assetId', 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.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, 'fake-proxy-image-bytes')
})
vi.mocked(s3Service.headObject).mockResolvedValue({
contentType: 'image/webp',
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
const tool = createDownloadAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'asset-img-1', key: null })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'asset-img-1',
})
const expectedPath = path.join(piDir, 'asset-img-1_sample_photo.jpg')
createdFiles.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'proxy/sample_photo.webp',
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 resolve version_stack asset to its latest version file', async () => {
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'stack-1',
name: '',
type: 'version_stack',
storageKey: null,
media: null,
} as unknown as Asset)
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
id: 'file-ver-2',
name: 'banana_pig.png',
type: 'file',
storageKey: { key: 'raw/banana_pig.png' },
media: {
proxyType: 'image',
imageTranscodes: [{ key: 'proxy/banana_pig.webp' }],
},
} as unknown as Asset)
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, 'fake-version-bytes')
})
vi.mocked(s3Service.headObject).mockResolvedValue({
contentType: 'image/webp',
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
const tool = createDownloadAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'stack-1', key: null })
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
where: { parentId: 'stack-1', isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: { storageKey: true },
})
const expectedPath = path.join(piDir, 'file-ver-2_banana_pig.png')
createdFiles.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'proxy/banana_pig.webp',
expectedPath,
)
expect(fs.existsSync(expectedPath)).toBe(true)
expect(result.details.name).toBe('banana_pig.png')
})
})
describe('Download by S3 key and Authorization', () => {
it('should reject keys that do not start with files/', async () => {
const tool = createDownloadAssetTool('user-1')
await expect(
tool.execute('call-1', { assetId: null, key: 'avatars/user-1.png' }),
).rejects.toThrow('Invalid storage key format: key must start with "files/"')
})
it('should reject keys with path traversal (..)', async () => {
const tool = createDownloadAssetTool('user-1')
await expect(
tool.execute('call-1', { assetId: null, key: 'files/../../etc/passwd' }),
).rejects.toThrow('cannot contain ".."')
})
it('should reject keys with insufficient path segments', async () => {
const tool = createDownloadAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: null, key: 'files/invalid' })).rejects.toThrow(
'Invalid storage key format',
)
})
it('should reject keys that do not belong to any valid asset in database', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
const tool = createDownloadAssetTool('user-1')
await expect(
tool.execute('call-1', { assetId: null, key: 'files/nonexistent-id/shot.webp' }),
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
})
it('should reject download when user lacks read permission on the owning asset (cross-project protection)', async () => {
// Key belongs to asset-in-other-project
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'asset-in-other-project',
} as unknown as Asset)
// Authz rejects because user is in a different project/team
vi.mocked(authzService.hasPermission).mockRejectedValue(
new Error('User does not have Read permission on asset asset-in-other-project'),
)
const tool = createDownloadAssetTool('user-1')
await expect(
tool.execute('call-1', {
assetId: null,
key: 'files/asset-in-other-project/screenshots/secret_frame.webp',
}),
).rejects.toThrow('User does not have Read permission on asset asset-in-other-project')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'asset-in-other-project',
})
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('should authorize and download derived artifact key (files/<assetId>/...)', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'ast-123',
} as unknown as Asset)
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, 'fake-screenshot-bytes')
})
vi.mocked(s3Service.headObject).mockResolvedValue({
contentType: 'image/webp',
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
const tool = createDownloadAssetTool('user-1')
const result = await tool.execute('call-1', {
assetId: null,
key: 'files/ast-123/screenshots/shot_5.0s.webp',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'ast-123',
})
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
createdFiles.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/ast-123/screenshots/shot_5.0s.webp',
expectedPath,
)
expect(fs.existsSync(expectedPath)).toBe(true)
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-screenshot-bytes')
expect(result.details.filePath).toBe(path.join('.pi', 'shot_5.0s.webp'))
expect(result.details.key).toBe('files/ast-123/screenshots/shot_5.0s.webp')
expect(result.details.assetId).toBe('ast-123')
expect(result.details.size).toBe(Buffer.from('fake-screenshot-bytes').length)
})
it('should authorize and download original upload key (files/<uploadUlid>/...) via StorageKey', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
id: 'sk-1',
key: 'files/upload-ulid-456/photo.png',
assets: [{ id: 'asset-photo-1' }],
} as unknown as StorageKey & { assets: Asset[] })
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, 'fake-original-photo-bytes')
})
vi.mocked(s3Service.headObject).mockResolvedValue({
contentType: 'image/png',
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
const tool = createDownloadAssetTool('user-1')
const result = await tool.execute('call-1', {
assetId: null,
key: 'files/upload-ulid-456/photo.png',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'asset-photo-1',
})
const expectedPath = path.join(piDir, 'photo.png')
createdFiles.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/upload-ulid-456/photo.png',
expectedPath,
)
expect(fs.existsSync(expectedPath)).toBe(true)
expect(result.details.assetId).toBe('asset-photo-1')
})
it('should fall back to file MIME detection when headObject returns generic application/octet-stream', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
id: 'sk-2',
key: 'files/upload-ulid-789/graphic.png',
assets: [{ id: 'asset-graphic-1' }],
} as unknown as StorageKey & { assets: Asset[] })
vi.mocked(authzService.hasPermission).mockResolvedValue()
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
await fs.promises.writeFile(dest, pngHeader)
})
vi.mocked(s3Service.headObject).mockResolvedValue({
contentType: 'application/octet-stream',
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
const tool = createDownloadAssetTool('user-1')
const result = await tool.execute('call-1', {
assetId: null,
key: 'files/upload-ulid-789/graphic.png',
})
const expectedPath = path.join(piDir, 'graphic.png')
createdFiles.push(expectedPath)
expect(result.details.contentType).toBe('image/png')
})
})
describe('resolveAssetIdFromKey helper unit tests', () => {
it('resolves directly by asset ID', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'ast-999' } as unknown as Asset)
+2 -200
View File
@@ -1,32 +1,8 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
// Storage-key helpers shared by download_asset (operation-extensions) and the media generation tools.
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 { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
import * as fs from 'fs'
import * as path from 'path'
export const downloadAssetSchema = Type.Object(
{
assetId: Type.Union([
Type.String({
description:
'The asset ID of the workspace asset to download to local disk, or null if providing "key".',
}),
Type.Null(),
]),
key: Type.Union([
Type.String({
description:
'The storage S3 key of a specific media artifact (e.g. a screenshot or transcode key from read_asset) to download to local disk, or null if providing "assetId".',
}),
Type.Null(),
]),
},
{ additionalProperties: false },
)
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
export async function resolveAssetIdFromKey(key: string): Promise<string> {
if (!key.startsWith('files/') || key.includes('..')) {
@@ -118,177 +94,3 @@ export async function resolveS3MediaBuffer(
return { buffer, mimeType }
}
export function createDownloadAssetTool(userId: string): AgentTool<typeof downloadAssetSchema> {
return {
name: 'download_asset',
label: 'Download Asset',
description:
'Downloads a workspace asset or specific storage S3 key to the local .pi directory for processing with local scripts or bash commands. ' +
'Provide exactly one of "assetId" (for full assets) or "key" (for intermediate artifacts like screenshots from read_asset). ' +
'Remember to delete the temporary downloaded file when finished.',
parameters: downloadAssetSchema,
execute: async (_toolCallId, params) => {
const { assetId, key } = params
if (!userId) {
throw new Error('User ID is required for authorization.')
}
const hasAssetId = assetId !== null
const hasKey = key !== null
if (hasAssetId === hasKey) {
throw new Error(
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
)
}
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) {
fs.mkdirSync(piDir, { recursive: true })
}
const bucket = process.env.S3_BUCKET || 'shumai'
// Branch A: Download by assetId
if (assetId) {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
let asset = await prisma.asset.findUnique({
where: { id: assetId },
include: { storageKey: true },
})
if (!asset) {
throw new Error(`Asset with ID ${assetId} not found.`)
}
if (asset.type === 'version_stack') {
const latestVersion = await prisma.asset.findFirst({
where: { parentId: asset.id, isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: { storageKey: true },
})
if (latestVersion) {
asset = latestVersion
}
}
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.original?.key) {
mediaKey = mediaInfo.original.key || mediaKey
}
}
if (!mediaKey) {
throw new Error(`No media content found for asset ${assetId}.`)
}
const safeName = sanitizeFilename(asset.name || 'file')
const filename = `${asset.id}_${safeName}`
const targetFilePath = path.join(piDir, filename)
const relativePath = path.join('.pi', filename)
const objectInfo = await s3Service.headObject(bucket, mediaKey).catch(() => null)
await s3Service.downloadToFile(bucket, mediaKey, targetFilePath)
const stat = await fs.promises
.stat(targetFilePath)
.catch(() => ({ size: objectInfo?.size ?? 0 }))
const contentType =
objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream'
? objectInfo.contentType
: readFileMimeType(targetFilePath)
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,
size: stat.size,
},
}
}
// Branch B: Download by S3 storage key
if (key) {
const owningAssetId = await resolveAssetIdFromKey(key)
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: owningAssetId,
})
const rawBasename = path.basename(key)
const safeBasename = sanitizeFilename(rawBasename) || 'downloaded_file'
const filename = safeBasename
const targetFilePath = path.join(piDir, filename)
const relativePath = path.join('.pi', filename)
const objectInfo = await s3Service.headObject(bucket, key).catch(() => null)
await s3Service.downloadToFile(bucket, key, targetFilePath)
const stat = await fs.promises
.stat(targetFilePath)
.catch(() => ({ size: objectInfo?.size ?? 0 }))
const contentType =
objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream'
? objectInfo.contentType
: readFileMimeType(targetFilePath)
return {
content: [
{
type: 'text',
text: `Downloaded storage key "${key}" to "${relativePath}". Remember to delete this temporary file when finished.`,
},
],
details: {
key,
assetId: owningAssetId,
filePath: relativePath,
absolutePath: targetFilePath,
contentType,
size: stat.size,
},
}
}
throw new Error('Invalid download_asset parameters.')
},
}
}
@@ -99,7 +99,7 @@ export async function presentReadForMcp(
if (output.text) {
text += `\n\n${output.text.content}`
if (output.text.truncated) {
text += `\n\n[Content truncated: showing the first part of a ${output.text.size}-byte file.]`
text += `\n\n[Content truncated: showing the first part of a ${output.text.size}-byte file. Use download_asset to get the whole file.]`
}
}
return { content: [{ type: 'text', text }, ...images], structuredContent }
@@ -255,6 +255,43 @@ describe('MCP server and /api/ops (integration)', () => {
expect(await render.json()).toEqual({ error: 'Render not found' })
})
it('gives MCP and CLI callers a download link to the file', async () => {
const client = await connect(reviewerToken)
const result = await client.callTool({
name: 'download_asset',
arguments: { assetIds: [imageId] },
})
expect(result.isError).toBeFalsy()
const viaMcp = result.structuredContent as { files: Array<Record<string, unknown>> }
expect(viaMcp.files).toEqual([
{
assetId: imageId,
name: 'photo.png',
kind: 'original',
size: png.length,
mimeType: 'image/png',
url: expect.any(String),
},
])
const res = await app.request('/api/ops/download_asset', {
method: 'POST',
headers: {
Authorization: `Bearer ${reviewerToken}`,
'Content-Type': 'application/json',
'x-shumai-client': 'cli',
},
body: JSON.stringify({ assetIds: [imageId], proxy: false }),
})
expect(res.status).toBe(200)
const viaCli = (await res.json()) as { files: Array<{ url: string; key?: string }> }
expect(viaCli.files[0].key).toBeUndefined()
const link = new URL(viaCli.files[0].url)
const file = await app.request(link.pathname + link.search)
expect(file.status).toBe(200)
expect(Buffer.from(await file.arrayBuffer()).equals(png)).toBe(true)
})
it('does not let users outside the project read', async () => {
const outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'mcp-outsider@test.com', password: 'pw' },
+2 -1
View File
@@ -55,6 +55,7 @@ describe('MCP server', () => {
expect(tools.map((t) => t.name).sort()).toEqual([
'create_folder',
'delete_asset',
'download_asset',
'get_asset_render',
'list_assets',
'list_projects',
@@ -136,7 +137,7 @@ describe('MCP server', () => {
it('does not expose agent-only capabilities', async () => {
const names = (await client.listTools()).tools.map((t) => t.name)
for (const agentOnly of ['bash', 'read_skill', 'download_asset', 'mcp']) {
for (const agentOnly of ['bash', 'read_skill', 'mcp']) {
expect(names).not.toContain(agentOnly)
}
})
@@ -0,0 +1,245 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AssetType, prisma, type Prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { projectService } from '@shumai/core/src/project/project'
import { s3Service } from '@shumai/core/src/s3/s3'
import { downloadAssetOp, runOperation, type OperationContext } from '@shumai/core/src/operations'
import { READ_URL_EXPIRES_SECONDS } from '@shumai/core/src/asset-read/asset-read'
import { proxyKeyOf } from './asset-download'
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
describe('download_asset Operation', () => {
setupTestDbHooks()
let owner: User
let reviewer: User
let outsider: User
let projectId: string
let rootFolderId: string
const as = (user: User, via: OperationContext['via'] = 'cli'): OperationContext => ({
userId: user.id,
via,
})
beforeEach(async () => {
owner = await prisma.user.create({
data: { name: 'Owner', email: 'dl-owner@test.com', password: 'pw' },
})
reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'dl-reviewer@test.com', password: 'pw' },
})
outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'dl-outsider@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Download Team' } })
await prisma.teamMember.create({ data: { teamId: team.id, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: reviewer.id, role: 'reviewer' },
})
const project = await projectService.createProject(owner, {
teamId: team.id,
name: 'Download Project',
})
projectId = project.id
rootFolderId = project.rootFolder!
vi.spyOn(s3Service, 'presign').mockImplementation(
async (_bucket, key) => `https://signed.example/${key}`,
)
vi.spyOn(s3Service, 'headObject').mockImplementation(
async (_bucket, key) => ({ key, size: 100, contentType: 'application/octet-stream' }) as Head,
)
})
afterEach(() => {
vi.restoreAllMocks()
})
async function createFile(
name: string,
data: Partial<Prisma.AssetUncheckedCreateInput> & { key?: string } = {},
) {
const { key, ...rest } = data
const storageKey = key ? await prisma.storageKey.create({ data: { key } }) : null
return prisma.asset.create({
data: {
name,
type: AssetType.file,
status: 'uploaded',
projectId,
parentId: rootFolderId,
storageKeyId: storageKey?.id,
...rest,
},
})
}
const media = (value: Record<string, unknown>) => value as unknown as PrismaJson.MediaInfo
it('returns the web preview by default and the original with proxy false', async () => {
const photo = await createFile('photo.jpg', {
key: 'files/up-1/photo.jpg',
media: media({ proxyType: 'image', imageTranscodes: [{ key: 'files/p-1/web.webp' }] }),
})
const preview = await runOperation(downloadAssetOp, as(reviewer), { assetIds: [photo.id] })
expect(preview).toEqual({
files: [
{
assetId: photo.id,
name: 'photo.webp',
kind: 'proxy',
size: 100,
mimeType: 'image/webp',
url: 'https://signed.example/files/p-1/web.webp',
},
],
})
expect(s3Service.presign).toHaveBeenCalledWith(
expect.any(String),
'files/p-1/web.webp',
'GET',
true,
'photo.webp',
false,
READ_URL_EXPIRES_SECONDS,
)
const original = await runOperation(downloadAssetOp, as(reviewer), {
assetIds: [photo.id],
proxy: false,
})
expect(original.files[0]).toMatchObject({
name: 'photo.jpg',
kind: 'original',
mimeType: 'image/jpeg',
url: 'https://signed.example/files/up-1/photo.jpg',
})
})
it('renames a video proxy to its extension and falls back to the original without one', async () => {
const clip = await createFile('clip.mov', {
key: 'files/up-2/clip.mov',
media: media({ proxyType: 'video', videoTranscodes: [{ key: 'files/c-1/720p.mp4' }] }),
})
const song = await createFile('song.wav', {
key: 'files/up-3/song.wav',
media: media({ proxyType: 'audio', original: { key: 'files/up-3/song.wav' } }),
})
const archive = await createFile('bundle.zip', { key: 'files/up-4/bundle.zip' })
const { files } = await runOperation(downloadAssetOp, as(owner), {
assetIds: [clip.id, song.id, archive.id, clip.id],
})
expect(files.map((f) => [f.name, f.kind])).toEqual([
['clip.mp4', 'proxy'],
['song.wav', 'original'],
['bundle.zip', 'original'],
])
})
it('downloads the latest version of a version stack', async () => {
const stack = await prisma.asset.create({
data: {
name: 'diagram',
type: AssetType.version_stack,
status: 'uploaded',
projectId,
parentId: rootFolderId,
},
})
await createFile('diagram_v1.png', {
parentId: stack.id,
sortIndex: 'b',
key: 'files/v1/diagram_v1.png',
})
const v2 = await createFile('diagram_v2.png', {
parentId: stack.id,
sortIndex: 'a',
key: 'files/v2/diagram_v2.png',
})
const { files } = await runOperation(downloadAssetOp, as(owner), { assetIds: [stack.id] })
expect(files).toEqual([expect.objectContaining({ assetId: v2.id, name: 'diagram_v2.png' })])
})
it('only gives storage keys to the built-in agent', async () => {
const doc = await createFile('notes.md', { key: 'files/up-5/notes.md' })
for (const via of ['mcp', 'cli', 'api'] as const) {
const { files } = await runOperation(downloadAssetOp, as(owner, via), { assetIds: [doc.id] })
expect(files[0]).not.toHaveProperty('key')
}
const { files } = await runOperation(downloadAssetOp, as(owner, 'agent'), {
assetIds: [doc.id],
})
expect(files[0].key).toBe('files/up-5/notes.md')
})
it('rejects folders', async () => {
const folder = await prisma.asset.create({
data: {
name: 'Renders',
type: AssetType.folder,
status: 'uploaded',
projectId,
parentId: rootFolderId,
},
})
await expect(
runOperation(downloadAssetOp, as(owner), { assetIds: [folder.id] }),
).rejects.toMatchObject({
status: 400,
message: `Asset ${folder.id} ("Renders") is a folder. Download the files inside it instead.`,
})
})
it('rejects users without Read access before resolving anything', async () => {
const doc = await createFile('notes.md', { key: 'files/up-6/notes.md' })
await expect(
runOperation(downloadAssetOp, as(outsider), { assetIds: [doc.id] }),
).rejects.toMatchObject({ status: 403 })
expect(s3Service.headObject).not.toHaveBeenCalled()
expect(s3Service.presign).not.toHaveBeenCalled()
})
it('reports files missing from storage', async () => {
const doc = await createFile('notes.md', { key: 'files/up-7/notes.md' })
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('NotFound'))
await expect(
runOperation(downloadAssetOp, as(owner), { assetIds: [doc.id] }),
).rejects.toMatchObject({
status: 404,
message: `The file for asset ${doc.id} ("notes.md") is missing from storage.`,
})
})
it.each([[[]], [Array.from({ length: 51 }, (_, i) => `a-${i}`)]])(
'rejects %# asset ID lists outside 1 to 50',
async (assetIds) => {
await expect(runOperation(downloadAssetOp, as(owner), { assetIds })).rejects.toMatchObject({
status: 400,
})
},
)
})
describe('proxyKeyOf', () => {
it.each([
[{ proxyType: 'image', imageTranscodes: [{ key: 'i.webp' }] }, 'i.webp'],
[{ proxyType: '3d', imageTranscodes: [{ key: 'views.webp' }] }, 'views.webp'],
[{ proxyType: 'video', videoTranscodes: [{ key: 'v.mp4' }] }, 'v.mp4'],
[{ proxyType: 'video', videoTranscodes: [], videoPreview: { key: 'p.mp4' } }, 'p.mp4'],
[{ proxyType: 'pdf', original: { key: 'doc.pdf' } }, 'doc.pdf'],
[{ proxyType: 'image', imageTranscodes: [] }, undefined],
])('%o → %s', (value, expected) => {
expect(proxyKeyOf(value as unknown as PrismaJson.MediaInfo)).toBe(expected)
})
it('has no proxy without media', () => {
expect(proxyKeyOf(null)).toBeUndefined()
})
})
@@ -0,0 +1,140 @@
import * as path from 'path'
import type { DownloadAssetOutput } from '@shumai/operations'
import { AssetType, prisma, type Prisma } from '@shumai/db'
import { HTTPException } from 'hono/http-exception'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { READ_URL_EXPIRES_SECONDS } from '@shumai/core/src/asset-read/asset-read'
import { storageBucket } from '@shumai/core/src/asset-read/types'
const assetWithStorage = { storageKey: true } satisfies Prisma.AssetInclude
type AssetRecord = Prisma.AssetGetPayload<{ include: typeof assetWithStorage }>
const FOLDER_TYPES: ReadonlySet<string> = new Set([
AssetType.folder,
AssetType.root,
AssetType.share_root,
AssetType.share,
])
/**
* The web preview version of a file: the web image for images (and the 4-view image for 3D
* models), the transcoded video for videos, otherwise none. Matches what the built-in agent
* has always downloaded by default.
*/
export function proxyKeyOf(media: PrismaJson.MediaInfo | null): string | undefined {
if (!media) return undefined
if (media.proxyType === 'image' || media.imageTranscodes?.length) {
return media.imageTranscodes?.[0]?.key || undefined
}
if (media.proxyType === 'video' || media.videoTranscodes?.length || media.videoPreview?.key) {
return media.videoTranscodes?.[0]?.key || media.videoPreview?.key || undefined
}
return media.original?.key || undefined
}
/** `clip.mov` downloaded as its `.mp4` proxy is saved as `clip.mp4`. */
function nameForKey(assetName: string, key: string, isOriginal: boolean): string {
if (isOriginal) return assetName
const ext = path.extname(key)
if (!ext) return assetName
const current = path.extname(assetName)
return `${current ? assetName.slice(0, -current.length) : assetName}${ext}`
}
export class AssetDownloadService {
/**
* Download links for files and version stacks. The caller checks Read on every ID first.
* Folders are rejected; version stacks resolve to their latest version and symlinks to
* their target.
*/
async getDownloads(
assetIds: string[],
opts: { proxy: boolean; includeKeys: boolean },
): Promise<DownloadAssetOutput> {
const files: DownloadAssetOutput['files'] = []
for (const assetId of [...new Set(assetIds)]) {
const asset = await this.resolveFile(assetId)
const originalKey = asset.storageKey?.key
const proxyKey = opts.proxy
? proxyKeyOf(asset.media as PrismaJson.MediaInfo | null)
: undefined
const key = proxyKey || originalKey
if (!key) {
throw new HTTPException(400, {
message: `Asset ${assetId} ("${asset.name}") has no file to download.`,
})
}
const isOriginal = key === originalKey
const name = nameForKey(asset.name || 'file', key, isOriginal)
const bucket = storageBucket()
const info = await s3Service.headObject(bucket, key).catch(() => null)
if (!info) {
throw new HTTPException(404, {
message: `The file for asset ${assetId} ("${asset.name}") is missing from storage.`,
})
}
const mimeType =
info.contentType && info.contentType !== 'application/octet-stream'
? info.contentType
: getFileMimeType(null, key, 'application/octet-stream')
files.push({
assetId: asset.id,
name,
kind: isOriginal ? 'original' : 'proxy',
size: info.size,
mimeType,
url: await s3Service.presign(
bucket,
key,
'GET',
true,
name,
false,
READ_URL_EXPIRES_SECONDS,
),
...(opts.includeKeys ? { key } : {}),
})
}
return { files }
}
private async resolveFile(assetId: string): Promise<AssetRecord> {
let asset = await prisma.asset.findUnique({
where: { id: assetId },
include: assetWithStorage,
})
if (asset?.type === AssetType.symlink && asset.targetId) {
asset = await prisma.asset.findUnique({
where: { id: asset.targetId },
include: assetWithStorage,
})
}
if (!asset || asset.isDeleted) {
throw new HTTPException(404, { message: `Asset with ID ${assetId} not found.` })
}
if (FOLDER_TYPES.has(asset.type)) {
throw new HTTPException(400, {
message: `Asset ${assetId} ("${asset.name}") is a folder. Download the files inside it instead.`,
})
}
if (asset.type === AssetType.version_stack) {
const latest = await prisma.asset.findFirst({
where: { parentId: asset.id, isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: assetWithStorage,
})
if (!latest) {
throw new HTTPException(400, {
message: `Version stack ${assetId} ("${asset.name}") has no versions to download.`,
})
}
asset = latest
}
return asset
}
}
export const assetDownloadService = new AssetDownloadService()
@@ -590,6 +590,33 @@ describe('read_asset and get_asset_render Operations', () => {
expect(waitFor).toHaveBeenLastCalledWith(expect.anything(), budget)
})
it('points unsupported files to the download command of each surface', async () => {
const video = await prisma.asset.findUniqueOrThrow({ where: { id: videoId } })
const zip = await prisma.asset.create({
data: {
name: 'bundle.zip',
type: AssetType.file,
status: 'uploaded',
mediaType: 'application/zip',
projectId: video.projectId,
parentId: video.parentId,
},
})
const prefix = `Unsupported asset type for read_asset. Asset ${zip.id} has media type "application/zip".`
for (const via of ['agent', 'mcp', 'api'] as const) {
await expect(runOperation(readAssetOp, as(via), { assetId: zip.id })).rejects.toMatchObject({
status: 400,
message: `${prefix} Use download_asset to download this file.`,
})
}
// The CLI has no tools; it names the command instead.
await expect(runOperation(readAssetOp, as('cli'), { assetId: zip.id })).rejects.toMatchObject({
status: 400,
message: `${prefix} Run \`shumai-cli download ${zip.id}\` to download it.`,
})
})
it('rejects invalid input before touching the asset', async () => {
await expect(
runOperation(readAssetOp, as('mcp'), {
+8 -4
View File
@@ -11,7 +11,13 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
import { s3Service } from '@shumai/core/src/s3/s3'
import { resolveAnnotationsById } from './annotations'
import { findReader, getReader, readers } from './registry'
import { badRequest, storageBucket, type ReadableAsset, type ReadResult } from './types'
import {
badRequest,
storageBucket,
UnsupportedAssetTypeError,
type ReadableAsset,
type ReadResult,
} from './types'
/** Who is reading: a user (Read permission required) or the autofill system agent. */
export type ReadAccess =
@@ -81,9 +87,7 @@ export class AssetReadService {
const reader = findReader(asset)
if (!reader) {
throw badRequest(
`Unsupported asset type for read_asset. Asset ${asset.id} has media type "${asset.mediaTypeLower || 'unknown'}". Use download_asset to download this file to disk.`,
)
throw new UnsupportedAssetTypeError(asset.id, asset.mediaTypeLower)
}
// Reject configs meant for another type (empty objects like `imageConfig: {}` are ignored).
+1 -1
View File
@@ -10,5 +10,5 @@ export {
export { resolveAnnotationsById } from './annotations'
export { findReader, getReader, readers } from './registry'
export { isPlainTextAsset, MAX_TEXT_BYTES, MAX_TEXT_LINES } from './readers/document'
export { storageBucket } from './types'
export { storageBucket, UnsupportedAssetTypeError } from './types'
export type { AssetReader, ReadableAsset, ReadImage, ReadPlan, ReadResult } from './types'
+13
View File
@@ -91,6 +91,19 @@ export interface AssetReader<TKind extends ReaderKind = ReaderKind> {
): ReadResult
}
/** No reader handles this asset; the message points to download_asset. */
export class UnsupportedAssetTypeError extends HTTPException {
constructor(
readonly assetId: string,
readonly mediaType: string,
hint = 'Use download_asset to download this file.',
) {
super(400, {
message: `Unsupported asset type for read_asset. Asset ${assetId} has media type "${mediaType || 'unknown'}". ${hint}`,
})
}
}
export function badRequest(message: string): HTTPException {
return new HTTPException(400, { message })
}
@@ -0,0 +1,19 @@
import { downloadAsset } from '@shumai/operations'
import { assetDownloadService } from '@shumai/core/src/asset-download/asset-download'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const downloadAssetOp = implementOperation(downloadAsset, {
authz: (input) =>
[...new Set(input.assetIds)].map((id) => ({
permission: Permission.Read,
type: ResourceType.Asset,
id,
})),
execute: (input, ctx) =>
assetDownloadService.getDownloads(input.assetIds, {
proxy: input.proxy !== false,
// The built-in agent saves files into its sandbox straight from storage.
includeKeys: ctx.via === 'agent',
}),
})
@@ -1,5 +1,9 @@
import { getAssetRender, readAsset, type Via } from '@shumai/operations'
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
import {
assetReadService,
toAssetReadOutput,
UnsupportedAssetTypeError,
} from '@shumai/core/src/asset-read'
import { implementOperation } from '../implement'
/**
@@ -31,9 +35,21 @@ export const readAssetOp = implementOperation(readAsset, {
authz: () => [],
execute: async (input, ctx) => {
const { maxWaitSeconds, ...request } = input
const outcome = await assetReadService.read({ kind: 'user', userId: ctx.userId }, request, {
waitBudgetMs: waitBudgetMs(ctx.via, maxWaitSeconds),
})
const outcome = await assetReadService
.read({ kind: 'user', userId: ctx.userId }, request, {
waitBudgetMs: waitBudgetMs(ctx.via, maxWaitSeconds),
})
.catch((err: unknown) => {
// CLI users download with a command, not a tool.
if (err instanceof UnsupportedAssetTypeError && ctx.via === 'cli') {
throw new UnsupportedAssetTypeError(
err.assetId,
err.mediaType,
`Run \`shumai-cli download ${err.assetId}\` to download it.`,
)
}
throw err
})
return toAssetReadOutput(outcome, { includeKeys: SERVER_PRESENTED.has(ctx.via) })
},
})
+1
View File
@@ -12,6 +12,7 @@ export { runOperation } from './run'
export { getOperation, getOperationsForSurface, operations } from './registry'
export { createFolderOp } from './asset/create-folder'
export { deleteAssetOp } from './asset/delete-asset'
export { downloadAssetOp } from './asset/download-asset'
export { listAssetsOp } from './asset/list-assets'
export { moveAssetsOp } from './asset/move-assets'
export {
+2
View File
@@ -1,6 +1,7 @@
import type { OperationName, Surface } from '@shumai/operations'
import { createFolderOp } from './asset/create-folder'
import { deleteAssetOp } from './asset/delete-asset'
import { downloadAssetOp } from './asset/download-asset'
import { listAssetsOp } from './asset/list-assets'
import { moveAssetsOp } from './asset/move-assets'
import { getAssetRenderOp, readAssetOp } from './asset/read-asset'
@@ -34,6 +35,7 @@ export const operations = defineRegistry([
deleteAssetOp,
readAssetOp,
getAssetRenderOp,
downloadAssetOp,
] as const)
const operationsByName = new Map<string, Operation>()
+18 -1
View File
@@ -22,7 +22,8 @@ type ExecutableTool = {
/**
* read_asset end to end: real render workflows (frames, PDF pages) through the reader
* pipeline, the pending → get_asset_render path, and the agent tool in a chat workflow.
* pipeline, the pending → get_asset_render path, and the agent's read_asset and
* download_asset tools in a chat workflow.
* Only the model call is mocked.
*/
describe('Workflow E2E - read_asset', () => {
@@ -56,10 +57,20 @@ describe('Workflow E2E - read_asset', () => {
})
const text = result.content.find((c) => c.type === 'text')?.text ?? ''
const images = result.content.filter((c) => c.type === 'image' && c.data)
// download_asset saves the original into the agent's sandbox (.pi)
const download = this.getTools().find((t) => t.name === 'download_asset') as unknown as
ExecutableTool | undefined
const downloaded = download
? await download.execute('call-2', { assetIds: [videoAssetId], proxy: false })
: undefined
const savedPath = (
downloaded as unknown as { details?: { files?: Array<{ absolutePath: string }> } }
)?.details?.files?.[0]?.absolutePath
const summary = [
`images:${images.length}`,
`frames:${(text.match(/- Frame at /g) ?? []).length}`,
`render_tool:${hasRenderTool ? 'present' : 'absent'}`,
`downloaded:${savedPath ?? 'none'}`,
].join('|')
return {
content: [{ type: 'text', text: summary }],
@@ -283,6 +294,12 @@ describe('Workflow E2E - read_asset', () => {
expect(reply?.message).toContain('images:2')
expect(reply?.message).toContain('frames:2')
expect(reply?.message).toContain('render_tool:present')
const savedPath = /downloaded:([^|]+)/.exec(reply?.message ?? '')?.[1] ?? 'none'
expect(savedPath).not.toBe('none')
expect(
fs.readFileSync(savedPath).equals(fs.readFileSync(path.join(fixturesDir, 'small.mp4'))),
).toBe(true)
fs.rmSync(savedPath, { force: true })
const render = await prisma.workflowTask.findFirstOrThrow({
where: { assetId: video.id, type: 'transcode_screenshot' },
@@ -0,0 +1,60 @@
import { z } from 'zod'
import { defineOperation } from '../define'
/** Most assets one download call accepts. */
export const MAX_DOWNLOAD_ASSETS = 50
const downloadFileSchema = z.object({
assetId: z
.string()
.describe('The asset this file belongs to (the latest version for a version stack).'),
name: z.string().describe('File name to save it as.'),
kind: z
.enum(['proxy', 'original'])
.describe('"proxy" is the web preview version; "original" is the uploaded file.'),
size: z.number().describe('Size in bytes.'),
mimeType: z.string(),
url: z.string().describe('Short-lived download link (about 1 hour).'),
/** Storage key; only returned to Shumai's built-in agent. */
key: z.string().optional(),
})
export const downloadAssetOutputSchema = z.object({
files: z.array(downloadFileSchema),
})
export type DownloadAssetOutput = z.infer<typeof downloadAssetOutputSchema>
export const downloadAsset = defineOperation({
name: 'download_asset',
title: 'Download Asset',
description:
`Gets download links for up to ${MAX_DOWNLOAD_ASSETS} files. ` +
'By default it returns the web preview version (proxy) when there is one, e.g. the transcoded video or the web image, which is smaller and easier to process; set proxy to false for the original uploaded file. ' +
'Files without a preview (e.g. audio, archives, text) always return the original. ' +
'A version stack returns its latest version. Folders are not supported: download the files inside them instead. ' +
'Links expire after about an hour.',
input: z.object({
assetIds: z
.array(z.string().min(1))
.min(1)
.max(MAX_DOWNLOAD_ASSETS)
.describe(`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}).`),
proxy: z
.boolean()
.optional()
.describe(
'Download the web preview version when there is one (default true). Set to false for the original uploaded file.',
),
}),
output: downloadAssetOutputSchema,
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: true, destructive: false, idempotent: true },
cli: {
command: ['download'],
description:
'Download files into a folder (the current folder by default). Saves the web preview version when there is one; use --original for the uploaded file.',
positional: ['assetIds'],
// The CLI exposes `--original` instead of a `--proxy` flag that is on by default.
omit: ['proxy'],
},
})
+1
View File
@@ -8,4 +8,5 @@ export { listAssets } from './asset/list-assets'
export { moveAssets } from './asset/move-assets'
export { renameAsset } from './asset/rename-asset'
export * from './asset/read-asset'
export * from './asset/download-asset'
export { listProjects } from './project/list-projects'
+3
View File
@@ -19,6 +19,7 @@ describe('operation registry', () => {
expect(operationDefinitions.map((d) => d.name).sort()).toEqual([
'create_folder',
'delete_asset',
'download_asset',
'get_asset_render',
'list_assets',
'list_projects',
@@ -47,6 +48,7 @@ describe('operation registry', () => {
expect(destructive.map((d) => d.name)).toEqual(['delete_asset'])
const readOnly = operationDefinitions.filter((d) => d.annotations.readOnly)
expect(readOnly.map((d) => d.name).sort()).toEqual([
'download_asset',
'get_asset_render',
'list_assets',
'list_projects',
@@ -96,6 +98,7 @@ describe('operation registry', () => {
['delete_asset', ['delete', 'rm']],
['read_asset', ['read']],
['get_asset_render', ['render']],
['download_asset', ['download']],
])
})
+2
View File
@@ -1,5 +1,6 @@
import { createFolder } from './asset/create-folder'
import { deleteAsset } from './asset/delete-asset'
import { downloadAsset } from './asset/download-asset'
import { listAssets } from './asset/list-assets'
import { moveAssets } from './asset/move-assets'
import { getAssetRender, readAsset } from './asset/read-asset'
@@ -20,6 +21,7 @@ export const operationDefinitions = [
deleteAsset,
readAsset,
getAssetRender,
downloadAsset,
] as const
export type RegisteredOperationDefinition = (typeof operationDefinitions)[number]
@@ -112,6 +112,11 @@ const BUILTIN_TOOLS = [
name: () => m.agent_tool_create_version_name(),
description: () => m.agent_tool_create_version_desc(),
},
{
id: 'download_asset',
name: () => m.agent_tool_download_asset_name(),
description: () => m.agent_tool_download_asset_desc(),
},
{
id: 'generate_image',
name: () => m.agent_tool_generate_image_name(),
+2
View File
@@ -609,6 +609,8 @@
"agent_tool_read_skill_desc": "Allows the agent to load and read skill definitions to perform specialized actions.",
"agent_tool_read_asset_name": "Read Asset",
"agent_tool_read_asset_desc": "Allows the agent to view and inspect images, video frames, and document pages.",
"agent_tool_download_asset_name": "Download Asset",
"agent_tool_download_asset_desc": "Allows the agent to download files to its workspace to process them with scripts or terminal commands.",
"agent_tool_get_asset_render_name": "Get Asset Render",
"agent_tool_get_asset_render_desc": "Allows the agent to pick up video frames or document pages that took longer to render.",
"agent_tool_list_projects_name": "List Projects",
+2
View File
@@ -609,6 +609,8 @@
"agent_tool_read_skill_desc": "允许智能体加载和读取技能定义以执行特定操作。",
"agent_tool_read_asset_name": "读取资源",
"agent_tool_read_asset_desc": "允许智能体查看和分析图片、视频画面和文档页面。",
"agent_tool_download_asset_name": "下载资源",
"agent_tool_download_asset_desc": "允许智能体将文件下载到其工作区,以便用脚本或终端命令处理。",
"agent_tool_get_asset_render_name": "获取资源渲染结果",
"agent_tool_get_asset_render_desc": "允许智能体获取渲染耗时较长的视频画面或文档页面。",
"agent_tool_list_projects_name": "列出项目",