refactor(agent)!: migrate to Pi Durable and embed the agent queue (#525)

* refactor(agent)!: migrate sessions to Pi Durable

Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server.

BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs.

* fix(agent): constrain session log dialog scrolling

Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow.

* fix(agent): hide entry IDs from session log card headers

Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them.

* test(e2e): handle browser wheel limits in session log checks

Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions.

* fix(agent): select model providers without inheriting unrelated auth

* fix(webui): prevent resize feedback when toggling agent panel

* test(agent): reproduce concurrent comment session races

* fix(agent): serialize comment sessions and deduplicate history

* docs(changelog): consolidate Pi Durable changes into one entry
This commit is contained in:
Yiling-J
2026-11-11 16:05:18 +08:00
committed by GitHub
parent 843a56304c
commit 35a0e82284
120 changed files with 7593 additions and 5972 deletions
@@ -1,10 +1,11 @@
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 { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma, type Asset, type StorageKey } from '@shumai/db'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { toAgentTool } from '../operation-tools'
import './download-asset'
@@ -96,7 +97,7 @@ describe('download_asset agent tool', () => {
mockAssets(photo)
mockStorage('image/webp', 'proxy-bytes')
const result = await downloadTool().execute('call-1', { assetIds: ['img-1'] })
const result = await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'] })
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
created.push(expectedPath)
@@ -130,7 +131,7 @@ describe('download_asset agent tool', () => {
mockAssets(photo)
mockStorage('image/jpeg')
await downloadTool().execute('call-1', { assetIds: ['img-1'], proxy: false })
await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'], proxy: false })
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
created.push(expectedPath)
@@ -153,7 +154,7 @@ describe('download_asset agent tool', () => {
} as unknown as Asset)
mockStorage('image/webp')
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
assetIds: ['img-1', 'stack-1'],
key: null,
})
@@ -173,7 +174,7 @@ describe('download_asset agent tool', () => {
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(
await expect(invokeTool(downloadTool(), '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()
@@ -185,36 +186,36 @@ describe('download_asset agent tool', () => {
if (id === 'secret') throw new Error('Forbidden')
})
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1', 'secret'] }),
invokeTool(downloadTool(), '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',
)
await expect(
invokeTool(downloadTool(), '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' }),
invokeTool(downloadTool(), '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' }),
invokeTool(downloadTool(''), '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' }),
invokeTool(downloadTool(), 'call-1', { key: 'avatars/user-1.png' }),
).rejects.toThrow('Invalid storage key format: key must start with "files/"')
await expect(
invokeTool(downloadTool(), 'call-1', { key: 'files/../../etc/passwd' }),
).rejects.toThrow('cannot contain ".."')
})
@@ -223,7 +224,7 @@ describe('download_asset agent tool', () => {
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' }),
invokeTool(downloadTool(), 'call-1', { key: 'files/nope/shot.webp' }),
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
})
@@ -231,7 +232,7 @@ describe('download_asset agent tool', () => {
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' }),
invokeTool(downloadTool(), 'call-1', { key: 'files/other-project-asset/shots/a.webp' }),
).rejects.toThrow('Forbidden')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
@@ -246,7 +247,7 @@ describe('download_asset agent tool', () => {
mockAssets({ id: 'ast-123' })
mockStorage('image/webp', 'frame-bytes')
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
key: 'files/ast-123/screenshots/shot_5.0s.webp',
})
@@ -279,7 +280,7 @@ describe('download_asset agent tool', () => {
await fs.promises.writeFile(dest, pngHeader)
})
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
key: 'files/upload-ulid-456/photo.png',
})
@@ -1,17 +1,17 @@
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { s3Service } from '@shumai/core/src/s3/s3'
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import type { User } from '@shumai/db'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
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 { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
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'
import { resolveAssetIdFromKey } from '../tools/download-asset'
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
@@ -47,7 +47,7 @@ async function saveToSandbox(key: string, filename: string) {
}
/** 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>> {
async function downloadKey(key: string, userId: string): Promise<AgentToolResult> {
const owningAssetId = await resolveAssetIdFromKey(key)
await authzService.hasPermission({
user: { id: userId } as User,
@@ -59,7 +59,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
const saved = await saveToSandbox(key, filename)
return {
content: [
output: [
{
type: 'text',
text: `Downloaded storage key "${key}" to "${saved.filePath}". Remember to delete this temporary file when finished.`,
@@ -70,9 +70,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
}
/** Saves each file of a download_asset result into the sandbox. */
export async function presentDownloadOutput(
output: DownloadAssetOutput,
): Promise<AgentToolResult<unknown>> {
export async function presentDownloadOutput(output: DownloadAssetOutput): Promise<AgentToolResult> {
const lines: string[] = []
const files = []
for (const file of output.files) {
@@ -87,7 +85,7 @@ export async function presentDownloadOutput(
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 } }
return { output: [{ type: 'text', text: lines.join('\n') }], details: { files } }
}
const downloadAssetExtension: AgentToolExtension = {
@@ -1,17 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import {
prisma,
WorkflowTaskType,
WorkflowTaskStatus,
WorkflowTaskType,
type Asset,
type WorkflowTask,
} from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { workflowService } from '@shumai/workflow-core'
import { authzService } from '@shumai/core/src/authz/authz'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { getOperation } from '@shumai/core/src/operations'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { toAgentTool } from '../operation-tools'
import { createAutofillReadAssetTool } from './read-asset'
@@ -90,7 +91,7 @@ type Details = {
taskId?: string
isTruncated?: boolean
}
function details(result: { details: unknown }): Details {
function details(result: { details?: unknown }): Details {
return result.details as Details
}
@@ -212,7 +213,7 @@ describe('read_asset agent tool', () => {
})
it('throws an authorization error if the user ID is empty', async () => {
await expect(readAssetTool('').execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(''), 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'User ID is required for authorization.',
)
})
@@ -220,7 +221,7 @@ describe('read_asset agent tool', () => {
it('throws if the asset is not found', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'asset-1',
annotationId: null,
imageConfig: null,
@@ -233,7 +234,7 @@ describe('read_asset agent tool', () => {
it('does not plan or render anything when Read is denied', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 1, count: 1 },
}),
@@ -244,7 +245,7 @@ describe('read_asset agent tool', () => {
it('rejects unsupported asset types', async () => {
mockAsset({ id: 'zip-1', name: 'bundle.zip', mediaType: 'application/zip', media: null })
await expect(readAssetTool().execute('call-1', { assetId: 'zip-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'zip-1' })).rejects.toThrow(
'Unsupported asset type for read_asset. Asset zip-1 has media type "application/zip".',
)
})
@@ -254,7 +255,7 @@ describe('read_asset agent tool', () => {
mockAsset(imageAsset)
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
annotationId: null,
imageConfig: null,
@@ -289,14 +290,17 @@ describe('read_asset agent tool', () => {
it('ignores an empty imageConfig', async () => {
mockAsset(imageAsset)
mockObjects()
const result = await readAssetTool().execute('call-1', { assetId: 'img-1', imageConfig: {} })
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
imageConfig: {},
})
expect(details(result).key).toBe('proxy/photo.webp')
})
it('rejects a config meant for another asset type', async () => {
mockAsset(imageAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 1 },
}),
@@ -312,7 +316,7 @@ describe('read_asset agent tool', () => {
mockTaskFinished('task-anno', { key: 'annotated/photo.webp' })
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
annotationId: 'comment-1',
})
@@ -348,7 +352,7 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
mockObjects()
const result = await readAssetTool().execute('call-3d', { assetId: 'model-1' })
const result = await invokeTool(readAssetTool(), 'call-3d', { assetId: 'model-1' })
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/views.webp')
const text = textOf(result)
@@ -367,7 +371,7 @@ describe('read_asset agent tool', () => {
it('supports s3KeyOnly for 3D assets', async () => {
mockAsset(modelAsset)
const result = await readAssetTool().execute('call-3d-s3', {
const result = await invokeTool(readAssetTool(), 'call-3d-s3', {
assetId: 'model-1',
s3KeyOnly: true,
})
@@ -381,7 +385,7 @@ describe('read_asset agent tool', () => {
it('rejects videoConfig for 3D assets', async () => {
mockAsset(modelAsset)
await expect(
readAssetTool().execute('call-3d-err', {
invokeTool(readAssetTool(), 'call-3d-err', {
assetId: 'model-1',
videoConfig: { start: 0, end: 4, count: 4 },
}),
@@ -392,9 +396,9 @@ describe('read_asset agent tool', () => {
it('throws if the 4-views image is missing when the overview is requested', async () => {
mockAsset({ ...modelAsset, media: { proxyType: '3d', imageTranscodes: [] } })
await expect(readAssetTool().execute('call-3d-err2', { assetId: 'model-1' })).rejects.toThrow(
'4-views image (views.webp) is missing',
)
await expect(
invokeTool(readAssetTool(), 'call-3d-err2', { assetId: 'model-1' }),
).rejects.toThrow('4-views image (views.webp) is missing')
})
it('renders a turntable frame when config3d.degree is provided', async () => {
@@ -405,7 +409,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-degree', {
const result = await invokeTool(readAssetTool(), 'call-3d-degree', {
assetId: 'model-1',
config3d: { degree: 45 },
})
@@ -446,10 +450,10 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
const tool = readAssetTool()
await expect(
tool.execute('call-1', { assetId: 'model-1', config3d: { degree: 40 } }),
invokeTool(tool, 'call-1', { assetId: 'model-1', config3d: { degree: 40 } }),
).rejects.toThrow('Invalid turntable degree: 40')
await expect(
tool.execute('call-2', { assetId: 'model-1', config3d: { degree: 360 } }),
invokeTool(tool, 'call-2', { assetId: 'model-1', config3d: { degree: 360 } }),
).rejects.toThrow('Invalid turntable degree: 360')
expect(resolveAnnotationsById).not.toHaveBeenCalled()
})
@@ -463,7 +467,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-ann', {
const result = await invokeTool(readAssetTool(), 'call-3d-ann', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: null,
@@ -500,7 +504,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-session-ann', {
const result = await invokeTool(readAssetTool(), 'call-3d-session-ann', {
assetId: 'model-1',
annotationId: 'session-entry-1',
})
@@ -524,7 +528,7 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
vi.mocked(resolveAnnotationsById).mockResolvedValue({ annotations: arrow, timestamp: 0.5 })
await expect(
readAssetTool().execute('call-3d-conflict', {
invokeTool(readAssetTool(), 'call-3d-conflict', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: { degree: 90 },
@@ -538,7 +542,7 @@ describe('read_asset agent tool', () => {
it('throws if the turntable video is missing when an angle is requested', async () => {
mockAsset({ ...modelAsset, media: { proxyType: '3d', videoTranscodes: [] } })
await expect(
readAssetTool().execute('call-1', { assetId: 'model-1', config3d: { degree: 45 } }),
invokeTool(readAssetTool(), 'call-1', { assetId: 'model-1', config3d: { degree: 45 } }),
).rejects.toThrow('turntable video (turntable.mp4) is missing')
})
})
@@ -546,7 +550,7 @@ describe('read_asset agent tool', () => {
describe('Video Assets', () => {
it('requires videoConfig', async () => {
mockAsset(videoAsset)
await expect(readAssetTool().execute('call-1', { assetId: 'vid-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'vid-1' })).rejects.toThrow(
'videoConfig with start, end, and count is required',
)
})
@@ -554,7 +558,7 @@ describe('read_asset agent tool', () => {
it('rejects an invalid time range', async () => {
mockAsset(videoAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 10, end: 5, count: 1 },
}),
@@ -566,7 +570,7 @@ describe('read_asset agent tool', () => {
it('rejects more than 20 frames', async () => {
mockAsset(videoAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 60, count: 21 },
}),
@@ -584,7 +588,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
annotationId: null,
imageConfig: null,
@@ -638,7 +642,7 @@ describe('read_asset agent tool', () => {
done: false,
}))
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 10, count: 5 },
maxWaitSeconds: 0,
@@ -661,7 +665,7 @@ describe('read_asset agent tool', () => {
mockTaskFinished('task-shot', { screenshots: [{ key: 's/1.webp', timestamp: 0 }] })
mockObjects()
await readAssetTool().execute('call-1', {
await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 0, count: 1 },
maxWaitSeconds: 600,
@@ -673,7 +677,7 @@ describe('read_asset agent tool', () => {
describe('Document Assets', () => {
it('requires docConfig', async () => {
mockAsset(pdfAsset)
await expect(readAssetTool().execute('call-1', { assetId: 'doc-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'doc-1' })).rejects.toThrow(
'docConfig with mode ("pages" or "text") is required',
)
})
@@ -689,7 +693,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 2 },
})
@@ -716,7 +720,7 @@ describe('read_asset agent tool', () => {
it('rejects page ranges over 20 pages', async () => {
mockAsset(pdfAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 25 },
}),
@@ -726,7 +730,7 @@ describe('read_asset agent tool', () => {
it('rejects mode "text" on a binary PDF', async () => {
mockAsset({ ...pdfAsset, name: 'manual.pdf' })
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'text', startPage: null, endPage: null },
}),
@@ -736,7 +740,7 @@ describe('read_asset agent tool', () => {
it('rejects mode "text" with annotationId', async () => {
mockAsset(markdownAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
annotationId: 'comment-123',
docConfig: { mode: 'text', startPage: null, endPage: null },
@@ -748,7 +752,7 @@ describe('read_asset agent tool', () => {
it('rejects page numbers in mode "text"', async () => {
mockAsset(markdownAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text', startPage: 1, endPage: 2 },
}),
@@ -762,7 +766,7 @@ describe('read_asset agent tool', () => {
contentType: 'text/markdown',
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text', startPage: null, endPage: null },
})
@@ -793,7 +797,7 @@ describe('read_asset agent tool', () => {
contentType: 'text/markdown',
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text' },
})
@@ -824,7 +828,7 @@ describe('read_asset agent tool', () => {
} as unknown as Asset)
mockObjects()
const result = await readAssetTool().execute('call-1', { assetId: 'stack-1' })
const result = await invokeTool(readAssetTool(), 'call-1', { assetId: 'stack-1' })
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
where: { parentId: 'stack-1', isDeleted: false },
@@ -839,7 +843,7 @@ describe('read_asset agent tool', () => {
describe('s3KeyOnly mode', () => {
it('returns only the S3 key and MIME for image assets', async () => {
mockAsset(imageAsset)
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
s3KeyOnly: true,
})
@@ -859,7 +863,7 @@ describe('read_asset agent tool', () => {
screenshots: [{ key: 'screenshots/shot1.webp', timestamp: 1.5 }],
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
s3KeyOnly: true,
videoConfig: { start: 1.5, end: 1.5, count: 1 },
@@ -875,7 +879,7 @@ describe('read_asset agent tool', () => {
it('returns only the document S3 key and MIME without reading the text', async () => {
mockAsset({ ...markdownAsset, name: 'notes.md', storageKey: { key: 'raw/notes.md' } })
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
s3KeyOnly: true,
docConfig: { mode: 'text', startPage: null, endPage: null },
@@ -919,7 +923,7 @@ describe('get_asset_render agent tool', () => {
})
mockObjects()
const result = await getAssetRenderTool().execute('call-1', { taskId: 'task-1' })
const result = await invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
@@ -936,14 +940,14 @@ describe('get_asset_render agent tool', () => {
mockPendingTask('user-1')
vi.mocked(workflowService.waitFor).mockImplementation(async (task) => ({ task, done: false }))
const result = await getAssetRenderTool().execute('call-1', { taskId: 'task-1' })
const result = await invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })
expect(textOf(result)).toContain('Call get_asset_render with taskId "task-1"')
expect(details(result)).toEqual({ taskId: 'task-1', status: 'pending' })
})
it('hides renders requested by another user', async () => {
mockPendingTask('someone-else')
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-1' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })).rejects.toThrow(
'Render not found',
)
expect(workflowService.waitFor).not.toHaveBeenCalled()
@@ -952,7 +956,7 @@ describe('get_asset_render agent tool', () => {
it('hides renders once the user loses access to the asset', async () => {
mockPendingTask('user-1')
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-1' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })).rejects.toThrow(
'Render not found',
)
})
@@ -963,7 +967,7 @@ describe('get_asset_render agent tool', () => {
assetId: 'vid-1',
payload: { projectId: 'project-1' },
} as unknown as WorkflowTask)
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-2' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-2' })).rejects.toThrow(
'Render not found',
)
})
@@ -976,14 +980,14 @@ describe('autofill read_asset tool', () => {
it('requires targetAssetId', async () => {
const tool = createAutofillReadAssetTool({ teamId: 'team-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Target asset ID is required for autofill agent authorization.',
)
})
it('requires teamId', async () => {
const tool = createAutofillReadAssetTool({ targetAssetId: 'asset-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Team ID is required for autofill agent authorization.',
)
})
@@ -991,7 +995,7 @@ describe('autofill read_asset tool', () => {
it('denies assets from another team', async () => {
mockAsset({ id: 'asset-1', project: { teamId: 'other-team' } })
const tool = createAutofillReadAssetTool({ teamId: 'team-1', targetAssetId: 'asset-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Access denied: asset asset-1 does not belong to team team-1.',
)
})
@@ -1002,7 +1006,7 @@ describe('autofill read_asset tool', () => {
teamId: 'team-1',
targetAssetId: 'target-asset-id',
})
await expect(tool.execute('call-1', { assetId: 'other-asset' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'other-asset' })).rejects.toThrow(
'Access denied: autofill agent can only read target asset target-asset-id.',
)
})
@@ -1021,7 +1025,7 @@ describe('autofill read_asset tool', () => {
targetAssetId: 'target-asset-id',
})
const result = await tool.execute('call-1', {
const result = await invokeTool(tool, 'call-1', {
assetId: 'target-asset-id',
annotationId: null,
s3KeyOnly: true,
@@ -1041,7 +1045,7 @@ describe('autofill read_asset tool', () => {
mockTaskFinished('task-shot', { screenshots: [{ key: 's/1.webp', timestamp: 0 }] })
const tool = createAutofillReadAssetTool({ teamId: 'team-1', targetAssetId: 'vid-1' })
await tool.execute('call-1', {
await invokeTool(tool, 'call-1', {
assetId: 'vid-1',
s3KeyOnly: true,
videoConfig: { start: 0, end: 0, count: 1 },
@@ -1,12 +1,19 @@
import { z } from 'zod'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
import { readAsset, type AssetReadOutput } from '@shumai/operations'
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import {
assetReadService,
MAX_TEXT_BYTES,
MAX_TEXT_LINES,
toAssetReadOutput,
} from '@shumai/core/src/asset-read'
import { getOperation, READ_WAIT_BUDGET_MS } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { MAX_TEXT_BYTES, MAX_TEXT_LINES } from '@shumai/core/src/asset-read'
import { readAsset, type AssetReadOutput } from '@shumai/operations'
import { z } from 'zod'
import {
registerAgentToolExtension,
splitAgentParams,
@@ -24,7 +31,7 @@ const extraParameters = z.object({
})
/** Details kept compatible with the previous tool; `sourceKeys` drives session image storage. */
interface ReadAssetDetails {
type ReadAssetDetails = {
assetId: string
name: string
mediaType: string | null
@@ -45,7 +52,7 @@ export async function presentReadOutput(
if (output.status === 'pending') {
const retry = output.retryAfterSeconds ?? 5
return {
content: [
output: [
{
type: 'text',
text: `${output.summary} Call get_asset_render with taskId "${output.taskId}" in about ${retry} seconds to get the result.`,
@@ -87,7 +94,7 @@ export async function presentReadOutput(
const imageKeys = output.images.map((i) => i.key ?? '')
const content: Array<TextContent | ImageContent> = [{ type: 'text', text }, ...imageBlocks]
return {
content,
output: content,
details: {
assetId: output.asset.id,
name: output.asset.name,
@@ -131,10 +138,10 @@ export function createAutofillReadAssetTool(access: {
const op = getOperation(readAsset.name)!
return {
name: readAsset.name,
label: readAsset.title,
description: readAsset.description,
parameters: toToolParameters(op, readAssetExtension),
execute: async (_toolCallId, params) => {
execute: async (params) => {
const { input, extra } = splitAgentParams(op, readAssetExtension, params)
const parsed = readAsset.input.safeParse(input)
if (!parsed.success) {
@@ -1,16 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Value } from 'typebox/value'
import { validateToolArguments } from '@earendil-works/pi-ai'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { Value } from 'typebox/value'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { fieldsToTypeBoxSchema } from '../index'
import { toAgentTool, type AgentToolOptions } from '../operation-tools'
import './upload'
@@ -106,7 +107,7 @@ describe('create_file and create_version agent tools', () => {
it('uploads a local file to storage and creates the file as the agent', async () => {
const filePath = tempFile('# Hello from disk', 'agent-create-file.md')
const result = await tool('create_file').execute('call-1', {
const result = await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
} as never)
@@ -155,7 +156,7 @@ describe('create_file and create_version agent tools', () => {
})
it('creates a text file from name and content', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'notes.md',
content: '# Notes\n\nHello',
@@ -172,7 +173,7 @@ describe('create_file and create_version agent tools', () => {
})
it('defaults unknown extensions to text/plain when creating from content', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'script.ts',
content: 'const x = 1',
@@ -185,7 +186,7 @@ describe('create_file and create_version agent tools', () => {
})
it('sanitizes the name', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'my/notes.md',
content: 'hello',
@@ -200,7 +201,7 @@ describe('create_file and create_version agent tools', () => {
it('forwards Creation Context metadata, including new select options', async () => {
const filePath = tempFile('# Hello', 'agent-create-file-meta.md')
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: { prompt: { newOption: { value: 'Kling' } } },
@@ -214,7 +215,7 @@ describe('create_file and create_version agent tools', () => {
it('treats null metadata as omitted', async () => {
const filePath = tempFile('# Hello', 'agent-create-file-null.md')
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: null,
@@ -227,7 +228,7 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Hello', 'agent-create-file-bad-meta.md')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: { status: 'approved' },
@@ -240,10 +241,10 @@ describe('create_file and create_version agent tools', () => {
it('rejects a call with neither or both of "path" and "content"', async () => {
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1' } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1' } as never),
).rejects.toThrow('Provide exactly one of "path" (a local file) or "content" (with "name").')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '/some/file.md',
name: 'notes.md',
@@ -255,13 +256,13 @@ describe('create_file and create_version agent tools', () => {
it('requires a name with "content"', async () => {
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1', content: 'x' } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', content: 'x' } as never),
).rejects.toThrow('"name" is required')
})
it('fails when the local file does not exist, without touching storage', async () => {
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '/nonexistent/file.md',
} as never),
@@ -277,10 +278,10 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Not allowed', 'agent-create-file-denied.md')
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1', path: filePath } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', path: filePath } as never),
).rejects.toThrow('User is not a member of the team')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'notes.md',
content: 'x',
@@ -306,7 +307,7 @@ describe('create_file and create_version agent tools', () => {
} as Parameters<typeof validateToolArguments>[1],
)
await t.execute('call-1', validated as never)
await invokeTool(t, 'call-1', validated as never)
expect(assetService.createFile).toHaveBeenCalledWith(
expect.objectContaining({ name: 'random.txt' }),
)
@@ -324,7 +325,7 @@ describe('create_file and create_version agent tools', () => {
it('uploads a local file and creates a version as the agent', async () => {
const filePath = tempFile('# Hello from disk', 'agent-create-version.md')
const result = await tool('create_version').execute('call-1', {
const result = await invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: filePath,
} as never)
@@ -349,7 +350,7 @@ describe('create_file and create_version agent tools', () => {
it('forwards Creation Context metadata', async () => {
const filePath = tempFile('# Hello', 'agent-create-version-meta.md')
await tool('create_version').execute('call-1', {
await invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: filePath,
metadata: { prompt: 'Generated using gemini' },
@@ -367,7 +368,7 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Not allowed', 'agent-create-version-denied.md')
await expect(
tool('create_version').execute('call-1', { parent: 'file-1', path: filePath } as never),
invokeTool(tool('create_version'), 'call-1', { parent: 'file-1', path: filePath } as never),
).rejects.toThrow('User is not a member of the team')
expect(s3Service.putObject).not.toHaveBeenCalled()
expect(assetService.createVersion).not.toHaveBeenCalled()
@@ -375,7 +376,7 @@ describe('create_file and create_version agent tools', () => {
it('fails when the local file does not exist', async () => {
await expect(
tool('create_version').execute('call-1', {
invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: '/nonexistent/file.md',
} as never),
@@ -1,13 +1,13 @@
import * as fs from 'fs'
import * as path from 'path'
import { z } from 'zod'
import { Type } from 'typebox'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { createFile, type StartedUploadOutput } from '@shumai/operations'
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { completeUploadOp, runOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { createFile, type StartedUploadOutput } from '@shumai/operations'
import * as fs from 'fs'
import * as path from 'path'
import { Type } from 'typebox'
import { z } from 'zod'
import {
registerAgentToolExtension,
type AgentOperationContext,
@@ -48,7 +48,7 @@ async function uploadAndComplete(
raw: unknown,
extra: Record<string, unknown>,
ctx: AgentOperationContext,
): Promise<AgentToolResult<unknown>> {
): Promise<AgentToolResult> {
const started = raw as StartedUploadOutput
if (!started.key) throw new Error('The upload did not return a storage key')
@@ -79,7 +79,7 @@ async function uploadAndComplete(
{ ...ctx, via: 'agent' },
{ uploadId: started.uploadId },
)
return { content: [{ type: 'text', text: JSON.stringify(asset, null, 2) }], details: {} }
return { output: [{ type: 'text', text: JSON.stringify(asset, null, 2) }], details: {} }
}
const createFileExtension: AgentToolExtension = {