feat(asset-read): rewrite read_asset as a reader registry and Operations

Replace the monolithic agent read_asset tool with a reader registry in
@shumai/core/src/asset-read (model3d, image, video, document) behind a
shared pipeline that handles access checks, version stacks, annotations,
render tasks, and waiting.

- Add read_asset and get_asset_render Operations (agent surface only).
  Renders that outlast the caller's wait budget return "pending" with the
  workflow task ID; the read request is stored on the task payload so
  get_asset_render works across restarts and instances (requester only).
- Add workflowService.waitFor and presign expiry support.
- Keep agent output compatible via an agent tool extension (s3KeyOnly,
  image blocks, session image details); autofill keeps its team-scoped tool.
- Cap video frames at 20 per call; add the get_asset_render agent toggle.
This commit is contained in:
yiling
2026-10-26 15:07:10 +08:00
parent d904395202
commit 4581058e0d
40 changed files with 3787 additions and 2229 deletions
@@ -0,0 +1,64 @@
import { prisma } from '@shumai/db'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
/**
* Resolve the visual markup referenced by an annotation ID: a comment (comments mode) or an
* agent session entry (1-on-1 chat mode). The annotation must belong to `assetId`.
*/
export async function resolveAnnotationsById(
assetId: string,
annotationId?: string | null,
): Promise<{ annotations: PrismaJson.AnnotationList | null; timestamp: number | null }> {
if (!annotationId) {
return { annotations: null, timestamp: null }
}
// 1. Check AssetComment table (Comments Mode)
const comment = await prisma.assetComment.findUnique({
where: { id: annotationId },
select: { assetId: true, annotation: true, second: true },
})
if (comment) {
if (comment.assetId !== assetId) {
throw new HTTPException(400, {
message: `Annotation "${annotationId}" belongs to asset "${comment.assetId}", not target asset "${assetId}".`,
})
}
const list = comment.annotation
const annotations =
Array.isArray(list) && list.length > 0 ? (list as PrismaJson.AnnotationList) : null
return { annotations, timestamp: comment.second }
}
// 2. Check AgentSessionEntry table (1-on-1 Chat Mode)
const entry = await prisma.agentSessionEntry.findUnique({
where: { id: annotationId },
select: { assetId: true, data: true },
})
if (entry) {
const details = (entry.data as Record<string, unknown> | null)?.details as
ShumaiMessageContext | undefined
const entryAssetId = entry.assetId || details?.currentAsset?.id
if (entryAssetId && entryAssetId !== assetId) {
throw new HTTPException(400, {
message: `Annotation "${annotationId}" belongs to asset "${entryAssetId}", not target asset "${assetId}".`,
})
}
const list = details?.annotations
const annotations =
Array.isArray(list) && list.length > 0 ? (list as unknown as PrismaJson.AnnotationList) : null
let timestamp: number | null = null
if (details?.position?.type === 'time') {
timestamp = details.position.seconds
} else if (details?.position?.type === 'degree') {
timestamp = degreeToSecond(details.position.degree)
} else if (details?.position?.type === 'page') {
timestamp = details.position.page
}
return { annotations, timestamp }
}
throw new HTTPException(404, { message: `Annotation with ID "${annotationId}" not found.` })
}
@@ -0,0 +1,601 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
AssetType,
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
type Prisma,
type User,
} from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService } from '@shumai/workflow-core'
import { projectService } from '@shumai/core/src/project/project'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getAssetRenderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
import type { OperationContext } from '@shumai/core/src/operations'
import { assetReadService, READ_URL_EXPIRES_SECONDS, toAssetReadOutput } from './asset-read'
describe('AssetReadService', () => {
setupTestDbHooks()
let owner: User
let reviewer: User
let outsider: User
let teamId: string
let projectId: string
let rootFolderId: string
const user = (u: User) => ({ kind: 'user' as const, userId: u.id })
const now = { waitBudgetMs: 0 }
beforeEach(async () => {
owner = await prisma.user.create({
data: { name: 'Owner', email: 'read-owner@test.com', password: 'pw' },
})
reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'read-reviewer@test.com', password: 'pw' },
})
outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'read-outsider@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Read Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
const project = await projectService.createProject(owner, { teamId, name: 'Read Project' })
projectId = project.id
rootFolderId = project.rootFolder!
vi.spyOn(s3Service, 'presign').mockImplementation(
async (_bucket, key) => `https://signed.example/${key}`,
)
vi.spyOn(s3Service, 'getObject').mockImplementation(async (_bucket, key) => ({
buffer: Buffer.from(`content of ${key}`),
contentType: 'text/plain',
}))
})
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 imageMedia = {
proxyType: 'image',
imageTranscodes: [{ key: 'proxy/photo.webp' }],
} as unknown as PrismaJson.MediaInfo
async function createVideo() {
return createFile('clip.mp4', {
mediaType: 'video/mp4',
media: { proxyType: 'video' } as unknown as PrismaJson.MediaInfo,
key: 'raw/clip.mp4',
})
}
describe('access', () => {
it('lets a reviewer read an image without creating a render task', async () => {
const image = await createFile('photo.png', { mediaType: 'image/png', media: imageMedia })
const outcome = await assetReadService.read(user(reviewer), { assetId: image.id }, now)
expect(outcome).toMatchObject({
status: 'ready',
kind: 'image',
asset: { id: image.id, name: 'photo.png' },
result: {
summary: `Image asset "photo.png" (ID: ${image.id}):`,
images: [{ key: 'proxy/photo.webp', label: 'Image', mimeType: 'image/webp' }],
},
})
expect(await prisma.workflowTask.count({ where: { assetId: image.id } })).toBe(0)
})
it('rejects users without Read access before creating anything', async () => {
const video = await createVideo()
await expect(
assetReadService.read(
user(outsider),
{ assetId: video.id, videoConfig: { start: 0, end: 1, count: 1 } },
now,
),
).rejects.toMatchObject({ status: 403 })
expect(await prisma.workflowTask.count({ where: { assetId: video.id } })).toBe(0)
})
it('confines the autofill agent to its team and target asset', async () => {
const image = await createFile('photo.png', { mediaType: 'image/png', media: imageMedia })
const other = await createFile('other.png', { mediaType: 'image/png', media: imageMedia })
const ok = await assetReadService.read(
{ kind: 'autofill', teamId, targetAssetId: image.id },
{ assetId: image.id },
now,
)
expect(ok.status).toBe('ready')
await expect(
assetReadService.read(
{ kind: 'autofill', teamId, targetAssetId: image.id },
{ assetId: other.id },
now,
),
).rejects.toThrow(`autofill agent can only read target asset ${image.id}`)
await expect(
assetReadService.read(
{ kind: 'autofill', teamId: 'another-team', targetAssetId: image.id },
{ assetId: image.id },
now,
),
).rejects.toThrow(`does not belong to team another-team`)
})
})
it('reads 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',
mediaType: 'image/png',
key: 'raw/v1.png',
})
const v2 = await createFile('diagram_v2.png', {
parentId: stack.id,
sortIndex: 'a',
mediaType: 'image/png',
key: 'raw/v2.png',
})
const outcome = await assetReadService.read(user(owner), { assetId: stack.id }, now)
expect(outcome.asset.id).toBe(v2.id)
expect(outcome.status === 'ready' && outcome.result.images[0].key).toBe('raw/v2.png')
})
describe('reader selection and options', () => {
it.each([
['model.glb', 'model/gltf-binary', 'model3d'],
['photo.psd', 'image/vnd.adobe.photoshop', 'image'],
['clip.mov', 'video/quicktime', 'video'],
['doc.pdf', 'application/pdf', 'document'],
['notes.md', 'text/markdown', 'document'],
['script.ts', null, 'document'],
])('reads %s with the %s reader', async (name, mediaType, kind) => {
const asset = await createFile(name, { mediaType, key: `raw/${name}` })
// An empty-object config of the wrong type is ignored; the error names the right reader.
const error = await assetReadService
.read(user(owner), { assetId: asset.id, imageConfig: {}, config3d: { degree: 7 } }, now)
.catch((err: unknown) => err)
if (kind === 'model3d') {
expect(error).toMatchObject({
message: expect.stringContaining('Invalid turntable degree'),
})
} else {
expect(error).toMatchObject({
status: 400,
message: expect.stringContaining(`Asset ${asset.id} is a`),
})
expect((error as Error).message).toContain('do not pass config3d')
}
})
it('rejects unsupported files', async () => {
const zip = await createFile('bundle.zip', { mediaType: 'application/zip' })
await expect(assetReadService.read(user(owner), { assetId: zip.id }, now)).rejects.toThrow(
'Unsupported asset type for read_asset',
)
})
it('reads text content and reports truncation', async () => {
const doc = await createFile('notes.md', { mediaType: 'text/markdown', key: 'raw/notes.md' })
const outcome = await assetReadService.read(
user(owner),
{ assetId: doc.id, docConfig: { mode: 'text' } },
now,
)
expect(outcome).toMatchObject({
status: 'ready',
kind: 'document',
result: {
images: [],
text: {
content: 'content of raw/notes.md',
truncated: false,
size: 'content of raw/notes.md'.length,
key: 'raw/notes.md',
mimeType: 'text/markdown',
},
},
})
})
it('skips reading text when includeContent is false', async () => {
const doc = await createFile('notes.md', { mediaType: 'text/markdown', key: 'raw/notes.md' })
const outcome = await assetReadService.read(
user(owner),
{ assetId: doc.id, docConfig: { mode: 'text' }, includeContent: false },
now,
)
expect(s3Service.getObject).not.toHaveBeenCalled()
expect(outcome.status === 'ready' && outcome.result.text?.content).toBe('')
})
})
describe('render tasks', () => {
it('stores the read request on the task and returns pending when the budget runs out', async () => {
const video = await createVideo()
const outcome = await assetReadService.read(
user(reviewer),
{ assetId: video.id, videoConfig: { start: 0, end: 4, count: 2 } },
now,
)
expect(outcome).toMatchObject({ status: 'pending', kind: 'video', retryAfterSeconds: 5 })
const taskId = outcome.status === 'pending' ? outcome.taskId : ''
const task = await prisma.workflowTask.findUniqueOrThrow({ where: { id: taskId } })
expect(task).toMatchObject({
assetId: video.id,
projectId,
type: WorkflowTaskType.transcode_screenshot,
status: WorkflowTaskStatus.pending,
})
expect(task.payload).toEqual({
projectId,
screenshot: { start: 0, end: 4, count: 2, commentTimestamp: null, annotations: null },
assetRead: {
reader: 'video',
options: { start: 0, end: 4, count: 2 },
requestedBy: reviewer.id,
},
})
})
it('overlays annotations from a comment on the image', async () => {
const image = await createFile('photo.png', { mediaType: 'image/png', media: imageMedia })
const annotation = [
{
type: 'box',
color: '#ff0000',
points: [
[0, 0],
[10, 10],
],
},
] as unknown as PrismaJson.AnnotationList
const comment = await prisma.assetComment.create({
data: { assetId: image.id, creatorId: owner.id, message: 'here', annotation },
})
const outcome = await assetReadService.read(
user(owner),
{ assetId: image.id, annotationId: comment.id },
now,
)
expect(outcome).toMatchObject({ status: 'pending', kind: 'image', retryAfterSeconds: 3 })
const task = await prisma.workflowTask.findFirstOrThrow({ where: { assetId: image.id } })
expect(task.type).toBe(WorkflowTaskType.transcode_image_annotation)
expect(task.payload?.imageAnnotation).toEqual({ annotations: annotation })
expect(task.payload?.assetRead).toMatchObject({ reader: 'image', annotationId: comment.id })
})
it('rejects annotations from another asset', async () => {
const image = await createFile('photo.png', { mediaType: 'image/png', media: imageMedia })
const other = await createFile('other.png', { mediaType: 'image/png', media: imageMedia })
const comment = await prisma.assetComment.create({
data: { assetId: other.id, creatorId: owner.id, message: 'elsewhere' },
})
await expect(
assetReadService.read(user(owner), { assetId: image.id, annotationId: comment.id }, now),
).rejects.toMatchObject({ status: 400 })
})
it('stores reader context for 3D angles and collects it later', async () => {
const model = await createFile('robot.glb', {
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
} as unknown as PrismaJson.MediaInfo,
})
const pending = await assetReadService.read(
user(owner),
{ assetId: model.id, config3d: { degree: 90 } },
now,
)
const taskId = pending.status === 'pending' ? pending.taskId : ''
const task = await prisma.workflowTask.findUniqueOrThrow({ where: { id: taskId } })
expect(task.payload?.assetRead?.context).toEqual({ degree: 90, hasMarkup: false })
await prisma.workflowTask.update({
where: { id: taskId },
data: {
status: WorkflowTaskStatus.completed,
output: { screenshots: [{ key: 'shots/90.webp', timestamp: 1 }] },
},
})
const ready = await assetReadService.getRender(owner.id, taskId, now)
expect(ready).toMatchObject({
status: 'ready',
kind: 'model3d',
result: {
summary: `3D asset "robot.glb" (ID: ${model.id}) view at 90°:`,
images: [{ key: 'shots/90.webp', label: 'View at 90°' }],
},
})
})
})
describe('getRender', () => {
async function pendingVideoRead(by: User) {
const video = await createVideo()
const outcome = await assetReadService.read(
user(by),
{ assetId: video.id, videoConfig: { start: 0, end: 4, count: 2 } },
now,
)
if (outcome.status !== 'pending') throw new Error('expected pending')
return { video, taskId: outcome.taskId }
}
it('stays pending until the task completes, then returns the frames', async () => {
const { taskId } = await pendingVideoRead(reviewer)
expect(await assetReadService.getRender(reviewer.id, taskId, now)).toMatchObject({
status: 'pending',
taskId,
})
await prisma.workflowTask.update({
where: { id: taskId },
data: {
status: WorkflowTaskStatus.completed,
output: {
screenshots: [
{ key: 'shots/0.webp', timestamp: 0 },
{ key: 'shots/4.webp', timestamp: 4 },
],
},
},
})
const ready = await assetReadService.getRender(reviewer.id, taskId, now)
expect(ready).toMatchObject({
status: 'ready',
result: {
summary: 'Extracted 2 frame(s) from "clip.mp4" (0s - 4s):',
images: [
{ key: 'shots/0.webp', label: 'Frame at 0s', mimeType: 'image/webp' },
{ key: 'shots/4.webp', label: 'Frame at 4s', mimeType: 'image/webp' },
],
},
})
})
it('surfaces a failed render', async () => {
const { taskId } = await pendingVideoRead(owner)
await prisma.workflowTask.update({
where: { id: taskId },
data: { status: WorkflowTaskStatus.failed, output: { error: 'ffmpeg exploded' } },
})
await expect(assetReadService.getRender(owner.id, taskId, now)).rejects.toThrow(
'ffmpeg exploded',
)
})
it('returns 404 to anyone but the requester', async () => {
const { taskId } = await pendingVideoRead(reviewer)
await expect(assetReadService.getRender(owner.id, taskId, now)).rejects.toMatchObject({
status: 404,
message: 'Render not found',
})
})
it('returns 404 once the requester loses access', async () => {
const { taskId } = await pendingVideoRead(reviewer)
await prisma.teamMember.deleteMany({ where: { userId: reviewer.id } })
await expect(assetReadService.getRender(reviewer.id, taskId, now)).rejects.toMatchObject({
status: 404,
})
})
it('returns 404 for unknown tasks and tasks that are not asset reads', async () => {
const video = await createVideo()
const other = await prisma.workflowTask.create({
data: {
assetId: video.id,
projectId,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
payload: { projectId },
},
})
await expect(assetReadService.getRender(owner.id, other.id, now)).rejects.toMatchObject({
status: 404,
})
await expect(assetReadService.getRender(owner.id, 'nope', now)).rejects.toMatchObject({
status: 404,
})
})
})
describe('toAssetReadOutput', () => {
it('returns short-lived links and only includes storage keys when asked', async () => {
const image = await createFile('photo.png', { mediaType: 'image/png', media: imageMedia })
const outcome = await assetReadService.read(user(owner), { assetId: image.id }, now)
const external = await toAssetReadOutput(outcome, { includeKeys: false })
expect(external.images).toEqual([
{ label: 'Image', mimeType: 'image/webp', url: 'https://signed.example/proxy/photo.webp' },
])
expect(s3Service.presign).toHaveBeenCalledWith(
expect.any(String),
'proxy/photo.webp',
'GET',
false,
undefined,
false,
READ_URL_EXPIRES_SECONDS,
)
const internal = await toAssetReadOutput(outcome, { includeKeys: true })
expect(internal.images[0].key).toBe('proxy/photo.webp')
})
it('hides the text storage key and link from external callers', async () => {
const doc = await createFile('notes.md', { mediaType: 'text/markdown', key: 'raw/notes.md' })
const outcome = await assetReadService.read(
user(owner),
{ assetId: doc.id, docConfig: { mode: 'text' } },
now,
)
const external = await toAssetReadOutput(outcome, { includeKeys: false })
expect(external.text).toEqual({
content: 'content of raw/notes.md',
truncated: false,
size: 23,
mimeType: 'text/markdown',
})
const internal = await toAssetReadOutput(outcome, { includeKeys: true })
expect(internal.text).toMatchObject({
key: 'raw/notes.md',
url: 'https://signed.example/raw/notes.md',
})
})
})
})
describe('read_asset and get_asset_render Operations', () => {
setupTestDbHooks()
let owner: User
let videoId: string
let imageId: string
const as = (via: OperationContext['via']): OperationContext => ({ userId: owner.id, via })
beforeEach(async () => {
owner = await prisma.user.create({
data: { name: 'Owner', email: 'read-op-owner@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Read Op Team' } })
await prisma.teamMember.create({ data: { teamId: team.id, userId: owner.id, role: 'owner' } })
const project = await projectService.createProject(owner, {
teamId: team.id,
name: 'Read Op Project',
})
const base = {
type: AssetType.file,
status: 'uploaded' as const,
projectId: project.id,
parentId: project.rootFolder!,
}
videoId = (
await prisma.asset.create({
data: {
...base,
name: 'clip.mp4',
mediaType: 'video/mp4',
media: { proxyType: 'video' } as unknown as PrismaJson.MediaInfo,
},
})
).id
imageId = (
await prisma.asset.create({
data: {
...base,
name: 'photo.png',
mediaType: 'image/png',
media: {
proxyType: 'image',
imageTranscodes: [{ key: 'proxy/photo.webp' }],
} as unknown as PrismaJson.MediaInfo,
},
})
).id
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example/x')
})
afterEach(() => {
vi.restoreAllMocks()
})
it.each([
['agent', true],
['mcp', false],
['cli', false],
['api', false],
] as const)('via %s includes storage keys: %s', async (via, includesKey) => {
const output = await runOperation(readAssetOp, as(via), { assetId: imageId })
expect(output.status).toBe('ready')
expect(output.images[0].url).toBe('https://signed.example/x')
expect('key' in output.images[0]).toBe(includesKey)
})
it.each([
['agent', undefined, 60_000],
['mcp', undefined, 20_000],
['cli', undefined, 120_000],
['api', undefined, 20_000],
['cli', 5, 5_000],
['mcp', 600, 20_000],
['agent', 0, 0],
] as const)('via %s with maxWaitSeconds %s waits %sms', async (via, maxWaitSeconds, budget) => {
const waitFor = vi
.spyOn(workflowService, 'waitFor')
.mockImplementation(async (task) => ({ task, done: false }))
const output = await runOperation(readAssetOp, as(via), {
assetId: videoId,
videoConfig: { start: 0, end: 1, count: 1 },
maxWaitSeconds,
})
expect(waitFor).toHaveBeenCalledWith(expect.anything(), budget)
expect(output).toMatchObject({
status: 'pending',
summary: 'Rendering is still in progress for "clip.mp4".',
asset: { id: videoId, kind: 'video' },
images: [],
taskId: expect.any(String),
retryAfterSeconds: 5,
})
await runOperation(getAssetRenderOp, as(via), { taskId: output.taskId!, maxWaitSeconds })
expect(waitFor).toHaveBeenLastCalledWith(expect.anything(), budget)
})
it('rejects invalid input before touching the asset', async () => {
await expect(
runOperation(readAssetOp, as('mcp'), {
assetId: videoId,
videoConfig: { start: 0, end: 1 },
}),
).rejects.toMatchObject({ status: 400 })
expect(await prisma.workflowTask.count({ where: { assetId: videoId } })).toBe(0)
})
})
+342
View File
@@ -0,0 +1,342 @@
import {
readerOptionSchemas,
type AssetReadOutput,
type ReaderConfigKey,
type ReaderKind,
} from '@shumai/operations'
import { AssetType, prisma, WorkflowTaskStatus, type Prisma, type WorkflowTask } from '@shumai/db'
import { HTTPException } from 'hono/http-exception'
import { workflowService } from '@shumai/workflow-core'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
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'
/** Who is reading: a user (Read permission required) or the autofill system agent. */
export type ReadAccess =
{ kind: 'user'; userId: string } | { kind: 'autofill'; teamId?: string; targetAssetId?: string }
export type ReadAssetRequest = {
assetId: string
annotationId?: string
includeContent?: boolean
} & { [K in ReaderConfigKey]?: Record<string, unknown> }
export type ReadOutcome =
| { status: 'ready'; asset: ReadableAsset; kind: ReaderKind; result: ReadResult }
| {
status: 'pending'
asset: ReadableAsset
kind: ReaderKind
taskId: string
retryAfterSeconds: number
}
/** Lifetime of image links handed to callers outside the server. */
export const READ_URL_EXPIRES_SECONDS = 3600
const assetWithStorage = { storageKey: true } satisfies Prisma.AssetInclude
type AssetRecord = Prisma.AssetGetPayload<{ include: typeof assetWithStorage }>
function toReadable(asset: AssetRecord): ReadableAsset {
return {
id: asset.id,
name: asset.name,
projectId: asset.projectId,
mediaType: asset.mediaType,
mediaTypeLower: asset.mediaType?.toLowerCase() || '',
filenameLower: asset.name?.toLowerCase() || '',
storageKey: asset.storageKey?.key ?? null,
media: asset.media as PrismaJson.MediaInfo | null,
}
}
function hasContent(value: unknown): boolean {
return (
value !== null &&
value !== undefined &&
typeof value === 'object' &&
Object.values(value).some((v) => v !== null && v !== undefined)
)
}
function notFoundRender(): HTTPException {
return new HTTPException(404, { message: 'Render not found' })
}
/**
* Shared pipeline behind `read_asset` and `get_asset_render`: access checks, version stacks,
* reader selection, option validation, annotations, render tasks, and waiting. Readers in
* `./readers` only contain the type-specific logic.
*/
export class AssetReadService {
async read(
access: ReadAccess,
request: ReadAssetRequest,
opts: { waitBudgetMs: number },
): Promise<ReadOutcome> {
await this.checkAccess(access, request.assetId)
const asset = await this.loadLatestVersion(request.assetId)
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.`,
)
}
// Reject configs meant for another type (empty objects like `imageConfig: {}` are ignored).
const configKey = readerOptionSchemas[reader.kind].key
for (const other of readers) {
const otherKey = readerOptionSchemas[other.kind].key
if (otherKey !== configKey && hasContent(request[otherKey])) {
throw badRequest(
`Asset ${asset.id} is a ${reader.label}. ${reader.configHint}; do not pass ${otherKey}.`,
)
}
}
const options = request[configKey]
reader.validate(asset, options as never, { hasAnnotation: Boolean(request.annotationId) })
const annotation = request.annotationId
? {
annotationId: request.annotationId,
...(await resolveAnnotationsById(asset.id, request.annotationId)),
}
: null
const plan = await reader.plan(asset, options as never, {
annotation,
includeContent: request.includeContent !== false,
})
if (plan.status === 'ready') {
return { status: 'ready', asset, kind: reader.kind, result: plan.result }
}
const projectId = asset.projectId || 'none'
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId,
type: plan.task.type,
status: WorkflowTaskStatus.pending,
payload: {
projectId,
...plan.task.spec,
assetRead: {
reader: reader.kind,
options: options ?? undefined,
annotationId: request.annotationId,
context: plan.context,
requestedBy: access.kind === 'user' ? access.userId : undefined,
},
},
},
})
return this.finish(task, asset, opts.waitBudgetMs)
}
/** Completes a read that returned `pending`. Only the requesting user can fetch it. */
async getRender(
userId: string,
taskId: string,
opts: { waitBudgetMs: number },
): Promise<ReadOutcome> {
const task = await prisma.workflowTask.findUnique({ where: { id: taskId } })
const request = task?.payload?.assetRead
if (!task || !request || !task.assetId || !userId || request.requestedBy !== userId) {
throw notFoundRender()
}
try {
await authzService.hasPermission({
user: { id: userId },
permission: Permission.Read,
type: ResourceType.Asset,
id: task.assetId,
})
} catch {
// Don't reveal that the task exists to someone who can no longer see the asset.
throw notFoundRender()
}
const record = await prisma.asset.findUnique({
where: { id: task.assetId },
include: assetWithStorage,
})
if (!record) throw notFoundRender()
return this.finish(task, toReadable(record), opts.waitBudgetMs)
}
private async finish(
task: WorkflowTask,
asset: ReadableAsset,
waitBudgetMs: number,
): Promise<ReadOutcome> {
const request = task.payload!.assetRead!
const reader = getReader(request.reader)
const { task: latest, done } = await workflowService.waitFor(task, waitBudgetMs)
if (!done) {
return {
status: 'pending',
asset,
kind: reader.kind,
taskId: task.id,
retryAfterSeconds: reader.kind === 'video' || reader.kind === 'document' ? 5 : 3,
}
}
if (!reader.collect) {
throw new Error(`Reader "${reader.kind}" cannot collect render results`)
}
const result = reader.collect(
asset,
request.options as never,
latest.output ?? {},
request.context ?? {},
)
return { status: 'ready', asset, kind: reader.kind, result }
}
private async checkAccess(access: ReadAccess, assetId: string): Promise<void> {
if (access.kind === 'user') {
if (!access.userId) {
throw new HTTPException(401, { message: 'User ID is required for authorization.' })
}
await authzService.hasPermission({
user: { id: access.userId },
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
return
}
// Autofill system agent: no user; confined to its team and target asset.
if (!access.targetAssetId) {
throw new HTTPException(403, {
message: 'Target asset ID is required for autofill agent authorization.',
})
}
if (!access.teamId) {
throw new HTTPException(403, {
message: 'Team ID is required for autofill agent authorization.',
})
}
const asset = await prisma.asset.findUnique({
where: { id: assetId },
include: { project: true, teamRootFolder: true },
})
if (!asset) {
throw new HTTPException(404, { message: `Asset with ID ${assetId} not found.` })
}
const assetTeamId = asset.project?.teamId || asset.teamRootFolder?.id
if (!assetTeamId || assetTeamId !== access.teamId) {
throw new HTTPException(403, {
message: `Access denied: asset ${assetId} does not belong to team ${access.teamId}.`,
})
}
if (asset.id !== access.targetAssetId && asset.parentId !== access.targetAssetId) {
throw new HTTPException(403, {
message: `Access denied: autofill agent can only read target asset ${access.targetAssetId}.`,
})
}
}
private async loadLatestVersion(assetId: string): Promise<ReadableAsset> {
let asset = await prisma.asset.findUnique({
where: { id: assetId },
include: assetWithStorage,
})
if (!asset) {
throw new HTTPException(404, { message: `Asset with ID ${assetId} not found.` })
}
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) asset = latest
}
return toReadable(asset)
}
}
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.
*/
export async function toAssetReadOutput(
outcome: ReadOutcome,
opts: { includeKeys: boolean },
): Promise<AssetReadOutput> {
const asset = {
id: outcome.asset.id,
name: outcome.asset.name,
kind: outcome.kind,
mediaType: outcome.asset.mediaType,
}
if (outcome.status === 'pending') {
return {
status: 'pending',
summary: `Rendering is still in progress for "${outcome.asset.name}".`,
asset,
details: [],
images: [],
taskId: outcome.taskId,
retryAfterSeconds: outcome.retryAfterSeconds,
}
}
const bucket = storageBucket()
const { result } = outcome
const images = await Promise.all(
result.images.map(async (image) => ({
label: image.label,
mimeType: image.mimeType,
url: await s3Service.presign(
bucket,
image.key,
'GET',
false,
undefined,
false,
READ_URL_EXPIRES_SECONDS,
),
...(opts.includeKeys ? { key: image.key } : {}),
})),
)
const text = result.text
? {
content: result.text.content,
truncated: result.text.truncated,
size: result.text.size,
mimeType: result.text.mimeType,
...(opts.includeKeys
? {
key: result.text.key,
url: await s3Service.presign(
bucket,
result.text.key,
'GET',
true,
outcome.asset.name || undefined,
false,
READ_URL_EXPIRES_SECONDS,
),
}
: {}),
}
: undefined
return {
status: 'ready',
summary: result.summary,
asset,
details: result.details,
images,
...(text ? { text } : {}),
}
}
+13
View File
@@ -0,0 +1,13 @@
export {
assetReadService,
AssetReadService,
READ_URL_EXPIRES_SECONDS,
toAssetReadOutput,
type ReadAccess,
type ReadAssetRequest,
type ReadOutcome,
} from './asset-read'
export { resolveAnnotationsById } from './annotations'
export { findReader, getReader, readers } from './registry'
export { isPlainTextAsset, MAX_TEXT_BYTES, MAX_TEXT_LINES } from './readers/document'
export type { AssetReader, ReadableAsset, ReadImage, ReadPlan, ReadResult } from './types'
@@ -0,0 +1,188 @@
import { MAX_RENDER_ITEMS } from '@shumai/operations'
import { WorkflowTaskType } from '@shumai/db'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { s3Service } from '@shumai/core/src/s3/s3'
import { badRequest, storageBucket, type AssetReader } from '../types'
export const MAX_TEXT_BYTES = 50 * 1024
export const MAX_TEXT_LINES = 1000
const TEXT_MEDIA_TYPES = new Set([
'application/json',
'application/javascript',
'application/typescript',
'application/xml',
'application/x-yaml',
])
const TEXT_EXTENSIONS = [
'.txt',
'.md',
'.markdown',
'.json',
'.csv',
'.tsv',
'.js',
'.ts',
'.tsx',
'.jsx',
'.html',
'.htm',
'.css',
'.scss',
'.yaml',
'.yml',
'.xml',
'.py',
'.rb',
'.go',
'.rs',
'.c',
'.cpp',
'.h',
'.hpp',
'.java',
'.sh',
'.bash',
'.zsh',
'.sql',
]
export function isPlainTextAsset(mediaType: string, filename: string): boolean {
if (mediaType.startsWith('text/') || TEXT_MEDIA_TYPES.has(mediaType)) {
return true
}
return TEXT_EXTENSIONS.some((ext) => filename.endsWith(ext))
}
/** Truncate to the line and byte limits; returns the kept text and whether anything was cut. */
export function truncateText(raw: string): { content: string; truncated: boolean } {
let content = raw
let truncated = false
const lines = content.split('\n')
if (lines.length > MAX_TEXT_LINES) {
content = lines.slice(0, MAX_TEXT_LINES).join('\n')
truncated = true
}
if (Buffer.byteLength(content, 'utf-8') > MAX_TEXT_BYTES) {
content = Buffer.from(content, 'utf-8').subarray(0, MAX_TEXT_BYTES).toString('utf-8')
truncated = true
}
return { content, truncated }
}
/** PDFs and text files: rendered page images ("pages") or raw text content ("text"). */
export const documentReader: AssetReader<'document'> = {
kind: 'document',
label: 'document',
configHint: "Pass 'docConfig: { mode, startPage, endPage }'",
matches: (asset) =>
asset.media?.proxyType === 'pdf' ||
asset.mediaTypeLower === 'application/pdf' ||
isPlainTextAsset(asset.mediaTypeLower, asset.filenameLower),
validate(asset, options, { hasAnnotation }) {
if (!options) {
throw badRequest(
'docConfig with mode ("pages" or "text") is required when inspecting document/PDF assets.',
)
}
const startPage = options.startPage ?? null
const endPage = options.endPage ?? null
if (options.mode === 'text') {
if (hasAnnotation) {
throw badRequest(
'annotationId cannot be used with docConfig mode "text" because visual markups can only be rendered on visual pages. Use docConfig: { mode: "pages", startPage: ..., endPage: ... } instead.',
)
}
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".',
)
}
if (!isPlainTextAsset(asset.mediaTypeLower, asset.filenameLower)) {
throw badRequest(
`Asset "${asset.name}" is a binary PDF/document and cannot be read as raw text. Please call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: ... } to view its visual pages.`,
)
}
return
}
if (startPage === null || endPage === null) {
throw badRequest('startPage and endPage are required when docConfig mode is "pages".')
}
if (startPage < 1) {
throw badRequest(`Invalid page range: start page (${startPage}) must be at least 1.`)
}
if (startPage > endPage) {
throw badRequest(
`Invalid page range: start page (${startPage}) must be less than or equal to end page (${endPage}).`,
)
}
const requested = endPage - startPage + 1
if (requested > MAX_RENDER_ITEMS) {
throw badRequest(
`Page range (${requested} pages requested) exceeds the maximum limit of ${MAX_RENDER_ITEMS} pages per request.`,
)
}
},
async plan(asset, options, { annotation, includeContent }) {
// validate() guarantees options are present and consistent
const opts = options!
if (opts.mode === 'text') {
const key = asset.storageKey
if (!key) {
throw new Error(`No media content found for asset ${asset.id}.`)
}
const mimeType = asset.mediaType || getFileMimeType(null, asset.name || key, 'text/plain')
let text = { content: '', truncated: false, size: 0, key, mimeType }
if (includeContent) {
const { buffer } = await s3Service.getObject(storageBucket(), key)
text = { ...truncateText(buffer.toString('utf-8')), size: buffer.length, key, mimeType }
}
return {
status: 'ready',
result: {
summary: `Document "${asset.name}" (ID: ${asset.id}):`,
details: [],
images: [],
text,
},
}
}
return {
status: 'render',
task: {
type: WorkflowTaskType.transcode_pdf_pages,
spec: {
pdfPages: {
start: opts.startPage!,
end: opts.endPage!,
commentTimestamp: annotation?.timestamp ?? null,
annotations: annotation?.annotations ?? null,
},
},
},
}
},
collect(asset, options, output) {
const pages = output.pages as Array<{ key: string; page: number }> | undefined
if (!pages || pages.length === 0) {
throw new Error('No PDF page images were generated.')
}
return {
summary: `Rendered ${pages.length} page(s) of "${asset.name}" (Pages ${options!.startPage} to ${options!.endPage}):`,
details: [],
images: pages.map((page) => ({
key: page.key,
label: `Page ${page.page}`,
mimeType: getFileMimeType(null, page.key, 'image/webp'),
})),
}
},
}
@@ -0,0 +1,61 @@
import { WorkflowTaskType } from '@shumai/db'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import type { AssetReader } from '../types'
/** Images (including PSD): the web proxy, or a copy with the annotation drawn on top. */
export const imageReader: AssetReader<'image'> = {
kind: 'image',
label: 'image',
configHint: "Pass 'imageConfig: {}' or no config",
matches: (asset) =>
asset.media?.proxyType === 'image' ||
asset.mediaTypeLower.startsWith('image/') ||
asset.filenameLower.endsWith('.psd'),
validate() {},
async plan(asset, _options, { annotation }) {
const key = asset.media?.imageTranscodes?.[0]?.key || asset.storageKey
if (!key) {
throw new Error('No media content found for this asset.')
}
if (annotation?.annotations && annotation.annotations.length > 0) {
return {
status: 'render',
task: {
type: WorkflowTaskType.transcode_image_annotation,
spec: { imageAnnotation: { annotations: annotation.annotations } },
},
}
}
return {
status: 'ready',
result: {
summary: `Image asset "${asset.name}" (ID: ${asset.id}):`,
details: [],
images: [
{
key,
label: 'Image',
mimeType: getFileMimeType(null, key, asset.mediaType || 'image/png'),
},
],
},
}
},
collect(asset, _options, output) {
const key = typeof output.key === 'string' ? output.key : null
if (!key) {
throw new Error('Image annotation transcode workflow failed to output S3 key.')
}
return {
summary: `Image asset "${asset.name}" (ID: ${asset.id}) with visual markups overlaid:`,
details: [],
images: [{ key, label: 'Image with markups', mimeType: 'image/webp' }],
}
},
}
@@ -0,0 +1,112 @@
import { WorkflowTaskType } from '@shumai/db'
import { is3dModel } from '@shumai/core/src/utils/mime'
import {
degreeToSecond,
isValidTurntableDegree,
secondToDegree,
} from '@shumai/core/src/utils/model3d'
import { badRequest, type AssetReader, type ReadResult } from '../types'
const QUADRANT_LEGEND = [
'Orthogonal 4-view composite image (2x2 grid across 360° rotation):',
'- Top-Left quadrant: Front view (0°)',
'- Top-Right quadrant: Right side view (90°)',
'- Bottom-Left quadrant: Back view (180°)',
'- Bottom-Right quadrant: Left side view (270°)',
]
function angleSummary(name: string, id: string, degree: number, hasMarkup: boolean): string {
return hasMarkup
? `3D asset "${name}" (ID: ${id}) view at ${degree}° with visual markups overlaid:`
: `3D asset "${name}" (ID: ${id}) view at ${degree}°:`
}
/** 3D models: the 4-view composite, or one turntable angle rendered from the turntable video. */
export const model3dReader: AssetReader<'model3d'> = {
kind: 'model3d',
label: '3D model',
configHint: "To inspect specific angles pass 'config3d: { degree: ... }'",
matches: (asset) =>
asset.media?.proxyType === '3d' || is3dModel(asset.mediaTypeLower, asset.filenameLower),
validate(_asset, options) {
const degree = options?.degree
if (degree !== undefined && degree !== null && !isValidTurntableDegree(degree)) {
throw badRequest(
`Invalid turntable degree: ${degree}. Degree must be an integer multiple of 15 between 0 and 345 (e.g. 0, 15, 30, 45, ..., 345).`,
)
}
},
async plan(asset, options, { annotation }) {
const requestedDegree = options?.degree ?? null
const annotations = annotation?.annotations ?? null
const commentTimestamp = annotation?.timestamp ?? null
if (annotation && commentTimestamp !== null) {
const commentDegree = secondToDegree(commentTimestamp)
if (requestedDegree !== null && requestedDegree !== commentDegree) {
throw badRequest(
`Annotation "${annotation.annotationId}" was drawn at ${commentDegree}°, but degree ${requestedDegree}° was specified. Do not pass a conflicting degree with annotationId.`,
)
}
}
if (requestedDegree !== null || annotation) {
if (!asset.media?.videoTranscodes || asset.media.videoTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its turntable video (turntable.mp4) is missing.`,
)
}
const second =
requestedDegree !== null ? degreeToSecond(requestedDegree) : (commentTimestamp ?? 0)
const degree = requestedDegree ?? secondToDegree(second)
return {
status: 'render',
task: {
type: WorkflowTaskType.transcode_screenshot,
spec: {
screenshot: {
start: second,
end: second,
count: 1,
commentTimestamp: second,
annotations: annotations ?? undefined,
},
},
},
context: { degree, hasMarkup: Boolean(annotations && annotations.length > 0) },
}
}
const key = asset.media?.imageTranscodes?.[0]?.key
if (!asset.media?.imageTranscodes || asset.media.imageTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its 4-views image (views.webp) is missing.`,
)
}
if (!key) {
throw new Error(`Asset ${asset.id} is a 3D model, but its 4-views image key is missing.`)
}
const result: ReadResult = {
summary: `3D asset "${asset.name}" (ID: ${asset.id}):`,
details: QUADRANT_LEGEND,
images: [{ key, label: '4-view composite', mimeType: 'image/webp' }],
}
return { status: 'ready', result }
},
collect(asset, _options, output, context) {
const degree = Number(context.degree)
const screenshots = output.screenshots as Array<{ key: string }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error(`Failed to extract 3D turntable frame for asset ${asset.id} at ${degree}°.`)
}
return {
summary: angleSummary(asset.name, asset.id, degree, context.hasMarkup === true),
details: [],
images: [{ key: screenshots[0].key, label: `View at ${degree}°`, mimeType: 'image/webp' }],
}
},
}
@@ -0,0 +1,223 @@
import { describe, expect, it } from 'vitest'
import { READER_KINDS, readerOptionSchemas } from '@shumai/operations'
import { findReader, getReader, readers } from '../registry'
import type { ReadableAsset } from '../types'
import { documentReader, isPlainTextAsset, MAX_TEXT_BYTES, truncateText } from './document'
import { imageReader } from './image'
import { model3dReader } from './model3d'
import { videoReader } from './video'
function asset(overrides: Partial<ReadableAsset> & { name: string }): ReadableAsset {
const mediaType = overrides.mediaType ?? null
return {
id: 'asset-1',
projectId: 'project-1',
storageKey: null,
media: null,
mediaType,
mediaTypeLower: mediaType?.toLowerCase() ?? '',
filenameLower: overrides.name.toLowerCase(),
...overrides,
}
}
const noAnnotation = { annotation: null, includeContent: true }
describe('reader registry', () => {
it('has exactly one reader per declared kind, each with a config field', () => {
expect(readers.map((r) => r.kind).sort()).toEqual([...READER_KINDS].sort())
for (const kind of READER_KINDS) {
expect(getReader(kind).kind).toBe(kind)
expect(readerOptionSchemas[kind].key).toMatch(/Config$|^config3d$/)
}
})
it.each([
[{ name: 'robot.glb', mediaType: 'model/gltf-binary' }, 'model3d'],
// 3D models also have image transcodes; the 3D reader must win.
[{ name: 'robot.png', mediaType: 'image/png', media: { proxyType: '3d' } }, 'model3d'],
[{ name: 'photo.JPG', mediaType: 'IMAGE/JPEG' }, 'image'],
[{ name: 'layers.psd', mediaType: 'application/octet-stream' }, 'image'],
[{ name: 'clip.webm', mediaType: 'video/webm' }, 'video'],
[{ name: 'slides.pdf', mediaType: 'application/pdf' }, 'document'],
[{ name: 'data.csv', mediaType: null }, 'document'],
[{ name: 'config.json', mediaType: 'application/json' }, 'document'],
] as const)('%o is read by %s', (overrides, kind) => {
expect(findReader(asset(overrides as Partial<ReadableAsset> & { name: string }))?.kind).toBe(
kind,
)
})
it('has no reader for archives', () => {
expect(findReader(asset({ name: 'bundle.zip', mediaType: 'application/zip' }))).toBeUndefined()
})
})
describe('imageReader', () => {
it('prefers the web proxy over the original', async () => {
const plan = await imageReader.plan(
asset({
name: 'photo.png',
mediaType: 'image/png',
storageKey: 'raw/photo.png',
media: { imageTranscodes: [{ key: 'proxy/photo.webp' }] } as PrismaJson.MediaInfo,
}),
undefined,
noAnnotation,
)
expect(plan).toMatchObject({
status: 'ready',
result: { images: [{ key: 'proxy/photo.webp', mimeType: 'image/webp' }] },
})
})
it('fails without any stored content', async () => {
await expect(
imageReader.plan(asset({ name: 'photo.png' }), undefined, noAnnotation),
).rejects.toThrow('No media content found')
})
it('requires the annotated key from the render', () => {
expect(() => imageReader.collect!(asset({ name: 'photo.png' }), undefined, {}, {})).toThrow(
'failed to output S3 key',
)
})
})
describe('videoReader', () => {
const video = asset({ name: 'clip.mp4', mediaType: 'video/mp4' })
it.each([
[{ start: -1, end: 2, count: 1 }, 'must be non-negative'],
[{ start: 3, end: 2, count: 1 }, 'must be less than or equal to end'],
[{ start: 0, end: 2, count: 0 }, 'must be at least 1'],
[{ start: 0, end: 2, count: 21 }, 'exceeds the maximum of 20 frames'],
])('rejects %o', (options, message) => {
expect(() => videoReader.validate(video, options, { hasAnnotation: false })).toThrow(message)
})
it('accepts exactly 20 frames', () => {
expect(() =>
videoReader.validate(video, { start: 0, end: 60, count: 20 }, { hasAnnotation: false }),
).not.toThrow()
})
it('renders frames through the screenshot workflow with the annotation', async () => {
const plan = await videoReader.plan(
video,
{ start: 1, end: 3, count: 2 },
{
annotation: { annotationId: 'c1', annotations: [], timestamp: 2 },
includeContent: true,
},
)
expect(plan).toEqual({
status: 'render',
task: {
type: 'transcode_screenshot',
spec: {
screenshot: { start: 1, end: 3, count: 2, commentTimestamp: 2, annotations: [] },
},
},
})
})
it('fails when the render produced no frames', () => {
expect(() =>
videoReader.collect!(video, { start: 0, end: 1, count: 1 }, { screenshots: [] }, {}),
).toThrow('No screenshots were generated.')
})
})
describe('model3dReader', () => {
const model = asset({
name: 'robot.glb',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
imageTranscodes: [{ key: 'proxy/views.webp' }],
} 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)
expect(plan.status).toBe('ready')
})
it('carries the angle to collect through the task context', async () => {
const plan = await model3dReader.plan(model, { degree: 180 }, noAnnotation)
expect(plan).toMatchObject({
status: 'render',
context: { degree: 180, hasMarkup: false },
})
const result = model3dReader.collect!(
model,
{ degree: 180 },
{ screenshots: [{ key: 'shots/180.webp' }] },
{ degree: 180, hasMarkup: false },
)
expect(result.images).toEqual([
{ key: 'shots/180.webp', label: 'View at 180°', mimeType: 'image/webp' },
])
})
})
describe('documentReader', () => {
const pdf = asset({ name: 'slides.pdf', mediaType: 'application/pdf' })
it.each([
[undefined, 'docConfig with mode'],
[{ mode: 'pages' as const }, 'startPage and endPage are required'],
[{ mode: 'pages' as const, startPage: 0, endPage: 1 }, 'must be at least 1'],
[{ mode: 'pages' as const, startPage: 3, endPage: 2 }, 'less than or equal to end page'],
[{ mode: 'pages' as const, startPage: 1, endPage: 21 }, 'exceeds the maximum limit of 20'],
[{ mode: 'text' as const }, 'cannot be read as raw text'],
])('rejects %o for PDFs', (options, message) => {
expect(() => documentReader.validate(pdf, options, { hasAnnotation: false })).toThrow(message)
})
it('renders a page range with annotations', async () => {
const plan = await documentReader.plan(
pdf,
{ mode: 'pages', startPage: 2, endPage: 3 },
{ annotation: { annotationId: 'c1', annotations: null, timestamp: 2 }, includeContent: true },
)
expect(plan).toMatchObject({
status: 'render',
task: {
type: 'transcode_pdf_pages',
spec: { pdfPages: { start: 2, end: 3, commentTimestamp: 2, annotations: null } },
},
})
})
it('labels rendered pages by page number', () => {
const result = documentReader.collect!(
pdf,
{ mode: 'pages', startPage: 2, endPage: 3 },
{ pages: [{ key: 'p/2.webp', page: 2 }] },
{},
)
expect(result.summary).toBe('Rendered 1 page(s) of "slides.pdf" (Pages 2 to 3):')
expect(result.images).toEqual([{ key: 'p/2.webp', label: 'Page 2', mimeType: 'image/webp' }])
})
it('detects plain text by media type or extension', () => {
expect(isPlainTextAsset('text/plain', 'a.bin')).toBe(true)
expect(isPlainTextAsset('application/x-yaml', 'a')).toBe(true)
expect(isPlainTextAsset('', 'main.rs')).toBe(true)
expect(isPlainTextAsset('application/pdf', 'a.pdf')).toBe(false)
})
it('truncates by bytes as well as lines', () => {
const big = 'x'.repeat(MAX_TEXT_BYTES + 10)
const { content, truncated } = truncateText(big)
expect(truncated).toBe(true)
expect(Buffer.byteLength(content)).toBe(MAX_TEXT_BYTES)
expect(truncateText('short')).toEqual({ content: 'short', truncated: false })
})
})
@@ -0,0 +1,75 @@
import { MAX_RENDER_ITEMS } from '@shumai/operations'
import { WorkflowTaskType } from '@shumai/db'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { badRequest, type AssetReader } from '../types'
/** Videos: evenly spaced frames between `start` and `end`, rendered by the screenshot workflow. */
export const videoReader: AssetReader<'video'> = {
kind: 'video',
label: 'video',
configHint: "Pass 'videoConfig: { start, end, count }'",
matches: (asset) =>
asset.media?.proxyType === 'video' || asset.mediaTypeLower.startsWith('video/'),
validate(_asset, options) {
if (!options) {
throw badRequest(
'videoConfig with start, end, and count is required when inspecting video assets.',
)
}
const { start, end, count } = options
if (start < 0 || end < 0) {
throw badRequest('Invalid video time range: start and end must be non-negative numbers.')
}
if (start > end) {
throw badRequest(
`Invalid video time range: start (${start}) must be less than or equal to end (${end}).`,
)
}
if (count < 1) {
throw badRequest(`Invalid frame count: count (${count}) must be at least 1.`)
}
if (count > MAX_RENDER_ITEMS) {
throw badRequest(
`Invalid frame count: count (${count}) exceeds the maximum of ${MAX_RENDER_ITEMS} frames per request. Read a shorter range or fewer frames per call.`,
)
}
},
async plan(_asset, options, { annotation }) {
// validate() guarantees options are present
const { start, end, count } = options!
return {
status: 'render',
task: {
type: WorkflowTaskType.transcode_screenshot,
spec: {
screenshot: {
start,
end,
count,
commentTimestamp: annotation?.timestamp ?? null,
annotations: annotation?.annotations ?? null,
},
},
},
}
},
collect(asset, options, output) {
const screenshots = output.screenshots as Array<{ key: string; timestamp: number }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error('No screenshots were generated.')
}
return {
summary: `Extracted ${screenshots.length} frame(s) from "${asset.name}" (${options!.start}s - ${options!.end}s):`,
details: [],
images: screenshots.map((shot) => ({
key: shot.key,
label: `Frame at ${shot.timestamp}s`,
mimeType: getFileMimeType(null, shot.key, 'image/webp'),
})),
}
},
}
+42
View File
@@ -0,0 +1,42 @@
import type { ReaderKind } from '@shumai/operations'
import { documentReader } from './readers/document'
import { imageReader } from './readers/image'
import { model3dReader } from './readers/model3d'
import { videoReader } from './readers/video'
import type { AssetReader, ReadableAsset } from './types'
type MissingKinds<TReaders extends readonly AssetReader[]> = Exclude<
ReaderKind,
TReaders[number]['kind']
>
/** Compile-time guard: every reader kind declared in `@shumai/operations` needs a reader. */
function defineReaderRegistry<const TReaders extends readonly AssetReader[]>(
readers: TReaders &
([MissingKinds<TReaders>] extends [never]
? unknown
: { missingReaders: MissingKinds<TReaders> }),
): TReaders {
return readers
}
/**
* Readers in matching order: the first reader whose `matches` returns true handles the asset.
* 3D comes before image (3D models also have image transcodes); documents cover PDFs and text.
*/
export const readers = defineReaderRegistry([
model3dReader,
imageReader,
videoReader,
documentReader,
] as const)
export function findReader(asset: ReadableAsset): AssetReader | undefined {
return readers.find((reader) => reader.matches(asset)) as AssetReader | undefined
}
export function getReader(kind: ReaderKind): AssetReader {
const reader = readers.find((r) => r.kind === kind)
if (!reader) throw new Error(`No reader registered for "${kind}"`)
return reader as AssetReader
}
+100
View File
@@ -0,0 +1,100 @@
import type { ReaderKind, ReaderOptions } from '@shumai/operations'
import type { WorkflowTaskType } from '@shumai/db'
import { HTTPException } from 'hono/http-exception'
/** The asset being read, after version stacks are resolved to their latest version. */
export interface ReadableAsset {
id: string
name: string
projectId: string | null
/** Media type as stored (may be null). */
mediaType: string | null
/** Lowercased media type ('' when unknown), for matching. */
mediaTypeLower: string
/** Lowercased file name, for extension matching. */
filenameLower: string
storageKey: string | null
media: PrismaJson.MediaInfo | null
}
export interface ReadAnnotation {
annotationId: string
annotations: PrismaJson.AnnotationList | null
/** Seconds (video, 3D turntable) or page number (PDF) where the markup was drawn. */
timestamp: number | null
}
export interface ReadImage {
key: string
/** What the image shows, e.g. "Frame at 30s", "Page 3", "View at 90°". */
label: string
mimeType: string
}
export interface ReadResult {
/** One-line description, e.g. `Extracted 4 frame(s) from "clip.mp4" (0s - 60s):`. */
summary: string
/** Extra description lines (e.g. the 3D quadrant legend). */
details: string[]
images: ReadImage[]
text?: { content: string; truncated: boolean; size: number; key: string; mimeType: string }
}
export interface PlanContext {
annotation: ReadAnnotation | null
/** False when the caller only wants a description (skip reading text content). */
includeContent: boolean
}
export type RenderSpec = Pick<
PrismaJson.WorkflowTaskPayload,
'screenshot' | 'imageAnnotation' | 'pdfPages'
>
export type ReadPlan =
| { status: 'ready'; result: ReadResult }
| {
status: 'render'
task: { type: WorkflowTaskType; spec: RenderSpec }
/** Reader-private values stored on the task and passed back to `collect`. */
context?: Record<string, unknown>
}
/**
* Reads one family of assets. The shared pipeline (`assetReadService`) handles access checks,
* version stacks, annotations, workflow tasks, and waiting; a reader only decides what to show.
*/
export interface AssetReader<TKind extends ReaderKind = ReaderKind> {
kind: TKind
/** Shown in errors, e.g. "Asset X is a 3D model." */
label: string
/** How to pass this reader's options, shown when another reader's config is passed. */
configHint: string
matches(asset: ReadableAsset): boolean
/** Synchronous argument checks, run before annotations are resolved or anything is rendered. */
validate(
asset: ReadableAsset,
options: ReaderOptions<TKind> | undefined,
ctx: { hasAnnotation: boolean },
): void
plan(
asset: ReadableAsset,
options: ReaderOptions<TKind> | undefined,
ctx: PlanContext,
): Promise<ReadPlan>
/** Builds the result from a finished render. Required when `plan` can return `render`. */
collect?(
asset: ReadableAsset,
options: ReaderOptions<TKind> | undefined,
renderOutput: PrismaJson.WorkflowTaskOutput,
context: Record<string, unknown>,
): ReadResult
}
export function badRequest(message: string): HTTPException {
return new HTTPException(400, { message })
}
export function storageBucket(): string {
return process.env.S3_BUCKET || 'shumai'
}
@@ -0,0 +1,43 @@
import { getAssetRender, readAsset, type Via } from '@shumai/operations'
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
import { implementOperation } from '../implement'
/**
* How long each surface waits for a render before returning `pending`. MCP clients commonly
* time out around 60s, so MCP and generic API callers get a short budget.
*/
export const READ_WAIT_BUDGET_MS: Record<Via, number> = {
agent: 60_000,
mcp: 20_000,
cli: 120_000,
api: 20_000,
}
/** `maxWaitSeconds` can only shorten the surface budget. */
export function waitBudgetMs(via: Via, maxWaitSeconds: number | undefined): number {
const budget = READ_WAIT_BUDGET_MS[via]
return maxWaitSeconds === undefined ? budget : Math.min(budget, maxWaitSeconds * 1000)
}
export const readAssetOp = implementOperation(readAsset, {
// assetReadService checks Read on the asset before planning or creating any render task.
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' })
},
})
export const getAssetRenderOp = implementOperation(getAssetRender, {
// Only the requesting user, with Read on the asset, can fetch a render (checked by the service).
authz: () => [],
execute: async (input, ctx) => {
const outcome = await assetReadService.getRender(ctx.userId, input.taskId, {
waitBudgetMs: waitBudgetMs(ctx.via, input.maxWaitSeconds),
})
return toAssetReadOutput(outcome, { includeKeys: ctx.via === 'agent' })
},
})
+6
View File
@@ -14,5 +14,11 @@ export { createFolderOp } from './asset/create-folder'
export { deleteAssetOp } from './asset/delete-asset'
export { listAssetsOp } from './asset/list-assets'
export { moveAssetsOp } from './asset/move-assets'
export {
getAssetRenderOp,
READ_WAIT_BUDGET_MS,
readAssetOp,
waitBudgetMs,
} from './asset/read-asset'
export { renameAssetOp } from './asset/rename-asset'
export { listProjectsOp } from './project/list-projects'
+3
View File
@@ -3,6 +3,7 @@ import { createFolderOp } from './asset/create-folder'
import { deleteAssetOp } from './asset/delete-asset'
import { listAssetsOp } from './asset/list-assets'
import { moveAssetsOp } from './asset/move-assets'
import { getAssetRenderOp, readAssetOp } from './asset/read-asset'
import { renameAssetOp } from './asset/rename-asset'
import type { Operation } from './implement'
import { listProjectsOp } from './project/list-projects'
@@ -31,6 +32,8 @@ export const operations = defineRegistry([
renameAssetOp,
moveAssetsOp,
deleteAssetOp,
readAssetOp,
getAssetRenderOp,
] as const)
const operationsByName = new Map<string, Operation>()
+37
View File
@@ -94,6 +94,43 @@ describe('S3Service implementations', () => {
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
})
it('signs with an explicit lifetime and caches it separately from the default', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://default-url')
getSignedUrlSpy.mockResolvedValueOnce('http://short-url')
const defaultUrl = await s3.presign('bucket', 'expiry-key', 'GET')
const shortUrl = await s3.presign(
'bucket',
'expiry-key',
'GET',
false,
undefined,
false,
3600,
)
const shortAgain = await s3.presign(
'bucket',
'expiry-key',
'GET',
false,
undefined,
false,
3600,
)
expect(defaultUrl).toBe('http://default-url')
expect(shortUrl).toBe('http://short-url')
expect(shortAgain).toBe('http://short-url')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
expect(getSignedUrlSpy).toHaveBeenLastCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 3600 }),
)
})
it('should NOT cache PUT presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
+11 -6
View File
@@ -112,6 +112,8 @@ export interface S3Service {
download?: boolean,
filename?: string,
internal?: boolean,
/** URL lifetime; defaults to PRESIGNED_URL_EXPIRES_IN hours. Ignored by local storage. */
expiresInSeconds?: number,
) => Promise<string>
presignMultipart: (
bucket: string,
@@ -360,12 +362,15 @@ export class S3StorageService implements S3Service {
download?: boolean,
filename?: string,
internal?: boolean,
expiresInSeconds?: number,
): Promise<string> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
const cacheTtlMs = expiresInSeconds * 1000
const lifetimeSeconds = expiresInSeconds ?? expireHours * 3600
// With an explicit (usually short) lifetime, only reuse a cached URL while it has at
// least half of its lifetime left, so callers never receive a nearly expired link.
const cacheTtlMs = expiresInSeconds ? (lifetimeSeconds * 1000) / 2 : lifetimeSeconds * 1000
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}`
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${expiresInSeconds ?? 'default'}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
if (cached) {
@@ -382,19 +387,19 @@ export class S3StorageService implements S3Service {
Key: key,
ResponseContentDisposition: download ? buildContentDisposition(filename) : undefined,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(signingClient, command, { expiresIn: lifetimeSeconds })
} else if (method === 'PUT') {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(signingClient, command, { expiresIn: lifetimeSeconds })
} else if (method === 'DELETE') {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(signingClient, command, { expiresIn: lifetimeSeconds })
} else {
throw new Error(`Unsupported method for presign: ${method}`)
}