feat(operations): add shared Operation layer for agent capabilities (#494)

Introduce @shumai/operations (pure definitions: Zod schemas, metadata,
CLI hints) and @shumai/core/src/operations (implementOperation and the
runOperation pipeline: validate, authorize, prepare, execute, validate
output, audit).

Migrate list_assets, create_folder, rename_asset, move_assets and
delete_asset to Operations, and add list_projects. The agent now builds
these tools from the registry, and the folder create/rename, file
rename and reparent routes call the same Operations.

Audit logs gain a nullable via column recording the surface. A lint
rule keeps the Prisma client out of Operation implementations.
This commit is contained in:
Yiling-J
2026-10-27 08:09:09 +08:00
committed by GitHub
parent 47ee794ae4
commit 76057ccd21
65 changed files with 2372 additions and 1149 deletions
+27
View File
@@ -153,6 +153,7 @@ The project is a monorepo managed by **Bun Workspaces**. It follows a strictly d
2. **Core Layer** calls **Database Layer** and other Core services.
3. **DTO Layer** is imported by all layers to ensure end-to-end type safety.
4. **No Direct DB Leak**: Do not return Prisma objects directly from the API; always map them to DTOs.
5. **Operations First**: If an Operation exists for an action (see [Operations](#operations)), API routes must call it via `runOperation` instead of re-implementing its permission checks and audit logging. UI-only routes (ordering, recents, settings, multi-id variants, etc.) keep calling services directly.
## Dependency Management
@@ -208,6 +209,32 @@ We use a root-level `tsconfig.json` to manage path mappings for the entire works
```
- **Type Safety**: Use `zValidator` for request validation (query, json, form) to ensure full end-to-end type safety with the Hono RPC client.
### Operations
An **Operation** is a capability agents can use, defined once and exposed automatically on every surface: Shumai's built-in agent tools, the MCP server, and `shumai-cli`. Its implementation holds the policy (permission checks, audit logging) and orchestration; the work itself is done by core services.
- **Definition** (`packages/operations/src/**`, package `@shumai/operations`): name (snake_case, used as the tool name), title, description written for an LLM, Zod `input`/`output` schemas with `.describe()` on every field, `surfaces`, `annotations` (`readOnly`, `destructive`, `idempotent`), and optional `cli` metadata. This package must stay free of server dependencies (no `@shumai/core`/`@shumai/db`) so clients like the CLI can import it.
```typescript
export const createFolder = defineOperation({
name: 'create_folder',
title: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
input: z.object({ parent: z.string().describe('...'), name: z.string().describe('...') }),
output: assetSummarySchema,
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false },
cli: { command: ['mkdir'], positional: ['name'], flags: { parent: ['-p', '--parent'] } },
})
```
- **Implementation** (`packages/core/src/operations/**`): `implementOperation(definition, { authz, prepare?, execute, audit? })`.
- `authz` returns every permission the input requires; all are checked before any side effect.
- `execute` calls core services only. **Importing the `prisma` client in Operations is forbidden** (enforced by lint), which is stricter than DBOS activities. Add a service method if one is missing.
- `audit` returns entries; team/project are resolved from the affected asset, never trusted from the caller.
- Outputs are DTOs (validated against the output schema), never Prisma objects.
- **Register** the definition in `packages/operations/src/registry.ts` and the implementation in `packages/core/src/operations/registry.ts`. A definition without an implementation fails typecheck.
- **Run** Operations only through `runOperation(op, { userId, via, agentId? }, input)`. `via` (`api`, `agent`, `mcp`, `cli`) is recorded in audit logs.
- **Tests**: real-database tests per Operation covering success, permission denial (no side effects), and audit entries.
## Frontend Architecture
The frontend is built with:
+4
View File
@@ -8,13 +8,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
* **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
### Fixed
* **asset**: Fix an issue where folders created in the web app didn't record who created them
* **agent**: Fix an issue where an agent could read a comment thread from a project or team the user doesn't have access to by referencing its ID
* **agent**: Fix an issue where an agent creating a file or a new version in a folder the user can't edit still uploaded the file to storage before the request was rejected
### Changed
* **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
* **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
+12
View File
@@ -154,6 +154,7 @@
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@shumai/workflow-core": "workspace:*",
"adm-zip": "0.6.0",
"jittered-fractional-indexing": "1.0.1",
@@ -174,6 +175,7 @@
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"hono": "4.13.5",
"pino": "10.3.1",
"ulid": "3.0.2",
@@ -211,6 +213,7 @@
"@modelcontextprotocol/client": "2.0.0",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@sinclair/typebox": "0.34.52",
"adm-zip": "0.6.0",
"ai": "7.0.84",
@@ -280,6 +283,13 @@
"sharp": "0.35.4",
},
},
"packages/operations": {
"name": "@shumai/operations",
"version": "0.6.1",
"dependencies": {
"zod": "4.5.4",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.6.1",
@@ -1109,6 +1119,8 @@
"@shumai/e2e": ["@shumai/e2e@workspace:packages/e2e"],
"@shumai/operations": ["@shumai/operations@workspace:packages/operations"],
"@shumai/premiere-uxp": ["@shumai/premiere-uxp@workspace:apps/premiere-uxp"],
"@shumai/tableprinter": ["@shumai/tableprinter@workspace:packages/tableprinter"],
+20
View File
@@ -92,6 +92,26 @@ export default tseslint.config(
'@typescript-eslint/naming-convention': baseNamingConvention,
},
},
{
// Operations hold policy and orchestration only; data access belongs in core services.
files: ['packages/core/src/operations/**/*.ts'],
ignores: ['**/*.test.ts'],
rules: {
'@typescript-eslint/no-restricted-imports': [
'error',
{
paths: [
{
name: '@shumai/db',
importNames: ['prisma'],
message: 'Operations must call core services instead of the Prisma client.',
allowTypeImports: true,
},
],
},
],
},
},
{
files: ['**/*.test.ts', '**/*.test.tsx'],
rules: {
+1
View File
@@ -13,6 +13,7 @@
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@shumai/workflow-core": "workspace:*",
"adm-zip": "0.6.0",
"jittered-fractional-indexing": "1.0.1",
+4 -13
View File
@@ -19,19 +19,15 @@ import * as path from 'path'
import { DatabaseSessionStorage } from './database-session-storage'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { createCreateFileTool } from './tools/create-file'
import { createCreateFolderTool } from './tools/create-folder'
import { createCreateVersionTool } from './tools/create-version'
import { createDownloadAssetTool } from './tools/download-asset'
import { createListAssetsTool } from './tools/list-assets'
import { createReadAssetTool } from './tools/read-asset'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { createRenameAssetTool } from './tools/rename-asset'
import { createMoveAssetsTool } from './tools/move-assets'
import { createDeleteAssetTool } from './tools/delete-asset'
import { buildOperationTools } from './operation-tools'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { serializeContextToXml } from './context/serialize-context'
import { DEFAULT_DENIED_TOOLS, type ShumaiMessageContext } from '@shumai/dtos'
@@ -341,14 +337,11 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
const metadataSchema = await buildProjectMetadataSchema(projectId)
const agentContext = { teamId, agentId }
systemTools.push(
createListAssetsTool(userId),
createCreateFolderTool(userId, agentContext),
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete
...buildOperationTools({ userId, agentId, teamId, projectId }),
createCreateFileTool(userId, metadataSchema, agentContext),
createCreateVersionTool(userId, metadataSchema, agentContext),
createDownloadAssetTool(userId),
createRenameAssetTool(userId, agentContext),
createMoveAssetsTool(userId, agentContext),
createDeleteAssetTool(userId, agentContext),
)
}
@@ -635,6 +628,4 @@ export * from './workflows/agent-chat'
export * from './workflows/agent-embedding'
export * from './tools/generate-image'
export * from './tools/generate-video'
export * from './tools/rename-asset'
export * from './tools/move-assets'
export * from './tools/delete-asset'
export * from './operation-tools'
+408
View File
@@ -0,0 +1,408 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Value } from 'typebox/value'
import { validateToolArguments } from '@earendil-works/pi-ai'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { AuditAction, type AssetInfo, type ProjectInfo } from '@shumai/dtos'
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 { projectService } from '@shumai/core/src/project/project'
import { buildOperationTools } from './operation-tools'
const ctx = { userId: 'user-1', agentId: 'agent-1', teamId: 'team-1', projectId: 'proj-1' }
function assetInfo(overrides: Partial<AssetInfo>): AssetInfo {
return {
id: 'asset-1',
name: 'Asset',
sizeByte: 0,
fileCount: 0,
type: 'file',
status: 'uploaded',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
projectId: 'proj-1',
...overrides,
}
}
function getTool(name: string): AgentTool {
const tool = buildOperationTools(ctx).find((t) => t.name === name)
if (!tool) throw new Error(`tool ${name} not built`)
return tool
}
async function run(name: string, params: Record<string, unknown>) {
const result = await getTool(name).execute('call-1', params as never)
return { result, output: JSON.parse((result.content[0] as { text: string }).text) as unknown }
}
function editCheck(id: string) {
return {
user: { id: 'user-1' },
permission: Permission.Edit,
type: ResourceType.Asset,
id,
}
}
describe('operation-backed agent tools', () => {
beforeEach(() => {
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
vi.spyOn(auditLogService, 'logAction').mockResolvedValue(null)
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
})
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('tool definitions', () => {
it('keeps the existing tool names and adds list_projects', () => {
expect(
buildOperationTools(ctx)
.map((t) => t.name)
.sort(),
).toEqual([
'create_folder',
'delete_asset',
'list_assets',
'list_projects',
'move_assets',
'rename_asset',
])
})
it('keeps the existing parameter names', () => {
const params = (name: string) =>
Object.keys((getTool(name).parameters as unknown as { properties: object }).properties)
expect(params('create_folder')).toEqual(['parent', 'name'])
expect(params('rename_asset')).toEqual(['assetId', 'name'])
expect(params('move_assets')).toEqual(['assetIds', 'newParentId'])
expect(params('delete_asset')).toEqual(['assetId'])
expect(params('list_assets')).toEqual(['parent', 'type', 'first', 'after'])
})
it('exposes JSON Schema parameters the harness can validate', () => {
const tool = getTool('move_assets')
expect(tool.parameters).not.toHaveProperty('$schema')
expect(Value.Check(tool.parameters, { assetIds: ['a'], newParentId: 'b' })).toBe(true)
expect(Value.Check(tool.parameters, { assetIds: 'a', newParentId: 'b' })).toBe(false)
const description = (
tool.parameters as unknown as { properties: { assetIds: { description: string } } }
).properties.assetIds.description
expect(description).toContain('same parent folder')
})
it('passes harness validation with null optional parameters', async () => {
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [],
pageInfo: { total: 0 },
})
const tool = getTool('list_assets')
const validated = validateToolArguments(
{ name: tool.name, description: '', parameters: tool.parameters } as Parameters<
typeof validateToolArguments
>[0],
{
type: 'toolCall',
id: 'call-1',
name: tool.name,
arguments: { parent: 'folder-1' },
} as Parameters<typeof validateToolArguments>[1],
)
await expect(tool.execute('call-1', validated as never)).resolves.toBeDefined()
})
})
describe('list_assets', () => {
beforeEach(() => {
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [
assetInfo({ id: '01M2FILE2', name: 'file2.txt', sizeByte: 200 }),
assetInfo({ id: '01M1FILE1', name: 'file1.txt', sizeByte: 100 }),
],
pageInfo: { cursor: 'next-cursor', total: 5 },
})
})
it('checks read permission and lists all types with the default page size', async () => {
const { result, output } = await run('list_assets', { parent: 'folder-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: Permission.Read,
type: ResourceType.Asset,
id: 'folder-1',
})
expect(assetService.listChildren).toHaveBeenCalledWith({
assetId: 'folder-1',
assetType: 'all',
first: 20,
after: undefined,
})
expect(result.details).toEqual({})
expect(output).toEqual({
data: [
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', size: 200, projectId: 'proj-1' },
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', size: 100, projectId: 'proj-1' },
],
pageInfo: { hasNextPage: true, endCursor: 'next-cursor' },
total: 5,
})
})
it('passes cursor pagination and the type filter through', async () => {
await run('list_assets', { parent: 'folder-1', first: 10, after: 'cur', type: 'folder' })
expect(assetService.listChildren).toHaveBeenCalledWith({
assetId: 'folder-1',
assetType: 'folder',
first: 10,
after: 'cur',
})
})
it('treats null optional parameters as omitted', async () => {
await run('list_assets', { parent: 'folder-1', type: null, first: null, after: null })
expect(assetService.listChildren).toHaveBeenCalledWith({
assetId: 'folder-1',
assetType: 'all',
first: 20,
after: undefined,
})
})
it('rejects a null required parameter', async () => {
await expect(run('list_assets', { parent: null })).rejects.toMatchObject({ status: 400 })
expect(assetService.listChildren).not.toHaveBeenCalled()
})
})
describe('create_folder', () => {
beforeEach(() => {
vi.spyOn(assetService, 'createAsset').mockResolvedValue(
assetInfo({ id: 'folder-1', name: 'New Folder', type: 'folder' }),
)
})
it('checks edit permission and creates a folder attributed to the user and agent', async () => {
const { result, output } = await run('create_folder', {
parent: 'root-folder',
name: 'New Folder',
})
expect(authzService.hasPermission).toHaveBeenCalledWith(editCheck('root-folder'))
expect(assetService.createAsset).toHaveBeenCalledWith({
name: 'New Folder',
parentId: 'root-folder',
type: 'folder',
creatorId: 'user-1',
agentId: 'agent-1',
})
expect(result.details).toEqual({})
expect(output).toEqual({
id: 'folder-1',
name: 'New Folder',
type: 'folder',
size: 0,
projectId: 'proj-1',
})
})
it('logs folder_create with the agent and via agent', async () => {
await run('create_folder', { parent: 'root-folder', name: 'New Folder' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_create,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
via: 'agent',
})
})
})
describe('rename_asset', () => {
it('checks edit permission and renames', async () => {
vi.spyOn(assetService, 'updateAssetName').mockResolvedValue(
assetInfo({ id: 'asset-1', name: 'Renamed Asset', sizeByte: 1024 }),
)
const { output } = await run('rename_asset', { assetId: 'asset-1', name: 'Renamed Asset' })
expect(authzService.hasPermission).toHaveBeenCalledWith(editCheck('asset-1'))
expect(assetService.updateAssetName).toHaveBeenCalledWith({
id: 'asset-1',
name: 'Renamed Asset',
})
expect(output).toEqual({
id: 'asset-1',
name: 'Renamed Asset',
type: 'file',
size: 1024,
projectId: 'proj-1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith(
expect.objectContaining({ action: AuditAction.file_update, itemId: 'asset-1' }),
)
})
it('logs folder_update when renaming a folder', async () => {
vi.spyOn(assetService, 'updateAssetName').mockResolvedValue(
assetInfo({ id: 'folder-1', name: 'Renamed Folder', type: 'folder' }),
)
await run('rename_asset', { assetId: 'folder-1', name: 'Renamed Folder' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_update,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
via: 'agent',
})
})
it('fails without renaming when the permission check rejects', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
const update = vi.spyOn(assetService, 'updateAssetName')
await expect(run('rename_asset', { assetId: 'asset-1', name: 'New' })).rejects.toThrow(
'Permission denied',
)
expect(update).not.toHaveBeenCalled()
})
})
describe('move_assets', () => {
beforeEach(() => {
vi.spyOn(assetService, 'reparentAssets').mockResolvedValue(undefined)
})
it('checks permissions on the destination and every asset, then reparents', async () => {
const { output } = await run('move_assets', {
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
expect(vi.mocked(authzService.hasPermission).mock.calls.map(([req]) => req)).toEqual([
editCheck('folder-dest'),
editCheck('asset-1'),
editCheck('asset-2'),
])
expect(assetService.reparentAssets).toHaveBeenCalledWith({
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
creatorId: 'user-1',
})
expect(output).toEqual({ movedAssetIds: ['asset-1', 'asset-2'], newParentId: 'folder-dest' })
})
it('logs asset_reparent for each asset', async () => {
await run('move_assets', { assetIds: ['asset-1', 'asset-2'], newParentId: 'folder-dest' })
expect(assetService.getAssetContext).toHaveBeenCalledWith('folder-dest')
expect(auditLogService.logAction).toHaveBeenCalledTimes(2)
for (const itemId of ['asset-1', 'asset-2']) {
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.asset_reparent,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId,
via: 'agent',
})
}
})
it('fails without moving when the destination permission check rejects', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
new Error('Access denied to destination'),
)
await expect(
run('move_assets', { assetIds: ['asset-1'], newParentId: 'folder-dest' }),
).rejects.toThrow('Access denied to destination')
expect(assetService.reparentAssets).not.toHaveBeenCalled()
})
})
describe('delete_asset', () => {
beforeEach(() => {
vi.spyOn(assetService, 'deleteAssets').mockResolvedValue(undefined)
})
it.each([
['file', AuditAction.file_delete],
['folder', AuditAction.folder_delete],
] as const)('deletes a %s and logs %s', async (type, action) => {
vi.spyOn(assetService, 'getAssetMeta').mockResolvedValue({
id: 'asset-1',
name: 'x',
type,
teamId: 'team-1',
projectId: 'proj-1',
})
const { output } = await run('delete_asset', { assetId: 'asset-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith(editCheck('asset-1'))
expect(assetService.deleteAssets).toHaveBeenCalledWith(['asset-1'])
expect(output).toEqual({ deletedAssetId: 'asset-1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
via: 'agent',
})
})
it('fails without deleting when the asset is not found', async () => {
vi.spyOn(assetService, 'getAssetMeta').mockRejectedValue(new Error('Asset not found'))
await expect(run('delete_asset', { assetId: 'missing' })).rejects.toThrow('Asset not found')
expect(assetService.deleteAssets).not.toHaveBeenCalled()
})
it('fails without deleting when the permission check rejects', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
await expect(run('delete_asset', { assetId: 'asset-1' })).rejects.toThrow('Permission denied')
expect(assetService.deleteAssets).not.toHaveBeenCalled()
})
})
describe('list_projects', () => {
it("lists the user's projects", async () => {
const project: ProjectInfo = {
id: 'proj-1',
name: 'Project',
teamId: 'team-1',
rootFolder: 'root-1',
enableNotification: true,
updatedAt: '2026-01-01T00:00:00.000Z',
}
vi.spyOn(projectService, 'getUserProjects').mockResolvedValue([project])
const { output } = await run('list_projects', {})
expect(projectService.getUserProjects).toHaveBeenCalledWith('user-1', 200)
expect(output).toEqual({
data: [{ id: 'proj-1', name: 'Project', teamId: 'team-1', rootFolderId: 'root-1' }],
})
})
})
})
+67
View File
@@ -0,0 +1,67 @@
import { z } from 'zod'
import type { TSchema } from 'typebox'
import { Compile } from 'typebox/compile'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import {
getOperationsForSurface,
runOperation,
type Operation,
type OperationContext,
} from '@shumai/core/src/operations'
/** Context for agent-invoked Operations; `via` is always `agent`. */
export type AgentOperationContext = Omit<OperationContext, 'via'>
/**
* Convert an Operation's Zod input schema into the JSON Schema the agent harness expects.
* TypeBox schemas are plain JSON Schema at runtime, so the converted schema is used as-is.
* Throws when the schema cannot be compiled, so a bad definition fails loudly in tests.
*/
export function toToolParameters(op: Operation): TSchema {
const schema: Record<string, unknown> = z.toJSONSchema(op.definition.input, { io: 'input' })
// `$schema` is not understood by the harness validator or every model provider.
delete schema.$schema
Compile(schema)
return schema as unknown as TSchema
}
/**
* Models sometimes send `null` for optional parameters they don't want to set. Drop those
* so the Operation's input schema treats them as omitted; nulls for required fields still fail.
*/
function dropNullOptionalFields(op: Operation, params: unknown): unknown {
if (!params || typeof params !== 'object' || Array.isArray(params)) return params
const shape = op.definition.input.shape
return Object.fromEntries(
Object.entries(params).filter(
([key, value]) => !(value === null && shape[key]?.safeParse(undefined).success),
),
)
}
/** Expose an Operation as a native agent tool that runs through `runOperation`. */
export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentTool {
const { definition } = op
return {
name: definition.name,
label: definition.title,
description: definition.description,
parameters: toToolParameters(op),
execute: async (_toolCallId, params) => {
const output = await runOperation(
op,
{ ...ctx, via: 'agent' },
dropNullOptionalFields(op, params),
)
return {
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
details: {},
}
},
}
}
/** Agent tools for every Operation with the `agent` surface. */
export function buildOperationTools(ctx: AgentOperationContext): AgentTool[] {
return getOperationsForSurface('agent').map((op) => toAgentTool(op, ctx))
}
@@ -1,87 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createCreateFolderTool } from './create-folder'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { AuditAction } from '@shumai/dtos'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Edit: 'edit', Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
createAsset: vi.fn().mockResolvedValue({
id: 'folder-1',
name: 'New Folder',
type: 'folder',
sizeByte: 0,
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
describe('createCreateFolderTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks edit permission and calls assetService.createAsset with folder type', async () => {
const tool = createCreateFolderTool('user-1')
const result = await tool.execute('call-1', { parent: 'root-folder', name: 'New Folder' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'root-folder',
})
expect(assetService.createAsset).toHaveBeenCalledWith({
name: 'New Folder',
parentId: 'root-folder',
type: 'folder',
creatorId: 'user-1',
agentId: undefined,
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
id: 'folder-1',
name: 'New Folder',
type: 'folder',
size: 0,
})
})
it('passes agentId and logs audit action when agentContext is provided', async () => {
const tool = createCreateFolderTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { parent: 'root-folder', name: 'New Folder' })
expect(assetService.createAsset).toHaveBeenCalledWith({
name: 'New Folder',
parentId: 'root-folder',
type: 'folder',
creatorId: 'user-1',
agentId: 'agent-1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_create,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: undefined,
itemId: 'folder-1',
})
})
})
-68
View File
@@ -1,68 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
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 { type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const createFolderSchema = Type.Object({
parent: Type.String({
description:
'The parent folder ID under which to create the new folder. This parameter is required.',
}),
name: Type.String({
description: 'The name of the new folder to create. This parameter is required.',
}),
})
export function createCreateFolderTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof createFolderSchema> {
return {
name: 'create_folder',
label: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
parameters: createFolderSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.parent,
})
const newFolder = await assetService.createAsset({
name: params.name,
parentId: params.parent,
type: 'folder',
creatorId: userId,
agentId: agentContext?.agentId,
})
if (agentContext?.teamId) {
await auditLogService.logAction({
action: AuditAction.folder_create,
teamId: agentContext.teamId,
userId,
agentId: agentContext.agentId,
projectId: newFolder.projectId ?? undefined,
itemId: newFolder.id,
})
}
const result = {
id: newFolder.id,
name: newFolder.name,
type: newFolder.type,
size: Number(newFolder.sizeByte),
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
@@ -1,128 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createDeleteAssetTool } from './delete-asset'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Edit: 'edit', Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
deleteAssets: vi.fn().mockResolvedValue(undefined),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('@shumai/db', () => ({
prisma: {
asset: {
findUnique: vi.fn(),
},
},
}))
describe('createDeleteAssetTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks edit permission, deletes asset, and returns success for a file', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'asset-1',
type: 'file',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'asset-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['asset-1'])
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
success: true,
deletedAssetId: 'asset-1',
})
})
it('logs file_delete audit action when deleting a file with agentContext', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'asset-1',
type: 'file',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'asset-1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_delete,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
})
it('logs folder_delete audit action when deleting a folder with agentContext', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'folder-1',
type: 'folder',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'folder-1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_delete,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
})
})
it('throws when asset is not found', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
const tool = createDeleteAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'missing-asset' })).rejects.toThrow(
'Asset not found',
)
})
it('fails when permission check fails', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
const tool = createDeleteAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Permission denied',
)
})
})
-74
View File
@@ -1,74 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
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 { prisma, type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const deleteAssetSchema = Type.Object(
{
assetId: Type.String({
description:
'The ID of the single asset (file or folder) to delete. This parameter is required.',
}),
},
{ additionalProperties: false },
)
export function createDeleteAssetTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof deleteAssetSchema> {
return {
name: 'delete_asset',
label: 'Delete Asset',
description:
'Delete a single asset (file or folder) by its ID. Can only delete one asset at a time.',
parameters: deleteAssetSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.assetId,
})
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
select: { id: true, type: true, projectId: true },
})
if (!asset) {
throw new Error('Asset not found')
}
const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({
teamId: agentContext?.teamId || '',
projectId: asset.projectId ?? undefined,
}))
await assetService.deleteAssets([params.assetId])
if (agentContext?.teamId) {
await auditLogService.logAction({
action: asset.type === 'folder' ? AuditAction.folder_delete : AuditAction.file_delete,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId ?? asset.projectId ?? undefined,
itemId: params.assetId,
})
}
const result = {
success: true,
deletedAssetId: params.assetId,
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
@@ -1,79 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createListAssetsTool } from './list-assets'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService } from '@shumai/core/src/authz/authz'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Edit: 'edit', Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
listChildren: vi.fn().mockResolvedValue({
data: [
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', sizeByte: 200 },
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', sizeByte: 100 },
],
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
}),
},
}))
describe('createListAssetsTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks read permissions and invokes assetService.listChildren with default all and id desc ordering', async () => {
const tool = createListAssetsTool('user-1')
const result = await tool.execute('call-1', { parent: 'folder-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'read',
type: 'asset',
id: 'folder-1',
})
expect(assetService.listChildren).toHaveBeenCalledWith({
assetId: 'folder-1',
assetType: 'all',
sort: 'createdAt',
order: 'desc',
first: 20,
after: undefined,
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
assets: [
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', size: 200 },
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', size: 100 },
],
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
})
})
it('passes explicit pagination and type filter options to assetService.listChildren', async () => {
const tool = createListAssetsTool('user-1')
await tool.execute('call-1', {
parent: 'folder-1',
page: 2,
pageSize: 10,
type: 'folder',
})
expect(assetService.listChildren).toHaveBeenCalledWith({
assetId: 'folder-1',
assetType: 'folder',
sort: 'createdAt',
order: 'desc',
first: 10,
after: expect.any(String),
})
})
})
-77
View File
@@ -1,77 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { encodeCursor } from '@shumai/core/src/pagination'
import { type User } from '@shumai/db'
const listAssetsSchema = Type.Object({
parent: Type.String({
description: 'The parent folder ID to list assets from. This parameter is required.',
}),
page: Type.Optional(
Type.Number({
description: 'The page number to retrieve, default is 1.',
default: 1,
}),
),
pageSize: Type.Optional(
Type.Number({
description: 'The number of assets per page, default is 20.',
default: 20,
}),
),
type: Type.Optional(
Type.Union([Type.Literal('file'), Type.Literal('folder'), Type.Literal('all')], {
description: "Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'.",
default: 'all',
}),
),
})
export function createListAssetsTool(userId: string): AgentTool<typeof listAssetsSchema> {
return {
name: 'list_assets',
label: 'List Assets',
description: 'List the assets (files and folders) inside a parent folder with pagination.',
parameters: listAssetsSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: params.parent,
})
const page = params.page || 1
const pageSize = params.pageSize || 20
const type = params.type || 'all'
const result = await assetService.listChildren({
assetId: params.parent,
assetType: type,
sort: 'createdAt',
order: 'desc',
first: pageSize,
after: page > 1 ? encodeCursor((page - 1) * pageSize) : undefined,
})
const assets = result.data.map((a) => ({
id: a.id,
name: a.name,
type: a.type,
size: Number(a.sizeByte),
}))
const output = {
assets,
pageInfo: result.pageInfo,
}
return {
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
details: {},
}
},
}
}
@@ -1,118 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMoveAssetsTool } from './move-assets'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { AuditAction } from '@shumai/dtos'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Edit: 'edit', Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
reparentAssets: vi.fn().mockResolvedValue(undefined),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
describe('createMoveAssetsTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks permissions on destination and all assets, and calls reparentAssets', async () => {
const tool = createMoveAssetsTool('user-1')
const result = await tool.execute('call-1', {
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'folder-dest',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-2',
})
expect(assetService.reparentAssets).toHaveBeenCalledWith({
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
creatorId: 'user-1',
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
success: true,
movedAssetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
})
it('logs asset_reparent for each asset when agentContext is provided', async () => {
const tool = createMoveAssetsTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', {
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
expect(auditLogService.logAction).toHaveBeenCalledTimes(2)
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.asset_reparent,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.asset_reparent,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-2',
})
})
it('fails when permission check on target folder fails', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
new Error('Access denied to destination'),
)
const tool = createMoveAssetsTool('user-1')
await expect(
tool.execute('call-1', {
assetIds: ['asset-1'],
newParentId: 'folder-dest',
}),
).rejects.toThrow('Access denied to destination')
})
})
-84
View File
@@ -1,84 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
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 { type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const moveAssetsSchema = Type.Object({
assetIds: Type.Array(Type.String(), {
description:
'The IDs of the assets to move. All assets must belong to the same parent folder. At least one asset ID is required.',
minItems: 1,
}),
newParentId: Type.String({
description:
'The destination parent folder ID to move the assets into. This parameter is required.',
}),
})
export function createMoveAssetsTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof moveAssetsSchema> {
return {
name: 'move_assets',
label: 'Move Assets',
description:
'Move one or more assets (files or folders) to a specified parent folder. Note: All assets to be moved must belong to the same current parent folder.',
parameters: moveAssetsSchema,
execute: async (_toolCallId, params) => {
// Check Edit permission on destination folder
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.newParentId,
})
// Check Edit permission on all source assets
for (const assetId of params.assetIds) {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
}
await assetService.reparentAssets({
assetIds: params.assetIds,
newParentId: params.newParentId,
creatorId: userId,
})
if (agentContext?.teamId) {
const ctx = await assetService
.getAssetContext(params.newParentId)
.catch(() => ({ teamId: agentContext.teamId!, projectId: undefined }))
for (const assetId of params.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_reparent,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId,
itemId: assetId,
})
}
}
const result = {
success: true,
movedAssetIds: params.assetIds,
newParentId: params.newParentId,
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
@@ -1,112 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createRenameAssetTool } from './rename-asset'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: { Edit: 'edit', Read: 'read' },
ResourceType: { Asset: 'asset' },
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
updateAssetName: vi.fn().mockResolvedValue({
id: 'asset-1',
name: 'Renamed Asset',
type: 'file',
sizeByte: 1024,
projectId: 'proj-1',
}),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
describe('createRenameAssetTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks edit permission and calls assetService.updateAssetName', async () => {
const tool = createRenameAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed Asset' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(assetService.updateAssetName).toHaveBeenCalledWith({
id: 'asset-1',
name: 'Renamed Asset',
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
id: 'asset-1',
name: 'Renamed Asset',
type: 'file',
size: 1024,
})
})
it('logs file_update audit action when renaming a file with agentContext', async () => {
const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed File' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_update,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
})
it('logs folder_update audit action when renaming a folder with agentContext', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValueOnce({
id: 'folder-1',
name: 'Renamed Folder',
type: 'folder',
sizeByte: 0,
projectId: 'proj-1',
} as unknown as AssetInfo)
const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'folder-1', name: 'Renamed Folder' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_update,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
})
})
it('fails when permission check rejects', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
const tool = createRenameAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'asset-1', name: 'New' })).rejects.toThrow(
'Permission denied',
)
})
})
-69
View File
@@ -1,69 +0,0 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
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 { type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const renameAssetSchema = Type.Object({
assetId: Type.String({
description: 'The ID of the asset (file or folder) to rename. This parameter is required.',
}),
name: Type.String({
description: 'The new name for the asset. This parameter is required.',
}),
})
export function createRenameAssetTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof renameAssetSchema> {
return {
name: 'rename_asset',
label: 'Rename Asset',
description: 'Rename an existing asset (file or folder).',
parameters: renameAssetSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.assetId,
})
const updatedAsset = await assetService.updateAssetName({
id: params.assetId,
name: params.name,
})
if (agentContext?.teamId) {
const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({
teamId: agentContext.teamId!,
projectId: updatedAsset.projectId ?? undefined,
}))
await auditLogService.logAction({
action:
updatedAsset.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId ?? updatedAsset.projectId ?? undefined,
itemId: params.assetId,
})
}
const result = {
id: updatedAsset.id,
name: updatedAsset.name,
type: updatedAsset.type,
size: Number(updatedAsset.sizeByte),
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
+1
View File
@@ -10,6 +10,7 @@
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"hono": "4.13.5",
"pino": "10.3.1",
"ulid": "3.0.2",
+15 -28
View File
@@ -8,6 +8,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import { authMiddleware } from './middleware/auth'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { renameAssetOp, runOperation } from '@shumai/core/src/operations'
vi.mock('fs', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
@@ -55,6 +56,11 @@ vi.mock('./middleware/auth', () => ({
},
}))
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
describe('file api', () => {
beforeEach(() => {
vi.mocked(authzService.hasPermission).mockClear()
@@ -114,18 +120,9 @@ describe('file api', () => {
})
})
it('PUT /files/:fileId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id',
name: 'new-name',
sizeByte: 10,
fileCount: 1,
type: 'file',
status: 'active',
proxyType: 'image',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
it('PUT /files/:fileId runs rename_asset', async () => {
const summary = { id: 'test-id', name: 'new-name', type: 'file', size: 10, projectId: 'p1' }
vi.mocked(runOperation).mockResolvedValue(summary)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/files/test-id', {
@@ -135,22 +132,12 @@ describe('file api', () => {
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'file_update',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
expect(await res.json()).toEqual(summary)
expect(runOperation).toHaveBeenCalledWith(
renameAssetOp,
{ userId: 'user1', via: 'api' },
{ assetId: 'test-id', name: 'new-name' },
)
})
it('DELETE /files', async () => {
+7 -25
View File
@@ -6,6 +6,7 @@ import { notificationService } from '@shumai/core/src/notification/notification'
import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { renameAssetOp, runOperation } from '@shumai/core/src/operations'
import {
createCommentRequestSchema,
deleteFilesRequestSchema,
@@ -63,32 +64,13 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(updated)
})
.put('/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
})
const updatedAsset = await assetService.updateAssetName({
id: fileId,
name: req.name,
})
const context = await assetService.getAssetContext(fileId)
await auditLogService.logAction({
action: AuditAction.file_update,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: fileId,
})
return c.json(updatedAsset)
const file = await runOperation(
renameAssetOp,
{ userId: c.get('user').id, via: 'api' },
{ assetId: c.req.param('fileId'), name: req.name },
)
return c.json(file)
})
.delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
const user = c.get('user')
+36 -52
View File
@@ -5,6 +5,8 @@ import { assetService } from '@shumai/core/src/asset/asset'
import { searchService } from '@shumai/core/src/search/search'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { authMiddleware } from './middleware/auth'
import { HTTPException } from 'hono/http-exception'
import { createFolderOp, renameAssetOp, runOperation } from '@shumai/core/src/operations'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -36,6 +38,11 @@ vi.mock('./middleware/auth', () => ({
},
}))
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
describe('folder api', () => {
beforeEach(() => {
vi.mocked(authzService.hasPermission).mockClear()
@@ -81,17 +88,9 @@ describe('folder api', () => {
})
})
it('PUT /folders/:folderId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id',
name: 'new-name',
sizeByte: 10,
fileCount: 1,
type: 'folder',
status: 'active',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
it('PUT /folders/:folderId runs rename_asset', async () => {
const summary = { id: 'test-id', name: 'new-name', type: 'folder', size: 10, projectId: 'p1' }
vi.mocked(runOperation).mockResolvedValue(summary)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/folders/test-id', {
@@ -101,35 +100,17 @@ describe('folder api', () => {
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'test-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'folder_update',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
expect(await res.json()).toEqual(summary)
expect(runOperation).toHaveBeenCalledWith(
renameAssetOp,
{ userId: 'user1', via: 'api' },
{ assetId: 'test-id', name: 'new-name' },
)
})
it('POST /folders', async () => {
vi.mocked(assetService.createAsset).mockResolvedValue({
id: 'new-id',
name: 'new-folder',
sizeByte: 0,
fileCount: 0,
type: 'folder',
status: 'active',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
it('POST /folders runs create_folder', async () => {
const summary = { id: 'new-id', name: 'new-folder', type: 'folder', size: 0, projectId: 'p1' }
vi.mocked(runOperation).mockResolvedValue(summary)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/folders', {
@@ -139,22 +120,25 @@ describe('folder api', () => {
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-folder')
expect(await res.json()).toEqual(summary)
expect(runOperation).toHaveBeenCalledWith(
createFolderOp,
{ userId: 'user1', via: 'api' },
{ parent: 'parent-id', name: 'new-folder' },
)
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'parent-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'folder_create',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'new-id',
it('POST /folders surfaces Operation errors with their status', async () => {
vi.mocked(runOperation).mockRejectedValue(new HTTPException(403, { message: 'Forbidden' }))
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/folders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
})
expect(res.status).toBe(403)
})
it('GET /folders/:folderId/children', async () => {
+13 -50
View File
@@ -14,37 +14,19 @@ import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction }
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { createFolderOp, renameAssetOp, runOperation } from '@shumai/core/src/operations'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.post('/folders', zValidator('json', createFolderRequestSchema), async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: req.parentId,
})
const newAsset = await assetService.createAsset({
name: req.name,
parentId: req.parentId,
type: 'folder',
})
const parentCtx = await assetService.getAssetContext(req.parentId)
await auditLogService.logAction({
action: AuditAction.folder_create,
teamId: parentCtx.teamId,
userId: user.id,
projectId: parentCtx.projectId,
itemId: newAsset.id,
})
return c.json(newAsset)
const folder = await runOperation(
createFolderOp,
{ userId: c.get('user').id, via: 'api' },
{ parent: req.parentId, name: req.name },
)
return c.json(folder)
})
.patch(
'/folders/:folderId/order',
@@ -66,32 +48,13 @@ const route = new Hono<{ Variables: { user: User } }>()
},
)
.put('/folders/:folderId', zValidator('json', updateFolderRequestSchema), async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: folderId,
})
const updatedAsset = await assetService.updateAssetName({
id: folderId,
name: req.name,
})
const ctx = await assetService.getAssetContext(folderId)
await auditLogService.logAction({
action: AuditAction.folder_update,
teamId: ctx.teamId,
userId: user.id,
projectId: ctx.projectId,
itemId: folderId,
})
return c.json(updatedAsset)
const folder = await runOperation(
renameAssetOp,
{ userId: c.get('user').id, via: 'api' },
{ assetId: c.req.param('folderId'), name: req.name },
)
return c.json(folder)
})
.get('/folders/:folderId', async (c) => {
const folderId = c.req.param('folderId')
+15 -40
View File
@@ -6,6 +6,7 @@ import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { ProjectInfo } from '@shumai/dtos'
import { moveAssetsOp, runOperation } from '@shumai/core/src/operations'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
@@ -35,6 +36,10 @@ vi.mock('@shumai/core/src/project/project', () => ({
},
}))
vi.mock('@shumai/core/src/asset/asset')
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
@@ -181,9 +186,11 @@ describe('project api', () => {
})
})
it('POST /projects/:projectId/reparent', async () => {
vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1')
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
it('POST /projects/:projectId/reparent runs move_assets', async () => {
vi.mocked(runOperation).mockResolvedValue({
movedAssetIds: ['asset_1', 'asset_2'],
newParentId: 'new_parent_id',
})
const res = await app.request('/projects/p/reparent', {
method: 'POST',
@@ -195,43 +202,11 @@ describe('project api', () => {
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'new_parent_id',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'asset_1',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Asset,
id: 'asset_2',
})
expect(assetService.reparentAssets).toHaveBeenCalledWith({
newParentId: 'new_parent_id',
assetIds: ['asset_1', 'asset_2'],
creatorId: 'user1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_reparent',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_reparent',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_2',
})
expect(runOperation).toHaveBeenCalledWith(
moveAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: ['asset_1', 'asset_2'], newParentId: 'new_parent_id' },
)
})
it('POST /projects/:projectId/copy', async () => {
+7 -39
View File
@@ -18,6 +18,7 @@ import {
import { listMembersQuerySchema, AuditAction } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { moveAssetsOp, runOperation } from '@shumai/core/src/operations'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -291,46 +292,13 @@ const route = new Hono<{ Variables: { user: User } }>()
'/projects/:projectId/reparent',
zValidator('json', reparentAssetsRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
// Check Edit permission on target folder/project
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: req.newParentId,
})
// Check Edit permission on all source assets
for (const assetId of req.assetIds) {
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
}
await assetService.reparentAssets({
...req,
creatorId: user.id,
})
const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
if (teamId) {
for (const assetId of req.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_reparent,
teamId,
userId: user.id,
projectId,
itemId: assetId,
})
}
}
// Team/project for authorization and audit come from the assets themselves, not the path.
await runOperation(
moveAssetsOp,
{ userId: c.get('user').id, via: 'api' },
{ assetIds: req.assetIds, newParentId: req.newParentId },
)
return c.body(null, 204)
},
)
+1
View File
@@ -33,6 +33,7 @@
"@modelcontextprotocol/client": "2.0.0",
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@shumai/operations": "workspace:*",
"@sinclair/typebox": "0.34.52",
"adm-zip": "0.6.0",
"ai": "7.0.84",
+18
View File
@@ -1140,6 +1140,24 @@ export class AssetService {
throw new Error(`Asset has no team context: ${assetId}`)
}
/**
* Lightweight lookup of an asset's type and team/project, without building a full AssetInfo
* (no presigned URLs). Use it to capture context before a mutation such as a delete.
*/
async getAssetMeta(
assetId: string,
): Promise<{ id: string; name: string; type: AssetType; teamId: string; projectId?: string }> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
select: { id: true, name: true, type: true },
})
if (!asset) {
throw new HTTPException(404, { message: 'Asset not found' })
}
const { teamId, projectId } = await this.getAssetContext(assetId)
return { ...asset, teamId, projectId }
}
async resolveTargetAssetId(assetId: string): Promise<string> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
+4
View File
@@ -1,6 +1,7 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import type { AuditAction } from '@shumai/dtos'
import type { Via } from '@shumai/operations'
import { paginateQuery } from '@shumai/core/src/pagination'
import { logger } from '@shumai/core/src/logger'
@@ -11,6 +12,8 @@ export interface LogActionParams {
agentId?: string
projectId?: string
itemId?: string
/** Surface the action came through. Set by Operations; omitted elsewhere. */
via?: Via
}
export interface ListAuditLogsParams {
@@ -34,6 +37,7 @@ export class AuditLogService {
agentId: params.agentId,
projectId: params.projectId,
itemId: params.itemId,
via: params.via,
},
})
} catch (err) {
+2 -1
View File
@@ -30,7 +30,8 @@ export enum ResourceType {
}
export interface AuthzRequest {
user: User
/** Only the user's ID is used, so callers that only know the ID can pass `{ id }`. */
user: Pick<User, 'id'>
permission: Permission
type: ResourceType
id: string
@@ -0,0 +1,23 @@
import { createFolder } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const createFolderOp = implementOperation(createFolder, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.parent }],
execute: async (input, ctx) =>
toAssetSummary(
await assetService.createAsset({
name: input.name,
parentId: input.parent,
type: 'folder',
creatorId: ctx.userId,
agentId: ctx.agentId,
}),
),
audit: (_input, output) => [
{ action: AuditAction.folder_create, itemId: output.id, contextAssetId: output.id },
],
})
@@ -0,0 +1,23 @@
import { deleteAsset } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const deleteAssetOp = implementOperation(deleteAsset, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.assetId }],
// Resolve type and team before deleting: the audit entry needs them afterwards.
prepare: (input) => assetService.getAssetMeta(input.assetId),
execute: async (input) => {
await assetService.deleteAssets([input.assetId])
return { deletedAssetId: input.assetId }
},
audit: (input, _output, _ctx, asset) => [
{
action: asset.type === 'folder' ? AuditAction.folder_delete : AuditAction.file_delete,
itemId: input.assetId,
teamId: asset.teamId,
projectId: asset.projectId,
},
],
})
@@ -0,0 +1,25 @@
import { DEFAULT_PAGE_SIZE, listAssets } from '@shumai/operations'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const listAssetsOp = implementOperation(listAssets, {
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.parent }],
execute: async (input) => {
const result = await assetService.listChildren({
assetId: input.parent,
assetType: input.type ?? 'all',
first: input.first ?? DEFAULT_PAGE_SIZE,
after: input.after,
})
return {
data: result.data.map(toAssetSummary),
pageInfo: {
hasNextPage: Boolean(result.pageInfo.cursor),
endCursor: result.pageInfo.cursor ?? null,
},
total: result.pageInfo.total ?? result.data.length,
}
},
})
@@ -0,0 +1,30 @@
import { moveAssets } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
export const moveAssetsOp = implementOperation(moveAssets, {
authz: (input) => [
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.newParentId },
...input.assetIds.map((id) => ({
permission: Permission.Edit,
type: ResourceType.Asset,
id,
})),
],
execute: async (input, ctx) => {
await assetService.reparentAssets({
assetIds: input.assetIds,
newParentId: input.newParentId,
creatorId: ctx.userId,
})
return { movedAssetIds: input.assetIds, newParentId: input.newParentId }
},
audit: (input) =>
input.assetIds.map((assetId) => ({
action: AuditAction.asset_reparent,
itemId: assetId,
contextAssetId: input.newParentId,
})),
})
@@ -0,0 +1,19 @@
import { renameAsset } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset'
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { implementOperation } from '../implement'
import { toAssetSummary } from './to-asset-summary'
export const renameAssetOp = implementOperation(renameAsset, {
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.assetId }],
execute: async (input) =>
toAssetSummary(await assetService.updateAssetName({ id: input.assetId, name: input.name })),
audit: (input, output) => [
{
action: output.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update,
itemId: input.assetId,
contextAssetId: input.assetId,
},
],
})
@@ -0,0 +1,12 @@
import type { AssetSummary } from '@shumai/operations'
import type { AssetInfo } from '@shumai/dtos'
export function toAssetSummary(asset: AssetInfo): AssetSummary {
return {
id: asset.id,
name: asset.name,
type: asset.type,
size: Number(asset.sizeByte),
projectId: asset.projectId ?? null,
}
}
+17
View File
@@ -0,0 +1,17 @@
import type { Via } from '@shumai/operations'
/** Who is invoking an Operation and through which surface. */
export interface OperationContext {
/** The acting user. Permission checks and audit attribution use this user. */
userId: string
/** Where the invocation came from; recorded in audit logs. */
via: Via
/** The agent acting on the user's behalf, when invoked by Shumai's built-in agent. */
agentId?: string
/**
* Session hints from the caller (e.g. the agent's current team/project). Never used for
* authorization or audit attribution, which are always resolved from the affected resource.
*/
teamId?: string
projectId?: string
}
+66
View File
@@ -0,0 +1,66 @@
import type { z } from 'zod'
import type { AnyOperationDefinition } from '@shumai/operations'
import type { AuditAction } from '@shumai/dtos'
import type { Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { OperationContext } from './context'
/** A permission the caller must hold before the Operation runs. */
export interface AuthzCheck {
permission: Permission
type: ResourceType
id: string
}
/**
* An audit log entry written after the Operation succeeds. Team and project are resolved
* from `contextAssetId`, or supplied explicitly when that asset may no longer resolve
* (e.g. after a delete; load them in `prepare`).
*/
export type AuditEntry =
| { action: AuditAction; itemId: string; contextAssetId: string }
| { action: AuditAction; itemId: string; teamId: string; projectId?: string }
export type OperationInput<TDef extends AnyOperationDefinition> = z.output<TDef['input']>
export type OperationOutput<TDef extends AnyOperationDefinition> = z.output<TDef['output']>
type OperationResult<TDef extends AnyOperationDefinition> = z.input<TDef['output']>
export interface OperationImplementation<TDef extends AnyOperationDefinition, TPrepared> {
/** Permissions required for this input. All are checked before any side effect. */
authz(
input: OperationInput<TDef>,
ctx: OperationContext,
): readonly AuthzCheck[] | Promise<readonly AuthzCheck[]>
/** Optional read-only step after authorization; its result is passed to `execute` and `audit`. */
prepare?(input: OperationInput<TDef>, ctx: OperationContext): Promise<TPrepared>
/** Perform the Operation by calling core services. Must return data matching the output schema. */
execute(
input: OperationInput<TDef>,
ctx: OperationContext,
prepared: TPrepared,
): Promise<OperationResult<TDef>>
/** Audit entries to record for a successful invocation. */
audit?(
input: OperationInput<TDef>,
output: OperationOutput<TDef>,
ctx: OperationContext,
prepared: TPrepared,
): readonly AuditEntry[] | Promise<readonly AuditEntry[]>
}
/** An Operation definition bound to its implementation. Run it with `runOperation`. */
export interface Operation<TDef extends AnyOperationDefinition = AnyOperationDefinition> {
readonly definition: TDef
readonly implementation: OperationImplementation<TDef, unknown>
}
export function implementOperation<TDef extends AnyOperationDefinition, TPrepared = undefined>(
definition: TDef,
implementation: OperationImplementation<TDef, TPrepared>,
): Operation<TDef> {
return Object.freeze({
definition,
// The prepared value only flows from this implementation's `prepare` into its own
// `execute`/`audit`, so erasing its type here is safe.
implementation: implementation as OperationImplementation<TDef, unknown>,
})
}
+18
View File
@@ -0,0 +1,18 @@
export type { OperationContext } from './context'
export {
implementOperation,
type AuditEntry,
type AuthzCheck,
type Operation,
type OperationImplementation,
type OperationInput,
type OperationOutput,
} from './implement'
export { runOperation } from './run'
export { getOperation, getOperationsForSurface, operations } from './registry'
export { createFolderOp } from './asset/create-folder'
export { deleteAssetOp } from './asset/delete-asset'
export { listAssetsOp } from './asset/list-assets'
export { moveAssetsOp } from './asset/move-assets'
export { renameAssetOp } from './asset/rename-asset'
export { listProjectsOp } from './project/list-projects'
@@ -0,0 +1,297 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { AuditAction } from '@shumai/dtos'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import {
createFolderOp,
deleteAssetOp,
listAssetsOp,
listProjectsOp,
moveAssetsOp,
renameAssetOp,
} from './index'
import { runOperation } from './run'
import type { OperationContext } from './context'
describe('asset and project Operations', () => {
setupTestDbHooks()
let owner: User
let reviewer: User
let outsider: User
let teamId: string
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: 'ops-owner@test.com', password: 'pw' },
})
reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'ops-reviewer@test.com', password: 'pw' },
})
outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'ops-outsider@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'Ops Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
const project = await projectService.createProject(owner, { teamId, name: 'Ops Project' })
projectId = project.id
rootFolderId = project.rootFolder!
})
async function auditRows(action: AuditAction) {
return prisma.auditLog.findMany({ where: { action }, orderBy: { id: 'asc' } })
}
describe('create_folder', () => {
it('creates a folder attributed to the caller and audits it with via', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'Renders',
})
expect(folder).toEqual({
id: expect.any(String),
name: 'Renders',
type: 'folder',
size: 0,
projectId,
})
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.parentId).toBe(rootFolderId)
expect(row.creatorId).toBe(owner.id)
const [audit] = await auditRows(AuditAction.folder_create)
expect(audit).toMatchObject({
teamId,
projectId,
userId: owner.id,
itemId: folder.id,
via: 'cli',
})
})
it.each([
['reviewer', () => reviewer],
['non-member', () => outsider],
])('rejects a %s without creating anything', async (_label, user) => {
await expect(
runOperation(createFolderOp, as(user()), { parent: rootFolderId, name: 'Nope' }),
).rejects.toMatchObject({ status: 403 })
expect(await prisma.asset.count({ where: { name: 'Nope' } })).toBe(0)
expect(await auditRows(AuditAction.folder_create)).toHaveLength(0)
})
})
describe('list_assets', () => {
it('paginates with first/after and reports the total', async () => {
for (const name of ['a', 'b', 'c']) {
await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name })
}
const page1 = await runOperation(listAssetsOp, as(reviewer), {
parent: rootFolderId,
first: 2,
})
expect(page1.data).toHaveLength(2)
expect(page1.total).toBe(3)
expect(page1.pageInfo.hasNextPage).toBe(true)
expect(page1.pageInfo.endCursor).toEqual(expect.any(String))
const page2 = await runOperation(listAssetsOp, as(reviewer), {
parent: rootFolderId,
first: 2,
after: page1.pageInfo.endCursor!,
})
expect(page2.data).toHaveLength(1)
expect(page2.pageInfo).toEqual({ hasNextPage: false, endCursor: null })
const names = [...page1.data, ...page2.data].map((a) => a.name).sort()
expect(names).toEqual(['a', 'b', 'c'])
})
it('filters by type', async () => {
await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'only-folder' })
const files = await runOperation(listAssetsOp, as(owner), {
parent: rootFolderId,
type: 'file',
})
expect(files.data).toEqual([])
const folders = await runOperation(listAssetsOp, as(owner), {
parent: rootFolderId,
type: 'folder',
})
expect(folders.data.map((a) => a.name)).toEqual(['only-folder'])
})
it('rejects a non-member', async () => {
await expect(
runOperation(listAssetsOp, as(outsider), { parent: rootFolderId }),
).rejects.toMatchObject({ status: 403 })
})
it('rejects a page size above the maximum', async () => {
await expect(
runOperation(listAssetsOp, as(owner), { parent: rootFolderId, first: 500 }),
).rejects.toMatchObject({ status: 400 })
})
})
describe('rename_asset', () => {
it('renames and audits a folder update', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'old',
})
const renamed = await runOperation(renameAssetOp, as(owner, 'api'), {
assetId: folder.id,
name: 'new',
})
expect(renamed).toMatchObject({ id: folder.id, name: 'new', type: 'folder' })
const [audit] = await auditRows(AuditAction.folder_update)
expect(audit).toMatchObject({ itemId: folder.id, teamId, projectId, via: 'api' })
})
it('rejects a reviewer and leaves the name unchanged', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'keep',
})
await expect(
runOperation(renameAssetOp, as(reviewer), { assetId: folder.id, name: 'changed' }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.name).toBe('keep')
})
})
describe('move_assets', () => {
it('moves assets and audits each one', async () => {
const dest = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'dest',
})
const a = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'a' })
const b = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'b' })
const result = await runOperation(moveAssetsOp, as(owner, 'mcp'), {
assetIds: [a.id, b.id],
newParentId: dest.id,
})
expect(result).toEqual({ movedAssetIds: [a.id, b.id], newParentId: dest.id })
const moved = await prisma.asset.findMany({ where: { id: { in: [a.id, b.id] } } })
expect(moved.every((m) => m.parentId === dest.id)).toBe(true)
const audits = await auditRows(AuditAction.asset_reparent)
expect(audits.map((r) => r.itemId).sort()).toEqual([a.id, b.id].sort())
expect(audits.every((r) => r.via === 'mcp' && r.projectId === projectId)).toBe(true)
})
it('requires at least one asset', async () => {
await expect(
runOperation(moveAssetsOp, as(owner), { assetIds: [], newParentId: rootFolderId }),
).rejects.toMatchObject({ status: 400 })
})
it('rejects a reviewer without moving anything', async () => {
const dest = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'dest',
})
const a = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 'a' })
await expect(
runOperation(moveAssetsOp, as(reviewer), { assetIds: [a.id], newParentId: dest.id }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: a.id } })
expect(row.parentId).toBe(rootFolderId)
})
})
describe('delete_asset', () => {
it('trashes the asset and audits with the context captured before deletion', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'trash-me',
})
const result = await runOperation(deleteAssetOp, as(owner, 'agent'), { assetId: folder.id })
expect(result).toEqual({ deletedAssetId: folder.id })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.isDeleted).toBe(true)
const [audit] = await auditRows(AuditAction.folder_delete)
expect(audit).toMatchObject({ itemId: folder.id, teamId, projectId, via: 'agent' })
})
it('rejects a reviewer without deleting', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'keep-me',
})
await expect(
runOperation(deleteAssetOp, as(reviewer), { assetId: folder.id }),
).rejects.toMatchObject({ status: 403 })
const row = await prisma.asset.findUniqueOrThrow({ where: { id: folder.id } })
expect(row.isDeleted).toBe(false)
})
it('returns 404 for an unknown asset', async () => {
await expect(
runOperation(deleteAssetOp, as(owner), { assetId: 'missing' }),
).rejects.toMatchObject({ status: 404 })
})
})
describe('list_projects', () => {
it("lists the caller's projects with their root folder", async () => {
const result = await runOperation(listProjectsOp, as(reviewer), {})
expect(result.data).toEqual([{ id: projectId, name: 'Ops Project', teamId, rootFolderId }])
})
it('returns nothing for a user outside every team', async () => {
const result = await runOperation(listProjectsOp, as(outsider), {})
expect(result.data).toEqual([])
})
})
describe('assetService.getAssetMeta', () => {
it('returns type and team context without building AssetInfo', async () => {
const folder = await runOperation(createFolderOp, as(owner), {
parent: rootFolderId,
name: 'meta',
})
await expect(assetService.getAssetMeta(folder.id)).resolves.toEqual({
id: folder.id,
name: 'meta',
type: 'folder',
teamId,
projectId,
})
})
it('throws a 404 for an unknown asset', async () => {
await expect(assetService.getAssetMeta('missing')).rejects.toMatchObject({ status: 404 })
})
})
})
@@ -0,0 +1,19 @@
import { listProjects, MAX_PAGE_SIZE } from '@shumai/operations'
import { projectService } from '@shumai/core/src/project/project'
import { implementOperation } from '../implement'
export const listProjectsOp = implementOperation(listProjects, {
// Only the caller's own projects are listed, scoped by team/project membership in the service.
authz: () => [],
execute: async (input, ctx) => {
const projects = await projectService.getUserProjects(ctx.userId, input.first ?? MAX_PAGE_SIZE)
return {
data: projects.map((p) => ({
id: p.id,
name: p.name,
teamId: p.teamId,
rootFolderId: p.rootFolder ?? null,
})),
}
},
})
+50
View File
@@ -0,0 +1,50 @@
import type { OperationName, Surface } from '@shumai/operations'
import { createFolderOp } from './asset/create-folder'
import { deleteAssetOp } from './asset/delete-asset'
import { listAssetsOp } from './asset/list-assets'
import { moveAssetsOp } from './asset/move-assets'
import { renameAssetOp } from './asset/rename-asset'
import type { Operation } from './implement'
import { listProjectsOp } from './project/list-projects'
type ImplementedName<TOps extends readonly Operation[]> = TOps[number]['definition']['name']
type MissingNames<TOps extends readonly Operation[]> = Exclude<OperationName, ImplementedName<TOps>>
/**
* Type-level guard: compiling fails with `missingImplementations` listing any definition in
* `@shumai/operations` that has no implementation here.
*/
function defineRegistry<const TOps extends readonly Operation[]>(
ops: TOps &
([MissingNames<TOps>] extends [never]
? unknown
: { missingImplementations: MissingNames<TOps> }),
): TOps {
return ops
}
/** Every implemented Operation. Each definition in `@shumai/operations` must appear exactly once. */
export const operations = defineRegistry([
listProjectsOp,
listAssetsOp,
createFolderOp,
renameAssetOp,
moveAssetsOp,
deleteAssetOp,
] as const)
const operationsByName = new Map<string, Operation>()
for (const op of operations) {
if (operationsByName.has(op.definition.name)) {
throw new Error(`Duplicate operation implementation "${op.definition.name}"`)
}
operationsByName.set(op.definition.name, op)
}
export function getOperation(name: string): Operation | undefined {
return operationsByName.get(name)
}
export function getOperationsForSurface(surface: Surface): Operation[] {
return operations.filter((op) => op.definition.surfaces.includes(surface))
}
+187
View File
@@ -0,0 +1,187 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { HTTPException } from 'hono/http-exception'
import { defineOperation } from '@shumai/operations'
import { AuditAction } from '@shumai/dtos'
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 { implementOperation, type OperationImplementation } from './implement'
import { runOperation } from './run'
import type { OperationContext } from './context'
const touchThing = defineOperation({
name: 'touch_thing',
title: 'Touch Thing',
description: 'Touch a thing for testing.',
input: z.object({ thingId: z.string().min(1), otherId: z.string().optional() }),
output: z.object({ touched: z.string() }),
surfaces: ['agent'],
annotations: { readOnly: false, destructive: false },
})
const ctx: OperationContext = { userId: 'user-1', agentId: 'agent-1', via: 'agent' }
describe('runOperation', () => {
const calls: string[] = []
beforeEach(() => {
calls.length = 0
vi.spyOn(authzService, 'hasPermission').mockImplementation(async (req) => {
calls.push(`authz:${req.id}`)
})
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({
teamId: 'team-ctx',
projectId: 'project-ctx',
})
vi.spyOn(auditLogService, 'logAction').mockImplementation(async (params) => {
calls.push(`audit:${params.itemId}`)
return null
})
})
afterEach(() => {
vi.restoreAllMocks()
})
function makeOp(overrides: Partial<OperationImplementation<typeof touchThing, unknown>> = {}) {
return implementOperation(touchThing, {
authz: (input) => {
const checks = [
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.thingId },
]
if (input.otherId) {
checks.push({ permission: Permission.Read, type: ResourceType.Asset, id: input.otherId })
}
return checks
},
prepare: async () => {
calls.push('prepare')
return { label: 'prepared' }
},
execute: async (input, _ctx, prepared) => {
calls.push(`execute:${(prepared as { label: string }).label}`)
return { touched: input.thingId }
},
audit: (input) => [
{ action: AuditAction.file_update, itemId: input.thingId, contextAssetId: input.thingId },
],
...overrides,
})
}
it('runs validate → authz → prepare → execute → audit in order and returns the output', async () => {
const output = await runOperation(makeOp(), ctx, { thingId: 't1', otherId: 't2' })
expect(output).toEqual({ touched: 't1' })
expect(calls).toEqual(['authz:t1', 'authz:t2', 'prepare', 'execute:prepared', 'audit:t1'])
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: Permission.Edit,
type: ResourceType.Asset,
id: 't1',
})
})
it('rejects invalid input with a 400 before checking permissions', async () => {
const promise = runOperation(makeOp(), ctx, { thingId: '' })
await expect(promise).rejects.toBeInstanceOf(HTTPException)
await expect(runOperation(makeOp(), ctx, { thingId: '' })).rejects.toMatchObject({
status: 400,
message: expect.stringContaining('Invalid input for touch_thing'),
})
expect(calls).toEqual([])
})
it('treats a missing input as an empty object', async () => {
await expect(runOperation(makeOp(), ctx, undefined)).rejects.toMatchObject({ status: 400 })
})
it('stops before any side effect when a later permission check fails', async () => {
vi.mocked(authzService.hasPermission).mockImplementation(async (req) => {
calls.push(`authz:${req.id}`)
if (req.id === 't2') throw new HTTPException(403, { message: 'Forbidden' })
})
await expect(runOperation(makeOp(), ctx, { thingId: 't1', otherId: 't2' })).rejects.toThrow(
'Forbidden',
)
expect(calls).toEqual(['authz:t1', 'authz:t2'])
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('fails with a 500 and writes no audit entry when the output does not match the schema', async () => {
const op = makeOp({
// Simulates an implementation bug the type checker cannot see
execute: async () => ({ touched: 42 }) as unknown as { touched: string },
})
await expect(runOperation(op, ctx, { thingId: 't1' })).rejects.toMatchObject({ status: 500 })
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('strips fields that are not part of the output schema', async () => {
const op = makeOp({
execute: async () => ({ touched: 't1', secret: 'x' }) as { touched: string },
})
await expect(runOperation(op, ctx, { thingId: 't1' })).resolves.toEqual({ touched: 't1' })
})
it('records audit entries with the caller, agent, via, and the resource team context', async () => {
await runOperation(makeOp(), { ...ctx, teamId: 'session-team' }, { thingId: 't1' })
expect(assetService.getAssetContext).toHaveBeenCalledWith('t1')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_update,
teamId: 'team-ctx',
projectId: 'project-ctx',
itemId: 't1',
userId: 'user-1',
agentId: 'agent-1',
via: 'agent',
})
})
it('uses explicit team context from audit entries when provided', async () => {
const op = makeOp({
audit: () => [
{ action: AuditAction.file_delete, itemId: 't1', teamId: 'team-x', projectId: 'p-x' },
],
})
await runOperation(op, { userId: 'user-1', via: 'api' }, { thingId: 't1' })
expect(assetService.getAssetContext).not.toHaveBeenCalled()
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_delete,
teamId: 'team-x',
projectId: 'p-x',
itemId: 't1',
userId: 'user-1',
agentId: undefined,
via: 'api',
})
})
it('still succeeds when the audit context cannot be resolved', async () => {
vi.mocked(assetService.getAssetContext).mockRejectedValue(new Error('Asset not found'))
await expect(runOperation(makeOp(), ctx, { thingId: 't1' })).resolves.toEqual({
touched: 't1',
})
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
it('propagates errors thrown by execute without auditing', async () => {
const op = makeOp({
execute: async () => {
throw new HTTPException(409, { message: 'Conflict' })
},
})
await expect(runOperation(op, ctx, { thingId: 't1' })).rejects.toMatchObject({ status: 409 })
expect(auditLogService.logAction).not.toHaveBeenCalled()
})
})
+100
View File
@@ -0,0 +1,100 @@
import { z } from 'zod'
import { HTTPException } from 'hono/http-exception'
import type { AnyOperationDefinition } from '@shumai/operations'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import type { OperationContext } from './context'
import type { AuditEntry, Operation, OperationInput, OperationOutput } from './implement'
/**
* Run an Operation for a caller. Every surface (agent tools, MCP, CLI, REST routes) goes
* through this pipeline, in this order:
*
* 1. validate the input against the definition (HTTP 400 on failure)
* 2. check every declared permission, before any side effect
* 3. prepare (optional read-only step)
* 4. execute
* 5. validate the output against the definition (HTTP 500 on failure: a bug)
* 6. write audit entries
*
* Errors from authorization and services propagate unchanged (usually `HTTPException`).
*/
export async function runOperation<TDef extends AnyOperationDefinition>(
op: Operation<TDef>,
ctx: OperationContext,
rawInput: unknown,
): Promise<OperationOutput<TDef>> {
const { definition, implementation } = op
const parsedInput = definition.input.safeParse(rawInput ?? {})
if (!parsedInput.success) {
throw new HTTPException(400, {
message: `Invalid input for ${definition.name}: ${z.prettifyError(parsedInput.error)}`,
})
}
// safeParse on the generic schema type loses the concrete shape; the schema guarantees it.
const input = parsedInput.data as OperationInput<TDef>
const checks = await implementation.authz(input, ctx)
for (const check of checks) {
await authzService.hasPermission({ user: { id: ctx.userId }, ...check })
}
const prepared = implementation.prepare ? await implementation.prepare(input, ctx) : undefined
const result = await implementation.execute(input, ctx, prepared)
const parsedOutput = definition.output.safeParse(result)
if (!parsedOutput.success) {
logger.error(
{ operation: definition.name, issues: parsedOutput.error.issues },
'Operation returned output that does not match its schema',
)
throw new HTTPException(500, { message: `Operation ${definition.name} failed` })
}
const output = parsedOutput.data as OperationOutput<TDef>
if (implementation.audit) {
const entries = await implementation.audit(input, output, ctx, prepared)
for (const entry of entries) {
await writeAuditEntry(definition.name, entry, ctx)
}
}
return output
}
async function writeAuditEntry(
operation: string,
entry: AuditEntry,
ctx: OperationContext,
): Promise<void> {
let teamId: string
let projectId: string | undefined
if ('contextAssetId' in entry) {
try {
;({ teamId, projectId } = await assetService.getAssetContext(entry.contextAssetId))
} catch (err) {
// The Operation already succeeded; a missing audit entry must not turn it into a failure.
logger.warn(
{ err, operation, itemId: entry.itemId, contextAssetId: entry.contextAssetId },
'Skipping audit entry: could not resolve team context',
)
return
}
} else {
teamId = entry.teamId
projectId = entry.projectId
}
await auditLogService.logAction({
action: entry.action,
teamId,
projectId,
itemId: entry.itemId,
userId: ctx.userId,
agentId: ctx.agentId,
via: ctx.via,
})
}
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "audit_logs" ADD COLUMN "via" TEXT;
+2
View File
@@ -1132,6 +1132,8 @@ model AuditLog {
agentId String? @map("agent_id")
projectId String? @map("project_id")
itemId String? @map("item_id")
/// Surface the action came through: api, agent, mcp, or cli. Null for actions recorded outside Operations.
via String? @map("via")
createdAt DateTime @default(now()) @map("created_at")
team Team @relation("TeamToAuditLog", fields: [teamId], references: [id], onDelete: Cascade)
File diff suppressed because one or more lines are too long
@@ -4976,6 +4976,7 @@ export const AuditLogScalarFieldEnum = {
agentId: 'agentId',
projectId: 'projectId',
itemId: 'itemId',
via: 'via',
createdAt: 'createdAt'
} as const
@@ -742,6 +742,7 @@ export const AuditLogScalarFieldEnum = {
agentId: 'agentId',
projectId: 'projectId',
itemId: 'itemId',
via: 'via',
createdAt: 'createdAt'
} as const
+57 -1
View File
@@ -34,6 +34,7 @@ export type AuditLogMinAggregateOutputType = {
agentId: string | null
projectId: string | null
itemId: string | null
via: string | null
createdAt: Date | null
}
@@ -45,6 +46,7 @@ export type AuditLogMaxAggregateOutputType = {
agentId: string | null
projectId: string | null
itemId: string | null
via: string | null
createdAt: Date | null
}
@@ -56,6 +58,7 @@ export type AuditLogCountAggregateOutputType = {
agentId: number
projectId: number
itemId: number
via: number
createdAt: number
_all: number
}
@@ -69,6 +72,7 @@ export type AuditLogMinAggregateInputType = {
agentId?: true
projectId?: true
itemId?: true
via?: true
createdAt?: true
}
@@ -80,6 +84,7 @@ export type AuditLogMaxAggregateInputType = {
agentId?: true
projectId?: true
itemId?: true
via?: true
createdAt?: true
}
@@ -91,6 +96,7 @@ export type AuditLogCountAggregateInputType = {
agentId?: true
projectId?: true
itemId?: true
via?: true
createdAt?: true
_all?: true
}
@@ -175,6 +181,7 @@ export type AuditLogGroupByOutputType = {
agentId: string | null
projectId: string | null
itemId: string | null
via: string | null
createdAt: Date
_count: AuditLogCountAggregateOutputType | null
_min: AuditLogMinAggregateOutputType | null
@@ -207,6 +214,7 @@ export type AuditLogWhereInput = {
agentId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
projectId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
itemId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
via?: Prisma.StringNullableFilter<"AuditLog"> | string | null
createdAt?: Prisma.DateTimeFilter<"AuditLog"> | Date | string
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
user?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
@@ -222,6 +230,7 @@ export type AuditLogOrderByWithRelationInput = {
agentId?: Prisma.SortOrderInput | Prisma.SortOrder
projectId?: Prisma.SortOrderInput | Prisma.SortOrder
itemId?: Prisma.SortOrderInput | Prisma.SortOrder
via?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
team?: Prisma.TeamOrderByWithRelationInput
user?: Prisma.UserOrderByWithRelationInput
@@ -240,6 +249,7 @@ export type AuditLogWhereUniqueInput = Prisma.AtLeast<{
agentId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
projectId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
itemId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
via?: Prisma.StringNullableFilter<"AuditLog"> | string | null
createdAt?: Prisma.DateTimeFilter<"AuditLog"> | Date | string
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
user?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
@@ -255,6 +265,7 @@ export type AuditLogOrderByWithAggregationInput = {
agentId?: Prisma.SortOrderInput | Prisma.SortOrder
projectId?: Prisma.SortOrderInput | Prisma.SortOrder
itemId?: Prisma.SortOrderInput | Prisma.SortOrder
via?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder
_count?: Prisma.AuditLogCountOrderByAggregateInput
_max?: Prisma.AuditLogMaxOrderByAggregateInput
@@ -272,6 +283,7 @@ export type AuditLogScalarWhereWithAggregatesInput = {
agentId?: Prisma.StringNullableWithAggregatesFilter<"AuditLog"> | string | null
projectId?: Prisma.StringNullableWithAggregatesFilter<"AuditLog"> | string | null
itemId?: Prisma.StringNullableWithAggregatesFilter<"AuditLog"> | string | null
via?: Prisma.StringNullableWithAggregatesFilter<"AuditLog"> | string | null
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AuditLog"> | Date | string
}
@@ -279,6 +291,7 @@ export type AuditLogCreateInput = {
id?: string
action: string
itemId?: string | null
via?: string | null
createdAt?: Date | string
team: Prisma.TeamCreateNestedOneWithoutAuditLogsInput
user?: Prisma.UserCreateNestedOneWithoutAuditLogsInput
@@ -294,6 +307,7 @@ export type AuditLogUncheckedCreateInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -301,6 +315,7 @@ export type AuditLogUpdateInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
team?: Prisma.TeamUpdateOneRequiredWithoutAuditLogsNestedInput
user?: Prisma.UserUpdateOneWithoutAuditLogsNestedInput
@@ -316,6 +331,7 @@ export type AuditLogUncheckedUpdateInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -327,6 +343,7 @@ export type AuditLogCreateManyInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -334,6 +351,7 @@ export type AuditLogUpdateManyMutationInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -345,6 +363,7 @@ export type AuditLogUncheckedUpdateManyInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -366,6 +385,7 @@ export type AuditLogCountOrderByAggregateInput = {
agentId?: Prisma.SortOrder
projectId?: Prisma.SortOrder
itemId?: Prisma.SortOrder
via?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
}
@@ -377,6 +397,7 @@ export type AuditLogMaxOrderByAggregateInput = {
agentId?: Prisma.SortOrder
projectId?: Prisma.SortOrder
itemId?: Prisma.SortOrder
via?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
}
@@ -388,6 +409,7 @@ export type AuditLogMinOrderByAggregateInput = {
agentId?: Prisma.SortOrder
projectId?: Prisma.SortOrder
itemId?: Prisma.SortOrder
via?: Prisma.SortOrder
createdAt?: Prisma.SortOrder
}
@@ -563,6 +585,7 @@ export type AuditLogCreateWithoutUserInput = {
id?: string
action: string
itemId?: string | null
via?: string | null
createdAt?: Date | string
team: Prisma.TeamCreateNestedOneWithoutAuditLogsInput
agent?: Prisma.AgentCreateNestedOneWithoutAuditLogsInput
@@ -576,6 +599,7 @@ export type AuditLogUncheckedCreateWithoutUserInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -616,6 +640,7 @@ export type AuditLogScalarWhereInput = {
agentId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
projectId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
itemId?: Prisma.StringNullableFilter<"AuditLog"> | string | null
via?: Prisma.StringNullableFilter<"AuditLog"> | string | null
createdAt?: Prisma.DateTimeFilter<"AuditLog"> | Date | string
}
@@ -623,6 +648,7 @@ export type AuditLogCreateWithoutTeamInput = {
id?: string
action: string
itemId?: string | null
via?: string | null
createdAt?: Date | string
user?: Prisma.UserCreateNestedOneWithoutAuditLogsInput
agent?: Prisma.AgentCreateNestedOneWithoutAuditLogsInput
@@ -636,6 +662,7 @@ export type AuditLogUncheckedCreateWithoutTeamInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -669,6 +696,7 @@ export type AuditLogCreateWithoutProjectInput = {
id?: string
action: string
itemId?: string | null
via?: string | null
createdAt?: Date | string
team: Prisma.TeamCreateNestedOneWithoutAuditLogsInput
user?: Prisma.UserCreateNestedOneWithoutAuditLogsInput
@@ -682,6 +710,7 @@ export type AuditLogUncheckedCreateWithoutProjectInput = {
userId?: string | null
agentId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -715,6 +744,7 @@ export type AuditLogCreateWithoutAgentInput = {
id?: string
action: string
itemId?: string | null
via?: string | null
createdAt?: Date | string
team: Prisma.TeamCreateNestedOneWithoutAuditLogsInput
user?: Prisma.UserCreateNestedOneWithoutAuditLogsInput
@@ -728,6 +758,7 @@ export type AuditLogUncheckedCreateWithoutAgentInput = {
userId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -764,6 +795,7 @@ export type AuditLogCreateManyUserInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -771,6 +803,7 @@ export type AuditLogUpdateWithoutUserInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
team?: Prisma.TeamUpdateOneRequiredWithoutAuditLogsNestedInput
agent?: Prisma.AgentUpdateOneWithoutAuditLogsNestedInput
@@ -784,6 +817,7 @@ export type AuditLogUncheckedUpdateWithoutUserInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -794,6 +828,7 @@ export type AuditLogUncheckedUpdateManyWithoutUserInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -804,6 +839,7 @@ export type AuditLogCreateManyTeamInput = {
agentId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -811,6 +847,7 @@ export type AuditLogUpdateWithoutTeamInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
user?: Prisma.UserUpdateOneWithoutAuditLogsNestedInput
agent?: Prisma.AgentUpdateOneWithoutAuditLogsNestedInput
@@ -824,6 +861,7 @@ export type AuditLogUncheckedUpdateWithoutTeamInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -834,6 +872,7 @@ export type AuditLogUncheckedUpdateManyWithoutTeamInput = {
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -844,6 +883,7 @@ export type AuditLogCreateManyProjectInput = {
userId?: string | null
agentId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -851,6 +891,7 @@ export type AuditLogUpdateWithoutProjectInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
team?: Prisma.TeamUpdateOneRequiredWithoutAuditLogsNestedInput
user?: Prisma.UserUpdateOneWithoutAuditLogsNestedInput
@@ -864,6 +905,7 @@ export type AuditLogUncheckedUpdateWithoutProjectInput = {
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -874,6 +916,7 @@ export type AuditLogUncheckedUpdateManyWithoutProjectInput = {
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
agentId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -884,6 +927,7 @@ export type AuditLogCreateManyAgentInput = {
userId?: string | null
projectId?: string | null
itemId?: string | null
via?: string | null
createdAt?: Date | string
}
@@ -891,6 +935,7 @@ export type AuditLogUpdateWithoutAgentInput = {
id?: Prisma.StringFieldUpdateOperationsInput | string
action?: Prisma.StringFieldUpdateOperationsInput | string
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
team?: Prisma.TeamUpdateOneRequiredWithoutAuditLogsNestedInput
user?: Prisma.UserUpdateOneWithoutAuditLogsNestedInput
@@ -904,6 +949,7 @@ export type AuditLogUncheckedUpdateWithoutAgentInput = {
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -914,6 +960,7 @@ export type AuditLogUncheckedUpdateManyWithoutAgentInput = {
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
projectId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
itemId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
via?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
}
@@ -927,6 +974,7 @@ export type AuditLogSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs
agentId?: boolean
projectId?: boolean
itemId?: boolean
via?: boolean
createdAt?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
user?: boolean | Prisma.AuditLog$userArgs<ExtArgs>
@@ -942,6 +990,7 @@ export type AuditLogSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Exte
agentId?: boolean
projectId?: boolean
itemId?: boolean
via?: boolean
createdAt?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
user?: boolean | Prisma.AuditLog$userArgs<ExtArgs>
@@ -957,6 +1006,7 @@ export type AuditLogSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Exte
agentId?: boolean
projectId?: boolean
itemId?: boolean
via?: boolean
createdAt?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
user?: boolean | Prisma.AuditLog$userArgs<ExtArgs>
@@ -972,10 +1022,11 @@ export type AuditLogSelectScalar = {
agentId?: boolean
projectId?: boolean
itemId?: boolean
via?: boolean
createdAt?: boolean
}
export type AuditLogOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "action" | "teamId" | "userId" | "agentId" | "projectId" | "itemId" | "createdAt", ExtArgs["result"]["auditLog"]>
export type AuditLogOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "action" | "teamId" | "userId" | "agentId" | "projectId" | "itemId" | "via" | "createdAt", ExtArgs["result"]["auditLog"]>
export type AuditLogInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
user?: boolean | Prisma.AuditLog$userArgs<ExtArgs>
@@ -1011,6 +1062,10 @@ export type $AuditLogPayload<ExtArgs extends runtime.Types.Extensions.InternalAr
agentId: string | null
projectId: string | null
itemId: string | null
/**
* Surface the action came through: api, agent, mcp, or cli. Null for actions recorded outside Operations.
*/
via: string | null
createdAt: Date
}, ExtArgs["result"]["auditLog"]>
composites: {}
@@ -1446,6 +1501,7 @@ export interface AuditLogFieldRefs {
readonly agentId: Prisma.FieldRef<"AuditLog", 'String'>
readonly projectId: Prisma.FieldRef<"AuditLog", 'String'>
readonly itemId: Prisma.FieldRef<"AuditLog", 'String'>
readonly via: Prisma.FieldRef<"AuditLog", 'String'>
readonly createdAt: Prisma.FieldRef<"AuditLog", 'DateTime'>
}
@@ -0,0 +1,213 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
import { initAgentWorkflows } from '@shumai/agent'
import { s3Service } from '@shumai/core/src/s3/s3'
import { projectService } from '@shumai/core/src/project/project'
import { AgentHarness } from '@earendil-works/pi-agent-core'
type ToolResult = { content: Array<{ type: string; text?: string }> }
type ExecutableTool = {
execute: (id: string, params: Record<string, unknown>) => Promise<ToolResult>
}
const toolText = (result: ToolResult) =>
result.content.map((c) => (typeof c.text === 'string' ? c.text : '')).join('\n')
/**
* Exercises the Operation-backed agent tools through the real chat workflow:
* createAgentSession → buildOperationTools → runOperation → core services → DB.
* Only the model call is mocked; it invokes the tools the way a model would.
*/
describe('Workflow E2E - agent Operation tools', () => {
setupTestDbHooks()
let rootFolderId = ''
beforeAll(async () => {
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-agent-ops'
process.env.GEMINI_API_KEY = 'dummy-key'
initAgentWorkflows()
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
this: AgentHarness,
) {
const tool = (name: string) =>
this.getTools().find((t) => t.name === name) as unknown as ExecutableTool | undefined
const createFolder = tool('create_folder')
const listAssets = tool('list_assets')
const deleteAsset = tool('delete_asset')
if (!createFolder || !listAssets) {
return {
content: [{ type: 'text', text: 'MISSING_OPERATION_TOOLS' }],
usage: { input: 1, output: 1 },
stopReason: 'stop',
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
}
const created = JSON.parse(
toolText(
await createFolder.execute('call-1', { parent: rootFolderId, name: 'Agent Folder' }),
),
) as { id: string }
const listed = JSON.parse(
toolText(await listAssets.execute('call-2', { parent: rootFolderId, type: null })),
) as { data: Array<{ id: string; name: string }> }
const summary = [
`created:${created.id}`,
`listed:${listed.data.map((a) => a.name).join(',')}`,
// delete_asset is denied by default and must not be registered
`delete_tool:${deleteAsset ? 'present' : 'absent'}`,
].join('|')
return {
content: [{ type: 'text', text: summary }],
usage: { input: 10, output: 20 },
stopReason: 'stop',
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
})
await workflowService.startWorkers(TaskQueueAgent)
})
afterAll(async () => {
await workflowService.shutdownWorkers()
workflowService.close()
vi.restoreAllMocks()
try {
await s3Service.deletePrefix('shumai-e2e-test-bucket-agent-ops', '')
} catch (err) {
console.error('Failed to clean up E2E storage folder:', err)
}
})
it('creates and lists assets through Operations, attributed to the user and agent', async () => {
const team = await prisma.team.create({ data: { name: 'E2E Agent Ops Team' } })
const regularUser = await prisma.user.create({
data: { name: 'Ops User', email: 'ops-user@example.com', type: 'human' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: regularUser.id, role: 'owner' },
})
const project = await projectService.createProject(regularUser, {
teamId: team.id,
name: 'E2E Agent Ops Project',
})
rootFolderId = project.rootFolder!
const agentUser = await prisma.user.create({
data: { name: 'E2E Ops Agent', email: 'e2e-ops-agent@shumai.ai', type: 'agent' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: agentUser.id, role: 'editor' },
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 8192,
maxTokens: 2048,
reasoning: false,
},
},
})
await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
await prisma.agentSession.create({
data: {
id: 'agent-ops-session',
agentId: agentUser.id,
userId: regularUser.id,
cwd: process.cwd(),
},
})
const asset = await prisma.asset.create({
data: {
name: 'brief.png',
type: 'file',
status: 'uploaded',
mediaType: 'image/png',
projectId: project.id,
parentId: rootFolderId,
},
})
const userComment = await prisma.assetComment.create({
data: {
assetId: asset.id,
message: 'Create a folder called Agent Folder and list the root',
creatorId: regularUser.id,
sessionId: 'agent-ops-session',
},
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: asset.id,
projectId: project.id,
teamId: team.id,
payload: {
projectId: project.id,
agent: {
agentId: agentUser.id,
sessionId: 'agent-ops-session',
userCommentId: userComment.id,
userId: regularUser.id,
},
},
},
})
const completedTask = await workflowService.executeWait(task, 45000)
expect(completedTask.status).toBe('completed')
const folder = await prisma.asset.findFirstOrThrow({
where: { name: 'Agent Folder', parentId: rootFolderId },
})
expect(folder.type).toBe('folder')
expect(folder.creatorId).toBe(regularUser.id)
expect(folder.agentId).toBe(agentUser.id)
const audit = await prisma.auditLog.findFirstOrThrow({
where: { action: 'folder_create', itemId: folder.id },
})
expect(audit).toMatchObject({
teamId: team.id,
projectId: project.id,
userId: regularUser.id,
agentId: agentUser.id,
via: 'agent',
})
const [reply] = await prisma.assetComment.findMany({
where: { assetId: asset.id, replyToId: userComment.id },
})
expect(reply?.message).toContain(`created:${folder.id}`)
expect(reply?.message).toMatch(/listed:.*Agent Folder/)
expect(reply?.message).toContain('delete_tool:absent')
}, 50000)
})
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@shumai/operations",
"version": "0.6.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"dependencies": {
"zod": "4.5.4"
}
}
@@ -0,0 +1,25 @@
import { z } from 'zod'
import { defineOperation } from '../define'
import { assetSummarySchema } from '../schemas'
export const createFolder = defineOperation({
name: 'create_folder',
title: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
input: z.object({
parent: z
.string()
.min(1)
.describe('The parent folder ID under which to create the new folder.'),
name: z.string().min(1).describe('The name of the new folder to create.'),
}),
output: assetSummarySchema,
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false },
cli: {
command: ['mkdir'],
positional: ['name'],
flags: { parent: ['-p', '--parent'] },
format: (output) => `Created folder with ID: ${output.id}`,
},
})
@@ -0,0 +1,24 @@
import { z } from 'zod'
import { defineOperation } from '../define'
export const deleteAsset = defineOperation({
name: 'delete_asset',
title: 'Delete Asset',
description:
'Delete a single asset (file or folder) by its ID. Can only delete one asset at a time. ' +
'Deleted assets are moved to the project trash.',
input: z.object({
assetId: z.string().min(1).describe('The ID of the single asset (file or folder) to delete.'),
}),
output: z.object({
deletedAssetId: z.string(),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: true },
cli: {
command: ['delete'],
aliases: ['rm'],
positional: ['assetId'],
format: (output) => `Deleted asset ${output.deletedAssetId}`,
},
})
@@ -0,0 +1,40 @@
import { z } from 'zod'
import { defineOperation } from '../define'
import { assetSummarySchema, MAX_PAGE_SIZE, pageInfoSchema } from '../schemas'
export const listAssets = defineOperation({
name: 'list_assets',
title: 'List Assets',
description:
'List the assets (files and folders) inside a parent folder. Results are paginated: when ' +
'pageInfo.hasNextPage is true, call again with after set to pageInfo.endCursor.',
input: z.object({
parent: z.string().min(1).describe('The parent folder ID to list assets from.'),
type: z
.enum(['file', 'folder', 'all'])
.optional()
.describe("Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'."),
first: z
.number()
.int()
.min(1)
.max(MAX_PAGE_SIZE)
.optional()
.describe(`Maximum number of assets to return. Default is 20, maximum ${MAX_PAGE_SIZE}.`),
after: z
.string()
.optional()
.describe('Cursor from a previous response (pageInfo.endCursor) to fetch the next page.'),
}),
output: z.object({
data: z.array(assetSummarySchema),
pageInfo: pageInfoSchema,
total: z.number(),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: true, destructive: false, idempotent: true },
cli: {
command: ['ls'],
flags: { parent: ['-p', '--parent'] },
},
})
@@ -0,0 +1,36 @@
import { z } from 'zod'
import { defineOperation } from '../define'
export const moveAssets = defineOperation({
name: 'move_assets',
title: 'Move Assets',
description:
'Move one or more assets (files or folders) to a specified parent folder. Note: All assets ' +
'to be moved must belong to the same current parent folder.',
input: z.object({
assetIds: z
.array(z.string().min(1))
.min(1)
.describe(
'The IDs of the assets to move. All assets must belong to the same parent folder. At least one asset ID is required.',
),
newParentId: z
.string()
.min(1)
.describe('The destination parent folder ID to move the assets into.'),
}),
output: z.object({
movedAssetIds: z.array(z.string()),
newParentId: z.string(),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false, idempotent: true },
cli: {
command: ['move'],
aliases: ['mv'],
positional: ['assetIds'],
flags: { newParentId: ['-p', '--parent'] },
format: (output) =>
`Moved ${output.movedAssetIds.length} asset(s) to parent ${output.newParentId}`,
},
})
@@ -0,0 +1,21 @@
import { z } from 'zod'
import { defineOperation } from '../define'
import { assetSummarySchema } from '../schemas'
export const renameAsset = defineOperation({
name: 'rename_asset',
title: 'Rename Asset',
description: 'Rename an existing asset (file or folder).',
input: z.object({
assetId: z.string().min(1).describe('The ID of the asset (file or folder) to rename.'),
name: z.string().min(1).describe('The new name for the asset.'),
}),
output: assetSummarySchema,
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: false, destructive: false, idempotent: true },
cli: {
command: ['rename'],
positional: ['assetId', 'name'],
format: (output) => `Renamed asset ${output.id} to "${output.name}"`,
},
})
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import { defineOperation, type OperationDefinition } from './define'
function baseDefinition(): OperationDefinition<string, z.ZodObject<{ id: z.ZodString }>> {
return {
name: 'get_thing',
title: 'Get Thing',
description: 'Get a thing by ID.',
input: z.object({ id: z.string() }),
output: z.object({ id: z.string() }),
surfaces: ['agent', 'mcp'],
annotations: { readOnly: true, destructive: false },
}
}
describe('defineOperation', () => {
it('returns a frozen definition', () => {
const def = defineOperation(baseDefinition())
expect(def.name).toBe('get_thing')
expect(Object.isFrozen(def)).toBe(true)
})
it.each(['GetThing', 'get-thing', 'get thing', '_get', 'get__thing', '1get', 'get_'])(
'rejects non snake_case name %s',
(name) => {
expect(() => defineOperation({ ...baseDefinition(), name })).toThrow('expected snake_case')
},
)
it('requires a title and description', () => {
expect(() => defineOperation({ ...baseDefinition(), title: ' ' })).toThrow(
'must have a title and a description',
)
expect(() => defineOperation({ ...baseDefinition(), description: '' })).toThrow(
'must have a title and a description',
)
})
it('rejects empty or duplicated surfaces', () => {
expect(() => defineOperation({ ...baseDefinition(), surfaces: [] })).toThrow('each surface')
expect(() => defineOperation({ ...baseDefinition(), surfaces: ['agent', 'agent'] })).toThrow(
'each surface',
)
})
it('rejects contradictory annotations', () => {
expect(() =>
defineOperation({
...baseDefinition(),
annotations: { readOnly: true, destructive: true },
}),
).toThrow('cannot be both readOnly and destructive')
})
it('requires a cli spec for the cli surface', () => {
expect(() => defineOperation({ ...baseDefinition(), surfaces: ['cli'] })).toThrow('no cli spec')
})
it('rejects cli specs that reference unknown input fields', () => {
expect(() =>
defineOperation({
...baseDefinition(),
surfaces: ['cli'],
// Cast simulates a definition built without type checking (e.g. from JS)
cli: { command: ['get'], positional: ['missing' as 'id'] },
}),
).toThrow('unknown input "missing"')
expect(() =>
defineOperation({
...baseDefinition(),
surfaces: ['cli'],
cli: { command: ['get'], flags: { ['other' as 'id']: ['-o'] } },
}),
).toThrow('unknown input "other"')
})
})
+104
View File
@@ -0,0 +1,104 @@
import type { z } from 'zod'
/**
* Channels through which an Operation can be invoked by an agent.
*
* - `agent`: native tool of Shumai's built-in agent
* - `mcp`: tool on Shumai's MCP server
* - `cli`: command of `shumai-cli` (served by `POST /api/ops/:name`)
*
* REST routes are not a surface: they call Operations explicitly.
*/
export const SURFACES = ['agent', 'mcp', 'cli'] as const
export type Surface = (typeof SURFACES)[number]
/** Where an invocation came from: one of the surfaces, or a REST route (`api`). Recorded in audit logs. */
export type Via = Surface | 'api'
/** Behavioral hints, mapped to MCP tool annotations and surface-specific safety gates. */
export interface OperationAnnotations {
/** The Operation does not modify any state. */
readOnly: boolean
/** The Operation may irreversibly remove data (e.g. delete). */
destructive: boolean
/** Repeating the call with the same input has no additional effect. */
idempotent?: boolean
}
/** How an Operation is exposed as a `shumai-cli` command. */
export interface CliSpec<TInput, TOutput> {
/** Command path, e.g. `['mkdir']` or `['project', 'ls']`. */
command: readonly string[]
/** Alternative names for the last command segment, e.g. `['mv']`. */
aliases?: readonly string[]
/** Input fields taken from positional arguments, in order. An array field must be last (variadic). */
positional?: readonly (keyof TInput & string)[]
/** Flag spellings for input fields, e.g. `{ parent: ['-p', '--parent'] }`. */
flags?: { readonly [K in keyof TInput & string]?: readonly string[] }
/** Human-friendly rendering of the output; the CLI falls back to a generic renderer. */
format?(output: TOutput): string
}
/**
* A single capability exposed to agents, defined once and shared by every surface.
*
* Definitions are pure metadata and schemas: they must not depend on server code so
* that clients such as the CLI can import them. Implementations live in
* `@shumai/core/src/operations`.
*/
export interface OperationDefinition<
TName extends string = string,
TInput extends z.ZodObject = z.ZodObject,
TOutput extends z.ZodType = z.ZodType,
> {
/** Unique snake_case name, used as the agent/MCP tool name and the `/api/ops/:name` path. */
readonly name: TName
/** Short human-readable label. */
readonly title: string
/** What the Operation does, written for an LLM choosing between tools. */
readonly description: string
readonly input: TInput
readonly output: TOutput
readonly surfaces: readonly Surface[]
readonly annotations: OperationAnnotations
readonly cli?: CliSpec<z.input<TInput>, z.output<TOutput>>
}
export type AnyOperationDefinition = OperationDefinition<string, z.ZodObject, z.ZodType>
const NAME_PATTERN = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/
/**
* Define an Operation. Validates the metadata eagerly so mistakes fail at import time.
*/
export function defineOperation<
const TName extends string,
TInput extends z.ZodObject,
TOutput extends z.ZodType,
>(def: OperationDefinition<TName, TInput, TOutput>): OperationDefinition<TName, TInput, TOutput> {
if (!NAME_PATTERN.test(def.name)) {
throw new Error(`Invalid operation name "${def.name}": expected snake_case`)
}
if (!def.title.trim() || !def.description.trim()) {
throw new Error(`Operation "${def.name}" must have a title and a description`)
}
if (def.surfaces.length === 0 || new Set(def.surfaces).size !== def.surfaces.length) {
throw new Error(`Operation "${def.name}" must list each surface at most once`)
}
if (def.annotations.readOnly && def.annotations.destructive) {
throw new Error(`Operation "${def.name}" cannot be both readOnly and destructive`)
}
if (def.surfaces.includes('cli') && !def.cli) {
throw new Error(`Operation "${def.name}" has the cli surface but no cli spec`)
}
if (def.cli) {
const fields = new Set(Object.keys(def.input.shape))
const referenced = [...(def.cli.positional ?? []), ...Object.keys(def.cli.flags ?? {})]
for (const field of referenced) {
if (!fields.has(field)) {
throw new Error(`Operation "${def.name}" cli spec references unknown input "${field}"`)
}
}
}
return Object.freeze(def)
}
+9
View File
@@ -0,0 +1,9 @@
export * from './define'
export * from './schemas'
export * from './registry'
export { createFolder } from './asset/create-folder'
export { deleteAsset } from './asset/delete-asset'
export { listAssets } from './asset/list-assets'
export { moveAssets } from './asset/move-assets'
export { renameAsset } from './asset/rename-asset'
export { listProjects } from './project/list-projects'
@@ -0,0 +1,28 @@
import { z } from 'zod'
import { defineOperation } from '../define'
import { MAX_PAGE_SIZE, projectSummarySchema } from '../schemas'
export const listProjects = defineOperation({
name: 'list_projects',
title: 'List Projects',
description:
'List the projects the user can access across all of their teams, newest first. ' +
"Use a project's rootFolderId as the parent for asset operations.",
input: z.object({
first: z
.number()
.int()
.min(1)
.max(MAX_PAGE_SIZE)
.optional()
.describe(`Maximum number of projects to return. Default and maximum is ${MAX_PAGE_SIZE}.`),
}),
output: z.object({
data: z.array(projectSummarySchema),
}),
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: true, destructive: false, idempotent: true },
cli: {
command: ['project', 'ls'],
},
})
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
import {
getOperationDefinition,
getOperationDefinitionsForSurface,
operationDefinitions,
} from './registry'
describe('operation registry', () => {
it('has unique names', () => {
const names = operationDefinitions.map((d) => d.name)
expect(new Set(names).size).toBe(names.length)
})
it('contains the initial asset and project operations', () => {
expect(operationDefinitions.map((d) => d.name).sort()).toEqual([
'create_folder',
'delete_asset',
'list_assets',
'list_projects',
'move_assets',
'rename_asset',
])
})
it('looks up definitions by name', () => {
expect(getOperationDefinition('create_folder')?.title).toBe('Create Folder')
expect(getOperationDefinition('nope')).toBeUndefined()
})
it('filters definitions by surface', () => {
const cli = getOperationDefinitionsForSurface('cli').map((d) => d.name)
expect(cli).toContain('list_assets')
})
it('annotates only delete_asset as destructive', () => {
const destructive = operationDefinitions.filter((d) => d.annotations.destructive)
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(['list_assets', 'list_projects'])
})
it.each(operationDefinitions.map((d) => [d.name, d] as const))(
'%s exports an object JSON Schema with described fields',
(_name, definition) => {
const schema = z.toJSONSchema(definition.input, { io: 'input' }) as {
type: string
properties: Record<string, { description?: string }>
}
expect(schema.type).toBe('object')
for (const [field, property] of Object.entries(schema.properties)) {
expect(property.description, `${definition.name}.${field}`).toBeTruthy()
}
// Output schemas must also be representable (used as MCP outputSchema)
expect(() => z.toJSONSchema(definition.output, { io: 'output' })).not.toThrow()
},
)
it('keeps legacy CLI invocations mapped', () => {
const commands = operationDefinitions.map((d) => [
d.name,
[...(d.cli?.command ?? []), ...(d.cli?.aliases ?? [])],
])
expect(commands).toEqual([
['list_projects', ['project', 'ls']],
['list_assets', ['ls']],
['create_folder', ['mkdir']],
['rename_asset', ['rename']],
['move_assets', ['move', 'mv']],
['delete_asset', ['delete', 'rm']],
])
})
it('does not depend on server packages', () => {
const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as {
dependencies?: Record<string, string>
}
const deps = Object.keys(pkg.dependencies ?? {})
expect(deps).not.toContain('@shumai/core')
expect(deps).not.toContain('@shumai/db')
expect(deps).not.toContain('@shumai/api')
})
})
+43
View File
@@ -0,0 +1,43 @@
import { createFolder } from './asset/create-folder'
import { deleteAsset } from './asset/delete-asset'
import { listAssets } from './asset/list-assets'
import { moveAssets } from './asset/move-assets'
import { renameAsset } from './asset/rename-asset'
import type { AnyOperationDefinition, Surface } from './define'
import { listProjects } from './project/list-projects'
/**
* Every Operation definition. Adding one here requires a matching implementation in
* `@shumai/core/src/operations/registry.ts` (enforced by the type checker).
*/
export const operationDefinitions = [
listProjects,
listAssets,
createFolder,
renameAsset,
moveAssets,
deleteAsset,
] as const
export type RegisteredOperationDefinition = (typeof operationDefinitions)[number]
export type OperationName = RegisteredOperationDefinition['name']
export type OperationDefinitionByName<TName extends OperationName> = Extract<
RegisteredOperationDefinition,
{ name: TName }
>
const definitionsByName = new Map<string, AnyOperationDefinition>()
for (const definition of operationDefinitions) {
if (definitionsByName.has(definition.name)) {
throw new Error(`Duplicate operation name "${definition.name}"`)
}
definitionsByName.set(definition.name, definition)
}
export function getOperationDefinition(name: string): AnyOperationDefinition | undefined {
return definitionsByName.get(name)
}
export function getOperationDefinitionsForSurface(surface: Surface): AnyOperationDefinition[] {
return operationDefinitions.filter((definition) => definition.surfaces.includes(surface))
}
+33
View File
@@ -0,0 +1,33 @@
import { z } from 'zod'
/** Compact asset representation returned by asset Operations. */
export const assetSummarySchema = z.object({
id: z.string(),
name: z.string(),
/** `file`, `folder`, `version_stack`, or `symlink`. */
type: z.string(),
/** Size in bytes. */
size: z.number(),
projectId: z.string().nullable(),
})
export type AssetSummary = z.infer<typeof assetSummarySchema>
/** Cursor pagination metadata. Pass `endCursor` as `after` to fetch the next page. */
export const pageInfoSchema = z.object({
hasNextPage: z.boolean(),
endCursor: z.string().nullable(),
})
export type PageInfo = z.infer<typeof pageInfoSchema>
export const projectSummarySchema = z.object({
id: z.string(),
name: z.string(),
teamId: z.string(),
/** The project's root folder; use it as the parent for asset Operations. */
rootFolderId: z.string().nullable(),
})
export type ProjectSummary = z.infer<typeof projectSummarySchema>
/** Page size bounds shared by list Operations (matches `paginateQuery`). */
export const DEFAULT_PAGE_SIZE = 20
export const MAX_PAGE_SIZE = 200
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}
+2
View File
@@ -20,6 +20,8 @@
"@shumai/db/enums": ["./packages/db/src/generated/prisma/enums.ts"],
"@shumai/db/test": ["./packages/db/src/test.ts"],
"@shumai/dtos": ["./packages/dtos/src/index.ts"],
"@shumai/operations": ["./packages/operations/src/index.ts"],
"@shumai/operations/src/*": ["./packages/operations/src/*"],
"@shumai/workflow-core": ["./packages/workflow-core/src/index.ts"],
"@shumai/workflow-core/src/*": ["./packages/workflow-core/src/*"],
"@shumai/agent": ["./packages/agent/src/index.ts"],