Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(tools): adapt legacy old_string/new_string shape in Edit tool
Totopo27ecaf4c643070
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex de74c150d..9be84c3cb 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1411,16 +1411,6 @@ fn tool_edit(.get("path").and_then(|v| v.as_str()).ok_or_else(|| hashline::ToolError::new("INVALID_ARGUMENT", "path required"))?;- let tag = args.get("tag").and_then(|v| v.as_str()).ok_or_else(|| {- hashline::ToolError::new(- "EDIT_TAG_REQUIRED",- "tag required; pass the 4-hex tag from the latest Read, Grep, Write, or Edit",- )- })?;- let ops = args- .get("ops")- .and_then(|v| v.as_str())- .ok_or_else(|| hashline::ToolError::new("INVALID_ARGUMENT", "ops required"))?;let (resolved, root_kind) =resolve_tool_path_with_external(root, scratch, path, allow_external_paths).map_err(|e| hashline::ToolError::new(e.clone(), e))?;@@ -1435,13 +1425,68 @@ fn tool_edit(hashline::ToolError::new("TOOL_FAILED", format!("read failed: {e}"))}})?;+ let legacy_old = args.get("old_string").and_then(Value::as_str);+ let legacy_new = args.get("new_string").and_then(Value::as_str);+ let (tag, ops) = match (+ args.get("tag").and_then(Value::as_str),+ args.get("ops").and_then(Value::as_str),+ legacy_old,+ legacy_new,+ ) {+ (Some(tag), Some(ops), _, _) => (tag.to_string(), ops.to_string()),+ (None, None, Some(old), Some(new)) => {+ let file = hashline::normalize_file(&live);+ let tag = hashline::tag_of_lf_text(&file.text);+ let matches: Vec<_> = file+ .text+ .match_indices(old)+ .map(|(start, _)| start)+ .collect();+ if matches.is_empty() {+ return Err(hashline::ToolError::new(+ "EDIT_LEGACY_MATCH_FAILED",+ format!(+ "old_string not found in {path}; re-read the file to verify the content"+ ),+ ));+ }+ if matches.len() > 1 {+ return Err(hashline::ToolError::new(+ "EDIT_LEGACY_MATCH_FAILED",+ format!(+ "old_string must match exactly once; found {} matches in {path}",+ matches.len()+ ),+ ));+ }+ let start = matches[0];+ let first_line = file.text[..start].bytes().filter(|b| *b == b'\n').count() + 1;+ let old_lines = old.split('\n').count().max(1);+ let mut ops = format!("PUT {first_line}.={}:\n", first_line + old_lines - 1);+ for line in new.split('\n') {+ ops.push('+');+ ops.push_str(line);+ ops.push('\n');+ }+ (tag, ops)+ }+ (None, _, _, _) => {+ return Err(hashline::ToolError::new(+ "EDIT_TAG_REQUIRED",+ "tag required; pass the 4-hex tag from the latest Read, Grep, Write, or Edit",+ ));+ }+ (_, None, _, _) => {+ return Err(hashline::ToolError::new("INVALID_ARGUMENT", "ops required"));+ }+ };let display = display_tool_path(root_kind, root, &resolved);let canonical = hashline::canonical_key(&resolved);let (file, success) = hashline::apply_edit(&display,&canonical,- tag,- ops,+ &tag,+ &ops,&live,hashline.map(|c| c.session_id),hashline.map(|c| c.store),@@ -4480,6 +4525,55 @@ mod tests {assert_eq!(written, "line one\r\nline TWO replaced\r\nline three\r\n");}+ #[tokio::test]+ async fn edit_accepts_legacy_old_string_new_string_shape() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("legacy.txt");+ std::fs::write(&target, "fn main() {\n println!(\"hello\");\n}\n").unwrap();++ // Model sends old_string and new_string without tag or ops+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Edit",+ &serde_json::json!({+ "path": "legacy.txt",+ "old_string": " println!(\"hello\");",+ "new_string": " println!(\"world\");"+ }),+ 5_000,+ )+ .await;+ assert!(+ result.ok,+ "Edit with legacy shape should succeed: {:?}",+ result.content+ );+ assert_eq!(result.content["tag"].as_str().unwrap().len(), 4);++ let written = std::fs::read_to_string(&target).unwrap();+ assert_eq!(written, "fn main() {\n println!(\"world\");\n}\n");++ // Fails cleanly when old_string is not found+ let not_found = execute_tool(+ Some(dir.path()),+ None,+ "Edit",+ &serde_json::json!({+ "path": "legacy.txt",+ "old_string": "non_existent_text",+ "new_string": "replacement"+ }),+ 5_000,+ )+ .await;+ assert!(!not_found.ok);+ assert_eq!(+ not_found.error_code.as_deref(),+ Some("EDIT_LEGACY_MATCH_FAILED")+ );+ }+#[tokio::test]async fn read_missing_file_reports_file_not_found() {let dir = tempfile::tempdir().unwrap();diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex 36c623f8b..8e0a6edff 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -195,6 +195,7 @@ loses that. See| code | retriable | meaning ||---|---|---|| `EDIT_TAG_REQUIRED` | no | `tag` missing or not 4 hex digits |+| `EDIT_LEGACY_MATCH_FAILED` | yes after a `Read` | legacy `old_string` was not found or matched multiple times; model must re-read or provide unique context || `EDIT_TAG_MISMATCH` | yes after a `Read` | tag does not hash the live file and drift recovery declined; carries the live tag and current content at the anchors || `EDIT_TAG_UNKNOWN` | yes after a `Read` | tag is well-formed but the session recorded no such content for the path || `EDIT_LINES_UNSEEN` | yes | anchors reference lines the session never displayed; carries the revealed content |diff --git a/docs/spec/03-runtime/18-line-anchored-edit-contract.md b/docs/spec/03-runtime/18-line-anchored-edit-contract.mdindex 1f1d26513..efa768497 100644--- a/docs/spec/03-runtime/18-line-anchored-edit-contract.md+++ b/docs/spec/03-runtime/18-line-anchored-edit-contract.md@@ -518,6 +518,7 @@ Recovery warnings distinguish cause, because the corrective action differs:| code | retriable | meaning ||---|---|---|| `EDIT_TAG_REQUIRED` | no | `tag` missing or not 4 hex |+| `EDIT_LEGACY_MATCH_FAILED` | yes after a `Read` | legacy `old_string` was not found or matched multiple times || `EDIT_TAG_MISMATCH` | yes after a `Read` | tag does not hash the live file and recovery declined; carries the live tag and current content at the anchors || `EDIT_TAG_UNKNOWN` | yes after a `Read` | tag is well-formed but this session recorded no such content for the path || `EDIT_LINES_UNSEEN` | yes | anchors reference lines never displayed; carries the revealed content |diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.mdindex c30ff27b6..8b0fbb458 100644--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@ -196,6 +196,7 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况| 代码 | 可重试 | 含义 ||---|---|---|| `EDIT_TAG_REQUIRED` | 否 | `tag` 缺失或不是 4 位十六进制 |+| `EDIT_LEGACY_MATCH_FAILED` | `Read` 之后可以 | 旧版兼容参数 `old_string` 未找到或出现多次 || `EDIT_TAG_MISMATCH` | `Read` 之后可以 | tag 无法哈希出实时文件且漂移恢复拒绝;携带实时 tag 与锚点处的当前内容 || `EDIT_TAG_UNKNOWN` | `Read` 之后可以 | tag 格式正确,但本会话没有为该路径记录过对应内容 || `EDIT_LINES_UNSEEN` | 是 | 锚点引用了会话从未显示过的行;携带被揭示的内容 |diff --git a/docs/zh-CN/spec/03-runtime/18-line-anchored-edit-contract.md b/docs/zh-CN/spec/03-runtime/18-line-anchored-edit-contract.mdindex 3810efc63..083678da6 100644--- a/docs/zh-CN/spec/03-runtime/18-line-anchored-edit-contract.md+++ b/docs/zh-CN/spec/03-runtime/18-line-anchored-edit-contract.md@@ -442,6 +442,7 @@ turn 与一个选择什么都不说的模型无法区分。| 代码 | 可重试 | 含义 ||---|---|---|| `EDIT_TAG_REQUIRED` | 否 | `tag` 缺失或不是 4 位十六进制 |+| `EDIT_LEGACY_MATCH_FAILED` | `Read` 之后可以 | 旧版兼容参数 `old_string` 未找到或出现多次 || `EDIT_TAG_MISMATCH` | `Read` 之后可以 | tag 无法哈希出实时文件且恢复拒绝;携带实时 tag 与锚点处的当前内容 || `EDIT_TAG_UNKNOWN` | `Read` 之后可以 | tag 格式正确,但本会话没有为该路径记录过对应内容 || `EDIT_LINES_UNSEEN` | 是 | 锚点引用了从未显示过的行;携带被揭示的内容 |diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 3d2fc7e9c..c62804ac0 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -808,6 +808,39 @@ describe("DesktopAgentRuntime configuration matching", () => {await runtime.dispose();});+ it("executes an edit with legacy old_string and new_string parameters", async () => {+ let capturedArgs: any;+ const host = {+ call: vi.fn(async (method: string, params: any) => {+ if (method !== "tools.execute") return undefined;+ capturedArgs = params.args;+ return {+ ok: true,+ isError: false,+ content: { path: "src/example.ts", tag: "C3D4" },+ };+ }),+ };+ const runtime = createRuntime({ host });+ const agent = (runtime as any).agent;+ const edit = agent.state.tools.find((tool: any) => tool.name === "Edit");+ const args = {+ path: "src/example.ts",+ old_string: "const a = 1;",+ new_string: "const a = 2;",+ };++ const result = await edit.execute("edit-legacy", args);+ expect(result.isError).toBe(false);+ expect(capturedArgs).toMatchObject({+ path: "src/example.ts",+ old_string: "const a = 1;",+ new_string: "const a = 2;",+ });++ await runtime.dispose();+ });+it("reports a visible error row when the mutation guard ends the turn", async () => {const onEvent = vi.fn();const host = {diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex e148770e6..98aa572dd 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -3014,14 +3014,30 @@ Do not invent objections or turn speculative risks into blockers. Stop when theEdit: {path: pathParam("File to edit; workspace-relative."),file_path: aliasParam("path"),- tag: Type.String({- description:- "4 uppercase hex from the latest Read, Grep, Write, or Edit for this path.",- }),- ops: Type.String({- description:- "One or more operation headers with + body rows, newline separated. A PUT with body rows must end its header with `:` (for example, `PUT 48.=48:`); `PUT 48.=48` followed by + rows is invalid. A colonless PUT is only for a register paste such as `PUT <1 @name`.",- }),+ tag: Type.Optional(+ Type.String({+ description:+ "4 uppercase hex from the latest Read, Grep, Write, or Edit for this path. Required unless legacy old_string/new_string is used.",+ }),+ ),+ ops: Type.Optional(+ Type.String({+ description:+ "One or more operation headers with + body rows, newline separated. A PUT with body rows must end its header with `:` (for example, `PUT 48.=48:`); `PUT 48.=48` followed by + rows is invalid. A colonless PUT is only for a register paste such as `PUT <1 @name`. Required unless legacy old_string/new_string is used.",+ }),+ ),+ old_string: Type.Optional(+ Type.String({+ description:+ "Legacy text replacement: exact text to be replaced (must match exactly once in the target file).",+ }),+ ),+ new_string: Type.Optional(+ Type.String({+ description:+ "Legacy text replacement: new text to replace old_string with.",+ }),+ ),},Bash: {command: Type.String(),diff --git a/packages/shared/src/errors.test.ts b/packages/shared/src/errors.test.tsindex 4b78b3bc5..f8b53f443 100644--- a/packages/shared/src/errors.test.ts+++ b/packages/shared/src/errors.test.ts@@ -37,6 +37,7 @@ describe("result helpers", () => {"EMPTY_MODEL_RESPONSE","SUBAGENT_OUTPUT_TRUNCATED","EDIT_TAG_REQUIRED",+ "EDIT_LEGACY_MATCH_FAILED","EDIT_TAG_MISMATCH","EDIT_TAG_UNKNOWN","EDIT_LINES_UNSEEN",diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.tsindex c4458599a..b316de887 100644--- a/packages/shared/src/errors.ts+++ b/packages/shared/src/errors.ts@@ -150,6 +150,7 @@ export const ErrorCodes = {PROCESS_RESOURCE_EXHAUSTED: "PROCESS_RESOURCE_EXHAUSTED",TOOL_ABORTED: "TOOL_ABORTED",EDIT_TAG_REQUIRED: "EDIT_TAG_REQUIRED",+ EDIT_LEGACY_MATCH_FAILED: "EDIT_LEGACY_MATCH_FAILED",EDIT_TAG_MISMATCH: "EDIT_TAG_MISMATCH",EDIT_TAG_UNKNOWN: "EDIT_TAG_UNKNOWN",EDIT_LINES_UNSEEN: "EDIT_LINES_UNSEEN",