mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 01:08:19 +00:00
feat(asset-download): share download_asset across agent, MCP and CLI
Turn the agent-only download_asset tool into an Operation on all three surfaces. - download_asset takes up to 50 file or version stack IDs and returns presigned links. proxy (default true) picks the web preview when there is one, as the agent always did; proxy: false returns the original. Folders are rejected. Read is checked on every ID before anything runs. - Agent: an extension saves the files into the .pi sandbox and keeps the agent-only storage key mode (e.g. frames from read_asset). Agent tool extensions gain description, parameterOverrides and intercept. - CLI: `shumai-cli download <assetId...> [--out <dir>] [--original]` streams files to disk without overwriting existing names. - read_asset's unsupported-type error now names the right way to download on each surface (download_asset, or `shumai-cli download`). - Add the Download Asset toggle to agent settings.
This commit is contained in:
@@ -236,7 +236,7 @@ An **Operation** is a capability agents can use, defined once and exposed automa
|
||||
- **Tests**: real-database tests per Operation covering success, permission denial (no side effects), and audit entries.
|
||||
- **CLI spec**: object input fields must be listed in `cli.flatten` (one flag per sub-field, e.g. `{ videoConfig: 'video' }` → `--video-start`) or in `cli.omit` (optional fields the CLI doesn't expose).
|
||||
- **Surface presentation**: by default each surface shows the Operation output as JSON. To add surface-only parameters or render output differently, add an extension for that surface:
|
||||
- agent: `AgentToolExtension` in `packages/agent/src/operation-extensions/` (e.g. image blocks);
|
||||
- agent: `AgentToolExtension` in `packages/agent/src/operation-extensions/` (e.g. image blocks, saving downloads into the sandbox). `parameterOverrides` and `intercept` support agent-only modes, such as `download_asset` by storage key;
|
||||
- MCP: `McpToolExtension` in `packages/api/src/mcp-extensions/` (`structuredContent` must still match the output schema);
|
||||
- CLI: `CliCommandExtension` in `apps/cli/src/operations/extensions/` (local I/O such as downloads).
|
||||
|
||||
|
||||
+3
-1
@@ -10,7 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
* **mcp**: Shumai now has a built-in MCP server, so external AI agents such as Claude Code, Cursor, or Kiro can browse projects and create, rename, move, or delete folders and files with your API token and permissions
|
||||
* **agent**: The built-in agent can now list the projects you have access to, so it can find a project's root folder on its own. Team owners can turn this off per agent like other tools
|
||||
* **mcp**: External AI agents connected to Shumai's MCP server can now look at your files: images, video frames, PDF pages, 3D model views, and text files. Images are attached so the AI can see them, along with links that stay valid for about an hour
|
||||
* **mcp**: External AI agents connected to Shumai's MCP server can now look at your files: images, video frames, PDF pages, 3D model views, and text files. Images are attached so the AI can see them, along with links that stay valid for about an hour. They can also get download links for files, as the web preview or the original upload
|
||||
* **cli**: New `shumai-cli download` command saves files to your computer, up to 50 at a time: the smaller web preview by default, or the original upload with `--original`
|
||||
* **cli**: New `shumai-cli read` command shows an image, video frames, PDF pages, a 3D model view, or the text of a file, and `--out` downloads the images into a folder. If rendering takes a while, `shumai-cli render <taskId>` picks up the result later
|
||||
|
||||
### Fixed
|
||||
@@ -24,6 +25,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
* **cli**: `shumai-cli` has clearer help for every command (`shumai-cli <command> --help`), suggests the right command when you mistype one, and can print raw JSON with `--json`. `ls` can now filter by type and page through very large folders. Existing commands work as before; the npm package now needs Node.js 22.12 or later
|
||||
* **agent**: When the agent lists a folder's contents, large folders are now paged with a "next page" marker instead of page numbers, and items appear in the same order as in the file browser
|
||||
* **agent**: When the agent looks at a long video or a large document that takes more than about a minute to render, it no longer fails with a timeout. The agent is told the render is still in progress and picks up the frames or pages when they're ready, using the new "Get Asset Render" tool. Each call can now read at most 20 video frames, the same limit as PDF pages
|
||||
* **agent**: The agent can now download several files at once (up to 50), and can get the original upload instead of the smaller web preview. Downloaded files keep the preview's file type in their name (e.g. `photo.webp`). Team owners can now turn the Download Asset tool on or off per agent in agent settings
|
||||
* **api-token**: API tokens are now stored securely, so they can no longer be read back from the database. A new token is shown only once when you create it, so copy it right away; the token list now shows just the last few characters. Existing tokens keep working without any changes.
|
||||
|
||||
## [0.6.1] - 2026-10-24
|
||||
|
||||
@@ -167,6 +167,19 @@ Get the result of a `read` that was still rendering. Takes the same `--out`, `--
|
||||
shumai-cli render <taskId> --out frames
|
||||
```
|
||||
|
||||
#### 11. Download Files
|
||||
|
||||
Download up to 50 files at once. By default it saves the web preview version when there is one (for example the transcoded video or the web image), which is smaller; use `--original` for the uploaded file. A version stack downloads its latest version. Folders aren't supported: download the files inside them. Files keep their names; if a name is taken, the new file gets a number, like `clip (2).mp4`.
|
||||
|
||||
```bash
|
||||
shumai-cli download <assetId...> --out ./downloads
|
||||
shumai-cli download <assetId> --original
|
||||
```
|
||||
|
||||
- **Options:**
|
||||
- `-o`, `--out <dir>`: Folder to save the files in (default: the current folder). With `--json`, each file also gets a `path`.
|
||||
- `--original`: Download the original uploaded files instead of the web previews.
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import type { DownloadAssetOutput } from '@shumai/operations'
|
||||
import { CliError } from '../errors'
|
||||
import { downloadAssetExtension, safeFileName, uniquePath } from './download-asset'
|
||||
|
||||
const output: DownloadAssetOutput = {
|
||||
files: [
|
||||
{
|
||||
assetId: 'a-1',
|
||||
name: 'clip.mp4',
|
||||
kind: 'proxy',
|
||||
size: 2048,
|
||||
mimeType: 'video/mp4',
|
||||
url: 'https://files.example/a-1',
|
||||
},
|
||||
{
|
||||
assetId: 'a-2',
|
||||
name: 'clip.mp4',
|
||||
kind: 'original',
|
||||
size: 10,
|
||||
mimeType: 'video/mp4',
|
||||
url: 'https://files.example/a-2',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('download CLI extension', () => {
|
||||
let dir: string
|
||||
let written: string
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), 'shumai-cli-download-'))
|
||||
written = ''
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (url: string) => new Response(`bytes of ${url}`, { status: 200 })),
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const o = () => ({ out: { write: (s: string) => void (written += s) }, isTty: true, columns: 80 })
|
||||
|
||||
it('saves every file, numbering names that are already taken', async () => {
|
||||
await writeFile(path.join(dir, 'clip.mp4'), 'existing')
|
||||
|
||||
await downloadAssetExtension.present(output, { opts: { out: dir }, json: false, output: o() })
|
||||
|
||||
expect((await readdir(dir)).sort()).toEqual(['clip (2).mp4', 'clip (3).mp4', 'clip.mp4'])
|
||||
expect(await readFile(path.join(dir, 'clip.mp4'), 'utf8')).toBe('existing')
|
||||
expect(await readFile(path.join(dir, 'clip (2).mp4'), 'utf8')).toBe(
|
||||
'bytes of https://files.example/a-1',
|
||||
)
|
||||
expect(written).toBe(
|
||||
`Saved ${path.join(dir, 'clip (2).mp4')} (2 KB, proxy)\nSaved ${path.join(dir, 'clip (3).mp4')} (10 B, original)\n`,
|
||||
)
|
||||
})
|
||||
|
||||
it('creates the folder and prints JSON with the saved paths', async () => {
|
||||
const out = path.join(dir, 'nested', 'files')
|
||||
await downloadAssetExtension.present(output, { opts: { out }, json: true, output: o() })
|
||||
|
||||
const printed = JSON.parse(written) as { files: Array<{ path: string; url: string }> }
|
||||
expect(printed.files.map((f) => f.path)).toEqual([
|
||||
path.join(out, 'clip.mp4'),
|
||||
path.join(out, 'clip (2).mp4'),
|
||||
])
|
||||
expect(printed.files[0].url).toBe('https://files.example/a-1')
|
||||
})
|
||||
|
||||
it('fails clearly when a download fails', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('gone', { status: 403 })),
|
||||
)
|
||||
await expect(
|
||||
downloadAssetExtension.present(output, { opts: { out: dir }, json: false, output: o() }),
|
||||
).rejects.toThrow(new CliError('Failed to download "clip.mp4" (status 403).'))
|
||||
})
|
||||
|
||||
it('keeps file names inside the target folder', () => {
|
||||
expect(safeFileName('../../etc/passwd')).toBe('_.._etc_passwd')
|
||||
expect(safeFileName('a\\b.txt')).toBe('a_b.txt')
|
||||
expect(safeFileName('...')).toBe('file')
|
||||
const taken = new Set<string>()
|
||||
expect(uniquePath(dir, 'notes', taken)).toBe(path.join(dir, 'notes'))
|
||||
expect(uniquePath(dir, 'notes', taken)).toBe(path.join(dir, 'notes (2)'))
|
||||
})
|
||||
|
||||
it('maps --original to proxy false', () => {
|
||||
expect(downloadAssetExtension.toInput!({ assetIds: ['a'] }, { original: true })).toEqual({
|
||||
assetIds: ['a'],
|
||||
proxy: false,
|
||||
})
|
||||
expect(downloadAssetExtension.toInput!({ assetIds: ['a'] }, {})).toEqual({ assetIds: ['a'] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import { Option } from 'commander'
|
||||
import type { DownloadAssetOutput } from '@shumai/operations'
|
||||
import type { CliCommandExtension } from '../generate'
|
||||
import { formatSize } from '../render'
|
||||
import { saveUrlToFile } from './save-url'
|
||||
|
||||
/** A file name that is safe to create inside the target folder (no paths or control chars). */
|
||||
export function safeFileName(name: string): string {
|
||||
const safe = name
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[\x00-\x1f\x7f/\\]/g, '_')
|
||||
.replace(/^[\s.]+|[\s.]+$/g, '')
|
||||
return safe || 'file'
|
||||
}
|
||||
|
||||
/** `name.ext`, or `name (2).ext`, `name (3).ext`, ... if taken on disk or in this download. */
|
||||
export function uniquePath(dir: string, name: string, taken: Set<string>): string {
|
||||
const ext = path.extname(name)
|
||||
const stem = ext ? name.slice(0, -ext.length) : name
|
||||
for (let n = 1; ; n++) {
|
||||
const candidate = path.join(dir, n === 1 ? name : `${stem} (${n})${ext}`)
|
||||
if (!taken.has(candidate) && !existsSync(candidate)) {
|
||||
taken.add(candidate)
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** `download`: saves each file into `--out` (the current folder by default). */
|
||||
export const downloadAssetExtension: CliCommandExtension = {
|
||||
options: () => [
|
||||
new Option('-o, --out <dir>', 'Folder to save the files in.').default('.'),
|
||||
new Option('--original', 'Download the original uploaded files instead of the web previews.'),
|
||||
],
|
||||
toInput: (input, opts) => (opts.original === true ? { ...input, proxy: false } : input),
|
||||
async present(raw, { opts, json, output: o }) {
|
||||
const output = raw as DownloadAssetOutput
|
||||
const dir = typeof opts.out === 'string' ? opts.out : '.'
|
||||
await mkdir(dir, { recursive: true })
|
||||
const taken = new Set<string>()
|
||||
const saved: string[] = []
|
||||
for (const file of output.files) {
|
||||
const filePath = uniquePath(dir, safeFileName(file.name), taken)
|
||||
await saveUrlToFile(file.url, filePath, file.name)
|
||||
saved.push(filePath)
|
||||
if (!json) {
|
||||
o.out.write(`Saved ${filePath} (${formatSize(file.size)}, ${file.kind})\n`)
|
||||
}
|
||||
}
|
||||
if (json) {
|
||||
const files = output.files.map((file, i) => ({ ...file, path: saved[i] }))
|
||||
o.out.write(`${JSON.stringify({ files }, null, 2)}\n`)
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { CliCommandExtension } from '../generate'
|
||||
import { downloadAssetExtension } from './download-asset'
|
||||
import { getAssetRenderExtension, readAssetExtension } from './read-asset'
|
||||
|
||||
/** CLI-specific behavior for generated commands, by Operation name. */
|
||||
export const cliExtensions: ReadonlyMap<string, CliCommandExtension> = new Map([
|
||||
['read_asset', readAssetExtension],
|
||||
['get_asset_render', getAssetRenderExtension],
|
||||
['download_asset', downloadAssetExtension],
|
||||
])
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import { Option } from 'commander'
|
||||
import type { AssetReadOutput } from '@shumai/operations'
|
||||
import { CliError } from '../errors'
|
||||
import { saveUrlToFile } from './save-url'
|
||||
import type { CliCommandExtension } from '../generate'
|
||||
import type { Output } from '../render'
|
||||
|
||||
@@ -41,19 +42,8 @@ export async function downloadImages(output: AssetReadOutput, dir: string): Prom
|
||||
if (!image.url) {
|
||||
throw new CliError(`No download link was returned for "${image.label}".`)
|
||||
}
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(image.url)
|
||||
} catch (err) {
|
||||
throw new CliError(
|
||||
`Failed to download "${image.label}": ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new CliError(`Failed to download "${image.label}" (status ${res.status}).`)
|
||||
}
|
||||
const filePath = path.join(dir, imageFileName(output.asset.id, index, image))
|
||||
await writeFile(filePath, Buffer.from(await res.arrayBuffer()))
|
||||
await saveUrlToFile(image.url, filePath, image.label)
|
||||
saved.push(filePath)
|
||||
}
|
||||
return saved
|
||||
@@ -75,7 +65,7 @@ function writeReady(output: AssetReadOutput, paths: string[] | null, o: Output):
|
||||
if (!output.text.content.endsWith('\n')) o.out.write('\n')
|
||||
if (output.text.truncated) {
|
||||
o.out.write(
|
||||
`\n[Content truncated: showing the first part of a ${output.text.size}-byte file.]\n`,
|
||||
`\n[Content truncated: showing the first part of a ${output.text.size}-byte file. Run \`shumai-cli download ${output.asset.id}\` to get the whole file.]\n`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { rm } from 'node:fs/promises'
|
||||
import { Readable } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import type { ReadableStream as WebReadableStream } from 'node:stream/web'
|
||||
import { CliError } from '../errors'
|
||||
|
||||
/** Streams a download link to `filePath` (large files never sit in memory). */
|
||||
export async function saveUrlToFile(url: string, filePath: string, label: string): Promise<void> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(url)
|
||||
} catch (err) {
|
||||
throw new CliError(
|
||||
`Failed to download "${label}": ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
if (!res.ok || !res.body) {
|
||||
throw new CliError(`Failed to download "${label}" (status ${res.status}).`)
|
||||
}
|
||||
try {
|
||||
await pipeline(
|
||||
Readable.fromWeb(res.body as unknown as WebReadableStream<Uint8Array>),
|
||||
createWriteStream(filePath),
|
||||
)
|
||||
} catch (err) {
|
||||
await rm(filePath, { force: true })
|
||||
throw new CliError(
|
||||
`Failed to save "${label}" to ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { Command } from 'commander'
|
||||
import {
|
||||
createFolder,
|
||||
deleteAsset,
|
||||
downloadAsset,
|
||||
getAssetRender,
|
||||
readAsset,
|
||||
listAssets,
|
||||
@@ -352,7 +353,7 @@ describe('shumai-cli', () => {
|
||||
await cli.run('read', 'd-1', '--doc-mode', 'text')
|
||||
|
||||
expect(cli.stdout()).toBe(
|
||||
'Document "notes.md" (ID: d-1):\n\n# Notes\nhello\n\n[Content truncated: showing the first part of a 90000-byte file.]\n',
|
||||
'Document "notes.md" (ID: d-1):\n\n# Notes\nhello\n\n[Content truncated: showing the first part of a 90000-byte file. Run `shumai-cli download vid-1` to get the whole file.]\n',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -419,6 +420,36 @@ describe('shumai-cli', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('download', () => {
|
||||
it('downloads the web previews by default, or the originals with --original', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ files: [] })
|
||||
|
||||
await cli.run('download', 'a-1', 'a-2')
|
||||
expect(cli.callOperation).toHaveBeenLastCalledWith(downloadAsset, {
|
||||
assetIds: ['a-1', 'a-2'],
|
||||
})
|
||||
|
||||
await cli.run('download', 'a-1', '--original')
|
||||
expect(cli.callOperation).toHaveBeenLastCalledWith(downloadAsset, {
|
||||
assetIds: ['a-1'],
|
||||
proxy: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('requires at least one asset ID and documents its options', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('download')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("missing required argument 'assetIds'")
|
||||
|
||||
await expect(cli.run('download', '--help')).rejects.toThrow()
|
||||
expect(cli.stdout()).toContain('-o, --out <dir>')
|
||||
expect(cli.stdout()).toContain('--original')
|
||||
expect(cli.stdout()).not.toContain('--proxy')
|
||||
})
|
||||
})
|
||||
|
||||
describe('--json', () => {
|
||||
it('prints the raw Operation output', async () => {
|
||||
const cli = setup()
|
||||
@@ -482,6 +513,7 @@ describe('shumai-cli', () => {
|
||||
'delete|rm',
|
||||
'read',
|
||||
'render',
|
||||
'download',
|
||||
'upload',
|
||||
'create-version',
|
||||
]) {
|
||||
|
||||
@@ -58,16 +58,17 @@ claude mcp add --transport http shumai https://<your-shumai-host>/api/mcp \
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | What it does |
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------------- |
|
||||
| `list_projects` | Lists the projects you can access, with each project's root folder. |
|
||||
| `list_assets` | Lists files and folders in a folder, page by page. |
|
||||
| `create_folder` | Creates a folder. |
|
||||
| `rename_asset` | Renames a file or folder. |
|
||||
| `move_assets` | Moves files or folders into another folder. |
|
||||
| `delete_asset` | Moves a file or folder to the project trash. Marked as destructive so clients can ask you to confirm. |
|
||||
| `read_asset` | Looks at a file: an image, video frames, PDF pages, a 3D model view, or the text of a text file. |
|
||||
| `get_asset_render` | Gets the result of a `read_asset` call that was still rendering. |
|
||||
| Tool | What it does |
|
||||
| ------------------ | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| `list_projects` | Lists the projects you can access, with each project's root folder. |
|
||||
| `list_assets` | Lists files and folders in a folder, page by page. |
|
||||
| `create_folder` | Creates a folder. |
|
||||
| `rename_asset` | Renames a file or folder. |
|
||||
| `move_assets` | Moves files or folders into another folder. |
|
||||
| `delete_asset` | Moves a file or folder to the project trash. Marked as destructive so clients can ask you to confirm. |
|
||||
| `read_asset` | Looks at a file: an image, video frames, PDF pages, a 3D model view, or the text of a text file. |
|
||||
| `get_asset_render` | Gets the result of a `read_asset` call that was still rendering. |
|
||||
| `download_asset` | Gets download links for up to 50 files: the web preview version by default, or the original with `proxy: false`. |
|
||||
|
||||
### Reading Files
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ The following tools can be individually toggled in the agent configuration dialo
|
||||
|
||||
### 12. Download Asset (`download_asset`)
|
||||
|
||||
- **Description:** Allows the agent to download a workspace asset or specific storage S3 key to the local `.pi` directory for processing with local scripts or bash commands.
|
||||
- **Description:** Allows the agent to download up to 50 workspace files, or a specific storage S3 key (such as a frame from `read_asset`), to the local `.pi` directory for processing with local scripts or bash commands. By default it downloads the web preview version when there is one (for example the transcoded video or the web image); the agent can ask for the original uploaded file instead. Folders are not supported.
|
||||
- **Why it matters:** Enables agents executing custom skill scripts to fetch files or intermediate transcode artifacts to local disk.
|
||||
|
||||
### 13. Rename Asset (`rename_asset`)
|
||||
|
||||
@@ -20,7 +20,6 @@ import { DatabaseSessionStorage } from './database-session-storage'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { createCreateVersionTool } from './tools/create-version'
|
||||
import { createDownloadAssetTool } from './tools/download-asset'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
@@ -337,11 +336,10 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const agentContext = { teamId, agentId }
|
||||
systemTools.push(
|
||||
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete,
|
||||
// read_asset and get_asset_render
|
||||
// read_asset, get_asset_render, and download_asset
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }),
|
||||
createCreateFileTool(userId, metadataSchema, agentContext),
|
||||
createCreateVersionTool(userId, metadataSchema, agentContext),
|
||||
createDownloadAssetTool(userId),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { prisma, type Asset, type StorageKey } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { toAgentTool } from '../operation-tools'
|
||||
import './download-asset'
|
||||
|
||||
vi.mock('@shumai/db', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/db')>()
|
||||
return {
|
||||
...actual,
|
||||
prisma: {
|
||||
asset: { findUnique: vi.fn(), findFirst: vi.fn() },
|
||||
storageKey: { findFirst: vi.fn(), findUnique: vi.fn() },
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/s3/s3')>()
|
||||
return {
|
||||
...actual,
|
||||
s3Service: {
|
||||
headObject: vi.fn(),
|
||||
downloadToFile: vi.fn(),
|
||||
presign: vi.fn().mockResolvedValue('https://signed.example/file'),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/authz/authz')>()
|
||||
return { ...actual, authzService: { hasPermission: vi.fn() } }
|
||||
})
|
||||
|
||||
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
|
||||
type Saved = { filePath: string; absolutePath: string; contentType: string; size: number }
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
|
||||
function downloadTool(userId = 'user-1') {
|
||||
return toAgentTool(getOperation('download_asset')!, { userId })
|
||||
}
|
||||
|
||||
function textOf(result: { content: unknown[] }): string {
|
||||
return (result.content[0] as { text: string }).text
|
||||
}
|
||||
|
||||
function mockAssets(...assets: Array<Record<string, unknown>>) {
|
||||
vi.mocked(prisma.asset.findUnique).mockImplementation(
|
||||
(async (args: { where: { id: string } }) =>
|
||||
assets.find((a) => a.id === args.where.id) ?? null) as never,
|
||||
)
|
||||
}
|
||||
|
||||
function mockStorage(contentType: string, write = 'bytes') {
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({ size: 1234, contentType } as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, dest) => {
|
||||
await fs.promises.writeFile(dest, write)
|
||||
})
|
||||
}
|
||||
|
||||
const photo = {
|
||||
id: 'img-1',
|
||||
name: 'sample_photo.jpg',
|
||||
type: 'file',
|
||||
isDeleted: false,
|
||||
storageKey: { key: 'files/up-1/sample_photo.jpg' },
|
||||
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/img-1/proxy.webp' }] },
|
||||
}
|
||||
|
||||
describe('download_asset agent tool', () => {
|
||||
const created: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const file of created.splice(0)) fs.rmSync(file, { force: true })
|
||||
})
|
||||
|
||||
it('offers assetIds, proxy, and the agent-only key parameter', () => {
|
||||
const tool = downloadTool()
|
||||
const schema = tool.parameters as { properties: Record<string, unknown>; required?: string[] }
|
||||
expect(Object.keys(schema.properties)).toEqual(['assetIds', 'proxy', 'key'])
|
||||
expect(schema.required ?? []).not.toContain('assetIds')
|
||||
expect(tool.description).toContain('.pi directory')
|
||||
})
|
||||
|
||||
it('saves the web preview into .pi by default, named after the asset', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/webp', 'proxy-bytes')
|
||||
|
||||
const result = await downloadTool().execute('call-1', { assetIds: ['img-1'] })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
|
||||
created.push(expectedPath)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'img-1',
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/img-1/proxy.webp',
|
||||
expectedPath,
|
||||
)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('proxy-bytes')
|
||||
expect(textOf(result)).toBe(
|
||||
[
|
||||
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.join('.pi', 'img-1_sample_photo.webp')}".`,
|
||||
'Remember to delete these temporary files when finished.',
|
||||
].join('\n'),
|
||||
)
|
||||
const details = result.details as { files: Saved[] }
|
||||
expect(details.files[0]).toMatchObject({
|
||||
filePath: path.join('.pi', 'img-1_sample_photo.webp'),
|
||||
contentType: 'image/webp',
|
||||
size: 11,
|
||||
})
|
||||
})
|
||||
|
||||
it('saves the original with proxy false', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/jpeg')
|
||||
|
||||
await downloadTool().execute('call-1', { assetIds: ['img-1'], proxy: false })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
|
||||
created.push(expectedPath)
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/up-1/sample_photo.jpg',
|
||||
expectedPath,
|
||||
)
|
||||
})
|
||||
|
||||
it('downloads several files and the latest version of a version stack', async () => {
|
||||
mockAssets(photo, { id: 'stack-1', name: 'banana', type: 'version_stack', isDeleted: false })
|
||||
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
|
||||
id: 'file-v2',
|
||||
name: 'banana_pig.png',
|
||||
type: 'file',
|
||||
isDeleted: false,
|
||||
storageKey: { key: 'files/up-2/banana_pig.png' },
|
||||
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/file-v2/proxy.webp' }] },
|
||||
} as unknown as Asset)
|
||||
mockStorage('image/webp')
|
||||
|
||||
const result = await downloadTool().execute('call-1', {
|
||||
assetIds: ['img-1', 'stack-1'],
|
||||
key: null,
|
||||
})
|
||||
|
||||
created.push(
|
||||
path.join(piDir, 'img-1_sample_photo.webp'),
|
||||
path.join(piDir, 'file-v2_banana_pig.webp'),
|
||||
)
|
||||
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
|
||||
where: { parentId: 'stack-1', isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledTimes(2)
|
||||
expect(textOf(result)).toContain('Downloaded "banana_pig.webp" (ID: file-v2, proxy')
|
||||
})
|
||||
|
||||
it('rejects folders', async () => {
|
||||
mockAssets({ id: 'folder-1', name: 'Renders', type: 'folder', isDeleted: false })
|
||||
await expect(downloadTool().execute('call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
|
||||
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
|
||||
)
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks Read on every asset before downloading anything', async () => {
|
||||
mockAssets(photo)
|
||||
vi.mocked(authzService.hasPermission).mockImplementation(async ({ id }) => {
|
||||
if (id === 'secret') throw new Error('Forbidden')
|
||||
})
|
||||
await expect(
|
||||
downloadTool().execute('call-1', { assetIds: ['img-1', 'secret'] }),
|
||||
).rejects.toThrow('Forbidden')
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires assetIds or key', async () => {
|
||||
await expect(downloadTool().execute('call-1', { assetIds: null, key: null })).rejects.toThrow(
|
||||
'Invalid input for download_asset',
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects assetIds and key together', async () => {
|
||||
await expect(
|
||||
downloadTool().execute('call-1', { assetIds: ['img-1'], key: 'files/img-1/a.webp' }),
|
||||
).rejects.toThrow('Provide either "assetIds" or "key", not both.')
|
||||
})
|
||||
|
||||
describe('by storage key', () => {
|
||||
it('requires a user', async () => {
|
||||
await expect(
|
||||
downloadTool('').execute('call-1', { key: 'files/ast-1/shot.webp' }),
|
||||
).rejects.toThrow('User ID is required for authorization.')
|
||||
})
|
||||
|
||||
it('rejects keys outside files/ and path traversal', async () => {
|
||||
await expect(downloadTool().execute('call-1', { key: 'avatars/user-1.png' })).rejects.toThrow(
|
||||
'Invalid storage key format: key must start with "files/"',
|
||||
)
|
||||
await expect(
|
||||
downloadTool().execute('call-1', { key: 'files/../../etc/passwd' }),
|
||||
).rejects.toThrow('cannot contain ".."')
|
||||
})
|
||||
|
||||
it('rejects keys that belong to no asset', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
|
||||
await expect(
|
||||
downloadTool().execute('call-1', { key: 'files/nope/shot.webp' }),
|
||||
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
|
||||
})
|
||||
|
||||
it('checks Read on the owning asset', async () => {
|
||||
mockAssets({ id: 'other-project-asset' })
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
|
||||
await expect(
|
||||
downloadTool().execute('call-1', { key: 'files/other-project-asset/shots/a.webp' }),
|
||||
).rejects.toThrow('Forbidden')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'other-project-asset',
|
||||
})
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('downloads a read_asset artifact into .pi', async () => {
|
||||
mockAssets({ id: 'ast-123' })
|
||||
mockStorage('image/webp', 'frame-bytes')
|
||||
|
||||
const result = await downloadTool().execute('call-1', {
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
|
||||
created.push(expectedPath)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('frame-bytes')
|
||||
expect(textOf(result)).toBe(
|
||||
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
|
||||
)
|
||||
expect(result.details).toMatchObject({
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
assetId: 'ast-123',
|
||||
size: Buffer.from('frame-bytes').length,
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves original upload keys through the storage key', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
|
||||
id: 'sk-1',
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
assets: [{ id: 'asset-photo-1' }],
|
||||
} as unknown as StorageKey & { assets: Asset[] })
|
||||
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
size: 8,
|
||||
contentType: 'application/octet-stream',
|
||||
} as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, pngHeader)
|
||||
})
|
||||
|
||||
const result = await downloadTool().execute('call-1', {
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
})
|
||||
|
||||
created.push(path.join(piDir, 'photo.png'))
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'asset-photo-1' }),
|
||||
)
|
||||
// Falls back to detecting the type from the bytes
|
||||
expect(result.details).toMatchObject({ assetId: 'asset-photo-1', contentType: 'image/png' })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
|
||||
import type { User } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { resolveAssetIdFromKey } from '../tools/download-asset'
|
||||
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
|
||||
|
||||
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
|
||||
|
||||
/** The agent's sandbox, where downloaded files are saved for local scripts and bash. */
|
||||
function sandboxDir(): string {
|
||||
const dir = path.join(process.cwd(), '.pi')
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
return dir
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
/** Saves a storage object into the sandbox; returns the paths and detected content type. */
|
||||
async function saveToSandbox(key: string, filename: string) {
|
||||
const dir = sandboxDir()
|
||||
const absolutePath = path.join(dir, filename)
|
||||
const bucket = storageBucket()
|
||||
const info = await s3Service.headObject(bucket, key).catch(() => null)
|
||||
await s3Service.downloadToFile(bucket, key, absolutePath)
|
||||
const size = await fs.promises
|
||||
.stat(absolutePath)
|
||||
.then((s) => s.size)
|
||||
.catch(() => info?.size ?? 0)
|
||||
const contentType =
|
||||
info?.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: readFileMimeType(absolutePath)
|
||||
return { absolutePath, filePath: path.join('.pi', filename), size, contentType }
|
||||
}
|
||||
|
||||
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
|
||||
async function downloadKey(key: string, userId: string): Promise<AgentToolResult<unknown>> {
|
||||
const owningAssetId = await resolveAssetIdFromKey(key)
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: owningAssetId,
|
||||
})
|
||||
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
|
||||
const saved = await saveToSandbox(key, filename)
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Downloaded storage key "${key}" to "${saved.filePath}". Remember to delete this temporary file when finished.`,
|
||||
},
|
||||
],
|
||||
details: { key, assetId: owningAssetId, ...saved },
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves each file of a download_asset result into the sandbox. */
|
||||
export async function presentDownloadOutput(
|
||||
output: DownloadAssetOutput,
|
||||
): Promise<AgentToolResult<unknown>> {
|
||||
const lines: string[] = []
|
||||
const files = []
|
||||
for (const file of output.files) {
|
||||
if (!file.key) throw new Error(`download_asset returned no storage key for ${file.assetId}`)
|
||||
const saved = await saveToSandbox(
|
||||
file.key,
|
||||
`${file.assetId}_${sanitizeFilename(file.name) || 'file'}`,
|
||||
)
|
||||
lines.push(
|
||||
`Downloaded "${file.name}" (ID: ${file.assetId}, ${file.kind}, ${saved.contentType}, ${formatSize(saved.size)}) to "${saved.filePath}".`,
|
||||
)
|
||||
files.push({ assetId: file.assetId, name: file.name, kind: file.kind, ...saved })
|
||||
}
|
||||
lines.push(CLEANUP_REMINDER)
|
||||
return { content: [{ type: 'text', text: lines.join('\n') }], details: { files } }
|
||||
}
|
||||
|
||||
const downloadAssetExtension: AgentToolExtension = {
|
||||
description:
|
||||
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the local .pi directory, for processing with local scripts or bash commands. ` +
|
||||
'By default it saves the web preview version (proxy) when there is one, e.g. the transcoded video or the web image; set proxy to false for the original uploaded file. ' +
|
||||
'A version stack downloads its latest version; folders are not supported. ' +
|
||||
'To download a specific artifact from read_asset (e.g. a frame or page), pass its storage key as "key" instead of assetIds. ' +
|
||||
'Remember to delete the downloaded files when finished.',
|
||||
parameterOverrides: z.object({
|
||||
assetIds: downloadAsset.input.shape.assetIds
|
||||
.optional()
|
||||
.describe(
|
||||
`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}). Omit when passing "key".`,
|
||||
),
|
||||
}),
|
||||
extraParameters: z.object({
|
||||
key: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Storage S3 key of a specific media artifact to download instead of assetIds, e.g. a screenshot or page key from read_asset.',
|
||||
),
|
||||
}),
|
||||
async intercept(input, extra, ctx) {
|
||||
if (typeof extra.key !== 'string') return undefined
|
||||
if (Array.isArray(input.assetIds) && input.assetIds.length > 0) {
|
||||
throw new Error('Provide either "assetIds" or "key", not both.')
|
||||
}
|
||||
if (!ctx.userId) throw new Error('User ID is required for authorization.')
|
||||
return downloadKey(extra.key, ctx.userId)
|
||||
},
|
||||
present: (output) => presentDownloadOutput(output as DownloadAssetOutput),
|
||||
}
|
||||
|
||||
registerAgentToolExtension('download_asset', downloadAssetExtension)
|
||||
@@ -1,2 +1,3 @@
|
||||
// Registers agent-specific presentation for Operations. Import once before building tools.
|
||||
export { createAutofillReadAssetTool, presentReadOutput } from './read-asset'
|
||||
export { presentDownloadOutput } from './download-asset'
|
||||
|
||||
@@ -61,7 +61,7 @@ describe('operation-backed agent tools', () => {
|
||||
})
|
||||
|
||||
describe('tool definitions', () => {
|
||||
it('keeps the existing tool names and adds list_projects and get_asset_render', () => {
|
||||
it('keeps the existing tool names and adds the newer Operations', () => {
|
||||
expect(
|
||||
buildOperationTools(ctx)
|
||||
.map((t) => t.name)
|
||||
@@ -69,6 +69,7 @@ describe('operation-backed agent tools', () => {
|
||||
).toEqual([
|
||||
'create_folder',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
|
||||
@@ -19,10 +19,27 @@ export type AgentOperationContext = Omit<OperationContext, 'via'>
|
||||
* and render the output (e.g. as image blocks).
|
||||
*/
|
||||
export interface AgentToolExtension {
|
||||
/** Replaces the Operation description for the agent (e.g. where files end up). */
|
||||
description?: string
|
||||
/** Extra parameters only the agent sees; they are removed before the Operation runs. */
|
||||
extraParameters?: z.ZodObject
|
||||
/**
|
||||
* Agent-facing versions of Operation input fields, e.g. a required field made optional
|
||||
* because an extra parameter can be used instead. The Operation still validates its own
|
||||
* input when it runs.
|
||||
*/
|
||||
parameterOverrides?: z.ZodObject
|
||||
/** Adjust the Operation input using the extra parameters. */
|
||||
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
|
||||
/**
|
||||
* Handle an agent-only mode without running the Operation (e.g. a storage key instead of
|
||||
* an asset). Return undefined to run the Operation.
|
||||
*/
|
||||
intercept?(
|
||||
input: Record<string, unknown>,
|
||||
extra: Record<string, unknown>,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult<unknown> | undefined>
|
||||
present(output: unknown, extra: Record<string, unknown>): Promise<AgentToolResult<unknown>>
|
||||
}
|
||||
|
||||
@@ -34,9 +51,10 @@ export function registerAgentToolExtension(name: string, extension: AgentToolExt
|
||||
}
|
||||
|
||||
function toolInputSchema(op: Operation, extension?: AgentToolExtension): z.ZodObject {
|
||||
return extension?.extraParameters
|
||||
? op.definition.input.extend(extension.extraParameters.shape)
|
||||
: op.definition.input
|
||||
let schema = op.definition.input
|
||||
if (extension?.parameterOverrides) schema = schema.extend(extension.parameterOverrides.shape)
|
||||
if (extension?.extraParameters) schema = schema.extend(extension.extraParameters.shape)
|
||||
return schema
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,10 +98,14 @@ export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentToo
|
||||
return {
|
||||
name: definition.name,
|
||||
label: definition.title,
|
||||
description: definition.description,
|
||||
description: extension?.description ?? definition.description,
|
||||
parameters: toToolParameters(op, extension),
|
||||
execute: async (_toolCallId, params) => {
|
||||
const { input, extra } = splitAgentParams(op, extension, params)
|
||||
if (extension?.intercept) {
|
||||
const handled = await extension.intercept(input as Record<string, unknown>, extra, ctx)
|
||||
if (handled) return handled
|
||||
}
|
||||
const output = await runOperation(op, { ...ctx, via: 'agent' }, input)
|
||||
if (extension) {
|
||||
return extension.present(output, extra)
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import {
|
||||
createDownloadAssetTool,
|
||||
resolveAssetIdFromKey,
|
||||
resolveS3MediaBuffer,
|
||||
} from './download-asset'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { resolveAssetIdFromKey, resolveS3MediaBuffer } from './download-asset'
|
||||
import { prisma, type Asset, type StorageKey } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
vi.mock('@shumai/db', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/db')>()
|
||||
@@ -43,333 +37,11 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
describe('downloadAssetTool', () => {
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
const createdFiles: string[] = []
|
||||
|
||||
describe('download-asset storage key helpers', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const f of createdFiles) {
|
||||
if (fs.existsSync(f)) {
|
||||
fs.unlinkSync(f)
|
||||
}
|
||||
}
|
||||
createdFiles.length = 0
|
||||
})
|
||||
|
||||
it('should throw authorization error if user ID is empty', async () => {
|
||||
const tool = createDownloadAssetTool('')
|
||||
await expect(tool.execute('call-1', { assetId: 'asset-1', key: null })).rejects.toThrow(
|
||||
'User ID is required for authorization.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw error if both assetId and key are null', async () => {
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(tool.execute('call-1', { assetId: null, key: null })).rejects.toThrow(
|
||||
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw error if both assetId and key are provided', async () => {
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { assetId: 'asset-1', key: 'files/path/file.png' }),
|
||||
).rejects.toThrow(
|
||||
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
|
||||
)
|
||||
})
|
||||
|
||||
describe('Download by assetId', () => {
|
||||
it('should throw error if asset not found', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(tool.execute('call-1', { assetId: 'asset-1', key: null })).rejects.toThrow(
|
||||
'Asset with ID asset-1 not found.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should download proxy image to .pi directory when downloading by assetId', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'asset-img-1',
|
||||
name: 'sample_photo.jpg',
|
||||
storageKey: { key: 'raw/sample_photo.jpg' },
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [{ key: 'proxy/sample_photo.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, 'fake-proxy-image-bytes')
|
||||
})
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
contentType: 'image/webp',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', { assetId: 'asset-img-1', key: null })
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'asset-img-1',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'asset-img-1_sample_photo.jpg')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'proxy/sample_photo.webp',
|
||||
expectedPath,
|
||||
)
|
||||
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-proxy-image-bytes')
|
||||
|
||||
expect(result.details.filePath).toBe(path.join('.pi', 'asset-img-1_sample_photo.jpg'))
|
||||
expect(result.details.contentType).toBe('image/webp')
|
||||
expect((result.content[0] as { type: 'text'; text: string }).text).toContain(
|
||||
'Remember to delete this temporary file when finished.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should resolve version_stack asset to its latest version file', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'stack-1',
|
||||
name: '',
|
||||
type: 'version_stack',
|
||||
storageKey: null,
|
||||
media: null,
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
|
||||
id: 'file-ver-2',
|
||||
name: 'banana_pig.png',
|
||||
type: 'file',
|
||||
storageKey: { key: 'raw/banana_pig.png' },
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [{ key: 'proxy/banana_pig.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, 'fake-version-bytes')
|
||||
})
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
contentType: 'image/webp',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', { assetId: 'stack-1', key: null })
|
||||
|
||||
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
|
||||
where: { parentId: 'stack-1', isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'file-ver-2_banana_pig.png')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'proxy/banana_pig.webp',
|
||||
expectedPath,
|
||||
)
|
||||
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(result.details.name).toBe('banana_pig.png')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Download by S3 key and Authorization', () => {
|
||||
it('should reject keys that do not start with files/', async () => {
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { assetId: null, key: 'avatars/user-1.png' }),
|
||||
).rejects.toThrow('Invalid storage key format: key must start with "files/"')
|
||||
})
|
||||
|
||||
it('should reject keys with path traversal (..)', async () => {
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { assetId: null, key: 'files/../../etc/passwd' }),
|
||||
).rejects.toThrow('cannot contain ".."')
|
||||
})
|
||||
|
||||
it('should reject keys with insufficient path segments', async () => {
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(tool.execute('call-1', { assetId: null, key: 'files/invalid' })).rejects.toThrow(
|
||||
'Invalid storage key format',
|
||||
)
|
||||
})
|
||||
|
||||
it('should reject keys that do not belong to any valid asset in database', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { assetId: null, key: 'files/nonexistent-id/shot.webp' }),
|
||||
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
|
||||
})
|
||||
|
||||
it('should reject download when user lacks read permission on the owning asset (cross-project protection)', async () => {
|
||||
// Key belongs to asset-in-other-project
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'asset-in-other-project',
|
||||
} as unknown as Asset)
|
||||
|
||||
// Authz rejects because user is in a different project/team
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new Error('User does not have Read permission on asset asset-in-other-project'),
|
||||
)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', {
|
||||
assetId: null,
|
||||
key: 'files/asset-in-other-project/screenshots/secret_frame.webp',
|
||||
}),
|
||||
).rejects.toThrow('User does not have Read permission on asset asset-in-other-project')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'asset-in-other-project',
|
||||
})
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should authorize and download derived artifact key (files/<assetId>/...)', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'ast-123',
|
||||
} as unknown as Asset)
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, 'fake-screenshot-bytes')
|
||||
})
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
contentType: 'image/webp',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', {
|
||||
assetId: null,
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
})
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'ast-123',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
expectedPath,
|
||||
)
|
||||
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('fake-screenshot-bytes')
|
||||
|
||||
expect(result.details.filePath).toBe(path.join('.pi', 'shot_5.0s.webp'))
|
||||
expect(result.details.key).toBe('files/ast-123/screenshots/shot_5.0s.webp')
|
||||
expect(result.details.assetId).toBe('ast-123')
|
||||
expect(result.details.size).toBe(Buffer.from('fake-screenshot-bytes').length)
|
||||
})
|
||||
|
||||
it('should authorize and download original upload key (files/<uploadUlid>/...) via StorageKey', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
|
||||
id: 'sk-1',
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
assets: [{ id: 'asset-photo-1' }],
|
||||
} as unknown as StorageKey & { assets: Asset[] })
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, 'fake-original-photo-bytes')
|
||||
})
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
contentType: 'image/png',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', {
|
||||
assetId: null,
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
})
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'asset-photo-1',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'photo.png')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/upload-ulid-456/photo.png',
|
||||
expectedPath,
|
||||
)
|
||||
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(result.details.assetId).toBe('asset-photo-1')
|
||||
})
|
||||
|
||||
it('should fall back to file MIME detection when headObject returns generic application/octet-stream', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
|
||||
id: 'sk-2',
|
||||
key: 'files/upload-ulid-789/graphic.png',
|
||||
assets: [{ id: 'asset-graphic-1' }],
|
||||
} as unknown as StorageKey & { assets: Asset[] })
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
await fs.promises.writeFile(dest, pngHeader)
|
||||
})
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
contentType: 'application/octet-stream',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.headObject>>)
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', {
|
||||
assetId: null,
|
||||
key: 'files/upload-ulid-789/graphic.png',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'graphic.png')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(result.details.contentType).toBe('image/png')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveAssetIdFromKey helper unit tests', () => {
|
||||
it('resolves directly by asset ID', async () => {
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'ast-999' } as unknown as Asset)
|
||||
|
||||
@@ -1,32 +1,8 @@
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
// Storage-key helpers shared by download_asset (operation-extensions) and the media generation tools.
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
export const downloadAssetSchema = Type.Object(
|
||||
{
|
||||
assetId: Type.Union([
|
||||
Type.String({
|
||||
description:
|
||||
'The asset ID of the workspace asset to download to local disk, or null if providing "key".',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
key: Type.Union([
|
||||
Type.String({
|
||||
description:
|
||||
'The storage S3 key of a specific media artifact (e.g. a screenshot or transcode key from read_asset) to download to local disk, or null if providing "assetId".',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
|
||||
export async function resolveAssetIdFromKey(key: string): Promise<string> {
|
||||
if (!key.startsWith('files/') || key.includes('..')) {
|
||||
@@ -118,177 +94,3 @@ export async function resolveS3MediaBuffer(
|
||||
|
||||
return { buffer, mimeType }
|
||||
}
|
||||
|
||||
export function createDownloadAssetTool(userId: string): AgentTool<typeof downloadAssetSchema> {
|
||||
return {
|
||||
name: 'download_asset',
|
||||
label: 'Download Asset',
|
||||
description:
|
||||
'Downloads a workspace asset or specific storage S3 key to the local .pi directory for processing with local scripts or bash commands. ' +
|
||||
'Provide exactly one of "assetId" (for full assets) or "key" (for intermediate artifacts like screenshots from read_asset). ' +
|
||||
'Remember to delete the temporary downloaded file when finished.',
|
||||
parameters: downloadAssetSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const { assetId, key } = params
|
||||
|
||||
if (!userId) {
|
||||
throw new Error('User ID is required for authorization.')
|
||||
}
|
||||
|
||||
const hasAssetId = assetId !== null
|
||||
const hasKey = key !== null
|
||||
|
||||
if (hasAssetId === hasKey) {
|
||||
throw new Error(
|
||||
'Provide exactly one of "assetId" (to download a workspace asset) or "key" (to download a specific S3 storage key). Set the unused parameter to null.',
|
||||
)
|
||||
}
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) {
|
||||
fs.mkdirSync(piDir, { recursive: true })
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
// Branch A: Download by assetId
|
||||
if (assetId) {
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
|
||||
let asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
if (!asset) {
|
||||
throw new Error(`Asset with ID ${assetId} not found.`)
|
||||
}
|
||||
|
||||
if (asset.type === 'version_stack') {
|
||||
const latestVersion = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (latestVersion) {
|
||||
asset = latestVersion
|
||||
}
|
||||
}
|
||||
|
||||
let mediaKey = asset.storageKey?.key
|
||||
|
||||
if (asset.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
if (
|
||||
mediaInfo.proxyType === 'image' ||
|
||||
(mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0)
|
||||
) {
|
||||
if (mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0) {
|
||||
mediaKey = mediaInfo.imageTranscodes[0].key || mediaKey
|
||||
}
|
||||
} else if (
|
||||
mediaInfo.proxyType === 'video' ||
|
||||
(mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) ||
|
||||
mediaInfo.videoPreview?.key
|
||||
) {
|
||||
if (mediaInfo.videoTranscodes && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaKey = mediaInfo.videoTranscodes[0].key || mediaKey
|
||||
} else if (mediaInfo.videoPreview?.key) {
|
||||
mediaKey = mediaInfo.videoPreview.key
|
||||
}
|
||||
} else if (mediaInfo.original?.key) {
|
||||
mediaKey = mediaInfo.original.key || mediaKey
|
||||
}
|
||||
}
|
||||
|
||||
if (!mediaKey) {
|
||||
throw new Error(`No media content found for asset ${assetId}.`)
|
||||
}
|
||||
|
||||
const safeName = sanitizeFilename(asset.name || 'file')
|
||||
const filename = `${asset.id}_${safeName}`
|
||||
const targetFilePath = path.join(piDir, filename)
|
||||
const relativePath = path.join('.pi', filename)
|
||||
|
||||
const objectInfo = await s3Service.headObject(bucket, mediaKey).catch(() => null)
|
||||
await s3Service.downloadToFile(bucket, mediaKey, targetFilePath)
|
||||
const stat = await fs.promises
|
||||
.stat(targetFilePath)
|
||||
.catch(() => ({ size: objectInfo?.size ?? 0 }))
|
||||
const contentType =
|
||||
objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream'
|
||||
? objectInfo.contentType
|
||||
: readFileMimeType(targetFilePath)
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Downloaded asset "${asset.name}" (ID: ${assetId}) to "${relativePath}". Remember to delete this temporary file when finished.`,
|
||||
},
|
||||
],
|
||||
details: {
|
||||
assetId,
|
||||
name: asset.name,
|
||||
filePath: relativePath,
|
||||
absolutePath: targetFilePath,
|
||||
contentType,
|
||||
size: stat.size,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Branch B: Download by S3 storage key
|
||||
if (key) {
|
||||
const owningAssetId = await resolveAssetIdFromKey(key)
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: owningAssetId,
|
||||
})
|
||||
|
||||
const rawBasename = path.basename(key)
|
||||
const safeBasename = sanitizeFilename(rawBasename) || 'downloaded_file'
|
||||
const filename = safeBasename
|
||||
const targetFilePath = path.join(piDir, filename)
|
||||
const relativePath = path.join('.pi', filename)
|
||||
|
||||
const objectInfo = await s3Service.headObject(bucket, key).catch(() => null)
|
||||
await s3Service.downloadToFile(bucket, key, targetFilePath)
|
||||
const stat = await fs.promises
|
||||
.stat(targetFilePath)
|
||||
.catch(() => ({ size: objectInfo?.size ?? 0 }))
|
||||
const contentType =
|
||||
objectInfo?.contentType && objectInfo.contentType !== 'application/octet-stream'
|
||||
? objectInfo.contentType
|
||||
: readFileMimeType(targetFilePath)
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Downloaded storage key "${key}" to "${relativePath}". Remember to delete this temporary file when finished.`,
|
||||
},
|
||||
],
|
||||
details: {
|
||||
key,
|
||||
assetId: owningAssetId,
|
||||
filePath: relativePath,
|
||||
absolutePath: targetFilePath,
|
||||
contentType,
|
||||
size: stat.size,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Invalid download_asset parameters.')
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ export async function presentReadForMcp(
|
||||
if (output.text) {
|
||||
text += `\n\n${output.text.content}`
|
||||
if (output.text.truncated) {
|
||||
text += `\n\n[Content truncated: showing the first part of a ${output.text.size}-byte file.]`
|
||||
text += `\n\n[Content truncated: showing the first part of a ${output.text.size}-byte file. Use download_asset to get the whole file.]`
|
||||
}
|
||||
}
|
||||
return { content: [{ type: 'text', text }, ...images], structuredContent }
|
||||
|
||||
@@ -255,6 +255,43 @@ describe('MCP server and /api/ops (integration)', () => {
|
||||
expect(await render.json()).toEqual({ error: 'Render not found' })
|
||||
})
|
||||
|
||||
it('gives MCP and CLI callers a download link to the file', async () => {
|
||||
const client = await connect(reviewerToken)
|
||||
const result = await client.callTool({
|
||||
name: 'download_asset',
|
||||
arguments: { assetIds: [imageId] },
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const viaMcp = result.structuredContent as { files: Array<Record<string, unknown>> }
|
||||
expect(viaMcp.files).toEqual([
|
||||
{
|
||||
assetId: imageId,
|
||||
name: 'photo.png',
|
||||
kind: 'original',
|
||||
size: png.length,
|
||||
mimeType: 'image/png',
|
||||
url: expect.any(String),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request('/api/ops/download_asset', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${reviewerToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'x-shumai-client': 'cli',
|
||||
},
|
||||
body: JSON.stringify({ assetIds: [imageId], proxy: false }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const viaCli = (await res.json()) as { files: Array<{ url: string; key?: string }> }
|
||||
expect(viaCli.files[0].key).toBeUndefined()
|
||||
const link = new URL(viaCli.files[0].url)
|
||||
const file = await app.request(link.pathname + link.search)
|
||||
expect(file.status).toBe(200)
|
||||
expect(Buffer.from(await file.arrayBuffer()).equals(png)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not let users outside the project read', async () => {
|
||||
const outsider = await prisma.user.create({
|
||||
data: { name: 'Outsider', email: 'mcp-outsider@test.com', password: 'pw' },
|
||||
|
||||
@@ -55,6 +55,7 @@ describe('MCP server', () => {
|
||||
expect(tools.map((t) => t.name).sort()).toEqual([
|
||||
'create_folder',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
@@ -136,7 +137,7 @@ describe('MCP server', () => {
|
||||
|
||||
it('does not expose agent-only capabilities', async () => {
|
||||
const names = (await client.listTools()).tools.map((t) => t.name)
|
||||
for (const agentOnly of ['bash', 'read_skill', 'download_asset', 'mcp']) {
|
||||
for (const agentOnly of ['bash', 'read_skill', 'mcp']) {
|
||||
expect(names).not.toContain(agentOnly)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AssetType, prisma, type Prisma, type User } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { downloadAssetOp, runOperation, type OperationContext } from '@shumai/core/src/operations'
|
||||
import { READ_URL_EXPIRES_SECONDS } from '@shumai/core/src/asset-read/asset-read'
|
||||
import { proxyKeyOf } from './asset-download'
|
||||
|
||||
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
|
||||
|
||||
describe('download_asset Operation', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let owner: User
|
||||
let reviewer: User
|
||||
let outsider: User
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
|
||||
const as = (user: User, via: OperationContext['via'] = 'cli'): OperationContext => ({
|
||||
userId: user.id,
|
||||
via,
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: 'dl-owner@test.com', password: 'pw' },
|
||||
})
|
||||
reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'dl-reviewer@test.com', password: 'pw' },
|
||||
})
|
||||
outsider = await prisma.user.create({
|
||||
data: { name: 'Outsider', email: 'dl-outsider@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Download Team' } })
|
||||
await prisma.teamMember.create({ data: { teamId: team.id, userId: owner.id, role: 'owner' } })
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewer.id, role: 'reviewer' },
|
||||
})
|
||||
const project = await projectService.createProject(owner, {
|
||||
teamId: team.id,
|
||||
name: 'Download Project',
|
||||
})
|
||||
projectId = project.id
|
||||
rootFolderId = project.rootFolder!
|
||||
|
||||
vi.spyOn(s3Service, 'presign').mockImplementation(
|
||||
async (_bucket, key) => `https://signed.example/${key}`,
|
||||
)
|
||||
vi.spyOn(s3Service, 'headObject').mockImplementation(
|
||||
async (_bucket, key) => ({ key, size: 100, contentType: 'application/octet-stream' }) as Head,
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function createFile(
|
||||
name: string,
|
||||
data: Partial<Prisma.AssetUncheckedCreateInput> & { key?: string } = {},
|
||||
) {
|
||||
const { key, ...rest } = data
|
||||
const storageKey = key ? await prisma.storageKey.create({ data: { key } }) : null
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: AssetType.file,
|
||||
status: 'uploaded',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
storageKeyId: storageKey?.id,
|
||||
...rest,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const media = (value: Record<string, unknown>) => value as unknown as PrismaJson.MediaInfo
|
||||
|
||||
it('returns the web preview by default and the original with proxy false', async () => {
|
||||
const photo = await createFile('photo.jpg', {
|
||||
key: 'files/up-1/photo.jpg',
|
||||
media: media({ proxyType: 'image', imageTranscodes: [{ key: 'files/p-1/web.webp' }] }),
|
||||
})
|
||||
|
||||
const preview = await runOperation(downloadAssetOp, as(reviewer), { assetIds: [photo.id] })
|
||||
expect(preview).toEqual({
|
||||
files: [
|
||||
{
|
||||
assetId: photo.id,
|
||||
name: 'photo.webp',
|
||||
kind: 'proxy',
|
||||
size: 100,
|
||||
mimeType: 'image/webp',
|
||||
url: 'https://signed.example/files/p-1/web.webp',
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/p-1/web.webp',
|
||||
'GET',
|
||||
true,
|
||||
'photo.webp',
|
||||
false,
|
||||
READ_URL_EXPIRES_SECONDS,
|
||||
)
|
||||
|
||||
const original = await runOperation(downloadAssetOp, as(reviewer), {
|
||||
assetIds: [photo.id],
|
||||
proxy: false,
|
||||
})
|
||||
expect(original.files[0]).toMatchObject({
|
||||
name: 'photo.jpg',
|
||||
kind: 'original',
|
||||
mimeType: 'image/jpeg',
|
||||
url: 'https://signed.example/files/up-1/photo.jpg',
|
||||
})
|
||||
})
|
||||
|
||||
it('renames a video proxy to its extension and falls back to the original without one', async () => {
|
||||
const clip = await createFile('clip.mov', {
|
||||
key: 'files/up-2/clip.mov',
|
||||
media: media({ proxyType: 'video', videoTranscodes: [{ key: 'files/c-1/720p.mp4' }] }),
|
||||
})
|
||||
const song = await createFile('song.wav', {
|
||||
key: 'files/up-3/song.wav',
|
||||
media: media({ proxyType: 'audio', original: { key: 'files/up-3/song.wav' } }),
|
||||
})
|
||||
const archive = await createFile('bundle.zip', { key: 'files/up-4/bundle.zip' })
|
||||
|
||||
const { files } = await runOperation(downloadAssetOp, as(owner), {
|
||||
assetIds: [clip.id, song.id, archive.id, clip.id],
|
||||
})
|
||||
|
||||
expect(files.map((f) => [f.name, f.kind])).toEqual([
|
||||
['clip.mp4', 'proxy'],
|
||||
['song.wav', 'original'],
|
||||
['bundle.zip', 'original'],
|
||||
])
|
||||
})
|
||||
|
||||
it('downloads the latest version of a version stack', async () => {
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'diagram',
|
||||
type: AssetType.version_stack,
|
||||
status: 'uploaded',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
},
|
||||
})
|
||||
await createFile('diagram_v1.png', {
|
||||
parentId: stack.id,
|
||||
sortIndex: 'b',
|
||||
key: 'files/v1/diagram_v1.png',
|
||||
})
|
||||
const v2 = await createFile('diagram_v2.png', {
|
||||
parentId: stack.id,
|
||||
sortIndex: 'a',
|
||||
key: 'files/v2/diagram_v2.png',
|
||||
})
|
||||
|
||||
const { files } = await runOperation(downloadAssetOp, as(owner), { assetIds: [stack.id] })
|
||||
|
||||
expect(files).toEqual([expect.objectContaining({ assetId: v2.id, name: 'diagram_v2.png' })])
|
||||
})
|
||||
|
||||
it('only gives storage keys to the built-in agent', async () => {
|
||||
const doc = await createFile('notes.md', { key: 'files/up-5/notes.md' })
|
||||
for (const via of ['mcp', 'cli', 'api'] as const) {
|
||||
const { files } = await runOperation(downloadAssetOp, as(owner, via), { assetIds: [doc.id] })
|
||||
expect(files[0]).not.toHaveProperty('key')
|
||||
}
|
||||
const { files } = await runOperation(downloadAssetOp, as(owner, 'agent'), {
|
||||
assetIds: [doc.id],
|
||||
})
|
||||
expect(files[0].key).toBe('files/up-5/notes.md')
|
||||
})
|
||||
|
||||
it('rejects folders', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Renders',
|
||||
type: AssetType.folder,
|
||||
status: 'uploaded',
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
},
|
||||
})
|
||||
await expect(
|
||||
runOperation(downloadAssetOp, as(owner), { assetIds: [folder.id] }),
|
||||
).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: `Asset ${folder.id} ("Renders") is a folder. Download the files inside it instead.`,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects users without Read access before resolving anything', async () => {
|
||||
const doc = await createFile('notes.md', { key: 'files/up-6/notes.md' })
|
||||
await expect(
|
||||
runOperation(downloadAssetOp, as(outsider), { assetIds: [doc.id] }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(s3Service.headObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports files missing from storage', async () => {
|
||||
const doc = await createFile('notes.md', { key: 'files/up-7/notes.md' })
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('NotFound'))
|
||||
await expect(
|
||||
runOperation(downloadAssetOp, as(owner), { assetIds: [doc.id] }),
|
||||
).rejects.toMatchObject({
|
||||
status: 404,
|
||||
message: `The file for asset ${doc.id} ("notes.md") is missing from storage.`,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([[[]], [Array.from({ length: 51 }, (_, i) => `a-${i}`)]])(
|
||||
'rejects %# asset ID lists outside 1 to 50',
|
||||
async (assetIds) => {
|
||||
await expect(runOperation(downloadAssetOp, as(owner), { assetIds })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('proxyKeyOf', () => {
|
||||
it.each([
|
||||
[{ proxyType: 'image', imageTranscodes: [{ key: 'i.webp' }] }, 'i.webp'],
|
||||
[{ proxyType: '3d', imageTranscodes: [{ key: 'views.webp' }] }, 'views.webp'],
|
||||
[{ proxyType: 'video', videoTranscodes: [{ key: 'v.mp4' }] }, 'v.mp4'],
|
||||
[{ proxyType: 'video', videoTranscodes: [], videoPreview: { key: 'p.mp4' } }, 'p.mp4'],
|
||||
[{ proxyType: 'pdf', original: { key: 'doc.pdf' } }, 'doc.pdf'],
|
||||
[{ proxyType: 'image', imageTranscodes: [] }, undefined],
|
||||
])('%o → %s', (value, expected) => {
|
||||
expect(proxyKeyOf(value as unknown as PrismaJson.MediaInfo)).toBe(expected)
|
||||
})
|
||||
|
||||
it('has no proxy without media', () => {
|
||||
expect(proxyKeyOf(null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
import * as path from 'path'
|
||||
import type { DownloadAssetOutput } from '@shumai/operations'
|
||||
import { AssetType, prisma, type Prisma } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { READ_URL_EXPIRES_SECONDS } from '@shumai/core/src/asset-read/asset-read'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read/types'
|
||||
|
||||
const assetWithStorage = { storageKey: true } satisfies Prisma.AssetInclude
|
||||
type AssetRecord = Prisma.AssetGetPayload<{ include: typeof assetWithStorage }>
|
||||
|
||||
const FOLDER_TYPES: ReadonlySet<string> = new Set([
|
||||
AssetType.folder,
|
||||
AssetType.root,
|
||||
AssetType.share_root,
|
||||
AssetType.share,
|
||||
])
|
||||
|
||||
/**
|
||||
* The web preview version of a file: the web image for images (and the 4-view image for 3D
|
||||
* models), the transcoded video for videos, otherwise none. Matches what the built-in agent
|
||||
* has always downloaded by default.
|
||||
*/
|
||||
export function proxyKeyOf(media: PrismaJson.MediaInfo | null): string | undefined {
|
||||
if (!media) return undefined
|
||||
if (media.proxyType === 'image' || media.imageTranscodes?.length) {
|
||||
return media.imageTranscodes?.[0]?.key || undefined
|
||||
}
|
||||
if (media.proxyType === 'video' || media.videoTranscodes?.length || media.videoPreview?.key) {
|
||||
return media.videoTranscodes?.[0]?.key || media.videoPreview?.key || undefined
|
||||
}
|
||||
return media.original?.key || undefined
|
||||
}
|
||||
|
||||
/** `clip.mov` downloaded as its `.mp4` proxy is saved as `clip.mp4`. */
|
||||
function nameForKey(assetName: string, key: string, isOriginal: boolean): string {
|
||||
if (isOriginal) return assetName
|
||||
const ext = path.extname(key)
|
||||
if (!ext) return assetName
|
||||
const current = path.extname(assetName)
|
||||
return `${current ? assetName.slice(0, -current.length) : assetName}${ext}`
|
||||
}
|
||||
|
||||
export class AssetDownloadService {
|
||||
/**
|
||||
* Download links for files and version stacks. The caller checks Read on every ID first.
|
||||
* Folders are rejected; version stacks resolve to their latest version and symlinks to
|
||||
* their target.
|
||||
*/
|
||||
async getDownloads(
|
||||
assetIds: string[],
|
||||
opts: { proxy: boolean; includeKeys: boolean },
|
||||
): Promise<DownloadAssetOutput> {
|
||||
const files: DownloadAssetOutput['files'] = []
|
||||
for (const assetId of [...new Set(assetIds)]) {
|
||||
const asset = await this.resolveFile(assetId)
|
||||
const originalKey = asset.storageKey?.key
|
||||
const proxyKey = opts.proxy
|
||||
? proxyKeyOf(asset.media as PrismaJson.MediaInfo | null)
|
||||
: undefined
|
||||
const key = proxyKey || originalKey
|
||||
if (!key) {
|
||||
throw new HTTPException(400, {
|
||||
message: `Asset ${assetId} ("${asset.name}") has no file to download.`,
|
||||
})
|
||||
}
|
||||
const isOriginal = key === originalKey
|
||||
const name = nameForKey(asset.name || 'file', key, isOriginal)
|
||||
|
||||
const bucket = storageBucket()
|
||||
const info = await s3Service.headObject(bucket, key).catch(() => null)
|
||||
if (!info) {
|
||||
throw new HTTPException(404, {
|
||||
message: `The file for asset ${assetId} ("${asset.name}") is missing from storage.`,
|
||||
})
|
||||
}
|
||||
const mimeType =
|
||||
info.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: getFileMimeType(null, key, 'application/octet-stream')
|
||||
|
||||
files.push({
|
||||
assetId: asset.id,
|
||||
name,
|
||||
kind: isOriginal ? 'original' : 'proxy',
|
||||
size: info.size,
|
||||
mimeType,
|
||||
url: await s3Service.presign(
|
||||
bucket,
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
name,
|
||||
false,
|
||||
READ_URL_EXPIRES_SECONDS,
|
||||
),
|
||||
...(opts.includeKeys ? { key } : {}),
|
||||
})
|
||||
}
|
||||
return { files }
|
||||
}
|
||||
|
||||
private async resolveFile(assetId: string): Promise<AssetRecord> {
|
||||
let asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: assetWithStorage,
|
||||
})
|
||||
if (asset?.type === AssetType.symlink && asset.targetId) {
|
||||
asset = await prisma.asset.findUnique({
|
||||
where: { id: asset.targetId },
|
||||
include: assetWithStorage,
|
||||
})
|
||||
}
|
||||
if (!asset || asset.isDeleted) {
|
||||
throw new HTTPException(404, { message: `Asset with ID ${assetId} not found.` })
|
||||
}
|
||||
if (FOLDER_TYPES.has(asset.type)) {
|
||||
throw new HTTPException(400, {
|
||||
message: `Asset ${assetId} ("${asset.name}") is a folder. Download the files inside it instead.`,
|
||||
})
|
||||
}
|
||||
if (asset.type === AssetType.version_stack) {
|
||||
const latest = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: assetWithStorage,
|
||||
})
|
||||
if (!latest) {
|
||||
throw new HTTPException(400, {
|
||||
message: `Version stack ${assetId} ("${asset.name}") has no versions to download.`,
|
||||
})
|
||||
}
|
||||
asset = latest
|
||||
}
|
||||
return asset
|
||||
}
|
||||
}
|
||||
|
||||
export const assetDownloadService = new AssetDownloadService()
|
||||
@@ -590,6 +590,33 @@ describe('read_asset and get_asset_render Operations', () => {
|
||||
expect(waitFor).toHaveBeenLastCalledWith(expect.anything(), budget)
|
||||
})
|
||||
|
||||
it('points unsupported files to the download command of each surface', async () => {
|
||||
const video = await prisma.asset.findUniqueOrThrow({ where: { id: videoId } })
|
||||
const zip = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'bundle.zip',
|
||||
type: AssetType.file,
|
||||
status: 'uploaded',
|
||||
mediaType: 'application/zip',
|
||||
projectId: video.projectId,
|
||||
parentId: video.parentId,
|
||||
},
|
||||
})
|
||||
const prefix = `Unsupported asset type for read_asset. Asset ${zip.id} has media type "application/zip".`
|
||||
|
||||
for (const via of ['agent', 'mcp', 'api'] as const) {
|
||||
await expect(runOperation(readAssetOp, as(via), { assetId: zip.id })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: `${prefix} Use download_asset to download this file.`,
|
||||
})
|
||||
}
|
||||
// The CLI has no tools; it names the command instead.
|
||||
await expect(runOperation(readAssetOp, as('cli'), { assetId: zip.id })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: `${prefix} Run \`shumai-cli download ${zip.id}\` to download it.`,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid input before touching the asset', async () => {
|
||||
await expect(
|
||||
runOperation(readAssetOp, as('mcp'), {
|
||||
|
||||
@@ -11,7 +11,13 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { resolveAnnotationsById } from './annotations'
|
||||
import { findReader, getReader, readers } from './registry'
|
||||
import { badRequest, storageBucket, type ReadableAsset, type ReadResult } from './types'
|
||||
import {
|
||||
badRequest,
|
||||
storageBucket,
|
||||
UnsupportedAssetTypeError,
|
||||
type ReadableAsset,
|
||||
type ReadResult,
|
||||
} from './types'
|
||||
|
||||
/** Who is reading: a user (Read permission required) or the autofill system agent. */
|
||||
export type ReadAccess =
|
||||
@@ -81,9 +87,7 @@ export class AssetReadService {
|
||||
|
||||
const reader = findReader(asset)
|
||||
if (!reader) {
|
||||
throw badRequest(
|
||||
`Unsupported asset type for read_asset. Asset ${asset.id} has media type "${asset.mediaTypeLower || 'unknown'}". Use download_asset to download this file to disk.`,
|
||||
)
|
||||
throw new UnsupportedAssetTypeError(asset.id, asset.mediaTypeLower)
|
||||
}
|
||||
|
||||
// Reject configs meant for another type (empty objects like `imageConfig: {}` are ignored).
|
||||
|
||||
@@ -10,5 +10,5 @@ export {
|
||||
export { resolveAnnotationsById } from './annotations'
|
||||
export { findReader, getReader, readers } from './registry'
|
||||
export { isPlainTextAsset, MAX_TEXT_BYTES, MAX_TEXT_LINES } from './readers/document'
|
||||
export { storageBucket } from './types'
|
||||
export { storageBucket, UnsupportedAssetTypeError } from './types'
|
||||
export type { AssetReader, ReadableAsset, ReadImage, ReadPlan, ReadResult } from './types'
|
||||
|
||||
@@ -91,6 +91,19 @@ export interface AssetReader<TKind extends ReaderKind = ReaderKind> {
|
||||
): ReadResult
|
||||
}
|
||||
|
||||
/** No reader handles this asset; the message points to download_asset. */
|
||||
export class UnsupportedAssetTypeError extends HTTPException {
|
||||
constructor(
|
||||
readonly assetId: string,
|
||||
readonly mediaType: string,
|
||||
hint = 'Use download_asset to download this file.',
|
||||
) {
|
||||
super(400, {
|
||||
message: `Unsupported asset type for read_asset. Asset ${assetId} has media type "${mediaType || 'unknown'}". ${hint}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function badRequest(message: string): HTTPException {
|
||||
return new HTTPException(400, { message })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { downloadAsset } from '@shumai/operations'
|
||||
import { assetDownloadService } from '@shumai/core/src/asset-download/asset-download'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const downloadAssetOp = implementOperation(downloadAsset, {
|
||||
authz: (input) =>
|
||||
[...new Set(input.assetIds)].map((id) => ({
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})),
|
||||
execute: (input, ctx) =>
|
||||
assetDownloadService.getDownloads(input.assetIds, {
|
||||
proxy: input.proxy !== false,
|
||||
// The built-in agent saves files into its sandbox straight from storage.
|
||||
includeKeys: ctx.via === 'agent',
|
||||
}),
|
||||
})
|
||||
@@ -1,5 +1,9 @@
|
||||
import { getAssetRender, readAsset, type Via } from '@shumai/operations'
|
||||
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
|
||||
import {
|
||||
assetReadService,
|
||||
toAssetReadOutput,
|
||||
UnsupportedAssetTypeError,
|
||||
} from '@shumai/core/src/asset-read'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
/**
|
||||
@@ -31,9 +35,21 @@ export const readAssetOp = implementOperation(readAsset, {
|
||||
authz: () => [],
|
||||
execute: async (input, ctx) => {
|
||||
const { maxWaitSeconds, ...request } = input
|
||||
const outcome = await assetReadService.read({ kind: 'user', userId: ctx.userId }, request, {
|
||||
waitBudgetMs: waitBudgetMs(ctx.via, maxWaitSeconds),
|
||||
})
|
||||
const outcome = await assetReadService
|
||||
.read({ kind: 'user', userId: ctx.userId }, request, {
|
||||
waitBudgetMs: waitBudgetMs(ctx.via, maxWaitSeconds),
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
// CLI users download with a command, not a tool.
|
||||
if (err instanceof UnsupportedAssetTypeError && ctx.via === 'cli') {
|
||||
throw new UnsupportedAssetTypeError(
|
||||
err.assetId,
|
||||
err.mediaType,
|
||||
`Run \`shumai-cli download ${err.assetId}\` to download it.`,
|
||||
)
|
||||
}
|
||||
throw err
|
||||
})
|
||||
return toAssetReadOutput(outcome, { includeKeys: SERVER_PRESENTED.has(ctx.via) })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ export { runOperation } from './run'
|
||||
export { getOperation, getOperationsForSurface, operations } from './registry'
|
||||
export { createFolderOp } from './asset/create-folder'
|
||||
export { deleteAssetOp } from './asset/delete-asset'
|
||||
export { downloadAssetOp } from './asset/download-asset'
|
||||
export { listAssetsOp } from './asset/list-assets'
|
||||
export { moveAssetsOp } from './asset/move-assets'
|
||||
export {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { OperationName, Surface } from '@shumai/operations'
|
||||
import { createFolderOp } from './asset/create-folder'
|
||||
import { deleteAssetOp } from './asset/delete-asset'
|
||||
import { downloadAssetOp } from './asset/download-asset'
|
||||
import { listAssetsOp } from './asset/list-assets'
|
||||
import { moveAssetsOp } from './asset/move-assets'
|
||||
import { getAssetRenderOp, readAssetOp } from './asset/read-asset'
|
||||
@@ -34,6 +35,7 @@ export const operations = defineRegistry([
|
||||
deleteAssetOp,
|
||||
readAssetOp,
|
||||
getAssetRenderOp,
|
||||
downloadAssetOp,
|
||||
] as const)
|
||||
|
||||
const operationsByName = new Map<string, Operation>()
|
||||
|
||||
@@ -22,7 +22,8 @@ type ExecutableTool = {
|
||||
|
||||
/**
|
||||
* read_asset end to end: real render workflows (frames, PDF pages) through the reader
|
||||
* pipeline, the pending → get_asset_render path, and the agent tool in a chat workflow.
|
||||
* pipeline, the pending → get_asset_render path, and the agent's read_asset and
|
||||
* download_asset tools in a chat workflow.
|
||||
* Only the model call is mocked.
|
||||
*/
|
||||
describe('Workflow E2E - read_asset', () => {
|
||||
@@ -56,10 +57,20 @@ describe('Workflow E2E - read_asset', () => {
|
||||
})
|
||||
const text = result.content.find((c) => c.type === 'text')?.text ?? ''
|
||||
const images = result.content.filter((c) => c.type === 'image' && c.data)
|
||||
// download_asset saves the original into the agent's sandbox (.pi)
|
||||
const download = this.getTools().find((t) => t.name === 'download_asset') as unknown as
|
||||
ExecutableTool | undefined
|
||||
const downloaded = download
|
||||
? await download.execute('call-2', { assetIds: [videoAssetId], proxy: false })
|
||||
: undefined
|
||||
const savedPath = (
|
||||
downloaded as unknown as { details?: { files?: Array<{ absolutePath: string }> } }
|
||||
)?.details?.files?.[0]?.absolutePath
|
||||
const summary = [
|
||||
`images:${images.length}`,
|
||||
`frames:${(text.match(/- Frame at /g) ?? []).length}`,
|
||||
`render_tool:${hasRenderTool ? 'present' : 'absent'}`,
|
||||
`downloaded:${savedPath ?? 'none'}`,
|
||||
].join('|')
|
||||
return {
|
||||
content: [{ type: 'text', text: summary }],
|
||||
@@ -283,6 +294,12 @@ describe('Workflow E2E - read_asset', () => {
|
||||
expect(reply?.message).toContain('images:2')
|
||||
expect(reply?.message).toContain('frames:2')
|
||||
expect(reply?.message).toContain('render_tool:present')
|
||||
const savedPath = /downloaded:([^|]+)/.exec(reply?.message ?? '')?.[1] ?? 'none'
|
||||
expect(savedPath).not.toBe('none')
|
||||
expect(
|
||||
fs.readFileSync(savedPath).equals(fs.readFileSync(path.join(fixturesDir, 'small.mp4'))),
|
||||
).toBe(true)
|
||||
fs.rmSync(savedPath, { force: true })
|
||||
|
||||
const render = await prisma.workflowTask.findFirstOrThrow({
|
||||
where: { assetId: video.id, type: 'transcode_screenshot' },
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod'
|
||||
import { defineOperation } from '../define'
|
||||
|
||||
/** Most assets one download call accepts. */
|
||||
export const MAX_DOWNLOAD_ASSETS = 50
|
||||
|
||||
const downloadFileSchema = z.object({
|
||||
assetId: z
|
||||
.string()
|
||||
.describe('The asset this file belongs to (the latest version for a version stack).'),
|
||||
name: z.string().describe('File name to save it as.'),
|
||||
kind: z
|
||||
.enum(['proxy', 'original'])
|
||||
.describe('"proxy" is the web preview version; "original" is the uploaded file.'),
|
||||
size: z.number().describe('Size in bytes.'),
|
||||
mimeType: z.string(),
|
||||
url: z.string().describe('Short-lived download link (about 1 hour).'),
|
||||
/** Storage key; only returned to Shumai's built-in agent. */
|
||||
key: z.string().optional(),
|
||||
})
|
||||
|
||||
export const downloadAssetOutputSchema = z.object({
|
||||
files: z.array(downloadFileSchema),
|
||||
})
|
||||
export type DownloadAssetOutput = z.infer<typeof downloadAssetOutputSchema>
|
||||
|
||||
export const downloadAsset = defineOperation({
|
||||
name: 'download_asset',
|
||||
title: 'Download Asset',
|
||||
description:
|
||||
`Gets download links for up to ${MAX_DOWNLOAD_ASSETS} files. ` +
|
||||
'By default it returns the web preview version (proxy) when there is one, e.g. the transcoded video or the web image, which is smaller and easier to process; set proxy to false for the original uploaded file. ' +
|
||||
'Files without a preview (e.g. audio, archives, text) always return the original. ' +
|
||||
'A version stack returns its latest version. Folders are not supported: download the files inside them instead. ' +
|
||||
'Links expire after about an hour.',
|
||||
input: z.object({
|
||||
assetIds: z
|
||||
.array(z.string().min(1))
|
||||
.min(1)
|
||||
.max(MAX_DOWNLOAD_ASSETS)
|
||||
.describe(`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}).`),
|
||||
proxy: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'Download the web preview version when there is one (default true). Set to false for the original uploaded file.',
|
||||
),
|
||||
}),
|
||||
output: downloadAssetOutputSchema,
|
||||
surfaces: ['agent', 'mcp', 'cli'],
|
||||
annotations: { readOnly: true, destructive: false, idempotent: true },
|
||||
cli: {
|
||||
command: ['download'],
|
||||
description:
|
||||
'Download files into a folder (the current folder by default). Saves the web preview version when there is one; use --original for the uploaded file.',
|
||||
positional: ['assetIds'],
|
||||
// The CLI exposes `--original` instead of a `--proxy` flag that is on by default.
|
||||
omit: ['proxy'],
|
||||
},
|
||||
})
|
||||
@@ -8,4 +8,5 @@ export { listAssets } from './asset/list-assets'
|
||||
export { moveAssets } from './asset/move-assets'
|
||||
export { renameAsset } from './asset/rename-asset'
|
||||
export * from './asset/read-asset'
|
||||
export * from './asset/download-asset'
|
||||
export { listProjects } from './project/list-projects'
|
||||
|
||||
@@ -19,6 +19,7 @@ describe('operation registry', () => {
|
||||
expect(operationDefinitions.map((d) => d.name).sort()).toEqual([
|
||||
'create_folder',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
@@ -47,6 +48,7 @@ describe('operation registry', () => {
|
||||
expect(destructive.map((d) => d.name)).toEqual(['delete_asset'])
|
||||
const readOnly = operationDefinitions.filter((d) => d.annotations.readOnly)
|
||||
expect(readOnly.map((d) => d.name).sort()).toEqual([
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
@@ -96,6 +98,7 @@ describe('operation registry', () => {
|
||||
['delete_asset', ['delete', 'rm']],
|
||||
['read_asset', ['read']],
|
||||
['get_asset_render', ['render']],
|
||||
['download_asset', ['download']],
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createFolder } from './asset/create-folder'
|
||||
import { deleteAsset } from './asset/delete-asset'
|
||||
import { downloadAsset } from './asset/download-asset'
|
||||
import { listAssets } from './asset/list-assets'
|
||||
import { moveAssets } from './asset/move-assets'
|
||||
import { getAssetRender, readAsset } from './asset/read-asset'
|
||||
@@ -20,6 +21,7 @@ export const operationDefinitions = [
|
||||
deleteAsset,
|
||||
readAsset,
|
||||
getAssetRender,
|
||||
downloadAsset,
|
||||
] as const
|
||||
|
||||
export type RegisteredOperationDefinition = (typeof operationDefinitions)[number]
|
||||
|
||||
@@ -112,6 +112,11 @@ const BUILTIN_TOOLS = [
|
||||
name: () => m.agent_tool_create_version_name(),
|
||||
description: () => m.agent_tool_create_version_desc(),
|
||||
},
|
||||
{
|
||||
id: 'download_asset',
|
||||
name: () => m.agent_tool_download_asset_name(),
|
||||
description: () => m.agent_tool_download_asset_desc(),
|
||||
},
|
||||
{
|
||||
id: 'generate_image',
|
||||
name: () => m.agent_tool_generate_image_name(),
|
||||
|
||||
@@ -609,6 +609,8 @@
|
||||
"agent_tool_read_skill_desc": "Allows the agent to load and read skill definitions to perform specialized actions.",
|
||||
"agent_tool_read_asset_name": "Read Asset",
|
||||
"agent_tool_read_asset_desc": "Allows the agent to view and inspect images, video frames, and document pages.",
|
||||
"agent_tool_download_asset_name": "Download Asset",
|
||||
"agent_tool_download_asset_desc": "Allows the agent to download files to its workspace to process them with scripts or terminal commands.",
|
||||
"agent_tool_get_asset_render_name": "Get Asset Render",
|
||||
"agent_tool_get_asset_render_desc": "Allows the agent to pick up video frames or document pages that took longer to render.",
|
||||
"agent_tool_list_projects_name": "List Projects",
|
||||
|
||||
@@ -609,6 +609,8 @@
|
||||
"agent_tool_read_skill_desc": "允许智能体加载和读取技能定义以执行特定操作。",
|
||||
"agent_tool_read_asset_name": "读取资源",
|
||||
"agent_tool_read_asset_desc": "允许智能体查看和分析图片、视频画面和文档页面。",
|
||||
"agent_tool_download_asset_name": "下载资源",
|
||||
"agent_tool_download_asset_desc": "允许智能体将文件下载到其工作区,以便用脚本或终端命令处理。",
|
||||
"agent_tool_get_asset_render_name": "获取资源渲染结果",
|
||||
"agent_tool_get_asset_render_desc": "允许智能体获取渲染耗时较长的视频画面或文档页面。",
|
||||
"agent_tool_list_projects_name": "列出项目",
|
||||
|
||||
Reference in New Issue
Block a user