march-cli 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.md +1 -1
  2. package/README.zh.md +1 -1
  3. package/bin/march.mjs +13 -13
  4. package/package.json +49 -43
  5. package/src/agent/command-exec-tool.mjs +172 -172
  6. package/src/agent/context-stats-tool.mjs +57 -57
  7. package/src/agent/editing/cohesion-warning.mjs +57 -0
  8. package/src/agent/editing/diff-apply.mjs +28 -28
  9. package/src/agent/editing/diff-format.mjs +57 -57
  10. package/src/agent/editing/lsp-report.mjs +69 -69
  11. package/src/agent/file-edit-tool.mjs +277 -262
  12. package/src/agent/file-tools/read-file-tool.mjs +112 -112
  13. package/src/agent/file-tools/read-image-tool.mjs +76 -76
  14. package/src/agent/model-payload-dumper.mjs +208 -208
  15. package/src/agent/pi-session/pi-session-sidecar-failure.mjs +10 -10
  16. package/src/agent/provider/payload-messages.mjs +138 -138
  17. package/src/agent/runner/codex-large-context-guard.mjs +87 -87
  18. package/src/agent/runner/codex-transport-compression.mjs +180 -180
  19. package/src/agent/runner/codex-transport-debug.mjs +113 -113
  20. package/src/agent/runner/codex-websocket-event-debug.mjs +130 -130
  21. package/src/agent/runner/fast-model.mjs +36 -36
  22. package/src/agent/runner/runner-cleanup.mjs +12 -12
  23. package/src/agent/runner/runner-init.mjs +15 -15
  24. package/src/agent/runner/runner-session-state.mjs +40 -40
  25. package/src/agent/runner/runner-utils.mjs +24 -24
  26. package/src/agent/runner.mjs +299 -299
  27. package/src/agent/runtime/ipc/ipc-peer.mjs +99 -99
  28. package/src/agent/runtime/ipc/process-ipc-transport.mjs +16 -16
  29. package/src/agent/runtime/remote-runner-client.mjs +73 -73
  30. package/src/agent/runtime/remote-ui-client.mjs +20 -20
  31. package/src/agent/runtime/runner-ipc-target.mjs +125 -125
  32. package/src/agent/runtime/runner-process-client.mjs +47 -47
  33. package/src/agent/runtime/runner-process-entry.mjs +11 -11
  34. package/src/agent/runtime/runner-process-factory.mjs +111 -108
  35. package/src/agent/runtime/runner-runtime-host.mjs +79 -79
  36. package/src/agent/runtime/runtime-factory.mjs +42 -42
  37. package/src/agent/runtime/runtime-host.mjs +34 -34
  38. package/src/agent/runtime/ui-event-bridge.mjs +95 -95
  39. package/src/agent/screen-tools/list-windows-tool.mjs +39 -39
  40. package/src/agent/screen-tools/screen-tool.mjs +49 -49
  41. package/src/agent/screen-tools/windows-screen.mjs +133 -133
  42. package/src/agent/session/session-auto-name.mjs +41 -41
  43. package/src/agent/session/session-binding.mjs +12 -12
  44. package/src/agent/session/session-options.mjs +47 -47
  45. package/src/agent/tool-names.mjs +1 -1
  46. package/src/agent/tool-result.mjs +3 -3
  47. package/src/agent/tool-summary.mjs +112 -112
  48. package/src/agent/tools.mjs +58 -58
  49. package/src/agent/turn/turn-events.mjs +111 -111
  50. package/src/agent/turn/turn-logging.mjs +30 -30
  51. package/src/agent/turn/turn-runner.mjs +196 -196
  52. package/src/agent/vision-capability.mjs +14 -14
  53. package/src/auth/login-command.mjs +90 -90
  54. package/src/auth/storage.mjs +34 -34
  55. package/src/cli/args.mjs +96 -79
  56. package/src/cli/commands/copy-command.mjs +87 -87
  57. package/src/cli/commands/export-command.mjs +206 -206
  58. package/src/cli/commands/extensions-command.mjs +53 -53
  59. package/src/cli/commands/help-command.mjs +7 -7
  60. package/src/cli/commands/model-command.mjs +141 -141
  61. package/src/cli/commands/paste-image-command.mjs +43 -43
  62. package/src/cli/commands/provider-command.mjs +59 -59
  63. package/src/cli/commands/status-command.mjs +196 -194
  64. package/src/cli/commands/thinking-command.mjs +87 -87
  65. package/src/cli/fallback-ui.mjs +156 -156
  66. package/src/cli/input/attachment-tokens.mjs +20 -20
  67. package/src/cli/input/autocomplete.mjs +74 -74
  68. package/src/cli/input/external-editor.mjs +39 -39
  69. package/src/cli/input/file-search/index.mjs +160 -160
  70. package/src/cli/input/history-store.mjs +35 -35
  71. package/src/cli/input/image-clipboard.mjs +55 -55
  72. package/src/cli/input/keybinding-dispatch.mjs +76 -76
  73. package/src/cli/input/keybindings.mjs +96 -96
  74. package/src/cli/input/mode-state.mjs +43 -43
  75. package/src/cli/input/prompt-templates.mjs +84 -84
  76. package/src/cli/input/select-with-keyboard.mjs +86 -86
  77. package/src/cli/permissions.mjs +103 -103
  78. package/src/cli/repl-commands.mjs +86 -86
  79. package/src/cli/repl-loop.mjs +183 -183
  80. package/src/cli/selector-list.mjs +21 -21
  81. package/src/cli/session/pi-session-switch-command.mjs +41 -41
  82. package/src/cli/session/session-command.mjs +23 -23
  83. package/src/cli/session/session-list-command.mjs +68 -68
  84. package/src/cli/session/session-name-command.mjs +26 -26
  85. package/src/cli/session/session-source-command.mjs +89 -89
  86. package/src/cli/session/session-switch-command.mjs +1 -1
  87. package/src/cli/shell/shell-command.mjs +55 -55
  88. package/src/cli/shell/shell-drawer-controls.mjs +33 -33
  89. package/src/cli/shell/shell-drawer.mjs +192 -192
  90. package/src/cli/shell/shell-split-layout.mjs +70 -70
  91. package/src/cli/slash-commands.mjs +192 -192
  92. package/src/cli/startup/create-runtime-runner.mjs +61 -61
  93. package/src/cli/startup/runtime-close.mjs +23 -23
  94. package/src/cli/startup/startup-banner.mjs +71 -71
  95. package/src/cli/startup/startup-session.mjs +51 -51
  96. package/src/cli/status-line-updater.mjs +75 -75
  97. package/src/cli/tool-output.mjs +9 -9
  98. package/src/cli/tui/editor/external-editor-runner.mjs +24 -24
  99. package/src/cli/tui/input/mouse-selection-controller.mjs +91 -91
  100. package/src/cli/tui/input/mouse-tracking.mjs +20 -20
  101. package/src/cli/tui/layout/main-pane-layout.mjs +47 -47
  102. package/src/cli/tui/layout/safe-render-boundary.mjs +46 -46
  103. package/src/cli/tui/markdown-renderer.mjs +285 -285
  104. package/src/cli/tui/output/scroll-state.mjs +79 -79
  105. package/src/cli/tui/output/text-line-renderer.mjs +50 -50
  106. package/src/cli/tui/output/tool-card-renderer.mjs +59 -59
  107. package/src/cli/tui/output/visible-lines.mjs +8 -8
  108. package/src/cli/tui/output-buffer.mjs +293 -293
  109. package/src/cli/tui/permission-request-ui.mjs +18 -18
  110. package/src/cli/tui/recall-rendering.mjs +28 -25
  111. package/src/cli/tui/render/render-scheduler.mjs +26 -26
  112. package/src/cli/tui/render/stream-delta-buffer.mjs +46 -46
  113. package/src/cli/tui/select/editor-select-list.mjs +111 -111
  114. package/src/cli/tui/selection-screen.mjs +269 -269
  115. package/src/cli/tui/status/retry-status.mjs +72 -72
  116. package/src/cli/tui/status/spinner-status.mjs +42 -42
  117. package/src/cli/tui/status/status-bar.mjs +225 -225
  118. package/src/cli/tui/syntax/highlighting.mjs +260 -260
  119. package/src/cli/tui/syntax/languages.mjs +91 -91
  120. package/src/cli/tui/syntax/tree-sitter/bash.highlights.scm +261 -261
  121. package/src/cli/tui/syntax/tree-sitter/c.highlights.scm +341 -341
  122. package/src/cli/tui/syntax/tree-sitter/cpp.highlights.scm +268 -268
  123. package/src/cli/tui/syntax/tree-sitter/csharp.highlights.scm +577 -577
  124. package/src/cli/tui/syntax/tree-sitter/css.highlights.scm +109 -109
  125. package/src/cli/tui/syntax/tree-sitter/diff.highlights.scm +49 -49
  126. package/src/cli/tui/syntax/tree-sitter/go.highlights.scm +254 -254
  127. package/src/cli/tui/syntax/tree-sitter/html.highlights.scm +13 -13
  128. package/src/cli/tui/syntax/tree-sitter/java.highlights.scm +330 -330
  129. package/src/cli/tui/syntax/tree-sitter/json.highlights.scm +38 -38
  130. package/src/cli/tui/syntax/tree-sitter/php.highlights.scm +203 -203
  131. package/src/cli/tui/syntax/tree-sitter/python.highlights.scm +137 -137
  132. package/src/cli/tui/syntax/tree-sitter/ruby.highlights.scm +309 -309
  133. package/src/cli/tui/syntax/tree-sitter/rust.highlights.scm +531 -531
  134. package/src/cli/tui/syntax/tree-sitter/toml.highlights.scm +39 -39
  135. package/src/cli/tui/syntax/tree-sitter/tsx.highlights.scm +35 -35
  136. package/src/cli/tui/syntax/tree-sitter/typescript.highlights.scm +35 -35
  137. package/src/cli/tui/syntax/tree-sitter/yaml.highlights.scm +99 -99
  138. package/src/cli/tui/tool-rendering.mjs +87 -87
  139. package/src/cli/tui/tui-diff-rendering.mjs +157 -157
  140. package/src/cli/tui/tui-handlers.mjs +111 -111
  141. package/src/cli/tui/tui-input-controller.mjs +61 -61
  142. package/src/cli/tui/ui-theme.mjs +157 -157
  143. package/src/cli/ui.mjs +297 -297
  144. package/src/config/config-json.mjs +108 -84
  145. package/src/config/dotenv.mjs +20 -20
  146. package/src/config/features.mjs +75 -75
  147. package/src/config/loader.mjs +156 -143
  148. package/src/config/settings-command.mjs +97 -97
  149. package/src/context/engine.mjs +199 -198
  150. package/src/context/injections.mjs +26 -26
  151. package/src/context/profiles.mjs +39 -39
  152. package/src/context/project-context.mjs +20 -20
  153. package/src/context/session-status.mjs +25 -17
  154. package/src/context/shell-layers.mjs +23 -23
  155. package/src/context/system-core/base.md +50 -50
  156. package/src/context/system-core/prompts/deepseek-v4-pro.md +3 -3
  157. package/src/context/system-core/prompts/default.md +3 -3
  158. package/src/context/system-core.mjs +35 -35
  159. package/src/debug/logger.mjs +141 -141
  160. package/src/debug/model-context-dumper.mjs +52 -52
  161. package/src/extensions/discovery.mjs +40 -40
  162. package/src/extensions/lifecycle-adapter.mjs +210 -210
  163. package/src/extensions/lifecycle-manifest.mjs +69 -69
  164. package/src/image-gen/index.mjs +7 -7
  165. package/src/image-gen/provider.mjs +231 -231
  166. package/src/image-gen/tool.mjs +84 -84
  167. package/src/lsp/client.mjs +257 -257
  168. package/src/lsp/diagnostic-store.mjs +42 -42
  169. package/src/lsp/diagnostics-format.mjs +72 -72
  170. package/src/lsp/managed-node-server.mjs +99 -99
  171. package/src/lsp/path-match.mjs +10 -10
  172. package/src/lsp/server-definitions.mjs +188 -188
  173. package/src/lsp/servers.mjs +165 -165
  174. package/src/lsp/service.mjs +110 -110
  175. package/src/lsp/status-message.mjs +9 -9
  176. package/src/lsp/typescript-project-resolver.mjs +186 -186
  177. package/src/main.mjs +294 -299
  178. package/src/mcp/client.mjs +195 -195
  179. package/src/mcp/config.mjs +130 -130
  180. package/src/mcp/index.mjs +48 -48
  181. package/src/mcp/tools.mjs +98 -98
  182. package/src/memory/command.mjs +120 -0
  183. package/src/memory/markdown/markdown-delete.mjs +23 -23
  184. package/src/memory/markdown/markdown-format.mjs +128 -128
  185. package/src/memory/markdown/markdown-recall.mjs +28 -28
  186. package/src/memory/markdown/ripgrep.mjs +16 -16
  187. package/src/memory/markdown/sqlite-index.mjs +87 -87
  188. package/src/memory/markdown-store.mjs +272 -286
  189. package/src/memory/markdown-tools.mjs +174 -103
  190. package/src/memory/remote/client.mjs +68 -0
  191. package/src/memory/remote/config.mjs +52 -0
  192. package/src/memory/remote/server.mjs +99 -0
  193. package/src/memory/search.mjs +183 -0
  194. package/src/network/environment.mjs +131 -131
  195. package/src/notification/desktop-notifier.mjs +262 -262
  196. package/src/platform/open-file.mjs +28 -28
  197. package/src/platform/spawn-command.mjs +27 -27
  198. package/src/provider/accept-command.mjs +89 -89
  199. package/src/provider/command.mjs +21 -21
  200. package/src/provider/config-command.mjs +129 -129
  201. package/src/provider/custom-provider.mjs +113 -113
  202. package/src/provider/hosted-tools.mjs +111 -111
  203. package/src/provider/presets.mjs +72 -72
  204. package/src/provider/share-command.mjs +79 -79
  205. package/src/provider/share-payload.mjs +52 -52
  206. package/src/session/attachment-display.mjs +16 -16
  207. package/src/session/attachment-references.mjs +65 -65
  208. package/src/session/attachments.mjs +140 -140
  209. package/src/session/persist.mjs +1 -1
  210. package/src/session/pi-manager.mjs +34 -34
  211. package/src/session/session-utils.mjs +16 -16
  212. package/src/session/sidecar-sync.mjs +19 -19
  213. package/src/session/sidecar.mjs +69 -69
  214. package/src/session/transcript.mjs +83 -83
  215. package/src/session/tree.mjs +42 -42
  216. package/src/shell/cli-runtime.mjs +11 -11
  217. package/src/shell/hints.mjs +12 -12
  218. package/src/shell/node-pty-adapter.mjs +81 -81
  219. package/src/shell/runtime-state.mjs +126 -126
  220. package/src/shell/runtime.mjs +252 -252
  221. package/src/shell/screen-buffer.mjs +136 -136
  222. package/src/shell/tool-read.mjs +74 -74
  223. package/src/shell/tools.mjs +299 -299
  224. package/src/supergrok/actions/image-generate.mjs +60 -60
  225. package/src/supergrok/actions/search.mjs +78 -78
  226. package/src/supergrok/auth.mjs +36 -36
  227. package/src/supergrok/constants.mjs +18 -18
  228. package/src/supergrok/oauth-provider.mjs +278 -278
  229. package/src/supergrok/provider.mjs +35 -35
  230. package/src/supergrok/response.mjs +76 -76
  231. package/src/supergrok/tool.mjs +61 -61
  232. package/src/text/ansi.mjs +3 -3
  233. package/src/web/config-command.mjs +43 -43
  234. package/src/web/fetch.mjs +78 -78
  235. package/src/web/presets.mjs +16 -16
  236. package/src/web/search.mjs +83 -83
  237. package/src/web/tools.mjs +107 -107
@@ -1,262 +1,277 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname } from "node:path";
3
- import { defineTool } from "@earendil-works/pi-coding-agent";
4
- import { Type } from "typebox";
5
- import { toolText } from "./tool-result.mjs";
6
- import { applyReplaceTextPatch, applyReplaceRangePatch } from "./editing/diff-apply.mjs";
7
- import { formatAppliedDiff, formatDiff } from "./editing/diff-format.mjs";
8
- import { waitForLspReport } from "./editing/lsp-report.mjs";
9
-
10
- export { formatDiff } from "./editing/diff-format.mjs";
11
-
12
- const PATCH_MODE = "patch";
13
- const WRITE_MODE = "write";
14
- const OVERWRITE_MODE = "overwrite";
15
-
16
- const replaceTextEditSchema = Type.Object({
17
- type: Type.Literal("replace_text"),
18
- oldText: Type.String({ description: "Exact text to replace. Must match exactly once in the original file." }),
19
- newText: Type.String({ description: "Replacement text" }),
20
- });
21
-
22
- const replaceRangeEditSchema = Type.Object({
23
- type: Type.Literal("replace_range"),
24
- startLine: Type.Number({ description: "1-based inclusive start line" }),
25
- endLine: Type.Number({ description: "1-based inclusive end line. This line is deleted too; keep it out of the range or include it in newText if it should remain." }),
26
- newText: Type.String({ description: "Replacement text. Omit a trailing newline unless intentionally adding a blank line." }),
27
- });
28
-
29
- export function createEditFileTool({ engine, ui, lspService = null }) {
30
- return defineTool({
31
- name: "edit_file",
32
- label: "Edit File",
33
- description:
34
- "Single file write tool. Use mode=patch with edits[] for targeted edits. " +
35
- "Use mode=write with content for new files. Use mode=overwrite with content for full-file replacement.",
36
- parameters: Type.Object({
37
- path: Type.String({ description: "Absolute or relative path" }),
38
- mode: Type.Optional(Type.Union([
39
- Type.Literal(PATCH_MODE),
40
- Type.Literal(WRITE_MODE),
41
- Type.Literal(OVERWRITE_MODE),
42
- ], { description: "patch (default), write, or overwrite" })),
43
- edits: Type.Optional(Type.Array(Type.Union([replaceTextEditSchema, replaceRangeEditSchema]), {
44
- description: "Patch edits. replace_text uses exact text; replace_range uses 1-based inclusive line numbers and deletes the endLine content too.",
45
- })),
46
- content: Type.Optional(Type.String({ description: "Full file content for mode=write or mode=overwrite" })),
47
- }),
48
- execute: async (_toolCallId, params) => executeEditFile({ params, engine, ui, lspService }),
49
- });
50
- }
51
-
52
- export async function executeEditFile({ params, engine, ui, lspService = null }) {
53
- const absPath = engine.resolvePath(params.path);
54
- const mode = params.mode ?? PATCH_MODE;
55
-
56
- if (mode === WRITE_MODE || mode === OVERWRITE_MODE) {
57
- return await writeFullFile({ absPath, path: params.path, content: params.content, mode, engine, ui, lspService });
58
- }
59
- if (mode !== PATCH_MODE) return toolText(`Error: unsupported edit_file mode: ${mode}`, { error: true });
60
- return await patchFile({ absPath, path: params.path, edits: params.edits, engine, ui, lspService });
61
- }
62
-
63
- async function writeFullFile({ absPath, path, content, mode, engine, ui, lspService }) {
64
- if (typeof content !== "string") {
65
- return toolText(`Error: content is required for mode=${mode}`, { error: true });
66
- }
67
- if (mode === WRITE_MODE && existsSync(absPath)) {
68
- return toolText(`Error: ${absPath} already exists. Use mode=overwrite to replace it.`, { error: true });
69
- }
70
- const oldText = mode === OVERWRITE_MODE && existsSync(absPath) ? readFileSync(absPath, "utf8") : "";
71
- const diffLines = formatDiff(oldText, content, { startLine: 1 });
72
- try {
73
- mkdirSync(dirname(absPath), { recursive: true });
74
- writeFileSync(absPath, content, "utf8");
75
- const lspTouchedAt = Date.now();
76
- const lspResult = await lspService?.touchFile?.(absPath);
77
- ui.editDiff(absPath, diffLines);
78
-
79
- return await toolTextWithDiagnostics(`${mode === WRITE_MODE ? "Wrote" : "Overwrote"} ${path}\n\n${formatAppliedDiff([{ oldText, newText: content, startLine: 1 }])}`, { path: absPath }, { lspService, path: absPath, lspResult, since: lspTouchedAt });
80
- } catch (err) {
81
- return toolText(`Error writing ${absPath}: ${err.message}`, { error: true });
82
- }
83
- }
84
-
85
- async function patchFile({ absPath, path, edits, engine, ui, lspService }) {
86
- if (!existsSync(absPath)) {
87
- return toolText(`Error: ${absPath} does not exist. Use mode=write to create it.`, { error: true });
88
- }
89
- if (!Array.isArray(edits) || edits.length === 0) {
90
- return toolText("Error: mode=patch requires at least one edit", { error: true });
91
- }
92
- if (edits.length > 50) {
93
- return toolText("Error: maximum 50 edits per call", { error: true });
94
- }
95
-
96
- const content = readFileSync(absPath, "utf8");
97
- const prepared = preparePatchEdits(content, edits, absPath);
98
- if (prepared.error) return toolText(prepared.error, { error: true });
99
-
100
- const newContent = applyPreparedEdits(content, prepared.edits);
101
- try {
102
- mkdirSync(dirname(absPath), { recursive: true });
103
- writeFileSync(absPath, newContent, "utf8");
104
- const lspTouchedAt = Date.now();
105
- const lspResult = await lspService?.touchFile?.(absPath);
106
- ui.editDiff(absPath, prepared.edits.flatMap((edit) => formatDiff(edit.oldText, edit.newText, { startLine: edit.startLine })));
107
- return await toolTextWithDiagnostics(`Edited ${absPath}\n\n${formatAppliedDiff(prepared.edits)}`, { path: absPath, edits: prepared.edits.length }, { lspService, path: absPath, lspResult, since: lspTouchedAt });
108
- } catch (err) {
109
- return toolText(`Error writing ${absPath}: ${err.message}`, { error: true });
110
- }
111
- }
112
-
113
- async function toolTextWithDiagnostics(text, details, { lspService, path, lspResult, since = Date.now(), timeoutMs = 3000, intervalMs = 150 } = {}) {
114
- const lspReport = await waitForLspReport({ lspService, path, lspResult, since, timeoutMs, intervalMs });
115
- return toolText(lspReport ? `${text}\n\n${lspReport}` : text, details);
116
- }
117
-
118
- export function preparePatchEdits(content, edits, path = "file") {
119
- const prepared = [];
120
- for (const edit of edits) {
121
- const next = prepareOneEdit(content, edit, path);
122
- if (next.error) return next;
123
- prepared.push(next.edit);
124
- }
125
- prepared.sort((a, b) => a.start - b.start || a.end - b.end);
126
- for (let i = 1; i < prepared.length; i++) {
127
- if (prepared[i].start < prepared[i - 1].end) {
128
- return { error: `Error: edits overlap in ${path}` };
129
- }
130
- }
131
- return { edits: prepared };
132
- }
133
-
134
- function prepareOneEdit(content, edit, path) {
135
- if (edit?.type === "replace_text") return prepareTextEdit(content, edit, path);
136
- if (edit?.type === "replace_range") return prepareRangeEdit(content, edit, path);
137
- return { error: `Error: unsupported edit type: ${edit?.type}` };
138
- }
139
-
140
- function prepareTextEdit(content, edit, path) {
141
- if (!edit.oldText) return { error: "Error: replace_text oldText must be non-empty" };
142
- const first = content.indexOf(edit.oldText);
143
- if (first < 0) return { error: formatMissingOldTextError(content, edit.oldText, path) };
144
- const second = content.indexOf(edit.oldText, first + edit.oldText.length);
145
- if (second >= 0) return { error: `Error: oldText is not unique in ${path}. Use replace_range or include more context.` };
146
- return {
147
- edit: {
148
- start: first,
149
- end: first + edit.oldText.length,
150
- oldText: edit.oldText,
151
- newText: edit.newText,
152
- startLine: lineNumberForOffset(content, first),
153
- },
154
- };
155
- }
156
-
157
- function formatMissingOldTextError(content, oldText, path) {
158
- const candidate = findClosestTextCandidate(content, oldText);
159
- const lines = [`Error: oldText not found in ${path}. File may have changed.`];
160
- if (!candidate) return lines.join("\n");
161
- lines.push(
162
- "",
163
- "Closest candidate:",
164
- `lines ${candidate.startLine}-${candidate.endLine}, similarity ${candidate.score.toFixed(2)}`,
165
- "---",
166
- candidate.snippet,
167
- "---",
168
- `Use replace_range with startLine=${candidate.startLine} endLine=${candidate.endLine} if this is intended.`,
169
- );
170
- return lines.join("\n");
171
- }
172
-
173
- function findClosestTextCandidate(content, oldText) {
174
- const lines = content.split("\n");
175
- const oldLineCount = Math.max(1, oldText.split("\n").length);
176
- const windowSizes = [...new Set([oldLineCount - 1, oldLineCount, oldLineCount + 1])]
177
- .filter((size) => size > 0 && size <= lines.length);
178
- let best = null;
179
- for (const size of windowSizes) {
180
- for (let start = 0; start <= lines.length - size; start++) {
181
- const snippet = lines.slice(start, start + size).join("\n");
182
- const score = textSimilarity(oldText, snippet);
183
- if (!best || score > best.score) {
184
- best = { startLine: start + 1, endLine: start + size, score, snippet: truncateSnippet(snippet) };
185
- }
186
- }
187
- }
188
- return best?.score >= 0.2 ? best : null;
189
- }
190
-
191
- function textSimilarity(a, b) {
192
- const aTokens = tokenizeForSimilarity(a);
193
- const bTokens = tokenizeForSimilarity(b);
194
- if (aTokens.length === 0 || bTokens.length === 0) return 0;
195
- const counts = new Map();
196
- for (const token of aTokens) counts.set(token, (counts.get(token) ?? 0) + 1);
197
- let common = 0;
198
- for (const token of bTokens) {
199
- const count = counts.get(token) ?? 0;
200
- if (count <= 0) continue;
201
- common++;
202
- counts.set(token, count - 1);
203
- }
204
- return (2 * common) / (aTokens.length + bTokens.length);
205
- }
206
-
207
- function tokenizeForSimilarity(text) {
208
- const tokens = String(text).toLowerCase().match(/[a-z0-9_]+/g);
209
- if (tokens?.length) return tokens;
210
- return String(text).replace(/\s+/g, "").split("").filter(Boolean);
211
- }
212
-
213
- function truncateSnippet(text) {
214
- const limit = 1200;
215
- if (text.length <= limit) return text;
216
- return `${text.slice(0, limit)}\n...(snippet truncated)`;
217
- }
218
-
219
- function prepareRangeEdit(content, edit, path) {
220
- const lines = content.split("\n");
221
- const startLine = Math.trunc(edit.startLine);
222
- const endLine = Math.trunc(edit.endLine);
223
- if (startLine < 1 || endLine > lines.length || startLine > endLine) {
224
- return { error: `Error: line range ${startLine}-${endLine} out of bounds (file has ${lines.length} lines)` };
225
- }
226
- const oldText = lines.slice(startLine - 1, endLine).join("\n");
227
- const newText = normalizeRangeNewText(edit.newText, endLine, lines.length);
228
- return {
229
- edit: {
230
- start: offsetForLine(lines, startLine),
231
- end: offsetForLine(lines, startLine) + oldText.length,
232
- oldText,
233
- newText,
234
- startLine,
235
- },
236
- };
237
- }
238
-
239
- function normalizeRangeNewText(newText, endLine, lineCount) {
240
- if (endLine < lineCount && /\r?\n$/.test(newText)) return newText.replace(/\r?\n$/, "");
241
- return newText;
242
- }
243
-
244
- function lineNumberForOffset(content, offset) {
245
- let line = 1;
246
- for (let i = 0; i < offset; i++) if (content[i] === "\n") line++;
247
- return line;
248
- }
249
-
250
- function offsetForLine(lines, lineNumber) {
251
- let offset = 0;
252
- for (let i = 0; i < lineNumber - 1; i++) offset += lines[i].length + 1;
253
- return offset;
254
- }
255
-
256
- function applyPreparedEdits(content, edits) {
257
- let next = content;
258
- for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
259
- next = next.slice(0, edit.start) + edit.newText + next.slice(edit.end);
260
- }
261
- return next;
262
- }
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { defineTool } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { toolText } from "./tool-result.mjs";
6
+ import { applyReplaceTextPatch, applyReplaceRangePatch } from "./editing/diff-apply.mjs";
7
+ import { buildCohesionWarning } from "./editing/cohesion-warning.mjs";
8
+ import { formatAppliedDiff, formatDiff } from "./editing/diff-format.mjs";
9
+ import { waitForLspReport } from "./editing/lsp-report.mjs";
10
+
11
+ export { formatDiff } from "./editing/diff-format.mjs";
12
+
13
+ const PATCH_MODE = "patch";
14
+ const WRITE_MODE = "write";
15
+ const OVERWRITE_MODE = "overwrite";
16
+
17
+ const replaceTextEditSchema = Type.Object({
18
+ type: Type.Literal("replace_text"),
19
+ oldText: Type.String({ description: "Exact text to replace. Must match exactly once in the original file." }),
20
+ newText: Type.String({ description: "Replacement text" }),
21
+ });
22
+
23
+ const replaceRangeEditSchema = Type.Object({
24
+ type: Type.Literal("replace_range"),
25
+ startLine: Type.Number({ description: "1-based inclusive start line" }),
26
+ endLine: Type.Number({ description: "1-based inclusive end line. This line is deleted too; keep it out of the range or include it in newText if it should remain." }),
27
+ newText: Type.String({ description: "Replacement text. Omit a trailing newline unless intentionally adding a blank line." }),
28
+ });
29
+
30
+ export function createEditFileTool({ engine, ui, lspService = null }) {
31
+ return defineTool({
32
+ name: "edit_file",
33
+ label: "Edit File",
34
+ description:
35
+ "Single file write tool. Use mode=patch with edits[] for targeted edits. " +
36
+ "Use mode=write with content for new files. Use mode=overwrite with content for full-file replacement.",
37
+ parameters: Type.Object({
38
+ path: Type.String({ description: "Absolute or relative path" }),
39
+ mode: Type.Optional(Type.Union([
40
+ Type.Literal(PATCH_MODE),
41
+ Type.Literal(WRITE_MODE),
42
+ Type.Literal(OVERWRITE_MODE),
43
+ ], { description: "patch (default), write, or overwrite" })),
44
+ edits: Type.Optional(Type.Array(Type.Union([replaceTextEditSchema, replaceRangeEditSchema]), {
45
+ description: "Patch edits. replace_text uses exact text; replace_range uses 1-based inclusive line numbers and deletes the endLine content too.",
46
+ })),
47
+ content: Type.Optional(Type.String({ description: "Full file content for mode=write or mode=overwrite" })),
48
+ }),
49
+ execute: async (_toolCallId, params) => executeEditFile({ params, engine, ui, lspService }),
50
+ });
51
+ }
52
+
53
+ export async function executeEditFile({ params, engine, ui, lspService = null }) {
54
+ const absPath = engine.resolvePath(params.path);
55
+ const mode = params.mode ?? PATCH_MODE;
56
+
57
+ if (mode === WRITE_MODE || mode === OVERWRITE_MODE) {
58
+ return await writeFullFile({ absPath, path: params.path, content: params.content, mode, engine, ui, lspService });
59
+ }
60
+ if (mode !== PATCH_MODE) return toolText(`Error: unsupported edit_file mode: ${mode}`, { error: true });
61
+ return await patchFile({ absPath, path: params.path, edits: params.edits, engine, ui, lspService });
62
+ }
63
+
64
+ async function writeFullFile({ absPath, path, content, mode, engine, ui, lspService }) {
65
+ if (typeof content !== "string") {
66
+ return toolText(`Error: content is required for mode=${mode}`, { error: true });
67
+ }
68
+ if (mode === WRITE_MODE && existsSync(absPath)) {
69
+ return toolText(`Error: ${absPath} already exists. Use mode=overwrite to replace it.`, { error: true });
70
+ }
71
+ const oldText = mode === OVERWRITE_MODE && existsSync(absPath) ? readFileSync(absPath, "utf8") : "";
72
+ const cohesionWarning = buildCohesionWarning({ path: absPath, oldText, newText: content });
73
+ const diffLines = formatDiff(oldText, content, { startLine: 1 });
74
+ try {
75
+ mkdirSync(dirname(absPath), { recursive: true });
76
+ writeFileSync(absPath, content, "utf8");
77
+ const lspTouchedAt = Date.now();
78
+ const lspResult = await lspService?.touchFile?.(absPath);
79
+ ui.editDiff(absPath, diffLines);
80
+
81
+ const baseText = `${mode === WRITE_MODE ? "Wrote" : "Overwrote"} ${path}\n\n${formatAppliedDiff([{ oldText, newText: content, startLine: 1 }])}`;
82
+ return await toolTextWithDiagnostics(appendSections(baseText, [cohesionWarning]), withWarnings({ path: absPath }, cohesionWarning), { lspService, path: absPath, lspResult, since: lspTouchedAt });
83
+ } catch (err) {
84
+ return toolText(`Error writing ${absPath}: ${err.message}`, { error: true });
85
+ }
86
+ }
87
+
88
+ async function patchFile({ absPath, path, edits, engine, ui, lspService }) {
89
+ if (!existsSync(absPath)) {
90
+ return toolText(`Error: ${absPath} does not exist. Use mode=write to create it.`, { error: true });
91
+ }
92
+ if (!Array.isArray(edits) || edits.length === 0) {
93
+ return toolText("Error: mode=patch requires at least one edit", { error: true });
94
+ }
95
+ if (edits.length > 50) {
96
+ return toolText("Error: maximum 50 edits per call", { error: true });
97
+ }
98
+
99
+ const content = readFileSync(absPath, "utf8");
100
+ const prepared = preparePatchEdits(content, edits, absPath);
101
+ if (prepared.error) return toolText(prepared.error, { error: true });
102
+
103
+ const newContent = applyPreparedEdits(content, prepared.edits);
104
+ const cohesionWarning = buildCohesionWarning({ path: absPath, oldText: content, newText: newContent });
105
+ try {
106
+ mkdirSync(dirname(absPath), { recursive: true });
107
+ writeFileSync(absPath, newContent, "utf8");
108
+ const lspTouchedAt = Date.now();
109
+ const lspResult = await lspService?.touchFile?.(absPath);
110
+ ui.editDiff(absPath, prepared.edits.flatMap((edit) => formatDiff(edit.oldText, edit.newText, { startLine: edit.startLine })));
111
+ const baseText = `Edited ${absPath}\n\n${formatAppliedDiff(prepared.edits)}`;
112
+ const details = withWarnings({ path: absPath, edits: prepared.edits.length }, cohesionWarning);
113
+ return await toolTextWithDiagnostics(appendSections(baseText, [cohesionWarning]), details, { lspService, path: absPath, lspResult, since: lspTouchedAt });
114
+ } catch (err) {
115
+ return toolText(`Error writing ${absPath}: ${err.message}`, { error: true });
116
+ }
117
+ }
118
+
119
+ async function toolTextWithDiagnostics(text, details, { lspService, path, lspResult, since = Date.now(), timeoutMs = 3000, intervalMs = 150 } = {}) {
120
+ const lspReport = await waitForLspReport({ lspService, path, lspResult, since, timeoutMs, intervalMs });
121
+ return toolText(lspReport ? `${text}\n\n${lspReport}` : text, details);
122
+ }
123
+
124
+ function appendSections(text, sections) {
125
+ return [text, ...sections.filter(Boolean)].join("\n\n");
126
+ }
127
+
128
+ function withWarnings(details, cohesionWarning) {
129
+ if (!cohesionWarning) return details;
130
+ return { ...details, warnings: ["cohesion"] };
131
+ }
132
+
133
+ export function preparePatchEdits(content, edits, path = "file") {
134
+ const prepared = [];
135
+ for (const edit of edits) {
136
+ const next = prepareOneEdit(content, edit, path);
137
+ if (next.error) return next;
138
+ prepared.push(next.edit);
139
+ }
140
+ prepared.sort((a, b) => a.start - b.start || a.end - b.end);
141
+ for (let i = 1; i < prepared.length; i++) {
142
+ if (prepared[i].start < prepared[i - 1].end) {
143
+ return { error: `Error: edits overlap in ${path}` };
144
+ }
145
+ }
146
+ return { edits: prepared };
147
+ }
148
+
149
+ function prepareOneEdit(content, edit, path) {
150
+ if (edit?.type === "replace_text") return prepareTextEdit(content, edit, path);
151
+ if (edit?.type === "replace_range") return prepareRangeEdit(content, edit, path);
152
+ return { error: `Error: unsupported edit type: ${edit?.type}` };
153
+ }
154
+
155
+ function prepareTextEdit(content, edit, path) {
156
+ if (!edit.oldText) return { error: "Error: replace_text oldText must be non-empty" };
157
+ const first = content.indexOf(edit.oldText);
158
+ if (first < 0) return { error: formatMissingOldTextError(content, edit.oldText, path) };
159
+ const second = content.indexOf(edit.oldText, first + edit.oldText.length);
160
+ if (second >= 0) return { error: `Error: oldText is not unique in ${path}. Use replace_range or include more context.` };
161
+ return {
162
+ edit: {
163
+ start: first,
164
+ end: first + edit.oldText.length,
165
+ oldText: edit.oldText,
166
+ newText: edit.newText,
167
+ startLine: lineNumberForOffset(content, first),
168
+ },
169
+ };
170
+ }
171
+
172
+ function formatMissingOldTextError(content, oldText, path) {
173
+ const candidate = findClosestTextCandidate(content, oldText);
174
+ const lines = [`Error: oldText not found in ${path}. File may have changed.`];
175
+ if (!candidate) return lines.join("\n");
176
+ lines.push(
177
+ "",
178
+ "Closest candidate:",
179
+ `lines ${candidate.startLine}-${candidate.endLine}, similarity ${candidate.score.toFixed(2)}`,
180
+ "---",
181
+ candidate.snippet,
182
+ "---",
183
+ `Use replace_range with startLine=${candidate.startLine} endLine=${candidate.endLine} if this is intended.`,
184
+ );
185
+ return lines.join("\n");
186
+ }
187
+
188
+ function findClosestTextCandidate(content, oldText) {
189
+ const lines = content.split("\n");
190
+ const oldLineCount = Math.max(1, oldText.split("\n").length);
191
+ const windowSizes = [...new Set([oldLineCount - 1, oldLineCount, oldLineCount + 1])]
192
+ .filter((size) => size > 0 && size <= lines.length);
193
+ let best = null;
194
+ for (const size of windowSizes) {
195
+ for (let start = 0; start <= lines.length - size; start++) {
196
+ const snippet = lines.slice(start, start + size).join("\n");
197
+ const score = textSimilarity(oldText, snippet);
198
+ if (!best || score > best.score) {
199
+ best = { startLine: start + 1, endLine: start + size, score, snippet: truncateSnippet(snippet) };
200
+ }
201
+ }
202
+ }
203
+ return best?.score >= 0.2 ? best : null;
204
+ }
205
+
206
+ function textSimilarity(a, b) {
207
+ const aTokens = tokenizeForSimilarity(a);
208
+ const bTokens = tokenizeForSimilarity(b);
209
+ if (aTokens.length === 0 || bTokens.length === 0) return 0;
210
+ const counts = new Map();
211
+ for (const token of aTokens) counts.set(token, (counts.get(token) ?? 0) + 1);
212
+ let common = 0;
213
+ for (const token of bTokens) {
214
+ const count = counts.get(token) ?? 0;
215
+ if (count <= 0) continue;
216
+ common++;
217
+ counts.set(token, count - 1);
218
+ }
219
+ return (2 * common) / (aTokens.length + bTokens.length);
220
+ }
221
+
222
+ function tokenizeForSimilarity(text) {
223
+ const tokens = String(text).toLowerCase().match(/[a-z0-9_]+/g);
224
+ if (tokens?.length) return tokens;
225
+ return String(text).replace(/\s+/g, "").split("").filter(Boolean);
226
+ }
227
+
228
+ function truncateSnippet(text) {
229
+ const limit = 1200;
230
+ if (text.length <= limit) return text;
231
+ return `${text.slice(0, limit)}\n...(snippet truncated)`;
232
+ }
233
+
234
+ function prepareRangeEdit(content, edit, path) {
235
+ const lines = content.split("\n");
236
+ const startLine = Math.trunc(edit.startLine);
237
+ const endLine = Math.trunc(edit.endLine);
238
+ if (startLine < 1 || endLine > lines.length || startLine > endLine) {
239
+ return { error: `Error: line range ${startLine}-${endLine} out of bounds (file has ${lines.length} lines)` };
240
+ }
241
+ const oldText = lines.slice(startLine - 1, endLine).join("\n");
242
+ const newText = normalizeRangeNewText(edit.newText, endLine, lines.length);
243
+ return {
244
+ edit: {
245
+ start: offsetForLine(lines, startLine),
246
+ end: offsetForLine(lines, startLine) + oldText.length,
247
+ oldText,
248
+ newText,
249
+ startLine,
250
+ },
251
+ };
252
+ }
253
+
254
+ function normalizeRangeNewText(newText, endLine, lineCount) {
255
+ if (endLine < lineCount && /\r?\n$/.test(newText)) return newText.replace(/\r?\n$/, "");
256
+ return newText;
257
+ }
258
+
259
+ function lineNumberForOffset(content, offset) {
260
+ let line = 1;
261
+ for (let i = 0; i < offset; i++) if (content[i] === "\n") line++;
262
+ return line;
263
+ }
264
+
265
+ function offsetForLine(lines, lineNumber) {
266
+ let offset = 0;
267
+ for (let i = 0; i < lineNumber - 1; i++) offset += lines[i].length + 1;
268
+ return offset;
269
+ }
270
+
271
+ function applyPreparedEdits(content, edits) {
272
+ let next = content;
273
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
274
+ next = next.slice(0, edit.start) + edit.newText + next.slice(edit.end);
275
+ }
276
+ return next;
277
+ }