mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 05:54:44 +00:00
feat: expose read_asset and download_asset on MCP and the CLI (#499)
* feat(asset-read): expose read_asset on MCP and the CLI Enable the mcp and cli surfaces for read_asset and get_asset_render. - MCP: add per-Operation tool extensions. The read presenter attaches up to 8 images (2 MB each) inline, lists image links, supports inlineImages: false, and tells the model to call get_asset_render when a render is pending. Storage keys are stripped from the result. - CLI: generated commands can flatten object inputs into prefixed flags (cli.flatten) and omit fields (cli.omit); add per-command extensions. New `read` and `render` commands print image links, download them with --out, and support --no-wait with a printed `render <taskId>` hint. - Round frame timestamps in labels to 3 decimals. * fix(mcp): make tool input schemas portable to single-type dialects Nullable inputs were emitted as `type: ["number", "null"]` (or a `null` anyOf branch), which clients that map tool schemas onto an OpenAPI-style subset (e.g. Gemini function declarations) may reject. - Make read_asset's startPage, endPage, and degree optional instead of nullable. - Move null handling into a shared dropNullOptionals helper in @shumai/operations that also strips nulls inside nested config objects. The agent uses it, and the MCP server applies it before the SDK validates arguments, so models that send null keep working. - Test that no Operation input schema (and no listed MCP tool) uses a nullable type. * 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:
@@ -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()
|
||||
@@ -547,7 +547,8 @@ describe('read_asset and get_asset_render Operations', () => {
|
||||
|
||||
it.each([
|
||||
['agent', true],
|
||||
['mcp', false],
|
||||
// The MCP presenter attaches image bytes, then strips the keys (packages/api)
|
||||
['mcp', true],
|
||||
['cli', false],
|
||||
['api', false],
|
||||
] as const)('via %s includes storage keys: %s', async (via, includesKey) => {
|
||||
@@ -589,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'), {
|
||||
|
||||
@@ -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).
|
||||
@@ -265,8 +269,8 @@ export class AssetReadService {
|
||||
export const assetReadService = new AssetReadService()
|
||||
|
||||
/**
|
||||
* Converts a read outcome into the Operation output. Storage keys are included only for
|
||||
* Shumai's built-in agent; every image gets a short-lived link.
|
||||
* Converts a read outcome into the Operation output. Every image gets a short-lived link;
|
||||
* storage keys (and the source file link) only when the result is presented server-side.
|
||||
*/
|
||||
export async function toAssetReadOutput(
|
||||
outcome: ReadOutcome,
|
||||
|
||||
@@ -10,4 +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, UnsupportedAssetTypeError } from './types'
|
||||
export type { AssetReader, ReadableAsset, ReadImage, ReadPlan, ReadResult } from './types'
|
||||
|
||||
@@ -99,7 +99,7 @@ export const documentReader: AssetReader<'document'> = {
|
||||
}
|
||||
if (startPage !== null || endPage !== null) {
|
||||
throw badRequest(
|
||||
'startPage and endPage must be null when docConfig mode is "text". To inspect specific page numbers, use mode: "pages".',
|
||||
'startPage and endPage must be left out when docConfig mode is "text". To inspect specific page numbers, use mode: "pages".',
|
||||
)
|
||||
}
|
||||
if (!isPlainTextAsset(asset.mediaTypeLower, asset.filenameLower)) {
|
||||
|
||||
@@ -122,6 +122,16 @@ describe('videoReader', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('rounds frame timestamps in labels', () => {
|
||||
const result = videoReader.collect!(
|
||||
video,
|
||||
{ start: 0, end: 8, count: 3 },
|
||||
{ screenshots: [{ key: 's/1.webp', timestamp: 2.6666666666666665 }] },
|
||||
{},
|
||||
)
|
||||
expect(result.images[0].label).toBe('Frame at 2.667s')
|
||||
})
|
||||
|
||||
it('fails when the render produced no frames', () => {
|
||||
expect(() =>
|
||||
videoReader.collect!(video, { start: 0, end: 1, count: 1 }, { screenshots: [] }, {}),
|
||||
@@ -140,11 +150,9 @@ describe('model3dReader', () => {
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
})
|
||||
|
||||
it('accepts null as "show the overview"', async () => {
|
||||
expect(() =>
|
||||
model3dReader.validate(model, { degree: null }, { hasAnnotation: false }),
|
||||
).not.toThrow()
|
||||
const plan = await model3dReader.plan(model, { degree: null }, noAnnotation)
|
||||
it('shows the overview when no degree is given', async () => {
|
||||
expect(() => model3dReader.validate(model, {}, { hasAnnotation: false })).not.toThrow()
|
||||
const plan = await model3dReader.plan(model, {}, noAnnotation)
|
||||
expect(plan.status).toBe('ready')
|
||||
})
|
||||
|
||||
|
||||
@@ -67,7 +67,8 @@ export const videoReader: AssetReader<'video'> = {
|
||||
details: [],
|
||||
images: screenshots.map((shot) => ({
|
||||
key: shot.key,
|
||||
label: `Frame at ${shot.timestamp}s`,
|
||||
// Evenly spaced timestamps can be long fractions (2.6666666666666665)
|
||||
label: `Frame at ${Number(shot.timestamp.toFixed(3))}s`,
|
||||
mimeType: getFileMimeType(null, shot.key, 'image/webp'),
|
||||
})),
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
/**
|
||||
@@ -13,6 +17,13 @@ export const READ_WAIT_BUDGET_MS: Record<Via, number> = {
|
||||
api: 20_000,
|
||||
}
|
||||
|
||||
/**
|
||||
* Surfaces whose results are presented on the server (agent tools, MCP tool results). They get
|
||||
* storage keys so the presenter can attach image bytes; the MCP presenter strips the keys
|
||||
* before anything leaves the server. CLI and REST callers only get links.
|
||||
*/
|
||||
const SERVER_PRESENTED: ReadonlySet<Via> = new Set(['agent', 'mcp'])
|
||||
|
||||
/** `maxWaitSeconds` can only shorten the surface budget. */
|
||||
export function waitBudgetMs(via: Via, maxWaitSeconds: number | undefined): number {
|
||||
const budget = READ_WAIT_BUDGET_MS[via]
|
||||
@@ -24,10 +35,22 @@ 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),
|
||||
})
|
||||
return toAssetReadOutput(outcome, { includeKeys: ctx.via === 'agent' })
|
||||
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) })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -38,6 +61,6 @@ export const getAssetRenderOp = implementOperation(getAssetRender, {
|
||||
const outcome = await assetReadService.getRender(ctx.userId, input.taskId, {
|
||||
waitBudgetMs: waitBudgetMs(ctx.via, input.maxWaitSeconds),
|
||||
})
|
||||
return toAssetReadOutput(outcome, { includeKeys: ctx.via === 'agent' })
|
||||
return toAssetReadOutput(outcome, { includeKeys: SERVER_PRESENTED.has(ctx.via) })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>()
|
||||
|
||||
Reference in New Issue
Block a user