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
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { resolveAnnotationsById } from './annotation-resolver'
import { DatabaseSessionStorage } from '../database-session-storage'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { DatabaseSessionStorage } from './database-session-storage'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
@@ -7,7 +7,7 @@ import { DatabaseSessionStorage } from './database-session-storage'
import { agentService } from '@shumai/core/src/agent/agent'
import { createAgentSession, type DbProviderInfo } from './index'
import * as sandboxedBashModule from './tools/sandboxed-bash'
import * as readAssetModule from './tools/read-asset'
import * as operationToolsModule from './operation-tools'
describe('DatabaseSessionStorage', () => {
setupTestDbHooks()
@@ -450,8 +450,8 @@ describe('DatabaseSessionStorage', () => {
})
const sessionId = initialStorage.sessionId
// 2. Spy on media tool constructor
const createReadAssetToolSpy = vi.spyOn(readAssetModule, 'createReadAssetTool')
// 2. Spy on the Operation tools builder (read_asset comes from the Operation registry)
const buildOperationToolsSpy = vi.spyOn(operationToolsModule, 'buildOperationTools')
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
@@ -468,8 +468,10 @@ describe('DatabaseSessionStorage', () => {
providers: mockProviders,
})
// 4. Assert that the tool was instantiated using user ID
expect(createReadAssetToolSpy).toHaveBeenCalledWith(user.id)
// 4. Assert that the tools were built for the user
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
expect.objectContaining({ userId: user.id }),
)
})
it('should instantiate media tools with user ID in subsequent turns (video)', async () => {
@@ -502,8 +504,8 @@ describe('DatabaseSessionStorage', () => {
})
const sessionId = initialStorage.sessionId
// 2. Spy on media tool constructor
const createReadAssetToolSpy = vi.spyOn(readAssetModule, 'createReadAssetTool')
// 2. Spy on the Operation tools builder (read_asset comes from the Operation registry)
const buildOperationToolsSpy = vi.spyOn(operationToolsModule, 'buildOperationTools')
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
@@ -520,8 +522,10 @@ describe('DatabaseSessionStorage', () => {
providers: mockProviders,
})
// 4. Assert that the tool was instantiated using user ID
expect(createReadAssetToolSpy).toHaveBeenCalledWith(user.id)
// 4. Assert that the tools were built for the user
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
expect.objectContaining({ userId: user.id }),
)
})
describe('P1 Bug Reproductions', () => {
+7 -7
View File
@@ -21,13 +21,13 @@ import { metadataService } from '@shumai/core/src/metadata/metadata'
import { createCreateFileTool } from './tools/create-file'
import { createCreateVersionTool } from './tools/create-version'
import { createDownloadAssetTool } from './tools/download-asset'
import { createReadAssetTool } from './tools/read-asset'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { buildOperationTools } from './operation-tools'
import { createAutofillReadAssetTool } from './operation-extensions'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { serializeContextToXml } from './context/serialize-context'
import { DEFAULT_DENIED_TOOLS, type ShumaiMessageContext } from '@shumai/dtos'
@@ -267,13 +267,12 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
const mediaTools: AgentTool[] = []
if (userId) {
mediaTools.push(createReadAssetTool(userId))
} else if (agent?.type === 'autofill' && assetId) {
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
if (!userId && agent?.type === 'autofill' && assetId) {
mediaTools.push(
createReadAssetTool({
createAutofillReadAssetTool({
teamId,
agentType: 'autofill',
targetAssetId: assetId,
}),
)
@@ -337,7 +336,8 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const metadataSchema = await buildProjectMetadataSchema(projectId)
const agentContext = { teamId, agentId }
systemTools.push(
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete,
// read_asset and get_asset_render
...buildOperationTools({ userId, agentId, teamId, projectId }),
createCreateFileTool(userId, metadataSchema, agentContext),
createCreateVersionTool(userId, metadataSchema, agentContext),
@@ -0,0 +1,2 @@
// Registers agent-specific presentation for Operations. Import once before building tools.
export { createAutofillReadAssetTool, presentReadOutput } from './read-asset'
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,155 @@
import { z } from 'zod'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
import { readAsset, type AssetReadOutput } from '@shumai/operations'
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
import { getOperation, READ_WAIT_BUDGET_MS } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { MAX_TEXT_BYTES, MAX_TEXT_LINES } from '@shumai/core/src/asset-read'
import {
registerAgentToolExtension,
splitAgentParams,
toToolParameters,
type AgentToolExtension,
} from '../operation-tools'
const extraParameters = z.object({
s3KeyOnly: z
.boolean()
.optional()
.describe(
'When true, returns only the storage S3 key(s) and MIME types of the asset/frames without attaching base64 image or text content to the agent context. Use this to obtain S3 keys for generate_image or generate_video references without consuming context tokens.',
),
})
/** Details kept compatible with the previous tool; `sourceKeys` drives session image storage. */
interface ReadAssetDetails {
assetId: string
name: string
mediaType: string | null
key?: string
keys: string[]
downloadUrl?: string
results: Array<{ key: string; label: string; downloadUrl?: string }>
sourceKeys: string[]
size?: number
isTruncated?: boolean
}
/** Render a read_asset / get_asset_render output as agent content (text plus image blocks). */
export async function presentReadOutput(
output: AssetReadOutput,
opts: { s3KeyOnly: boolean },
): Promise<AgentToolResult<ReadAssetDetails | { taskId?: string; status: 'pending' }>> {
if (output.status === 'pending') {
const retry = output.retryAfterSeconds ?? 5
return {
content: [
{
type: 'text',
text: `${output.summary} Call get_asset_render with taskId "${output.taskId}" in about ${retry} seconds to get the result.`,
},
],
details: { taskId: output.taskId, status: 'pending' },
}
}
const bucket = process.env.S3_BUCKET || 'shumai'
const imageBlocks: ImageContent[] = []
const imageLines: string[] = []
for (const image of output.images) {
const key = image.key ?? ''
let mimeType = image.mimeType
if (!opts.s3KeyOnly && key) {
const { buffer, contentType } = await s3Service.getObject(bucket, key)
mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, key, image.mimeType)
imageBlocks.push({ type: 'image', data: buffer.toString('base64'), mimeType })
}
imageLines.push(`- ${image.label} (S3 Key: "${key}", MIME: ${mimeType})`)
}
const lines = [output.summary, ...output.details, ...imageLines]
if (output.text) {
lines.push(`- Source file (S3 Key: "${output.text.key ?? ''}", MIME: ${output.text.mimeType})`)
}
let text = lines.join('\n')
if (output.text && !opts.s3KeyOnly) {
text += `\n\n${output.text.content}`
if (output.text.truncated) {
text += `\n\n[Content truncated to ${MAX_TEXT_LINES} lines / ${MAX_TEXT_BYTES / 1024}KB limit. Use download_asset to process the full file.]`
}
}
const imageKeys = output.images.map((i) => i.key ?? '')
const content: Array<TextContent | ImageContent> = [{ type: 'text', text }, ...imageBlocks]
return {
content,
details: {
assetId: output.asset.id,
name: output.asset.name,
mediaType: output.asset.mediaType,
key: imageKeys[0] ?? output.text?.key,
keys: imageKeys,
downloadUrl: output.images[0]?.url ?? output.text?.url,
results: output.images.map((i) => ({ key: i.key ?? '', label: i.label, downloadUrl: i.url })),
sourceKeys: output.text?.key && imageKeys.length === 0 ? [output.text.key] : imageKeys,
...(output.text ? { size: output.text.size, isTruncated: output.text.truncated } : {}),
},
}
}
const readAssetExtension: AgentToolExtension = {
extraParameters,
// s3KeyOnly also means "don't read text content", as before.
toInput: (input, extra) => (extra.s3KeyOnly ? { ...input, includeContent: false } : input),
present: (output, extra) =>
presentReadOutput(output as AssetReadOutput, { s3KeyOnly: extra.s3KeyOnly === true }),
}
const getAssetRenderExtension: AgentToolExtension = {
present: (output) => presentReadOutput(output as AssetReadOutput, { s3KeyOnly: false }),
}
registerAgentToolExtension('read_asset', readAssetExtension)
registerAgentToolExtension('get_asset_render', getAssetRenderExtension)
/** Longer than the chat budget: autofill can't poll get_asset_render (it has no user). */
const AUTOFILL_WAIT_BUDGET_MS = 2 * READ_WAIT_BUDGET_MS.agent
/**
* `read_asset` for the autofill system agent, which runs without a user. It uses the same
* pipeline and presentation, but access is confined to the agent's team and target asset.
*/
export function createAutofillReadAssetTool(access: {
teamId?: string
targetAssetId?: string
}): AgentTool {
const op = getOperation(readAsset.name)!
return {
name: readAsset.name,
label: readAsset.title,
description: readAsset.description,
parameters: toToolParameters(op, readAssetExtension),
execute: async (_toolCallId, params) => {
const { input, extra } = splitAgentParams(op, readAssetExtension, params)
const parsed = readAsset.input.safeParse(input)
if (!parsed.success) {
throw new Error(`Invalid input for read_asset: ${z.prettifyError(parsed.error)}`)
}
const { maxWaitSeconds, ...request } = parsed.data
const budget =
maxWaitSeconds === undefined
? AUTOFILL_WAIT_BUDGET_MS
: Math.min(AUTOFILL_WAIT_BUDGET_MS, maxWaitSeconds * 1000)
const outcome = await assetReadService.read({ kind: 'autofill', ...access }, request, {
waitBudgetMs: budget,
})
const output = await toAssetReadOutput(outcome, { includeKeys: true })
return presentReadOutput(output, { s3KeyOnly: extra.s3KeyOnly === true })
},
}
}
+3 -1
View File
@@ -61,7 +61,7 @@ describe('operation-backed agent tools', () => {
})
describe('tool definitions', () => {
it('keeps the existing tool names and adds list_projects', () => {
it('keeps the existing tool names and adds list_projects and get_asset_render', () => {
expect(
buildOperationTools(ctx)
.map((t) => t.name)
@@ -69,9 +69,11 @@ describe('operation-backed agent tools', () => {
).toEqual([
'create_folder',
'delete_asset',
'get_asset_render',
'list_assets',
'list_projects',
'move_assets',
'read_asset',
'rename_asset',
])
})
+60 -12
View File
@@ -1,7 +1,7 @@
import { z } from 'zod'
import type { TSchema } from 'typebox'
import { Compile } from 'typebox/compile'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import {
getOperationsForSurface,
runOperation,
@@ -12,13 +12,41 @@ import {
/** Context for agent-invoked Operations; `via` is always `agent`. */
export type AgentOperationContext = Omit<OperationContext, 'via'>
/**
* Agent-specific presentation for an Operation. By default a tool returns the Operation output
* as JSON text; an extension can add agent-only parameters, map them into the Operation input,
* and render the output (e.g. as image blocks).
*/
export interface AgentToolExtension {
/** Extra parameters only the agent sees; they are removed before the Operation runs. */
extraParameters?: z.ZodObject
/** Adjust the Operation input using the extra parameters. */
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
present(output: unknown, extra: Record<string, unknown>): Promise<AgentToolResult<unknown>>
}
const extensions = new Map<string, AgentToolExtension>()
/** Register agent presentation for an Operation (see `./operation-extensions`). */
export function registerAgentToolExtension(name: string, extension: AgentToolExtension): void {
extensions.set(name, extension)
}
function toolInputSchema(op: Operation, extension?: AgentToolExtension): z.ZodObject {
return extension?.extraParameters
? op.definition.input.extend(extension.extraParameters.shape)
: op.definition.input
}
/**
* Convert an Operation's Zod input schema into the JSON Schema the agent harness expects.
* TypeBox schemas are plain JSON Schema at runtime, so the converted schema is used as-is.
* Throws when the schema cannot be compiled, so a bad definition fails loudly in tests.
*/
export function toToolParameters(op: Operation): TSchema {
const schema: Record<string, unknown> = z.toJSONSchema(op.definition.input, { io: 'input' })
export function toToolParameters(op: Operation, extension?: AgentToolExtension): TSchema {
const schema: Record<string, unknown> = z.toJSONSchema(toolInputSchema(op, extension), {
io: 'input',
})
// `$schema` is not understood by the harness validator or every model provider.
delete schema.$schema
Compile(schema)
@@ -27,11 +55,11 @@ export function toToolParameters(op: Operation): TSchema {
/**
* Models sometimes send `null` for optional parameters they don't want to set. Drop those
* so the Operation's input schema treats them as omitted; nulls for required fields still fail.
* so the input schema treats them as omitted; nulls for required fields still fail.
*/
function dropNullOptionalFields(op: Operation, params: unknown): unknown {
export function dropNullOptionalFields(schema: z.ZodObject, params: unknown): unknown {
if (!params || typeof params !== 'object' || Array.isArray(params)) return params
const shape = op.definition.input.shape
const shape = schema.shape
return Object.fromEntries(
Object.entries(params).filter(
([key, value]) => !(value === null && shape[key]?.safeParse(undefined).success),
@@ -39,20 +67,40 @@ function dropNullOptionalFields(op: Operation, params: unknown): unknown {
)
}
/** Split agent-only parameters from the Operation input. */
export function splitAgentParams(
op: Operation,
extension: AgentToolExtension | undefined,
params: unknown,
): { input: unknown; extra: Record<string, unknown> } {
const cleaned = dropNullOptionalFields(toolInputSchema(op, extension), params)
if (!extension?.extraParameters || !cleaned || typeof cleaned !== 'object') {
return { input: cleaned, extra: {} }
}
const extraKeys = new Set(Object.keys(extension.extraParameters.shape))
const input: Record<string, unknown> = {}
const extra: Record<string, unknown> = {}
for (const [key, value] of Object.entries(cleaned)) {
;(extraKeys.has(key) ? extra : input)[key] = value
}
return { input: extension.toInput ? extension.toInput(input, extra) : input, extra }
}
/** Expose an Operation as a native agent tool that runs through `runOperation`. */
export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentTool {
const { definition } = op
const extension = extensions.get(definition.name)
return {
name: definition.name,
label: definition.title,
description: definition.description,
parameters: toToolParameters(op),
parameters: toToolParameters(op, extension),
execute: async (_toolCallId, params) => {
const output = await runOperation(
op,
{ ...ctx, via: 'agent' },
dropNullOptionalFields(op, params),
)
const { input, extra } = splitAgentParams(op, extension, params)
const output = await runOperation(op, { ...ctx, via: 'agent' }, input)
if (extension) {
return extension.present(output, extra)
}
return {
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
details: {},
@@ -1,59 +0,0 @@
import { prisma } from '@shumai/db'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
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 Error(
`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 Error(
`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 Error(`Annotation with ID "${annotationId}" not found.`)
}
File diff suppressed because it is too large Load Diff
-922
View File
@@ -1,922 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { workflowService } from '@shumai/workflow-core'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { resolveAnnotationsById } from './annotation-resolver'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { is3dModel } from '@shumai/core/src/utils/mime'
import {
isValidTurntableDegree,
secondToDegree,
degreeToSecond,
} from '@shumai/core/src/utils/model3d'
export const readAssetSchema = Type.Object(
{
assetId: Type.String({
description: 'The asset ID of the workspace asset to inspect. Required.',
}),
annotationId: Type.Union([
Type.String({
description:
'The ID of the comment or message entry from <annotation id="..." /> whose visual markup should be overlaid, or null.',
}),
Type.Null(),
]),
s3KeyOnly: Type.Optional(
Type.Boolean({
description:
'When true, returns only the storage S3 key(s) and MIME types of the asset/frames without attaching base64 image or text content to the agent context. Use this to obtain S3 keys for generate_image or generate_video references without consuming context tokens.',
default: false,
}),
),
imageConfig: Type.Union([
Type.Object(
{},
{
additionalProperties: false,
description: 'Optional configuration for image assets, or null.',
},
),
Type.Null(),
]),
config3d: Type.Optional(
Type.Union([
Type.Object(
{
degree: Type.Optional(
Type.Union([
Type.Integer({
minimum: 0,
maximum: 345,
description:
'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave null/omitted to view the 4-view composite overview.',
}),
Type.Null(),
]),
),
},
{
additionalProperties: false,
description:
'Configuration for 3D model assets. Pass null if inspecting another asset type. Optionally pass degree to inspect a specific turntable angle, or leave null/omitted to view the 4-view composite overview.',
},
),
Type.Null(),
]),
),
videoConfig: Type.Union([
Type.Object(
{
start: Type.Number({ description: 'Start time in seconds.' }),
end: Type.Number({ description: 'End time in seconds.' }),
count: Type.Number({ description: 'Number of frames to extract (e.g. 1 to 10).' }),
},
{
additionalProperties: false,
description:
'Configuration for video assets. Required when inspecting videos, or null for other asset types.',
},
),
Type.Null(),
]),
docConfig: Type.Union([
Type.Object(
{
mode: Type.Union([
Type.Literal('pages', {
description:
'Render specific page range as images for visual layout, charts, or visual annotations (required for binary PDFs).',
}),
Type.Literal('text', {
description:
'Read raw text content directly (ideal for .md, .txt, .csv, code files).',
}),
]),
startPage: Type.Union([
Type.Number({
description:
'Start page number (1-based index, required when mode="pages"), or null when mode="text".',
}),
Type.Null(),
]),
endPage: Type.Union([
Type.Number({
description:
'End page number (1-based index, max 20 pages per call, required when mode="pages"), or null when mode="text".',
}),
Type.Null(),
]),
},
{
additionalProperties: false,
description:
'Configuration for document/PDF/text assets, or null if inspecting another asset type.',
},
),
Type.Null(),
]),
},
{ additionalProperties: false },
)
export function isPlainTextAsset(mediaType: string, filename: string): boolean {
if (
mediaType.startsWith('text/') ||
mediaType === 'application/json' ||
mediaType === 'application/javascript' ||
mediaType === 'application/typescript' ||
mediaType === 'application/xml' ||
mediaType === 'application/x-yaml'
) {
return true
}
const textExtensions = [
'.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',
]
return textExtensions.some((ext) => filename.endsWith(ext))
}
const MAX_TEXT_BYTES = 50 * 1024
const MAX_TEXT_LINES = 1000
export type ReadAssetAuthContext =
| {
userId?: string
teamId?: string
agentType?: 'chat' | 'embedding'
targetAssetId?: string
}
| {
userId?: undefined
teamId: string
agentType: 'autofill'
targetAssetId: string
}
export function createReadAssetTool(
auth: string | ReadAssetAuthContext,
): AgentTool<typeof readAssetSchema> {
const authContext: ReadAssetAuthContext =
typeof auth === 'string' ? { userId: auth, agentType: 'chat' } : auth
const { userId, teamId, agentType = 'chat', targetAssetId } = authContext
return {
name: 'read_asset',
label: 'Read Asset',
description:
'Inspects and reads the content of an asset in the workspace. ' +
'Supports visual analysis for images, 3D models (overview or specific degree angle), video frame extraction, PDF page rendering, and direct text reading for text/markdown files. ' +
'Pass assetId, and provide the specific config (imageConfig, config3d, videoConfig, or docConfig) while setting unused configs to null. ' +
'Optionally provide annotationId to view visual markups drawn on the asset.',
parameters: readAssetSchema,
execute: async (_toolCallId, params) => {
const { assetId, annotationId, s3KeyOnly, config3d, videoConfig, docConfig } = params
if (agentType === 'autofill' && !userId) {
if (!targetAssetId) {
throw new Error('Target asset ID is required for autofill agent authorization.')
}
if (!teamId) {
throw new Error('Team ID is required for autofill agent authorization.')
}
// System background execution for Autofill Agent
const assetRecord = await prisma.asset.findUnique({
where: { id: assetId },
include: { project: true, teamRootFolder: true },
})
if (!assetRecord) {
throw new Error(`Asset with ID ${assetId} not found.`)
}
// Strict team boundary check
const assetTeamId = assetRecord.project?.teamId || assetRecord.teamRootFolder?.id
if (!assetTeamId || assetTeamId !== teamId) {
throw new Error(`Access denied: asset ${assetId} does not belong to team ${teamId}.`)
}
// Strict target asset boundary check (allows the target asset or its version stack children)
if (assetRecord.id !== targetAssetId && assetRecord.parentId !== targetAssetId) {
throw new Error(
`Access denied: autofill agent can only read target asset ${targetAssetId}.`,
)
}
} else {
// Chat agents or user-driven executions strictly require a userId and full ACL validation
if (!userId) {
throw new Error('User ID is required for authorization.')
}
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
}
let asset = await prisma.asset.findUnique({
where: { id: assetId },
include: { storageKey: true },
})
if (!asset) {
throw new Error(`Asset with ID ${assetId} not found.`)
}
if (asset.type === 'version_stack') {
const latestVersion = await prisma.asset.findFirst({
where: { parentId: asset.id, isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: { storageKey: true },
})
if (latestVersion) {
asset = latestVersion
}
}
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo | null
const proxyType = mediaInfo?.proxyType
const mediaType = asset.mediaType?.toLowerCase() || ''
const filename = asset.name?.toLowerCase() || ''
const bucket = process.env.S3_BUCKET || 'shumai'
// ----------------------------------------------------------------------
// Branch 0: 3D Assets (Orthogonal 4-View Composite Image or Degree Angle)
// ----------------------------------------------------------------------
const is3d = proxyType === '3d' || is3dModel(mediaType, filename)
if (is3d) {
if (videoConfig) {
throw new Error(
`Asset ${asset.id} is a 3D model. To inspect specific angles pass 'config3d: { degree: ... }'; do not pass videoConfig.`,
)
}
if (config3d?.degree !== undefined && config3d?.degree !== null) {
if (!isValidTurntableDegree(config3d.degree)) {
throw new Error(
`Invalid turntable degree: ${config3d.degree}. Degree must be an integer multiple of 15 between 0 and 345 (e.g. 0, 15, 30, 45, ..., 345).`,
)
}
}
let annotations: PrismaJson.AnnotationList | null = null
let commentTimestamp: number | null = null
if (annotationId) {
const resolved = await resolveAnnotationsById(asset.id, annotationId)
annotations = resolved.annotations
commentTimestamp = resolved.timestamp
if (commentTimestamp !== null && commentTimestamp !== undefined) {
const commentDegree = secondToDegree(commentTimestamp)
if (
config3d?.degree !== undefined &&
config3d?.degree !== null &&
config3d.degree !== commentDegree
) {
throw new Error(
`Annotation "${annotationId}" was drawn at ${commentDegree}°, but degree ${config3d.degree}° was specified. Do not pass a conflicting degree with annotationId.`,
)
}
}
}
if ((config3d?.degree !== undefined && config3d?.degree !== null) || annotationId) {
if (!mediaInfo?.videoTranscodes || mediaInfo.videoTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its turntable video (turntable.mp4) is missing.`,
)
}
let targetDegree: number
let targetSecond: number
if (config3d?.degree !== undefined && config3d?.degree !== null) {
targetDegree = config3d.degree
targetSecond = degreeToSecond(targetDegree)
} else {
targetSecond =
commentTimestamp !== null && commentTimestamp !== undefined ? commentTimestamp : 0
targetDegree = secondToDegree(targetSecond)
}
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_screenshot,
status: WorkflowTaskStatus.pending,
payload: {
projectId: asset.projectId || 'none',
screenshot: {
start: targetSecond,
end: targetSecond,
count: 1,
commentTimestamp: targetSecond,
annotations: annotations ?? undefined,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
Array<{ key: string; timestamp: number }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error(
`Failed to extract 3D turntable frame for asset ${asset.id} at ${targetDegree}°.`,
)
}
const shotKey = screenshots[0].key
const downloadUrl = await s3Service.presign(
bucket,
shotKey,
'GET',
true,
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = []
const hasMarkup = Boolean(annotations && annotations.length > 0)
const textDescription = hasMarkup
? `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}° with visual markups overlaid:`
: `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}°:`
if (s3KeyOnly) {
content.push({
type: 'text',
text: textDescription,
})
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, shotKey)
const actualMimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
content.push({
type: 'text',
text: textDescription,
})
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: actualMimeType,
})
}
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: shotKey,
downloadUrl,
sourceKeys: [shotKey],
},
}
}
if (!mediaInfo?.imageTranscodes || mediaInfo.imageTranscodes.length === 0) {
throw new Error(
`Asset ${asset.id} is a 3D model, but its 4-views image (views.webp) is missing.`,
)
}
const mediaKey = mediaInfo.imageTranscodes[0].key
if (!mediaKey) {
throw new Error(`Asset ${asset.id} is a 3D model, but its 4-views image key is missing.`)
}
const keyToUse = mediaKey
const mimeType = 'image/webp'
const downloadUrl = await s3Service.presign(
bucket,
keyToUse,
'GET',
true,
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = []
const textDescription = [
`3D asset "${asset.name}" (ID: ${asset.id}, MIME: ${mimeType}, S3 Key: "${keyToUse}"):`,
'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°)',
].join('\n')
if (s3KeyOnly) {
content.push({
type: 'text',
text: textDescription,
})
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
const actualMimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : mimeType
content.push({
type: 'text',
text: textDescription,
})
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: actualMimeType,
})
}
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: keyToUse,
downloadUrl,
sourceKeys: [keyToUse],
},
}
}
// ----------------------------------------------------------------------
// Branch 1: Image Assets
// ----------------------------------------------------------------------
if (proxyType === 'image' || mediaType.startsWith('image/') || filename.endsWith('.psd')) {
let mediaKey = asset.storageKey?.key
if (mediaInfo?.imageTranscodes && mediaInfo.imageTranscodes.length > 0) {
mediaKey = mediaInfo.imageTranscodes[0].key || mediaKey
}
if (!mediaKey) {
throw new Error('No media content found for this asset.')
}
let keyToUse = mediaKey
let mimeType = getFileMimeType(null, keyToUse, asset.mediaType || 'image/png')
if (annotationId) {
const { annotations } = await resolveAnnotationsById(asset.id, annotationId)
if (annotations && annotations.length > 0) {
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_image_annotation,
status: WorkflowTaskStatus.pending,
payload: {
projectId: asset.projectId || 'none',
imageAnnotation: {
annotations,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode image annotation task output
const output = completedTask.output as any
if (output?.key) {
keyToUse = output.key
mimeType = 'image/webp'
} else {
throw new Error('Image annotation transcode workflow failed to output S3 key.')
}
}
}
const downloadUrl = await s3Service.presign(
bucket,
keyToUse,
'GET',
true,
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = []
if (s3KeyOnly) {
content.push({
type: 'text',
text: `Image asset "${asset.name}" (ID: ${asset.id}, MIME: ${mimeType}, S3 Key: "${keyToUse}")`,
})
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
const actualMimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : mimeType
content.push({
type: 'text',
text: `Image asset "${asset.name}" (ID: ${asset.id}, MIME: ${actualMimeType}, S3 Key: "${keyToUse}")`,
})
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: actualMimeType,
})
}
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: keyToUse,
downloadUrl,
sourceKeys: [keyToUse],
},
}
}
// ----------------------------------------------------------------------
// Branch 2: Video Assets
// ----------------------------------------------------------------------
if (proxyType === 'video' || mediaType.startsWith('video/')) {
if (!videoConfig) {
throw new Error(
'videoConfig with start, end, and count is required when inspecting video assets.',
)
}
const { start, end, count } = videoConfig
if (start < 0 || end < 0) {
throw new Error('Invalid video time range: start and end must be non-negative numbers.')
}
if (start > end) {
throw new Error(
`Invalid video time range: start (${start}) must be less than or equal to end (${end}).`,
)
}
if (count < 1) {
throw new Error(`Invalid frame count: count (${count}) must be at least 1.`)
}
const { annotations, timestamp: commentTimestamp } = await resolveAnnotationsById(
asset.id,
annotationId,
)
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_screenshot,
status: WorkflowTaskStatus.pending,
payload: {
projectId: asset.projectId || 'none',
screenshot: {
start,
end,
count,
commentTimestamp,
annotations,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
Array<{ key: string; timestamp: number }> | undefined
if (!screenshots || screenshots.length === 0) {
throw new Error('No screenshots were generated.')
}
const content: Array<TextContent | ImageContent> = []
const sourceKeys: string[] = []
const results: Array<{ key: string; timestamp: number; downloadUrl: string }> = []
const textLines: string[] = [
`Extracted ${screenshots.length} frame(s) from "${asset.name}" (${start}s - ${end}s):`,
]
for (const shot of screenshots) {
const downloadUrl = await s3Service.presign(
bucket,
shot.key,
'GET',
true,
asset.name || undefined,
)
sourceKeys.push(shot.key)
results.push({
key: shot.key,
timestamp: shot.timestamp,
downloadUrl,
})
if (s3KeyOnly) {
const mimeType = getFileMimeType(null, shot.key, 'image/webp')
textLines.push(
`- Frame at ${shot.timestamp}s (S3 Key: "${shot.key}", MIME: ${mimeType})`,
)
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, shot.key)
const mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, shot.key, 'image/webp')
textLines.push(
`- Frame at ${shot.timestamp}s (S3 Key: "${shot.key}", MIME: ${mimeType})`,
)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
}
}
content.unshift({
type: 'text',
text: textLines.join('\n'),
})
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
keys: sourceKeys,
results,
sourceKeys,
},
}
}
// ----------------------------------------------------------------------
// Branch 3: Documents & PDF Assets
// ----------------------------------------------------------------------
if (
proxyType === 'pdf' ||
mediaType === 'application/pdf' ||
isPlainTextAsset(mediaType, filename)
) {
if (!docConfig) {
throw new Error(
'docConfig with mode ("pages" or "text") is required when inspecting document/PDF assets.',
)
}
if (docConfig.mode === 'text') {
if (annotationId !== null) {
throw new Error(
'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 (docConfig.startPage !== null || docConfig.endPage !== null) {
throw new Error(
'startPage and endPage must be null when docConfig mode is "text". To inspect specific page numbers, use mode: "pages".',
)
}
if (!isPlainTextAsset(mediaType, filename)) {
throw new Error(
`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.`,
)
}
const mediaKey = asset.storageKey?.key
if (!mediaKey) {
throw new Error(`No media content found for asset ${asset.id}.`)
}
const docMimeType =
asset.mediaType || getFileMimeType(null, asset.name || mediaKey, 'text/plain')
const downloadUrl = await s3Service.presign(
bucket,
mediaKey,
'GET',
true,
asset.name || undefined,
)
if (s3KeyOnly) {
return {
content: [
{
type: 'text',
text: `Document "${asset.name}" (ID: ${asset.id}, MIME: ${docMimeType}, S3 Key: "${mediaKey}")`,
},
],
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: mediaKey,
downloadUrl,
sourceKeys: [mediaKey],
size: 0,
isTruncated: false,
},
}
}
const { buffer } = await s3Service.getObject(bucket, mediaKey)
const rawText = buffer.toString('utf-8')
let text = rawText
let isTruncated = false
const lines = text.split('\n')
if (lines.length > MAX_TEXT_LINES) {
text = lines.slice(0, MAX_TEXT_LINES).join('\n')
isTruncated = true
}
if (Buffer.byteLength(text, 'utf-8') > MAX_TEXT_BYTES) {
text = Buffer.from(text, 'utf-8').subarray(0, MAX_TEXT_BYTES).toString('utf-8')
isTruncated = true
}
if (isTruncated) {
text += `\n\n[Content truncated to ${MAX_TEXT_LINES} lines / ${MAX_TEXT_BYTES / 1024}KB limit. Use download_asset to process the full file.]`
}
return {
content: [
{
type: 'text',
text: `Document "${asset.name}" (ID: ${asset.id}, MIME: ${docMimeType}, S3 Key: "${mediaKey}"):\n\n${text}`,
},
],
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: mediaKey,
downloadUrl,
sourceKeys: [mediaKey],
size: buffer.length,
isTruncated,
},
}
}
// docConfig.mode === 'pages'
if (docConfig.startPage === null || docConfig.endPage === null) {
throw new Error('startPage and endPage are required when docConfig mode is "pages".')
}
const start = docConfig.startPage
const end = docConfig.endPage
if (start < 1) {
throw new Error(`Invalid page range: start page (${start}) must be at least 1.`)
}
if (start > end) {
throw new Error(
`Invalid page range: start page (${start}) must be less than or equal to end page (${end}).`,
)
}
const MAX_PAGE_RANGE = 20
const requestedPages = end - start + 1
if (requestedPages > MAX_PAGE_RANGE) {
throw new Error(
`Page range (${requestedPages} pages requested) exceeds the maximum limit of ${MAX_PAGE_RANGE} pages per request.`,
)
}
const { annotations, timestamp: commentTimestamp } = await resolveAnnotationsById(
asset.id,
annotationId,
)
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_pdf_pages,
status: WorkflowTaskStatus.pending,
payload: {
projectId: asset.projectId || 'none',
pdfPages: {
start,
end,
commentTimestamp,
annotations,
},
},
},
})
const completedTask = await workflowService.executeWait(task)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode pdf pages output
const output = completedTask.output as any
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.')
}
const content: Array<TextContent | ImageContent> = []
const sourceKeys: string[] = []
const results: Array<{ key: string; page: number; downloadUrl: string }> = []
const textLines: string[] = [
`Rendered ${pages.length} page(s) of "${asset.name}" (Pages ${start} to ${end}):`,
]
for (const pageItem of pages) {
const downloadUrl = await s3Service.presign(
bucket,
pageItem.key,
'GET',
true,
asset.name || undefined,
)
sourceKeys.push(pageItem.key)
results.push({
key: pageItem.key,
page: pageItem.page,
downloadUrl,
})
if (s3KeyOnly) {
const mimeType = getFileMimeType(null, pageItem.key, 'image/webp')
textLines.push(`- Page ${pageItem.page} (S3 Key: "${pageItem.key}", MIME: ${mimeType})`)
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, pageItem.key)
const mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, pageItem.key, 'image/webp')
textLines.push(`- Page ${pageItem.page} (S3 Key: "${pageItem.key}", MIME: ${mimeType})`)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
}
}
content.unshift({
type: 'text',
text: textLines.join('\n'),
})
return {
content,
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
keys: sourceKeys,
results,
sourceKeys,
},
}
}
throw new Error(
`Unsupported asset type for read_asset. Asset ${asset.id} has media type "${mediaType || 'unknown'}". Use download_asset to download this file to disk.`,
)
},
}
}