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

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
2026-10-26 11:36:36 +08:00
parent 47ee794ae4
commit 028fae0286
65 changed files with 2372 additions and 1149 deletions
+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)
},
)