/** * ============================================================ * src/tools/write.ts —— Write 工具(整文件写入) * ------------------------------------------------------------ * 对应 kakadeai 主仓库的 FileWriteTool。 * 把 content 整段写到 file_path(覆盖既有内容)。 * 目录不存在时自动创建(递归)。 * * v0.2 增强: * - 路径安全校验(null byte / UNC 路径) * - 内容大小上限(1GB) * - 覆盖已有文件时在返回值中明确提示 * ============================================================ */ import { existsSync } from 'node:fs'; import { stat } from 'node:fs/promises'; import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { applyLineEnding, atomicWriteFile, encodeTextFile, readTextFile, resolveToolPath, } from '../shared/fileUtils.js'; import { filePathField } from '../shared/schemas.js'; import { assertFresh, hashFileBytes, recordRead, type FileReadState } from '../shared/fileState.js'; import { fileActivityMetadata } from '../shared/fileActivity.js'; import { emitFileMutation } from '../shared/fileMutationBus.js'; import { buildPatchSummary } from '../shared/diffSummary.js'; /** 写入内容上限:1GB。防止模型试图写入超大内容撑爆内存/磁盘。 */ const MAX_WRITE_SIZE_BYTES = 1024 * 1024 * 1024; // ---------------- 1. Zod 输入 schema ---------------- const inputSchema = z.object({ file_path: filePathField('写入'), content: z.string().describe('文件完整内容(会覆盖既有内容)'), }); type WriteInput = z.infer; // ---------------- 2. JSON Schema(由 Zod 自动派生) ---------------- const parameters = toToolParameters(inputSchema); // ---------------- 3. Description ---------------- const description = '创建文件或整体覆盖;新文件可直接写入。覆盖已有文件前须完整 Read(一次全量或分段覆盖全部范围)且内容未变化;仅有局部读取时使用 Edit/ApplyPatch。'; // ---------------- 5. call() ---------------- async function call(input: WriteInput, state?: FileReadState, cwd?: string): Promise { const pathResult = resolveToolPath(input.file_path, cwd); if (!pathResult.ok) return pathResult; const filePath = pathResult.resolvedPath; // Pre-read guard:覆盖已存在文件前必须先 Read 过;防止盲写覆盖外部修改。 const freshness = await assertFresh(filePath, { requireComplete: true }, state); if (!freshness.ok) { return { ok: false, error: freshness.error }; } const contentSize = Buffer.byteLength(input.content, 'utf8'); if (contentSize > MAX_WRITE_SIZE_BYTES) { return { ok: false, error: `写入内容过大(${contentSize} 字节 > ${MAX_WRITE_SIZE_BYTES} 字节 ≈ 1GB)。请拆分内容或使用 Edit 工具分块修改。`, }; } try { let originalSize = 0; const fileExisted = existsSync(filePath); if (fileExisted) { try { const st = await stat(filePath); originalSize = st.size; } catch {} } let contentToWrite = input.content; let originalContent = ''; let bomEncoding: Awaited>['encoding'] = 'utf8'; if (fileExisted) { const snapshot = await readTextFile(filePath); originalContent = snapshot.content; bomEncoding = snapshot.encoding; contentToWrite = applyLineEnding(input.content, snapshot.lineEnding); } await atomicWriteFile(filePath, contentToWrite, bomEncoding); recordRead(filePath, { contentHash: hashFileBytes(encodeTextFile(contentToWrite, bomEncoding)), }, state); emitFileMutation(filePath); const action = fileExisted ? '已覆盖' : '已创建新文件'; const newSize = Buffer.byteLength(contentToWrite, 'utf8'); const sizeInfo = fileExisted ? `(原文件 ${originalSize} 字节 → 新内容 ${newSize} 字节)` : `(${newSize} 字节)`; const bomInfo = bomEncoding === 'utf8-bom' ? ',已保留 UTF-8 BOM' : bomEncoding === 'utf16le' ? ',已保留 UTF-16 LE' : ''; const patch = buildPatchSummary(originalContent, contentToWrite, input.file_path); return { ok: true, content: `${action} ${filePath}${sizeInfo}${bomInfo}\n${patch.unifiedDiff ?? '[diff omitted: too large]'}`, metadata: await fileActivityMetadata(filePath, fileExisted ? 'modified' : 'created', 'not_run', 'support', cwd, patch), }; } catch (e) { return { ok: false, error: `写入失败:${(e as Error).message}` }; } } // ---------------- 6. 导出 ---------------- export const writeTool: Tool = { name: 'Write', description, inputSchema, parameters, isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'block', call: (input) => call(input), callWithContext: (input, _signal, context: ToolCallContext) => call(input, context.sessionState?.fileReads, context.cwd), };