@caupulican/pi-adaptative 0.84.1 → 0.85.3

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 (214) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -8
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -8
  6. package/dist/bundled-resources/runtimes/pi-shell-engine/arithmetic.py +364 -0
  7. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +2 -1
  8. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +16 -0
  9. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +137 -14
  10. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +23 -2
  11. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +134 -6
  12. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +25 -2
  13. package/dist/bundled-resources/skills/deduplicate-by-evidence/SKILL.md +7 -5
  14. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +63 -0
  15. package/dist/core/agent-session.d.ts.map +1 -1
  16. package/dist/core/agent-session.js +8 -0
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  19. package/dist/core/autonomy/lane-tool-surface.js +4 -2
  20. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  21. package/dist/core/background-lane-controller.d.ts +3 -0
  22. package/dist/core/background-lane-controller.d.ts.map +1 -1
  23. package/dist/core/background-lane-controller.js +6 -0
  24. package/dist/core/background-lane-controller.js.map +1 -1
  25. package/dist/core/compaction-controller.d.ts +2 -0
  26. package/dist/core/compaction-controller.d.ts.map +1 -1
  27. package/dist/core/compaction-controller.js +35 -13
  28. package/dist/core/compaction-controller.js.map +1 -1
  29. package/dist/core/default-tool-surface.d.ts.map +1 -1
  30. package/dist/core/default-tool-surface.js +1 -0
  31. package/dist/core/default-tool-surface.js.map +1 -1
  32. package/dist/core/delegation/worker-delegation-controller.d.ts +7 -0
  33. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  34. package/dist/core/delegation/worker-delegation-controller.js +28 -0
  35. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  36. package/dist/core/delegation/worker-profile-resolver.d.ts +2 -0
  37. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  38. package/dist/core/delegation/worker-profile-resolver.js +46 -11
  39. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  40. package/dist/core/doctor.d.ts +1 -1
  41. package/dist/core/doctor.d.ts.map +1 -1
  42. package/dist/core/doctor.js +5 -4
  43. package/dist/core/doctor.js.map +1 -1
  44. package/dist/core/failure-corpus.d.ts +26 -1
  45. package/dist/core/failure-corpus.d.ts.map +1 -1
  46. package/dist/core/failure-corpus.js +17 -0
  47. package/dist/core/failure-corpus.js.map +1 -1
  48. package/dist/core/model-capability.d.ts.map +1 -1
  49. package/dist/core/model-capability.js +1 -0
  50. package/dist/core/model-capability.js.map +1 -1
  51. package/dist/core/model-tool-protocol.d.ts +3 -2
  52. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  53. package/dist/core/model-tool-protocol.js +5 -1
  54. package/dist/core/model-tool-protocol.js.map +1 -1
  55. package/dist/core/models/runtime-process.d.ts +7 -1
  56. package/dist/core/models/runtime-process.d.ts.map +1 -1
  57. package/dist/core/models/runtime-process.js +4 -2
  58. package/dist/core/models/runtime-process.js.map +1 -1
  59. package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
  60. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  61. package/dist/core/orchestration/lane-tool-manifests.js +6 -1
  62. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  63. package/dist/core/orchestration/session-task-profile-store.d.ts +31 -0
  64. package/dist/core/orchestration/session-task-profile-store.d.ts.map +1 -0
  65. package/dist/core/orchestration/session-task-profile-store.js +138 -0
  66. package/dist/core/orchestration/session-task-profile-store.js.map +1 -0
  67. package/dist/core/orchestration/task-profile-writer.d.ts +58 -0
  68. package/dist/core/orchestration/task-profile-writer.d.ts.map +1 -0
  69. package/dist/core/orchestration/task-profile-writer.js +165 -0
  70. package/dist/core/orchestration/task-profile-writer.js.map +1 -0
  71. package/dist/core/process-matrix/runtime.js +43 -11
  72. package/dist/core/process-matrix/runtime.js.map +1 -1
  73. package/dist/core/resource-loader.d.ts +2 -0
  74. package/dist/core/resource-loader.d.ts.map +1 -1
  75. package/dist/core/resource-loader.js +18 -6
  76. package/dist/core/resource-loader.js.map +1 -1
  77. package/dist/core/runtime-builder.d.ts +3 -1
  78. package/dist/core/runtime-builder.d.ts.map +1 -1
  79. package/dist/core/runtime-builder.js +14 -0
  80. package/dist/core/runtime-builder.js.map +1 -1
  81. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  82. package/dist/core/security/untrusted-boundary.js +4 -6
  83. package/dist/core/security/untrusted-boundary.js.map +1 -1
  84. package/dist/core/session-role.d.ts.map +1 -1
  85. package/dist/core/session-role.js +1 -0
  86. package/dist/core/session-role.js.map +1 -1
  87. package/dist/core/system-prompt.d.ts.map +1 -1
  88. package/dist/core/system-prompt.js +21 -23
  89. package/dist/core/system-prompt.js.map +1 -1
  90. package/dist/core/tool-capability-policy.js +1 -1
  91. package/dist/core/tool-capability-policy.js.map +1 -1
  92. package/dist/core/tool-recovery-log-records.d.ts +33 -1
  93. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  94. package/dist/core/tool-recovery-log-records.js +59 -12
  95. package/dist/core/tool-recovery-log-records.js.map +1 -1
  96. package/dist/core/tool-recovery-logger.d.ts +12 -1
  97. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  98. package/dist/core/tool-recovery-logger.js +24 -1
  99. package/dist/core/tool-recovery-logger.js.map +1 -1
  100. package/dist/core/tool-repair-health.d.ts.map +1 -1
  101. package/dist/core/tool-repair-health.js +6 -0
  102. package/dist/core/tool-repair-health.js.map +1 -1
  103. package/dist/core/tools/bash.d.ts +3 -8
  104. package/dist/core/tools/bash.d.ts.map +1 -1
  105. package/dist/core/tools/bash.js +4 -28
  106. package/dist/core/tools/bash.js.map +1 -1
  107. package/dist/core/tools/delegate.js +4 -4
  108. package/dist/core/tools/delegate.js.map +1 -1
  109. package/dist/core/tools/edit-diff.d.ts +32 -5
  110. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  111. package/dist/core/tools/edit-diff.js +137 -69
  112. package/dist/core/tools/edit-diff.js.map +1 -1
  113. package/dist/core/tools/edit.d.ts +22 -7
  114. package/dist/core/tools/edit.d.ts.map +1 -1
  115. package/dist/core/tools/edit.js +128 -55
  116. package/dist/core/tools/edit.js.map +1 -1
  117. package/dist/core/tools/file-mutation-intent.d.ts +70 -0
  118. package/dist/core/tools/file-mutation-intent.d.ts.map +1 -0
  119. package/dist/core/tools/file-mutation-intent.js +325 -0
  120. package/dist/core/tools/file-mutation-intent.js.map +1 -0
  121. package/dist/core/tools/find.d.ts +2 -1
  122. package/dist/core/tools/find.d.ts.map +1 -1
  123. package/dist/core/tools/find.js +2 -6
  124. package/dist/core/tools/find.js.map +1 -1
  125. package/dist/core/tools/goal.d.ts.map +1 -1
  126. package/dist/core/tools/goal.js +41 -18
  127. package/dist/core/tools/goal.js.map +1 -1
  128. package/dist/core/tools/grep.d.ts +2 -1
  129. package/dist/core/tools/grep.d.ts.map +1 -1
  130. package/dist/core/tools/grep.js +2 -6
  131. package/dist/core/tools/grep.js.map +1 -1
  132. package/dist/core/tools/index.d.ts +3 -1
  133. package/dist/core/tools/index.d.ts.map +1 -1
  134. package/dist/core/tools/index.js +31 -8
  135. package/dist/core/tools/index.js.map +1 -1
  136. package/dist/core/tools/managed-search-tool.d.ts +8 -0
  137. package/dist/core/tools/managed-search-tool.d.ts.map +1 -0
  138. package/dist/core/tools/managed-search-tool.js +10 -0
  139. package/dist/core/tools/managed-search-tool.js.map +1 -0
  140. package/dist/core/tools/profile-writer.d.ts +33 -0
  141. package/dist/core/tools/profile-writer.d.ts.map +1 -0
  142. package/dist/core/tools/profile-writer.js +67 -0
  143. package/dist/core/tools/profile-writer.js.map +1 -0
  144. package/dist/core/tools/shell-command-parser.d.ts +4 -3
  145. package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
  146. package/dist/core/tools/shell-command-parser.js +32 -7
  147. package/dist/core/tools/shell-command-parser.js.map +1 -1
  148. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  149. package/dist/core/tools/shell-contract-router.js +23 -1
  150. package/dist/core/tools/shell-contract-router.js.map +1 -1
  151. package/dist/core/tools/task-steps.d.ts.map +1 -1
  152. package/dist/core/tools/task-steps.js +6 -11
  153. package/dist/core/tools/task-steps.js.map +1 -1
  154. package/dist/core/tools/tmux-dispatch.d.ts +2 -0
  155. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  156. package/dist/core/tools/tmux-dispatch.js +16 -2
  157. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  158. package/dist/core/tools/windows-shell-engine.js +1 -1
  159. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  160. package/dist/core/tools/write.d.ts +24 -7
  161. package/dist/core/tools/write.d.ts.map +1 -1
  162. package/dist/core/tools/write.js +182 -107
  163. package/dist/core/tools/write.js.map +1 -1
  164. package/dist/index.d.ts +1 -1
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +1 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/jscpd-cli.d.ts +3 -0
  169. package/dist/jscpd-cli.d.ts.map +1 -0
  170. package/dist/jscpd-cli.js +22 -0
  171. package/dist/jscpd-cli.js.map +1 -0
  172. package/dist/modes/interactive/components/profile-resource-editor.js +2 -2
  173. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  174. package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
  175. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  176. package/dist/modes/interactive/components/tool-execution.js +85 -3
  177. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  178. package/dist/modes/interactive/interactive-mode.js +1 -1
  179. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  180. package/dist/utils/bundled-jscpd.d.ts +20 -0
  181. package/dist/utils/bundled-jscpd.d.ts.map +1 -0
  182. package/dist/utils/bundled-jscpd.js +154 -0
  183. package/dist/utils/bundled-jscpd.js.map +1 -0
  184. package/dist/utils/paths.js +1 -1
  185. package/dist/utils/paths.js.map +1 -1
  186. package/dist/utils/shell.d.ts.map +1 -1
  187. package/dist/utils/shell.js +11 -0
  188. package/dist/utils/shell.js.map +1 -1
  189. package/dist/utils/tools-manager.d.ts +19 -2
  190. package/dist/utils/tools-manager.d.ts.map +1 -1
  191. package/dist/utils/tools-manager.js +92 -40
  192. package/dist/utils/tools-manager.js.map +1 -1
  193. package/docs/index.md +3 -0
  194. package/docs/managed-data-tools.md +15 -0
  195. package/docs/models.md +1 -1
  196. package/docs/quickstart.md +2 -2
  197. package/docs/settings.md +1 -1
  198. package/docs/tool-boundary-performance-roadmap-2026-08-02.md +166 -0
  199. package/docs/tool-repair.md +4 -4
  200. package/docs/windows.md +7 -5
  201. package/docs/worker-profiles.md +16 -0
  202. package/examples/extensions/built-in-tool-renderer.ts +12 -5
  203. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  204. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  205. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  206. package/examples/extensions/minimal-mode.ts +8 -7
  207. package/examples/extensions/prompt-customizer.ts +4 -2
  208. package/examples/extensions/sandbox/package-lock.json +2 -2
  209. package/examples/extensions/sandbox/package.json +1 -1
  210. package/examples/extensions/ssh.ts +113 -24
  211. package/examples/extensions/with-deps/package-lock.json +2 -2
  212. package/examples/extensions/with-deps/package.json +1 -1
  213. package/npm-shrinkwrap.json +112 -12
  214. package/package.json +7 -5
@@ -1,30 +1,40 @@
1
1
  import { Box, Container, Spacer, Text } from "@caupulican/pi-tui";
2
- import { constants } from "fs";
3
- import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";
2
+ import { readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises";
4
3
  import { Type } from "typebox";
5
4
  import { renderDiff } from "../../modes/interactive/components/diff.js";
6
- import { applyEditsToNormalizedContent, computeEditsDiff, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
5
+ import { applyEditMatchPlan, applyEditsToNormalizedContent, computeEditsPlannedDiff, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
7
6
  import { isValidUTF8 } from "./file-encoding-policy.js";
7
+ import { FileMutationIntentController } from "./file-mutation-intent.js";
8
8
  import { withFileMutationQueue } from "./file-mutation-queue.js";
9
9
  import { resolveToCwd } from "./path-utils.js";
10
10
  import { renderToolPath, str } from "./render-utils.js";
11
11
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
12
12
  const replaceEditSchema = Type.Object({
13
- oldText: Type.String({
14
- description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.",
15
- }),
16
- newText: Type.String({ description: "Replacement text for this targeted edit." }),
17
- }, { additionalProperties: false });
18
- const editSchema = Type.Object({
19
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
20
- edits: Type.Array(replaceEditSchema, {
21
- description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.",
22
- }),
13
+ oldText: Type.String({ minLength: 1 }),
14
+ newText: Type.String(),
15
+ range: Type.Optional(Type.Object({
16
+ startLine: Type.Integer({ minimum: 1 }),
17
+ endLine: Type.Integer({ minimum: 1 }),
18
+ }, { additionalProperties: false })),
23
19
  }, { additionalProperties: false });
20
+ const editPathSchema = Type.String({ minLength: 1 });
21
+ const editSchema = Type.Union([
22
+ Type.Object({
23
+ action: Type.Literal("prepare"),
24
+ path: editPathSchema,
25
+ }, { additionalProperties: false }),
26
+ Type.Object({
27
+ action: Type.Literal("commit"),
28
+ path: editPathSchema,
29
+ intentId: Type.String({ minLength: 1 }),
30
+ edits: Type.Array(replaceEditSchema, {
31
+ minItems: 1,
32
+ }),
33
+ }, { additionalProperties: false }),
34
+ ]);
24
35
  const defaultEditOperations = {
25
36
  readFile: (path) => fsReadFile(path),
26
37
  writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
27
- access: (path) => fsAccess(path, constants.R_OK | constants.W_OK),
28
38
  };
29
39
  function prepareEditArguments(input) {
30
40
  if (!input || typeof input !== "object") {
@@ -41,15 +51,17 @@ function prepareEditArguments(input) {
41
51
  return { ...rest, edits };
42
52
  }
43
53
  function validateEditInput(input) {
54
+ if (input.action === "prepare")
55
+ return input;
44
56
  if (!Array.isArray(input.edits) || input.edits.length === 0) {
45
57
  throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
46
58
  }
47
- return { path: input.path, edits: input.edits };
59
+ return { action: "commit", path: input.path, intentId: input.intentId, edits: input.edits };
48
60
  }
49
61
  function createEditCallRenderComponent() {
50
62
  return Object.assign(new Box(1, 1, (text) => text), {
51
63
  preview: undefined,
52
- previewArgsKey: undefined,
64
+ previewRequestId: 0,
53
65
  previewPending: false,
54
66
  settledError: false,
55
67
  });
@@ -71,23 +83,50 @@ function getRenderablePreviewInput(args) {
71
83
  if (!args) {
72
84
  return null;
73
85
  }
86
+ if (args.action !== "commit")
87
+ return null;
74
88
  const path = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : null;
75
89
  if (!path) {
76
90
  return null;
77
91
  }
92
+ if (typeof args.intentId !== "string" || args.intentId.length === 0)
93
+ return null;
78
94
  if (Array.isArray(args.edits) &&
79
95
  args.edits.length > 0 &&
80
96
  args.edits.every((edit) => typeof edit?.oldText === "string" && typeof edit?.newText === "string")) {
81
- return { path, edits: args.edits };
97
+ return { path, intentId: args.intentId, edits: args.edits };
82
98
  }
83
99
  if (typeof args.oldText === "string" && typeof args.newText === "string") {
84
- return { path, edits: [{ oldText: args.oldText, newText: args.newText }] };
100
+ return { path, intentId: args.intentId, edits: [{ oldText: args.oldText, newText: args.newText }] };
85
101
  }
86
102
  return null;
87
103
  }
104
+ function snapshotEdits(edits) {
105
+ return edits.map((edit) => ({
106
+ oldText: edit.oldText,
107
+ newText: edit.newText,
108
+ ...(edit.range ? { range: { startLine: edit.range.startLine, endLine: edit.range.endLine } } : {}),
109
+ }));
110
+ }
111
+ function editsMatch(left, right) {
112
+ if (left.length !== right.length)
113
+ return false;
114
+ for (let index = 0; index < left.length; index++) {
115
+ const leftEdit = left[index];
116
+ const rightEdit = right[index];
117
+ if (leftEdit.oldText !== rightEdit.oldText ||
118
+ leftEdit.newText !== rightEdit.newText ||
119
+ leftEdit.range?.startLine !== rightEdit.range?.startLine ||
120
+ leftEdit.range?.endLine !== rightEdit.range?.endLine) {
121
+ return false;
122
+ }
123
+ }
124
+ return true;
125
+ }
88
126
  function formatEditCall(args, theme, cwd) {
89
127
  const pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);
90
- return `${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`;
128
+ const action = args?.action === "prepare" ? "prepare" : args?.action === "commit" ? "commit" : undefined;
129
+ return `${theme.fg("toolTitle", theme.bold("edit"))}${action ? ` ${theme.fg("muted", action)}` : ""} ${pathDisplay}`;
91
130
  }
92
131
  function formatEditResult(args, preview, result, theme, isError) {
93
132
  const rawPath = str(args?.file_path ?? args?.path);
@@ -133,7 +172,7 @@ function buildEditCallComponent(component, args, theme, cwd) {
133
172
  component.addChild(new Text(body, 0, 0));
134
173
  return component;
135
174
  }
136
- function setEditPreview(component, preview, argsKey) {
175
+ function setEditPreview(component, preview) {
137
176
  const current = component.preview;
138
177
  const changed = current === undefined ||
139
178
  ("error" in current && "error" in preview
@@ -143,28 +182,31 @@ function setEditPreview(component, preview, argsKey) {
143
182
  !("error" in preview) &&
144
183
  (current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));
145
184
  component.preview = preview;
146
- component.previewArgsKey = argsKey;
147
185
  component.previewPending = false;
148
186
  return changed;
149
187
  }
150
188
  export function createEditToolDefinition(cwd, options) {
151
189
  const ops = options?.operations ?? defaultEditOperations;
190
+ if (options?.operations && !options.intentController) {
191
+ throw new Error("Custom edit operations require a matching file mutation intent controller.");
192
+ }
193
+ const intentController = options?.intentController ?? new FileMutationIntentController();
194
+ let cachedMatchPlan;
152
195
  return {
153
196
  name: "edit",
154
197
  label: "edit",
155
- description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
156
- promptSnippet: "Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
198
+ description: "Edit existing UTF-8 text: prepare(path), then commit(path,intentId,edits). oldText must be exact, unique, and non-overlapping; optional inclusive line ranges bind matches to prior reads; stale targets are rejected.",
199
+ promptSnippet: "Preflight existing files; commit exact, stale-safe edits",
157
200
  promptGuidelines: [
158
- "Use edit for precise changes (edits[].oldText must match exactly)",
159
- "When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls",
160
- "Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.",
161
- "Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.",
201
+ "Before replacements, prepare(path); then commit once with intentId and all edits.",
202
+ "oldText is exact, unique, minimal, and original-file based; pass the inclusive line range from the supplying read when known, batch separate edits, and merge overlaps.",
162
203
  ],
163
204
  parameters: editSchema,
164
205
  renderShell: "self",
165
206
  prepareArguments: prepareEditArguments,
166
207
  async execute(_toolCallId, input, signal, _onUpdate, _ctx) {
167
- const { path, edits } = validateEditInput(input);
208
+ const validated = validateEditInput(input);
209
+ const { path } = validated;
168
210
  const absolutePath = resolveToCwd(path, cwd);
169
211
  return withFileMutationQueue(absolutePath, async () => {
170
212
  // Do not reject from an abort event listener here: that would release the
@@ -176,20 +218,26 @@ export function createEditToolDefinition(cwd, options) {
176
218
  throw new Error("Operation aborted");
177
219
  };
178
220
  throwIfAborted();
179
- // Check if file exists.
180
- try {
181
- await ops.access(absolutePath);
182
- }
183
- catch (error) {
184
- throwIfAborted();
185
- const errorMessage = error instanceof Error && "code" in error ? `Error code: ${error.code}` : String(error);
186
- throw new Error(`Could not edit file: ${path}. ${errorMessage}.`);
221
+ if (validated.action === "prepare") {
222
+ const prepared = await intentController.prepare("edit", absolutePath, signal, path);
223
+ return {
224
+ content: [
225
+ {
226
+ type: "text",
227
+ text: `Edit target accepted. Commit ${path} with intentId ${prepared.intentId}.`,
228
+ },
229
+ ],
230
+ details: { phase: "prepared", intentId: prepared.intentId },
231
+ };
187
232
  }
233
+ const { edits, intentId } = validated;
234
+ const lease = intentController.consume(intentId, "edit", absolutePath);
235
+ await intentController.assertCurrent(lease, signal);
188
236
  throwIfAborted();
189
237
  // Read the file.
190
238
  const buffer = await ops.readFile(absolutePath);
191
239
  if (!isValidUTF8(buffer)) {
192
- throw new Error(`Could not edit file: ${path}. Binary or non-UTF-8 text cannot be safely edited by the text edit tool.`);
240
+ throw new Error(`PI_FILE_ENCODING_CORRUPTION: ${path} is not valid UTF-8 text; exact text replacement is unsafe and could corrupt its bytes.`);
193
241
  }
194
242
  const rawContent = buffer.toString("utf-8");
195
243
  throwIfAborted();
@@ -197,42 +245,67 @@ export function createEditToolDefinition(cwd, options) {
197
245
  const { bom, text: content } = stripBom(rawContent);
198
246
  const originalEnding = detectLineEnding(content);
199
247
  const normalizedContent = normalizeToLF(content);
200
- const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);
248
+ const cachedForIntent = cachedMatchPlan?.intentId === intentId ? cachedMatchPlan : undefined;
249
+ if (cachedForIntent)
250
+ cachedMatchPlan = undefined;
251
+ const matchPlanReused = cachedForIntent !== undefined &&
252
+ cachedForIntent.absolutePath === absolutePath &&
253
+ editsMatch(cachedForIntent.edits, edits);
254
+ const { baseContent, newContent } = matchPlanReused
255
+ ? applyEditMatchPlan(normalizedContent, cachedForIntent.plan, path)
256
+ : applyEditsToNormalizedContent(normalizedContent, edits, path);
201
257
  throwIfAborted();
202
258
  const finalContent = bom + restoreLineEndings(newContent, originalEnding);
203
259
  await ops.writeFile(absolutePath, finalContent);
204
260
  throwIfAborted();
205
- const diffResult = generateDiffString(baseContent, newContent);
261
+ const contentReference = intentController.rememberContent(absolutePath, finalContent);
262
+ const diffResult = matchPlanReused
263
+ ? { diff: cachedForIntent.diff, firstChangedLine: cachedForIntent.firstChangedLine }
264
+ : generateDiffString(baseContent, newContent);
206
265
  const patch = generateUnifiedPatch(path, baseContent, newContent);
207
266
  return {
208
267
  content: [
209
268
  {
210
269
  type: "text",
211
- text: `Successfully replaced ${edits.length} block(s) in ${path}.`,
270
+ text: `Successfully replaced ${edits.length} block(s) in ${path}. Reuse exact bytes with contentRef ${contentReference.contentRef}.`,
212
271
  },
213
272
  ],
214
- details: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },
273
+ details: {
274
+ phase: "committed",
275
+ contentRef: contentReference.contentRef,
276
+ diff: diffResult.diff,
277
+ patch,
278
+ firstChangedLine: diffResult.firstChangedLine,
279
+ matchPlanReused,
280
+ },
215
281
  };
216
282
  });
217
283
  },
218
284
  renderCall(args, theme, context) {
219
285
  const component = getEditCallRenderComponent(context.state, context.lastComponent);
220
286
  const previewInput = getRenderablePreviewInput(args);
221
- const argsKey = previewInput
222
- ? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })
223
- : undefined;
224
- if (component.previewArgsKey !== argsKey) {
287
+ if ((!context.argsComplete || !previewInput) && (component.preview || component.previewPending)) {
225
288
  component.preview = undefined;
226
- component.previewArgsKey = argsKey;
227
289
  component.previewPending = false;
228
290
  component.settledError = false;
291
+ component.previewRequestId++;
229
292
  }
230
293
  if (context.argsComplete && previewInput && !component.preview && !component.previewPending) {
231
294
  component.previewPending = true;
232
- const requestKey = argsKey;
233
- void computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {
234
- if (component.previewArgsKey === requestKey) {
235
- setEditPreview(component, preview, requestKey);
295
+ const requestId = ++component.previewRequestId;
296
+ void computeEditsPlannedDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {
297
+ if (component.previewRequestId === requestId) {
298
+ if (!("error" in preview) && !options?.operations) {
299
+ cachedMatchPlan = {
300
+ intentId: previewInput.intentId,
301
+ absolutePath: resolveToCwd(previewInput.path, context.cwd),
302
+ edits: snapshotEdits(previewInput.edits),
303
+ plan: preview.plan,
304
+ diff: preview.diff,
305
+ firstChangedLine: preview.firstChangedLine,
306
+ };
307
+ }
308
+ setEditPreview(component, preview);
236
309
  context.invalidate();
237
310
  }
238
311
  });
@@ -241,17 +314,17 @@ export function createEditToolDefinition(cwd, options) {
241
314
  },
242
315
  renderResult(result, _options, theme, context) {
243
316
  const callComponent = context.state.callComponent;
244
- const previewInput = getRenderablePreviewInput(context.args);
245
- const argsKey = previewInput
246
- ? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })
247
- : undefined;
248
317
  const typedResult = result;
249
318
  const resultDiff = !context.isError ? typedResult.details?.diff : undefined;
250
319
  let changed = false;
251
320
  if (callComponent) {
321
+ callComponent.previewRequestId++;
252
322
  if (typeof resultDiff === "string") {
253
323
  changed =
254
- setEditPreview(callComponent, { diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine }, argsKey) || changed;
324
+ setEditPreview(callComponent, {
325
+ diff: resultDiff,
326
+ firstChangedLine: typedResult.details?.firstChangedLine,
327
+ }) || changed;
255
328
  }
256
329
  if (callComponent.settledError !== context.isError) {
257
330
  callComponent.settledError = context.isError;
@@ -1 +1 @@
1
- {"version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AAK,EAAE,CAAC;YAClB,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC3C,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { Box, Container, Spacer, Text } from \"@caupulican/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { renderDiff } from \"../../modes/interactive/components/diff.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tcomputeEditsDiff,\n\tdetectLineEnding,\n\ttype Edit,\n\ttype EditDiffError,\n\ttype EditDiffResult,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { isValidUTF8 } from \"./file-encoding-policy.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\ntype EditPreview = EditDiffResult | EditDiffError;\n\ntype EditRenderState = {\n\tcallComponent?: EditCallRenderComponent;\n};\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst editSchema = Type.Object(\n\t{\n\t\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = EditToolInput & {\n\toldText?: unknown;\n\tnewText?: unknown;\n};\n\nexport interface EditToolDetails {\n\t/** Display-oriented diff of the changes made */\n\tdiff: string;\n\t/** Standard unified patch of the changes made */\n\tpatch: string;\n\t/** Line number of the first change in the new file (for editor navigation) */\n\tfirstChangedLine?: number;\n}\n\n/**\n * Pluggable operations for the edit tool.\n * Override these to delegate file editing to remote systems (for example SSH).\n */\nexport interface EditOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Check if file is readable and writable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n}\n\nconst defaultEditOperations: EditOperations = {\n\treadFile: (path) => fsReadFile(path),\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\taccess: (path) => fsAccess(path, constants.R_OK | constants.W_OK),\n};\n\nexport interface EditToolOptions {\n\t/** Custom operations for file editing. Default: local filesystem */\n\toperations?: EditOperations;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") {\n\t\treturn input as EditToolInput;\n\t}\n\n\tconst args = input as Record<string, unknown>;\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") {\n\t\treturn args as EditToolInput;\n\t}\n\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\ntype RenderableEditArgs = {\n\tpath?: string;\n\tfile_path?: string;\n\tedits?: Edit[];\n\toldText?: string;\n\tnewText?: string;\n};\n\ntype EditToolResultLike = {\n\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\tdetails?: EditToolDetails;\n};\n\ntype EditCallRenderComponent = Box & {\n\tpreview?: EditPreview;\n\tpreviewArgsKey?: string;\n\tpreviewPending?: boolean;\n\tsettledError?: boolean;\n};\n\nfunction createEditCallRenderComponent(): EditCallRenderComponent {\n\treturn Object.assign(new Box(1, 1, (text: string) => text), {\n\t\tpreview: undefined as EditPreview | undefined,\n\t\tpreviewArgsKey: undefined as string | undefined,\n\t\tpreviewPending: false,\n\t\tsettledError: false,\n\t});\n}\n\nfunction getEditCallRenderComponent(state: EditRenderState, lastComponent: unknown): EditCallRenderComponent {\n\tif (lastComponent instanceof Box) {\n\t\tconst component = lastComponent as EditCallRenderComponent;\n\t\tstate.callComponent = component;\n\t\treturn component;\n\t}\n\tif (state.callComponent) {\n\t\treturn state.callComponent;\n\t}\n\tconst component = createEditCallRenderComponent();\n\tstate.callComponent = component;\n\treturn component;\n}\n\nfunction getRenderablePreviewInput(args: RenderableEditArgs | undefined): { path: string; edits: Edit[] } | null {\n\tif (!args) {\n\t\treturn null;\n\t}\n\n\tconst path = typeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\tif (!path) {\n\t\treturn null;\n\t}\n\n\tif (\n\t\tArray.isArray(args.edits) &&\n\t\targs.edits.length > 0 &&\n\t\targs.edits.every((edit) => typeof edit?.oldText === \"string\" && typeof edit?.newText === \"string\")\n\t) {\n\t\treturn { path, edits: args.edits };\n\t}\n\n\tif (typeof args.oldText === \"string\" && typeof args.newText === \"string\") {\n\t\treturn { path, edits: [{ oldText: args.oldText, newText: args.newText }] };\n\t}\n\n\treturn null;\n}\n\nfunction formatEditCall(args: RenderableEditArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"edit\"))} ${pathDisplay}`;\n}\n\nfunction formatEditResult(\n\targs: RenderableEditArgs | undefined,\n\tpreview: EditPreview | undefined,\n\tresult: EditToolResultLike,\n\ttheme: Theme,\n\tisError: boolean,\n): string | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst previewDiff = preview && !(\"error\" in preview) ? preview.diff : undefined;\n\tconst previewError = preview && \"error\" in preview ? preview.error : undefined;\n\tif (isError) {\n\t\tconst errorText = result.content\n\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t.map((c) => c.text || \"\")\n\t\t\t.join(\"\\n\");\n\t\tif (!errorText || errorText === previewError) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn theme.fg(\"error\", errorText);\n\t}\n\n\tconst resultDiff = result.details?.diff;\n\tif (resultDiff && resultDiff !== previewDiff) {\n\t\treturn renderDiff(resultDiff, { filePath: rawPath ?? undefined });\n\t}\n\n\treturn undefined;\n}\n\nfunction getEditHeaderBg(\n\tpreview: EditPreview | undefined,\n\tsettledError: boolean | undefined,\n\ttheme: Theme,\n): (text: string) => string {\n\tif (preview) {\n\t\tif (\"error\" in preview) {\n\t\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t\t}\n\t\treturn (text: string) => theme.bg(\"toolSuccessBg\", text);\n\t}\n\tif (settledError) {\n\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t}\n\treturn (text: string) => theme.bg(\"toolPendingBg\", text);\n}\n\nfunction buildEditCallComponent(\n\tcomponent: EditCallRenderComponent,\n\targs: RenderableEditArgs | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): EditCallRenderComponent {\n\tcomponent.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));\n\tcomponent.clear();\n\tcomponent.addChild(new Text(formatEditCall(args, theme, cwd), 0, 0));\n\n\tif (!component.preview) {\n\t\treturn component;\n\t}\n\n\tconst body =\n\t\t\"error\" in component.preview ? theme.fg(\"error\", component.preview.error) : renderDiff(component.preview.diff);\n\tcomponent.addChild(new Spacer(1));\n\tcomponent.addChild(new Text(body, 0, 0));\n\treturn component;\n}\n\nfunction setEditPreview(\n\tcomponent: EditCallRenderComponent,\n\tpreview: EditPreview,\n\targsKey: string | undefined,\n): boolean {\n\tconst current = component.preview;\n\tconst changed =\n\t\tcurrent === undefined ||\n\t\t(\"error\" in current && \"error\" in preview\n\t\t\t? current.error !== preview.error\n\t\t\t: \"error\" in current !== \"error\" in preview) ||\n\t\t(!(\"error\" in current) &&\n\t\t\t!(\"error\" in preview) &&\n\t\t\t(current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));\n\tcomponent.preview = preview;\n\tcomponent.previewArgsKey = argsKey;\n\tcomponent.previewPending = false;\n\treturn changed;\n}\n\nexport function createEditToolDefinition(\n\tcwd: string,\n\toptions?: EditToolOptions,\n): ToolDefinition<typeof editSchema, EditToolDetails | undefined, EditRenderState> {\n\tconst ops = options?.operations ?? defaultEditOperations;\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tpromptSnippet:\n\t\t\t\"Make precise file edits with exact text replacement, including multiple disjoint edits in one call\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use edit for precise changes (edits[].oldText must match exactly)\",\n\t\t\t\"When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls\",\n\t\t\t\"Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.\",\n\t\t\t\"Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.\",\n\t\t],\n\t\tparameters: editSchema,\n\t\trenderShell: \"self\",\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input: EditToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, edits } = validateEditInput(input);\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Check if file exists.\n\t\t\t\ttry {\n\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\terror instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. ${errorMessage}.`);\n\t\t\t\t}\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Read the file.\n\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\tif (!isValidUTF8(buffer)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Could not edit file: ${path}. Binary or non-UTF-8 text cannot be safely edited by the text edit tool.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst rawContent = buffer.toString(\"utf-8\");\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Strip BOM before matching. The model will not include an invisible BOM in oldText.\n\t\t\t\tconst { bom, text: content } = stripBom(rawContent);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tawait ops.writeFile(absolutePath, finalContent);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\tconst patch = generateUnifiedPatch(path, baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Successfully replaced ${edits.length} block(s) in ${path}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = getEditCallRenderComponent(context.state, context.lastComponent);\n\t\t\tconst previewInput = getRenderablePreviewInput(args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\n\t\t\tif (component.previewArgsKey !== argsKey) {\n\t\t\t\tcomponent.preview = undefined;\n\t\t\t\tcomponent.previewArgsKey = argsKey;\n\t\t\t\tcomponent.previewPending = false;\n\t\t\t\tcomponent.settledError = false;\n\t\t\t}\n\n\t\t\tif (context.argsComplete && previewInput && !component.preview && !component.previewPending) {\n\t\t\t\tcomponent.previewPending = true;\n\t\t\t\tconst requestKey = argsKey;\n\t\t\t\tvoid computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {\n\t\t\t\t\tif (component.previewArgsKey === requestKey) {\n\t\t\t\t\t\tsetEditPreview(component, preview, requestKey);\n\t\t\t\t\t\tcontext.invalidate();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn buildEditCallComponent(component, args, theme, context.cwd);\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst callComponent = context.state.callComponent;\n\t\t\tconst previewInput = getRenderablePreviewInput(context.args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\t\t\tconst typedResult = result as EditToolResultLike;\n\t\t\tconst resultDiff = !context.isError ? typedResult.details?.diff : undefined;\n\t\t\tlet changed = false;\n\t\t\tif (callComponent) {\n\t\t\t\tif (typeof resultDiff === \"string\") {\n\t\t\t\t\tchanged =\n\t\t\t\t\t\tsetEditPreview(\n\t\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\t\t{ diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine },\n\t\t\t\t\t\t\targsKey,\n\t\t\t\t\t\t) || changed;\n\t\t\t\t}\n\t\t\t\tif (callComponent.settledError !== context.isError) {\n\t\t\t\t\tcallComponent.settledError = context.isError;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\tif (changed) {\n\t\t\t\t\tbuildEditCallComponent(\n\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\tcontext.args as RenderableEditArgs | undefined,\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tcontext.cwd,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError);\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tif (!output) {\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(output, 1, 0));\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createEditTool(cwd: string, options?: EditToolOptions): AgentTool<typeof editSchema> {\n\treturn wrapToolDefinition(createEditToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,QAAQ,IAAI,UAAU,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,4CAA4C,CAAC;AAGxE,OAAO,EACN,kBAAkB,EAClB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,EAKhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAQlE,MAAM,iBAAiB,GA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M,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;YAC3G,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;YACtF,SAAS,CAAC,KAAK,EAAE,CAAC;YAClB,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC3C,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { Box, Container, Spacer, Text } from \"@caupulican/pi-tui\";\nimport { readFile as fsReadFile, writeFile as fsWriteFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { renderDiff } from \"../../modes/interactive/components/diff.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\tapplyEditMatchPlan,\n\tapplyEditsToNormalizedContent,\n\tcomputeEditsPlannedDiff,\n\tdetectLineEnding,\n\ttype Edit,\n\ttype EditDiffError,\n\ttype EditDiffResult,\n\ttype EditMatchPlan,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { isValidUTF8 } from \"./file-encoding-policy.ts\";\nimport { FileMutationIntentController } from \"./file-mutation-intent.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\ntype EditPreview = EditDiffResult | EditDiffError;\n\ntype EditRenderState = {\n\tcallComponent?: EditCallRenderComponent;\n};\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({ minLength: 1 }),\n\t\tnewText: Type.String(),\n\t\trange: Type.Optional(\n\t\t\tType.Object(\n\t\t\t\t{\n\t\t\t\t\tstartLine: Type.Integer({ minimum: 1 }),\n\t\t\t\t\tendLine: Type.Integer({ minimum: 1 }),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst editPathSchema = Type.String({ minLength: 1 });\nconst editSchema = Type.Union([\n\tType.Object(\n\t\t{\n\t\t\taction: Type.Literal(\"prepare\"),\n\t\t\tpath: editPathSchema,\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\taction: Type.Literal(\"commit\"),\n\t\t\tpath: editPathSchema,\n\t\t\tintentId: Type.String({ minLength: 1 }),\n\t\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\t\tminItems: 1,\n\t\t\t}),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = {\n\taction?: unknown;\n\tpath?: unknown;\n\tintentId?: unknown;\n\tedits?: unknown;\n\toldText?: unknown;\n\tnewText?: unknown;\n};\n\nexport interface EditToolDetails {\n\tphase: \"prepared\" | \"committed\";\n\tintentId?: string;\n\tcontentRef?: string;\n\t/** Display-oriented diff of the changes made */\n\tdiff?: string;\n\t/** Standard unified patch of the changes made */\n\tpatch?: string;\n\t/** Line number of the first change in the new file (for editor navigation) */\n\tfirstChangedLine?: number;\n\t/** True when execution reused the match plan already validated for the call preview. */\n\tmatchPlanReused?: boolean;\n}\n\n/**\n * Pluggable operations for the edit tool.\n * Override these to delegate file editing to remote systems (for example SSH).\n */\nexport interface EditOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n}\n\nconst defaultEditOperations: EditOperations = {\n\treadFile: (path) => fsReadFile(path),\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n};\n\nexport interface EditToolOptions {\n\t/** Custom operations for file editing. Default: local filesystem */\n\toperations?: EditOperations;\n\t/** Session-owned two-phase intent and exact-content-reference authority. */\n\tintentController?: FileMutationIntentController;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") {\n\t\treturn input as EditToolInput;\n\t}\n\n\tconst args = input as Record<string, unknown>;\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") {\n\t\treturn args as EditToolInput;\n\t}\n\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(\n\tinput: EditToolInput,\n): { action: \"prepare\"; path: string } | { action: \"commit\"; path: string; intentId: string; edits: Edit[] } {\n\tif (input.action === \"prepare\") return input;\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { action: \"commit\", path: input.path, intentId: input.intentId, edits: input.edits };\n}\n\ntype RenderableEditArgs = {\n\taction?: string;\n\tpath?: string;\n\tfile_path?: string;\n\tintentId?: string;\n\tedits?: Edit[];\n\toldText?: string;\n\tnewText?: string;\n};\n\ntype EditToolResultLike = {\n\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\tdetails?: EditToolDetails;\n};\n\ntype EditCallRenderComponent = Box & {\n\tpreview?: EditPreview;\n\tpreviewRequestId: number;\n\tpreviewPending?: boolean;\n\tsettledError?: boolean;\n};\n\nfunction createEditCallRenderComponent(): EditCallRenderComponent {\n\treturn Object.assign(new Box(1, 1, (text: string) => text), {\n\t\tpreview: undefined as EditPreview | undefined,\n\t\tpreviewRequestId: 0,\n\t\tpreviewPending: false,\n\t\tsettledError: false,\n\t});\n}\n\nfunction getEditCallRenderComponent(state: EditRenderState, lastComponent: unknown): EditCallRenderComponent {\n\tif (lastComponent instanceof Box) {\n\t\tconst component = lastComponent as EditCallRenderComponent;\n\t\tstate.callComponent = component;\n\t\treturn component;\n\t}\n\tif (state.callComponent) {\n\t\treturn state.callComponent;\n\t}\n\tconst component = createEditCallRenderComponent();\n\tstate.callComponent = component;\n\treturn component;\n}\n\nfunction getRenderablePreviewInput(\n\targs: RenderableEditArgs | undefined,\n): { path: string; intentId: string; edits: Edit[] } | null {\n\tif (!args) {\n\t\treturn null;\n\t}\n\tif (args.action !== \"commit\") return null;\n\n\tconst path = typeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\tif (!path) {\n\t\treturn null;\n\t}\n\tif (typeof args.intentId !== \"string\" || args.intentId.length === 0) return null;\n\n\tif (\n\t\tArray.isArray(args.edits) &&\n\t\targs.edits.length > 0 &&\n\t\targs.edits.every((edit) => typeof edit?.oldText === \"string\" && typeof edit?.newText === \"string\")\n\t) {\n\t\treturn { path, intentId: args.intentId, edits: args.edits };\n\t}\n\n\tif (typeof args.oldText === \"string\" && typeof args.newText === \"string\") {\n\t\treturn { path, intentId: args.intentId, edits: [{ oldText: args.oldText, newText: args.newText }] };\n\t}\n\n\treturn null;\n}\n\ninterface CachedEditMatchPlan {\n\tintentId: string;\n\tabsolutePath: string;\n\tedits: Edit[];\n\tplan: EditMatchPlan;\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nfunction snapshotEdits(edits: Edit[]): Edit[] {\n\treturn edits.map((edit) => ({\n\t\toldText: edit.oldText,\n\t\tnewText: edit.newText,\n\t\t...(edit.range ? { range: { startLine: edit.range.startLine, endLine: edit.range.endLine } } : {}),\n\t}));\n}\n\nfunction editsMatch(left: Edit[], right: Edit[]): boolean {\n\tif (left.length !== right.length) return false;\n\tfor (let index = 0; index < left.length; index++) {\n\t\tconst leftEdit = left[index];\n\t\tconst rightEdit = right[index];\n\t\tif (\n\t\t\tleftEdit.oldText !== rightEdit.oldText ||\n\t\t\tleftEdit.newText !== rightEdit.newText ||\n\t\t\tleftEdit.range?.startLine !== rightEdit.range?.startLine ||\n\t\t\tleftEdit.range?.endLine !== rightEdit.range?.endLine\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction formatEditCall(args: RenderableEditArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\tconst action = args?.action === \"prepare\" ? \"prepare\" : args?.action === \"commit\" ? \"commit\" : undefined;\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"edit\"))}${action ? ` ${theme.fg(\"muted\", action)}` : \"\"} ${pathDisplay}`;\n}\n\nfunction formatEditResult(\n\targs: RenderableEditArgs | undefined,\n\tpreview: EditPreview | undefined,\n\tresult: EditToolResultLike,\n\ttheme: Theme,\n\tisError: boolean,\n): string | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst previewDiff = preview && !(\"error\" in preview) ? preview.diff : undefined;\n\tconst previewError = preview && \"error\" in preview ? preview.error : undefined;\n\tif (isError) {\n\t\tconst errorText = result.content\n\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t.map((c) => c.text || \"\")\n\t\t\t.join(\"\\n\");\n\t\tif (!errorText || errorText === previewError) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn theme.fg(\"error\", errorText);\n\t}\n\n\tconst resultDiff = result.details?.diff;\n\tif (resultDiff && resultDiff !== previewDiff) {\n\t\treturn renderDiff(resultDiff, { filePath: rawPath ?? undefined });\n\t}\n\n\treturn undefined;\n}\n\nfunction getEditHeaderBg(\n\tpreview: EditPreview | undefined,\n\tsettledError: boolean | undefined,\n\ttheme: Theme,\n): (text: string) => string {\n\tif (preview) {\n\t\tif (\"error\" in preview) {\n\t\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t\t}\n\t\treturn (text: string) => theme.bg(\"toolSuccessBg\", text);\n\t}\n\tif (settledError) {\n\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t}\n\treturn (text: string) => theme.bg(\"toolPendingBg\", text);\n}\n\nfunction buildEditCallComponent(\n\tcomponent: EditCallRenderComponent,\n\targs: RenderableEditArgs | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): EditCallRenderComponent {\n\tcomponent.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));\n\tcomponent.clear();\n\tcomponent.addChild(new Text(formatEditCall(args, theme, cwd), 0, 0));\n\n\tif (!component.preview) {\n\t\treturn component;\n\t}\n\n\tconst body =\n\t\t\"error\" in component.preview ? theme.fg(\"error\", component.preview.error) : renderDiff(component.preview.diff);\n\tcomponent.addChild(new Spacer(1));\n\tcomponent.addChild(new Text(body, 0, 0));\n\treturn component;\n}\n\nfunction setEditPreview(component: EditCallRenderComponent, preview: EditPreview): boolean {\n\tconst current = component.preview;\n\tconst changed =\n\t\tcurrent === undefined ||\n\t\t(\"error\" in current && \"error\" in preview\n\t\t\t? current.error !== preview.error\n\t\t\t: \"error\" in current !== \"error\" in preview) ||\n\t\t(!(\"error\" in current) &&\n\t\t\t!(\"error\" in preview) &&\n\t\t\t(current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));\n\tcomponent.preview = preview;\n\tcomponent.previewPending = false;\n\treturn changed;\n}\n\nexport function createEditToolDefinition(\n\tcwd: string,\n\toptions?: EditToolOptions,\n): ToolDefinition<typeof editSchema, EditToolDetails | undefined, EditRenderState> {\n\tconst ops = options?.operations ?? defaultEditOperations;\n\tif (options?.operations && !options.intentController) {\n\t\tthrow new Error(\"Custom edit operations require a matching file mutation intent controller.\");\n\t}\n\tconst intentController = options?.intentController ?? new FileMutationIntentController();\n\tlet cachedMatchPlan: CachedEditMatchPlan | undefined;\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit existing UTF-8 text: prepare(path), then commit(path,intentId,edits). oldText must be exact, unique, and non-overlapping; optional inclusive line ranges bind matches to prior reads; stale targets are rejected.\",\n\t\tpromptSnippet: \"Preflight existing files; commit exact, stale-safe edits\",\n\t\tpromptGuidelines: [\n\t\t\t\"Before replacements, prepare(path); then commit once with intentId and all edits.\",\n\t\t\t\"oldText is exact, unique, minimal, and original-file based; pass the inclusive line range from the supplying read when known, batch separate edits, and merge overlaps.\",\n\t\t],\n\t\tparameters: editSchema,\n\t\trenderShell: \"self\",\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input: EditToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst validated = validateEditInput(input);\n\t\t\tconst { path } = validated;\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\tif (validated.action === \"prepare\") {\n\t\t\t\t\tconst prepared = await intentController.prepare(\"edit\", absolutePath, signal, path);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\ttext: `Edit target accepted. Commit ${path} with intentId ${prepared.intentId}.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { phase: \"prepared\" as const, intentId: prepared.intentId },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst { edits, intentId } = validated;\n\t\t\t\tconst lease = intentController.consume(intentId, \"edit\", absolutePath);\n\t\t\t\tawait intentController.assertCurrent(lease, signal);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Read the file.\n\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\tif (!isValidUTF8(buffer)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`PI_FILE_ENCODING_CORRUPTION: ${path} is not valid UTF-8 text; exact text replacement is unsafe and could corrupt its bytes.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst rawContent = buffer.toString(\"utf-8\");\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Strip BOM before matching. The model will not include an invisible BOM in oldText.\n\t\t\t\tconst { bom, text: content } = stripBom(rawContent);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst cachedForIntent = cachedMatchPlan?.intentId === intentId ? cachedMatchPlan : undefined;\n\t\t\t\tif (cachedForIntent) cachedMatchPlan = undefined;\n\t\t\t\tconst matchPlanReused =\n\t\t\t\t\tcachedForIntent !== undefined &&\n\t\t\t\t\tcachedForIntent.absolutePath === absolutePath &&\n\t\t\t\t\teditsMatch(cachedForIntent.edits, edits);\n\t\t\t\tconst { baseContent, newContent } = matchPlanReused\n\t\t\t\t\t? applyEditMatchPlan(normalizedContent, cachedForIntent.plan, path)\n\t\t\t\t\t: applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tawait ops.writeFile(absolutePath, finalContent);\n\t\t\t\tthrowIfAborted();\n\t\t\t\tconst contentReference = intentController.rememberContent(absolutePath, finalContent);\n\n\t\t\t\tconst diffResult = matchPlanReused\n\t\t\t\t\t? { diff: cachedForIntent.diff, firstChangedLine: cachedForIntent.firstChangedLine }\n\t\t\t\t\t: generateDiffString(baseContent, newContent);\n\t\t\t\tconst patch = generateUnifiedPatch(path, baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Successfully replaced ${edits.length} block(s) in ${path}. Reuse exact bytes with contentRef ${contentReference.contentRef}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tphase: \"committed\" as const,\n\t\t\t\t\t\tcontentRef: contentReference.contentRef,\n\t\t\t\t\t\tdiff: diffResult.diff,\n\t\t\t\t\t\tpatch,\n\t\t\t\t\t\tfirstChangedLine: diffResult.firstChangedLine,\n\t\t\t\t\t\tmatchPlanReused,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = getEditCallRenderComponent(context.state, context.lastComponent);\n\t\t\tconst previewInput = getRenderablePreviewInput(args as RenderableEditArgs | undefined);\n\n\t\t\tif ((!context.argsComplete || !previewInput) && (component.preview || component.previewPending)) {\n\t\t\t\tcomponent.preview = undefined;\n\t\t\t\tcomponent.previewPending = false;\n\t\t\t\tcomponent.settledError = false;\n\t\t\t\tcomponent.previewRequestId++;\n\t\t\t}\n\n\t\t\tif (context.argsComplete && previewInput && !component.preview && !component.previewPending) {\n\t\t\t\tcomponent.previewPending = true;\n\t\t\t\tconst requestId = ++component.previewRequestId;\n\t\t\t\tvoid computeEditsPlannedDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {\n\t\t\t\t\tif (component.previewRequestId === requestId) {\n\t\t\t\t\t\tif (!(\"error\" in preview) && !options?.operations) {\n\t\t\t\t\t\t\tcachedMatchPlan = {\n\t\t\t\t\t\t\t\tintentId: previewInput.intentId,\n\t\t\t\t\t\t\t\tabsolutePath: resolveToCwd(previewInput.path, context.cwd),\n\t\t\t\t\t\t\t\tedits: snapshotEdits(previewInput.edits),\n\t\t\t\t\t\t\t\tplan: preview.plan,\n\t\t\t\t\t\t\t\tdiff: preview.diff,\n\t\t\t\t\t\t\t\tfirstChangedLine: preview.firstChangedLine,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsetEditPreview(component, preview);\n\t\t\t\t\t\tcontext.invalidate();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn buildEditCallComponent(component, args, theme, context.cwd);\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst callComponent = context.state.callComponent;\n\t\t\tconst typedResult = result as EditToolResultLike;\n\t\t\tconst resultDiff = !context.isError ? typedResult.details?.diff : undefined;\n\t\t\tlet changed = false;\n\t\t\tif (callComponent) {\n\t\t\t\tcallComponent.previewRequestId++;\n\t\t\t\tif (typeof resultDiff === \"string\") {\n\t\t\t\t\tchanged =\n\t\t\t\t\t\tsetEditPreview(callComponent, {\n\t\t\t\t\t\t\tdiff: resultDiff,\n\t\t\t\t\t\t\tfirstChangedLine: typedResult.details?.firstChangedLine,\n\t\t\t\t\t\t}) || changed;\n\t\t\t\t}\n\t\t\t\tif (callComponent.settledError !== context.isError) {\n\t\t\t\t\tcallComponent.settledError = context.isError;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\tif (changed) {\n\t\t\t\t\tbuildEditCallComponent(\n\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\tcontext.args as RenderableEditArgs | undefined,\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tcontext.cwd,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError);\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tif (!output) {\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(output, 1, 0));\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createEditTool(cwd: string, options?: EditToolOptions): AgentTool<typeof editSchema> {\n\treturn wrapToolDefinition(createEditToolDefinition(cwd, options));\n}\n"]}
@@ -0,0 +1,70 @@
1
+ export type FileMutationKind = "write" | "edit";
2
+ export interface FilePathIdentity {
3
+ dev: string;
4
+ ino: string;
5
+ mode: string;
6
+ size: string;
7
+ mtimeMs: string;
8
+ ctimeMs: string;
9
+ }
10
+ export interface FilePathInspection {
11
+ kind: "file" | "directory" | "other";
12
+ identity: FilePathIdentity;
13
+ }
14
+ export interface FileMutationIntentOperations {
15
+ inspect(path: string, followSymlinks: boolean): Promise<FilePathInspection | undefined>;
16
+ access(path: string, mode: number): Promise<void>;
17
+ copyFileExclusive(sourcePath: string, targetPath: string): Promise<void>;
18
+ hashFile(path: string, signal?: AbortSignal): Promise<string>;
19
+ removeFile(path: string): Promise<void>;
20
+ }
21
+ export interface PreparedFileMutation {
22
+ intentId: string;
23
+ kind: FileMutationKind;
24
+ path: string;
25
+ displayPath: string;
26
+ }
27
+ export interface FileMutationLease extends PreparedFileMutation {
28
+ identity?: FilePathIdentity;
29
+ }
30
+ export interface FileContentReference {
31
+ contentRef: string;
32
+ byteLength: number;
33
+ }
34
+ export interface FileMutationIntentControllerOptions {
35
+ operations?: FileMutationIntentOperations;
36
+ intentLimit?: number;
37
+ contentReferenceLimit?: number;
38
+ intentTtlMs?: number;
39
+ contentReferenceTtlMs?: number;
40
+ now?: () => number;
41
+ }
42
+ export declare const localFileMutationIntentOperations: FileMutationIntentOperations;
43
+ /**
44
+ * Session-owned authority for two-phase file mutation intents and bounded exact-content references.
45
+ * It retains only fixed-size metadata; file bytes remain owned by the filesystem.
46
+ */
47
+ export declare class FileMutationIntentController {
48
+ private readonly operations;
49
+ private readonly intentLimit;
50
+ private readonly contentReferenceLimit;
51
+ private readonly intentTtlMs;
52
+ private readonly contentReferenceTtlMs;
53
+ private readonly now;
54
+ private readonly intents;
55
+ private readonly intentByPath;
56
+ private readonly contentReferences;
57
+ constructor(options?: FileMutationIntentControllerOptions);
58
+ prepare(kind: FileMutationKind, path: string, signal?: AbortSignal, displayPath?: string): Promise<PreparedFileMutation>;
59
+ consume(intentId: string, kind: FileMutationKind, path: string): FileMutationLease;
60
+ assertCurrent(lease: FileMutationLease, signal?: AbortSignal): Promise<void>;
61
+ rememberContent(sourcePath: string, content: string): FileContentReference;
62
+ copyReferencedContent(contentRef: string, targetPath: string, signal?: AbortSignal): Promise<FileContentReference>;
63
+ private assertCreatableParent;
64
+ private rememberContentDigest;
65
+ private touchContentReference;
66
+ private removeFailedCopy;
67
+ private deleteIntent;
68
+ private pruneExpired;
69
+ }
70
+ //# sourceMappingURL=file-mutation-intent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-mutation-intent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-intent.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG,MAAM,CAAC;AAEhD,MAAM,WAAW,gBAAgB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,OAAO,CAAC;IACrC,QAAQ,EAAE,gBAAgB,CAAC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