mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 23:49:26 +00:00
feat: move MCP to /mcp and add teammate operations (#500)
* feat(operations): move MCP to /mcp and add search, comment, metadata, version, and upload operations - Serve the MCP server at /mcp instead of /api/mcp - Add search_assets, copy_assets, get_folder_instructions, list_comments, create_comment, resolve_comment, list_metadata_fields, update_asset_metadata, create_version_stack, list_versions, and remove_version on the agent, MCP, and CLI - Add create_file and create_version (agent, MCP) with Creation Context metadata, and complete_upload (MCP) for presigned two-step uploads - Replace the native agent create_file/create_version tools with Operation-backed ones - Route the comment-complete, metadata, copy, version stack, and AGENTS.md read REST endpoints through their Operations * docs(readme): add built-in MCP server and CLI to features list
This commit is contained in:
@@ -471,6 +471,7 @@ describe('DatabaseSessionStorage', () => {
|
||||
// 4. Assert that the tools were built for the user
|
||||
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: user.id }),
|
||||
expect.objectContaining({}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -525,6 +526,7 @@ describe('DatabaseSessionStorage', () => {
|
||||
// 4. Assert that the tools were built for the user
|
||||
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: user.id }),
|
||||
expect.objectContaining({}),
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -18,8 +18,6 @@ import * as fs from 'fs'
|
||||
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 { createCreateVersionTool } from './tools/create-version'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
@@ -332,14 +330,11 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
|
||||
const systemTools: AgentTool[] = []
|
||||
if (userId) {
|
||||
const metadataSchema = await buildProjectMetadataSchema(projectId)
|
||||
const agentContext = { teamId, agentId }
|
||||
const creationMetadataSchema = await buildProjectMetadataSchema(projectId)
|
||||
systemTools.push(
|
||||
// Shared Operations (also exposed via MCP and the CLI): list/create/rename/move/delete,
|
||||
// read_asset, get_asset_render, and download_asset
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }),
|
||||
createCreateFileTool(userId, metadataSchema, agentContext),
|
||||
createCreateVersionTool(userId, metadataSchema, agentContext),
|
||||
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
|
||||
// reading and downloading assets, creating files and versions, comments and metadata
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// Registers agent-specific presentation for Operations. Import once before building tools.
|
||||
export { createAutofillReadAssetTool, presentReadOutput } from './read-asset'
|
||||
export { presentDownloadOutput } from './download-asset'
|
||||
import './upload'
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Value } from 'typebox/value'
|
||||
import { validateToolArguments } from '@earendil-works/pi-ai'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { AuditAction, type AssetInfo } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { toAgentTool, type AgentToolOptions } from '../operation-tools'
|
||||
import './upload'
|
||||
|
||||
const ctx = { userId: 'user-1', agentId: 'agent-1', teamId: 'team-1', projectId: 'proj-1' }
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
function tool(name: 'create_file' | 'create_version', options: AgentToolOptions = {}) {
|
||||
return toAgentTool(getOperation(name)!, ctx, options)
|
||||
}
|
||||
|
||||
function assetInfo(overrides: Partial<AssetInfo>): AssetInfo {
|
||||
return {
|
||||
id: 'file-1',
|
||||
name: 'test',
|
||||
sizeByte: 100,
|
||||
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 outputOf(result: { content: unknown[] }) {
|
||||
return JSON.parse((result.content[0] as { text: string }).text) as unknown
|
||||
}
|
||||
|
||||
const promptField = {
|
||||
field: {
|
||||
id: 'f1',
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
readOnly: false,
|
||||
description: '',
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
visible: true,
|
||||
}
|
||||
|
||||
describe('create_file and create_version agent tools', () => {
|
||||
const tempFiles: string[] = []
|
||||
const tempFile = (content: string, filename: string): string => {
|
||||
const filePath = path.join(os.tmpdir(), filename)
|
||||
fs.writeFileSync(filePath, content)
|
||||
tempFiles.push(filePath)
|
||||
return filePath
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
vi.spyOn(auditLogService, 'logAction').mockResolvedValue(null)
|
||||
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
vi.spyOn(assetService, 'getAssetMeta').mockImplementation(async (id) => ({
|
||||
id,
|
||||
name: id,
|
||||
type: id.startsWith('folder') ? 'folder' : 'file',
|
||||
parentId: 'root',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
}))
|
||||
vi.spyOn(assetService, 'findAssetByStorageKey').mockResolvedValue(null)
|
||||
vi.spyOn(assetService, 'createFile').mockResolvedValue(assetInfo({}))
|
||||
vi.spyOn(assetService, 'createVersion').mockResolvedValue(assetInfo({ name: 'v2' }))
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([promptField] as never)
|
||||
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://storage.example/upload')
|
||||
// Read file streams to the end, as real storage would.
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(async (_bucket, _key, body) => {
|
||||
if (body && typeof body === 'object' && Symbol.asyncIterator in body) {
|
||||
for await (const chunk of body as AsyncIterable<unknown>) void chunk
|
||||
}
|
||||
})
|
||||
vi.spyOn(s3Service, 'headObject').mockImplementation(async (_bucket, key) => ({
|
||||
key,
|
||||
size: 17,
|
||||
lastModified: new Date(),
|
||||
contentType: 'text/markdown',
|
||||
eTag: '',
|
||||
}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const f of tempFiles.splice(0)) fs.rmSync(f, { force: true })
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('uploads a local file to storage and creates the file as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-file.md')
|
||||
|
||||
const result = await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
} as never)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'folder-1',
|
||||
})
|
||||
const [putBucket, key, , size, contentType] = vi.mocked(s3Service.putObject).mock.calls[0]
|
||||
expect(putBucket).toBe(bucket)
|
||||
expect(key).toMatch(/^files\/.+\/agent-create-file\.md$/)
|
||||
expect(size).toBe(Buffer.byteLength('# Hello from disk'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'agent-create-file.md',
|
||||
key,
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: AuditAction.file_create,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
userId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
itemId: 'file-1',
|
||||
via: 'agent',
|
||||
}),
|
||||
)
|
||||
expect(result.details).toEqual({})
|
||||
expect(outputOf(result)).toEqual({
|
||||
id: 'file-1',
|
||||
name: 'test',
|
||||
type: 'file',
|
||||
size: 100,
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('creates a text file from name and content', async () => {
|
||||
await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
name: 'notes.md',
|
||||
content: '# Notes\n\nHello',
|
||||
} as never)
|
||||
|
||||
const [, key, body, size, contentType] = vi.mocked(s3Service.putObject).mock.calls[0]
|
||||
expect(key).toMatch(/^files\/.+\/notes\.md$/)
|
||||
expect((body as Buffer).toString('utf-8')).toBe('# Notes\n\nHello')
|
||||
expect(size).toBe(Buffer.byteLength('# Notes\n\nHello'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'notes.md', contentType: 'text/markdown' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('defaults unknown extensions to text/plain when creating from content', async () => {
|
||||
await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
name: 'script.ts',
|
||||
content: 'const x = 1',
|
||||
} as never)
|
||||
|
||||
expect(vi.mocked(s3Service.putObject).mock.calls[0][4]).toBe('text/plain')
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ contentType: 'text/plain' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('sanitizes the name', async () => {
|
||||
await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
name: 'my/notes.md',
|
||||
content: 'hello',
|
||||
} as never)
|
||||
|
||||
expect(vi.mocked(s3Service.putObject).mock.calls[0][1]).toContain('my_notes.md')
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'my_notes.md' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata, including new select options', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-meta.md')
|
||||
|
||||
await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
metadata: { prompt: { newOption: { value: 'Kling' } } },
|
||||
} as never)
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ metadata: { prompt: { newOption: { value: 'Kling' } } } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('treats null metadata as omitted', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-null.md')
|
||||
|
||||
await tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
metadata: null,
|
||||
} as never)
|
||||
|
||||
expect(vi.mocked(assetService.createFile).mock.calls[0][0].metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects metadata keys that are not Creation Context fields before uploading', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-bad-meta.md')
|
||||
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
metadata: { status: 'approved' },
|
||||
} as never),
|
||||
).rejects.toThrow(/not allowed: status/)
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a call with neither or both of "path" and "content"', async () => {
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', { parent: 'folder-1' } as never),
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "content" (with "name").')
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '/some/file.md',
|
||||
name: 'notes.md',
|
||||
content: 'hello',
|
||||
} as never),
|
||||
).rejects.toThrow('Provide exactly one of')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires a name with "content"', async () => {
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', { parent: 'folder-1', content: 'x' } as never),
|
||||
).rejects.toThrow('"name" is required')
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist, without touching storage', async () => {
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '/nonexistent/file.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not write to storage when the user lacks Edit permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-file-denied.md')
|
||||
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', { parent: 'folder-1', path: filePath } as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
await expect(
|
||||
tool('create_file').execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
name: 'notes.md',
|
||||
content: 'x',
|
||||
} as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes harness validation with only one source set', async () => {
|
||||
const t = tool('create_file')
|
||||
const validated = validateToolArguments(
|
||||
{ name: t.name, description: '', parameters: t.parameters } as Parameters<
|
||||
typeof validateToolArguments
|
||||
>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: t.name,
|
||||
arguments: { parent: 'folder-1', name: 'random.txt', content: 'hello' },
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
)
|
||||
|
||||
await t.execute('call-1', validated as never)
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'random.txt' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the agent its own parameters', () => {
|
||||
const properties = Object.keys(
|
||||
(tool('create_file').parameters as unknown as { properties: object }).properties,
|
||||
)
|
||||
expect(properties.sort()).toEqual(['content', 'name', 'parent', 'path'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_version', () => {
|
||||
it('uploads a local file and creates a version as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-version.md')
|
||||
|
||||
const result = await tool('create_version').execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
} as never)
|
||||
|
||||
const key = vi.mocked(s3Service.putObject).mock.calls[0][1]
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'agent-create-version.md',
|
||||
key,
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
expect(outputOf(result)).toMatchObject({ id: 'file-1', name: 'v2' })
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: AuditAction.file_create, agentId: 'agent-1' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-version-meta.md')
|
||||
|
||||
await tool('create_version').execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
} as never)
|
||||
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not upload when the user lacks Edit permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-version-denied.md')
|
||||
|
||||
await expect(
|
||||
tool('create_version').execute('call-1', { parent: 'file-1', path: filePath } as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist', async () => {
|
||||
await expect(
|
||||
tool('create_version').execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: '/nonexistent/file.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the agent its own parameters', () => {
|
||||
const properties = Object.keys(
|
||||
(tool('create_version').parameters as unknown as { properties: object }).properties,
|
||||
)
|
||||
expect(properties.sort()).toEqual(['parent', 'path'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Creation Context metadata parameter', () => {
|
||||
const creationMetadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
{
|
||||
id: 'source',
|
||||
config: {
|
||||
name: 'Source',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
it.each(['create_file', 'create_version'] as const)(
|
||||
'%s exposes the project schema as a strict, nullable metadata parameter',
|
||||
(name) => {
|
||||
const parameters = tool(name, { creationMetadataSchema }).parameters as unknown as {
|
||||
properties: { metadata: { anyOf: [{ required: string[] }, { type: string }] } }
|
||||
}
|
||||
const meta = parameters.properties.metadata
|
||||
expect(meta.anyOf[0].required).toEqual(['prompt', 'source'])
|
||||
expect(meta.anyOf[1].type).toBe('null')
|
||||
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'gemini' })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, source: null })).toBe(true)
|
||||
expect(Value.Check(meta, null)).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello' })).toBe(false)
|
||||
expect(Value.Check(meta, { prompt: 'x', source: 'gemini', other: 1 })).toBe(false)
|
||||
expect(Value.Check(meta, { prompt: 'x', source: 'not-an-option' })).toBe(false)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps null values inside metadata through harness validation', () => {
|
||||
const t = tool('create_file', {
|
||||
creationMetadataSchema: fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
]),
|
||||
})
|
||||
const validated = validateToolArguments(
|
||||
{ name: t.name, description: '', parameters: t.parameters } as Parameters<
|
||||
typeof validateToolArguments
|
||||
>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: t.name,
|
||||
arguments: { parent: 'folder-1', name: 'a.md', content: 'x', metadata: { prompt: null } },
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
) as { metadata?: unknown }
|
||||
|
||||
expect(validated.metadata).toEqual({ prompt: null })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import { Type } from 'typebox'
|
||||
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { createFile, type StartedUploadOutput } from '@shumai/operations'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { completeUploadOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import {
|
||||
registerAgentToolExtension,
|
||||
type AgentOperationContext,
|
||||
type AgentToolExtension,
|
||||
type AgentToolOptions,
|
||||
type ToolParametersSchema,
|
||||
} from '../operation-tools'
|
||||
|
||||
const METADATA_HINT =
|
||||
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.'
|
||||
|
||||
/**
|
||||
* The agent gets the conversation project's Creation Context fields as a strict schema
|
||||
* (so it knows exactly what to fill in) instead of the open record MCP clients see. Without
|
||||
* such fields the parameter is left out.
|
||||
*/
|
||||
function setCreationMetadata(schema: ToolParametersSchema, options: AgentToolOptions): void {
|
||||
if (options.creationMetadataSchema) {
|
||||
schema.properties.metadata = Type.Union([options.creationMetadataSchema, Type.Null()])
|
||||
} else {
|
||||
delete schema.properties.metadata
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLocalFile(localPath: string): string {
|
||||
const absolutePath = path.resolve(process.cwd(), localPath)
|
||||
if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isFile()) {
|
||||
throw new Error(`Local file not found at path: ${localPath}`)
|
||||
}
|
||||
return absolutePath
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the file straight to the upload's storage key (the agent runs next to storage, so
|
||||
* it doesn't need the upload URL), then completes the upload as the agent.
|
||||
*/
|
||||
async function uploadAndComplete(
|
||||
raw: unknown,
|
||||
extra: Record<string, unknown>,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult<unknown>> {
|
||||
const started = raw as StartedUploadOutput
|
||||
if (!started.key) throw new Error('The upload did not return a storage key')
|
||||
|
||||
if (typeof extra.path === 'string') {
|
||||
const absolutePath = resolveLocalFile(extra.path)
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
fs.createReadStream(absolutePath),
|
||||
fs.statSync(absolutePath).size,
|
||||
readFileMimeType(absolutePath),
|
||||
)
|
||||
} else {
|
||||
const content = Buffer.from(typeof extra.content === 'string' ? extra.content : '', 'utf-8')
|
||||
// The key ends with the file name, which gives the same type as the upload's.
|
||||
const contentType = getFileMimeType(null, started.key, 'text/plain')
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
content,
|
||||
content.byteLength,
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
const asset = await runOperation(
|
||||
completeUploadOp,
|
||||
{ ...ctx, via: 'agent' },
|
||||
{ uploadId: started.uploadId },
|
||||
)
|
||||
return { content: [{ type: 'text', text: JSON.stringify(asset, null, 2) }], details: {} }
|
||||
}
|
||||
|
||||
const createFileExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new file in a folder. Choose exactly ONE source: ' +
|
||||
'(1) "path" to upload a local file (e.g. one you made in .pi), OR ' +
|
||||
'(2) "name" and "content" to create a text file with that content. ' +
|
||||
METADATA_HINT,
|
||||
parameterOverrides: z.object({
|
||||
name: createFile.input.shape.name
|
||||
.optional()
|
||||
.describe(
|
||||
'File name including its extension (e.g. "notes.md"). Required with "content"; defaults to the local file\'s name with "path".',
|
||||
),
|
||||
}),
|
||||
extraParameters: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Absolute or relative path of a local file to upload. Omit when using "content".'),
|
||||
content: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Full text content of a new text file. Requires "name"; omit when using "path".'),
|
||||
}),
|
||||
hiddenParameters: ['contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
const hasPath = typeof extra.path === 'string'
|
||||
const hasContent = typeof extra.content === 'string'
|
||||
if (hasPath === hasContent) {
|
||||
throw new Error('Provide exactly one of "path" (a local file) or "content" (with "name").')
|
||||
}
|
||||
if (hasPath) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
return {
|
||||
...input,
|
||||
name: input.name ?? path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
}
|
||||
}
|
||||
if (typeof input.name !== 'string' || !input.name.trim()) {
|
||||
throw new Error('"name" is required when creating a file from "content".')
|
||||
}
|
||||
return { ...input, contentType: getFileMimeType(null, input.name, 'text/plain') }
|
||||
},
|
||||
present: uploadAndComplete,
|
||||
}
|
||||
|
||||
const createVersionExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new version of an existing file (or version stack) from a local file path. ' +
|
||||
'The new version becomes the current one. ' +
|
||||
METADATA_HINT,
|
||||
extraParameters: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe('Absolute or relative path of the local file to upload as the new version.'),
|
||||
}),
|
||||
hiddenParameters: ['name', 'contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
return {
|
||||
...input,
|
||||
name: path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
}
|
||||
},
|
||||
present: uploadAndComplete,
|
||||
}
|
||||
|
||||
registerAgentToolExtension('create_file', createFileExtension)
|
||||
registerAgentToolExtension('create_version', createVersionExtension)
|
||||
@@ -67,18 +67,35 @@ describe('operation-backed agent tools', () => {
|
||||
.map((t) => t.name)
|
||||
.sort(),
|
||||
).toEqual([
|
||||
'copy_assets',
|
||||
'create_comment',
|
||||
'create_file',
|
||||
'create_folder',
|
||||
'create_version',
|
||||
'create_version_stack',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'get_folder_instructions',
|
||||
'list_assets',
|
||||
'list_comments',
|
||||
'list_metadata_fields',
|
||||
'list_projects',
|
||||
'list_versions',
|
||||
'move_assets',
|
||||
'read_asset',
|
||||
'remove_version',
|
||||
'rename_asset',
|
||||
'resolve_comment',
|
||||
'search_assets',
|
||||
'update_asset_metadata',
|
||||
])
|
||||
})
|
||||
|
||||
it('does not give the agent complete_upload: its create tools finish uploads themselves', () => {
|
||||
expect(buildOperationTools(ctx).map((t) => t.name)).not.toContain('complete_upload')
|
||||
})
|
||||
|
||||
it('keeps the existing parameter names', () => {
|
||||
const params = (name: string) =>
|
||||
Object.keys((getTool(name).parameters as unknown as { properties: object }).properties)
|
||||
@@ -353,6 +370,7 @@ describe('operation-backed agent tools', () => {
|
||||
id: 'asset-1',
|
||||
name: 'x',
|
||||
type,
|
||||
parentId: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
|
||||
@@ -13,6 +13,23 @@ import {
|
||||
/** Context for agent-invoked Operations; `via` is always `agent`. */
|
||||
export type AgentOperationContext = Omit<OperationContext, 'via'>
|
||||
|
||||
/** Per-session settings for building tools, e.g. schemas that depend on the project. */
|
||||
export interface AgentToolOptions {
|
||||
/**
|
||||
* Schema of the conversation project's Creation Context fields, for the `metadata`
|
||||
* parameter of tools that create files. Undefined when the project has none.
|
||||
*/
|
||||
creationMetadataSchema?: TSchema
|
||||
}
|
||||
|
||||
/** The JSON Schema of a tool's parameters (an object schema). */
|
||||
export interface ToolParametersSchema {
|
||||
type?: string
|
||||
properties: Record<string, unknown>
|
||||
required?: string[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent-specific presentation for an Operation. By default a tool returns the Operation output
|
||||
* as JSON text; an extension can add agent-only parameters, map them into the Operation input,
|
||||
@@ -29,6 +46,10 @@ export interface AgentToolExtension {
|
||||
* input when it runs.
|
||||
*/
|
||||
parameterOverrides?: z.ZodObject
|
||||
/** Operation input fields the agent doesn't see because `toInput` fills them in. */
|
||||
hiddenParameters?: readonly string[]
|
||||
/** Adjust the parameters' JSON Schema for this session (e.g. a project-specific field). */
|
||||
adjustParameters?(schema: ToolParametersSchema, options: AgentToolOptions): void
|
||||
/** Adjust the Operation input using the extra parameters. */
|
||||
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
|
||||
/**
|
||||
@@ -40,7 +61,11 @@ export interface AgentToolExtension {
|
||||
extra: Record<string, unknown>,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult<unknown> | undefined>
|
||||
present(output: unknown, extra: Record<string, unknown>): Promise<AgentToolResult<unknown>>
|
||||
present(
|
||||
output: unknown,
|
||||
extra: Record<string, unknown>,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult<unknown>>
|
||||
}
|
||||
|
||||
const extensions = new Map<string, AgentToolExtension>()
|
||||
@@ -62,12 +87,21 @@ function toolInputSchema(op: Operation, extension?: AgentToolExtension): z.ZodOb
|
||||
* 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, extension?: AgentToolExtension): TSchema {
|
||||
const schema: Record<string, unknown> = z.toJSONSchema(toolInputSchema(op, extension), {
|
||||
export function toToolParameters(
|
||||
op: Operation,
|
||||
extension?: AgentToolExtension,
|
||||
options: AgentToolOptions = {},
|
||||
): TSchema {
|
||||
const schema = z.toJSONSchema(toolInputSchema(op, extension), {
|
||||
io: 'input',
|
||||
})
|
||||
}) as unknown as ToolParametersSchema
|
||||
// `$schema` is not understood by the harness validator or every model provider.
|
||||
delete schema.$schema
|
||||
for (const name of extension?.hiddenParameters ?? []) {
|
||||
delete schema.properties[name]
|
||||
schema.required = schema.required?.filter((field) => field !== name)
|
||||
}
|
||||
extension?.adjustParameters?.(schema, options)
|
||||
Compile(schema)
|
||||
return schema as unknown as TSchema
|
||||
}
|
||||
@@ -92,14 +126,18 @@ export function splitAgentParams(
|
||||
}
|
||||
|
||||
/** Expose an Operation as a native agent tool that runs through `runOperation`. */
|
||||
export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentTool {
|
||||
export function toAgentTool(
|
||||
op: Operation,
|
||||
ctx: AgentOperationContext,
|
||||
options: AgentToolOptions = {},
|
||||
): AgentTool {
|
||||
const { definition } = op
|
||||
const extension = extensions.get(definition.name)
|
||||
return {
|
||||
name: definition.name,
|
||||
label: definition.title,
|
||||
description: extension?.description ?? definition.description,
|
||||
parameters: toToolParameters(op, extension),
|
||||
parameters: toToolParameters(op, extension, options),
|
||||
execute: async (_toolCallId, params) => {
|
||||
const { input, extra } = splitAgentParams(op, extension, params)
|
||||
if (extension?.intercept) {
|
||||
@@ -108,7 +146,7 @@ export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentToo
|
||||
}
|
||||
const output = await runOperation(op, { ...ctx, via: 'agent' }, input)
|
||||
if (extension) {
|
||||
return extension.present(output, extra)
|
||||
return extension.present(output, extra, ctx)
|
||||
}
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
|
||||
@@ -119,6 +157,9 @@ export function toAgentTool(op: Operation, ctx: AgentOperationContext): AgentToo
|
||||
}
|
||||
|
||||
/** Agent tools for every Operation with the `agent` surface. */
|
||||
export function buildOperationTools(ctx: AgentOperationContext): AgentTool[] {
|
||||
return getOperationsForSurface('agent').map((op) => toAgentTool(op, ctx))
|
||||
export function buildOperationTools(
|
||||
ctx: AgentOperationContext,
|
||||
options: AgentToolOptions = {},
|
||||
): AgentTool[] {
|
||||
return getOperationsForSurface('agent').map((op) => toAgentTool(op, ctx, options))
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { validateToolArguments } from '@earendil-works/pi-ai'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { fieldsToTypeBoxSchema } from './index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
uploadFileToKey: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
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: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
* Reproduce: pi-ai <= 0.82.1 runs its lenient coercion on typebox v1 schemas and
|
||||
* converts `null` in a `[string, null]` union into `""` (see
|
||||
* coerceWithUnionSchema in @earendil-works/pi-ai/dist/utils/validation.js).
|
||||
*
|
||||
* When the agent calls create_file with `path: null, data: {...}`, the harness
|
||||
* validates first: the `null` path becomes `""`, so the tool's
|
||||
* assertExactlyOneSource believes BOTH path and data were provided and throws
|
||||
* "Provide exactly one of ..." even though the call is valid.
|
||||
*
|
||||
* Fixed upstream in pi-ai 0.84.0 (#7328): values that already match a union arm
|
||||
* are preserved before coercion. This test should pass once @earendil-works/pi-ai
|
||||
* is upgraded to >= 0.84.0.
|
||||
*/
|
||||
describe('reproduce null coercion in harness tool validation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('keeps path: null when data is provided (no false "exactly one" error)', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
|
||||
const validated = validateToolArguments(
|
||||
{
|
||||
name: 'create_file',
|
||||
description: '',
|
||||
parameters: tool.parameters,
|
||||
} as Parameters<typeof validateToolArguments>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: 'create_file',
|
||||
arguments: {
|
||||
parent: '01KYKNP52YERGJ6Q4GTPF5FRQF',
|
||||
path: null,
|
||||
data: { name: 'random_text.txt', content: 'hello' },
|
||||
},
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
) as { path?: unknown; data?: unknown }
|
||||
|
||||
// The `null` path must survive validation untouched; coercion to "" makes
|
||||
// the tool think both path and data were provided.
|
||||
expect(validated.path).toBeNull()
|
||||
expect(validated.data).toEqual({ name: 'random_text.txt', content: 'hello' })
|
||||
|
||||
// execute must accept the valid call (data-only) without throwing
|
||||
const result = await tool.execute('call-1', validated as never)
|
||||
expect(result.details).toEqual({})
|
||||
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
|
||||
id: 'file-1',
|
||||
name: 'test',
|
||||
type: 'file',
|
||||
size: 100,
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
|
||||
expect(assetService.createFile).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps null metadata values (the "unknown" sentinel) through validation', () => {
|
||||
const tool = createCreateFileTool(
|
||||
'user-1',
|
||||
fieldsToTypeBoxSchema([{ id: 'prompt', config: { name: 'Prompt', type: 'text' } }]),
|
||||
)
|
||||
const validated = validateToolArguments(
|
||||
{
|
||||
name: 'create_file',
|
||||
description: '',
|
||||
parameters: tool.parameters,
|
||||
} as Parameters<typeof validateToolArguments>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: 'create_file',
|
||||
arguments: {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'a.md', content: 'x' },
|
||||
metadata: { prompt: null },
|
||||
},
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
) as { metadata?: Record<string, unknown> }
|
||||
|
||||
expect(validated.metadata).toEqual({ prompt: null })
|
||||
})
|
||||
})
|
||||
@@ -1,408 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateFileTool } from './create-file'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
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'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
uploadFileToKey: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
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: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateFileTool', () => {
|
||||
const createdFiles: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const f of createdFiles) {
|
||||
if (fs.existsSync(f)) {
|
||||
fs.unlinkSync(f)
|
||||
}
|
||||
}
|
||||
createdFiles.length = 0
|
||||
})
|
||||
|
||||
const createTempFile = (content: string | Buffer, filename: string): string => {
|
||||
const filePath = path.join(os.tmpdir(), filename)
|
||||
fs.writeFileSync(filePath, content)
|
||||
createdFiles.push(filePath)
|
||||
return filePath
|
||||
}
|
||||
|
||||
it('should upload a local file when "path" is provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-test.md')
|
||||
|
||||
const tool = createCreateFileTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null })
|
||||
|
||||
expect(s3Service.uploadFileToKey).toHaveBeenCalledTimes(1)
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
|
||||
const uploadArgs = vi.mocked(s3Service.uploadFileToKey).mock.calls[0]
|
||||
const s3Key = uploadArgs[1]
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'folder-1',
|
||||
})
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'create-file-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({})
|
||||
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
|
||||
id: 'file-1',
|
||||
name: 'test',
|
||||
type: 'file',
|
||||
size: 100,
|
||||
})
|
||||
})
|
||||
|
||||
it('should forward the metadata to assetService.createFile when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: null,
|
||||
})
|
||||
|
||||
const callArgs = vi.mocked(assetService.createFile).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md', data: null }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should create a file directly from name and content', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
const result = await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'notes.md', content: '# Notes\n\nHello' },
|
||||
})
|
||||
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
|
||||
const [bucket, s3Key, body, size, contentType] = vi.mocked(s3Service.putObject).mock
|
||||
.calls[0] as unknown as [string, string, Buffer, number, string]
|
||||
|
||||
expect(bucket).toBe(process.env.S3_BUCKET || 'shumai')
|
||||
expect(s3Key).toMatch(/^files\/.+notes\.md$/)
|
||||
expect(body.toString('utf-8')).toBe('# Notes\n\nHello')
|
||||
expect(size).toBe(Buffer.byteLength('# Notes\n\nHello', 'utf-8'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'notes.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Notes\n\nHello', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({})
|
||||
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
|
||||
id: 'file-1',
|
||||
name: 'test',
|
||||
type: 'file',
|
||||
size: 100,
|
||||
})
|
||||
})
|
||||
|
||||
it('should default unknown extensions to text/plain when creating from content', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'script.ts', content: 'const x = 1' },
|
||||
})
|
||||
|
||||
const [, , , , contentType] = vi.mocked(s3Service.putObject).mock.calls[0] as unknown as [
|
||||
string,
|
||||
string,
|
||||
Buffer,
|
||||
number,
|
||||
string,
|
||||
]
|
||||
expect(contentType).toBe('text/plain')
|
||||
})
|
||||
|
||||
it('should sanitize the name when creating from content', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'my/notes.md', content: 'hello' },
|
||||
})
|
||||
|
||||
const [, s3Key] = vi.mocked(s3Service.putObject).mock.calls[0] as unknown as [
|
||||
string,
|
||||
string,
|
||||
Buffer,
|
||||
number,
|
||||
string,
|
||||
]
|
||||
expect(s3Key).toContain('my_notes.md')
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'my_notes.md' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw when neither "path" nor "data" is provided', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'folder-1', path: null, data: null }),
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
})
|
||||
|
||||
it('should throw when both "path" and "data" are provided', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '/some/file.md',
|
||||
data: { name: 'notes.md', content: 'hello' },
|
||||
}),
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
{
|
||||
id: 'source',
|
||||
config: {
|
||||
name: 'Source',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' }] },
|
||||
},
|
||||
},
|
||||
{ id: 'rating', config: { name: 'Rating', type: 'rating' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const meta = (tool.parameters as any).properties.metadata
|
||||
// `metadata` is a nullable union: [strict object, null]
|
||||
const metaObject = meta.anyOf[0]
|
||||
|
||||
expect(meta).toBeDefined()
|
||||
expect(metaObject.required).toEqual(['prompt', 'source', 'rating'])
|
||||
expect(metaObject.additionalProperties).toBe(false)
|
||||
expect(metaObject.properties.prompt.anyOf[0].type).toBe('string')
|
||||
expect(metaObject.properties.prompt.anyOf[1].type).toBe('null')
|
||||
expect(metaObject.properties.source.anyOf[0].anyOf[0].enum).toEqual(['gemini'])
|
||||
expect(metaObject.properties.rating.anyOf[0].type).toBe('number')
|
||||
|
||||
// Every field must be present (use null when unknown); unknown keys and bad enums are rejected
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5 })).toBe(true)
|
||||
expect(
|
||||
Value.Check(meta, {
|
||||
prompt: 'hello',
|
||||
source: { newOption: { value: 'kling' } },
|
||||
rating: 5,
|
||||
}),
|
||||
).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello' })).toBe(false)
|
||||
expect(
|
||||
Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5, unknownKey: 'x' }),
|
||||
).toBe(false)
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'not-an-option', rating: null })).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('should omit the metadata parameter when no schema is provided', () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
expect((tool.parameters as any).properties.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
describe('when the user lacks Edit permission on the parent', () => {
|
||||
const denied = new Error('User is not a member of the team')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(denied)
|
||||
})
|
||||
|
||||
it('does not upload a local file to storage', async () => {
|
||||
const filePath = createTempFile('# Not allowed', 'create-file-denied.md')
|
||||
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null }),
|
||||
).rejects.toThrow(denied.message)
|
||||
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not write inline content to storage', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'notes.md', content: 'hello' },
|
||||
}),
|
||||
).rejects.toThrow(denied.message)
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass agentId and record audit log when agentContext is provided', async () => {
|
||||
const filePath = createTempFile('# Agent file', 'agent-file.md')
|
||||
|
||||
const tool = createCreateFileTool('user-1', undefined, { teamId: 'team-1', agentId: 'agent-1' })
|
||||
await tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null })
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
creatorId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.file_create,
|
||||
teamId: 'team-1',
|
||||
userId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
projectId: undefined,
|
||||
itemId: 'file-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,160 +0,0 @@
|
||||
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 { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
interface CreateFileToolParams {
|
||||
parent: string
|
||||
path: string | null
|
||||
data: { name: string; content: string } | null
|
||||
metadata?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
function assertExactlyOneSource(params: CreateFileToolParams) {
|
||||
const hasPath = params.path !== null
|
||||
const hasData = params.data !== null
|
||||
if (hasPath === hasData) {
|
||||
throw new Error('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
}
|
||||
return hasPath ? params.path! : params.data!
|
||||
}
|
||||
|
||||
export function createCreateFileTool(
|
||||
userId: string,
|
||||
metadataSchema?: TSchema,
|
||||
agentContext?: { teamId?: string; agentId?: string },
|
||||
): AgentTool {
|
||||
const createFileSchema = Type.Object(
|
||||
{
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent folder ID under which to create the file. This parameter is required.',
|
||||
}),
|
||||
path: Type.Union([
|
||||
Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to an existing file on disk. Provide a value here OR in "data", but not both. Use null if you are providing "data".',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
data: Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
name: Type.String({
|
||||
minLength: 1,
|
||||
description:
|
||||
'The desired name for the new file, including its extension (e.g. "notes.md").',
|
||||
}),
|
||||
content: Type.String({
|
||||
description: 'The full content of the file as a plain string.',
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Null(),
|
||||
]),
|
||||
...(metadataSchema ? { metadata: Type.Union([metadataSchema, Type.Null()]) } : {}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const tool: AgentTool = {
|
||||
name: 'create_file',
|
||||
label: 'Create File',
|
||||
description:
|
||||
'Create a new file under a folder. You MUST choose exactly ONE creation method: ' +
|
||||
'(1) provide "path" to upload an existing local file, OR ' +
|
||||
'(2) provide "data" with name and content to create a new text file. ' +
|
||||
'Set the unused parameter to null. ' +
|
||||
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.',
|
||||
parameters: createFileSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
// The harness validates tool args against `createFileSchema` before calling
|
||||
// execute, so `params` is guaranteed to match this shape.
|
||||
const p = params as CreateFileToolParams
|
||||
const source = assertExactlyOneSource(p)
|
||||
|
||||
// Authorize before touching storage so a denied call leaves no orphaned object behind.
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
let name: string
|
||||
let size: number
|
||||
let mimeType: string
|
||||
let s3Key: string
|
||||
|
||||
if (typeof source === 'string') {
|
||||
// Branch A: upload an existing local file
|
||||
const absolutePath = path.resolve(process.cwd(), source)
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
throw new Error(`Local file not found at path: ${source}`)
|
||||
}
|
||||
|
||||
name = path.basename(absolutePath)
|
||||
size = fs.statSync(absolutePath).size
|
||||
mimeType = readFileMimeType(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
s3Key = `files/${ulid()}/${sanitizeFilename(name)}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
} else {
|
||||
// Branch B: create the file directly from provided name and content
|
||||
name = sanitizeFilename(source.name)
|
||||
const content = Buffer.from(source.content, 'utf-8')
|
||||
size = content.byteLength
|
||||
mimeType = getFileMimeType(null, source.name, 'text/plain')
|
||||
|
||||
s3Key = `files/${ulid()}/${name}`
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', s3Key, content, size, mimeType)
|
||||
}
|
||||
|
||||
const asset = await assetService.createFile({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: size,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
agentId: agentContext?.agentId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
if (agentContext?.teamId) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.file_create,
|
||||
teamId: agentContext.teamId,
|
||||
userId,
|
||||
agentId: agentContext.agentId,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
itemId: asset.id,
|
||||
})
|
||||
}
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
return tool
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateVersionTool } from './create-version'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
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'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
uploadFileToKey: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
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: {
|
||||
createVersion: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'v2', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateVersionTool', () => {
|
||||
const createdFiles: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const f of createdFiles) {
|
||||
if (fs.existsSync(f)) {
|
||||
fs.unlinkSync(f)
|
||||
}
|
||||
}
|
||||
createdFiles.length = 0
|
||||
})
|
||||
|
||||
const createTempFile = (content: string | Buffer, filename: string): string => {
|
||||
const filePath = path.join(os.tmpdir(), filename)
|
||||
fs.writeFileSync(filePath, content)
|
||||
createdFiles.push(filePath)
|
||||
return filePath
|
||||
}
|
||||
|
||||
it('should not upload to storage when the user lacks Edit permission on the parent', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = createTempFile('# Not allowed', 'create-version-denied.md')
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
await expect(tool.execute('call-1', { parent: 'file-1', path: filePath })).rejects.toThrow(
|
||||
'User is not a member of the team',
|
||||
)
|
||||
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should upload a local file and create a version via assetService.createVersion', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-test.md')
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'file-1', path: filePath })
|
||||
|
||||
expect(s3Service.uploadFileToKey).toHaveBeenCalledTimes(1)
|
||||
const uploadArgs = vi.mocked(s3Service.uploadFileToKey).mock.calls[0]
|
||||
const s3Key = uploadArgs[1]
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'file-1',
|
||||
})
|
||||
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'create-version-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({})
|
||||
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
|
||||
id: 'file-1',
|
||||
name: 'v2',
|
||||
type: 'file',
|
||||
size: 100,
|
||||
})
|
||||
})
|
||||
|
||||
it('should forward the metadata to assetService.createVersion when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath, metadata: null })
|
||||
|
||||
const callArgs = vi.mocked(assetService.createVersion).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'file-1', path: '/nonexistent/file.md' }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
{ id: 'toggle', config: { name: 'Active', type: 'toggle' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const meta = (tool.parameters as any).properties.metadata
|
||||
// `metadata` is a nullable union: [strict object, null]
|
||||
const metaObject = meta.anyOf[0]
|
||||
|
||||
expect(meta).toBeDefined()
|
||||
expect(metaObject.required).toEqual(['prompt', 'toggle'])
|
||||
expect(metaObject.additionalProperties).toBe(false)
|
||||
expect(metaObject.properties.prompt.anyOf[0].type).toBe('string')
|
||||
expect(metaObject.properties.prompt.anyOf[1].type).toBe('null')
|
||||
expect(metaObject.properties.toggle.anyOf[0].type).toBe('boolean')
|
||||
|
||||
expect(Value.Check(meta, { prompt: 'p', toggle: true })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, toggle: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'p', toggle: null, unknownKey: 'x' })).toBe(false)
|
||||
})
|
||||
|
||||
it('should omit the metadata parameter when no schema is provided', () => {
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
expect((tool.parameters as any).properties.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should pass agentId and record audit log when agentContext is provided', async () => {
|
||||
const filePath = createTempFile('# Agent version file', 'agent-ver-file.md')
|
||||
|
||||
const tool = createCreateVersionTool('user-1', undefined, {
|
||||
teamId: 'team-1',
|
||||
agentId: 'agent-1',
|
||||
})
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath })
|
||||
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
creatorId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.file_create,
|
||||
teamId: 'team-1',
|
||||
userId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
projectId: undefined,
|
||||
itemId: 'file-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,110 +0,0 @@
|
||||
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 { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
interface CreateVersionToolParams {
|
||||
parent: string
|
||||
path: string
|
||||
metadata?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function createCreateVersionTool(
|
||||
userId: string,
|
||||
metadataSchema?: TSchema,
|
||||
agentContext?: { teamId?: string; agentId?: string },
|
||||
): AgentTool {
|
||||
const createVersionSchema = Type.Object(
|
||||
{
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent file ID for which to create a new version. This parameter is required.',
|
||||
}),
|
||||
path: Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to the file on disk. This parameter is required.',
|
||||
}),
|
||||
...(metadataSchema ? { metadata: Type.Union([metadataSchema, Type.Null()]) } : {}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const tool: AgentTool = {
|
||||
name: 'create_version',
|
||||
label: 'Create Version',
|
||||
description:
|
||||
'Create a new version of an existing file from a local file path. ' +
|
||||
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.',
|
||||
parameters: createVersionSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
// The harness validates tool args against `createVersionSchema` before calling
|
||||
// execute, so `params` is guaranteed to match this shape.
|
||||
const p = params as CreateVersionToolParams
|
||||
|
||||
// Authorize before touching storage so a denied call leaves no orphaned object behind.
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
const absolutePath = path.resolve(process.cwd(), p.path)
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
throw new Error(`Local file not found at path: ${p.path}`)
|
||||
}
|
||||
|
||||
const fileSize = fs.statSync(absolutePath).size
|
||||
const mimeType = readFileMimeType(absolutePath)
|
||||
const name = path.basename(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(name)}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const asset = await assetService.createVersion({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
agentId: agentContext?.agentId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
if (agentContext?.teamId) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.file_create,
|
||||
teamId: agentContext.teamId,
|
||||
userId,
|
||||
agentId: agentContext.agentId,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
itemId: asset.id,
|
||||
})
|
||||
}
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
return tool
|
||||
}
|
||||
Reference in New Issue
Block a user