@criogaid/pi-hashline-edit 0.1.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/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Override read: text files output "lineNo#hash│content"; non-text (images /
|
|
3
|
+
* binary) and read errors delegate to the built-in read.
|
|
4
|
+
*
|
|
5
|
+
* Hashes are computed from the current content on the fly — nothing is stored.
|
|
6
|
+
* The hash is `(line number, content)`, recomputed and checked at edit time, so
|
|
7
|
+
* no snapshot is needed to verify an anchor later.
|
|
8
|
+
*
|
|
9
|
+
* @module pi-hashline-edit/pi
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createReadToolDefinition, getLanguageFromPath, highlightCode, truncateHead } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
14
|
+
import { readFile } from "node:fs/promises";
|
|
15
|
+
import { join, resolve } from "node:path";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { hashFileLines } from "../core/hash.ts";
|
|
18
|
+
import { hasFinalNewline, splitLines } from "../core/lines.ts";
|
|
19
|
+
import { getState } from "./state.ts";
|
|
20
|
+
import { parseHashline } from "./render.ts";
|
|
21
|
+
|
|
22
|
+
const MAX_LINES = 2000;
|
|
23
|
+
const MAX_BYTES = 256 * 1024;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Canonical absolute path: shared by read/edit/grep to resolve a file consistently.
|
|
27
|
+
* Expands a leading `~` / `~/` to the user's home directory. (`~user` is not supported.)
|
|
28
|
+
*/
|
|
29
|
+
export function canonicalPath(cwd: string, p: string): string {
|
|
30
|
+
return resolve(cwd, expandTilde(p));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Mirrors pi core's `normalizePath` tilde handling: expands `~` / `~/` (and `~\` on Windows), leaves `~user` untouched. */
|
|
34
|
+
function expandTilde(p: string): string {
|
|
35
|
+
if (p === "~") return homedir();
|
|
36
|
+
if (p.startsWith("~/") || (process.platform === "win32" && p.startsWith("~\\"))) {
|
|
37
|
+
return join(homedir(), p.slice(2));
|
|
38
|
+
}
|
|
39
|
+
return p;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Render the expanded read body for the TUI: color the header, strip the
|
|
44
|
+
* `LINE#HASH│` prefix from every anchor line to ` N: content`, and
|
|
45
|
+
* syntax-highlight the code block by the file's language (falls back to a
|
|
46
|
+
* single `toolOutput` color when the language is unknown or the highlight
|
|
47
|
+
* line count diverges). Trailing notices (e.g. truncation) are shown in
|
|
48
|
+
* `warning`.
|
|
49
|
+
*/
|
|
50
|
+
function renderReadBody(raw: string, path: string, theme: any): string {
|
|
51
|
+
const lines = raw.split("\n");
|
|
52
|
+
if (lines.length === 0) return "";
|
|
53
|
+
const out: string[] = [];
|
|
54
|
+
|
|
55
|
+
// Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
|
|
56
|
+
// and/or " · no trailing newline".
|
|
57
|
+
let bodyStart = 0;
|
|
58
|
+
const h = lines[0].match(/^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/);
|
|
59
|
+
if (h) {
|
|
60
|
+
out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
|
|
61
|
+
bodyStart = 1;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Collect anchor rows (full content); the first non-anchor line begins the tail.
|
|
65
|
+
const lineNos: string[] = [];
|
|
66
|
+
const codeContents: string[] = [];
|
|
67
|
+
let tailStart = lines.length;
|
|
68
|
+
for (let i = bodyStart; i < lines.length; i++) {
|
|
69
|
+
const row = parseHashline(lines[i]);
|
|
70
|
+
if (!row) {
|
|
71
|
+
tailStart = i;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
lineNos.push(row.lineNo);
|
|
75
|
+
codeContents.push(row.content);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Syntax-highlight the whole block so multi-line constructs stay correct.
|
|
79
|
+
const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
|
|
80
|
+
const lang = getLanguageFromPath(path);
|
|
81
|
+
let rendered: string[];
|
|
82
|
+
if (lang) {
|
|
83
|
+
const hl = highlightCode(detabbed.join("\n"), lang);
|
|
84
|
+
// Guard against highlighters that reshape line count: fall back to plain.
|
|
85
|
+
rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
|
|
86
|
+
} else {
|
|
87
|
+
rendered = detabbed.map((l) => theme.fg("toolOutput", l));
|
|
88
|
+
}
|
|
89
|
+
for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
|
|
90
|
+
out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
for (let i = tailStart; i < lines.length; i++) {
|
|
94
|
+
out.push(theme.fg("warning", lines[i]));
|
|
95
|
+
}
|
|
96
|
+
return out.join("\n");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Build the read override (a ToolDefinition fragment for registerTool). */
|
|
100
|
+
export function makeReadOverride(cwd: string) {
|
|
101
|
+
const builtin = createReadToolDefinition(cwd);
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
name: "read" as const,
|
|
105
|
+
label: "read",
|
|
106
|
+
description:
|
|
107
|
+
"Read file contents. Text files display per-line content hashes (LINE#HASH│content) for hashline-verified editing.",
|
|
108
|
+
promptSnippet: "Read files with editable line anchors",
|
|
109
|
+
promptGuidelines: [
|
|
110
|
+
"Prefer read over shell output for files you intend to edit.",
|
|
111
|
+
],
|
|
112
|
+
parameters: builtin.parameters,
|
|
113
|
+
renderShell: "default" as const,
|
|
114
|
+
|
|
115
|
+
renderCall: builtin.renderCall,
|
|
116
|
+
|
|
117
|
+
renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
|
|
118
|
+
if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
|
|
119
|
+
const content = result.content?.[0];
|
|
120
|
+
if (context?.isError) {
|
|
121
|
+
const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
122
|
+
return new Text(theme.fg("error", t), 0, 0);
|
|
123
|
+
}
|
|
124
|
+
// Collapsed (not expanded): show nothing — the call line carries the
|
|
125
|
+
// title, matching the built-in read's fold behavior.
|
|
126
|
+
if (!expanded) return new Text("", 0, 0);
|
|
127
|
+
const raw = content?.type === "text" ? content.text : "";
|
|
128
|
+
return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
async execute(toolCallId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx?: any) {
|
|
132
|
+
// User cancelled → delegate to the built-in (builtin handles abort itself)
|
|
133
|
+
if (signal?.aborted) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
134
|
+
|
|
135
|
+
const absPath = canonicalPath(cwd, params.path as string);
|
|
136
|
+
let buf: Buffer;
|
|
137
|
+
try {
|
|
138
|
+
buf = await readFile(absPath);
|
|
139
|
+
} catch {
|
|
140
|
+
// read error → delegate to the built-in (it has polished error messages)
|
|
141
|
+
return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// binary/image detection (null byte) → delegate to the built-in (it uses file-type for images)
|
|
145
|
+
if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
146
|
+
|
|
147
|
+
const text = buf.toString("utf-8");
|
|
148
|
+
const allLines = splitLines(text);
|
|
149
|
+
const totalLines = allLines.length;
|
|
150
|
+
const hashes = hashFileLines(allLines, getState().config.hashLen);
|
|
151
|
+
|
|
152
|
+
// offset/limit
|
|
153
|
+
const offset = (params.offset as number | undefined) ?? 1;
|
|
154
|
+
const limit = (params.limit as number | undefined) ?? MAX_LINES;
|
|
155
|
+
const startIdx = Math.max(0, offset - 1);
|
|
156
|
+
const endIdx = Math.min(totalLines, startIdx + limit);
|
|
157
|
+
|
|
158
|
+
const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${hashes[startIdx + index]}│${line}`);
|
|
159
|
+
const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
|
|
160
|
+
|
|
161
|
+
const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
|
|
162
|
+
// A file whose last line carries no terminator is a byte-level fact that the
|
|
163
|
+
// numbered rows cannot show; state it in the header, the one line the model
|
|
164
|
+
// never copies into an edit `body`.
|
|
165
|
+
const noFinalNewline = hasFinalNewline(text) ? "" : " · no trailing newline";
|
|
166
|
+
const tail = truncation.firstLineExceedsLimit
|
|
167
|
+
? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row)`
|
|
168
|
+
: truncation.truncated ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)` : "";
|
|
169
|
+
const header = `${params.path} · ${totalLines} lines${shownFrom}${noFinalNewline}\n`;
|
|
170
|
+
const body = truncation.content;
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
content: [{ type: "text" as const, text: header + body + tail }],
|
|
174
|
+
details: truncation.truncated ? { truncation } : undefined,
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import registerHashline from "../index.ts";
|
|
7
|
+
import { getState } from "./state.ts";
|
|
8
|
+
|
|
9
|
+
test("enabled registration installs the Hashline write and shared Fusion schemas", async () => {
|
|
10
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
|
|
11
|
+
const previousCwd = process.cwd();
|
|
12
|
+
const state = getState();
|
|
13
|
+
const previousConfig = state.config;
|
|
14
|
+
try {
|
|
15
|
+
await mkdir(join(dir, ".pi"));
|
|
16
|
+
await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true, actionFusion: true } }));
|
|
17
|
+
process.chdir(dir);
|
|
18
|
+
const tools: any[] = [];
|
|
19
|
+
const entries: any[] = [];
|
|
20
|
+
registerHashline({
|
|
21
|
+
on() {},
|
|
22
|
+
registerEntryRenderer() {},
|
|
23
|
+
appendEntry(customType: string, data: unknown) { entries.push({ customType, data }); },
|
|
24
|
+
registerTool(tool: any) { tools.push(tool); },
|
|
25
|
+
} as any);
|
|
26
|
+
assert.deepEqual(tools.map((tool) => tool.name), ["write", "edit", "replace", "read", "grep"]);
|
|
27
|
+
for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
|
|
28
|
+
assert.ok(tool.parameters.properties.then_run, `${tool.name} should expose then_run when actionFusion is enabled`);
|
|
29
|
+
}
|
|
30
|
+
const writeTool = tools.find((tool) => tool.name === "write");
|
|
31
|
+
const result = await writeTool.execute("write-error", { path: "published.txt", content: "published\n", then_run: { command: "node -e \\\"process.exit(1)\\\"" } }, undefined, undefined, { cwd: dir });
|
|
32
|
+
assert.equal(result.details.actionFusion.command, "failed");
|
|
33
|
+
assert.match(result.content[1].text, /File changes are saved[\s\S]*Command failed/);
|
|
34
|
+
assert.deepEqual(entries.map((entry) => entry.data.command), ["waiting", "failed"]);
|
|
35
|
+
assert.equal(entries[1].data.publication, "PUBLISHED");
|
|
36
|
+
} finally {
|
|
37
|
+
process.chdir(previousCwd);
|
|
38
|
+
state.config = previousConfig;
|
|
39
|
+
await rm(dir, { recursive: true, force: true });
|
|
40
|
+
}
|
|
41
|
+
});
|
package/src/pi/render.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for the hashline-aware tool renderers.
|
|
3
|
+
*
|
|
4
|
+
* The model-facing `content` text uses the `LINE#HASH│content` anchor format so
|
|
5
|
+
* an anchor can be copied straight into an edit op. The user-facing TUI
|
|
6
|
+
* renderers (read, grep) strip that prefix back to a clean ` N: content` form.
|
|
7
|
+
* Parsing the anchor format in one place keeps read and grep in sync.
|
|
8
|
+
*
|
|
9
|
+
* @module pi-hashline-edit/pi
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { renderDiff } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
|
|
14
|
+
const HASHLINE_RE = /^(\d+)#[A-Za-z0-9]+│(.*)$/;
|
|
15
|
+
|
|
16
|
+
export interface HashlineRow {
|
|
17
|
+
/** Line number as written in the anchor (string form). */
|
|
18
|
+
lineNo: string;
|
|
19
|
+
/** Line content with the `LINE#HASH│` prefix removed. */
|
|
20
|
+
content: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Parse a `LINE#HASH│content` anchor line.
|
|
25
|
+
*
|
|
26
|
+
* @returns the row, or `null` for non-anchor lines (headers, notices, free
|
|
27
|
+
* text) so callers can fall through to their own formatting.
|
|
28
|
+
*/
|
|
29
|
+
export function parseHashline(line: string): HashlineRow | null {
|
|
30
|
+
const m = line.match(HASHLINE_RE);
|
|
31
|
+
return m ? { lineNo: m[1], content: m[2] } : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Max diff lines shown when a result is rendered collapsed. */
|
|
35
|
+
const MAX_COLLAPSED_DIFF_LINES = 24;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
|
|
39
|
+
* built-in renderer: semantic diff colors plus intra-line (word-level) change
|
|
40
|
+
* highlighting on single-line modifications. When not expanded, collapse to the
|
|
41
|
+
* first 24 rendered lines with an overflow marker — truncating after rendering
|
|
42
|
+
* keeps `-`/`+` pairs intact so the intra-line highlight never dangles.
|
|
43
|
+
*/
|
|
44
|
+
export function renderDiffPreview(diff: string, expanded: boolean, theme: any): string {
|
|
45
|
+
const rendered = renderDiff(diff);
|
|
46
|
+
if (expanded) return rendered;
|
|
47
|
+
const allLines = rendered.split("\n");
|
|
48
|
+
const more =
|
|
49
|
+
allLines.length > MAX_COLLAPSED_DIFF_LINES
|
|
50
|
+
? `\n${theme.fg("dim", `… (${allLines.length - MAX_COLLAPSED_DIFF_LINES} more)`)}`
|
|
51
|
+
: "";
|
|
52
|
+
return allLines.slice(0, MAX_COLLAPSED_DIFF_LINES).join("\n") + more;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Added/removed line counts of a pi-format diff string (`+N`/`-N` leading char). */
|
|
56
|
+
export interface DiffCounts {
|
|
57
|
+
added: number;
|
|
58
|
+
removed: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
|
|
62
|
+
export function countDiffLines(diff: string): DiffCounts {
|
|
63
|
+
let added = 0;
|
|
64
|
+
let removed = 0;
|
|
65
|
+
for (const line of diff.split("\n")) {
|
|
66
|
+
if (line.startsWith("+")) added++;
|
|
67
|
+
else if (line.startsWith("-")) removed++;
|
|
68
|
+
}
|
|
69
|
+
return { added, removed };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Format `+N -N` with the theme's diff colors for the tool call header. */
|
|
73
|
+
export function formatDiffCounts(counts: DiffCounts, theme: any): string {
|
|
74
|
+
return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Stash per-call diff counts into the row-local render state and refresh the
|
|
79
|
+
* call header component in place — pi's own edit-tool pattern (renderResult
|
|
80
|
+
* mutates the component stashed by renderCall; it never re-runs the renderer).
|
|
81
|
+
*
|
|
82
|
+
* `updateDisplay` runs renderCall before renderResult in every pass, so later
|
|
83
|
+
* passes (expand/collapse, result updates) rebuild the header from
|
|
84
|
+
* `state.diffCounts`; the in-place refresh covers the first result render,
|
|
85
|
+
* where renderCall ran before the counts existed. renderResult cannot find the
|
|
86
|
+
* header via `lastComponent` — there it is the *result* component — so
|
|
87
|
+
* renderCall stashes it (e.g. `state.callText`).
|
|
88
|
+
*
|
|
89
|
+
* MUST NOT call `context.invalidate()`: it re-enters `updateDisplay`
|
|
90
|
+
* synchronously (not re-entrant) and the outer pass then re-adds the result
|
|
91
|
+
* component after the nested one — the diff renders twice.
|
|
92
|
+
*/
|
|
93
|
+
export function publishDiffCounts(
|
|
94
|
+
diff: string | undefined,
|
|
95
|
+
context: any,
|
|
96
|
+
refreshHeader: (counts: DiffCounts) => void,
|
|
97
|
+
): void {
|
|
98
|
+
if (!diff || !context?.state) return;
|
|
99
|
+
const counts = countDiffLines(diff);
|
|
100
|
+
const prev: DiffCounts | undefined = context.state.diffCounts;
|
|
101
|
+
context.state.diffCounts = counts;
|
|
102
|
+
if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
|
|
103
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `replace`: powerful bulk text replacement — literal substring (replaceAll) or
|
|
3
|
+
* full JavaScript regex with capture-group substitution.
|
|
4
|
+
*
|
|
5
|
+
* Distinct from the anchor-verified `edit`. `replace` is **location-blind**:
|
|
6
|
+
* it matches `find` everywhere across the whole file and substitutes every
|
|
7
|
+
* occurrence. Use it for renames and pattern-based transforms that would
|
|
8
|
+
* otherwise need many individual edits. For a single surgical, verified change,
|
|
9
|
+
* prefer `edit`.
|
|
10
|
+
*
|
|
11
|
+
* - Literal mode (`regex` false): `find` is a substring, matched verbatim;
|
|
12
|
+
* `replace` is inserted as-is (no `$` expansion).
|
|
13
|
+
* - Regex mode (`regex` true): `find` is a JS pattern source; `replace` supports
|
|
14
|
+
* `$1`, `$2`, `$&`, etc.
|
|
15
|
+
* - `flags` adds regex flags in either mode; `g` is always forced so every
|
|
16
|
+
* occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
|
|
17
|
+
* `s` (dotall), `u` (unicode) all work.
|
|
18
|
+
*
|
|
19
|
+
* Concurrency: read-modify-write is wrapped in {@link withFileMutationQueue}
|
|
20
|
+
* (shared with `edit`), so a `replace` and an `edit` on the same file never
|
|
21
|
+
* interleave. AbortSignal is honored after read / before write.
|
|
22
|
+
*
|
|
23
|
+
* @module pi-hashline-edit/pi
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
generateDiffString,
|
|
28
|
+
generateUnifiedPatch,
|
|
29
|
+
withFileMutationQueue,
|
|
30
|
+
type EditToolDetails,
|
|
31
|
+
} from "@earendil-works/pi-coding-agent";
|
|
32
|
+
import { Type, type Static } from "typebox";
|
|
33
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
34
|
+
import { readFile } from "node:fs/promises";
|
|
35
|
+
import { hashFileLines, splitLines } from "../core/index.ts";
|
|
36
|
+
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
37
|
+
import { commitFile, FileMutationError, type PublicationStatus } from "./file-commit.ts";
|
|
38
|
+
import { getState } from "./state.ts";
|
|
39
|
+
import { canonicalPath } from "./read-tool.ts";
|
|
40
|
+
import { formatDiffCounts, publishDiffCounts, renderDiffPreview, type DiffCounts } from "./render.ts";
|
|
41
|
+
|
|
42
|
+
/** Cap on updated-anchor lines returned inline (bounds token cost for large spans). */
|
|
43
|
+
const MAX_ANCHOR_LINES = 40;
|
|
44
|
+
/** Default safety cap on match count (errors before writing if exceeded). */
|
|
45
|
+
const DEFAULT_MAX_MATCHES = 2000;
|
|
46
|
+
/** Valid JavaScript regular-expression flag characters (ES2023+, incl. hasIndices `d`). */
|
|
47
|
+
const VALID_FLAGS = new Set(["g", "i", "m", "s", "u", "y", "d"]);
|
|
48
|
+
|
|
49
|
+
function createReplaceSchema(actionFusion: boolean) {
|
|
50
|
+
return Type.Object({
|
|
51
|
+
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
52
|
+
find: Type.String({ description: "Text to find. Literal substring when `regex` is false/omitted; a JavaScript regex pattern source when `regex` is true." }),
|
|
53
|
+
replace: Type.String({ description: "Replacement text. Literal mode: inserted verbatim (no $ expansion). Regex mode: supports $1, $2, $&, $`, $' etc." }),
|
|
54
|
+
regex: Type.Optional(Type.Boolean({ description: "Treat `find` as a JavaScript regex pattern source (default false = literal substring, all occurrences replaced)." })),
|
|
55
|
+
flags: Type.Optional(Type.String({ description: "Regex flags appended in BOTH modes ('g' is always forced so every occurrence is replaced)." })),
|
|
56
|
+
maxMatches: Type.Optional(Type.Number({ description: `Safety cap: errors before writing if more matches than this (default ${DEFAULT_MAX_MATCHES}). Raise for deliberate bulk transforms.` })),
|
|
57
|
+
...(actionFusion ? { then_run: createThenRunSchema("Command to run after replace succeeds; failure does not roll back the replacement.") } : {}),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const replaceSchema = createReplaceSchema(false);
|
|
62
|
+
|
|
63
|
+
type ReplaceParams = Omit<Static<typeof replaceSchema>, "then_run"> & { then_run?: ThenRunInput };
|
|
64
|
+
|
|
65
|
+
/** Escape regex metacharacters so a literal string is matched verbatim. */
|
|
66
|
+
function escapeRegex(s: string): string {
|
|
67
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Build the matcher. `find` is escaped in literal mode; `flags` (validated) get
|
|
72
|
+
* `g` forced so all occurrences replace. Construction errors (bad pattern /
|
|
73
|
+
* conflicting flags such as `g`+`y`) surface as a friendly message rather than
|
|
74
|
+
* a raw `SyntaxError`.
|
|
75
|
+
*/
|
|
76
|
+
function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
|
|
77
|
+
for (const c of flagsRaw ?? "") {
|
|
78
|
+
if (!VALID_FLAGS.has(c)) throw new Error(`invalid regex flag '${c}' (valid: g i m s u y d)`);
|
|
79
|
+
}
|
|
80
|
+
const set = new Set((flagsRaw ?? "").split(""));
|
|
81
|
+
set.add("g");
|
|
82
|
+
const flagStr = [...set].join("");
|
|
83
|
+
const source = isRegex ? find : escapeRegex(find);
|
|
84
|
+
try {
|
|
85
|
+
return new RegExp(source, flagStr);
|
|
86
|
+
} catch (e) {
|
|
87
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
88
|
+
throw new Error(`invalid regex /${source}/${flagStr}: ${msg}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* First-to-last differing line span (0-based, inclusive) in the NEW line array —
|
|
94
|
+
* a contiguous superset that contains every changed line. Computed by stripping
|
|
95
|
+
* the common prefix and suffix, so it is O(n) regardless of file size (no LCS
|
|
96
|
+
* DP). `null` when the text is unchanged. Used only to bound the anchor report.
|
|
97
|
+
*/
|
|
98
|
+
function changedSpan(oldLines: readonly string[], newLines: readonly string[]): { start: number; end: number } | null {
|
|
99
|
+
const n = Math.min(oldLines.length, newLines.length);
|
|
100
|
+
let prefix = 0;
|
|
101
|
+
while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
|
|
102
|
+
// same length and fully equal → no change
|
|
103
|
+
if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
|
|
104
|
+
let oldSuffix = 0;
|
|
105
|
+
let newSuffix = 0;
|
|
106
|
+
while (
|
|
107
|
+
oldSuffix < oldLines.length - prefix &&
|
|
108
|
+
newSuffix < newLines.length - prefix &&
|
|
109
|
+
oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
|
|
110
|
+
) {
|
|
111
|
+
oldSuffix++;
|
|
112
|
+
newSuffix++;
|
|
113
|
+
}
|
|
114
|
+
const start = prefix;
|
|
115
|
+
const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
|
|
116
|
+
return end < start ? null : { start, end };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Format fresh `LINE#HASH│content` anchors for a contiguous span of the new file, capped. */
|
|
120
|
+
function formatSpanAnchors(newLines: readonly string[], span: { start: number; end: number }, hashLen: number): string {
|
|
121
|
+
const hashes = hashFileLines(newLines, hashLen);
|
|
122
|
+
const rows: string[] = [];
|
|
123
|
+
for (let i = span.start; i <= span.end; i++) rows.push(`${i + 1}#${hashes[i]}│${newLines[i]}`);
|
|
124
|
+
const shown = rows.length > MAX_ANCHOR_LINES ? rows.slice(0, MAX_ANCHOR_LINES) : rows;
|
|
125
|
+
const more = rows.length > MAX_ANCHOR_LINES ? `\n… (${rows.length - MAX_ANCHOR_LINES} more; re-read for full anchors)` : "";
|
|
126
|
+
return `\nUpdated anchors (changed region):\n${shown.join("\n")}${more}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Truncate a string for one-line display, folding newlines into a marker. */
|
|
130
|
+
function show(s: string, n = 30): string {
|
|
131
|
+
const folded = s.replace(/\n/g, "⏎");
|
|
132
|
+
return folded.length > n ? folded.slice(0, n) + "…" : folded;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Call-header line: `replace path — mode "find" → "replace"`, plus `+N -N` once the result's diff counts are known. */
|
|
136
|
+
function replaceHeader(args: ReplaceParams, theme: any, counts?: DiffCounts): string {
|
|
137
|
+
let t = theme.fg("toolTitle", theme.bold("replace "));
|
|
138
|
+
t += theme.fg("accent", args.path);
|
|
139
|
+
const mode = args.regex ? "regex" : "lit";
|
|
140
|
+
const f = args.flags ? `/${args.flags}` : "";
|
|
141
|
+
t += theme.fg("dim", ` — ${mode}${f} "${show(args.find)}" → "${show(args.replace)}"`);
|
|
142
|
+
if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
|
|
143
|
+
return t;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
|
|
147
|
+
const parameters = createReplaceSchema(fusion !== undefined);
|
|
148
|
+
return {
|
|
149
|
+
name: "replace" as const,
|
|
150
|
+
label: "replace",
|
|
151
|
+
description:
|
|
152
|
+
"Replace all matching text across a file. Supports literal strings and JavaScript regex; fails on zero matches. Returns a diff and fresh anchors.",
|
|
153
|
+
promptSnippet: "Replace matching text across a file",
|
|
154
|
+
promptGuidelines: [
|
|
155
|
+
"Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
|
|
156
|
+
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
157
|
+
],
|
|
158
|
+
parameters,
|
|
159
|
+
renderShell: "default" as const,
|
|
160
|
+
|
|
161
|
+
renderCall(args: ReplaceParams & { then_run?: ThenRunInput }, theme: any, context: any) {
|
|
162
|
+
const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
163
|
+
// Stash the header for renderResult: the diff counts land after
|
|
164
|
+
// execution and are refreshed in place (renderResult's lastComponent
|
|
165
|
+
// is the result component, not this header)
|
|
166
|
+
if (context?.state) context.state.callText = text;
|
|
167
|
+
text.setText(replaceHeader(args, theme, context?.state?.diffCounts));
|
|
168
|
+
return text;
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
|
|
172
|
+
if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", "Replacing…"), 0, 0);
|
|
173
|
+
const content = result.content?.[0];
|
|
174
|
+
if (context.isError) {
|
|
175
|
+
const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
176
|
+
return new Text(theme.fg("error", t), 0, 0);
|
|
177
|
+
}
|
|
178
|
+
const diff: string | undefined = result.details?.diff;
|
|
179
|
+
// refresh the call header's +N -N in place — never invalidate from
|
|
180
|
+
// inside a renderer (re-enters updateDisplay, diff renders twice)
|
|
181
|
+
publishDiffCounts(diff, context, (counts) => {
|
|
182
|
+
context.state?.callText?.setText(replaceHeader(context.args, theme, counts));
|
|
183
|
+
});
|
|
184
|
+
if (!diff) {
|
|
185
|
+
// No net diff: show only the summary line — content.text also carries
|
|
186
|
+
// `Updated anchors` (hashline) for the model.
|
|
187
|
+
const summary = content?.type === "text" ? content.text.split("\n")[0] : "Replaced";
|
|
188
|
+
return new Text(theme.fg("success", summary), 0, 0);
|
|
189
|
+
}
|
|
190
|
+
// details.diff is pi-format (+N/-N/<space>N content); renderDiff handles
|
|
191
|
+
// semantic colors plus intra-line change highlighting
|
|
192
|
+
const rendered = renderDiffPreview(diff, expanded, theme);
|
|
193
|
+
return new Text(rendered, 0, 0);
|
|
194
|
+
},
|
|
195
|
+
|
|
196
|
+
async execute(toolCallId: string, params: ReplaceParams & { then_run?: ThenRunInput }, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
|
|
197
|
+
const { then_run, ...mutationParams } = params;
|
|
198
|
+
if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
|
|
199
|
+
const state = getState();
|
|
200
|
+
const path = mutationParams.path;
|
|
201
|
+
const absolutePath = canonicalPath(cwd, path);
|
|
202
|
+
const mutate = () => withFileMutationQueue(absolutePath, () => runReplace(absolutePath, path, mutationParams, state.config.hashLen, signal));
|
|
203
|
+
if (!fusion) return mutate();
|
|
204
|
+
return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, signal, ctx, onUpdate });
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function runReplace(
|
|
210
|
+
absPath: string,
|
|
211
|
+
displayPath: string,
|
|
212
|
+
params: ReplaceParams,
|
|
213
|
+
hashLen: number,
|
|
214
|
+
signal: AbortSignal | undefined,
|
|
215
|
+
) {
|
|
216
|
+
const { find, replace } = params;
|
|
217
|
+
const isRegex = params.regex === true;
|
|
218
|
+
const maxMatches = params.maxMatches ?? DEFAULT_MAX_MATCHES;
|
|
219
|
+
|
|
220
|
+
if (find === "") throw new Error(`Replace ${displayPath}: \`find\` is empty.`);
|
|
221
|
+
|
|
222
|
+
let currentText: string;
|
|
223
|
+
try {
|
|
224
|
+
currentText = (await readFile(absPath)).toString("utf-8");
|
|
225
|
+
} catch (e) {
|
|
226
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
227
|
+
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
228
|
+
}
|
|
229
|
+
// honor cancel after read: if aborted, don't proceed to match/replace; the file stays untouched
|
|
230
|
+
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before apply.`);
|
|
231
|
+
|
|
232
|
+
let regex: RegExp;
|
|
233
|
+
try {
|
|
234
|
+
regex = buildRegex(find, isRegex, params.flags);
|
|
235
|
+
} catch (e) {
|
|
236
|
+
throw new Error(`Replace ${displayPath}: ${e instanceof Error ? e.message : String(e)}`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Count matches with an early guard so a runaway pattern (e.g. an empty-match
|
|
240
|
+
// regex) can't produce a catastrophic write. matchAll does not mutate the
|
|
241
|
+
// regex's lastIndex (it clones internally), so the subsequent `replace` is safe.
|
|
242
|
+
let count = 0;
|
|
243
|
+
for (const _ of currentText.matchAll(regex)) {
|
|
244
|
+
count++;
|
|
245
|
+
if (count > maxMatches) {
|
|
246
|
+
throw new Error(
|
|
247
|
+
`Replace ${displayPath}: ${count}+ matches exceed \`maxMatches\` (${maxMatches}). Raise \`maxMatches\` if intentional, or narrow \`find\`.`,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (count === 0) {
|
|
252
|
+
const shown = isRegex ? `/${find}/` : JSON.stringify(find);
|
|
253
|
+
throw new Error(`Replace ${displayPath}: no matches for ${shown}.`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Literal mode uses a function replacement so `$` in `replace` stays literal;
|
|
257
|
+
// regex mode passes the string so $1/$& etc. expand.
|
|
258
|
+
// Literal mode uses a function replacement so `$` in `replace` stays literal;
|
|
259
|
+
// regex mode passes the string so $1/$& etc. expand.
|
|
260
|
+
const newText = isRegex ? currentText.replace(regex, replace) : currentText.replace(regex, () => replace);
|
|
261
|
+
const changed = newText !== currentText;
|
|
262
|
+
|
|
263
|
+
// honor cancel before write: if aborted, don't touch the disk
|
|
264
|
+
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before write.`);
|
|
265
|
+
|
|
266
|
+
let publication: PublicationStatus = "NOT_PUBLISHED";
|
|
267
|
+
if (changed) {
|
|
268
|
+
try {
|
|
269
|
+
publication = (await commitFile(absPath, newText, { mode: "overwrite", signal })).publication;
|
|
270
|
+
} catch (e) {
|
|
271
|
+
if (e instanceof FileMutationError) throw e;
|
|
272
|
+
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
let details: EditToolDetails & { publication: PublicationStatus };
|
|
277
|
+
let anchors: string;
|
|
278
|
+
let note: string;
|
|
279
|
+
try {
|
|
280
|
+
// diff、anchors 和结果文本属于发布后的后处理;失败时保留 publication。
|
|
281
|
+
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
282
|
+
const newLf = newText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
283
|
+
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
284
|
+
details = {
|
|
285
|
+
diff,
|
|
286
|
+
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
287
|
+
firstChangedLine,
|
|
288
|
+
publication,
|
|
289
|
+
};
|
|
290
|
+
const oldLines = splitLines(currentText);
|
|
291
|
+
const newLines = splitLines(newText);
|
|
292
|
+
const span = changed ? changedSpan(oldLines, newLines) : null;
|
|
293
|
+
anchors = span ? formatSpanAnchors(newLines, span, hashLen) : "";
|
|
294
|
+
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
295
|
+
note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
296
|
+
} catch (error) {
|
|
297
|
+
throw new FileMutationError("post_process", publication, `file was published but replace result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
content: [{ type: "text" as const, text: `Replaced ${displayPath} (${note}).${anchors}` }],
|
|
301
|
+
details,
|
|
302
|
+
};
|
|
303
|
+
}
|