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
@@ -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