P0 会话可靠性收口(根治"模型思考着会话就停止"): - P0-1 finish_reason 全链路贯通:DONE 事件与 IterationStep 新增 finishReason,OpenAI 共享 SSE / Anthropic message_delta.stop_reason / Ollama done_reason 三路采集,TRACE 层弃用硬编码 'stop' 记录真值 - P0-2 空响应守卫 + 降级重试:零产出流→可重试错误走退避;思考耗尽输出预算(reasoning-only + length)→自动关闭思考降级重试一次;仍失败→OUTPUT_LENGTH_EXCEEDED 结构化错误 + 故障转移;附带根治 abort 恰逢零工具调用轮被 COMPLETED 抢占的真实缺陷 - P0-3 思考×能力×预算三对齐:DeepSeek/MiMo/Agnes/Ollama 四家 supportsThinking=false 强制不发思考参数;小输出预算告警;设置页联动提示 - P0-4 渲染层可见性:截断/空完成/友好错误三类提示,i18n 全部出层 - P0-5 回归四件套:reasoning-only 终止判定、集成级空闲超时、504 引擎重试归类、思考中 abort→USER_INTERRUPT、P4-2 强制收尾路径 FEAT-1:LLM 设置新增「最大输出上限」——Provider 支持矩阵显隐 + 模型上限钳制提示 + 超限保存警告 + llm.maxTokens 热生效 P1 修复面收口: - 渲染层三缺陷根治:后台会话回放缓冲(2000 条/4MB 有界 + agent:getReplayState + 事件总线)+ abort 双层自愈 + sendMessage 收尾兜底 + 中断卡片清扫 - 工具 abort 信号全覆盖:web_search/web_fetch/http_request/code_search/git 系列/delegate_task 全部接入引擎中断;web_search 时间预算收敛(720s→≤240s);移除伪造 ToolExecutionContext 与死代码 - 安全:本地 Pinned CONNECT 代理根治浏览器通道 DNS rebinding(校验期 IP pinning,可注入 resolver 表测);配置 URL 域名解析深校验(DeepCheckSoftFailure 软失败);SSE 空 error 帧防御修复;Ollama generate/embed AbortSignal.any 合并 - 缺陷清单:UTF-16 BOM 读取、tmp 同毫秒碰撞(nanoid 后缀)、code_search JS 回退参数对称(case_sensitive/前后文独立)、list_directory include_node_modules、崩溃自愈退避(60s 窗 ≥3 次停 reload)、MemoryViewer/Sidebar i18n 收口 P2 能力演进: - 会话回收站:SCHEMA_VERSION 3 + 迁移 10(deleted_at,存在性守卫),软删除/恢复/彻底删除/30 天自动清理(启动+24h),searchMessages 聚合剔除,Sidebar 回收站面板 - 会话回放播放器:sessions:listRecordings/readRecording(白名单+目录边界+20MB 上限),SessionReplayPlayer 时间轴/步进/变速,Trace 面板入口 - electron-updater 自动更新:双轨(手动 feed 比对保留),生产环境启动静默检查 + update:status 广播 + app:updateInstall + LogsSettings UpdatePanel + builder publish 配置 - @ 文件提及:workspace.listFiles/readFileClip(边界/512KB/NUL 拒绝/MEMORY.md 保护),ChatInput Fuse 联想+键盘导航+附件管线注入 - MCP Resources/Prompts 发现:可选能力 try/catch 降级,mcp:listServerContents,MCPSettings 展开视图 - 文档对齐:内部 API 标准 HTML(Adapter 清单补 MiMo/已实现注记/STREAM_RESET/DONE.finishReason/ repetition_truncation 映射);README v0.8.0 亮点表 P3 测试基建: - 新增 4 个测试文件:engine-stream-contract(6)、engine-stream-reliability(4:集成空闲超时/504 重试/思考中 abort/P4-2 强制收尾)、thinking-capability-gate(7)、pinned-proxy(9,含深校验 5)、session-trash(5,DB 域)、use-agent-stream hook 级(5)、agent.test 回放缓冲(2) - 契约更新:orchestrator 被中断 SubAgent success=false(abort 优先级修复语义)、SSE 空 error 帧、UTF-16 正常读取、DeepSeek 未配置思考显式 disabled、迁移矩阵 v2→3 - 弱断言根治:registry WEBP 单向断言、hooks-contracts 自比恒真、memory 空 token 补强 全量验证:typecheck 0 错误 / lint 0 问题 / 系统 Node 2144 通过(301 DB 用例按 ABI 跳过)/ Electron ABI 2445/2445 全量通过 0 跳过
459 lines
18 KiB
TypeScript
459 lines
18 KiB
TypeScript
/**
|
||
* 文件编辑工具(1 个)
|
||
*
|
||
* file_editor — 精准文件编辑,支持行替换/插入/删除/正则替换
|
||
*
|
||
* 相比 write_file 的整文件覆盖,file_editor 支持精准定位修改,
|
||
* 避免大文件全量重写,减少 token 消耗和出错风险。
|
||
*
|
||
* v0.3.2 优化:
|
||
* - 使用共享 safeResolvePath(消除重复代码)
|
||
* - 使用共享 extractErrorMessage、FILE_TOOL_TIMEOUT_MS、MAX_FILE_SIZE_BYTES
|
||
* - 新增 dry_run 模式(预览变更不写入)
|
||
* - 文件大小上限(防止 OOM)
|
||
* - 统一 timeoutMs 为 15_000
|
||
*
|
||
* @see docs/MetonaAI-Desktop 架构与交互设计.html — 9 个基础工具
|
||
*/
|
||
|
||
import { readFile, writeFile, rename, mkdir, stat, unlink } from 'fs/promises';
|
||
import { dirname } from 'path';
|
||
import { existsSync } from 'fs';
|
||
import { nanoid } from 'nanoid';
|
||
import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
|
||
import type { MetonaToolDef } from '../../../harness/types';
|
||
import { MetonaToolCategory, MetonaRiskLevel } from '../../../harness/types';
|
||
import {
|
||
safeResolvePath,
|
||
extractErrorMessage,
|
||
MAX_FILE_SIZE_BYTES,
|
||
FILE_TOOL_TIMEOUT_MS,
|
||
isPotentiallyCatastrophicRegex,
|
||
} from './file-guard';
|
||
|
||
/**
|
||
* v0.7.4 P2-7: 灾难性正则检测从 file-guard 导入(共享模块),
|
||
* search_files / file_editor / code_search 统一复用 —— 消除三份实现漂移。
|
||
* @see file-guard.ts — isPotentiallyCatastrophicRegex
|
||
*/
|
||
export { isPotentiallyCatastrophicRegex };
|
||
|
||
export class FileEditorTool implements IMetonaTool {
|
||
readonly definition: MetonaToolDef = {
|
||
name: 'file_editor',
|
||
description:
|
||
'Edit a file with precision. Supports operations: replace (replace lines), insert (insert at line), delete (delete lines), regex (regex replace in range), find_replace (literal string replace, avoids regex ambiguity). More efficient than write_file for targeted edits. Supports dry_run mode for preview, multiline regex matching, and automatic .bak backup. File size limit: 10MB.',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
file_path: { type: 'string', description: 'Path to the file to edit' },
|
||
operation: {
|
||
type: 'string',
|
||
description: 'Edit operation',
|
||
enum: ['replace', 'insert', 'delete', 'regex', 'find_replace'],
|
||
},
|
||
start_line: {
|
||
type: 'number',
|
||
description: 'Start line number (1-indexed). Used by replace/insert/delete/regex',
|
||
},
|
||
end_line: {
|
||
type: 'number',
|
||
description: 'End line number (inclusive). Used by replace/delete/regex',
|
||
},
|
||
content: { type: 'string', description: 'New content for replace/insert operations' },
|
||
pattern: { type: 'string', description: 'Regex pattern for regex operation' },
|
||
replacement: { type: 'string', description: 'Replacement string for regex operation' },
|
||
flags: {
|
||
type: 'string',
|
||
description:
|
||
'Regex flags (default "g"). Use "gm" for multiline, "gms" for multiline+dotall',
|
||
},
|
||
multiline: {
|
||
type: 'boolean',
|
||
description:
|
||
'F2-6: Enable cross-line regex matching. When true, regex is applied to the joined content of the range (not line-by-line). Useful for replacing multi-line code blocks. Default false.',
|
||
},
|
||
find: {
|
||
type: 'string',
|
||
description:
|
||
'F2-5: Literal string to find for find_replace operation (no regex interpretation)',
|
||
},
|
||
replace: {
|
||
type: 'string',
|
||
description: 'F2-5: Replacement string for find_replace operation',
|
||
},
|
||
replace_all: {
|
||
type: 'boolean',
|
||
description:
|
||
'F2-5: Replace all occurrences (true, default) or only the first (false). For find_replace operation.',
|
||
},
|
||
backup: {
|
||
type: 'boolean',
|
||
description: 'F2-7: Save a .bak copy of the original file before editing (default false)',
|
||
},
|
||
dry_run: {
|
||
type: 'boolean',
|
||
description: 'Preview mode: return the diff without writing to file (default false)',
|
||
},
|
||
},
|
||
required: ['file_path', 'operation'],
|
||
},
|
||
category: MetonaToolCategory.FILESYSTEM,
|
||
riskLevel: MetonaRiskLevel.MEDIUM,
|
||
requiresPermission: true,
|
||
timeoutMs: FILE_TOOL_TIMEOUT_MS,
|
||
};
|
||
|
||
async execute(args: Record<string, unknown>, context: ToolExecutionContext): Promise<unknown> {
|
||
try {
|
||
// F1.5: file_path 空值校验
|
||
if (!args.file_path || typeof args.file_path !== 'string') {
|
||
return { success: false, error: 'file_path is required' };
|
||
}
|
||
const filePath = safeResolvePath(args.file_path as string, context.workspacePath);
|
||
const operation = args.operation as
|
||
| 'replace'
|
||
| 'insert'
|
||
| 'delete'
|
||
| 'regex'
|
||
| 'find_replace';
|
||
const dryRun = (args.dry_run as boolean) ?? false;
|
||
// F2-7: backup 参数 — 编辑前保存 .bak 文件
|
||
const backup = (args.backup as boolean) ?? false;
|
||
|
||
// 文件必须存在(不支持创建新文件,请用 write_file)
|
||
if (!existsSync(filePath)) {
|
||
return {
|
||
success: false,
|
||
error: `File not found: ${args.file_path}. Use write_file to create new files.`,
|
||
};
|
||
}
|
||
|
||
// v0.3.2: 文件大小上限(防止 OOM)
|
||
const stats = await stat(filePath);
|
||
if (stats.size > MAX_FILE_SIZE_BYTES) {
|
||
return {
|
||
success: false,
|
||
error: `File too large (${stats.size} bytes, max ${MAX_FILE_SIZE_BYTES} bytes). Consider using write_file to rewrite.`,
|
||
};
|
||
}
|
||
|
||
const originalContent = await readFile(filePath, 'utf-8');
|
||
const lines = originalContent.split('\n');
|
||
|
||
let newLines: string[];
|
||
let affectedRange: { start: number; end: number };
|
||
let replaceCount = 0; // v0.3.2: 统一在外层声明,供 dry_run 返回
|
||
|
||
switch (operation) {
|
||
case 'replace': {
|
||
const startLine = Math.max(1, (args.start_line as number) ?? 1);
|
||
const endLine = Math.min(lines.length, (args.end_line as number) ?? startLine);
|
||
if (endLine < startLine) {
|
||
return {
|
||
success: false,
|
||
error: `end_line (${endLine}) must be >= start_line (${startLine})`,
|
||
};
|
||
}
|
||
const content = (args.content as string) ?? '';
|
||
const contentLines = content.split('\n');
|
||
newLines = [...lines.slice(0, startLine - 1), ...contentLines, ...lines.slice(endLine)];
|
||
affectedRange = { start: startLine, end: endLine };
|
||
replaceCount = endLine - startLine + 1;
|
||
break;
|
||
}
|
||
|
||
case 'insert': {
|
||
let startLine = Math.max(1, (args.start_line as number) ?? 1);
|
||
startLine = Math.min(startLine, lines.length + 1); // 允许追加到末尾
|
||
const content = (args.content as string) ?? '';
|
||
const contentLines = content.split('\n');
|
||
newLines = [
|
||
...lines.slice(0, startLine - 1),
|
||
...contentLines,
|
||
...lines.slice(startLine - 1),
|
||
];
|
||
affectedRange = { start: startLine, end: startLine + contentLines.length - 1 };
|
||
replaceCount = contentLines.length;
|
||
break;
|
||
}
|
||
|
||
case 'delete': {
|
||
const startLine = Math.max(1, (args.start_line as number) ?? 1);
|
||
const endLine = Math.min(lines.length, (args.end_line as number) ?? startLine);
|
||
if (endLine < startLine) {
|
||
return {
|
||
success: false,
|
||
error: `end_line (${endLine}) must be >= start_line (${startLine})`,
|
||
};
|
||
}
|
||
newLines = [...lines.slice(0, startLine - 1), ...lines.slice(endLine)];
|
||
affectedRange = { start: startLine, end: endLine };
|
||
replaceCount = endLine - startLine + 1;
|
||
break;
|
||
}
|
||
|
||
case 'regex': {
|
||
const pattern = args.pattern as string;
|
||
const replacement = (args.replacement as string) ?? '';
|
||
const flags = (args.flags as string) ?? 'g';
|
||
// F2-6: multiline 参数 — 支持跨行匹配
|
||
const multiline = (args.multiline as boolean) ?? false;
|
||
if (!pattern) {
|
||
return { success: false, error: 'Regex operation requires "pattern" parameter' };
|
||
}
|
||
// F1.3: regex pattern 长度限制
|
||
if (pattern.length > 500) {
|
||
return { success: false, error: 'Regex pattern too long (max 500 chars)' };
|
||
}
|
||
// #45 修复: ReDoS 防护 — 检测灾难性正则模式,拒绝可能导致指数级回溯的 pattern
|
||
// 攻击场景:恶意 LLM 传入 (a+)+ 等模式,在长字符串上阻塞主进程
|
||
if (isPotentiallyCatastrophicRegex(pattern)) {
|
||
return {
|
||
success: false,
|
||
error:
|
||
'Potentially catastrophic regex pattern detected (ReDoS risk): nested or overlapping quantifiers',
|
||
};
|
||
}
|
||
const startLine = Math.max(1, (args.start_line as number) ?? 1);
|
||
const endLine = Math.min(lines.length, (args.end_line as number) ?? lines.length);
|
||
if (endLine < startLine) {
|
||
return {
|
||
success: false,
|
||
error: `end_line (${endLine}) must be >= start_line (${startLine})`,
|
||
};
|
||
}
|
||
|
||
// F1-1 修复: 强制 regex 含 g 标志,保证 match 计数与 replace 结果一致
|
||
const effectiveFlags = flags.includes('g') ? flags : flags + 'g';
|
||
let regex: RegExp;
|
||
try {
|
||
regex = new RegExp(pattern, effectiveFlags);
|
||
} catch (err) {
|
||
// F4-2: 统一用 extractErrorMessage 提取错误信息
|
||
return { success: false, error: `Invalid regex: ${extractErrorMessage(err)}` };
|
||
}
|
||
|
||
if (multiline) {
|
||
// F2-6: 跨行匹配 — 对整个目标内容做正则替换(支持多行代码块替换)
|
||
const targetContent = lines.slice(startLine - 1, endLine).join('\n');
|
||
// #45 修复: 限制 multiline 模式的目标内容长度,防止大文件上的 regex 执行导致主进程阻塞
|
||
// Node.js RegExp 执行是同步的,超长内容 + 复杂正则可阻塞事件循环
|
||
const MAX_REGEX_CONTENT_LENGTH = 100_000;
|
||
if (targetContent.length > MAX_REGEX_CONTENT_LENGTH) {
|
||
return {
|
||
success: false,
|
||
error: `Target content too large for multiline regex (${targetContent.length} chars, max ${MAX_REGEX_CONTENT_LENGTH}). Use a smaller line range or split the operation.`,
|
||
};
|
||
}
|
||
const matches = targetContent.match(regex);
|
||
if (matches) replaceCount = matches.length;
|
||
const replacedContent = targetContent.replace(regex, replacement);
|
||
const replacedLines = replacedContent.split('\n');
|
||
newLines = [
|
||
...lines.slice(0, startLine - 1),
|
||
...replacedLines,
|
||
...lines.slice(endLine),
|
||
];
|
||
} else {
|
||
// F1-1 修复: 用同一个 regex 实例做 match 计数 + replace 替换(逐行)
|
||
const targetLines = lines.slice(startLine - 1, endLine);
|
||
const replacedLines = targetLines.map((line) => {
|
||
const matches = line.match(regex);
|
||
if (matches) replaceCount += matches.length;
|
||
return line.replace(regex, replacement);
|
||
});
|
||
newLines = [
|
||
...lines.slice(0, startLine - 1),
|
||
...replacedLines,
|
||
...lines.slice(endLine),
|
||
];
|
||
}
|
||
affectedRange = { start: startLine, end: endLine };
|
||
|
||
// 如果没有替换,返回提示
|
||
if (replaceCount === 0) {
|
||
return {
|
||
success: true,
|
||
operation,
|
||
file_path: args.file_path,
|
||
message: 'No matches found for regex pattern',
|
||
replacements: 0,
|
||
affected_range: affectedRange,
|
||
dry_run: dryRun,
|
||
};
|
||
}
|
||
|
||
break;
|
||
}
|
||
|
||
case 'find_replace': {
|
||
// F2-5: 字面量字符串替换 — 不解析正则元字符,避免歧义
|
||
// 适用于精准替换代码片段(如函数名、配置值)
|
||
const find = args.find as string;
|
||
const replaceStr = (args.replace as string) ?? '';
|
||
const replaceAll = (args.replace_all as boolean) ?? true;
|
||
if (find === undefined || find === null) {
|
||
return { success: false, error: 'find_replace operation requires "find" parameter' };
|
||
}
|
||
if (find.length === 0) {
|
||
return { success: false, error: '"find" must not be empty' };
|
||
}
|
||
|
||
if (replaceAll) {
|
||
// 全局替换:用 split + join 统计匹配次数并替换
|
||
const parts = originalContent.split(find);
|
||
replaceCount = parts.length - 1;
|
||
const newContent = parts.join(replaceStr);
|
||
newLines = newContent.split('\n');
|
||
} else {
|
||
// 只替换第一个匹配
|
||
const idx = originalContent.indexOf(find);
|
||
if (idx >= 0) {
|
||
replaceCount = 1;
|
||
const newContent =
|
||
originalContent.slice(0, idx) +
|
||
replaceStr +
|
||
originalContent.slice(idx + find.length);
|
||
newLines = newContent.split('\n');
|
||
} else {
|
||
replaceCount = 0;
|
||
newLines = lines;
|
||
}
|
||
}
|
||
|
||
// find_replace 作用于整个文件,affectedRange 覆盖全部行
|
||
affectedRange = { start: 1, end: lines.length };
|
||
|
||
if (replaceCount === 0) {
|
||
return {
|
||
success: true,
|
||
operation,
|
||
file_path: args.file_path,
|
||
message: 'No matches found for find pattern',
|
||
replacements: 0,
|
||
affected_range: affectedRange,
|
||
dry_run: dryRun,
|
||
};
|
||
}
|
||
|
||
break;
|
||
}
|
||
|
||
default:
|
||
return { success: false, error: `Unknown operation: ${operation}` };
|
||
}
|
||
|
||
// v0.3.2: dry_run 模式 — 预览变更不写入
|
||
if (dryRun) {
|
||
// v0.3.2 修复 WARN-1: 分模式计算 preview 范围
|
||
// - insert: affectedRange.end 是新文件行号,原文件无被替换内容 → original 为空
|
||
// - replace/delete/regex: affectedRange.end 是原文件行号,original/modified 取相同范围
|
||
let originalPreview: string;
|
||
let modifiedPreview: string;
|
||
|
||
if (operation === 'insert') {
|
||
// insert: 原文件无被替换内容;新文件显示插入的内容
|
||
originalPreview = '';
|
||
modifiedPreview = newLines
|
||
.slice(affectedRange.start - 1, Math.min(affectedRange.end, newLines.length))
|
||
.join('\n');
|
||
} else if (operation === 'find_replace') {
|
||
// F2-5: find_replace 的 dry_run — 只预览第一个匹配附近的内容
|
||
// 避免大文件预览整个文件(affectedRange 覆盖全部行)
|
||
const firstMatchIdx = originalContent.indexOf(args.find as string);
|
||
if (firstMatchIdx >= 0) {
|
||
const beforeMatch = originalContent.slice(0, firstMatchIdx);
|
||
const matchLine = beforeMatch.split('\n').length;
|
||
const contextRadius = 3; // 前后各 3 行
|
||
const previewStart = Math.max(1, matchLine - contextRadius);
|
||
const previewEnd = Math.min(lines.length, matchLine + contextRadius);
|
||
originalPreview = lines.slice(previewStart - 1, previewEnd).join('\n');
|
||
const lineDelta = newLines.length - lines.length;
|
||
const modifiedEnd = Math.min(newLines.length, previewEnd + lineDelta);
|
||
modifiedPreview = newLines
|
||
.slice(previewStart - 1, Math.max(previewStart - 1, modifiedEnd))
|
||
.join('\n');
|
||
} else {
|
||
originalPreview = '';
|
||
modifiedPreview = '';
|
||
}
|
||
} else {
|
||
// replace/delete/regex: 原文件取 [start-1, end) 区间
|
||
originalPreview = lines
|
||
.slice(affectedRange.start - 1, Math.min(affectedRange.end, lines.length))
|
||
.join('\n');
|
||
// 新文件取相同范围 + 行数差修正(replace 可能改变行数,delete 后该位置为空)
|
||
const lineDelta = newLines.length - lines.length;
|
||
const modifiedEnd = Math.min(affectedRange.end + lineDelta, newLines.length);
|
||
modifiedPreview = newLines
|
||
.slice(affectedRange.start - 1, Math.max(affectedRange.start - 1, modifiedEnd))
|
||
.join('\n');
|
||
}
|
||
|
||
return {
|
||
success: true,
|
||
dry_run: true,
|
||
operation,
|
||
file_path: args.file_path,
|
||
affected_range: affectedRange,
|
||
replacements: replaceCount,
|
||
lines_before: lines.length,
|
||
lines_after: newLines.length,
|
||
preview: {
|
||
original: originalPreview,
|
||
modified: modifiedPreview,
|
||
},
|
||
};
|
||
}
|
||
|
||
// 自动创建父目录 (F1.8: 异步 mkdir)
|
||
const parentDir = dirname(filePath);
|
||
if (!existsSync(parentDir)) {
|
||
await mkdir(parentDir, { recursive: true });
|
||
}
|
||
|
||
// F2-7: backup 模式 — 编辑前保存 .bak 文件
|
||
// 注意:备份在写入前进行,确保即使写入失败也有原始备份
|
||
let backupPath: string | null = null;
|
||
if (backup) {
|
||
backupPath = `${filePath}.bak`;
|
||
await writeFile(backupPath, originalContent, 'utf-8');
|
||
}
|
||
|
||
const newContent = newLines.join('\n');
|
||
// F1.7: 原子写入 - 临时文件 + rename
|
||
// v0.8.0 P1-3.4: tmp 文件名追加 nanoid 随机段(同毫秒并发写防碰撞)
|
||
const tmpPath = `${filePath}.tmp_${Date.now()}_${nanoid(6)}`;
|
||
try {
|
||
await writeFile(tmpPath, newContent, 'utf-8');
|
||
await rename(tmpPath, filePath);
|
||
} catch (err) {
|
||
// 原子写入失败,清理临时文件
|
||
if (existsSync(tmpPath)) {
|
||
try {
|
||
await unlink(tmpPath);
|
||
} catch {
|
||
/* 忽略清理错误 */
|
||
}
|
||
}
|
||
throw err;
|
||
}
|
||
|
||
return {
|
||
success: true,
|
||
operation,
|
||
file_path: args.file_path,
|
||
affected_range: affectedRange,
|
||
replacements: replaceCount,
|
||
lines_before: lines.length,
|
||
lines_after: newLines.length,
|
||
bytes_written: Buffer.byteLength(newContent, 'utf-8'),
|
||
backup_path: backupPath, // F2-7: 备份文件路径(null 表示未备份)
|
||
};
|
||
} catch (err) {
|
||
return { success: false, error: extractErrorMessage(err) };
|
||
}
|
||
}
|
||
}
|