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
@@ -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>()