mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 03:57:58 +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:
@@ -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)
|
||||
Reference in New Issue
Block a user