From 07ad0d2f659652957d47e8455964814f47dbc5bb Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 4 Aug 2026 21:16:33 +0800 Subject: [PATCH] feat(agent): allow create_file tool to create files directly from content Add an optional 'data' field ({name, content}) to the create_file agent tool so agents can create files without a local file (e.g. when bash is not available). The existing 'path' upload mode is preserved; exactly one of 'path' or 'data' must be provided. Extract mime detection helpers (getFileMimeType, readFileMimeType) into a new file-mime module, keeping utils/mime.ts free of fs/path imports so it stays compatible with the Temporal workflow bundle (agent-autofill imports getProxyType from it). Refactor create_version to reuse the extracted helpers. Content uploads reuse s3Service.putObject; mime type is derived from the filename extension with a text/plain fallback, and the name is sanitized for the S3 key. --- packages/agent/src/tools/create-file.test.ts | 177 ++++++++++++++++++ packages/agent/src/tools/create-file.ts | 116 +++++++----- packages/agent/src/tools/create-version.ts | 37 +--- packages/core/src/utils/file-mime.test.ts | 61 ++++++ packages/core/src/utils/file-mime.ts | 57 ++++++ packages/webui/messages/en.json | 2 +- packages/webui/messages/zh.json | 2 +- .../messages/agent_tool_create_file_desc.d.ts | 2 +- .../messages/agent_tool_create_file_desc.js | 6 +- 9 files changed, 368 insertions(+), 92 deletions(-) create mode 100644 packages/agent/src/tools/create-file.test.ts create mode 100644 packages/core/src/utils/file-mime.test.ts create mode 100644 packages/core/src/utils/file-mime.ts diff --git a/packages/agent/src/tools/create-file.test.ts b/packages/agent/src/tools/create-file.test.ts new file mode 100644 index 00000000..e646f689 --- /dev/null +++ b/packages/agent/src/tools/create-file.test.ts @@ -0,0 +1,177 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { createCreateFileTool } from './create-file' +import { s3Service } from '@shumai/core/src/s3/s3' +import { executeAgentToolWorkflow } from './utils' +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('./utils', () => ({ + executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }), +})) + +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 }) + + 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(executeAgentToolWorkflow).toHaveBeenCalledWith({ + toolName: 'create_file', + args: { + parent: 'folder-1', + s3Key, + name: 'create-file-test.md', + size: Buffer.byteLength('# Hello from disk', 'utf-8'), + contentType: 'text/markdown', + }, + userId: 'user-1', + assetId: 'folder-1', + }) + + expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' }) + }) + + 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' }), + ).rejects.toThrow('Local file not found at path: /nonexistent/file.md') + expect(s3Service.uploadFileToKey).not.toHaveBeenCalled() + expect(executeAgentToolWorkflow).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', + 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(executeAgentToolWorkflow).toHaveBeenCalledWith({ + toolName: 'create_file', + args: { + parent: 'folder-1', + s3Key, + name: 'notes.md', + size: Buffer.byteLength('# Notes\n\nHello', 'utf-8'), + contentType: 'text/markdown', + }, + userId: 'user-1', + assetId: 'folder-1', + }) + + expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' }) + }) + + 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', + 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', + 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(executeAgentToolWorkflow).toHaveBeenCalledWith( + expect.objectContaining({ + args: 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' })).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(executeAgentToolWorkflow).not.toHaveBeenCalled() + }) +}) diff --git a/packages/agent/src/tools/create-file.ts b/packages/agent/src/tools/create-file.ts index 008adbd3..96b8963d 100644 --- a/packages/agent/src/tools/create-file.ts +++ b/packages/agent/src/tools/create-file.ts @@ -4,79 +4,93 @@ import { executeAgentToolWorkflow } from './utils' import * as fs from 'fs' import * as path from 'path' import { s3Service } from '@shumai/core/src/s3/s3' -import { detectSupportedMimeType } from '@shumai/core/src/utils/mime' +import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime' import { ulid } from 'ulid' import { sanitizeFilename } from '@shumai/core/src/utils/filename' -function getMimeType(filePath: string): string { - try { - const fd = fs.openSync(filePath, 'r') - try { - const buffer = Buffer.alloc(4100) - const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0) - const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead))) - if (detected) return detected - } finally { - fs.closeSync(fd) - } - } catch { - /* Ignore detection errors and fallback to extension mapping */ - } - - const ext = path.extname(filePath).toLowerCase() - const mimeTypes: Record = { - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.webp': 'image/webp', - '.svg': 'image/svg+xml', - '.mp4': 'video/mp4', - '.mov': 'video/quicktime', - '.pdf': 'application/pdf', - '.txt': 'text/plain', - '.md': 'text/markdown', - '.markdown': 'text/markdown', - } - return mimeTypes[ext] || 'application/octet-stream' -} - const createFileSchema = Type.Object({ parent: Type.String({ description: 'The parent folder ID under which to create the file. This parameter is required.', }), - path: Type.String({ - description: - 'The absolute or relative local path to the file on disk. This parameter is required.', - }), + path: Type.Optional( + Type.String({ + description: + 'The absolute or relative local path to an existing file on disk. Provide either this or "data", but not both.', + }), + ), + data: Type.Optional( + 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.', + }), + }), + ), }) +function assertExactlyOneSource(params: { + path?: string + data?: { name: string; content: string } +}) { + const hasPath = params.path !== undefined + const hasData = params.data !== undefined + 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): AgentTool { return { name: 'create_file', label: 'Create File', - description: 'Create a new file in a specified parent folder from a local file path.', + description: + 'Create a new file in a specified parent folder, either from a local file path or directly from name and content.', parameters: createFileSchema, execute: async (_toolCallId, params) => { - const absolutePath = path.resolve(process.cwd(), params.path) - if (!fs.existsSync(absolutePath)) { - throw new Error(`Local file not found at path: ${params.path}`) + const source = assertExactlyOneSource(params) + + 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 fileSize = fs.statSync(absolutePath).size - const mimeType = getMimeType(absolutePath) - - // Generate compliant S3 key matching normal file upload format - const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}` - await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType) - const result = await executeAgentToolWorkflow({ toolName: 'create_file', args: { parent: params.parent, s3Key, - name: path.basename(absolutePath), - size: fileSize, + name, + size, contentType: mimeType, }, userId, diff --git a/packages/agent/src/tools/create-version.ts b/packages/agent/src/tools/create-version.ts index 28fb68dd..6418eb25 100644 --- a/packages/agent/src/tools/create-version.ts +++ b/packages/agent/src/tools/create-version.ts @@ -4,43 +4,10 @@ import { executeAgentToolWorkflow } from './utils' import * as fs from 'fs' import * as path from 'path' import { s3Service } from '@shumai/core/src/s3/s3' -import { detectSupportedMimeType } from '@shumai/core/src/utils/mime' +import { readFileMimeType } from '@shumai/core/src/utils/file-mime' import { ulid } from 'ulid' import { sanitizeFilename } from '@shumai/core/src/utils/filename' -function getMimeType(filePath: string): string { - try { - const fd = fs.openSync(filePath, 'r') - try { - const buffer = Buffer.alloc(4100) - const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0) - const detected = detectSupportedMimeType(new Uint8Array(buffer.subarray(0, bytesRead))) - if (detected) return detected - } finally { - fs.closeSync(fd) - } - } catch { - /* Ignore detection errors and fallback to extension mapping */ - } - - const ext = path.extname(filePath).toLowerCase() - const mimeTypes: Record = { - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.webp': 'image/webp', - '.svg': 'image/svg+xml', - '.mp4': 'video/mp4', - '.mov': 'video/quicktime', - '.pdf': 'application/pdf', - '.txt': 'text/plain', - '.md': 'text/markdown', - '.markdown': 'text/markdown', - } - return mimeTypes[ext] || 'application/octet-stream' -} - const createVersionSchema = Type.Object({ parent: Type.String({ description: @@ -65,7 +32,7 @@ export function createCreateVersionTool(userId: string): AgentTool void) { + const filePath = path.join(os.tmpdir(), filename) + fs.writeFileSync(filePath, content) + try { + fn(filePath) + } finally { + fs.unlinkSync(filePath) + } +} + +describe('getFileMimeType', () => { + it('should detect binary mime type from content signature', () => { + const png = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, + ]) + expect(getFileMimeType(png, 'photo.unknown')).toBe('image/png') + }) + + it('should map known extensions when no signature is available', () => { + expect(getFileMimeType(null, 'notes.md')).toBe('text/markdown') + expect(getFileMimeType(null, 'doc.pdf')).toBe('application/pdf') + expect(getFileMimeType(null, 'image.PNG')).toBe('image/png') + }) + + it('should fall back to application/octet-stream for unknown extensions', () => { + expect(getFileMimeType(null, 'script.ts')).toBe('application/octet-stream') + }) + + it('should honor a custom fallback for unknown extensions', () => { + expect(getFileMimeType(null, 'script.ts', 'text/plain')).toBe('text/plain') + }) +}) + +describe('readFileMimeType', () => { + it('should sniff binary file content', () => { + const pngBytes = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + ]) + withTempFile(pngBytes, 'file-mime-test-image.png', (filePath) => { + expect(readFileMimeType(filePath)).toBe('image/png') + }) + }) + + it('should map text files by extension', () => { + withTempFile('# Hello', 'file-mime-test-notes.md', (filePath) => { + expect(readFileMimeType(filePath)).toBe('text/markdown') + }) + }) + + it('should fall back to octet-stream for missing files', () => { + expect(readFileMimeType('/nonexistent/file.xyz')).toBe('application/octet-stream') + }) +}) diff --git a/packages/core/src/utils/file-mime.ts b/packages/core/src/utils/file-mime.ts new file mode 100644 index 00000000..4419873b --- /dev/null +++ b/packages/core/src/utils/file-mime.ts @@ -0,0 +1,57 @@ +import * as fs from 'fs' +import * as path from 'path' +import { detectSupportedMimeType } from './mime' + +const EXTENSION_MIME_TYPES: Record = { + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.svg': 'image/svg+xml', + '.mp4': 'video/mp4', + '.mov': 'video/quicktime', + '.pdf': 'application/pdf', + '.txt': 'text/plain', + '.md': 'text/markdown', + '.markdown': 'text/markdown', +} + +/** + * Resolve a mime type from an optional content signature and a filename. + * Content signature sniffing (binary formats) takes priority; otherwise the + * filename extension mapping is used, falling back to `fallback` (defaults to + * `application/octet-stream`). + */ +export function getFileMimeType( + buffer: Uint8Array | null, + filename: string, + fallback: string = 'application/octet-stream', +): string { + if (buffer) { + const detected = detectSupportedMimeType(buffer) + if (detected) return detected + } + const ext = path.extname(filename).toLowerCase() + return EXTENSION_MIME_TYPES[ext] || fallback +} + +/** + * Detect the mime type of a file on disk by sniffing its first bytes and + * falling back to extension mapping. + */ +export function readFileMimeType(filePath: string): string { + try { + const fd = fs.openSync(filePath, 'r') + try { + const buffer = Buffer.alloc(4100) + const bytesRead = fs.readSync(fd, buffer, 0, 4100, 0) + return getFileMimeType(new Uint8Array(buffer.subarray(0, bytesRead)), filePath) + } finally { + fs.closeSync(fd) + } + } catch { + /* Ignore read errors and fall back to extension mapping */ + return getFileMimeType(null, filePath) + } +} diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 5e347aee..95c1cc7e 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -403,7 +403,7 @@ "agent_tool_create_folder_name": "Create Folder", "agent_tool_create_folder_desc": "Allows the agent to create new folders in Shumai.", "agent_tool_create_file_name": "Create File", - "agent_tool_create_file_desc": "Allows the agent to create and upload new files to Shumai.", + "agent_tool_create_file_desc": "Allows the agent to create files in Shumai, either by uploading a local file or by providing the file name and content directly.", "agent_tool_create_version_name": "Create Version", "agent_tool_create_version_desc": "Allows the agent to upload and stack a new version of an existing file in Shumai.", "enabled": "Enabled", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index dd5da737..eb0ef81f 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -403,7 +403,7 @@ "agent_tool_create_folder_name": "创建文件夹", "agent_tool_create_folder_desc": "允许智能体在 Shumai 中创建新文件夹。", "agent_tool_create_file_name": "创建文件", - "agent_tool_create_file_desc": "允许智能体创建新文件并上传到 Shumai。", + "agent_tool_create_file_desc": "允许智能体在 Shumai 中创建文件,既可以通过上传本地文件,也可以直接提供文件名和内容。", "agent_tool_create_version_name": "创建版本", "agent_tool_create_version_desc": "允许智能体在 Shumai 中为已有文件上传并叠加新版本。", "enabled": "已启用", diff --git a/packages/webui/paraglide/messages/agent_tool_create_file_desc.d.ts b/packages/webui/paraglide/messages/agent_tool_create_file_desc.d.ts index 4c347add..5c3900c4 100644 --- a/packages/webui/paraglide/messages/agent_tool_create_file_desc.d.ts +++ b/packages/webui/paraglide/messages/agent_tool_create_file_desc.d.ts @@ -1,7 +1,7 @@ /** * | output | * | --- | -* | "Allows the agent to create and upload new files to Shumai." | +* | "Allows the agent to create files in Shumai, either by uploading a local file or by providing the file name and content directly." | * * @param {Agent_Tool_Create_File_DescInputs} inputs * @param {{ locale?: "en" | "zh" }} options diff --git a/packages/webui/paraglide/messages/agent_tool_create_file_desc.js b/packages/webui/paraglide/messages/agent_tool_create_file_desc.js index 3b4c64dc..babe6b94 100644 --- a/packages/webui/paraglide/messages/agent_tool_create_file_desc.js +++ b/packages/webui/paraglide/messages/agent_tool_create_file_desc.js @@ -6,17 +6,17 @@ import { getLocale, experimentalStaticLocale } from '../runtime.js'; /** @typedef {{}} Agent_Tool_Create_File_DescInputs */ const en_agent_tool_create_file_desc = /** @type {(inputs: Agent_Tool_Create_File_DescInputs) => LocalizedString} */ () => { - return /** @type {LocalizedString} */ (`Allows the agent to create and upload new files to Shumai.`) + return /** @type {LocalizedString} */ (`Allows the agent to create files in Shumai, either by uploading a local file or by providing the file name and content directly.`) }; const zh_agent_tool_create_file_desc = /** @type {(inputs: Agent_Tool_Create_File_DescInputs) => LocalizedString} */ () => { - return /** @type {LocalizedString} */ (`允许智能体创建新文件并上传到 Shumai。`) + return /** @type {LocalizedString} */ (`允许智能体在 Shumai 中创建文件,既可以通过上传本地文件,也可以直接提供文件名和内容。`) }; /** * | output | * | --- | -* | "Allows the agent to create and upload new files to Shumai." | +* | "Allows the agent to create files in Shumai, either by uploading a local file or by providing the file name and content directly." | * * @param {Agent_Tool_Create_File_DescInputs} inputs * @param {{ locale?: "en" | "zh" }} options