@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
package/src/pi/render.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared helpers for the hashline-aware tool renderers.
|
|
3
3
|
*
|
|
4
|
-
* Mutation previews and
|
|
4
|
+
* Mutation previews and the one TUI presentation of a report (report.ts): every
|
|
5
|
+
* card renders its result's facts from the structured report in `details`,
|
|
6
|
+
* never from the model text. Argument rejections are the exception Pi forces:
|
|
7
|
+
* they are raised before execution and arrive as text only, so they are decoded
|
|
8
|
+
* with the report codec.
|
|
5
9
|
*
|
|
6
10
|
* @module pi-hashline-edit/pi
|
|
7
11
|
*/
|
|
@@ -13,6 +17,9 @@ import {
|
|
|
13
17
|
} from "@earendil-works/pi-coding-agent";
|
|
14
18
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
15
19
|
import { Text, type Component } from "@earendil-works/pi-tui";
|
|
20
|
+
import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
21
|
+
import type { MutationToolName, ReportTool } from "./report-schema.ts";
|
|
22
|
+
import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
|
|
16
23
|
|
|
17
24
|
/** Max diff lines shown when a result is rendered collapsed. */
|
|
18
25
|
const MAX_COLLAPSED_DIFF_LINES = 24;
|
|
@@ -39,8 +46,8 @@ export function renderDiffPreview(diff: string, expanded: boolean, theme: Theme)
|
|
|
39
46
|
|
|
40
47
|
/** Added/removed line counts of a pi-format diff string (`+N`/`-N` leading char). */
|
|
41
48
|
export interface DiffCounts {
|
|
42
|
-
added: number;
|
|
43
|
-
removed: number;
|
|
49
|
+
readonly added: number;
|
|
50
|
+
readonly removed: number;
|
|
44
51
|
}
|
|
45
52
|
|
|
46
53
|
/** Row-local render state shared by the mutation call and result renderers. */
|
|
@@ -50,7 +57,7 @@ export interface MutationRenderState {
|
|
|
50
57
|
}
|
|
51
58
|
|
|
52
59
|
/** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
|
|
53
|
-
|
|
60
|
+
function countDiffLines(diff: string): DiffCounts {
|
|
54
61
|
let added = 0;
|
|
55
62
|
let removed = 0;
|
|
56
63
|
for (const line of diff.split("\n")) {
|
|
@@ -81,7 +88,7 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
|
|
|
81
88
|
* synchronously (not re-entrant) and the outer pass then re-adds the result
|
|
82
89
|
* component after the nested one — the diff renders twice.
|
|
83
90
|
*/
|
|
84
|
-
|
|
91
|
+
function publishDiffCounts(
|
|
85
92
|
diff: string | undefined,
|
|
86
93
|
context: { state?: MutationRenderState },
|
|
87
94
|
refreshHeader: (counts: DiffCounts) => void,
|
|
@@ -121,50 +128,161 @@ export function renderOutputPreview(
|
|
|
121
128
|
return new Text(shown.join("\n") + more, 0, 0);
|
|
122
129
|
}
|
|
123
130
|
|
|
124
|
-
/**
|
|
131
|
+
/** A value on one line when it is a scalar; lists and objects continue on indented lines. */
|
|
132
|
+
function factLines(key: string, value: unknown, theme: Theme, indent = ""): string[] {
|
|
133
|
+
const label = `${indent}${theme.fg("accent", key)}:`;
|
|
134
|
+
if (value === null || typeof value !== "object") {
|
|
135
|
+
const [first, ...rest] = String(value).split("\n");
|
|
136
|
+
return [`${label} ${first}`, ...rest.map((line) => `${indent} ${line}`)];
|
|
137
|
+
}
|
|
138
|
+
if (!Array.isArray(value))
|
|
139
|
+
return [
|
|
140
|
+
label,
|
|
141
|
+
...Object.entries(value).flatMap(([k, v]) => factLines(k, v, theme, `${indent} `)),
|
|
142
|
+
];
|
|
143
|
+
return [
|
|
144
|
+
label,
|
|
145
|
+
...value.flatMap((item: unknown) => {
|
|
146
|
+
if (item === null || typeof item !== "object") return [`${indent} - ${String(item)}`];
|
|
147
|
+
// Scalar fields share the item's line; nested lists follow it.
|
|
148
|
+
const entries = Object.entries(item);
|
|
149
|
+
const scalars = entries.filter(([, v]) => v === null || typeof v !== "object");
|
|
150
|
+
const nested = entries.filter(([, v]) => v !== null && typeof v === "object");
|
|
151
|
+
return [
|
|
152
|
+
`${indent} - ${scalars.map(([k, v]) => `${k}: ${String(v)}`).join(" · ")}`,
|
|
153
|
+
...nested.flatMap(([k, v]) => factLines(k, v, theme, `${indent} `)),
|
|
154
|
+
];
|
|
155
|
+
}),
|
|
156
|
+
];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Highlight field issues. */
|
|
160
|
+
function argumentLines(report: Report, theme: Theme): string[] {
|
|
161
|
+
const lines = [theme.fg("error", theme.bold(`Invalid arguments · ${report.tool} not executed`))];
|
|
162
|
+
// Keep source omission notices ahead of the bounded collapsed preview.
|
|
163
|
+
if (report.schemaLimited)
|
|
164
|
+
lines.push(
|
|
165
|
+
theme.fg("warning", "Schema diagnostic limit reached; additional issues may remain."),
|
|
166
|
+
);
|
|
167
|
+
if (report.omittedIssues)
|
|
168
|
+
lines.push(theme.fg("warning", `${report.omittedIssues} issues omitted from diagnostic.`));
|
|
169
|
+
for (const { field, reason, fix } of report.issues ?? []) {
|
|
170
|
+
const [first, ...rest] = reason.split("\n");
|
|
171
|
+
lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
|
|
172
|
+
for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
|
|
173
|
+
if (fix) lines.push(` ${theme.fg("dim", fix)}`);
|
|
174
|
+
}
|
|
175
|
+
return lines;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Fields every card shows in its own header or call line. */
|
|
179
|
+
const ENVELOPE_FIELDS = ["error", "tool", "path", "publication", "stage", "message", "next"];
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The one TUI presentation of a report: for a failure, a header with the code,
|
|
183
|
+
* tool, and path, the publication line, and the message; then one `key: value`
|
|
184
|
+
* row per fact in report order, and `next` last. `shown` names facts the card
|
|
185
|
+
* already presents another way (a diff, a separate command card).
|
|
186
|
+
*/
|
|
187
|
+
export function reportLines(
|
|
188
|
+
report: Report,
|
|
189
|
+
theme: Theme,
|
|
190
|
+
shown: ReadonlySet<string> = new Set(),
|
|
191
|
+
): string[] {
|
|
192
|
+
if (report.error === "INVALID_ARGUMENTS") return argumentLines(report, theme);
|
|
193
|
+
const lines: string[] = [];
|
|
194
|
+
if (report.error !== undefined) {
|
|
195
|
+
const { path } = report;
|
|
196
|
+
const target = path === undefined ? "" : ` ${Array.isArray(path) ? path.join(", ") : path}`;
|
|
197
|
+
lines.push(theme.fg("error", theme.bold(`${report.error} · ${report.tool}${target}`)));
|
|
198
|
+
if (report.publication !== undefined)
|
|
199
|
+
lines.push(
|
|
200
|
+
theme.fg(
|
|
201
|
+
report.publication === "NOT_PUBLISHED" ? "dim" : "warning",
|
|
202
|
+
`${report.publication}${report.stage === undefined ? "" : ` · ${report.stage}`}`,
|
|
203
|
+
),
|
|
204
|
+
);
|
|
205
|
+
if (report.message !== undefined)
|
|
206
|
+
for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
|
|
207
|
+
}
|
|
208
|
+
for (const [key, value] of reportEntries(report)) {
|
|
209
|
+
if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
|
|
210
|
+
for (const line of factLines(key, value, theme)) lines.push(line);
|
|
211
|
+
}
|
|
212
|
+
if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
|
|
213
|
+
return lines;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* A successful result's checked report and the content before its report block. Renderers
|
|
218
|
+
* read reports only here or through renderToolError, so the facts a card shows and the
|
|
219
|
+
* block it strips come from one check; content that is not our report stays.
|
|
220
|
+
*/
|
|
221
|
+
export function splitReport(result: Pick<AgentToolResult<unknown>, "content" | "details">): {
|
|
222
|
+
content: AgentToolResult<unknown>["content"];
|
|
223
|
+
report: Report | undefined;
|
|
224
|
+
} {
|
|
225
|
+
const report = detailsReport(result.details);
|
|
226
|
+
const last = result.content.at(-1);
|
|
227
|
+
const ours = report !== undefined && last?.type === "text" && last.text === renderReport(report);
|
|
228
|
+
return { content: ours ? result.content.slice(0, -1) : result.content, report };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Render a failure from its report; text that is not ours keeps its original lines. */
|
|
125
232
|
export function renderToolError(
|
|
126
|
-
result: Pick<AgentToolResult<unknown>, "content"
|
|
233
|
+
result: Pick<AgentToolResult<unknown>, "content"> &
|
|
234
|
+
Partial<Pick<AgentToolResult<unknown>, "details">>,
|
|
235
|
+
tool: ReportTool,
|
|
127
236
|
theme: Theme,
|
|
128
237
|
expanded: boolean,
|
|
129
238
|
): Text {
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
.
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
);
|
|
239
|
+
const report = reportOf(result, tool);
|
|
240
|
+
const lines = report
|
|
241
|
+
? reportLines(report, theme)
|
|
242
|
+
: result.content.flatMap((block) =>
|
|
243
|
+
block.type === "text" && block.text
|
|
244
|
+
? block.text.split("\n").map((line) => theme.fg("error", line))
|
|
245
|
+
: [],
|
|
246
|
+
);
|
|
247
|
+
return renderOutputPreview(lines.length ? lines : [theme.fg("error", "Error")], expanded, theme);
|
|
139
248
|
}
|
|
140
249
|
|
|
250
|
+
/** Facts a mutation card presents another way: the command card owns then_run. */
|
|
251
|
+
const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
|
|
252
|
+
|
|
141
253
|
/** Render mutation status or a diff, refreshing the call header's counts in place. */
|
|
142
254
|
export function renderMutationResult<TArgs>(
|
|
143
|
-
result: AgentToolResult<
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
255
|
+
result: AgentToolResult<
|
|
256
|
+
| {
|
|
257
|
+
diff?: string;
|
|
258
|
+
report?: Report;
|
|
259
|
+
actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
|
|
260
|
+
}
|
|
261
|
+
| undefined
|
|
262
|
+
>,
|
|
148
263
|
{ isPartial, expanded }: ToolRenderResultOptions,
|
|
149
264
|
theme: Theme,
|
|
150
265
|
context: { isError: boolean; args: TArgs; state?: MutationRenderState },
|
|
151
266
|
pending: string,
|
|
152
|
-
fallback: string,
|
|
153
267
|
header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
|
|
268
|
+
tool: MutationToolName,
|
|
154
269
|
): Text {
|
|
155
|
-
if (isPartial && result.details?.actionFusion?.
|
|
270
|
+
if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
|
|
156
271
|
return new Text(theme.fg("warning", pending), 0, 0);
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
|
|
272
|
+
if (context.isError) return renderToolError(result, tool, theme, expanded);
|
|
273
|
+
const diff = result.details?.diff;
|
|
160
274
|
// Refresh in place: invalidation inside a renderer re-enters updateDisplay.
|
|
161
275
|
publishDiffCounts(diff, context, (counts) => {
|
|
162
276
|
context.state?.callText?.setText(header(context.args, theme, counts));
|
|
163
277
|
});
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
278
|
+
const { report } = splitReport(result);
|
|
279
|
+
const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
|
|
280
|
+
const emptyDiff =
|
|
281
|
+
report?.publication === "NOT_PUBLISHED"
|
|
282
|
+
? "No net change"
|
|
283
|
+
: report?.publication === "PUBLISHED"
|
|
284
|
+
? "Updated; no logical line diff"
|
|
285
|
+
: "No diff available";
|
|
286
|
+
const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
|
|
287
|
+
return new Text([body, ...facts].join("\n"), 0, 0);
|
|
170
288
|
}
|
package/src/pi/replace-regex.ts
CHANGED
|
@@ -1,54 +1,19 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
* the same `core/replace.ts` engine that literal-only batches run in-process.
|
|
6
|
-
*
|
|
7
|
-
* @module pi-hashline-edit/pi
|
|
8
|
-
*/
|
|
1
|
+
/** Run a validated replacement batch through the shared isolated regex lifecycle. */
|
|
2
|
+
import type { Replacement, ReplacementResult } from "../core/replace-schema.ts";
|
|
3
|
+
import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
|
|
4
|
+
import { withRegexWorker } from "./regex-worker.ts";
|
|
9
5
|
|
|
10
|
-
|
|
11
|
-
import type { applyReplacements, Replacement } from "../core/replace.ts";
|
|
12
|
-
import { cancellationError, throwIfCancelled } from "./error-text.ts";
|
|
13
|
-
|
|
14
|
-
type ReplaceResult = ReturnType<typeof applyReplacements>;
|
|
15
|
-
|
|
16
|
-
export async function runRegexReplacements(
|
|
6
|
+
export function runRegexReplacements(
|
|
17
7
|
source: string,
|
|
18
8
|
rules: readonly Replacement[],
|
|
19
9
|
timeoutMs: number,
|
|
20
10
|
signal: AbortSignal | undefined,
|
|
21
|
-
): Promise<
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if (settled) return;
|
|
30
|
-
settled = true;
|
|
31
|
-
clearTimeout(timer);
|
|
32
|
-
signal?.removeEventListener("abort", abort);
|
|
33
|
-
const complete = () => (result instanceof Error ? reject(result) : resolve(result));
|
|
34
|
-
if (terminate) void worker.terminate().then(complete, reject);
|
|
35
|
-
else complete();
|
|
36
|
-
};
|
|
37
|
-
const abort = () => finish(cancellationError(), true);
|
|
38
|
-
const timer = setTimeout(
|
|
39
|
-
() => finish(new Error(`regex evaluation timed out after ${timeoutMs}ms`), true),
|
|
40
|
-
timeoutMs,
|
|
41
|
-
);
|
|
42
|
-
worker.on("message", (message: { result?: ReplaceResult; error?: string }) => {
|
|
43
|
-
if (message.error !== undefined) finish(new Error(message.error));
|
|
44
|
-
else if (message.result) finish(message.result);
|
|
45
|
-
else finish(new Error("Regex worker returned an invalid result"));
|
|
46
|
-
});
|
|
47
|
-
worker.on("error", (error) =>
|
|
48
|
-
finish(error instanceof Error ? error : new Error(String(error))),
|
|
49
|
-
);
|
|
50
|
-
worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
|
|
51
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
52
|
-
if (signal?.aborted) abort();
|
|
53
|
-
});
|
|
11
|
+
): Promise<ReplacementResult> {
|
|
12
|
+
return withRegexWorker<ReplacementRequest, ReplacementResult, ReplacementResult>(
|
|
13
|
+
new URL("./replace-worker.mjs", import.meta.url),
|
|
14
|
+
decodeWorkerReply,
|
|
15
|
+
timeoutMs,
|
|
16
|
+
signal,
|
|
17
|
+
(run) => run({ source, rules }),
|
|
18
|
+
);
|
|
54
19
|
}
|
package/src/pi/replace-tool.ts
CHANGED
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
* Distinct from the anchor-verified `edit`. `replace` is **location-blind**:
|
|
6
6
|
* it matches `find` everywhere across the whole file and substitutes every
|
|
7
7
|
* occurrence. Use it for renames and pattern-based transforms that would
|
|
8
|
-
* otherwise need many individual edits.
|
|
9
|
-
*
|
|
8
|
+
* otherwise need many individual edits. Inserting, deleting, or rewriting whole
|
|
9
|
+
* lines belongs to `edit`.
|
|
10
10
|
*
|
|
11
11
|
* - Both modes match the shared LF view and restore original line separators.
|
|
12
|
-
* -
|
|
12
|
+
* - Each rule states `literal`: literal mode keeps `$` verbatim; regex mode expands
|
|
13
|
+
* JavaScript replacement tokens.
|
|
13
14
|
* - `flags` adds regex flags in either mode; `g` is always forced so every
|
|
14
15
|
* occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
|
|
15
16
|
* `s` (dotall), `u` (unicode) all work.
|
|
@@ -29,14 +30,19 @@ import {
|
|
|
29
30
|
type ToolDefinition,
|
|
30
31
|
type ToolRenderResultOptions,
|
|
31
32
|
} from "@earendil-works/pi-coding-agent";
|
|
32
|
-
import type {
|
|
33
|
+
import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
33
34
|
import { Type, type Static } from "typebox";
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
35
|
+
import { applyReplacements } from "../core/replace.ts";
|
|
36
|
+
import { checkRegexArguments } from "../core/regex.ts";
|
|
37
|
+
import { REPLACEMENTS_SCHEMA } from "../core/replace-schema.ts";
|
|
36
38
|
import { runRegexReplacements } from "./replace-regex.ts";
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
|
|
39
|
+
import { unwritableTextError } from "../core/text.ts";
|
|
40
|
+
import {
|
|
41
|
+
ACTION_FUSION_GUIDELINES,
|
|
42
|
+
withThenRunDescription,
|
|
43
|
+
withThenRunSchema,
|
|
44
|
+
type ThenRunInput,
|
|
45
|
+
} from "./action-fusion.ts";
|
|
40
46
|
import type { HashlineEditConfig } from "./config.ts";
|
|
41
47
|
import {
|
|
42
48
|
formatDiffCounts,
|
|
@@ -44,7 +50,6 @@ import {
|
|
|
44
50
|
renderMutationResult,
|
|
45
51
|
type DiffCounts,
|
|
46
52
|
} from "./render.ts";
|
|
47
|
-
import { formatMutationAnchors } from "./mutation-result.ts";
|
|
48
53
|
import {
|
|
49
54
|
executeMutation,
|
|
50
55
|
runTextMutation,
|
|
@@ -52,115 +57,31 @@ import {
|
|
|
52
57
|
type MutationTarget,
|
|
53
58
|
type TextMutationDetails,
|
|
54
59
|
} from "./mutation-runner.ts";
|
|
55
|
-
import {
|
|
56
|
-
import {
|
|
57
|
-
import { throwIfCancelled } from "./error-text.ts";
|
|
60
|
+
import type { MutationResultDetails } from "./mutation-result.ts";
|
|
61
|
+
import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
|
|
58
62
|
import {
|
|
59
63
|
argumentItems,
|
|
60
64
|
createArgumentPreparer,
|
|
61
65
|
type ReportArgumentIssue,
|
|
62
66
|
} from "./argument-validation.ts";
|
|
63
|
-
type ReplaceDetails = TextMutationDetails
|
|
67
|
+
type ReplaceDetails = MutationResultDetails<TextMutationDetails>;
|
|
64
68
|
type ReplaceRenderContext = Parameters<
|
|
65
69
|
NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
|
|
66
70
|
>[2];
|
|
67
71
|
|
|
68
|
-
const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
|
|
69
|
-
|
|
70
|
-
const replacementSchema = Type.Object(
|
|
71
|
-
{
|
|
72
|
-
find: Type.String({
|
|
73
|
-
minLength: 1,
|
|
74
|
-
description:
|
|
75
|
-
"Text, or a JavaScript regex when regex is true. 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.",
|
|
76
|
-
}),
|
|
77
|
-
replace: Type.String({
|
|
78
|
-
description:
|
|
79
|
-
"Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
|
|
80
|
-
}),
|
|
81
|
-
regex: Type.Optional(
|
|
82
|
-
Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
|
|
83
|
-
),
|
|
84
|
-
flags: Type.Optional(
|
|
85
|
-
Type.String({
|
|
86
|
-
pattern: REGEX_FLAGS_PATTERN,
|
|
87
|
-
description: "Extra regex flags, also applied in literal mode; g is always added.",
|
|
88
|
-
}),
|
|
89
|
-
),
|
|
90
|
-
},
|
|
91
|
-
{ additionalProperties: false },
|
|
92
|
-
);
|
|
93
|
-
|
|
94
72
|
const replaceSchema = Type.Object(
|
|
95
73
|
{
|
|
96
74
|
path: Type.String({
|
|
97
75
|
minLength: 1,
|
|
98
76
|
description: "Path to the file (relative or absolute)",
|
|
99
77
|
}),
|
|
100
|
-
replacements:
|
|
101
|
-
minItems: 1,
|
|
102
|
-
description: "Rules applied to the original content; inserted text is not searched again.",
|
|
103
|
-
}),
|
|
78
|
+
replacements: REPLACEMENTS_SCHEMA,
|
|
104
79
|
},
|
|
105
80
|
{ additionalProperties: false },
|
|
106
81
|
);
|
|
107
82
|
|
|
108
|
-
function createReplaceSchema(actionFusion: boolean) {
|
|
109
|
-
return withThenRunSchema(replaceSchema, "replace", actionFusion);
|
|
110
|
-
}
|
|
111
83
|
type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
|
|
112
84
|
|
|
113
|
-
/**
|
|
114
|
-
* Bound candidate anchors by stripping common prefix/suffix lines in O(n).
|
|
115
|
-
* For a pure deletion, retain its first surviving successor. Shifted suffixes
|
|
116
|
-
* are otherwise omitted; the shared formatter removes unchanged positions.
|
|
117
|
-
*/
|
|
118
|
-
function anchorSpan(
|
|
119
|
-
oldLines: readonly string[],
|
|
120
|
-
newLines: readonly string[],
|
|
121
|
-
): { start: number; end: number; contextLines: number[] } | null {
|
|
122
|
-
const n = Math.min(oldLines.length, newLines.length);
|
|
123
|
-
let prefix = 0;
|
|
124
|
-
while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
|
|
125
|
-
// same length and fully equal → no change
|
|
126
|
-
if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
|
|
127
|
-
let oldSuffix = 0;
|
|
128
|
-
let newSuffix = 0;
|
|
129
|
-
while (
|
|
130
|
-
oldSuffix < oldLines.length - prefix &&
|
|
131
|
-
newSuffix < newLines.length - prefix &&
|
|
132
|
-
oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
|
|
133
|
-
) {
|
|
134
|
-
oldSuffix++;
|
|
135
|
-
newSuffix++;
|
|
136
|
-
}
|
|
137
|
-
const start = prefix;
|
|
138
|
-
const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
|
|
139
|
-
return start >= newLines.length
|
|
140
|
-
? null
|
|
141
|
-
: { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** Format changed positions within the candidate span, subject to the shared output budget. */
|
|
145
|
-
function formatSpanAnchors(
|
|
146
|
-
oldLines: readonly string[],
|
|
147
|
-
newLines: readonly string[],
|
|
148
|
-
span: NonNullable<ReturnType<typeof anchorSpan>>,
|
|
149
|
-
anchors: AnchorFormatter,
|
|
150
|
-
): string {
|
|
151
|
-
function* indices() {
|
|
152
|
-
for (let i = span.start; i <= span.end; i++) yield i;
|
|
153
|
-
}
|
|
154
|
-
return formatMutationAnchors(
|
|
155
|
-
oldLines,
|
|
156
|
-
newLines,
|
|
157
|
-
indices(),
|
|
158
|
-
anchors,
|
|
159
|
-
"Updated anchors:",
|
|
160
|
-
new Set(span.contextLines),
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
85
|
/** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
|
|
165
86
|
function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
|
|
166
87
|
let t = theme.fg("toolTitle", theme.bold("replace "));
|
|
@@ -171,26 +92,22 @@ function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts):
|
|
|
171
92
|
return t;
|
|
172
93
|
}
|
|
173
94
|
|
|
174
|
-
/** Report unwritable replacement text and regex compile errors; Pi checks field shapes. */
|
|
95
|
+
/** Report unwritable replacement text, flags V8 rejects, and regex compile errors; Pi checks field shapes. */
|
|
175
96
|
function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void {
|
|
176
97
|
const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
|
|
177
|
-
const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
|
|
178
98
|
rules.forEach((rule, index) => {
|
|
179
|
-
const { find, replace,
|
|
180
|
-
const
|
|
181
|
-
if (
|
|
182
|
-
if (
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
report(`replacements[${index}].find`, errorMessage(error));
|
|
192
|
-
}
|
|
193
|
-
}
|
|
99
|
+
const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
|
|
100
|
+
const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
|
|
101
|
+
if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
|
|
102
|
+
if (flags !== undefined && typeof flags !== "string") return;
|
|
103
|
+
const item = `replacements[${index}]`;
|
|
104
|
+
checkRegexArguments(
|
|
105
|
+
`${item}.flags`,
|
|
106
|
+
flags,
|
|
107
|
+
literal !== false,
|
|
108
|
+
[[`${item}.find`, find]],
|
|
109
|
+
report,
|
|
110
|
+
);
|
|
194
111
|
});
|
|
195
112
|
}
|
|
196
113
|
|
|
@@ -198,17 +115,20 @@ export function makeReplaceTool(
|
|
|
198
115
|
cwd: string,
|
|
199
116
|
config: HashlineEditConfig,
|
|
200
117
|
fusion?: ActionFusionExecutor,
|
|
118
|
+
budgets: OutputBudgetProvider = defaultOutputBudgets,
|
|
201
119
|
) {
|
|
202
|
-
const parameters =
|
|
120
|
+
const parameters = withThenRunSchema(replaceSchema, "replace", fusion !== undefined);
|
|
203
121
|
return {
|
|
204
122
|
name: "replace" as const,
|
|
205
123
|
label: "replace",
|
|
206
|
-
description:
|
|
207
|
-
"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.
|
|
124
|
+
description: withThenRunDescription(
|
|
125
|
+
"Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
|
|
126
|
+
fusion !== undefined,
|
|
127
|
+
),
|
|
208
128
|
promptSnippet: "Replace matching text across a file",
|
|
209
|
-
promptGuidelines: [
|
|
129
|
+
promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
|
|
210
130
|
parameters,
|
|
211
|
-
prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments),
|
|
131
|
+
prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments, budgets),
|
|
212
132
|
renderShell: "default" as const,
|
|
213
133
|
|
|
214
134
|
renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
|
|
@@ -216,7 +136,7 @@ export function makeReplaceTool(
|
|
|
216
136
|
},
|
|
217
137
|
|
|
218
138
|
renderResult(
|
|
219
|
-
result:
|
|
139
|
+
result: Parameters<typeof renderMutationResult>[0],
|
|
220
140
|
options: ToolRenderResultOptions,
|
|
221
141
|
theme: Theme,
|
|
222
142
|
context: ReplaceRenderContext,
|
|
@@ -227,22 +147,24 @@ export function makeReplaceTool(
|
|
|
227
147
|
theme,
|
|
228
148
|
context,
|
|
229
149
|
"Replacing…",
|
|
230
|
-
"Replaced",
|
|
231
150
|
replaceHeader,
|
|
151
|
+
"replace",
|
|
232
152
|
);
|
|
233
153
|
},
|
|
234
154
|
|
|
235
155
|
async execute(
|
|
236
156
|
toolCallId: string,
|
|
237
|
-
params: ReplaceParams
|
|
157
|
+
params: ReplaceParams,
|
|
238
158
|
signal: AbortSignal | undefined,
|
|
239
159
|
onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
|
|
240
160
|
ctx: ExtensionToolContext,
|
|
241
161
|
) {
|
|
242
|
-
return executeMutation<
|
|
162
|
+
return executeMutation<ReplaceParams, TextMutationDetails, "replace">(
|
|
243
163
|
{
|
|
164
|
+
tool: "replace",
|
|
244
165
|
cwd,
|
|
245
166
|
fusion,
|
|
167
|
+
budgets,
|
|
246
168
|
run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
|
|
247
169
|
},
|
|
248
170
|
{ toolCallId, params, signal, onUpdate, ctx },
|
|
@@ -256,39 +178,11 @@ function runReplace(
|
|
|
256
178
|
rules: ReplaceParams["replacements"],
|
|
257
179
|
config: HashlineEditConfig,
|
|
258
180
|
) {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
({ text: newText, count } = rules.some((rule) => rule.regex === true)
|
|
266
|
-
? await runRegexReplacements(
|
|
267
|
-
currentText,
|
|
268
|
-
rules,
|
|
269
|
-
config.replace.regexTimeoutMs,
|
|
270
|
-
target.signal,
|
|
271
|
-
)
|
|
272
|
-
: applyReplacements(currentText, rules));
|
|
273
|
-
} catch (error) {
|
|
274
|
-
throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
|
|
275
|
-
throw new Error(`Replace ${target.displayPath}: ${errorMessage(error)}`);
|
|
276
|
-
}
|
|
277
|
-
const changed = newText !== currentText;
|
|
278
|
-
|
|
279
|
-
return {
|
|
280
|
-
text: newText,
|
|
281
|
-
anchors: () => {
|
|
282
|
-
const oldLines = splitLines(currentText);
|
|
283
|
-
const newLines = splitLines(newText);
|
|
284
|
-
const span = changed ? anchorSpan(oldLines, newLines) : null;
|
|
285
|
-
return span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "";
|
|
286
|
-
},
|
|
287
|
-
summary: () => {
|
|
288
|
-
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
289
|
-
const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
290
|
-
return `Replaced ${target.displayPath} (${note}).`;
|
|
291
|
-
},
|
|
292
|
-
};
|
|
181
|
+
return runTextMutation<"replace">(target, async (currentText) => {
|
|
182
|
+
// The regex worker reports its own cancellation; a literal batch runs synchronously.
|
|
183
|
+
const { text, count } = rules.some((rule) => !rule.literal)
|
|
184
|
+
? await runRegexReplacements(currentText, rules, config.replace.regexTimeoutMs, target.signal)
|
|
185
|
+
: applyReplacements(currentText, rules);
|
|
186
|
+
return { text, facts: { matches: count } };
|
|
293
187
|
});
|
|
294
188
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Replacement worker request and reply decoder; shared worker errors are checked by the host. */
|
|
2
|
+
import { workerReplyDecoder } from "./regex-worker-contract.ts";
|
|
3
|
+
import { REPLACEMENT_RESULT_SCHEMA, type Replacement } from "../core/replace-schema.ts";
|
|
4
|
+
|
|
5
|
+
export interface ReplacementRequest {
|
|
6
|
+
readonly source: string;
|
|
7
|
+
readonly rules: readonly Replacement[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const decodeWorkerReply = workerReplyDecoder(REPLACEMENT_RESULT_SCHEMA);
|
package/src/pi/replace-worker.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { parentPort
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
2
|
import { applyReplacements } from "../core/replace.ts";
|
|
3
|
-
import {
|
|
3
|
+
import type { ReplacementRequest } from "./replace-worker-contract.ts";
|
|
4
|
+
// report-cause.ts only: the worker runs on plain jiti without the host's typebox mapping.
|
|
5
|
+
import { workerFailure } from "./report-cause.ts";
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
// The sole sender supplies rules already validated at the tool entry point.
|
|
8
|
+
parentPort!.on("message", ({ source, rules }: ReplacementRequest) => {
|
|
9
|
+
try {
|
|
10
|
+
parentPort!.postMessage({ result: applyReplacements(source, rules) });
|
|
11
|
+
} catch (error) {
|
|
12
|
+
parentPort!.postMessage(workerFailure(error));
|
|
13
|
+
}
|
|
14
|
+
});
|