From e9cabb9a35e371abd3880ad49b99d3afc6dd579f Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:00:46 +0800 Subject: [PATCH 1/2] feat(tools): read large files in part and tolerate common edit mismatches --- CHANGELOG.md | 1 + bun.lock | 7 +- docs/features/harness/README.md | 4 +- .../harness/comparison/loop-execution.md | 19 +- docs/features/harness/prompt/reminders.md | 3 +- docs/features/harness/prompt/tools.md | 2 + docs/tutorial/00-overview.en.md | 2 +- docs/tutorial/00-overview.zh.md | 2 +- docs/tutorial/02-code-tools.en.md | 4 +- docs/tutorial/02-code-tools.zh.md | 4 +- docs/tutorial/04-session-context.en.md | 2 +- docs/tutorial/04-session-context.zh.md | 2 +- docs/tutorial/06-desktop-integration.en.md | 2 +- docs/tutorial/06-desktop-integration.zh.md | 2 +- package.json | 1 + src/Tool.ts | 3 + src/components/FileEditToolDiff.tsx | 9 +- src/components/messages/AttachmentMessage.tsx | 2 +- .../__tests__/artifact-edit-locks.test.ts | 25 +- src/server/__tests__/deckEditNotice.test.ts | 22 +- .../__tests__/stream-retraction.test.ts | 2 - src/server/__tests__/ws-memory-events.test.ts | 15 +- src/server/session/translate.ts | 78 +-- src/services/compact/compact.ts | 1 + .../compact/postCompactFileRestore.test.ts | 27 + src/services/tools/toolExecution.ts | 40 +- src/tools/FileEditTool/FileEditTool.test.ts | 239 +++++++++ src/tools/FileEditTool/FileEditTool.ts | 80 +-- src/tools/FileEditTool/UI.tsx | 10 +- src/tools/FileEditTool/constants.ts | 3 + src/tools/FileEditTool/matchEdit.test.ts | 295 +++++++++++ src/tools/FileEditTool/matchEdit.ts | 486 ++++++++++++++++++ src/tools/FileEditTool/types.ts | 4 + src/tools/FileEditTool/utils.ts | 293 +---------- src/tools/FileReadTool/FileReadTool.test.ts | 197 ++++++- src/tools/FileReadTool/FileReadTool.ts | 103 +++- src/tools/FileReadTool/limits.ts | 14 - src/tools/FileReadTool/prompt.ts | 28 + src/tools/FileWriteTool/FileWriteTool.ts | 18 +- src/tools/testing/agentContext.ts | 25 + src/utils/api.ts | 27 +- src/utils/attachments.ts | 75 +-- src/utils/fileStateCache.ts | 1 + src/utils/messages.ts | 13 +- src/utils/queryHelpers.ts | 7 +- 45 files changed, 1556 insertions(+), 643 deletions(-) create mode 100644 src/services/compact/postCompactFileRestore.test.ts create mode 100644 src/tools/FileEditTool/FileEditTool.test.ts create mode 100644 src/tools/FileEditTool/matchEdit.test.ts create mode 100644 src/tools/FileEditTool/matchEdit.ts create mode 100644 src/tools/testing/agentContext.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4da00877..08451893 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ All notable changes to DreamCoder will be documented in this file. - Plan mode follows one procedure: the agent explores, asks you questions and writes the plan file as it goes, instead of being told in one place not to write any file and in another to launch planning subagents (#270). - With models other than Claude, notes that arrive in the middle of a turn (messages from other sessions, board notifications, reminders) are sent as their own message instead of being appended to the last tool result (#270). - The notice for a file that changed after the agent read it no longer claims you or a linter changed it or asks the agent to keep it from you, and shows at most about 2 KB of the change (#270). +- **Fewer wasted steps when the agent reads and edits files.** Reading a file that is too large returns the first lines that fit and says which lines they are, instead of an error; a file attached with @ is cut the same way instead of at 2,000 lines. An edit still applies when the text the agent quotes differs from the file only in line-number prefixes, whitespace at the end of lines, indentation or written-out escapes, and the approval prompt shows the text that will actually be written. After such a partial read the agent can edit the file but cannot overwrite it, and a successful edit or write tells the agent not to read the file back. ### Fixed diff --git a/bun.lock b/bun.lock index a0a1a858..b51b91d7 100644 --- a/bun.lock +++ b/bun.lock @@ -93,6 +93,7 @@ }, "devDependencies": { "@types/bun": "^1.3.14", + "@types/lodash-es": "^4.17.12", "typescript": "^6.0.3", }, }, @@ -429,6 +430,10 @@ "@types/bun": ["@types/bun@1.3.14", "https://registry.npmmirror.com/@types/bun/-/bun-1.3.14.tgz", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + "@types/lodash": ["@types/lodash@4.17.27", "", {}, "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew=="], + + "@types/lodash-es": ["@types/lodash-es@4.17.12", "", { "dependencies": { "@types/lodash": "*" } }, "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ=="], + "@types/mute-stream": ["@types/mute-stream@0.0.4", "https://registry.npmmirror.com/@types/mute-stream/-/mute-stream-0.0.4.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow=="], "@types/node": ["@types/node@25.9.1", "https://registry.npmmirror.com/@types/node/-/node-25.9.1.tgz", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="], @@ -1095,8 +1100,6 @@ "@aws-sdk/xml-builder/@smithy/types": ["@smithy/types@4.14.2", "https://registry.npmmirror.com/@smithy/types/-/types-4.14.2.tgz", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - "@commander-js/extra-typings/commander": ["commander@12.1.0", "https://registry.npmmirror.com/commander/-/commander-12.1.0.tgz", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="], - "@grpc/proto-loader/yargs": ["yargs@17.7.2", "https://registry.npmmirror.com/yargs/-/yargs-17.7.2.tgz", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], "@inquirer/checkbox/ansi-escapes": ["ansi-escapes@4.3.2", "https://registry.npmmirror.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="], diff --git a/docs/features/harness/README.md b/docs/features/harness/README.md index 338230b0..07ed67d5 100644 --- a/docs/features/harness/README.md +++ b/docs/features/harness/README.md @@ -94,8 +94,8 @@ DreamCoder 的 CLI 派生自 Claude Code 2.1.92(`src/constants/claudeCodeCompa ### 5. 执行层 -- 编辑只处理弯引号,缩进、行尾空白、行号前缀、转义的偏差都会直接失败。ZCode 有 7 种回退,Codex 有 4 遍逐级放宽。 -- Read 超过 25,000 token 直接报错,模型要多一轮按段重读;ZCode 返回前一部分。 +- 编辑只处理弯引号,缩进、行尾空白、行号前缀、转义的偏差都会直接失败。ZCode 有 7 种回退,Codex 有 4 遍逐级放宽。本次修复:精确和弯引号之后,依次尝试行号前缀、行尾空白、缩进、转义四种匹配,每种都要求只有一个候选;缩进匹配上时按同一关系调整 `new_string`,找不到统一的对应关系就不匹配(`src/tools/FileEditTool/matchEdit.ts`)。执行时按当时的文件匹配,确认框和 hook 拿到的是按匹配结果改写后的输入,用户确认的就是要写入的文本;会话记录和对话里的工具卡片仍是模型给的原文。Edit 和 Write 成功的结果里加了一句不需要读回;Edit 实际写入的文本和模型给的 `new_string` 不同,或者用户在确认时改过内容,就不加。 +- Read 超过 25,000 token 直接报错,模型要多一轮按段重读;ZCode 返回前一部分。本次修复:超过 token 上限或字节上限时按行返回能放下的前一部分,并说明返回的行范围、总行数和继续读的方法;一行都放不下时仍然报错。被裁过的读之后 Edit 可以继续,Write 会被拒绝,直到有一次没被裁的读;CLI 重启后从会话记录恢复时,这个限制仍然保留。用 `@` 附上的文件也按同一规则返回前一部分。 - 不读 `AGENTS.md`,`src` 里只有 `/init` 提到它。DreamCoder 自己的仓库就只有 `AGENTS.md`。 - 外部构建里没有「完成前先验证」的条文。 - 没有空响应重试和重复调用提醒(ZCode 有)。 diff --git a/docs/features/harness/comparison/loop-execution.md b/docs/features/harness/comparison/loop-execution.md index 7a488b13..e51c553d 100644 --- a/docs/features/harness/comparison/loop-execution.md +++ b/docs/features/harness/comparison/loop-execution.md @@ -17,6 +17,7 @@ 5. **只有 ZCode 有重复调用防护**:同名同参连续 3 次插入提醒(只提醒不拦截,每回合最多 3 次)。DreamCoder 与 Codex 未找到任何重复调用检测。ZCode 还有「静默 5 次响应提醒向用户汇报」。 6. **工具并行:Codex 和 ZCode 在流式过程中就开始执行,DreamCoder 在本场景下要等整个响应结束。** DreamCoder 的流式工具执行受 GrowthBook 门控,GrowthBook 关闭时为 false。Codex 对可并行工具不设数量上限;ZCode 与 DreamCoder 上限 10。 7. **读取上限:DreamCoder 与 ZCode 常量相同(256KB、25,000 token、描述写 2000 行但代码不按行截断),但超 token 时行为不同**:ZCode 首次整文件读取返回部分视图,DreamCoder 直接报错,模型要再发一次带 offset/limit 的请求。DreamCoder 每次 Read 结果末尾还附约 330 字符的恶意软件提醒,另两家没有。 + 状态:本次修复:超限时按行返回前一部分(代码现在按行截断),@ 附件不再按 2,000 行截断;Edit 匹配加了行号前缀、行尾空白、缩进、转义四种回退;成功文案告诉模型不必读回。见 [README](../README.md) 执行层。 8. **Shell 超时语义:Codex 不杀进程,10 秒后交回 session ID 由模型轮询;ZCode 与 DreamCoder 默认 120 秒,到时自动转后台并承诺完成后通知。** 输出上限:Codex 约 10,000 token/字节,ZCode 30KB 尾部预览,DreamCoder 30,000 字符。 9. **规划工具:Codex 不注册 `update_plan` 但 prompt 仍描述它;ZCode 的 TodoWrite 描述只有 3 行、不鼓励主动使用;DreamCoder 在应用里启用 4 个 Task 工具(约 8K 字符描述),描述要求「3 步以上主动使用」、开始前标 in_progress、完成后立即标 completed。** 这是 DreamCoder 在普通小任务上额外工具调用和往返的主要来源(推断)。 10. **子 agent:Codex 明文禁止未经要求就委派;ZCode 鼓励「需要跨多个文件阅读」时委派;DreamCoder 鼓励「超过 3 次查询」时用 Explore(模型为 provider 的 fastModel)。** DreamCoder 与 Codex 子 agent 都不能再嵌套(深度 1)。 @@ -66,7 +67,7 @@ | 描述长度 | prompt 一行 | Edit 约 380 字符 | Edit 约 1.2K 字符 | | read-before-edit | 无 | 有 | 有 | | 过期检查 | 无 | mtime 前进或大小变化 | mtime 前进且内容不同 | -| 匹配遍数 | 4 遍逐行 + 末尾空行回退 | 精确 + 7 回退 | 精确 + 弯引号;接收时反净化 | +| 匹配遍数 | 4 遍逐行 + 末尾空行回退 | 精确 + 7 回退 | 精确 + 弯引号;接收时反净化(本次:精确之后依次尝试反净化、弯引号、行号前缀、行尾空白、缩进、转义,都在执行时进行) | | 歧义处理 | 不拒绝,取游标后第一个 | 拒绝 | 拒绝 | | 失败提示是否带文件实际内容 | 否 | 否 | 否 | | 成功返回 | 文件列表 A/M/D,约 100–200 字符 | 一句话 + 「不要读回」 | 一句话,约 60–100 字符 | @@ -92,10 +93,10 @@ - 成功:`The file X has been updated successfully. (file state is current in your context — no need to Read it back)`(`edit.ts:53-77`);结果给模型的上限 100KB(`edit.ts:281-289`)。保留编码与行尾(`edit.ts:509-515`)。Write 描述约 230 字符,同样的未读/过期检查,保留原行尾(`handlers/write.ts:37-64, 109, 131`)。 **DreamCoder**(`src/tools/FileEditTool/`) -- 接收时(解析模型输出阶段,`src/utils/messages.ts:2798` → `src/utils/api.ts:622-645` → `utils.ts:581-662`):new_string 每行去尾部空白(.md/.mdx 除外);old_string 精确找不到时套用 18 项反净化表(``、``、`\n\nH:` 等,`utils.ts:531-550`),同样替换应用到 new_string。 -- validateInput 顺序(`FileEditTool.ts:138-345`):old==new → deny 规则 → >1GiB(`:85`)→ 读入并 CRLF→LF → 文件不存在(附 Did you mean)/ old_string 空但文件非空 → .ipynb → 未读过或部分视图(code 6)→ 过期(code 7,文案同 ZCode)→ 精确匹配,失败再弯引号归一(`utils.ts:73-96`)→ 找不到(code 8:`String to replace not found in file.\nString: `)→ 多处匹配(code 9)。 +- 接收时(解析模型输出阶段,`src/utils/messages.ts:2798` → `src/utils/api.ts:622-645` → `utils.ts:581-662`):new_string 每行去尾部空白(.md/.mdx 除外);old_string 精确找不到时套用 18 项反净化表(``、``、`\n\nH:` 等,`utils.ts:531-550`),同样替换应用到 new_string。(本次:接收时不再读文件,只去 new_string 行尾空白;反净化改为 `matchEdit` 的一种匹配方式,在 validateInput、确认和 call 时都生效,见 `src/tools/FileEditTool/matchEdit.ts`) +- validateInput 顺序(`FileEditTool.ts:138-345`):old==new → deny 规则 → >1GiB(`:85`)→ 读入并 CRLF→LF → 文件不存在(附 Did you mean)/ old_string 空但文件非空 → .ipynb → 未读过或部分视图(code 6)→ 过期(code 7,文案同 ZCode)→ 精确匹配,失败再弯引号归一(`utils.ts:73-96`;本次:改为 `matchEdit` 的各种匹配方式)→ 找不到(code 8:`String to replace not found in file.\nString: `)→ 多处匹配(code 9)。 - call 阶段再查一次过期,失败抛 `File has been unexpectedly modified. Read it again before attempting to write it.`(`FileEditTool.ts:445-470`;`constants.ts:10-11`)。new_string 为空且后接换行时连换行一起删(`utils.ts:218-229`)。保留编码(utf8/utf16le)与行尾(`src/utils/fileRead.ts:87-96`;`src/utils/file.ts:84-98`)。 -- 成功:`The file has been updated successfully.`(`FileEditTool.ts:555-575`)。没有「不要读回」提示。 +- 成功:`The file has been updated successfully.`(`FileEditTool.ts:555-575`)。没有「不要读回」提示(本次:加了一句不需要读回,写入文本和 new_string 不同或用户改过时不加)。 - Write:已存在文件要求读过且未改(`src/tools/FileWriteTool/FileWriteTool.ts:199-219`);content 每行去尾空白(非 md,`src/utils/api.ts:646-660`);固定写 LF(`FileWriteTool.ts:307`);返回 `File created successfully at: ` 或 `The file has been updated successfully.`(`:426, 432`)。 - 读过的文件被外部修改后,下一次请求附 `edited_text_file` 附件(`src/utils/attachments.ts:862, 2047-2102`)。 @@ -124,7 +125,7 @@ - Codex:读取靠 `cat`/`sed -n`/`rg`;exec 输出预算默认 10,000 token(`codex:core/src/unified_exec/mod.rs:74`),回退模型截断策略 10,000 字节(`codex:models-manager/src/model_info.rs:126`),截断时加 `Warning: truncated output (original token count: N)`(`codex:core/src/tools/context.rs:519-521`)。 - ZCode:常量 256KB / 25,000 / 2,000(`zcode:contracts/src/tools/read.ts:15-17`);2,000 只用于描述和附件(`zcode:core/src/runtime/helpers/attachments.ts:307`;`zcode:core/src/tool/handlers/read.ts:72`)。超 token 的首次整读返回前若干行,提示放在批次后附件中(`zcode:core/src/tool/handlers/read-text.ts:150-200`);带 offset/limit 超限才报错。超 256KB 报错,文案与 DreamCoder 相同(`zcode:adapters/src/fs/text-range-reader.ts:41-43`)。去重文案(`read-text.ts:17-18`;`read.ts:207-210`)。描述写明「Do NOT re-read a file you just edited to verify」(`read.ts:78`)。Glob 100 条/100KB(`zcode:core/src/tool/handlers/glob.ts:20-21`);Grep 默认 files_with_matches(`grep.ts:29, 203`)。 -- DreamCoder:确认上限为 256KB(`src/utils/file.ts:48`;`src/utils/readFileInRange.ts:63, 96-101`,仅在未给 limit 时检查,`src/tools/FileReadTool/FileReadTool.ts:1017-1025`)与 25,000 token(`src/tools/FileReadTool/limits.ts` `DEFAULT_MAX_OUTPUT_TOKENS`;`FileReadTool.ts:176-183, 753-770`)。报错文案都要求「Use offset and limit parameters to read specific portions of the file, or search for specific content」,模型下一步是带 offset/limit 重读或改用 Grep,+1 往返。描述默认不提 256KB(`includeMaxSizeInPrompt` 来自 GrowthBook,`FileReadTool.ts:347-349`)。估算超过 6,250 token 时调用 count_tokens API;代理只接 `/proxy/v1/messages`(`src/server/proxy/handler.ts:11-17`),调用失败返回 null 后用估算值(`src/services/tokenEstimation.ts:192-198`)(推断:每次大文件读取多一次失败的本地 HTTP 请求)。2,000 行只用于描述和附件(`src/tools/FileReadTool/prompt.ts:37`;`src/utils/attachments.ts:3137`)。去重仅对同 offset/limit、mtime 未变的 Read 生效(`FileReadTool.ts:530-570`),Edit 后的状态不参与去重。恶意软件提醒对 `claude-opus-4-7` 以外的所有模型都附(`FileReadTool.ts:697-698, 727-736`)。Grep head_limit 250、2 万字符(`src/tools/GrepTool/GrepTool.ts:108, 164`);Glob 100 个(`src/tools/GlobTool/GlobTool.ts:157`)。 +- DreamCoder:确认上限为 256KB(`src/utils/file.ts:48`;`src/utils/readFileInRange.ts:63, 96-101`,仅在未给 limit 时检查,`src/tools/FileReadTool/FileReadTool.ts:1017-1025`)与 25,000 token(`src/tools/FileReadTool/limits.ts` `DEFAULT_MAX_OUTPUT_TOKENS`;`FileReadTool.ts:176-183, 753-770`)。报错文案都要求「Use offset and limit parameters to read specific portions of the file, or search for specific content」,模型下一步是带 offset/limit 重读或改用 Grep,+1 往返。描述默认不提 256KB(`includeMaxSizeInPrompt` 来自 GrowthBook,`FileReadTool.ts:347-349`)。估算超过 6,250 token 时调用 count_tokens API;代理只接 `/proxy/v1/messages`(`src/server/proxy/handler.ts:11-17`),调用失败返回 null 后用估算值(`src/services/tokenEstimation.ts:192-198`)(推断:每次大文件读取多一次失败的本地 HTTP 请求)。2,000 行只用于描述和附件(`src/tools/FileReadTool/prompt.ts:37`;`src/utils/attachments.ts:3137`)(本次:附件不再按 2,000 行截断,2,000 只剩描述里那句)。去重仅对同 offset/limit、mtime 未变的 Read 生效(`FileReadTool.ts:530-570`),Edit 后的状态不参与去重。恶意软件提醒对 `claude-opus-4-7` 以外的所有模型都附(`FileReadTool.ts:697-698, 727-736`)。Grep head_limit 250、2 万字符(`src/tools/GrepTool/GrepTool.ts:108, 164`);Glob 100 个(`src/tools/GlobTool/GlobTool.ts:157`)。 ### 2.5 Shell @@ -212,17 +213,17 @@ TodoWrite 描述不要求主动使用,通常不调用。若 old_string 带行 |---|---|---| | 每次 Read 附恶意软件提醒 | 约 330 字符,除 `claude-opus-4-7` 外都附(`src/tools/FileReadTool/FileReadTool.ts:697-736`) | 每次读取多约 80–100 token,并累积进历史;对非 Claude 模型没有对应训练,可能使其对正常代码修改更犹豫 | | 应用内启用 4 个 Task 工具且描述要求主动、逐项更新 | `src/server/services/conversationService.ts:1052`;`src/constants/prompts.ts:270-282` | 小任务也可能多 1~2 次往返和多次工具调用;4 份描述每次请求都发送 | -| Read 超 25,000 token 直接报错 | `FileReadTool.ts:176-183, 753-770` | 大文件首读必定 +1 往返;ZCode 同常量但返回部分视图 | +| Read 超 25,000 token 直接报错 | `FileReadTool.ts:176-183, 753-770` | 大文件首读必定 +1 往返;ZCode 同常量但返回部分视图(本次修复) | | 大文件读取触发 count_tokens 请求 | 代理不接该路径(`src/server/proxy/handler.ts:11-17`) | 一次失败的本地 HTTP 请求,增加延迟,不增加 token | -| 接收时的反净化替换表 | `src/tools/FileEditTool/utils.ts:531-550` | 针对 Claude 输出特性的修正,对第三方模型基本无作用 | +| 接收时的反净化替换表 | `src/tools/FileEditTool/utils.ts:531-550` | 针对 Claude 输出特性的修正,对第三方模型基本无作用(本次:移入 `matchEdit`,执行时生效) | ### 另两家都有而 DreamCoder 没有 | 差异 | 事实 | 后果(推断) | |---|---|---| | 流式过程中开始执行工具 | Codex 全部、ZCode 只读类(`codex:core/src/stream_events_utils.rs:~345-372`;`zcode:core/src/runtime/methods/streaming-tool-coordinator.ts:383-406`);DreamCoder 被 GrowthBook 门关闭(`src/query/config.ts:33`) | 不影响 token 和轮数,只影响墙钟时间;与 benchmark 中 Claude Code「运行时间最长」方向一致,但贡献大小未测 | -| 编辑匹配对空白/缩进的容忍 | Codex trim_end/trim/Unicode 归一;ZCode 7 种回退;DreamCoder 只有弯引号 | 第三方模型常见的缩进、行尾空白、带行号前缀、转义错误在 DreamCoder 上都变成失败,每次 +1~2 往返,且需重发整段 old_string | -| 编辑成功后明确告诉模型「不要读回」 | ZCode 成功文案(`zcode:core/src/tool/handlers/edit.ts:59`)、Read 描述(`read.ts:78`);Codex prompt(`codex:models-manager/prompt.md:143`);DreamCoder 两处都没有 | 模型可能在编辑后再 Read 验证,+1 往返和一份全文输出 | +| 编辑匹配对空白/缩进的容忍 | Codex trim_end/trim/Unicode 归一;ZCode 7 种回退;DreamCoder 只有弯引号 | 第三方模型常见的缩进、行尾空白、带行号前缀、转义错误在 DreamCoder 上都变成失败,每次 +1~2 往返,且需重发整段 old_string(本次修复) | +| 编辑成功后明确告诉模型「不要读回」 | ZCode 成功文案(`zcode:core/src/tool/handlers/edit.ts:59`)、Read 描述(`read.ts:78`);Codex prompt(`codex:models-manager/prompt.md:143`);DreamCoder 两处都没有 | 模型可能在编辑后再 Read 验证,+1 往返和一份全文输出(本次修复) | | 循环异常保护(在两家中至少一家有) | ZCode 有重复调用提醒、可疑空响应重试、静默提醒;Codex 没有。严格说这不是「两家都有」,单列在此 | DreamCoder 遇到第三方模型重复同一调用时没有任何干预;空响应直接结束回合,headless 运行会以空结果收尾 | ### 三家共同点(不构成差异,但影响判断) diff --git a/docs/features/harness/prompt/reminders.md b/docs/features/harness/prompt/reminders.md index a7fe589b..64fe21bb 100644 --- a/docs/features/harness/prompt/reminders.md +++ b/docs/features/harness/prompt/reminders.md @@ -95,7 +95,7 @@ - 类型:问题 - 严重程度:中 -- 体量:每个引用的文件一次,最多 25,000 token 或截断为前 2,000 行,再加 340 字符条款(T-INJ-01)和约 180 字符的包装;文件未变时重复引用不再发送(`already_read_file`,`attachments.ts:3054-3100`)。 +- 体量:每个引用的文件一次,最多 25,000 token(超出时带能放下的前一部分),再加 340 字符条款(T-INJ-01)和约 180 字符的包装;文件未变时重复引用不再发送(`already_read_file`,`attachments.ts:3054-3100`)。 - 现状(按执行顺序): 1. 工作区面板加代码选区或行评论时,引用带 `absolutePath`、`lineStart`、`lineEnd`、`quote`(`desktop/src/components/workspace/WorkspacePanel.tsx:669-691`)。 2. 发送时,桌面端: @@ -234,6 +234,7 @@ ### T-INJ-14 多处提醒要求模型「不要告诉用户」,这是针对 Claude 习惯写的措辞 +- 状态:部分修复:文件改动那句在 #270 去掉(同 T-INJ-06);@ 文件截断那句随 2,000 行截断一起删除(本次),@ 文件改为和 Read 同样按能放下的行数裁剪,并说明返回了哪几行。任务提醒和跨天提醒两句未改。 - 类型:优化 - 严重程度:低 - 体量:每处 60~110 字符,随所在提醒出现 diff --git a/docs/features/harness/prompt/tools.md b/docs/features/harness/prompt/tools.md index cb13db8b..1a731b5c 100644 --- a/docs/features/harness/prompt/tools.md +++ b/docs/features/harness/prompt/tools.md @@ -230,6 +230,7 @@ ### T-TOOL-12 Read 描述说「默认最多读 2000 行」,实际默认读整个文件,256KB 和 25,000 token 的上限描述里没写 +- 状态:部分修复(本次):超过 token 或字节上限时按行返回能放下的前一部分,并说明行范围、总行数和继续读的方法,一行都放不下时仍报错;描述里大小上限那句同步改了。「默认最多 2000 行」和「建议读整个文件」两句未改。 - 类型:问题 - 严重程度:中 - 体量:描述 1 句;后果是超限时多一轮。 @@ -346,6 +347,7 @@ ### T-TOOL-21 缺少「编辑后不必重读验证」的说明;Edit 的「最小 old_string」提示只给 ant +- 状态:已修复(本次):Edit 和 Write 成功的结果末尾加了一句不需要读回;没有写进 Read 描述。 - 状态:部分修复(#270):ant 专用的「最小 old_string」提示已删除;「编辑后不必重读」未定。 - 状态:维护者已定(2026-11-18):「最小 old_string」这条 ant 专用提示随 ant 分支一起删除;「编辑后不必重读」未定。 - 类型:缺失 diff --git a/docs/tutorial/00-overview.en.md b/docs/tutorial/00-overview.en.md index 6cb161b4..7825e3ee 100644 --- a/docs/tutorial/00-overview.en.md +++ b/docs/tutorial/00-overview.en.md @@ -64,7 +64,7 @@ The program runs `Read`, gets the file contents with line numbers, and writes th } ``` -Before `Edit` runs, it goes through two checks. The argument check requires that the target file was read by `Read` first, that it has not changed since it was read, and that `old_string` can be found in the file ([Part 2](./02-code-tools.en.md)). The permission check may require user confirmation in the default mode ([Part 3](./03-permissions.en.md)). After the user allows it, `Edit` writes the file and returns a result whose `tool_use_id` is `toolu_edit_2` and whose content is `The file /example/src/app.ts has been updated successfully.`. Each `tool_result` points back to its `tool_use` through `tool_use_id`. This correspondence is explained in [Part 1](./01-execution-loop.en.md#from-tool_use-to-tool_result). +Before `Edit` runs, it goes through two checks. The argument check requires that the target file was read by `Read` first, that it has not changed since it was read, and that `old_string` can be found in the file ([Part 2](./02-code-tools.en.md)). The permission check may require user confirmation in the default mode ([Part 3](./03-permissions.en.md)). After the user allows it, `Edit` writes the file and returns a result whose `tool_use_id` is `toolu_edit_2` and whose content is `The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back.`. Each `tool_result` points back to its `tool_use` through `tool_use_id`. This correspondence is explained in [Part 1](./01-execution-loop.en.md#from-tool_use-to-tool_result). **Third request.** The program appends the messages again and requests the model. The model replies "Changed `value` to 2." with no tool call, and the execution loop ends. The file becomes: diff --git a/docs/tutorial/00-overview.zh.md b/docs/tutorial/00-overview.zh.md index bc27cfff..a334eacf 100644 --- a/docs/tutorial/00-overview.zh.md +++ b/docs/tutorial/00-overview.zh.md @@ -64,7 +64,7 @@ export const value = 1 } ``` -`Edit` 执行前要经过两项检查:参数检查要求目标文件先被 `Read` 读过、读取后没有被改动,且 `old_string` 能在文件中找到([第二篇](./02-code-tools.zh.md));权限检查在默认模式下可能要求用户确认([第三篇](./03-permissions.zh.md))。用户允许后,`Edit` 写入文件,返回 `tool_use_id` 为 `toolu_edit_2`、内容为 `The file /example/src/app.ts has been updated successfully.` 的结果。每个 `tool_result` 通过 `tool_use_id` 指回对应的 `tool_use`,这组对应关系在[第一篇](./01-execution-loop.zh.md#从-tool_use-到-tool_result)说明。 +`Edit` 执行前要经过两项检查:参数检查要求目标文件先被 `Read` 读过、读取后没有被改动,且 `old_string` 能在文件中找到([第二篇](./02-code-tools.zh.md));权限检查在默认模式下可能要求用户确认([第三篇](./03-permissions.zh.md))。用户允许后,`Edit` 写入文件,返回 `tool_use_id` 为 `toolu_edit_2`、内容为 `The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back.` 的结果。每个 `tool_result` 通过 `tool_use_id` 指回对应的 `tool_use`,这组对应关系在[第一篇](./01-execution-loop.zh.md#从-tool_use-到-tool_result)说明。 **第三次请求。** 程序再次追加消息并请求模型。模型回复“已将 `value` 改为 2”,没有工具调用,执行循环结束。文件变为: diff --git a/docs/tutorial/02-code-tools.en.md b/docs/tutorial/02-code-tools.en.md index 72a99e1e..18e7c1a7 100644 --- a/docs/tutorial/02-code-tools.en.md +++ b/docs/tutorial/02-code-tools.en.md @@ -75,7 +75,7 @@ In its next response the model proposes the change. `old_string` is the original } ``` -After writing the file, `Edit` returns `The file /example/src/app.ts has been updated successfully.`, and the file content becomes `export const value = 2`. The two calls belong to two separate model responses: the model sees the result of `Read` first, and only then can it write an `old_string` that matches the file. +After writing the file, `Edit` returns `The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back.`, and the file content becomes `export const value = 2`. The two calls belong to two separate model responses: the model sees the result of `Read` first, and only then can it write an `old_string` that matches the file. ## Mapping to the DreamCoder source @@ -128,7 +128,7 @@ If the model skips `Read` and proposes `toolu_edit_2` directly, the result is: } ``` -If `old_string` includes the line-number prefix (for example `1\texport const value = 1`), the text cannot be found in the file, and an error is also returned at this step. +If `old_string` includes the line-number prefix (for example `1\texport const value = 1`), the exact text is not in the file; when every line carries the prefix, Edit strips it and searches again, goes ahead if that finds exactly one match, and otherwise returns an error at this step. ### Step 4: permission decision diff --git a/docs/tutorial/02-code-tools.zh.md b/docs/tutorial/02-code-tools.zh.md index 0ee392dd..1d3ad94f 100644 --- a/docs/tutorial/02-code-tools.zh.md +++ b/docs/tutorial/02-code-tools.zh.md @@ -75,7 +75,7 @@ async function runTool(use, tools, context) { } ``` -`Edit` 写入文件后返回 `The file /example/src/app.ts has been updated successfully.`,文件内容变为 `export const value = 2`。两次调用分属两次模型响应:模型先看到 `Read` 的结果,才能写出与文件一致的 `old_string`。 +`Edit` 写入文件后返回 `The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back.`,文件内容变为 `export const value = 2`。两次调用分属两次模型响应:模型先看到 `Read` 的结果,才能写出与文件一致的 `old_string`。 ## 对应到 DreamCoder 源码 @@ -128,7 +128,7 @@ if (isValidCall?.result === false) { } ``` -`old_string` 带上了行号前缀(例如 `1\texport const value = 1`)时,文件中找不到这段文本,也会在这一步返回错误。 +`old_string` 带上了行号前缀(例如 `1\texport const value = 1`)时,精确匹配找不到这段文本;如果每一行都带前缀,Edit 会去掉前缀再找,只找到一处就照常修改,否则在这一步返回错误。 ### 第 4 步:权限决定 diff --git a/docs/tutorial/04-session-context.en.md b/docs/tutorial/04-session-context.en.md index c69c3304..e7c33be7 100644 --- a/docs/tutorial/04-session-context.en.md +++ b/docs/tutorial/04-session-context.en.md @@ -56,7 +56,7 @@ The example is the one from the earlier chapters: the user asks to change `value {"type":"assistant","uuid":"a1","parentUuid":"u1","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_read_1","name":"Read","input":{"file_path":"/example/src/app.ts"}}]}} {"type":"user","uuid":"u2","parentUuid":"a1","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_read_1","content":"1\texport const value = 1"}]}} {"type":"assistant","uuid":"a2","parentUuid":"u2","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_edit_2","name":"Edit","input":{"file_path":"/example/src/app.ts","old_string":"export const value = 1","new_string":"export const value = 2"}}]}} -{"type":"user","uuid":"u3","parentUuid":"a2","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_edit_2","content":"The file /example/src/app.ts has been updated successfully."}]}} +{"type":"user","uuid":"u3","parentUuid":"a2","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_edit_2","content":"The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back."}]}} {"type":"assistant","uuid":"a3","parentUuid":"u3","message":{"role":"assistant","content":[{"type":"text","text":"Changed value to 2."}]}} ``` diff --git a/docs/tutorial/04-session-context.zh.md b/docs/tutorial/04-session-context.zh.md index 14798fc3..06148bc6 100644 --- a/docs/tutorial/04-session-context.zh.md +++ b/docs/tutorial/04-session-context.zh.md @@ -56,7 +56,7 @@ async function request(history, file) { // 第 3 步 {"type":"assistant","uuid":"a1","parentUuid":"u1","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_read_1","name":"Read","input":{"file_path":"/example/src/app.ts"}}]}} {"type":"user","uuid":"u2","parentUuid":"a1","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_read_1","content":"1\texport const value = 1"}]}} {"type":"assistant","uuid":"a2","parentUuid":"u2","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_edit_2","name":"Edit","input":{"file_path":"/example/src/app.ts","old_string":"export const value = 1","new_string":"export const value = 2"}}]}} -{"type":"user","uuid":"u3","parentUuid":"a2","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_edit_2","content":"The file /example/src/app.ts has been updated successfully."}]}} +{"type":"user","uuid":"u3","parentUuid":"a2","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_edit_2","content":"The file /example/src/app.ts has been updated successfully. The result is already in your context, so there is no need to read the file back."}]}} {"type":"assistant","uuid":"a3","parentUuid":"u3","message":{"role":"assistant","content":[{"type":"text","text":"已将 value 改为 2。"}]}} ``` diff --git a/docs/tutorial/06-desktop-integration.en.md b/docs/tutorial/06-desktop-integration.en.md index ee2ccee3..2a63af52 100644 --- a/docs/tutorial/06-desktop-integration.en.md +++ b/docs/tutorial/06-desktop-integration.en.md @@ -155,7 +155,7 @@ CLI output returns to the Sidecar over `/sdk/:sessionId`. [`handleSdkPayload()`] | CLI message | UI event | | --- | --- | | Text deltas in `stream_event` | `content_delta` | -| A complete `tool_use` content block (from the `content_block_stop` streaming event, or from an `assistant` message) | `tool_use_complete`, with the tool name, `toolUseId` and arguments | +| A complete `tool_use` content block in an `assistant` message | `tool_use_complete`, with the tool name, `toolUseId` and arguments | | A `user` message carrying `tool_result` | `tool_result`, with `toolUseId`, content and `isError`; the UI uses these to match it to the call shown earlier. [source](https://github.com/GoDiao/dreamcoder/blob/dba5b24c75be4e3c35cd42d082dc9a7f8b631087/src/server/ws/handler.ts#L1075) | | `control_request` (`can_use_tool`) | `permission_request`; see [Part 3](./03-permissions.en.md) | | `result` | `message_complete`; when execution fails, an `error` may come before it. [source](https://github.com/GoDiao/dreamcoder/blob/dba5b24c75be4e3c35cd42d082dc9a7f8b631087/src/server/ws/handler.ts#L1229) | diff --git a/docs/tutorial/06-desktop-integration.zh.md b/docs/tutorial/06-desktop-integration.zh.md index 6a5579eb..e2c213a4 100644 --- a/docs/tutorial/06-desktop-integration.zh.md +++ b/docs/tutorial/06-desktop-integration.zh.md @@ -155,7 +155,7 @@ CLI 的输出经 `/sdk/:sessionId` 回到 Sidecar,[`handleSdkPayload()`](https | CLI 消息 | 界面事件 | | --- | --- | | `stream_event` 中的文本增量 | `content_delta` | -| 完整的 `tool_use` 内容块(来自流式事件的 `content_block_stop`,或 `assistant` 消息) | `tool_use_complete`,带工具名称、`toolUseId` 和参数 | +| `assistant` 消息里完整的 `tool_use` 内容块 | `tool_use_complete`,带工具名称、`toolUseId` 和参数 | | 带 `tool_result` 的 `user` 消息 | `tool_result`,带 `toolUseId`、内容和 `isError`,界面据此对应此前显示的调用。[源码](https://github.com/GoDiao/dreamcoder/blob/dba5b24c75be4e3c35cd42d082dc9a7f8b631087/src/server/ws/handler.ts#L1075) | | `control_request`(`can_use_tool`) | `permission_request`,见[第三篇](./03-permissions.zh.md) | | `result` | `message_complete`;执行出错时,前面可能还有一条 `error`。[源码](https://github.com/GoDiao/dreamcoder/blob/dba5b24c75be4e3c35cd42d082dc9a7f8b631087/src/server/ws/handler.ts#L1229) | diff --git a/package.json b/package.json index 6aac8531..f8922495 100644 --- a/package.json +++ b/package.json @@ -110,6 +110,7 @@ }, "devDependencies": { "@types/bun": "^1.3.14", + "@types/lodash-es": "^4.17.12", "typescript": "^6.0.3" } } diff --git a/src/Tool.ts b/src/Tool.ts index 205cac09..b7e257f0 100644 --- a/src/Tool.ts +++ b/src/Tool.ts @@ -251,6 +251,7 @@ export type ToolUseContext = { fileReadingLimits?: { maxTokens?: number maxSizeBytes?: number + failWhenOverLimit?: boolean } globLimits?: { maxResults?: number @@ -480,6 +481,8 @@ export type Tool< */ backfillObservableInput?(input: Record): void + resolveApprovalInput?(input: Record): void + /** * Determines if this tool is allowed to run with this input in the current context. * It informs the model of why the tool use failed, and does not directly display any UI. diff --git a/src/components/FileEditToolDiff.tsx b/src/components/FileEditToolDiff.tsx index 6b4896d8..5aa31157 100644 --- a/src/components/FileEditToolDiff.tsx +++ b/src/components/FileEditToolDiff.tsx @@ -5,7 +5,7 @@ import { Suspense, use, useState } from 'react'; import { useTerminalSize } from '../hooks/useTerminalSize.js'; import { Box, Text } from '../ink.js'; import type { FileEdit } from '../tools/FileEditTool/types.js'; -import { findActualString, preserveQuoteStyle } from '../tools/FileEditTool/utils.js'; +import { matchEdit } from '../tools/FileEditTool/matchEdit.js'; import { adjustHunkLineNumbers, CONTEXT_LINES, getPatchForDisplay } from '../utils/diff.js'; import { logError } from '../utils/log.js'; import { CHUNK_SIZE, openForScan, readCapped, scanForContext } from '../utils/readEditContext.js'; @@ -170,12 +170,11 @@ function diffToolInputsOnly(filePath: string, edits: FileEdit[]): DiffData { }; } function normalizeEdit(fileContent: string, edit: FileEdit): FileEdit { - const actualOld = findActualString(fileContent, edit.old_string) || edit.old_string; - const actualNew = preserveQuoteStyle(edit.old_string, actualOld, edit.new_string); + const match = matchEdit(fileContent, edit.old_string, edit.new_string, edit.replace_all); return { ...edit, - old_string: actualOld, - new_string: actualNew + old_string: match.oldString, + new_string: match.newString }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJTdHJ1Y3R1cmVkUGF0Y2hIdW5rIiwiUmVhY3QiLCJTdXNwZW5zZSIsInVzZSIsInVzZVN0YXRlIiwidXNlVGVybWluYWxTaXplIiwiQm94IiwiVGV4dCIsIkZpbGVFZGl0IiwiZmluZEFjdHVhbFN0cmluZyIsInByZXNlcnZlUXVvdGVTdHlsZSIsImFkanVzdEh1bmtMaW5lTnVtYmVycyIsIkNPTlRFWFRfTElORVMiLCJnZXRQYXRjaEZvckRpc3BsYXkiLCJsb2dFcnJvciIsIkNIVU5LX1NJWkUiLCJvcGVuRm9yU2NhbiIsInJlYWRDYXBwZWQiLCJzY2FuRm9yQ29udGV4dCIsImZpcnN0TGluZU9mIiwiU3RydWN0dXJlZERpZmZMaXN0IiwiUHJvcHMiLCJmaWxlX3BhdGgiLCJlZGl0cyIsIkRpZmZEYXRhIiwicGF0Y2giLCJmaXJzdExpbmUiLCJmaWxlQ29udGVudCIsIkZpbGVFZGl0VG9vbERpZmYiLCJwcm9wcyIsIiQiLCJfYyIsInQwIiwibG9hZERpZmZEYXRhIiwiZGF0YVByb21pc2UiLCJ0MSIsIlN5bWJvbCIsImZvciIsInQyIiwiRGlmZkJvZHkiLCJwcm9taXNlIiwiY29sdW1ucyIsIkRpZmZGcmFtZSIsImNoaWxkcmVuIiwicGxhY2Vob2xkZXIiLCJQcm9taXNlIiwidmFsaWQiLCJmaWx0ZXIiLCJlIiwib2xkX3N0cmluZyIsIm5ld19zdHJpbmciLCJzaW5nbGUiLCJsZW5ndGgiLCJ1bmRlZmluZWQiLCJkaWZmVG9vbElucHV0c09ubHkiLCJoYW5kbGUiLCJmaWxlIiwibm9ybWFsaXplZCIsIm1hcCIsIm5vcm1hbGl6ZUVkaXQiLC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sRUFDZnNCLFNBQVMsRUFDVEQsSUFBSSxDQUFDcEIsVUFDUCxDQUFDO0VBQ0QsT0FBTztJQUFFLEdBQUdvQixJQUFJO0lBQUVyQixVQUFVLEVBQUVzQixTQUFTO0lBQUVyQixVQUFVLEVBQUVzQjtFQUFVLENBQUM7QUFDbEUiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/src/components/messages/AttachmentMessage.tsx b/src/components/messages/AttachmentMessage.tsx index efbb758e..cb2bb69e 100644 --- a/src/components/messages/AttachmentMessage.tsx +++ b/src/components/messages/AttachmentMessage.tsx @@ -143,7 +143,7 @@ export function AttachmentMessage({ } return Read {attachment.displayPath} ( - {attachment.content.type === 'text' ? `${attachment.content.file.numLines}${attachment.truncated ? '+' : ''} lines` : formatFileSize(attachment.content.file.originalSize)} + {attachment.content.type === 'text' ? `${attachment.content.file.numLines}${attachment.content.file.truncated ? '+' : ''} lines` : formatFileSize(attachment.content.file.originalSize)} ) ; case 'compact_file_reference': diff --git a/src/server/__tests__/artifact-edit-locks.test.ts b/src/server/__tests__/artifact-edit-locks.test.ts index 7067e6d6..b0432e36 100644 --- a/src/server/__tests__/artifact-edit-locks.test.ts +++ b/src/server/__tests__/artifact-edit-locks.test.ts @@ -2,13 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, jest, mock, spyOn } from ' import * as fs from 'node:fs/promises' import * as os from 'node:os' import * as path from 'node:path' -import type { ToolUseContext } from '../../Tool.js' -import { getDefaultAppState } from '../../state/AppStateStore.js' import { FileEditTool } from '../../tools/FileEditTool/FileEditTool.js' import { FileReadTool } from '../../tools/FileReadTool/FileReadTool.js' import { FileWriteTool } from '../../tools/FileWriteTool/FileWriteTool.js' +import { agentContext, allow, turn } from '../../tools/testing/agentContext.js' import { ARTIFACT_EDIT_LOCKS_ENV } from '../../utils/artifactEditLock.js' -import { createFileStateCacheWithSizeLimit } from '../../utils/fileStateCache.js' import { setHostRequester } from '../../utils/hostRequests.js' import { artifactEditLocks, createArtifactEditLocks, type ArtifactEditLocks } from '../services/artifactEditLocks.js' import { conversationService } from '../services/conversationService.js' @@ -35,25 +33,6 @@ const publish = (sessionId: string, event: SessionStateEvent) => { const store = { apply: publish, applyIfPresent: publish } const waits = () => published.map(({ sessionId, event }) => (event.type === 'artifact_wait_changed' ? [sessionId, event.wait] : null)).filter(Boolean) -const allow = (async () => ({ behavior: 'allow' })) as unknown as Parameters[2] -const turn = { uuid: 'turn-1' } as unknown as Parameters[3] - -function agentContext(abortController = new AbortController()): ToolUseContext { - const appState = getDefaultAppState() - let fileHistory = appState.fileHistory - return { - updateFileHistoryState: (update: (state: typeof fileHistory) => typeof fileHistory) => { - fileHistory = update(fileHistory) - }, - readFileState: createFileStateCacheWithSizeLimit(100), - abortController, - getAppState: () => appState, - setAppState: () => {}, - options: { tools: [], commands: [], mcpClients: [], agentDefinitions: { activeAgents: [], allAgents: [] }, isNonInteractiveSession: true }, - messages: [], - } as unknown as ToolUseContext -} - function useLocksAsHost() { setHostRequester(async (request: Record, _schema: unknown, signal?: AbortSignal) => { const requestId = crypto.randomUUID() @@ -233,7 +212,7 @@ describe('an agent writing into an artifact the user is editing', () => { useLocksAsHost() await locks.hold(deckDir, 'tab') const abort = new AbortController() - const writing = FileWriteTool.call({ file_path: slidePath('agenda'), content: 'x' }, agentContext(abort), allow, turn) + const writing = FileWriteTool.call({ file_path: slidePath('agenda'), content: 'x' }, agentContext({ abortController: abort }), allow, turn) expect(await settled(writing)).toBe(false) abort.abort() await expect(writing).rejects.toThrow('aborted') diff --git a/src/server/__tests__/deckEditNotice.test.ts b/src/server/__tests__/deckEditNotice.test.ts index d73bffb0..2891edee 100644 --- a/src/server/__tests__/deckEditNotice.test.ts +++ b/src/server/__tests__/deckEditNotice.test.ts @@ -4,14 +4,13 @@ import * as fs from 'node:fs/promises' import * as os from 'node:os' import * as path from 'node:path' import type { ToolUseContext } from '../../Tool.js' -import { getDefaultAppState } from '../../state/AppStateStore.js' import { FileEditTool } from '../../tools/FileEditTool/FileEditTool.js' import { FileReadTool } from '../../tools/FileReadTool/FileReadTool.js' import { FileWriteTool } from '../../tools/FileWriteTool/FileWriteTool.js' +import { agentContext, allow, turn } from '../../tools/testing/agentContext.js' import type { Message } from '../../types/message.js' import { getChangedFiles } from '../../utils/attachments.js' import { DECK_ENTRY_HTML } from '../../utils/deck.js' -import { createFileStateCacheWithSizeLimit } from '../../utils/fileStateCache.js' import { extractReadFilesFromMessages } from '../../utils/queryHelpers.js' import { sanitizePath } from '../../utils/sessionStoragePortable.js' import { ArtifactService } from '../services/artifactService.js' @@ -26,25 +25,6 @@ let service: ArtifactService const manifest = { version: 1, id: 'id-talk', kind: 'deck', title: 'Talk', entry: 'index.html', slides: ['cover', 'agenda', 'close'] } const slide = (text: string) => `

${text}

\n` -function agentContext(): ToolUseContext { - const appState = getDefaultAppState() - let fileHistory = appState.fileHistory - return { - updateFileHistoryState: (update: (state: typeof fileHistory) => typeof fileHistory) => { - fileHistory = update(fileHistory) - }, - readFileState: createFileStateCacheWithSizeLimit(100), - abortController: new AbortController(), - getAppState: () => appState, - setAppState: () => {}, - options: { tools: [], commands: [], mcpClients: [], agentDefinitions: { activeAgents: [], allAgents: [] }, isNonInteractiveSession: true }, - messages: [], - } as unknown as ToolUseContext -} - -const allow = (async () => ({ behavior: 'allow' })) as unknown as Parameters[2] -const turn = { uuid: 'turn-1' } as unknown as Parameters[3] - const changedNames = async (context: ToolUseContext) => (await getChangedFiles(context)).map(attachment => ('filename' in attachment ? path.relative(deckDir, attachment.filename) : attachment.type)) beforeEach(async () => { diff --git a/src/server/__tests__/stream-retraction.test.ts b/src/server/__tests__/stream-retraction.test.ts index 0f602cb0..c0915fe0 100644 --- a/src/server/__tests__/stream-retraction.test.ts +++ b/src/server/__tests__/stream-retraction.test.ts @@ -18,8 +18,6 @@ describe('a stream the CLI retries', () => { expect(retracted.messages).toEqual([{ type: 'reply_retracted' }]) expect(retracted.events).toEqual([{ type: 'turn_activity_reported', activity: 'thinking' }]) expect(stream.activeBlockTypes.size).toBe(0) - expect(stream.activeToolBlocks.size).toBe(0) - expect(stream.streamedToolUseIds.size).toBe(0) expect(stream.hasReceivedStreamEvents).toBe(false) }) diff --git a/src/server/__tests__/ws-memory-events.test.ts b/src/server/__tests__/ws-memory-events.test.ts index 9a9c0009..4024bca3 100644 --- a/src/server/__tests__/ws-memory-events.test.ts +++ b/src/server/__tests__/ws-memory-events.test.ts @@ -475,7 +475,7 @@ describe('WebSocket goal command events', () => { }) describe('WebSocket stream event translation', () => { - it('keeps subagent parent linkage when later stream events omit the parent id', () => { + it('takes the tool input from the assistant message the CLI sends before the block stops', () => { const sessionId = `subagent-parent-${crypto.randomUUID()}` expect(translateCliMessage({ @@ -501,15 +501,15 @@ describe('WebSocket stream event translation', () => { event: { type: 'content_block_delta', index: 0, - delta: { type: 'input_json_delta', partial_json: '{"file_path":"src/App.tsx"}' }, + delta: { type: 'input_json_delta', partial_json: '{"file_path":"src/App.tsx","pages":""}' }, }, }, sessionId)).toEqual([ - { type: 'content_delta', toolInput: '{"file_path":"src/App.tsx"}' }, + { type: 'content_delta', toolInput: '{"file_path":"src/App.tsx","pages":""}' }, ]) expect(translateCliMessage({ - type: 'stream_event', - event: { type: 'content_block_stop', index: 0 }, + type: 'assistant', + message: { content: [{ type: 'tool_use', id: 'read-1', name: 'Read', input: { file_path: 'src/App.tsx' } }] }, }, sessionId)).toEqual([ { type: 'tool_use_complete', @@ -520,6 +520,11 @@ describe('WebSocket stream event translation', () => { }, ]) + expect(translateCliMessage({ + type: 'stream_event', + event: { type: 'content_block_stop', index: 0 }, + }, sessionId)).toEqual([]) + expect(translateCliMessage({ type: 'user', message: { diff --git a/src/server/session/translate.ts b/src/server/session/translate.ts index 97a7af7a..e410824e 100644 --- a/src/server/session/translate.ts +++ b/src/server/session/translate.ts @@ -19,10 +19,7 @@ import type { PendingPermission, SessionSlashCommand, SessionStateEvent } from ' export type SessionStreamState = { hasReceivedStreamEvents: boolean activeBlockTypes: Map - activeToolBlocks: Map pendingLocalCommand?: { name: string; args: string } - pendingToolBlocks: Map - streamedToolUseIds: Set toolParentUseIds: Map showUiToolUseIds: Set lastApiError?: { @@ -41,10 +38,7 @@ export function createStreamState(): SessionStreamState { return { hasReceivedStreamEvents: false, activeBlockTypes: new Map(), - activeToolBlocks: new Map(), pendingLocalCommand: undefined, - pendingToolBlocks: new Map(), - streamedToolUseIds: new Set(), toolParentUseIds: new Map(), showUiToolUseIds: new Set(), lastApiError: undefined, @@ -108,8 +102,8 @@ function replayedUserMessage(cliMsg: any): ServerMessage | null { return { type: 'user_message', id: cliMsg.uuid, content: text } } -function unstreamedToolUse(streamState: SessionStreamState, cliMsg: any, block: any): ServerMessage { - const parentToolUseId = cliParentToolUseId(cliMsg) +function completedToolUse(streamState: SessionStreamState, cliMsg: any, block: any): ServerMessage { + const parentToolUseId = cliParentToolUseId(cliMsg) ?? streamState.toolParentUseIds.get(block.id) rememberToolParentUseId(streamState, block.id, parentToolUseId) return { type: 'tool_use_complete', toolName: block.name, toolUseId: block.id, input: block.input, parentToolUseId } } @@ -195,19 +189,8 @@ function translateMessages( for (const block of cliMsg.message.content) { if (block.type === 'tool_use' && block.name === SHOW_UI_TOOL_NAME) streamState.showUiToolUseIds.add(block.id) if (streamState.hasReceivedStreamEvents) { - if (block.type === 'tool_use' && streamState.pendingToolBlocks.has(block.id)) { - const pending = streamState.pendingToolBlocks.get(block.id)! - streamState.pendingToolBlocks.delete(block.id) - rememberToolParentUseId(streamState, block.id, pending.parentToolUseId) - messages.push({ - type: 'tool_use_complete', - toolName: pending.toolName || block.name, - toolUseId: block.id, - input: block.input, - parentToolUseId: pending.parentToolUseId, - }) - } else if (block.type === 'tool_use' && !streamState.streamedToolUseIds.has(block.id)) { - messages.push(unstreamedToolUse(streamState, cliMsg, block)) + if (block.type === 'tool_use') { + messages.push(completedToolUse(streamState, cliMsg, block)) } } else { if (block.type === 'thinking' && block.thinking) { @@ -216,14 +199,12 @@ function translateMessages( messages.push({ type: 'content_start', blockType: 'text' }) messages.push({ type: 'content_delta', text: block.text }) } else if (block.type === 'tool_use') { - messages.push(unstreamedToolUse(streamState, cliMsg, block)) + messages.push(completedToolUse(streamState, cliMsg, block)) } } } streamState.hasReceivedStreamEvents = false - streamState.pendingToolBlocks.clear() - streamState.streamedToolUseIds.clear() if (typeof cliMsg.uuid === 'string' && hasTextBlock(cliMsg.message.content)) { messages.push({ type: 'message_id', id: cliMsg.uuid }) } @@ -311,13 +292,7 @@ function translateMessages( events.push({ type: 'turn_activity_reported', activity: 'tool' }) const parentToolUseId = cliParentToolUseId(cliMsg) streamState.activeBlockTypes.set(index, 'tool_use') - if (contentBlock.id) streamState.streamedToolUseIds.add(contentBlock.id) - streamState.activeToolBlocks.set(index, { - toolName: contentBlock.name || '', - toolUseId: contentBlock.id || '', - inputJson: '', - parentToolUseId, - }) + rememberToolParentUseId(streamState, contentBlock.id, parentToolUseId) return [{ type: 'content_start', blockType: 'tool_use', @@ -346,9 +321,6 @@ function translateMessages( return [{ type: 'content_delta', text: delta.text }] } if (delta.type === 'input_json_delta' && delta.partial_json) { - const index = event.index ?? 0 - const toolBlock = streamState.activeToolBlocks.get(index) - if (toolBlock) toolBlock.inputJson += delta.partial_json return [{ type: 'content_delta', toolInput: delta.partial_json }] } if (delta.type === 'thinking_delta' && delta.thinking) { @@ -358,40 +330,7 @@ function translateMessages( } case 'content_block_stop': { - const index = event.index ?? 0 - const blockType = streamState.activeBlockTypes.get(index) - streamState.activeBlockTypes.delete(index) - - if (blockType === 'tool_use') { - const toolBlock = streamState.activeToolBlocks.get(index) - streamState.activeToolBlocks.delete(index) - if (toolBlock) { - const parentToolUseId = - cliParentToolUseId(cliMsg) ?? toolBlock.parentToolUseId - let parsedInput = null - try { parsedInput = JSON.parse(toolBlock.inputJson) } catch {} - - if (parsedInput !== null) { - rememberToolParentUseId(streamState, toolBlock.toolUseId, parentToolUseId) - return [{ - type: 'tool_use_complete', - toolName: toolBlock.toolName, - toolUseId: toolBlock.toolUseId, - input: parsedInput, - parentToolUseId, - }] - } - - console.warn( - `[WS] Tool input JSON parse failed for ${toolBlock.toolName} (${toolBlock.toolUseId}), deferring to assistant message`, - ) - streamState.pendingToolBlocks.set(toolBlock.toolUseId, { - toolName: toolBlock.toolName, - toolUseId: toolBlock.toolUseId, - parentToolUseId, - }) - } - } + streamState.activeBlockTypes.delete(event.index ?? 0) return [] } @@ -466,9 +405,6 @@ function translateMessages( if (subtype === 'stream_retracted') { streamState.hasReceivedStreamEvents = false streamState.activeBlockTypes.clear() - streamState.activeToolBlocks.clear() - streamState.pendingToolBlocks.clear() - streamState.streamedToolUseIds.clear() events.push({ type: 'turn_activity_reported', activity: 'thinking' }) return [{ type: 'reply_retracted' }] } diff --git a/src/services/compact/compact.ts b/src/services/compact/compact.ts index e425d102..dcc9d48a 100644 --- a/src/services/compact/compact.ts +++ b/src/services/compact/compact.ts @@ -1449,6 +1449,7 @@ export async function createPostCompactFileAttachments( ...toolUseContext, fileReadingLimits: { maxTokens: POST_COMPACT_MAX_TOKENS_PER_FILE, + failWhenOverLimit: true, }, }, 'tengu_post_compact_file_restore_success', diff --git a/src/services/compact/postCompactFileRestore.test.ts b/src/services/compact/postCompactFileRestore.test.ts new file mode 100644 index 00000000..6fc3837a --- /dev/null +++ b/src/services/compact/postCompactFileRestore.test.ts @@ -0,0 +1,27 @@ +import { afterEach, beforeEach, expect, it, spyOn } from 'bun:test' +import * as fs from 'node:fs/promises' +import * as os from 'node:os' +import * as path from 'node:path' +import { agentContext } from '../../tools/testing/agentContext.js' +import * as tokenEstimation from '../tokenEstimation.js' +import { createPostCompactFileAttachments } from './compact.js' + +let dir: string +let countTokens: ReturnType> + +beforeEach(async () => { + dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'post-compact-restore-'))) + countTokens = spyOn(tokenEstimation, 'countTokensWithAPI').mockResolvedValue(null) +}) + +afterEach(async () => { + countTokens.mockRestore() + await fs.rm(dir, { recursive: true, force: true }) +}) + +it('refers to a file over the per-file limit instead of restoring part of it', async () => { + const filePath = path.join(dir, 'big.ts') + await fs.writeFile(filePath, Array.from({ length: 1000 }, (_, i) => `export const value${i} = ${i}`).join('\n')) + const [restored] = await createPostCompactFileAttachments({ [filePath]: { content: '', timestamp: 1 } }, agentContext(), 1) + expect(restored?.attachment).toMatchObject({ type: 'compact_file_reference', filename: filePath }) +}) diff --git a/src/services/tools/toolExecution.ts b/src/services/tools/toolExecution.ts index 22d107a1..765d65d3 100644 --- a/src/services/tools/toolExecution.ts +++ b/src/services/tools/toolExecution.ts @@ -1,4 +1,5 @@ import { feature } from 'bun:bundle' +import isEqual from 'lodash-es/isEqual.js' import type { ContentBlockParam, ToolResultBlockParam, @@ -802,19 +803,18 @@ async function checkPermissionsAndCallTool( // tools overwrite file_path with expandPath — that mutation must not reach // call() because tool results embed the input path verbatim (e.g. "File // created successfully at: {path}"), and changing it alters the serialized - // transcript and VCR fixture hashes. If a hook/permission later returns a - // fresh updatedInput, callInput converges on it below — that replacement - // is intentional and should reach call(). + // transcript and VCR fixture hashes. let callInput = processedInput - const backfilledClone = - tool.backfillObservableInput && + const observedInput = + (tool.backfillObservableInput || tool.resolveApprovalInput) && typeof processedInput === 'object' && processedInput !== null ? ({ ...processedInput } as typeof processedInput) : null - if (backfilledClone) { - tool.backfillObservableInput!(backfilledClone as Record) - processedInput = backfilledClone + if (observedInput) { + tool.backfillObservableInput?.(observedInput as Record) + tool.resolveApprovalInput?.(observedInput as Record) + processedInput = observedInput } let shouldPreventContinuation = false @@ -1203,29 +1203,7 @@ async function checkPermissionsAndCallTool( const startTime = Date.now() startSessionActivity('tool_exec') - // If processedInput still points at the backfill clone, no hook/permission - // replaced it — pass the pre-backfill callInput so call() sees the model's - // original field values. Otherwise converge on the hook-supplied input. - // Permission/hook flows may return a fresh object derived from the - // backfilled clone (e.g. via inputSchema.parse). If its file_path matches - // the backfill-expanded value, restore the model's original so the tool - // result string embeds the path the model emitted — keeps transcript/VCR - // hashes stable. Other hook modifications flow through unchanged. - if ( - backfilledClone && - processedInput !== callInput && - typeof processedInput === 'object' && - processedInput !== null && - 'file_path' in processedInput && - 'file_path' in (callInput as Record) && - (processedInput as Record).file_path === - (backfilledClone as Record).file_path - ) { - callInput = { - ...processedInput, - file_path: (callInput as Record).file_path, - } as typeof processedInput - } else if (processedInput !== backfilledClone) { + if (!observedInput || !isEqual(processedInput, observedInput)) { callInput = processedInput } try { diff --git a/src/tools/FileEditTool/FileEditTool.test.ts b/src/tools/FileEditTool/FileEditTool.test.ts new file mode 100644 index 00000000..522a6147 --- /dev/null +++ b/src/tools/FileEditTool/FileEditTool.test.ts @@ -0,0 +1,239 @@ +import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import * as fs from 'node:fs/promises' +import * as os from 'node:os' +import * as path from 'node:path' +import type { CanUseToolFn } from '../../hooks/useCanUseTool.js' +import { runToolUse } from '../../services/tools/toolExecution.js' +import type { ToolUseContext } from '../../Tool.js' +import { normalizeToolInput } from '../../utils/api.js' +import { createAssistantMessage } from '../../utils/messages.js' +import { FileReadTool } from '../FileReadTool/FileReadTool.js' +import { FileWriteTool } from '../FileWriteTool/FileWriteTool.js' +import { agentContext, allow, turn } from '../testing/agentContext.js' +import { NO_READ_BACK_NOTE } from './constants.js' +import { FileEditTool } from './FileEditTool.js' +import type { FileEditOutput } from './types.js' + +let dir: string +let context: ToolUseContext + +beforeEach(async () => { + dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'edit-matching-'))) + context = agentContext() +}) + +afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }) +}) + +async function readFile(name: string, content: string): Promise { + const filePath = path.join(dir, name) + await fs.writeFile(filePath, content) + await FileReadTool.call({ file_path: filePath }, context) + return filePath +} + +async function edit(filePath: string, oldString: string, newString: string, replaceAll = false) { + const input = { file_path: filePath, old_string: oldString, new_string: newString, replace_all: replaceAll } + const validation = await FileEditTool.validateInput(input, context) + if (!validation.result) return validation + const { data } = await FileEditTool.call(input, context, allow, turn) + return { result: true as const, text: String(FileEditTool.mapToolResultToToolResultBlockParam(data, 'tool-1').content) } +} + +describe('Edit with an old_string that differs from the file in form', () => { + it('fixes indentation in a CRLF file and keeps its line endings', async () => { + const filePath = await readFile('main.go', 'func f() {\r\n\tif x {\r\n\t\treturn 1\r\n\t}\r\n}\r\n') + const outcome = await edit(filePath, ' if x {\n return 1\n }', ' if y {\n return 2\n }') + expect(outcome.result).toBe(true) + expect(await fs.readFile(filePath, 'utf8')).toBe('func f() {\r\n\tif y {\r\n\t\treturn 2\r\n\t}\r\n}\r\n') + }) + + it('accepts line number prefixes copied from a read', async () => { + const filePath = await readFile('a.py', 'def f():\n return 1\n') + const outcome = await edit(filePath, '1\tdef f():\n2\t return 1', '1\tdef f():\n2\t return 2') + expect(outcome.result).toBe(true) + expect(await fs.readFile(filePath, 'utf8')).toBe('def f():\n return 2\n') + }) + + it('accepts whitespace missing from the end of lines', async () => { + const filePath = await readFile('notes.txt', 'alpha \nbeta\n') + const outcome = await edit(filePath, 'alpha\nbeta', 'alpha\ngamma') + expect(outcome.result).toBe(true) + expect(await fs.readFile(filePath, 'utf8')).toBe('alpha\ngamma\n') + }) + + it('accepts escapes written out', async () => { + const filePath = await readFile('a.js', 'log("a")\nlog("b")\n') + const outcome = await edit(filePath, 'log(\\"a\\")\\nlog(\\"b\\")', 'log(\\"c\\")') + expect(outcome.result).toBe(true) + expect(await fs.readFile(filePath, 'utf8')).toBe('log("c")\n') + }) + + it('replaces every occurrence when line number prefixes come with replace_all', async () => { + const filePath = await readFile('a.txt', 'x = 1\ny = 2\nx = 1\n') + const outcome = await edit(filePath, '1\tx = 1', '1\tx = 0', true) + expect(outcome.result).toBe(true) + expect(await fs.readFile(filePath, 'utf8')).toBe('x = 0\ny = 2\nx = 0\n') + }) + + it('reports several candidates with the existing message and leaves the file alone', async () => { + const content = ' a()\n b()\n a()\n b()\n' + const filePath = await readFile('a.txt', content) + const outcome = await edit(filePath, ' a()\n b()', 'c()') + expect(outcome).toMatchObject({ + result: false, + errorCode: 9, + message: + 'Found 2 matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: a()\n b()', + }) + expect(await fs.readFile(filePath, 'utf8')).toBe(content) + }) + + it('refuses to edit when the matched lines also occur as text earlier in the file', async () => { + const content = 'xa\nbz\na\nb\n' + const filePath = await readFile('a.txt', content) + const outcome = await edit(filePath, 'a \nb', 'c') + expect(outcome).toMatchObject({ result: false, errorCode: 9 }) + expect(await fs.readFile(filePath, 'utf8')).toBe(content) + }) + + it('reports indentation without one mapping as not found with the existing message', async () => { + const content = 'if a:\n if b:\n return 1\n' + const filePath = await readFile('a.py', content) + const outcome = await edit(filePath, ' if b:\n return 1', ' if b:\n return 2') + expect(outcome).toMatchObject({ result: false, errorCode: 8, message: 'String to replace not found in file.\nString: if b:\n return 1' }) + expect(await fs.readFile(filePath, 'utf8')).toBe(content) + }) +}) + +describe('the Edit input the user approves', () => { + const approved = (input: Record) => { + const observed = { ...input } + FileEditTool.backfillObservableInput!(observed) + FileEditTool.resolveApprovalInput!(observed) + return observed + } + + it('is not matched against the file while the reply streams in', async () => { + const filePath = await readFile('a.py', 'def f():\n return 1\n') + const input = { file_path: filePath, old_string: '\treturn 1', new_string: '\treturn 2', replace_all: false } + const streamed = { ...input } + FileEditTool.backfillObservableInput!(streamed) + expect(streamed).toEqual(input) + }) + + it('shows the text that will be written', async () => { + const filePath = await readFile('main.go', 'func f() {\n\tif x {\n\t\treturn 1\n\t}\n}\n') + const input = { file_path: filePath, old_string: ' if x {\n return 1\n }', new_string: ' if y {\n return 2\n }', replace_all: false } + expect(approved(input)).toEqual({ file_path: filePath, old_string: '\tif x {\n\t\treturn 1\n\t}', new_string: '\tif y {\n\t\treturn 2\n\t}', replace_all: false }) + }) + + it('shows written-out escapes as the characters that will be written', async () => { + const filePath = await readFile('build.sh', 'echo "done"\n') + const input = { file_path: filePath, old_string: 'echo \\"done\\"', new_string: '# echo \\"done\\"\\nrm -rf build', replace_all: false } + expect(approved(input)).toMatchObject({ old_string: 'echo "done"', new_string: '# echo "done"\nrm -rf build' }) + }) + + it('shows every occurrence rewritten with replace_all', async () => { + const filePath = await readFile('a.txt', 'x = 1\ny = 2\nx = 1\n') + const input = { file_path: filePath, old_string: '1\tx = 1', new_string: '1\tx = 0', replace_all: true } + expect(approved(input)).toMatchObject({ old_string: 'x = 1', new_string: 'x = 0' }) + }) + + it('leaves it alone when it matches several places', async () => { + const filePath = await readFile('a.txt', ' a()\n b()\n a()\n b()\n') + const input = { file_path: filePath, old_string: ' a()\n b()', new_string: 'c()', replace_all: false } + expect(approved(input)).toEqual(input) + }) + + it('matches each edit against the file as the earlier edits of the same reply left it', async () => { + const filePath = await readFile('a.ts', 'class Old {\n total(xs) {\n return sum(xs)\n }\n}\nclass Box {\n}\n') + const copy = { file_path: filePath, old_string: 'class Box {\n}', new_string: 'class Box {\n total(xs) {\n return sum(xs)\n }\n}', replace_all: false } + const change = { file_path: filePath, old_string: ' total(xs) {\n return sum(xs)\n }', new_string: ' total(xs) {\n return sum(xs) * 2\n }', replace_all: false } + const received = [copy, change].map(input => normalizeToolInput(FileEditTool, input)) + for (const input of received) { + expect(await edit(input.file_path, input.old_string, input.new_string)).toMatchObject({ result: true }) + } + expect(await fs.readFile(filePath, 'utf8')).toBe('class Old {\n total(xs) {\n return sum(xs)\n }\n}\nclass Box {\n total(xs) {\n return sum(xs) * 2\n }\n}\n') + }) +}) + +describe('an Edit carried out by the tool runner', () => { + type Decide = (observed: Record) => Record | undefined + + async function runEdit(input: Record, decide: Decide, userModified = false) { + const toolUse = { type: 'tool_use', id: 'toolu_1', name: FileEditTool.name, input } + const assistant = createAssistantMessage({ content: [toolUse as never] }) as Parameters[1] + const approvals: Record[] = [] + const canUseTool = (async (_tool: unknown, observed: Record) => { + approvals.push({ ...observed }) + return { behavior: 'allow', updatedInput: decide(observed), userModified } + }) as unknown as CanUseToolFn + const runContext = { ...context, options: { ...context.options, tools: [FileEditTool, FileReadTool] } } as ToolUseContext + const texts: string[] = [] + for await (const update of runToolUse(toolUse as never, assistant, canUseTool, runContext)) { + const content = (update.message as { message?: { content?: unknown } } | undefined)?.message?.content + if (Array.isArray(content)) { + for (const block of content as Array<{ type: string; content?: unknown }>) { + if (block.type === 'tool_result') texts.push(String(block.content)) + } + } + } + return { approvals, text: texts.join('\n') } + } + + it.each<[string, Decide]>([ + ['as shown', () => undefined], + ['through a fresh copy of what was shown', observed => ({ ...observed })], + ])('writes the shown text and leaves the note out when it differs from new_string, approved %s', async (_how, decide) => { + const filePath = await readFile('a.py', 'def f():\n return 1\n') + const outcome = await runEdit({ file_path: filePath, old_string: '\treturn 1', new_string: '\treturn 2', replace_all: false }, decide) + expect(outcome.approvals).toEqual([expect.objectContaining({ old_string: ' return 1', new_string: ' return 2' })]) + expect(await fs.readFile(filePath, 'utf8')).toBe('def f():\n return 2\n') + expect(outcome.text).toBe(`The file ${filePath} has been updated successfully.`) + }) + + it.each<[string, Decide, string]>([ + ['new_string', observed => ({ ...observed, new_string: ' return 3' }), 'def f():\n return 3\n'], + ['old_string', observed => ({ ...observed, old_string: 'return 1' }), 'def f():\n return 2\n'], + ])('writes the edit as the user approved it after changing its %s', async (_field, decide, written) => { + const filePath = await readFile('a.py', 'def f():\n return 1\n') + const outcome = await runEdit({ file_path: filePath, old_string: ' return 1', new_string: ' return 2', replace_all: false }, decide, true) + expect(outcome.approvals).toEqual([expect.objectContaining({ old_string: ' return 1', new_string: ' return 2' })]) + expect(await fs.readFile(filePath, 'utf8')).toBe(written) + expect(outcome.text).not.toContain(NO_READ_BACK_NOTE) + }) +}) + +describe('what Edit and Write say after they succeed', () => { + const edited: FileEditOutput = { filePath: '/repo/a.ts', oldString: 'a', newString: 'b', originalFile: 'a', structuredPatch: [], userModified: false, replaceAll: false } + const editText = (data: FileEditOutput) => String(FileEditTool.mapToolResultToToolResultBlockParam(data, 'tool-1').content) + + it('tells the model not to read the file back after an edit', async () => { + const filePath = await readFile('a.txt', 'one\ntwo\n') + expect(await edit(filePath, 'one', 'uno')).toEqual({ result: true, text: `The file ${filePath} has been updated successfully. ${NO_READ_BACK_NOTE}` }) + expect(editText({ ...edited, replaceAll: true })).toBe(`The file /repo/a.ts has been updated. All occurrences were successfully replaced. ${NO_READ_BACK_NOTE}`) + }) + + it('leaves the note out when the written text differs from new_string', async () => { + const filePath = await readFile('a.py', 'def f():\n return 1\n') + const outcome = await edit(filePath, 'def f():\n\treturn 1', 'def f():\n\treturn 2') + expect(await fs.readFile(filePath, 'utf8')).toBe('def f():\n return 2\n') + expect(outcome).toEqual({ result: true, text: `The file ${filePath} has been updated successfully.` }) + }) + + it('leaves the note out when the user changed the edit before accepting it', () => { + expect(editText({ ...edited, userModified: true })).not.toContain(NO_READ_BACK_NOTE) + }) + + it('tells the model not to read the file back after a write', async () => { + const filePath = path.join(dir, 'new.txt') + const writeText = async (content: string) => { + const { data } = await FileWriteTool.call({ file_path: filePath, content }, context, allow, turn) + return String(FileWriteTool.mapToolResultToToolResultBlockParam(data, 'tool-1').content) + } + expect(await writeText('first\n')).toBe(`File created successfully at: ${filePath}. ${NO_READ_BACK_NOTE}`) + expect(await writeText('second\n')).toBe(`The file ${filePath} has been updated successfully. ${NO_READ_BACK_NOTE}`) + }) +}) diff --git a/src/tools/FileEditTool/FileEditTool.ts b/src/tools/FileEditTool/FileEditTool.ts index 2cc09a58..f0526628 100644 --- a/src/tools/FileEditTool/FileEditTool.ts +++ b/src/tools/FileEditTool/FileEditTool.ts @@ -22,6 +22,7 @@ import { FILE_NOT_FOUND_CWD_NOTE, findSimilarFile, getFileModificationTime, + readFileSyncCached, suggestPathUnderCwd, writeTextContent, } from '../../utils/file.js' @@ -53,6 +54,7 @@ import { NOTEBOOK_EDIT_TOOL_NAME } from '../NotebookEditTool/constants.js' import { FILE_EDIT_TOOL_NAME, FILE_UNEXPECTEDLY_MODIFIED_ERROR, + NO_READ_BACK_NOTE, } from './constants.js' import { getEditToolDescription } from './prompt.js' import { @@ -69,12 +71,8 @@ import { renderToolUseRejectedMessage, userFacingName, } from './UI.js' -import { - areFileEditsInputsEquivalent, - findActualString, - getPatchForEdit, - preserveQuoteStyle, -} from './utils.js' +import { matchEdit } from './matchEdit.js' +import { areFileEditsInputsEquivalent, getPatchForEdit } from './utils.js' import { refuseWriteAfterUserEdits } from '../../utils/artifactEditLock.js' // V8/Bun string length limit is ~2^30 characters (~1 billion). For typical @@ -120,6 +118,7 @@ export const FileEditTool = buildTool({ input.file_path = expandPath(input.file_path) } }, + resolveApprovalInput: showMatchedStrings, async preparePermissionMatcher({ file_path }) { return pattern => matchWildcardPattern(pattern, file_path) }, @@ -313,9 +312,8 @@ export const FileEditTool = buildTool({ const file = fileContent - // Use findActualString to handle quote normalization - const actualOldString = findActualString(file, old_string) - if (!actualOldString) { + const match = matchEdit(file, old_string, new_string, replace_all) + if (match.matches === 0) { return { result: false, behavior: 'ask', @@ -327,17 +325,14 @@ export const FileEditTool = buildTool({ } } - const matches = file.split(actualOldString).length - 1 - - // Check if we have multiple matches but replace_all is false - if (matches > 1 && !replace_all) { + if (match.matches > 1 && !replace_all) { return { result: false, behavior: 'ask', - message: `Found ${matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${old_string}`, + message: `Found ${match.matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${old_string}`, meta: { isFilePathAbsolute: String(isAbsolute(file_path)), - actualOldString, + actualOldString: match.oldString, }, errorCode: 9, } @@ -350,8 +345,8 @@ export const FileEditTool = buildTool({ () => { // Simulate the edit to get the final content using the exact same logic as the tool return replace_all - ? file.replaceAll(actualOldString, new_string) - : file.replace(actualOldString, new_string) + ? file.replaceAll(match.oldString, match.newString) + : file.replace(match.oldString, match.newString) }, ) @@ -359,7 +354,7 @@ export const FileEditTool = buildTool({ return settingsValidationResult } - return { result: true, meta: { actualOldString } } + return { result: true, meta: { actualOldString: match.oldString } } }, inputsEquivalent(input1, input2) { return areFileEditsInputsEquivalent( @@ -470,16 +465,8 @@ export const FileEditTool = buildTool({ } } - // 3. Use findActualString to handle quote normalization - const actualOldString = - findActualString(originalFileContents, old_string) || old_string - - // Preserve curly quotes in new_string when the file uses them - const actualNewString = preserveQuoteStyle( - old_string, - actualOldString, - new_string, - ) + const { oldString: actualOldString, newString: actualNewString } = + matchEdit(originalFileContents, old_string, new_string, replace_all) // 4. Generate patch const { patch, updatedFile } = getPatchForEdit({ @@ -520,11 +507,13 @@ export const FileEditTool = buildTool({ notifyVscodeFileUpdated(absoluteFilePath, originalFileContents, updatedFile) // 6. Update read timestamp, to invalidate stale writes + const truncated = readFileState.get(absoluteFilePath)?.truncated readFileState.set(absoluteFilePath, { content: updatedFile, timestamp: getFileModificationTime(absoluteFilePath), offset: undefined, limit: undefined, + ...(truncated && { truncated }), }) // 7. Log events @@ -569,6 +558,7 @@ export const FileEditTool = buildTool({ structuredPatch: patch, userModified: userModified ?? false, replaceAll: replace_all, + ...(actualNewString !== new_string && { matchAdjusted: true }), ...(gitDiff && { gitDiff }), } return { @@ -576,29 +566,57 @@ export const FileEditTool = buildTool({ } }, mapToolResultToToolResultBlockParam(data: FileEditOutput, toolUseID) { - const { filePath, userModified, replaceAll } = data + const { filePath, userModified, replaceAll, matchAdjusted } = data const modifiedNote = userModified ? '. The user modified your proposed changes before accepting them. ' : '' + const readBackNote = + userModified || matchAdjusted ? '' : ` ${NO_READ_BACK_NOTE}` if (replaceAll) { return { tool_use_id: toolUseID, type: 'tool_result', - content: `The file ${filePath} has been updated${modifiedNote}. All occurrences were successfully replaced.`, + content: `The file ${filePath} has been updated${modifiedNote}. All occurrences were successfully replaced.${readBackNote}`, } } return { tool_use_id: toolUseID, type: 'tool_result', - content: `The file ${filePath} has been updated successfully${modifiedNote}.`, + content: `The file ${filePath} has been updated successfully${modifiedNote}.${readBackNote}`, } }, } satisfies ToolDef, FileEditOutput>) // -- +function showMatchedStrings(input: Record): void { + const { file_path, old_string, new_string, replace_all } = input + if ( + typeof file_path !== 'string' || + typeof old_string !== 'string' || + typeof new_string !== 'string' + ) { + return + } + let fileContent: string + try { + fileContent = readFileSyncCached(file_path) + } catch (error) { + if (!isENOENT(error)) { + logError(error) + } + return + } + const replaceAll = replace_all === true + const match = matchEdit(fileContent, old_string, new_string, replaceAll) + if (match.matches === 1 || (replaceAll && match.matches > 1)) { + input.old_string = match.oldString + input.new_string = match.newString + } +} + function readFileForEdit(absoluteFilePath: string): { content: string fileExists: boolean diff --git a/src/tools/FileEditTool/UI.tsx b/src/tools/FileEditTool/UI.tsx index c4069822..2e929c3d 100644 --- a/src/tools/FileEditTool/UI.tsx +++ b/src/tools/FileEditTool/UI.tsx @@ -20,7 +20,8 @@ import { readEditContext } from '../../utils/readEditContext.js'; import { firstLineOf } from '../../utils/stringUtils.js'; import type { ThemeName } from '../../utils/theme.js'; import type { FileEditOutput } from './types.js'; -import { findActualString, getPatchForEdit, preserveQuoteStyle } from './utils.js'; +import { matchEdit } from './matchEdit.js'; +import { getPatchForEdit } from './utils.js'; export function userFacingName(input: Partial<{ file_path: string; old_string: string; @@ -260,15 +261,14 @@ async function loadRejectionDiff(filePath: string, oldString: string, newString: fileContent: undefined }; } - const actualOld = findActualString(ctx.content, oldString) || oldString; - const actualNew = preserveQuoteStyle(oldString, actualOld, newString); + const match = matchEdit(ctx.content, oldString, newString, replaceAll); const { patch } = getPatchForEdit({ filePath, fileContents: ctx.content, - oldString: actualOld, - newString: actualNew, + oldString: match.oldString, + newString: match.newString, replaceAll }); return { diff --git a/src/tools/FileEditTool/constants.ts b/src/tools/FileEditTool/constants.ts index e5809d00..a80d18ca 100644 --- a/src/tools/FileEditTool/constants.ts +++ b/src/tools/FileEditTool/constants.ts @@ -9,3 +9,6 @@ export const CLAUDE_FOLDER_PERMISSION_PATTERN = '/.claude/**' export const FILE_UNEXPECTEDLY_MODIFIED_ERROR = 'File has been unexpectedly modified. Read it again before attempting to write it.' + +export const NO_READ_BACK_NOTE = + 'The result is already in your context, so there is no need to read the file back.' diff --git a/src/tools/FileEditTool/matchEdit.test.ts b/src/tools/FileEditTool/matchEdit.test.ts new file mode 100644 index 00000000..4d5b845f --- /dev/null +++ b/src/tools/FileEditTool/matchEdit.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from 'bun:test' +import { matchEdit } from './matchEdit.js' + +const NOT_FOUND = 0 + +describe('exact match', () => { + it('returns the strings unchanged and counts every occurrence', () => { + expect(matchEdit('a = 1\nb = 1\n', '= 1', '= 2', false)).toEqual({ oldString: '= 1', newString: '= 2', matches: 2 }) + expect(matchEdit('a = 1\nb = 1\n', 'a = 1', 'a = 2', false)).toEqual({ oldString: 'a = 1', newString: 'a = 2', matches: 1 }) + }) + + it('wins over a looser strategy that would also match', () => { + const file = '12\tfoo\nfoo\n' + expect(matchEdit(file, '12\tfoo', 'bar', false)).toEqual({ oldString: '12\tfoo', newString: 'bar', matches: 1 }) + }) + + it('treats an empty old_string as a single match', () => { + expect(matchEdit('', '', 'new file', false)).toEqual({ oldString: '', newString: 'new file', matches: 1 }) + }) + + it('reports no match with the inputs unchanged', () => { + expect(matchEdit('alpha\n', 'beta', 'gamma', false)).toEqual({ oldString: 'beta', newString: 'gamma', matches: NOT_FOUND }) + }) +}) + +describe('sanitized tags', () => { + it('restores tags the API shortened and applies the same change to new_string', () => { + const file = '\nok\n\n' + expect(matchEdit(file, '\nok', '\ndone', false)).toEqual({ oldString: '\nok', newString: '\ndone', matches: 1 }) + }) + + it('is available with replace_all', () => { + expect(matchEdit('a a\n', 'a', 'b', true)).toEqual({ oldString: 'a', newString: 'b', matches: 2 }) + }) +}) + +describe('curly quotes', () => { + it('finds straight quotes written for curly ones and keeps the file style in new_string', () => { + const file = 'title = \u201CHello\u201D\n' + expect(matchEdit(file, 'title = "Hello"', 'title = "Goodbye"', false)).toEqual({ + oldString: 'title = \u201CHello\u201D', + newString: 'title = \u201CGoodbye\u201D', + matches: 1, + }) + }) + + it('keeps an apostrophe inside a word as a closing quote', () => { + const file = 'say \u2018hi\u2019\n' + expect(matchEdit(file, "say 'hi'", "say 'don't'", false).newString).toBe('say \u2018don\u2019t\u2019') + }) + + it('leaves new_string alone when the file has the straight quotes', () => { + const file = 'title = "Hello"\n' + expect(matchEdit(file, 'title = \u201CHello\u201D', 'title = "Bye"', false)).toEqual({ oldString: 'title = "Hello"', newString: 'title = "Bye"', matches: 1 }) + }) + + it('counts candidates whose quote styles differ', () => { + expect(matchEdit('\u201Ca\u201D x \u201Ca"\n', '"a"', '"b"', false).matches).toBe(2) + }) + + it('counts every candidate', () => { + const file = '\u201Ca\u201D and \u201Ca\u201D\n' + expect(matchEdit(file, '"a"', '"b"', false).matches).toBe(2) + expect(matchEdit(file, '"a"', '"b"', true)).toEqual({ oldString: '\u201Ca\u201D', newString: '\u201Cb\u201D', matches: 2 }) + }) +}) + +describe('line number prefixes', () => { + const file = 'def f():\n return 1\n\ndef g():\n return 2\n' + + it('strips the tab form from both strings', () => { + expect(matchEdit(file, '1\tdef f():\n2\t return 1', '1\tdef f():\n2\t return 3', false)).toEqual({ + oldString: 'def f():\n return 1', + newString: 'def f():\n return 3', + matches: 1, + }) + }) + + it('strips the padded arrow form', () => { + expect(matchEdit(file, ' 4\u2192def g():\n 5\u2192 return 2', 'def g():\n return 4', false)).toEqual({ + oldString: 'def g():\n return 2', + newString: 'def g():\n return 4', + matches: 1, + }) + }) + + it('reads a bare number between prefixed lines as an empty line', () => { + expect(matchEdit(file, '2\t return 1\n3\n4\tdef g():', '2\t return 1\n3\n4\tdef h():', false)).toEqual({ + oldString: ' return 1\n\ndef g():', + newString: ' return 1\n\ndef h():', + matches: 1, + }) + }) + + it('keeps a trailing newline', () => { + expect(matchEdit(file, '5\t return 2\n', '5\t return 5\n', false)).toEqual({ oldString: ' return 2\n', newString: ' return 5\n', matches: 1 }) + }) + + it('leaves new_string alone when none of its lines carry a prefix', () => { + expect(matchEdit(file, '2\t return 1', ' x = 1\n return 1', false)).toEqual({ oldString: ' return 1', newString: ' x = 1\n return 1', matches: 1 }) + }) + + it('does not match when only some lines of new_string carry a prefix', () => { + expect(matchEdit(file, '2\t return 1', ' x = 1\n2\t return 1', false).matches).toBe(NOT_FOUND) + }) + + it('reads an empty line between prefixed lines as an empty line', () => { + expect(matchEdit(file, '1\tdef f():\n2\t return 1', '1\tdef f():\n\n2\t return 1', false)).toEqual({ + oldString: 'def f():\n return 1', + newString: 'def f():\n\n return 1', + matches: 1, + }) + }) + + it('does not apply when a line of old_string has no prefix', () => { + expect(matchEdit(file, '1\tdef f():\n return 9', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('does not apply to bare numbers alone', () => { + expect(matchEdit(file, '7', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('is available with replace_all and counts every occurrence', () => { + const repeated = 'x = 1\ny = 2\nx = 1\n' + expect(matchEdit(repeated, '1\tx = 1', '1\tx = 0', true)).toEqual({ oldString: 'x = 1', newString: 'x = 0', matches: 2 }) + expect(matchEdit(repeated, '1\tx = 1', '1\tx = 0', false).matches).toBe(2) + }) +}) + +describe('trailing whitespace', () => { + const file = 'first \nsecond\t\n \nthird\n' + + it('ignores whitespace at the end of each line and leaves new_string alone', () => { + expect(matchEdit(file, 'first\nsecond\n\nthird', 'first\nchanged \n\nthird', false)).toEqual({ + oldString: 'first \nsecond\t\n \nthird', + newString: 'first\nchanged \n\nthird', + matches: 1, + }) + }) + + it('ignores extra whitespace at the end of old_string lines', () => { + expect(matchEdit('alpha\nbeta\n', 'alpha \nbeta', 'gamma', false)).toEqual({ oldString: 'alpha\nbeta', newString: 'gamma', matches: 1 }) + }) + + it('takes the newline after the block when old_string ends with one', () => { + expect(matchEdit(file, 'first\nsecond\n', 'only\n', false)).toEqual({ oldString: 'first \nsecond\t\n', newString: 'only\n', matches: 1 }) + }) + + it('does not match a block at the end of a file that has no final newline when old_string ends with one', () => { + expect(matchEdit('a \nb ', 'a\nb\n', 'c\n', false).matches).toBe(NOT_FOUND) + }) + + it('does not ignore whitespace inside a line', () => { + expect(matchEdit('a = 1 \n', 'a = 1', 'a = 2', false).matches).toBe(NOT_FOUND) + }) + + it('reports every candidate', () => { + expect(matchEdit('x \ny\nx \ny\n', 'x\ny', 'z', false).matches).toBe(2) + }) + + it('reports several matches when the text of the only block also occurs inside earlier lines', () => { + expect(matchEdit('xa\nbz\na\nb\n', 'a \nb', 'c', false)).toEqual({ oldString: 'a\nb', newString: 'c', matches: 2 }) + }) + + it('counts an earlier occurrence that overlaps the block', () => { + expect(matchEdit('ax\nx\nx\n', 'x \nx', 'y', false).matches).toBe(2) + }) + + it('is not used with replace_all', () => { + expect(matchEdit(file, 'first\nsecond', 'x', true).matches).toBe(NOT_FOUND) + }) +}) + +describe('indentation', () => { + const nested = 'class A:\n def f(self):\n if x:\n return 1\n\n return 2\n' + + it('accepts lines that all miss the same prefix and adds it to new_string', () => { + expect(matchEdit(nested, 'if x:\n return 1\n\nreturn 2', 'if y:\n return 3\n\nreturn 2', false)).toEqual({ + oldString: ' if x:\n return 1\n\n return 2', + newString: ' if y:\n return 3\n\n return 2', + matches: 1, + }) + }) + + it('accepts lines that all carry the same extra prefix and removes it from new_string', () => { + expect(matchEdit(nested, ' if x:\n return 1', ' if x:\n return 9', false)).toEqual({ + oldString: ' if x:\n return 1', + newString: ' if x:\n return 9', + matches: 1, + }) + }) + + it('rejects the match when a new_string line is indented less than the extra prefix', () => { + expect(matchEdit(nested, ' if x:\n return 1', ' if x:\n return 9', false).matches).toBe(NOT_FOUND) + }) + + it('accepts spaces written for tabs at one width and converts new_string', () => { + const tabbed = 'func f() {\n\tif x {\n\t\treturn 1\n\t}\n}\n' + expect(matchEdit(tabbed, ' if x {\n return 1\n }', ' if y {\n return 2\n + aligned\n }', false)).toEqual({ + oldString: '\tif x {\n\t\treturn 1\n\t}', + newString: '\tif y {\n\t\treturn 2\n\t\t + aligned\n\t}', + matches: 1, + }) + }) + + it('accepts tabs written for spaces at one width and converts new_string', () => { + const spaced = 'function f() {\n if (x) {\n return 1\n }\n}\n' + expect(matchEdit(spaced, '\tif (x) {\n\t\treturn 1\n\t}', '\tif (y) {\n\t\treturn 2\n\t}', false)).toEqual({ + oldString: ' if (x) {\n return 1\n }', + newString: ' if (y) {\n return 2\n }', + matches: 1, + }) + }) + + it('rejects the match when a new_string line mixes in the other indent character', () => { + const tabbed = 'func f() {\n\tif x {\n\t\treturn 1\n\t}\n}\n' + expect(matchEdit(tabbed, ' if x {\n return 1\n }', ' if y {\n\t\treturn 2\n }', false).matches).toBe(NOT_FOUND) + }) + + it('rejects indentation that differs by a different amount on each line', () => { + expect(matchEdit(nested, ' if x:\n return 1', ' if x:\n return 9', false).matches).toBe(NOT_FOUND) + }) + + it('rejects a tab and space swap whose width changes between lines', () => { + const tabbed = '\tif x {\n\t\treturn 1\n\t}\n' + expect(matchEdit(tabbed, ' if x {\n return 1\n }', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('rejects a swap combined with a missing prefix', () => { + const tabbed = '\t\tif x {\n\t\t\treturn 1\n\t\t}\n' + expect(matchEdit(tabbed, 'if x {\n return 1\n}', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('does not ignore whitespace at the end of a line', () => { + expect(matchEdit(' a = 1 \n b = 2\n', 'a = 1\nb = 2', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('reports every candidate', () => { + const repeated = ' a()\n b()\n a()\n b()\n' + expect(matchEdit(repeated, ' a()\n b()', 'x', false).matches).toBe(2) + }) + + it('reports several matches when the text of the only block also occurs inside an earlier line', () => { + const file = 'if (a) return null\nlog()\n return null\n' + expect(matchEdit(file, '\treturn null', '\treturn 1', false)).toEqual({ oldString: ' return null', newString: ' return 1', matches: 2 }) + }) + + it('is not used with replace_all', () => { + expect(matchEdit(nested, 'if x:\n return 1', 'x', true).matches).toBe(NOT_FOUND) + }) +}) + +describe('escapes', () => { + it('reads escapes written out in old_string and new_string', () => { + const file = 'print("a")\n\tprint(\'b\')\npath = "C:\\\\dir"\n' + expect(matchEdit(file, 'print(\\"a\\")\\n\\tprint(\\\'b\\\')', 'print(\\"c\\")\\n\\tprint(\\\'d\\\')', false)).toEqual({ + oldString: 'print("a")\n\tprint(\'b\')', + newString: 'print("c")\n\tprint(\'d\')', + matches: 1, + }) + }) + + it('reads a doubled backslash as one', () => { + const file = 'pattern = /a\\d/\n' + expect(matchEdit(file, 'pattern = /a\\\\d/', 'pattern = /b\\\\d\\\\n/', false)).toEqual({ + oldString: 'pattern = /a\\d/', + newString: 'pattern = /b\\d\\n/', + matches: 1, + }) + }) + + it('does not apply when old_string has no escape', () => { + expect(matchEdit('a\nb\n', 'a b', 'c', false).matches).toBe(NOT_FOUND) + }) + + it('reports every candidate', () => { + expect(matchEdit('say "x"\nsay "x"\n', 'say \\"x\\"', 'y', false).matches).toBe(2) + }) + + it('is not used with replace_all', () => { + expect(matchEdit('say "x"\n', 'say \\"x\\"', 'y', true).matches).toBe(NOT_FOUND) + }) +}) + +describe('strategies are tried one at a time', () => { + it('does not combine a line number prefix with an indentation fix', () => { + const file = ' if x:\n return 1\n' + expect(matchEdit(file, '1\tif x:\n2\t return 1', 'x', false).matches).toBe(NOT_FOUND) + }) + + it('stops at the first strategy that has a candidate', () => { + const file = 'a \nb\n\ta\n\tb\n' + expect(matchEdit(file, 'a\nb', 'c', false)).toEqual({ oldString: 'a \nb', newString: 'c', matches: 1 }) + }) +}) diff --git a/src/tools/FileEditTool/matchEdit.ts b/src/tools/FileEditTool/matchEdit.ts new file mode 100644 index 00000000..18c506a3 --- /dev/null +++ b/src/tools/FileEditTool/matchEdit.ts @@ -0,0 +1,486 @@ +import { stripLineNumberPrefix } from '../../utils/file.js' + +const LEFT_SINGLE_CURLY_QUOTE = '\u2018' +const RIGHT_SINGLE_CURLY_QUOTE = '\u2019' +const LEFT_DOUBLE_CURLY_QUOTE = '\u201C' +const RIGHT_DOUBLE_CURLY_QUOTE = '\u201D' +const EM_DASH = '\u2014' +const EN_DASH = '\u2013' + +const DESANITIZATIONS: Record = { + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '': '', + '< META_START >': '', + '< META_END >': '', + '< EOT >': '', + '< META >': '', + '< SOS >': '', + '\n\nH:': '\n\nHuman:', + '\n\nA:': '\n\nAssistant:', +} + +const MAX_INDENT_WIDTH = 8 +const BARE_LINE_NUMBER = /^\s*\d+$/ +const ESCAPE_SEQUENCE = /\\([nt"'\\])/g +const ESCAPED_CHARACTERS: Record = { + n: '\n', + t: '\t', + '"': '"', + "'": "'", + '\\': '\\', +} + +export type EditMatch = { + oldString: string + newString: string + matches: number +} + +type MatchStrategy = ( + fileContent: string, + oldString: string, + newString: string, +) => EditMatch | null + +type Lines = { lines: string[]; trailingNewline: boolean } + +type Reindent = (indent: string) => string | null + +const REPLACE_ALL_STRATEGIES: MatchStrategy[] = [ + matchExact, + matchDesanitized, + matchCurlyQuotes, + matchLineNumberPrefixes, +] + +const STRATEGIES: MatchStrategy[] = [ + ...REPLACE_ALL_STRATEGIES, + matchTrailingWhitespace, + matchIndentation, + matchEscapes, +] + +export function matchEdit( + fileContent: string, + oldString: string, + newString: string, + replaceAll: boolean, +): EditMatch { + if (oldString === '') { + return { oldString, newString, matches: 1 } + } + for (const strategy of replaceAll ? REPLACE_ALL_STRATEGIES : STRATEGIES) { + const match = strategy(fileContent, oldString, newString) + if (match) { + return match + } + } + return { oldString, newString, matches: 0 } +} + +function countOccurrences( + text: string, + search: string, + step = search.length, +): number { + if (search === '') { + return 0 + } + let count = 0 + let index = text.indexOf(search) + while (index !== -1) { + count++ + index = text.indexOf(search, index + step) + } + return count +} + +function matchExact( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const matches = countOccurrences(fileContent, oldString) + return matches > 0 ? { oldString, newString, matches } : null +} + +function matchDesanitized( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const replacements = Object.entries(DESANITIZATIONS).filter(([sanitized]) => + oldString.includes(sanitized), + ) + if (replacements.length === 0) { + return null + } + const desanitize = (text: string) => + replacements.reduce( + (result, [sanitized, original]) => result.replaceAll(sanitized, original), + text, + ) + const desanitizedOld = desanitize(oldString) + const matches = countOccurrences(fileContent, desanitizedOld) + return matches > 0 + ? { oldString: desanitizedOld, newString: desanitize(newString), matches } + : null +} + +function normalizeQuotes(text: string): string { + return text + .replaceAll(LEFT_SINGLE_CURLY_QUOTE, "'") + .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, "'") + .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '"') + .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '"') +} + +function matchCurlyQuotes( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const normalizedFile = normalizeQuotes(fileContent) + const normalizedOld = normalizeQuotes(oldString) + const index = normalizedFile.indexOf(normalizedOld) + if (index === -1) { + return null + } + const actualOldString = fileContent.substring(index, index + oldString.length) + return { + oldString: actualOldString, + newString: applyQuoteStyle(actualOldString, newString), + matches: countOccurrences(normalizedFile, normalizedOld), + } +} + +function applyQuoteStyle(actualOldString: string, newString: string): string { + let result = newString + if ( + actualOldString.includes(LEFT_DOUBLE_CURLY_QUOTE) || + actualOldString.includes(RIGHT_DOUBLE_CURLY_QUOTE) + ) { + result = curlQuotes( + result, + '"', + LEFT_DOUBLE_CURLY_QUOTE, + RIGHT_DOUBLE_CURLY_QUOTE, + ) + } + if ( + actualOldString.includes(LEFT_SINGLE_CURLY_QUOTE) || + actualOldString.includes(RIGHT_SINGLE_CURLY_QUOTE) + ) { + result = curlQuotes( + result, + "'", + LEFT_SINGLE_CURLY_QUOTE, + RIGHT_SINGLE_CURLY_QUOTE, + ) + } + return result +} + +function curlQuotes( + text: string, + straight: string, + opening: string, + closing: string, +): string { + const chars = [...text] + return chars + .map((char, index) => { + if (char !== straight) { + return char + } + if (straight === "'" && isApostrophe(chars, index)) { + return closing + } + return opensQuote(chars, index) ? opening : closing + }) + .join('') +} + +function isApostrophe(chars: string[], index: number): boolean { + const previous = chars[index - 1] + const next = chars[index + 1] + return ( + previous !== undefined && + next !== undefined && + /\p{L}/u.test(previous) && + /\p{L}/u.test(next) + ) +} + +function opensQuote(chars: string[], index: number): boolean { + if (index === 0) { + return true + } + const previous = chars[index - 1] + return ( + previous === ' ' || + previous === '\t' || + previous === '\n' || + previous === '\r' || + previous === '(' || + previous === '[' || + previous === '{' || + previous === EM_DASH || + previous === EN_DASH + ) +} + +function matchLineNumberPrefixes( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const strippedOld = stripLineNumberPrefixes(oldString) + if (strippedOld === null) { + return null + } + const matches = countOccurrences(fileContent, strippedOld) + if (matches === 0) { + return null + } + const strippedNew = stripLineNumberPrefixes(newString) + if (strippedNew === null && hasLineNumberPrefix(newString)) { + return null + } + return { + oldString: strippedOld, + newString: strippedNew ?? newString, + matches, + } +} + +function hasLineNumberPrefix(text: string): boolean { + return text.split('\n').some(line => stripLineNumberPrefix(line) !== line) +} + +function stripLineNumberPrefixes(text: string): string | null { + const { lines, trailingNewline } = splitLines(text) + let hasPrefix = false + const stripped: string[] = [] + for (const line of lines) { + const withoutPrefix = stripLineNumberPrefix(line) + if (withoutPrefix !== line) { + hasPrefix = true + stripped.push(withoutPrefix) + } else if (line === '' || BARE_LINE_NUMBER.test(line)) { + stripped.push('') + } else { + return null + } + } + return hasPrefix ? joinLines(stripped, trailingNewline) : null +} + +function splitLines(text: string): Lines { + const trailingNewline = text.endsWith('\n') + return { + lines: (trailingNewline ? text.slice(0, -1) : text).split('\n'), + trailingNewline, + } +} + +function joinLines(lines: string[], trailingNewline: boolean): string { + return lines.join('\n') + (trailingNewline ? '\n' : '') +} + +function findLineBlocks( + fileContent: string, + old: Lines, + normalize: (line: string) => string, +): string[][] { + const fileLines = fileContent.split('\n') + const wanted = old.lines.map(normalize) + const lastStart = + fileLines.length - wanted.length - (old.trailingNewline ? 1 : 0) + const blocks: string[][] = [] + for (let start = 0; start <= lastStart; start++) { + if ( + wanted.every((line, index) => normalize(fileLines[start + index]!) === line) + ) { + blocks.push(fileLines.slice(start, start + wanted.length)) + } + } + return blocks +} + +function matchLineBlock( + fileContent: string, + block: string[], + blockCount: number, + trailingNewline: boolean, + newString: string, +): EditMatch { + const oldString = joinLines(block, trailingNewline) + return { + oldString, + newString, + matches: Math.max(blockCount, countOccurrences(fileContent, oldString, 1)), + } +} + +function matchTrailingWhitespace( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const old = splitLines(oldString) + const blocks = findLineBlocks(fileContent, old, line => line.trimEnd()) + const first = blocks[0] + if (!first) { + return null + } + return matchLineBlock( + fileContent, + first, + blocks.length, + old.trailingNewline, + newString, + ) +} + +function indentOf(line: string): string { + return line.slice(0, line.length - withoutIndent(line).length) +} + +function withoutIndent(line: string): string { + return line.replace(/^[ \t]+/, '') +} + +function isBlank(line: string): boolean { + return line.trim() === '' +} + +function matchIndentation( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const old = splitLines(oldString) + const candidates = findLineBlocks(fileContent, old, withoutIndent).flatMap( + block => { + const reindent = findReindent(old.lines, block) + return reindent ? [{ block, reindent }] : [] + }, + ) + const first = candidates[0] + if (!first) { + return null + } + const reindented = reindentLines(newString, first.reindent) + if (reindented === null) { + return null + } + return matchLineBlock( + fileContent, + first.block, + candidates.length, + old.trailingNewline, + reindented, + ) +} + +function findReindent(oldLines: string[], fileLines: string[]): Reindent | null { + const indents = oldLines.flatMap((line, index) => + isBlank(line) ? [] : [[indentOf(line), indentOf(fileLines[index]!)] as const], + ) + const first = indents[0] + if (!first) { + return null + } + return ( + reindentCandidates(first[0], first[1]).find(reindent => + indents.every(([oldIndent, fileIndent]) => reindent(oldIndent) === fileIndent), + ) ?? null + ) +} + +function reindentCandidates(oldIndent: string, fileIndent: string): Reindent[] { + const candidates: Reindent[] = [] + if (fileIndent.endsWith(oldIndent)) { + const added = fileIndent.slice(0, fileIndent.length - oldIndent.length) + candidates.push(indent => added + indent) + } + if (oldIndent.endsWith(fileIndent)) { + const removed = oldIndent.slice(0, oldIndent.length - fileIndent.length) + candidates.push(indent => + indent.startsWith(removed) ? indent.slice(removed.length) : null, + ) + } + for (let width = 1; width <= MAX_INDENT_WIDTH; width++) { + candidates.push( + indent => spacesToTabs(indent, width), + indent => tabsToSpaces(indent, width), + ) + } + return candidates +} + +function spacesToTabs(indent: string, width: number): string | null { + if (indent.includes('\t')) { + return null + } + return ( + '\t'.repeat(Math.floor(indent.length / width)) + + ' '.repeat(indent.length % width) + ) +} + +function tabsToSpaces(indent: string, width: number): string | null { + const tabs = indent.lastIndexOf('\t') + 1 + if (indent.slice(0, tabs).includes(' ')) { + return null + } + return ' '.repeat(tabs * width + indent.length - tabs) +} + +function reindentLines(text: string, reindent: Reindent): string | null { + const lines: string[] = [] + for (const line of text.split('\n')) { + if (isBlank(line)) { + lines.push(line) + continue + } + const indent = reindent(indentOf(line)) + if (indent === null) { + return null + } + lines.push(indent + withoutIndent(line)) + } + return lines.join('\n') +} + +function matchEscapes( + fileContent: string, + oldString: string, + newString: string, +): EditMatch | null { + const unescapedOld = unescape(oldString) + if (unescapedOld === oldString) { + return null + } + const matches = countOccurrences(fileContent, unescapedOld) + return matches > 0 + ? { oldString: unescapedOld, newString: unescape(newString), matches } + : null +} + +function unescape(text: string): string { + return text.replace( + ESCAPE_SEQUENCE, + (_, character: string) => ESCAPED_CHARACTERS[character]!, + ) +} diff --git a/src/tools/FileEditTool/types.ts b/src/tools/FileEditTool/types.ts index 86be2683..688a176e 100644 --- a/src/tools/FileEditTool/types.ts +++ b/src/tools/FileEditTool/types.ts @@ -75,6 +75,10 @@ const outputSchema = lazySchema(() => .boolean() .describe('Whether the user modified the proposed changes'), replaceAll: z.boolean().describe('Whether all occurrences were replaced'), + matchAdjusted: z + .boolean() + .optional() + .describe('Whether the written text differs from new_string'), gitDiff: gitDiffSchema().optional(), }), ) diff --git a/src/tools/FileEditTool/utils.ts b/src/tools/FileEditTool/utils.ts index aab53c95..e219ea2d 100644 --- a/src/tools/FileEditTool/utils.ts +++ b/src/tools/FileEditTool/utils.ts @@ -1,6 +1,4 @@ import { type StructuredPatchHunk, structuredPatch } from 'diff' -import { logError } from 'src/utils/log.js' -import { expandPath } from 'src/utils/path.js' import { countCharInString } from 'src/utils/stringUtils.js' import { DIFF_TIMEOUT_MS, @@ -13,28 +11,7 @@ import { convertLeadingTabsToSpaces, readFileSyncCached, } from '../../utils/file.js' -import type { EditInput, FileEdit } from './types.js' - -// Claude can't output curly quotes, so we define them as constants here for Claude to use -// in the code. We do this because we normalize curly quotes to straight quotes -// when applying edits. -export const LEFT_SINGLE_CURLY_QUOTE = '‘' -export const RIGHT_SINGLE_CURLY_QUOTE = '’' -export const LEFT_DOUBLE_CURLY_QUOTE = '“' -export const RIGHT_DOUBLE_CURLY_QUOTE = '”' - -/** - * Normalizes quotes in a string by converting curly quotes to straight quotes - * @param str The string to normalize - * @returns The string with all curly quotes replaced by straight quotes - */ -export function normalizeQuotes(str: string): string { - return str - .replaceAll(LEFT_SINGLE_CURLY_QUOTE, "'") - .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, "'") - .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '"') - .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '"') -} +import type { FileEdit } from './types.js' /** * Strips trailing whitespace from each line in a string while preserving line endings @@ -63,141 +40,6 @@ export function stripTrailingWhitespace(str: string): string { return result } -/** - * Finds the actual string in the file content that matches the search string, - * accounting for quote normalization - * @param fileContent The file content to search in - * @param searchString The string to search for - * @returns The actual string found in the file, or null if not found - */ -export function findActualString( - fileContent: string, - searchString: string, -): string | null { - // First try exact match - if (fileContent.includes(searchString)) { - return searchString - } - - // Try with normalized quotes - const normalizedSearch = normalizeQuotes(searchString) - const normalizedFile = normalizeQuotes(fileContent) - - const searchIndex = normalizedFile.indexOf(normalizedSearch) - if (searchIndex !== -1) { - // Find the actual string in the file that matches - return fileContent.substring(searchIndex, searchIndex + searchString.length) - } - - return null -} - -/** - * When old_string matched via quote normalization (curly quotes in file, - * straight quotes from model), apply the same curly quote style to new_string - * so the edit preserves the file's typography. - * - * Uses a simple open/close heuristic: a quote character preceded by whitespace, - * start of string, or opening punctuation is treated as an opening quote; - * otherwise it's a closing quote. - */ -export function preserveQuoteStyle( - oldString: string, - actualOldString: string, - newString: string, -): string { - // If they're the same, no normalization happened - if (oldString === actualOldString) { - return newString - } - - // Detect which curly quote types were in the file - const hasDoubleQuotes = - actualOldString.includes(LEFT_DOUBLE_CURLY_QUOTE) || - actualOldString.includes(RIGHT_DOUBLE_CURLY_QUOTE) - const hasSingleQuotes = - actualOldString.includes(LEFT_SINGLE_CURLY_QUOTE) || - actualOldString.includes(RIGHT_SINGLE_CURLY_QUOTE) - - if (!hasDoubleQuotes && !hasSingleQuotes) { - return newString - } - - let result = newString - - if (hasDoubleQuotes) { - result = applyCurlyDoubleQuotes(result) - } - if (hasSingleQuotes) { - result = applyCurlySingleQuotes(result) - } - - return result -} - -function isOpeningContext(chars: string[], index: number): boolean { - if (index === 0) { - return true - } - const prev = chars[index - 1] - return ( - prev === ' ' || - prev === '\t' || - prev === '\n' || - prev === '\r' || - prev === '(' || - prev === '[' || - prev === '{' || - prev === '\u2014' || // em dash - prev === '\u2013' // en dash - ) -} - -function applyCurlyDoubleQuotes(str: string): string { - const chars = [...str] - const result: string[] = [] - for (let i = 0; i < chars.length; i++) { - if (chars[i] === '"') { - result.push( - isOpeningContext(chars, i) - ? LEFT_DOUBLE_CURLY_QUOTE - : RIGHT_DOUBLE_CURLY_QUOTE, - ) - } else { - result.push(chars[i]!) - } - } - return result.join('') -} - -function applyCurlySingleQuotes(str: string): string { - const chars = [...str] - const result: string[] = [] - for (let i = 0; i < chars.length; i++) { - if (chars[i] === "'") { - // Don't convert apostrophes in contractions (e.g., "don't", "it's") - // An apostrophe between two letters is a contraction, not a quote - const prev = i > 0 ? chars[i - 1] : undefined - const next = i < chars.length - 1 ? chars[i + 1] : undefined - const prevIsLetter = prev !== undefined && /\p{L}/u.test(prev) - const nextIsLetter = next !== undefined && /\p{L}/u.test(next) - if (prevIsLetter && nextIsLetter) { - // Apostrophe in a contraction — use right single curly quote - result.push(RIGHT_SINGLE_CURLY_QUOTE) - } else { - result.push( - isOpeningContext(chars, i) - ? LEFT_SINGLE_CURLY_QUOTE - : RIGHT_SINGLE_CURLY_QUOTE, - ) - } - } else { - result.push(chars[i]!) - } - } - return result.join('') -} - /** * Transform edits to ensure replace_all always has a boolean value * @param edits Array of edits with optional replace_all @@ -520,139 +362,6 @@ export function getEditsForPatch(patch: StructuredPatchHunk[]): FileEdit[] { }) } -/** - * Contains replacements to de-sanitize strings from Claude - * Since Claude can't see any of these strings (sanitized in the API) - * It'll output the sanitized versions in the edit response - */ -const DESANITIZATIONS: Record = { - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '': '', - '< META_START >': '', - '< META_END >': '', - '< EOT >': '', - '< META >': '', - '< SOS >': '', - '\n\nH:': '\n\nHuman:', - '\n\nA:': '\n\nAssistant:', -} - -/** - * Normalizes a match string by applying specific replacements - * This helps handle when exact matches fail due to formatting differences - * @returns The normalized string and which replacements were applied - */ -function desanitizeMatchString(matchString: string): { - result: string - appliedReplacements: Array<{ from: string; to: string }> -} { - let result = matchString - const appliedReplacements: Array<{ from: string; to: string }> = [] - - for (const [from, to] of Object.entries(DESANITIZATIONS)) { - const beforeReplace = result - result = result.replaceAll(from, to) - - if (beforeReplace !== result) { - appliedReplacements.push({ from, to }) - } - } - - return { result, appliedReplacements } -} - -/** - * Normalize the input for the FileEditTool - * If the string to replace is not found in the file, try with a normalized version - * Returns the normalized input if successful, or the original input if not - */ -export function normalizeFileEditInput({ - file_path, - edits, -}: { - file_path: string - edits: EditInput[] -}): { - file_path: string - edits: EditInput[] -} { - if (edits.length === 0) { - return { file_path, edits } - } - - // Markdown uses two trailing spaces as a hard line break — stripping would - // silently change semantics. Skip stripTrailingWhitespace for .md/.mdx. - const isMarkdown = /\.(md|mdx)$/i.test(file_path) - - try { - const fullPath = expandPath(file_path) - - // Use cached file read to avoid redundant I/O operations. - // If the file doesn't exist, readFileSyncCached throws ENOENT which the - // catch below handles by returning the original input (no TOCTOU pre-check). - const fileContent = readFileSyncCached(fullPath) - - return { - file_path, - edits: edits.map(({ old_string, new_string, replace_all }) => { - const normalizedNewString = isMarkdown - ? new_string - : stripTrailingWhitespace(new_string) - - // If exact string match works, keep it as is - if (fileContent.includes(old_string)) { - return { - old_string, - new_string: normalizedNewString, - replace_all, - } - } - - // Try de-sanitize string if exact match fails - const { result: desanitizedOldString, appliedReplacements } = - desanitizeMatchString(old_string) - - if (fileContent.includes(desanitizedOldString)) { - // Apply the same exact replacements to new_string - let desanitizedNewString = normalizedNewString - for (const { from, to } of appliedReplacements) { - desanitizedNewString = desanitizedNewString.replaceAll(from, to) - } - - return { - old_string: desanitizedOldString, - new_string: desanitizedNewString, - replace_all, - } - } - - return { - old_string, - new_string: normalizedNewString, - replace_all, - } - }), - } - } catch (error) { - // If there's any error reading the file, just return original input. - // ENOENT is expected when the file doesn't exist yet (e.g., new file). - if (!isENOENT(error)) { - logError(error) - } - } - - return { file_path, edits } -} - /** * Compare two sets of edits to determine if they are equivalent * by applying both sets to the original content and comparing results. diff --git a/src/tools/FileReadTool/FileReadTool.test.ts b/src/tools/FileReadTool/FileReadTool.test.ts index 775b2088..8ef7d80a 100644 --- a/src/tools/FileReadTool/FileReadTool.test.ts +++ b/src/tools/FileReadTool/FileReadTool.test.ts @@ -1,5 +1,17 @@ -import { describe, expect, it } from 'bun:test' -import { FileReadTool } from './FileReadTool.js' +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test' +import * as fs from 'node:fs/promises' +import * as os from 'node:os' +import * as path from 'node:path' +import * as tokenEstimation from '../../services/tokenEstimation.js' +import type { ToolUseContext } from '../../Tool.js' +import { generateFileAttachment, getChangedFiles } from '../../utils/attachments.js' +import { normalizeAttachmentForAPI } from '../../utils/messages.js' +import { extractReadFilesFromMessages } from '../../utils/queryHelpers.js' +import { FileTooLargeError } from '../../utils/readFileInRange.js' +import { FileEditTool } from '../FileEditTool/FileEditTool.js' +import { FileWriteTool } from '../FileWriteTool/FileWriteTool.js' +import { agentContext, allow, turn } from '../testing/agentContext.js' +import { FileReadTool, MaxFileReadTokenExceededError } from './FileReadTool.js' describe('FileReadTool input', () => { it('treats an empty page range as no page range', () => { @@ -9,3 +21,184 @@ describe('FileReadTool input', () => { expect(schema.safeParse({ file_path: '/tmp/a.pdf', pages: 3 }).success).toBe(false) }) }) + +const LINE_CHARS = 39 +const TOTAL_LINES = 50 +const TOKEN_LIMIT = 100 +const LINES_WITHIN_TOKEN_LIMIT = 10 + +const line = (n: number) => `line ${String(n).padStart(4, '0')} `.padEnd(LINE_CHARS, 'x') +const lines = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => line(from + i)).join('\n') + +type Limits = NonNullable + +const limitedContext = (fileReadingLimits: Limits = { maxTokens: TOKEN_LIMIT }) => agentContext({ fileReadingLimits }) + +async function read(context: ToolUseContext, filePath: string, range: { offset?: number; limit?: number } = {}) { + const { data } = await FileReadTool.call({ file_path: filePath, ...range }, context) + if (data.type !== 'text') throw new Error(`expected a text read, got ${data.type}`) + const result = FileReadTool.mapToolResultToToolResultBlockParam(data, 'tool-1') + return { file: data.file, text: String(result.content) } +} + +describe('a text read that is over the limit', () => { + let dir: string + let big: string + let countTokens: ReturnType> + let modelAtStart: string | undefined + + beforeEach(async () => { + modelAtStart = process.env.ANTHROPIC_MODEL + process.env.ANTHROPIC_MODEL = 'test-model' + dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'read-truncation-'))) + big = path.join(dir, 'big.txt') + await fs.writeFile(big, lines(1, TOTAL_LINES)) + countTokens = spyOn(tokenEstimation, 'countTokensWithAPI').mockResolvedValue(null) + }) + + afterEach(async () => { + countTokens.mockRestore() + if (modelAtStart === undefined) delete process.env.ANTHROPIC_MODEL + else process.env.ANTHROPIC_MODEL = modelAtStart + await fs.rm(dir, { recursive: true, force: true }) + }) + + it('returns the lines that fit and says which lines they are', async () => { + const { file, text } = await read(limitedContext(), big) + expect(file).toMatchObject({ content: lines(1, LINES_WITHIN_TOKEN_LIMIT), numLines: LINES_WITHIN_TOKEN_LIMIT, startLine: 1, totalLines: TOTAL_LINES, truncated: true }) + expect(text).toContain(`${LINES_WITHIN_TOKEN_LIMIT}\t${line(LINES_WITHIN_TOKEN_LIMIT)}`) + expect(text).not.toContain(line(LINES_WITHIN_TOKEN_LIMIT + 1)) + expect(text).toContain(`it returned lines 1-${LINES_WITHIN_TOKEN_LIMIT} of ${TOTAL_LINES}`) + expect(text).toContain(`offset ${LINES_WITHIN_TOKEN_LIMIT + 1}`) + expect(text).toContain('limit') + }) + + it('cuts a read that gives offset and limit by the same rule', async () => { + const { file, text } = await read(limitedContext(), big, { offset: 21, limit: 20 }) + expect(file).toMatchObject({ content: lines(21, 30), numLines: 10, startLine: 21, totalLines: TOTAL_LINES, truncated: true }) + expect(text).toContain(`it returned lines 21-30 of ${TOTAL_LINES}`) + expect(text).toContain('offset 31') + }) + + it('keeps fewer lines when the counted tokens are denser than the estimate', async () => { + countTokens.mockResolvedValue(1000) + const { file } = await read(limitedContext(), big) + expect(file.numLines).toBe(5) + }) + + it('cuts at the byte limit when no limit is given', async () => { + const { file, text } = await read(limitedContext({ maxTokens: 100_000, maxSizeBytes: 200 }), big) + expect(file).toMatchObject({ content: lines(1, 5), numLines: 5, startLine: 1, totalLines: TOTAL_LINES, truncated: true }) + expect(text).toContain(`it returned lines 1-5 of ${TOTAL_LINES}`) + }) + + it('applies the token limit after the byte limit', async () => { + const { file } = await read(limitedContext({ maxTokens: TOKEN_LIMIT, maxSizeBytes: 1000 }), big) + expect(file.numLines).toBe(LINES_WITHIN_TOKEN_LIMIT) + }) + + it('still fails when the first line alone is over the token limit', async () => { + const oneLine = path.join(dir, 'one-line.txt') + await fs.writeFile(oneLine, 'x'.repeat(2000)) + const context = limitedContext() + await expect(FileReadTool.call({ file_path: oneLine }, context)).rejects.toBeInstanceOf(MaxFileReadTokenExceededError) + expect(context.readFileState.has(oneLine)).toBe(false) + }) + + it('still fails when the first line alone is over the byte limit', async () => { + const oneLine = path.join(dir, 'one-line.txt') + await fs.writeFile(oneLine, 'x'.repeat(2000)) + await expect(FileReadTool.call({ file_path: oneLine }, limitedContext({ maxTokens: 100_000, maxSizeBytes: 200 }))).rejects.toBeInstanceOf(FileTooLargeError) + }) + + it('leaves a read that fits unmarked', async () => { + const context = limitedContext() + const { file, text } = await read(context, big, { offset: 1, limit: 5 }) + expect(file.truncated).toBeUndefined() + expect(text).not.toContain('it returned lines') + expect(context.readFileState.get(big)?.truncated).toBeUndefined() + }) + + it('records the returned range in the read state', async () => { + const context = limitedContext() + await read(context, big, { offset: 21, limit: 20 }) + expect(context.readFileState.get(big)).toMatchObject({ content: lines(21, 30), offset: 21, limit: 20, truncated: { lastLine: 30, totalLines: TOTAL_LINES } }) + }) + + it('lets Edit proceed and makes Write refuse until a read that is not cut', async () => { + const context = limitedContext() + await read(context, big) + + const edit = { file_path: big, old_string: line(3), new_string: 'edited', replace_all: false } + expect(await FileEditTool.validateInput(edit, context)).toMatchObject({ result: true }) + await FileEditTool.call(edit, context, allow, turn) + expect((await fs.readFile(big, 'utf8')).split('\n').slice(2, 4)).toEqual(['edited', line(4)]) + + const write = { file_path: big, content: 'replacement\n' } + const refusal = await FileWriteTool.validateInput(write, context) + const reason = 'message' in refusal ? refusal.message : '' + expect(refusal.result).toBe(false) + expect(reason).toContain(`stopped at line ${LINES_WITHIN_TOKEN_LIMIT} of ${TOTAL_LINES}`) + expect(reason).toContain('use Edit') + + await read(context, big, { offset: 40, limit: 5 }) + expect(await FileWriteTool.validateInput(write, context)).toEqual({ result: true }) + }) + + it('makes Write refuse right after the cut read', async () => { + const context = limitedContext() + await read(context, big) + expect((await FileWriteTool.validateInput({ file_path: big, content: 'replacement\n' }, context)).result).toBe(false) + }) + + it('answers a repeat of the same read with the unchanged notice', async () => { + const context = limitedContext() + await read(context, big) + const { data } = await FileReadTool.call({ file_path: big }, context) + expect(data.type).toBe('file_unchanged') + }) + + it('keeps the cut through a restore from the transcript, also after an Edit', async () => { + const { text } = await read(limitedContext(), big) + const message = (type: 'assistant' | 'user', uuid: string, block: object) => ({ type, uuid, timestamp: new Date().toISOString(), message: { role: type, content: [block] } }) + const readUse = message('assistant', 'a1', { type: 'tool_use', id: 'read-1', name: 'Read', input: { file_path: big } }) + const readResult = message('user', 'u1', { type: 'tool_result', tool_use_id: 'read-1', content: text }) + const editUse = message('assistant', 'a2', { type: 'tool_use', id: 'edit-1', name: 'Edit', input: { file_path: big, old_string: 'a', new_string: 'b' } }) + const editResult = message('user', 'u2', { type: 'tool_result', tool_use_id: 'edit-1', content: 'ok' }) + const restore = (messages: object[]) => extractReadFilesFromMessages(messages as unknown as Parameters[0], dir) + const cut = { lastLine: LINES_WITHIN_TOKEN_LIMIT, totalLines: TOTAL_LINES } + + expect(restore([readUse, readResult]).get(big)).toMatchObject({ content: lines(1, LINES_WITHIN_TOKEN_LIMIT), offset: 1, truncated: cut }) + const afterEdit = restore([readUse, readResult, editUse, editResult]) + expect(afterEdit.get(big)).toMatchObject({ content: lines(1, TOTAL_LINES), truncated: cut }) + expect((await FileWriteTool.validateInput({ file_path: big, content: 'replacement\n' }, agentContext({ readFileState: afterEdit }))).result).toBe(false) + }) + + it('still fails for a caller that asks for the whole file or nothing', async () => { + const context = limitedContext({ maxTokens: TOKEN_LIMIT, failWhenOverLimit: true }) + await expect(FileReadTool.call({ file_path: big }, context)).rejects.toBeInstanceOf(MaxFileReadTokenExceededError) + await expect(FileReadTool.call({ file_path: big }, limitedContext({ maxTokens: 100_000, maxSizeBytes: 200, failWhenOverLimit: true }))).rejects.toBeInstanceOf(FileTooLargeError) + expect(context.readFileState.has(big)).toBe(false) + }) + + it('cuts a file attached with @ by the same rule', async () => { + const attachment = await generateFileAttachment(big, limitedContext(), 'success', 'error', 'at-mention') + expect(attachment).toMatchObject({ type: 'file', content: { type: 'text', file: { numLines: LINES_WITHIN_TOKEN_LIMIT, truncated: true } } }) + expect(JSON.stringify(normalizeAttachmentForAPI(attachment!))).toContain(`it returned lines 1-${LINES_WITHIN_TOKEN_LIMIT} of ${TOTAL_LINES}`) + + const oneLine = path.join(dir, 'one-line.txt') + await fs.writeFile(oneLine, 'x'.repeat(2000)) + expect(await generateFileAttachment(oneLine, limitedContext(), 'success', 'error', 'at-mention')).toBeNull() + }) + + it('does not report a cut read as an outside change to a file the agent wrote', async () => { + const context = limitedContext() + const written = path.join(dir, 'written.txt') + await FileWriteTool.call({ file_path: written, content: lines(1, TOTAL_LINES) }, context, allow, turn) + const stateAfterWrite = context.readFileState.get(written) + const later = new Date(Date.now() + 5000) + await fs.utimes(written, later, later) + expect(await getChangedFiles(context)).toEqual([]) + expect(context.readFileState.get(written)).toEqual(stateAfterWrite) + }) +}) diff --git a/src/tools/FileReadTool/FileReadTool.ts b/src/tools/FileReadTool/FileReadTool.ts index 3ed9e0d5..35e75008 100644 --- a/src/tools/FileReadTool/FileReadTool.ts +++ b/src/tools/FileReadTool/FileReadTool.ts @@ -71,7 +71,10 @@ import { } from '../../utils/permissions/filesystem.js' import type { PermissionDecision } from '../../utils/permissions/PermissionResult.js' import { matchWildcardPattern } from '../../utils/permissions/shellRuleMatching.js' -import { readFileInRange } from '../../utils/readFileInRange.js' +import { + FileTooLargeError, + readFileInRange, +} from '../../utils/readFileInRange.js' import { semanticNumber } from '../../utils/semanticNumber.js' import { semanticOptionalString } from '../../utils/semanticOptionalString.js' import { jsonStringify } from '../../utils/slowOperations.js' @@ -84,6 +87,7 @@ import { LINE_FORMAT_INSTRUCTION, OFFSET_INSTRUCTION_DEFAULT, OFFSET_INSTRUCTION_TARGETED, + readTruncatedNote, renderPromptTemplate, } from './prompt.js' import { @@ -264,6 +268,12 @@ const outputSchema = lazySchema(() => { .describe('Number of lines in the returned content'), startLine: z.number().describe('The starting line number'), totalLines: z.number().describe('Total number of lines in the file'), + truncated: z + .boolean() + .optional() + .describe( + 'True when the read stopped early at a line boundary to fit the size limit', + ), }), }), z.object({ @@ -346,7 +356,7 @@ export const FileReadTool = buildTool({ async prompt() { const limits = getDefaultFileReadingLimits() const maxSizeInstruction = limits.includeMaxSizeInPrompt - ? `. Files larger than ${formatFileSize(limits.maxSizeBytes)} will return an error; use offset and limit for larger files` + ? `. A read larger than ${formatFileSize(limits.maxSizeBytes)} returns the lines that fit; use offset and limit to read the rest` : '' const offsetInstruction = limits.targetedRangeNudge ? OFFSET_INSTRUCTION_TARGETED @@ -695,6 +705,13 @@ export const FileReadTool = buildTool({ content = memoryFileFreshnessPrefix(data) + formatFileLines(data.file) + + (data.file.truncated + ? readTruncatedNote( + data.file.startLine, + data.file.startLine + data.file.numLines - 1, + data.file.totalLines, + ) + : '') + (shouldIncludeFileReadMitigation() ? CYBER_RISK_MITIGATION_REMINDER : '') @@ -751,25 +768,45 @@ function memoryFileFreshnessPrefix(data: object): string { return memoryFreshnessNote(mtimeMs) } -async function validateContentTokens( +async function countContentTokens( content: string, ext: string, - maxTokens?: number, -): Promise { - const effectiveMaxTokens = - maxTokens ?? getDefaultFileReadingLimits().maxTokens - + maxTokens: number, +): Promise { const tokenEstimate = roughTokenCountEstimationForFileType(content, ext) - if (!tokenEstimate || tokenEstimate <= effectiveMaxTokens / 4) return + if (!tokenEstimate || tokenEstimate <= maxTokens / 4) return tokenEstimate - const tokenCount = await countTokensWithAPI(content) - const effectiveCount = tokenCount ?? tokenEstimate + return (await countTokensWithAPI(content)) ?? tokenEstimate +} - if (effectiveCount > effectiveMaxTokens) { - throw new MaxFileReadTokenExceededError(effectiveCount, effectiveMaxTokens) +async function validateContentTokens( + content: string, + ext: string, + maxTokens: number, +): Promise { + const tokenCount = await countContentTokens(content, ext, maxTokens) + if (tokenCount > maxTokens) { + throw new MaxFileReadTokenExceededError(tokenCount, maxTokens) } } +function linesWithinTokenLimit( + content: string, + tokenCount: number, + maxTokens: number, +): string[] { + const maxChars = (content.length * maxTokens) / tokenCount + const lines = content.split('\n') + let chars = -1 + let kept = 0 + for (const line of lines) { + chars += line.length + 1 + if (chars > maxChars) break + kept++ + } + return lines.slice(0, kept) +} + type ImageResult = { type: 'image' file: { @@ -1023,22 +1060,43 @@ async function callInner( // --- Text file (single async read via readFileInRange) --- const lineOffset = offset === 0 ? 0 : offset - 1 - const { content, lineCount, totalLines, totalBytes, readBytes, mtimeMs } = - await readFileInRange( - resolvedFilePath, - lineOffset, - limit, - limit === undefined ? maxSizeBytes : undefined, - context.abortController.signal, - ) + const truncateToFit = !context.fileReadingLimits?.failWhenOverLimit + const read = await readFileInRange( + resolvedFilePath, + lineOffset, + limit, + limit === undefined ? maxSizeBytes : undefined, + context.abortController.signal, + { truncateOnByteLimit: truncateToFit }, + ) + const { totalLines, totalBytes, mtimeMs } = read + if (read.truncatedByBytes && read.lineCount === 0) { + throw new FileTooLargeError(totalBytes, maxSizeBytes) + } - await validateContentTokens(content, ext, maxTokens) + let { content, lineCount } = read + const tokenCount = await countContentTokens(content, ext, maxTokens) + if (tokenCount > maxTokens) { + const lines = truncateToFit + ? linesWithinTokenLimit(content, tokenCount, maxTokens) + : [] + if (lines.length === 0) { + throw new MaxFileReadTokenExceededError(tokenCount, maxTokens) + } + content = lines.join('\n') + lineCount = lines.length + } + const truncated = read.truncatedByBytes || lineCount < read.lineCount + const readBytes = Buffer.byteLength(content, 'utf8') readFileState.set(fullFilePath, { content, timestamp: Math.floor(mtimeMs), offset, limit, + ...(truncated && { + truncated: { lastLine: lineOffset + lineCount, totalLines }, + }), }) context.nestedMemoryAttachmentTriggers?.add(fullFilePath) @@ -1056,6 +1114,7 @@ async function callInner( numLines: lineCount, startLine: offset, totalLines, + ...(truncated && { truncated }), }, } if (isAutoMemFile(fullFilePath)) { diff --git a/src/tools/FileReadTool/limits.ts b/src/tools/FileReadTool/limits.ts index 3e0247f6..b9afdd00 100644 --- a/src/tools/FileReadTool/limits.ts +++ b/src/tools/FileReadTool/limits.ts @@ -1,17 +1,3 @@ -/** - * Read tool output limits. Two caps apply to text reads: - * - * | limit | default | checks | cost | on overflow | - * |---------------|---------|---------------------------|---------------|-----------------| - * | maxSizeBytes | 256 KB | TOTAL FILE SIZE (not out) | 1 stat | throws pre-read | - * | maxTokens | 25000 | actual output tokens | API roundtrip | throws post-read| - * - * Known mismatch: maxSizeBytes gates on total file size, not the slice. - * Tested truncating instead of throwing for explicit-limit reads that - * exceed the byte cap (#21841, Mar 2026). Reverted: tool error rate - * dropped but mean tokens rose — the throw path yields a ~100-byte error - * tool-result while truncation yields ~25K tokens of content at the cap. - */ import memoize from 'lodash-es/memoize.js' import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js' import { MAX_OUTPUT_SIZE } from 'src/utils/file.js' diff --git a/src/tools/FileReadTool/prompt.ts b/src/tools/FileReadTool/prompt.ts index 8162776e..4a1f5e02 100644 --- a/src/tools/FileReadTool/prompt.ts +++ b/src/tools/FileReadTool/prompt.ts @@ -9,6 +9,34 @@ export const FILE_READ_TOOL_NAME = 'Read' export const FILE_UNCHANGED_STUB = 'File unchanged since last read. The content from the earlier Read tool_result in this conversation is still current — refer to that instead of re-reading.' +const READ_TRUNCATED_NOTE_START = + 'This read stopped early to fit the size limit' + +const READ_TRUNCATED_RANGE = /^: it returned lines \d+-(\d+) of (\d+)\./ + +export function readTruncatedNote( + firstLine: number, + lastLine: number, + totalLines: number, +): string { + return `\n\n${READ_TRUNCATED_NOTE_START}: it returned lines ${firstLine}-${lastLine} of ${totalLines}. Use offset and limit to read other parts of the file, for example offset ${lastLine + 1} for what follows.` +} + +export function readTruncatedRange( + result: string, +): { lastLine: number; totalLines: number } | null { + const start = result.indexOf(READ_TRUNCATED_NOTE_START) + if (start === -1) { + return null + } + const range = READ_TRUNCATED_RANGE.exec( + result.slice(start + READ_TRUNCATED_NOTE_START.length), + ) + return range + ? { lastLine: Number(range[1]), totalLines: Number(range[2]) } + : null +} + export const MAX_LINES_TO_READ = 2000 export const DESCRIPTION = 'Read a file from the local filesystem.' diff --git a/src/tools/FileWriteTool/FileWriteTool.ts b/src/tools/FileWriteTool/FileWriteTool.ts index c8253155..186def05 100644 --- a/src/tools/FileWriteTool/FileWriteTool.ts +++ b/src/tools/FileWriteTool/FileWriteTool.ts @@ -40,7 +40,11 @@ import { } from '../../utils/permissions/filesystem.js' import type { PermissionDecision } from '../../utils/permissions/PermissionResult.js' import { matchWildcardPattern } from '../../utils/permissions/shellRuleMatching.js' -import { FILE_UNEXPECTEDLY_MODIFIED_ERROR } from '../FileEditTool/constants.js' +import { + FILE_EDIT_TOOL_NAME, + FILE_UNEXPECTEDLY_MODIFIED_ERROR, + NO_READ_BACK_NOTE, +} from '../FileEditTool/constants.js' import { gitDiffSchema, hunkSchema } from '../FileEditTool/types.js' import { FILE_WRITE_TOOL_NAME, getWriteToolDescription } from './prompt.js' import { @@ -205,6 +209,14 @@ export const FileWriteTool = buildTool({ errorCode: 2, } } + if (readTimestamp.truncated) { + const { lastLine, totalLines } = readTimestamp.truncated + return { + result: false, + message: `The last read of this file stopped at line ${lastLine} of ${totalLines}, so writing it would discard lines that were never read. Read the rest with offset and limit first, or use ${FILE_EDIT_TOOL_NAME} to change part of the file.`, + errorCode: 4, + } + } // Reuse mtime from the stat above — avoids a redundant statSync via // getFileModificationTime. The readTimestamp guard above ensures this @@ -423,13 +435,13 @@ export const FileWriteTool = buildTool({ return { tool_use_id: toolUseID, type: 'tool_result', - content: `File created successfully at: ${filePath}`, + content: `File created successfully at: ${filePath}. ${NO_READ_BACK_NOTE}`, } case 'update': return { tool_use_id: toolUseID, type: 'tool_result', - content: `The file ${filePath} has been updated successfully.`, + content: `The file ${filePath} has been updated successfully. ${NO_READ_BACK_NOTE}`, } } }, diff --git a/src/tools/testing/agentContext.ts b/src/tools/testing/agentContext.ts new file mode 100644 index 00000000..d96860cc --- /dev/null +++ b/src/tools/testing/agentContext.ts @@ -0,0 +1,25 @@ +import { getDefaultAppState } from '../../state/AppStateStore.js' +import type { ToolUseContext } from '../../Tool.js' +import { createFileStateCacheWithSizeLimit } from '../../utils/fileStateCache.js' +import type { FileWriteTool } from '../FileWriteTool/FileWriteTool.js' + +export function agentContext(overrides: Partial = {}): ToolUseContext { + const appState = getDefaultAppState() + let fileHistory = appState.fileHistory + return { + updateFileHistoryState: (update: (state: typeof fileHistory) => typeof fileHistory) => { + fileHistory = update(fileHistory) + }, + readFileState: createFileStateCacheWithSizeLimit(100), + abortController: new AbortController(), + getAppState: () => appState, + setAppState: () => {}, + options: { tools: [], commands: [], mcpClients: [], agentDefinitions: { activeAgents: [], allAgents: [] }, isNonInteractiveSession: true }, + messages: [], + ...overrides, + } as unknown as ToolUseContext +} + +export const allow = (async () => ({ behavior: 'allow' })) as unknown as Parameters[2] + +export const turn = { uuid: 'turn-1' } as unknown as Parameters[3] diff --git a/src/utils/api.ts b/src/utils/api.ts index 0e285fe1..6601a534 100644 --- a/src/utils/api.ts +++ b/src/utils/api.ts @@ -19,10 +19,7 @@ import { prefetchAllMcpResources } from 'src/services/mcp/client.js' import type { ScopedMcpServerConfig } from 'src/services/mcp/types.js' import { BashTool } from 'src/tools/BashTool/BashTool.js' import { FileEditTool } from 'src/tools/FileEditTool/FileEditTool.js' -import { - normalizeFileEditInput, - stripTrailingWhitespace, -} from 'src/tools/FileEditTool/utils.js' +import { stripTrailingWhitespace } from 'src/tools/FileEditTool/utils.js' import { FileWriteTool } from 'src/tools/FileWriteTool/FileWriteTool.js' import { getTools } from 'src/tools.js' import type { AgentId } from 'src/types/ids.js' @@ -621,24 +618,16 @@ export function normalizeToolInput( // Validated upstream, won't throw const parsedInput = FileEditTool.inputSchema.parse(input) - // This is a workaround for tokens claude can't see - const { file_path, edits } = normalizeFileEditInput({ - file_path: parsedInput.file_path, - edits: [ - { - old_string: parsedInput.old_string, - new_string: parsedInput.new_string, - replace_all: parsedInput.replace_all, - }, - ], - }) + const isMarkdown = /\.(md|mdx)$/i.test(parsedInput.file_path) // SAFETY: See comment in BashTool case above return { - replace_all: edits[0]!.replace_all, - file_path, - old_string: edits[0]!.old_string, - new_string: edits[0]!.new_string, + replace_all: parsedInput.replace_all, + file_path: parsedInput.file_path, + old_string: parsedInput.old_string, + new_string: isMarkdown + ? parsedInput.new_string + : stripTrailingWhitespace(parsedInput.new_string), } as z.infer } case FileWriteTool.name: { diff --git a/src/utils/attachments.ts b/src/utils/attachments.ts index 3293f816..67fac0db 100644 --- a/src/utils/attachments.ts +++ b/src/utils/attachments.ts @@ -104,10 +104,7 @@ const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER') ? (require('./permissions/autoModeState.js') as typeof import('./permissions/autoModeState.js')) : null /* eslint-enable @typescript-eslint/no-require-imports */ -import { - MAX_LINES_TO_READ, - FILE_READ_TOOL_NAME, -} from 'src/tools/FileReadTool/prompt.js' +import { FILE_READ_TOOL_NAME } from 'src/tools/FileReadTool/prompt.js' import { getDefaultFileReadingLimits } from 'src/tools/FileReadTool/limits.js' import { cacheKeys, type FileStateCache } from './fileStateCache.js' import { @@ -293,10 +290,6 @@ export type FileAttachment = { type: 'file' filename: string content: FileReadToolOutput - /** - * Whether the file was truncated due to size limits - */ - truncated?: boolean /** Path relative to CWD at creation time, for stable display */ displayPath: string } @@ -321,10 +314,6 @@ export type AlreadyReadFileAttachment = { type: 'already_read_file' filename: string content: FileReadToolOutput - /** - * Whether the file was truncated due to size limits - */ - truncated?: boolean /** Path relative to CWD at creation time, for stable display */ displayPath: string } @@ -2086,7 +2075,13 @@ export async function getChangedFiles( return null } - const result = await FileReadTool.call(fileInput, toolUseContext) + const result = await FileReadTool.call(fileInput, { + ...toolUseContext, + fileReadingLimits: { + ...toolUseContext.fileReadingLimits, + failWhenOverLimit: true, + }, + }) // Extract only the changed section if (result.data.type === 'text') { const snippet = getSnippetForTwoFileDiff( @@ -3068,49 +3063,6 @@ export async function generateFileAttachment( limit, } - async function readTruncatedFile(): Promise< - | FileAttachment - | CompactFileReferenceAttachment - | AlreadyReadFileAttachment - | null - > { - if (mode === 'compact') { - return { - type: 'compact_file_reference', - filename, - displayPath: relative(getCwd(), filename), - } - } - - // Check deny rules before reading truncated file - const appState = toolUseContext.getAppState() - if (isFileReadDenied(filename, appState.toolPermissionContext)) { - return null - } - - try { - // Read only the first MAX_LINES_TO_READ lines for files that are too large - const truncatedInput = { - file_path: filename, - offset: offset ?? 1, - limit: MAX_LINES_TO_READ, - } - const result = await FileReadTool.call(truncatedInput, toolUseContext) - logEvent(successEventName, {}) - - return { - type: 'file' as const, - filename, - content: result.data, - truncated: true, - displayPath: relative(getCwd(), filename), - } - } catch { - logEvent(errorEventName, {}) - return null - } - } - // Validate file path is valid const isValid = await FileReadTool.validateInput(fileInput, toolUseContext) if (!isValid.result) { @@ -3128,10 +3080,15 @@ export async function generateFileAttachment( } } catch (error) { if ( - error instanceof MaxFileReadTokenExceededError || - error instanceof FileTooLargeError + mode === 'compact' && + (error instanceof MaxFileReadTokenExceededError || + error instanceof FileTooLargeError) ) { - return await readTruncatedFile() + return { + type: 'compact_file_reference', + filename, + displayPath: relative(getCwd(), filename), + } } throw error } diff --git a/src/utils/fileStateCache.ts b/src/utils/fileStateCache.ts index c7bb2f1d..634cbcee 100644 --- a/src/utils/fileStateCache.ts +++ b/src/utils/fileStateCache.ts @@ -12,6 +12,7 @@ export type FileState = { // Edit/Write must require an explicit Read first. `content` here holds the // RAW disk bytes (for getChangedFiles diffing), not what the model saw. isPartialView?: boolean + truncated?: { lastLine: number; totalLines: number } } // Default max entries for read file state caches diff --git a/src/utils/messages.ts b/src/utils/messages.ts index bc93f5e7..211f5881 100644 --- a/src/utils/messages.ts +++ b/src/utils/messages.ts @@ -109,10 +109,7 @@ import { ASK_USER_QUESTION_TOOL_NAME } from 'src/tools/AskUserQuestionTool/promp import { BashTool } from 'src/tools/BashTool/BashTool.js' import { ExitPlanModeV2Tool } from 'src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js' import { FileEditTool } from 'src/tools/FileEditTool/FileEditTool.js' -import { - FILE_READ_TOOL_NAME, - MAX_LINES_TO_READ, -} from 'src/tools/FileReadTool/prompt.js' +import { FILE_READ_TOOL_NAME } from 'src/tools/FileReadTool/prompt.js' import { FileWriteTool } from 'src/tools/FileWriteTool/FileWriteTool.js' import { GLOB_TOOL_NAME } from 'src/tools/GlobTool/prompt.js' import { GREP_TOOL_NAME } from 'src/tools/GrepTool/prompt.js' @@ -3503,14 +3500,6 @@ Read the team config to discover your teammates' names. Check the task list peri file_path: attachment.filename, }), createToolResultMessage(FileReadTool, fileContent), - ...(attachment.truncated - ? [ - createUserMessage({ - content: `Note: The file ${attachment.filename} was too large and has been truncated to the first ${MAX_LINES_TO_READ} lines. Don't tell the user about this truncation. Use ${FileReadTool.name} to read more of the file if you need.`, - isMeta: true, // only claude will see this - }), - ] - : []), ]) } case 'notebook': { diff --git a/src/utils/queryHelpers.ts b/src/utils/queryHelpers.ts index a3661baf..ca88571d 100644 --- a/src/utils/queryHelpers.ts +++ b/src/utils/queryHelpers.ts @@ -14,6 +14,7 @@ import type { Input as FileReadInput } from '../tools/FileReadTool/FileReadTool. import { FILE_READ_TOOL_NAME, FILE_UNCHANGED_STUB, + readTruncatedRange, } from '../tools/FileReadTool/prompt.js' import { FILE_WRITE_TOOL_NAME } from '../tools/FileWriteTool/prompt.js' import type { Message } from '../types/message.js' @@ -427,6 +428,7 @@ export function extractReadFilesFromMessages( // overwrite the real entry with stub text. !content.content.startsWith(FILE_UNCHANGED_STUB) ) { + const truncated = readTruncatedRange(content.content) // Remove system-reminder blocks from the content const processedContent = content.content.replace( /[\s\S]*?<\/system-reminder>/g, @@ -447,8 +449,9 @@ export function extractReadFilesFromMessages( cache.set(readFilePath, { content: fileContent, timestamp, - offset: undefined, + offset: truncated ? 1 : undefined, limit: undefined, + ...(truncated && { truncated }), }) } } @@ -479,11 +482,13 @@ export function extractReadFilesFromMessages( try { const { content: diskContent } = readFileSyncWithMetadata(editFilePath) + const truncated = cache.get(editFilePath)?.truncated cache.set(editFilePath, { content: diskContent, timestamp: getFileModificationTime(editFilePath), offset: undefined, limit: undefined, + ...(truncated && { truncated }), }) } catch (e: unknown) { if (!isFsInaccessible(e)) { From 8e001ab4df6d1cf9870f0a64dea4470bb9a58c77 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:02:04 +0800 Subject: [PATCH 2/2] docs(harness): cite #299 in the status lines and CHANGELOG --- CHANGELOG.md | 2 +- docs/features/harness/README.md | 4 ++-- .../harness/comparison/loop-execution.md | 20 +++++++++---------- docs/features/harness/prompt/reminders.md | 2 +- docs/features/harness/prompt/tools.md | 4 ++-- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08451893..479b44f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ All notable changes to DreamCoder will be documented in this file. - Plan mode follows one procedure: the agent explores, asks you questions and writes the plan file as it goes, instead of being told in one place not to write any file and in another to launch planning subagents (#270). - With models other than Claude, notes that arrive in the middle of a turn (messages from other sessions, board notifications, reminders) are sent as their own message instead of being appended to the last tool result (#270). - The notice for a file that changed after the agent read it no longer claims you or a linter changed it or asks the agent to keep it from you, and shows at most about 2 KB of the change (#270). -- **Fewer wasted steps when the agent reads and edits files.** Reading a file that is too large returns the first lines that fit and says which lines they are, instead of an error; a file attached with @ is cut the same way instead of at 2,000 lines. An edit still applies when the text the agent quotes differs from the file only in line-number prefixes, whitespace at the end of lines, indentation or written-out escapes, and the approval prompt shows the text that will actually be written. After such a partial read the agent can edit the file but cannot overwrite it, and a successful edit or write tells the agent not to read the file back. +- **Fewer wasted steps when the agent reads and edits files.** Reading a file that is too large returns the first lines that fit and says which lines they are, instead of an error; a file attached with @ is cut the same way instead of at 2,000 lines. An edit still applies when the text the agent quotes differs from the file only in line-number prefixes, whitespace at the end of lines, indentation or written-out escapes, and the approval prompt shows the text that will actually be written. After such a partial read the agent can edit the file but cannot overwrite it, and a successful edit or write tells the agent not to read the file back (#299). ### Fixed diff --git a/docs/features/harness/README.md b/docs/features/harness/README.md index 07ed67d5..f52d09f6 100644 --- a/docs/features/harness/README.md +++ b/docs/features/harness/README.md @@ -94,8 +94,8 @@ DreamCoder 的 CLI 派生自 Claude Code 2.1.92(`src/constants/claudeCodeCompa ### 5. 执行层 -- 编辑只处理弯引号,缩进、行尾空白、行号前缀、转义的偏差都会直接失败。ZCode 有 7 种回退,Codex 有 4 遍逐级放宽。本次修复:精确和弯引号之后,依次尝试行号前缀、行尾空白、缩进、转义四种匹配,每种都要求只有一个候选;缩进匹配上时按同一关系调整 `new_string`,找不到统一的对应关系就不匹配(`src/tools/FileEditTool/matchEdit.ts`)。执行时按当时的文件匹配,确认框和 hook 拿到的是按匹配结果改写后的输入,用户确认的就是要写入的文本;会话记录和对话里的工具卡片仍是模型给的原文。Edit 和 Write 成功的结果里加了一句不需要读回;Edit 实际写入的文本和模型给的 `new_string` 不同,或者用户在确认时改过内容,就不加。 -- Read 超过 25,000 token 直接报错,模型要多一轮按段重读;ZCode 返回前一部分。本次修复:超过 token 上限或字节上限时按行返回能放下的前一部分,并说明返回的行范围、总行数和继续读的方法;一行都放不下时仍然报错。被裁过的读之后 Edit 可以继续,Write 会被拒绝,直到有一次没被裁的读;CLI 重启后从会话记录恢复时,这个限制仍然保留。用 `@` 附上的文件也按同一规则返回前一部分。 +- 编辑只处理弯引号,缩进、行尾空白、行号前缀、转义的偏差都会直接失败。ZCode 有 7 种回退,Codex 有 4 遍逐级放宽。已在 #299 修复:精确和弯引号之后,依次尝试行号前缀、行尾空白、缩进、转义四种匹配,每种都要求只有一个候选;缩进匹配上时按同一关系调整 `new_string`,找不到统一的对应关系就不匹配(`src/tools/FileEditTool/matchEdit.ts`)。执行时按当时的文件匹配,确认框和 hook 拿到的是按匹配结果改写后的输入,用户确认的就是要写入的文本;会话记录和对话里的工具卡片仍是模型给的原文。Edit 和 Write 成功的结果里加了一句不需要读回;Edit 实际写入的文本和模型给的 `new_string` 不同,或者用户在确认时改过内容,就不加。 +- Read 超过 25,000 token 直接报错,模型要多一轮按段重读;ZCode 返回前一部分。已在 #299 修复:超过 token 上限或字节上限时按行返回能放下的前一部分,并说明返回的行范围、总行数和继续读的方法;一行都放不下时仍然报错。被裁过的读之后 Edit 可以继续,Write 会被拒绝,直到有一次没被裁的读;CLI 重启后从会话记录恢复时,这个限制仍然保留。用 `@` 附上的文件也按同一规则返回前一部分。 - 不读 `AGENTS.md`,`src` 里只有 `/init` 提到它。DreamCoder 自己的仓库就只有 `AGENTS.md`。 - 外部构建里没有「完成前先验证」的条文。 - 没有空响应重试和重复调用提醒(ZCode 有)。 diff --git a/docs/features/harness/comparison/loop-execution.md b/docs/features/harness/comparison/loop-execution.md index e51c553d..37d3020d 100644 --- a/docs/features/harness/comparison/loop-execution.md +++ b/docs/features/harness/comparison/loop-execution.md @@ -17,7 +17,7 @@ 5. **只有 ZCode 有重复调用防护**:同名同参连续 3 次插入提醒(只提醒不拦截,每回合最多 3 次)。DreamCoder 与 Codex 未找到任何重复调用检测。ZCode 还有「静默 5 次响应提醒向用户汇报」。 6. **工具并行:Codex 和 ZCode 在流式过程中就开始执行,DreamCoder 在本场景下要等整个响应结束。** DreamCoder 的流式工具执行受 GrowthBook 门控,GrowthBook 关闭时为 false。Codex 对可并行工具不设数量上限;ZCode 与 DreamCoder 上限 10。 7. **读取上限:DreamCoder 与 ZCode 常量相同(256KB、25,000 token、描述写 2000 行但代码不按行截断),但超 token 时行为不同**:ZCode 首次整文件读取返回部分视图,DreamCoder 直接报错,模型要再发一次带 offset/limit 的请求。DreamCoder 每次 Read 结果末尾还附约 330 字符的恶意软件提醒,另两家没有。 - 状态:本次修复:超限时按行返回前一部分(代码现在按行截断),@ 附件不再按 2,000 行截断;Edit 匹配加了行号前缀、行尾空白、缩进、转义四种回退;成功文案告诉模型不必读回。见 [README](../README.md) 执行层。 + 状态:已在 #299 修复:超限时按行返回前一部分(代码现在按行截断),@ 附件不再按 2,000 行截断;Edit 匹配加了行号前缀、行尾空白、缩进、转义四种回退;成功文案告诉模型不必读回。见 [README](../README.md) 执行层。 8. **Shell 超时语义:Codex 不杀进程,10 秒后交回 session ID 由模型轮询;ZCode 与 DreamCoder 默认 120 秒,到时自动转后台并承诺完成后通知。** 输出上限:Codex 约 10,000 token/字节,ZCode 30KB 尾部预览,DreamCoder 30,000 字符。 9. **规划工具:Codex 不注册 `update_plan` 但 prompt 仍描述它;ZCode 的 TodoWrite 描述只有 3 行、不鼓励主动使用;DreamCoder 在应用里启用 4 个 Task 工具(约 8K 字符描述),描述要求「3 步以上主动使用」、开始前标 in_progress、完成后立即标 completed。** 这是 DreamCoder 在普通小任务上额外工具调用和往返的主要来源(推断)。 10. **子 agent:Codex 明文禁止未经要求就委派;ZCode 鼓励「需要跨多个文件阅读」时委派;DreamCoder 鼓励「超过 3 次查询」时用 Explore(模型为 provider 的 fastModel)。** DreamCoder 与 Codex 子 agent 都不能再嵌套(深度 1)。 @@ -67,7 +67,7 @@ | 描述长度 | prompt 一行 | Edit 约 380 字符 | Edit 约 1.2K 字符 | | read-before-edit | 无 | 有 | 有 | | 过期检查 | 无 | mtime 前进或大小变化 | mtime 前进且内容不同 | -| 匹配遍数 | 4 遍逐行 + 末尾空行回退 | 精确 + 7 回退 | 精确 + 弯引号;接收时反净化(本次:精确之后依次尝试反净化、弯引号、行号前缀、行尾空白、缩进、转义,都在执行时进行) | +| 匹配遍数 | 4 遍逐行 + 末尾空行回退 | 精确 + 7 回退 | 精确 + 弯引号;接收时反净化(#299:精确之后依次尝试反净化、弯引号、行号前缀、行尾空白、缩进、转义,都在执行时进行) | | 歧义处理 | 不拒绝,取游标后第一个 | 拒绝 | 拒绝 | | 失败提示是否带文件实际内容 | 否 | 否 | 否 | | 成功返回 | 文件列表 A/M/D,约 100–200 字符 | 一句话 + 「不要读回」 | 一句话,约 60–100 字符 | @@ -93,10 +93,10 @@ - 成功:`The file X has been updated successfully. (file state is current in your context — no need to Read it back)`(`edit.ts:53-77`);结果给模型的上限 100KB(`edit.ts:281-289`)。保留编码与行尾(`edit.ts:509-515`)。Write 描述约 230 字符,同样的未读/过期检查,保留原行尾(`handlers/write.ts:37-64, 109, 131`)。 **DreamCoder**(`src/tools/FileEditTool/`) -- 接收时(解析模型输出阶段,`src/utils/messages.ts:2798` → `src/utils/api.ts:622-645` → `utils.ts:581-662`):new_string 每行去尾部空白(.md/.mdx 除外);old_string 精确找不到时套用 18 项反净化表(``、``、`\n\nH:` 等,`utils.ts:531-550`),同样替换应用到 new_string。(本次:接收时不再读文件,只去 new_string 行尾空白;反净化改为 `matchEdit` 的一种匹配方式,在 validateInput、确认和 call 时都生效,见 `src/tools/FileEditTool/matchEdit.ts`) -- validateInput 顺序(`FileEditTool.ts:138-345`):old==new → deny 规则 → >1GiB(`:85`)→ 读入并 CRLF→LF → 文件不存在(附 Did you mean)/ old_string 空但文件非空 → .ipynb → 未读过或部分视图(code 6)→ 过期(code 7,文案同 ZCode)→ 精确匹配,失败再弯引号归一(`utils.ts:73-96`;本次:改为 `matchEdit` 的各种匹配方式)→ 找不到(code 8:`String to replace not found in file.\nString: `)→ 多处匹配(code 9)。 +- 接收时(解析模型输出阶段,`src/utils/messages.ts:2798` → `src/utils/api.ts:622-645` → `utils.ts:581-662`):new_string 每行去尾部空白(.md/.mdx 除外);old_string 精确找不到时套用 18 项反净化表(``、``、`\n\nH:` 等,`utils.ts:531-550`),同样替换应用到 new_string。(#299:接收时不再读文件,只去 new_string 行尾空白;反净化改为 `matchEdit` 的一种匹配方式,在 validateInput、确认和 call 时都生效,见 `src/tools/FileEditTool/matchEdit.ts`) +- validateInput 顺序(`FileEditTool.ts:138-345`):old==new → deny 规则 → >1GiB(`:85`)→ 读入并 CRLF→LF → 文件不存在(附 Did you mean)/ old_string 空但文件非空 → .ipynb → 未读过或部分视图(code 6)→ 过期(code 7,文案同 ZCode)→ 精确匹配,失败再弯引号归一(`utils.ts:73-96`;#299:改为 `matchEdit` 的各种匹配方式)→ 找不到(code 8:`String to replace not found in file.\nString: `)→ 多处匹配(code 9)。 - call 阶段再查一次过期,失败抛 `File has been unexpectedly modified. Read it again before attempting to write it.`(`FileEditTool.ts:445-470`;`constants.ts:10-11`)。new_string 为空且后接换行时连换行一起删(`utils.ts:218-229`)。保留编码(utf8/utf16le)与行尾(`src/utils/fileRead.ts:87-96`;`src/utils/file.ts:84-98`)。 -- 成功:`The file has been updated successfully.`(`FileEditTool.ts:555-575`)。没有「不要读回」提示(本次:加了一句不需要读回,写入文本和 new_string 不同或用户改过时不加)。 +- 成功:`The file has been updated successfully.`(`FileEditTool.ts:555-575`)。没有「不要读回」提示(#299:加了一句不需要读回,写入文本和 new_string 不同或用户改过时不加)。 - Write:已存在文件要求读过且未改(`src/tools/FileWriteTool/FileWriteTool.ts:199-219`);content 每行去尾空白(非 md,`src/utils/api.ts:646-660`);固定写 LF(`FileWriteTool.ts:307`);返回 `File created successfully at: ` 或 `The file has been updated successfully.`(`:426, 432`)。 - 读过的文件被外部修改后,下一次请求附 `edited_text_file` 附件(`src/utils/attachments.ts:862, 2047-2102`)。 @@ -125,7 +125,7 @@ - Codex:读取靠 `cat`/`sed -n`/`rg`;exec 输出预算默认 10,000 token(`codex:core/src/unified_exec/mod.rs:74`),回退模型截断策略 10,000 字节(`codex:models-manager/src/model_info.rs:126`),截断时加 `Warning: truncated output (original token count: N)`(`codex:core/src/tools/context.rs:519-521`)。 - ZCode:常量 256KB / 25,000 / 2,000(`zcode:contracts/src/tools/read.ts:15-17`);2,000 只用于描述和附件(`zcode:core/src/runtime/helpers/attachments.ts:307`;`zcode:core/src/tool/handlers/read.ts:72`)。超 token 的首次整读返回前若干行,提示放在批次后附件中(`zcode:core/src/tool/handlers/read-text.ts:150-200`);带 offset/limit 超限才报错。超 256KB 报错,文案与 DreamCoder 相同(`zcode:adapters/src/fs/text-range-reader.ts:41-43`)。去重文案(`read-text.ts:17-18`;`read.ts:207-210`)。描述写明「Do NOT re-read a file you just edited to verify」(`read.ts:78`)。Glob 100 条/100KB(`zcode:core/src/tool/handlers/glob.ts:20-21`);Grep 默认 files_with_matches(`grep.ts:29, 203`)。 -- DreamCoder:确认上限为 256KB(`src/utils/file.ts:48`;`src/utils/readFileInRange.ts:63, 96-101`,仅在未给 limit 时检查,`src/tools/FileReadTool/FileReadTool.ts:1017-1025`)与 25,000 token(`src/tools/FileReadTool/limits.ts` `DEFAULT_MAX_OUTPUT_TOKENS`;`FileReadTool.ts:176-183, 753-770`)。报错文案都要求「Use offset and limit parameters to read specific portions of the file, or search for specific content」,模型下一步是带 offset/limit 重读或改用 Grep,+1 往返。描述默认不提 256KB(`includeMaxSizeInPrompt` 来自 GrowthBook,`FileReadTool.ts:347-349`)。估算超过 6,250 token 时调用 count_tokens API;代理只接 `/proxy/v1/messages`(`src/server/proxy/handler.ts:11-17`),调用失败返回 null 后用估算值(`src/services/tokenEstimation.ts:192-198`)(推断:每次大文件读取多一次失败的本地 HTTP 请求)。2,000 行只用于描述和附件(`src/tools/FileReadTool/prompt.ts:37`;`src/utils/attachments.ts:3137`)(本次:附件不再按 2,000 行截断,2,000 只剩描述里那句)。去重仅对同 offset/limit、mtime 未变的 Read 生效(`FileReadTool.ts:530-570`),Edit 后的状态不参与去重。恶意软件提醒对 `claude-opus-4-7` 以外的所有模型都附(`FileReadTool.ts:697-698, 727-736`)。Grep head_limit 250、2 万字符(`src/tools/GrepTool/GrepTool.ts:108, 164`);Glob 100 个(`src/tools/GlobTool/GlobTool.ts:157`)。 +- DreamCoder:确认上限为 256KB(`src/utils/file.ts:48`;`src/utils/readFileInRange.ts:63, 96-101`,仅在未给 limit 时检查,`src/tools/FileReadTool/FileReadTool.ts:1017-1025`)与 25,000 token(`src/tools/FileReadTool/limits.ts` `DEFAULT_MAX_OUTPUT_TOKENS`;`FileReadTool.ts:176-183, 753-770`)。报错文案都要求「Use offset and limit parameters to read specific portions of the file, or search for specific content」,模型下一步是带 offset/limit 重读或改用 Grep,+1 往返。描述默认不提 256KB(`includeMaxSizeInPrompt` 来自 GrowthBook,`FileReadTool.ts:347-349`)。估算超过 6,250 token 时调用 count_tokens API;代理只接 `/proxy/v1/messages`(`src/server/proxy/handler.ts:11-17`),调用失败返回 null 后用估算值(`src/services/tokenEstimation.ts:192-198`)(推断:每次大文件读取多一次失败的本地 HTTP 请求)。2,000 行只用于描述和附件(`src/tools/FileReadTool/prompt.ts:37`;`src/utils/attachments.ts:3137`)(#299:附件不再按 2,000 行截断,2,000 只剩描述里那句)。去重仅对同 offset/limit、mtime 未变的 Read 生效(`FileReadTool.ts:530-570`),Edit 后的状态不参与去重。恶意软件提醒对 `claude-opus-4-7` 以外的所有模型都附(`FileReadTool.ts:697-698, 727-736`)。Grep head_limit 250、2 万字符(`src/tools/GrepTool/GrepTool.ts:108, 164`);Glob 100 个(`src/tools/GlobTool/GlobTool.ts:157`)。 ### 2.5 Shell @@ -213,17 +213,17 @@ TodoWrite 描述不要求主动使用,通常不调用。若 old_string 带行 |---|---|---| | 每次 Read 附恶意软件提醒 | 约 330 字符,除 `claude-opus-4-7` 外都附(`src/tools/FileReadTool/FileReadTool.ts:697-736`) | 每次读取多约 80–100 token,并累积进历史;对非 Claude 模型没有对应训练,可能使其对正常代码修改更犹豫 | | 应用内启用 4 个 Task 工具且描述要求主动、逐项更新 | `src/server/services/conversationService.ts:1052`;`src/constants/prompts.ts:270-282` | 小任务也可能多 1~2 次往返和多次工具调用;4 份描述每次请求都发送 | -| Read 超 25,000 token 直接报错 | `FileReadTool.ts:176-183, 753-770` | 大文件首读必定 +1 往返;ZCode 同常量但返回部分视图(本次修复) | +| Read 超 25,000 token 直接报错 | `FileReadTool.ts:176-183, 753-770` | 大文件首读必定 +1 往返;ZCode 同常量但返回部分视图(#299 修复) | | 大文件读取触发 count_tokens 请求 | 代理不接该路径(`src/server/proxy/handler.ts:11-17`) | 一次失败的本地 HTTP 请求,增加延迟,不增加 token | -| 接收时的反净化替换表 | `src/tools/FileEditTool/utils.ts:531-550` | 针对 Claude 输出特性的修正,对第三方模型基本无作用(本次:移入 `matchEdit`,执行时生效) | +| 接收时的反净化替换表 | `src/tools/FileEditTool/utils.ts:531-550` | 针对 Claude 输出特性的修正,对第三方模型基本无作用(#299:移入 `matchEdit`,执行时生效) | ### 另两家都有而 DreamCoder 没有 | 差异 | 事实 | 后果(推断) | |---|---|---| | 流式过程中开始执行工具 | Codex 全部、ZCode 只读类(`codex:core/src/stream_events_utils.rs:~345-372`;`zcode:core/src/runtime/methods/streaming-tool-coordinator.ts:383-406`);DreamCoder 被 GrowthBook 门关闭(`src/query/config.ts:33`) | 不影响 token 和轮数,只影响墙钟时间;与 benchmark 中 Claude Code「运行时间最长」方向一致,但贡献大小未测 | -| 编辑匹配对空白/缩进的容忍 | Codex trim_end/trim/Unicode 归一;ZCode 7 种回退;DreamCoder 只有弯引号 | 第三方模型常见的缩进、行尾空白、带行号前缀、转义错误在 DreamCoder 上都变成失败,每次 +1~2 往返,且需重发整段 old_string(本次修复) | -| 编辑成功后明确告诉模型「不要读回」 | ZCode 成功文案(`zcode:core/src/tool/handlers/edit.ts:59`)、Read 描述(`read.ts:78`);Codex prompt(`codex:models-manager/prompt.md:143`);DreamCoder 两处都没有 | 模型可能在编辑后再 Read 验证,+1 往返和一份全文输出(本次修复) | +| 编辑匹配对空白/缩进的容忍 | Codex trim_end/trim/Unicode 归一;ZCode 7 种回退;DreamCoder 只有弯引号 | 第三方模型常见的缩进、行尾空白、带行号前缀、转义错误在 DreamCoder 上都变成失败,每次 +1~2 往返,且需重发整段 old_string(#299 修复) | +| 编辑成功后明确告诉模型「不要读回」 | ZCode 成功文案(`zcode:core/src/tool/handlers/edit.ts:59`)、Read 描述(`read.ts:78`);Codex prompt(`codex:models-manager/prompt.md:143`);DreamCoder 两处都没有 | 模型可能在编辑后再 Read 验证,+1 往返和一份全文输出(#299 修复) | | 循环异常保护(在两家中至少一家有) | ZCode 有重复调用提醒、可疑空响应重试、静默提醒;Codex 没有。严格说这不是「两家都有」,单列在此 | DreamCoder 遇到第三方模型重复同一调用时没有任何干预;空响应直接结束回合,headless 运行会以空结果收尾 | ### 三家共同点(不构成差异,但影响判断) diff --git a/docs/features/harness/prompt/reminders.md b/docs/features/harness/prompt/reminders.md index 64fe21bb..03826d33 100644 --- a/docs/features/harness/prompt/reminders.md +++ b/docs/features/harness/prompt/reminders.md @@ -234,7 +234,7 @@ ### T-INJ-14 多处提醒要求模型「不要告诉用户」,这是针对 Claude 习惯写的措辞 -- 状态:部分修复:文件改动那句在 #270 去掉(同 T-INJ-06);@ 文件截断那句随 2,000 行截断一起删除(本次),@ 文件改为和 Read 同样按能放下的行数裁剪,并说明返回了哪几行。任务提醒和跨天提醒两句未改。 +- 状态:部分修复:文件改动那句在 #270 去掉(同 T-INJ-06);@ 文件截断那句随 2,000 行截断一起删除(#299),@ 文件改为和 Read 同样按能放下的行数裁剪,并说明返回了哪几行。任务提醒和跨天提醒两句未改。 - 类型:优化 - 严重程度:低 - 体量:每处 60~110 字符,随所在提醒出现 diff --git a/docs/features/harness/prompt/tools.md b/docs/features/harness/prompt/tools.md index 1a731b5c..c89ca297 100644 --- a/docs/features/harness/prompt/tools.md +++ b/docs/features/harness/prompt/tools.md @@ -230,7 +230,7 @@ ### T-TOOL-12 Read 描述说「默认最多读 2000 行」,实际默认读整个文件,256KB 和 25,000 token 的上限描述里没写 -- 状态:部分修复(本次):超过 token 或字节上限时按行返回能放下的前一部分,并说明行范围、总行数和继续读的方法,一行都放不下时仍报错;描述里大小上限那句同步改了。「默认最多 2000 行」和「建议读整个文件」两句未改。 +- 状态:部分修复(#299):超过 token 或字节上限时按行返回能放下的前一部分,并说明行范围、总行数和继续读的方法,一行都放不下时仍报错;描述里大小上限那句同步改了。「默认最多 2000 行」和「建议读整个文件」两句未改。 - 类型:问题 - 严重程度:中 - 体量:描述 1 句;后果是超限时多一轮。 @@ -347,7 +347,7 @@ ### T-TOOL-21 缺少「编辑后不必重读验证」的说明;Edit 的「最小 old_string」提示只给 ant -- 状态:已修复(本次):Edit 和 Write 成功的结果末尾加了一句不需要读回;没有写进 Read 描述。 +- 状态:已修复(#299):Edit 和 Write 成功的结果末尾加了一句不需要读回;没有写进 Read 描述。 - 状态:部分修复(#270):ant 专用的「最小 old_string」提示已删除;「编辑后不必重读」未定。 - 状态:维护者已定(2026-11-18):「最小 old_string」这条 ant 专用提示随 ant 分支一起删除;「编辑后不必重读」未定。 - 类型:缺失