@criogaid/pi-hashline-edit 0.3.1 → 0.4.0
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.
- package/README.md +58 -49
- package/package.json +8 -3
- package/src/core/apply.test.ts +366 -310
- package/src/core/apply.ts +269 -202
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +45 -16
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +28 -9
- package/src/core/types.ts +54 -36
- package/src/index.ts +22 -16
- package/src/integration/grep-rg.test.ts +834 -219
- package/src/integration/large-text.test.ts +62 -0
- package/src/integration/replace-package.test.ts +37 -0
- package/src/pi/action-fusion.test.ts +535 -206
- package/src/pi/action-fusion.ts +469 -244
- package/src/pi/anchor-format.test.ts +30 -19
- package/src/pi/anchor-format.ts +27 -14
- package/src/pi/budgets.ts +20 -0
- package/src/pi/config.test.ts +60 -30
- package/src/pi/config.ts +45 -32
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +359 -0
- package/src/pi/edit-tool.ts +426 -262
- package/src/pi/error-text.ts +21 -0
- package/src/pi/execute.test.ts +1593 -712
- package/src/pi/failure-context.test.ts +105 -83
- package/src/pi/failure-context.ts +83 -71
- package/src/pi/failure-path.test.ts +171 -64
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +347 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +120 -85
- package/src/pi/grep-output.ts +208 -0
- package/src/pi/grep-render.ts +58 -0
- package/src/pi/grep-scope.ts +152 -0
- package/src/pi/grep-search.ts +217 -0
- package/src/pi/grep-tool.ts +191 -766
- package/src/pi/grep.test.ts +562 -150
- package/src/pi/mutation-result.test.ts +37 -0
- package/src/pi/mutation-result.ts +107 -59
- package/src/pi/mutation-runner.ts +168 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +95 -52
- package/src/pi/read-tool.ts +215 -132
- package/src/pi/registration.test.ts +274 -113
- package/src/pi/render.test.ts +218 -83
- package/src/pi/render.ts +152 -95
- package/src/pi/replace-apply.ts +109 -0
- package/src/pi/replace-tool.ts +280 -240
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +773 -389
- package/src/pi/result-safety.test.ts +779 -342
- package/src/pi/rg-line-filter.test.ts +64 -36
- package/src/pi/rg-line-filter.ts +40 -124
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +44 -82
- package/src/pi/rg-text-view.ts +106 -36
- package/src/pi/schema.ts +27 -0
- package/src/pi/state.ts +7 -7
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +115 -52
- package/src/pi/write.test.ts +248 -96
package/src/pi/replace-tool.ts
CHANGED
|
@@ -16,282 +16,322 @@
|
|
|
16
16
|
* - `replacements` batches rules against one original snapshot; conflicting
|
|
17
17
|
* ranges or a failing rule reject the entire batch before publication.
|
|
18
18
|
*
|
|
19
|
-
* Concurrency: read-modify-write is wrapped in
|
|
19
|
+
* Concurrency: read-modify-write is wrapped in Pi's withFileMutationQueue
|
|
20
20
|
* (shared with `edit`), so a `replace` and an `edit` on the same file never
|
|
21
|
-
* interleave.
|
|
21
|
+
* interleave. Regex batches run in a cancellable worker with a time limit.
|
|
22
22
|
*
|
|
23
23
|
* @module pi-hashline-edit/pi
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
|
-
|
|
27
|
+
type ExtensionContext,
|
|
28
|
+
type Theme,
|
|
29
|
+
type ToolDefinition,
|
|
30
|
+
type ToolRenderResultOptions,
|
|
28
31
|
} from "@earendil-works/pi-coding-agent";
|
|
32
|
+
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
29
33
|
import { Type, type Static } from "typebox";
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
34
|
+
import { Worker } from "node:worker_threads";
|
|
35
|
+
import { splitLines } from "../core/lines.ts";
|
|
36
|
+
import { applyReplacements, buildRegex, type Replacement } from "./replace-apply.ts";
|
|
37
|
+
import { unwritableTextReason } from "../core/text.ts";
|
|
38
|
+
import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
35
39
|
import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
|
|
36
|
-
import {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
40
|
+
import {
|
|
41
|
+
formatDiffCounts,
|
|
42
|
+
renderMutationCall,
|
|
43
|
+
renderMutationResult,
|
|
44
|
+
type DiffCounts,
|
|
45
|
+
} from "./render.ts";
|
|
46
|
+
import { formatMutationAnchors } from "./mutation-result.ts";
|
|
47
|
+
import {
|
|
48
|
+
executeMutation,
|
|
49
|
+
runTextMutation,
|
|
50
|
+
type ActionFusionExecutor,
|
|
51
|
+
type MutationTarget,
|
|
52
|
+
type TextMutationDetails,
|
|
53
|
+
} from "./mutation-runner.ts";
|
|
54
|
+
import {
|
|
55
|
+
cancellationError,
|
|
56
|
+
errorMessage,
|
|
57
|
+
invalidArgument,
|
|
58
|
+
throwIfCancelled,
|
|
59
|
+
} from "./error-text.ts";
|
|
60
|
+
type ReplaceDetails = TextMutationDetails;
|
|
61
|
+
type ReplaceRenderContext = Parameters<
|
|
62
|
+
NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
|
|
63
|
+
>[2];
|
|
53
64
|
|
|
54
|
-
|
|
55
|
-
return Type.Object({
|
|
56
|
-
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
57
|
-
...Type.Partial(replacementSchema).properties,
|
|
58
|
-
replacements: Type.Optional(Type.Array(replacementSchema, { minItems: 1, description: "Rules matched against one original snapshot. Mutually exclusive with top-level find/replace/regex/flags/maxMatches. Overlaps reject the entire batch." })),
|
|
59
|
-
...(actionFusion ? { then_run: createThenRunSchema("Command to run once after all replacements succeed; failure does not roll back the replacement.") } : {}),
|
|
60
|
-
});
|
|
61
|
-
}
|
|
65
|
+
const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
|
|
62
66
|
|
|
63
|
-
const
|
|
64
|
-
|
|
67
|
+
const replacementSchema = Type.Object(
|
|
68
|
+
{
|
|
69
|
+
find: Type.String({
|
|
70
|
+
minLength: 1,
|
|
71
|
+
description:
|
|
72
|
+
"Text, or a JavaScript regex when regex is true (not grep's ripgrep syntax). CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
|
|
73
|
+
}),
|
|
74
|
+
replace: Type.String({
|
|
75
|
+
description:
|
|
76
|
+
"Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
|
|
77
|
+
}),
|
|
78
|
+
regex: Type.Optional(
|
|
79
|
+
Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
|
|
80
|
+
),
|
|
81
|
+
flags: Type.Optional(
|
|
82
|
+
Type.String({
|
|
83
|
+
pattern: REGEX_FLAGS_PATTERN,
|
|
84
|
+
description: "Extra regex flags, also applied in literal mode; g is always added.",
|
|
85
|
+
}),
|
|
86
|
+
),
|
|
87
|
+
},
|
|
88
|
+
{ additionalProperties: false },
|
|
89
|
+
);
|
|
65
90
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
return rules as Replacement[];
|
|
80
|
-
}
|
|
91
|
+
const replaceSchema = Type.Object(
|
|
92
|
+
{
|
|
93
|
+
path: Type.String({
|
|
94
|
+
minLength: 1,
|
|
95
|
+
description: "Path to the file (relative or absolute)",
|
|
96
|
+
}),
|
|
97
|
+
replacements: Type.Array(replacementSchema, {
|
|
98
|
+
minItems: 1,
|
|
99
|
+
description: "Rules applied to the original content; inserted text is not searched again.",
|
|
100
|
+
}),
|
|
101
|
+
},
|
|
102
|
+
{ additionalProperties: false },
|
|
103
|
+
);
|
|
81
104
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
set.add("g");
|
|
89
|
-
const flagStr = [...set].join("");
|
|
90
|
-
const logical = normalizeLineEndings(find);
|
|
91
|
-
const source = isRegex ? logical : escapeRegex(logical);
|
|
92
|
-
try {
|
|
93
|
-
return new RegExp(source, flagStr);
|
|
94
|
-
} catch (e) {
|
|
95
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
96
|
-
throw new Error(`invalid regex /${source}/${flagStr}: ${msg}`);
|
|
97
|
-
}
|
|
105
|
+
function createReplaceSchema(actionFusion: boolean) {
|
|
106
|
+
return withThenRunSchema(
|
|
107
|
+
replaceSchema,
|
|
108
|
+
"Command to run once after all replacements succeed; failure does not roll back the replacement.",
|
|
109
|
+
actionFusion,
|
|
110
|
+
);
|
|
98
111
|
}
|
|
112
|
+
type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
|
|
99
113
|
|
|
100
|
-
|
|
101
|
-
function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
|
|
102
|
-
// Without named captures, $<...> is ordinary text and may contain other $ tokens.
|
|
103
|
-
const tokens = match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
|
|
104
|
-
return template.replace(tokens, (token, key: string) => {
|
|
105
|
-
if (key === "$") return "$";
|
|
106
|
-
if (key === "&") return match[0];
|
|
107
|
-
if (key === "`") return source.slice(0, match.index);
|
|
108
|
-
if (key === "'") return source.slice(match.index! + match[0].length);
|
|
109
|
-
if (key.startsWith("<")) return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
|
|
110
|
-
const index = Number(key);
|
|
111
|
-
if (index > 0 && index < match.length) return match[index] ?? "";
|
|
112
|
-
// $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
|
|
113
|
-
const first = Number(key[0]);
|
|
114
|
-
if (key.length === 2 && first > 0 && first < match.length) return (match[first] ?? "") + key[1];
|
|
115
|
-
return token;
|
|
116
|
-
});
|
|
117
|
-
}
|
|
114
|
+
const REGEX_TIMEOUT_MS = 5_000;
|
|
118
115
|
|
|
119
|
-
function
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
116
|
+
async function applyRegexReplacements(
|
|
117
|
+
source: string,
|
|
118
|
+
rules: readonly Replacement[],
|
|
119
|
+
signal: AbortSignal | undefined,
|
|
120
|
+
): Promise<{ text: string; count: number }> {
|
|
121
|
+
throwIfCancelled(signal);
|
|
122
|
+
const worker = new Worker(new URL("./replace-worker.mjs", import.meta.url), {
|
|
123
|
+
workerData: { source, rules },
|
|
124
|
+
});
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
let settled = false;
|
|
127
|
+
const finish = (result: { text: string; count: number } | Error, terminate = false) => {
|
|
128
|
+
if (settled) return;
|
|
129
|
+
settled = true;
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
signal?.removeEventListener("abort", abort);
|
|
132
|
+
const complete = () => (result instanceof Error ? reject(result) : resolve(result));
|
|
133
|
+
if (terminate) void worker.terminate().then(complete, reject);
|
|
134
|
+
else complete();
|
|
135
|
+
};
|
|
136
|
+
const abort = () => finish(cancellationError(), true);
|
|
137
|
+
const timer = setTimeout(
|
|
138
|
+
() => finish(new Error(`regex evaluation timed out after ${REGEX_TIMEOUT_MS}ms`), true),
|
|
139
|
+
REGEX_TIMEOUT_MS,
|
|
140
|
+
);
|
|
141
|
+
worker.on(
|
|
142
|
+
"message",
|
|
143
|
+
(message: { result?: { text: string; count: number }; error?: string }) => {
|
|
144
|
+
if (message.error !== undefined) finish(new Error(message.error));
|
|
145
|
+
else if (message.result) finish(message.result);
|
|
146
|
+
else finish(new Error("Regex worker returned an invalid result"));
|
|
147
|
+
},
|
|
148
|
+
);
|
|
149
|
+
worker.on("error", (error) =>
|
|
150
|
+
finish(error instanceof Error ? error : new Error(String(error))),
|
|
151
|
+
);
|
|
152
|
+
worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
|
|
153
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
154
|
+
if (signal?.aborted) abort();
|
|
155
|
+
});
|
|
158
156
|
}
|
|
159
|
-
|
|
160
157
|
/**
|
|
161
158
|
* Bound candidate anchors by stripping common prefix/suffix lines in O(n).
|
|
162
159
|
* For a pure deletion, retain its first surviving successor. Shifted suffixes
|
|
163
160
|
* are otherwise omitted; the shared formatter removes unchanged positions.
|
|
164
161
|
*/
|
|
165
|
-
function anchorSpan(
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
162
|
+
function anchorSpan(
|
|
163
|
+
oldLines: readonly string[],
|
|
164
|
+
newLines: readonly string[],
|
|
165
|
+
): { start: number; end: number; contextLines: number[] } | null {
|
|
166
|
+
const n = Math.min(oldLines.length, newLines.length);
|
|
167
|
+
let prefix = 0;
|
|
168
|
+
while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
|
|
169
|
+
// same length and fully equal → no change
|
|
170
|
+
if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
|
|
171
|
+
let oldSuffix = 0;
|
|
172
|
+
let newSuffix = 0;
|
|
173
|
+
while (
|
|
174
|
+
oldSuffix < oldLines.length - prefix &&
|
|
175
|
+
newSuffix < newLines.length - prefix &&
|
|
176
|
+
oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
|
|
177
|
+
) {
|
|
178
|
+
oldSuffix++;
|
|
179
|
+
newSuffix++;
|
|
180
|
+
}
|
|
181
|
+
const start = prefix;
|
|
182
|
+
const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
|
|
183
|
+
return start >= newLines.length
|
|
184
|
+
? null
|
|
185
|
+
: { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
|
|
184
186
|
}
|
|
185
187
|
|
|
186
188
|
/** Format changed positions within the candidate span, subject to the shared output budget. */
|
|
187
|
-
function formatSpanAnchors(
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
189
|
+
function formatSpanAnchors(
|
|
190
|
+
oldLines: readonly string[],
|
|
191
|
+
newLines: readonly string[],
|
|
192
|
+
span: NonNullable<ReturnType<typeof anchorSpan>>,
|
|
193
|
+
anchors: AnchorFormatter,
|
|
194
|
+
): string {
|
|
195
|
+
function* indices() {
|
|
196
|
+
for (let i = span.start; i <= span.end; i++) yield i;
|
|
197
|
+
}
|
|
198
|
+
return formatMutationAnchors(
|
|
199
|
+
oldLines,
|
|
200
|
+
newLines,
|
|
201
|
+
indices(),
|
|
202
|
+
anchors,
|
|
203
|
+
"Updated anchors:",
|
|
204
|
+
new Set(span.contextLines),
|
|
205
|
+
);
|
|
192
206
|
}
|
|
193
207
|
|
|
194
|
-
/**
|
|
195
|
-
function
|
|
196
|
-
|
|
197
|
-
|
|
208
|
+
/** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
|
|
209
|
+
function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
|
|
210
|
+
let t = theme.fg("toolTitle", theme.bold("replace "));
|
|
211
|
+
t += theme.fg("accent", args.path);
|
|
212
|
+
const count = args.replacements?.length ?? 0;
|
|
213
|
+
t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
|
|
214
|
+
if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
|
|
215
|
+
return t;
|
|
198
216
|
}
|
|
199
217
|
|
|
200
|
-
/**
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
218
|
+
/**
|
|
219
|
+
* Checks the schema cannot express, run before Pi's schema validation: replacement
|
|
220
|
+
* text must be writable as UTF-8, and regex rules must compile. Rules with malformed
|
|
221
|
+
* fields are left to the schema. Arguments are never changed.
|
|
222
|
+
*/
|
|
223
|
+
function checkReplaceArguments(args: unknown): void {
|
|
224
|
+
const rules = (args as { replacements?: unknown } | null)?.replacements;
|
|
225
|
+
if (!Array.isArray(rules)) return;
|
|
226
|
+
const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
|
|
227
|
+
rules.forEach((rule, index) => {
|
|
228
|
+
const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
|
|
229
|
+
const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
|
|
230
|
+
if (reason) throw invalidArgument(`replacements[${index}].replace`, reason);
|
|
231
|
+
if (
|
|
232
|
+
regex === true &&
|
|
233
|
+
typeof find === "string" &&
|
|
234
|
+
find !== "" &&
|
|
235
|
+
(flags === undefined || (typeof flags === "string" && validFlags.test(flags)))
|
|
236
|
+
) {
|
|
237
|
+
try {
|
|
238
|
+
buildRegex(find, true, flags);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
throw invalidArgument(`replacements[${index}].find`, errorMessage(error));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
});
|
|
213
244
|
}
|
|
214
245
|
|
|
215
|
-
export function makeReplaceTool(cwd: string, fusion?:
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
246
|
+
export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
|
|
247
|
+
const parameters = createReplaceSchema(fusion !== undefined);
|
|
248
|
+
return {
|
|
249
|
+
name: "replace" as const,
|
|
250
|
+
label: "replace",
|
|
251
|
+
description:
|
|
252
|
+
"Replace every match of one or more literal or JavaScript-regex rules in a file. Overlapping matches or a rule with no match reject the whole call. Returns a diff and fresh anchors.",
|
|
253
|
+
promptSnippet: "Replace matching text across a file",
|
|
254
|
+
promptGuidelines: [
|
|
255
|
+
"Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
|
|
256
|
+
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
257
|
+
],
|
|
258
|
+
parameters,
|
|
259
|
+
prepareArguments(args: unknown): ReplaceParams {
|
|
260
|
+
checkReplaceArguments(args);
|
|
261
|
+
return args as ReplaceParams;
|
|
262
|
+
},
|
|
263
|
+
renderShell: "default" as const,
|
|
229
264
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
265
|
+
renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
|
|
266
|
+
return renderMutationCall(args, theme, context, replaceHeader);
|
|
267
|
+
},
|
|
233
268
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
269
|
+
renderResult(
|
|
270
|
+
result: AgentToolResult<ReplaceDetails>,
|
|
271
|
+
options: ToolRenderResultOptions,
|
|
272
|
+
theme: Theme,
|
|
273
|
+
context: ReplaceRenderContext,
|
|
274
|
+
) {
|
|
275
|
+
return renderMutationResult(
|
|
276
|
+
result,
|
|
277
|
+
options,
|
|
278
|
+
theme,
|
|
279
|
+
context,
|
|
280
|
+
"Replacing…",
|
|
281
|
+
"Replaced",
|
|
282
|
+
replaceHeader,
|
|
283
|
+
);
|
|
284
|
+
},
|
|
237
285
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
286
|
+
async execute(
|
|
287
|
+
toolCallId: string,
|
|
288
|
+
params: ReplaceParams & { then_run?: ThenRunInput },
|
|
289
|
+
signal: AbortSignal | undefined,
|
|
290
|
+
onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
|
|
291
|
+
ctx: ExtensionContext,
|
|
292
|
+
) {
|
|
293
|
+
return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
|
|
294
|
+
{
|
|
295
|
+
cwd,
|
|
296
|
+
fusion,
|
|
297
|
+
reportsAnchors: true,
|
|
298
|
+
run: (mutationParams, target) => runReplace(target, mutationParams.replacements),
|
|
299
|
+
},
|
|
300
|
+
{ toolCallId, params, signal, onUpdate, ctx },
|
|
301
|
+
);
|
|
302
|
+
},
|
|
303
|
+
};
|
|
250
304
|
}
|
|
251
305
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
displayPath: string,
|
|
255
|
-
params: ReplaceParams,
|
|
256
|
-
signal: AbortSignal | undefined,
|
|
257
|
-
onAnchors: (anchors: string) => void,
|
|
258
|
-
) {
|
|
259
|
-
const anchorFormatter = createAnchorFormatter();
|
|
260
|
-
let rules: Replacement[];
|
|
261
|
-
try { rules = replacementRules(params); } catch (error) {
|
|
262
|
-
throw new Error(`Replace ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
|
|
266
|
-
// honor cancel after read: if aborted, don't proceed to match/replace; the file stays untouched
|
|
267
|
-
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before apply.`);
|
|
268
|
-
|
|
269
|
-
let newText: string;
|
|
270
|
-
let count: number;
|
|
271
|
-
try {
|
|
272
|
-
({ text: newText, count } = applyReplacements(currentText, rules));
|
|
273
|
-
} catch (error) {
|
|
274
|
-
throw new Error(`Replace ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
275
|
-
}
|
|
276
|
-
const changed = newText !== currentText;
|
|
277
|
-
|
|
278
|
-
// honor cancel before write: if aborted, don't touch the disk
|
|
279
|
-
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before write.`);
|
|
306
|
+
function runReplace(target: MutationTarget, rules: ReplaceParams["replacements"]) {
|
|
307
|
+
const anchorFormatter = createAnchorFormatter();
|
|
280
308
|
|
|
281
|
-
|
|
282
|
-
|
|
309
|
+
return runTextMutation("replace", target, async (currentText) => {
|
|
310
|
+
let newText: string;
|
|
311
|
+
let count: number;
|
|
312
|
+
try {
|
|
313
|
+
({ text: newText, count } = rules.some((rule) => rule.regex === true)
|
|
314
|
+
? await applyRegexReplacements(currentText, rules, target.signal)
|
|
315
|
+
: applyReplacements(currentText, rules));
|
|
316
|
+
} catch (error) {
|
|
317
|
+
throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
|
|
318
|
+
throw new Error(`Replace ${target.displayPath}: ${errorMessage(error)}`);
|
|
319
|
+
}
|
|
320
|
+
const changed = newText !== currentText;
|
|
283
321
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
322
|
+
return {
|
|
323
|
+
text: newText,
|
|
324
|
+
anchors: () => {
|
|
325
|
+
const oldLines = splitLines(currentText);
|
|
326
|
+
const newLines = splitLines(newText);
|
|
327
|
+
const span = changed ? anchorSpan(oldLines, newLines) : null;
|
|
328
|
+
return span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "";
|
|
329
|
+
},
|
|
330
|
+
summary: () => {
|
|
331
|
+
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
332
|
+
const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
333
|
+
return `Replaced ${target.displayPath} (${note}).`;
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
});
|
|
297
337
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { applyReplacements } from "./replace-apply.ts";
|
|
3
|
+
import { errorMessage } from "./error-text.ts";
|
|
4
|
+
|
|
5
|
+
try {
|
|
6
|
+
const { source, rules } = workerData;
|
|
7
|
+
parentPort!.postMessage({ result: applyReplacements(source, rules) });
|
|
8
|
+
} catch (error) {
|
|
9
|
+
parentPort!.postMessage({ error: errorMessage(error) });
|
|
10
|
+
}
|