@criogaid/pi-hashline-edit 0.3.1 → 0.5.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.
Files changed (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
package/src/pi/pi.test.ts CHANGED
@@ -12,70 +12,118 @@ import { makeWriteOverride } from "./write-tool.ts";
12
12
  import { canonicalPath } from "./path.ts";
13
13
  import { join, resolve } from "node:path";
14
14
  import { pathToFileURL } from "node:url";
15
+ import { callTool } from "./tool-call.testing.ts";
16
+ import { DEFAULT_CONFIG } from "./config.ts";
15
17
 
16
18
  test("canonicalPath resolves relative and absolute", () => {
17
- const cwd = resolve("/cwd");
18
- const absolute = resolve("/abs/x.ts");
19
- assert.equal(canonicalPath(cwd, "foo.ts"), join(cwd, "foo.ts"));
20
- assert.equal(canonicalPath(cwd, "./foo.ts"), join(cwd, "foo.ts"));
21
- assert.equal(canonicalPath(cwd, absolute), absolute);
19
+ const cwd = resolve("/cwd");
20
+ const absolute = resolve("/abs/x.ts");
21
+ assert.equal(canonicalPath(cwd, "foo.ts"), join(cwd, "foo.ts"));
22
+ assert.equal(canonicalPath(cwd, "./foo.ts"), join(cwd, "foo.ts"));
23
+ assert.equal(canonicalPath(cwd, absolute), absolute);
22
24
  });
23
25
 
24
26
  test("canonicalPath expands ~ to home directory", () => {
25
- const home = homedir();
26
- assert.equal(canonicalPath("/cwd", "~"), home);
27
- assert.equal(canonicalPath("/cwd", "~/foo.ts"), join(home, "foo.ts"));
27
+ const home = homedir();
28
+ assert.equal(canonicalPath("/cwd", "~"), home);
29
+ assert.equal(canonicalPath("/cwd", "~/foo.ts"), join(home, "foo.ts"));
28
30
  });
29
31
 
30
32
  test("canonicalPath matches Pi's file URL, @ prefix, and Unicode space handling", () => {
31
- const cwd = resolve("/cwd");
32
- const target = join(cwd, "space name.txt");
33
- const fileUrl = pathToFileURL(target).href;
34
- for (const input of ["space name.txt", "space\u00a0name.txt", "space\u2009name.txt", "@space name.txt", fileUrl, `@${fileUrl}`]) {
35
- assert.equal(canonicalPath(cwd, input), target, input);
36
- }
37
- assert.throws(() => canonicalPath(cwd, "file:///bad%ZZ"));
33
+ const cwd = resolve("/cwd");
34
+ const target = join(cwd, "space name.txt");
35
+ const fileUrl = pathToFileURL(target).href;
36
+ for (const input of [
37
+ "space name.txt",
38
+ "space\u00a0name.txt",
39
+ "space\u2009name.txt",
40
+ "@space name.txt",
41
+ fileUrl,
42
+ `@${fileUrl}`,
43
+ ]) {
44
+ assert.equal(canonicalPath(cwd, input), target, input);
45
+ }
46
+ assert.throws(() => canonicalPath(cwd, "file:///bad%ZZ"));
38
47
  });
39
48
 
40
49
  test("canonicalPath follows Pi's Windows shell-path conventions", () => {
41
- const cwd = resolve("/cwd");
42
- if (process.platform === "win32") {
43
- const target = "C:\\src\\file.txt";
44
- for (const input of ["/c/src/file.txt", "/mnt/c/src/file.txt", "/cygdrive/c/src/file.txt", "@/c/src/file.txt"]) {
45
- assert.equal(canonicalPath(cwd, input), target, input);
46
- }
47
- assert.equal(canonicalPath(cwd, "~\\file.txt"), join(homedir(), "file.txt"));
48
- assert.equal(canonicalPath(cwd, "@~\\file.txt"), join(homedir(), "file.txt"));
49
- } else {
50
- assert.equal(canonicalPath(cwd, "/c/src/file.txt"), "/c/src/file.txt");
51
- }
50
+ const cwd = resolve("/cwd");
51
+ if (process.platform === "win32") {
52
+ const target = "C:\\src\\file.txt";
53
+ for (const input of [
54
+ "/c/src/file.txt",
55
+ "/mnt/c/src/file.txt",
56
+ "/cygdrive/c/src/file.txt",
57
+ "@/c/src/file.txt",
58
+ ]) {
59
+ assert.equal(canonicalPath(cwd, input), target, input);
60
+ }
61
+ assert.equal(canonicalPath(cwd, "~\\file.txt"), join(homedir(), "file.txt"));
62
+ assert.equal(canonicalPath(cwd, "@~\\file.txt"), join(homedir(), "file.txt"));
63
+ } else {
64
+ assert.equal(canonicalPath(cwd, "/c/src/file.txt"), "/c/src/file.txt");
65
+ }
52
66
  });
53
67
 
54
68
  test("file tools share Pi-style URL and @ path resolution", async () => {
55
- const dir = await mkdtemp(join(tmpdir(), "hashline-path-"));
56
- try {
57
- const file = join(dir, "target.txt");
58
- const url = pathToFileURL(file).href;
59
- const ctx = { cwd: dir };
60
- await makeWriteOverride(dir).execute("write", { path: `@${url}`, content: "before\n" }, undefined, undefined, ctx);
61
- const read = await makeReadOverride(dir).execute("read", { path: url }, undefined, undefined, ctx);
62
- if (read.content[0]?.type !== "text") throw new Error("Expected a text read result");
63
- assert.match(read.content[0].text, /before/);
64
- await makeReplaceTool(dir).execute("replace", { path: url, find: "before", replace: "after" }, undefined, undefined, ctx);
65
- await makeEditOverride(dir).execute("edit", { path: `@${url}`, edits: [
66
- { op: "replace", anchor: `1#${computeLineHash(1, "after")}`, body: ["edited"] },
67
- ] }, undefined, undefined, ctx);
68
- const matches = await makeGrepOverride(dir).execute("grep", { path: `@${url}`, pattern: "edited" }, undefined, undefined);
69
- assert.match(matches.content[0].text, /edited/);
70
- assert.equal(await readFile(file, "utf8"), "edited\n");
71
- let commands = 0;
72
- const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
73
- const fused = await makeWriteOverride(dir, fusion).execute("fused", {
74
- path: `@${url}`, content: "edited\n", then_run: { command: "check" },
75
- }, undefined, undefined, ctx);
76
- assert.equal(fused.details.actionFusion.command, "succeeded");
77
- assert.equal(commands, 1);
78
- } finally {
79
- await rm(dir, { recursive: true, force: true });
80
- }
69
+ const dir = await mkdtemp(join(tmpdir(), "hashline-path-"));
70
+ try {
71
+ const file = join(dir, "target.txt");
72
+ const url = pathToFileURL(file).href;
73
+ const ctx = { cwd: dir } as Parameters<ReturnType<typeof makeReadOverride>["execute"]>[4];
74
+ await callTool(
75
+ makeWriteOverride(dir),
76
+ { path: `@${url}`, content: "before\n" },
77
+ {
78
+ toolCallId: "write",
79
+ ctx,
80
+ },
81
+ );
82
+ const read = await callTool(
83
+ makeReadOverride(dir, DEFAULT_CONFIG),
84
+ { path: url },
85
+ { toolCallId: "read", ctx },
86
+ );
87
+ if (read.content[0]?.type !== "text") throw new Error("Expected a text read result");
88
+ assert.match(read.content[0].text, /before/);
89
+ await callTool(
90
+ makeReplaceTool(dir, DEFAULT_CONFIG),
91
+ { path: url, replacements: [{ find: "before", replace: "after" }] },
92
+ { toolCallId: "replace", ctx },
93
+ );
94
+ await callTool(
95
+ makeEditOverride(dir, DEFAULT_CONFIG),
96
+ {
97
+ path: `@${url}`,
98
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] }],
99
+ },
100
+ { toolCallId: "edit", ctx },
101
+ );
102
+ const matches = await callTool(
103
+ makeGrepOverride(dir, DEFAULT_CONFIG),
104
+ { path: `@${url}`, pattern: "edited" },
105
+ { toolCallId: "grep" },
106
+ );
107
+ assert.match(matches.content[0].text, /edited/);
108
+ assert.equal(await readFile(file, "utf8"), "edited\n");
109
+ let commands = 0;
110
+ const fusion = createActionFusionExecutor(async () => {
111
+ commands++;
112
+ return "checked";
113
+ });
114
+ const fused = await callTool(
115
+ makeWriteOverride(dir, fusion),
116
+ {
117
+ path: `@${url}`,
118
+ content: "edited\n",
119
+ then_run: { command: "check" },
120
+ },
121
+ { toolCallId: "fused", ctx },
122
+ );
123
+ assert.ok(fused.details.actionFusion);
124
+ assert.equal(fused.details.actionFusion.command, "succeeded");
125
+ assert.equal(commands, 1);
126
+ } finally {
127
+ await rm(dir, { recursive: true, force: true });
128
+ }
81
129
  });
@@ -10,19 +10,47 @@
10
10
  */
11
11
 
12
12
  import {
13
- createReadToolDefinition, detectSupportedImageMimeTypeFromFile,
14
- getLanguageFromPath, highlightCode, truncateHead,
13
+ createReadToolDefinition,
14
+ detectSupportedImageMimeTypeFromFile,
15
+ getLanguageFromPath,
16
+ highlightCode,
17
+ type ReadToolInput,
18
+ type ReadToolDetails,
19
+ type ExtensionContext,
20
+ type Theme,
21
+ type ToolDefinition,
15
22
  } from "@earendil-works/pi-coding-agent";
23
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
16
24
  import { Text } from "@earendil-works/pi-tui";
17
- import { readFile } from "node:fs/promises";
18
- import { decodeUtf8 } from "../core/index.ts";
19
- import { hasFinalNewline, splitLines } from "../core/lines.ts";
20
- import { createAnchorFormatter } from "./anchor-format.ts";
25
+ import { scanTextLines } from "./text-stream.ts";
26
+ import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
21
27
  import { canonicalPath } from "./path.ts";
22
- import { parseHashline, renderToolError } from "./render.ts";
28
+ import { renderToolError } from "./render.ts";
29
+ import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
30
+ import { throwIfCancelled } from "./error-text.ts";
31
+ import { formatKiB } from "./budgets.ts";
32
+ import type { HashlineEditConfig } from "./config.ts";
23
33
 
24
- const MAX_LINES = 2000;
25
- const MAX_BYTES = 256 * 1024;
34
+ const DEFAULT_OFFSET = 1;
35
+
36
+ type ReadDetails = ReadToolDetails & { nativeRead?: true };
37
+
38
+ /**
39
+ * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
40
+ * ` · no trailing newline`. A missing final newline is a byte-level fact the
41
+ * numbered rows cannot show, so the header, which the model never copies into an
42
+ * edit `body`, states it. READ_HEADER is the TUI's parser for this exact line.
43
+ */
44
+ function formatReadHeader(
45
+ path: string,
46
+ totalLines: number,
47
+ start: number,
48
+ finalNewline: boolean,
49
+ ): string {
50
+ const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
51
+ return `${path} · ${totalLines} lines${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
52
+ }
53
+ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/;
26
54
 
27
55
  /**
28
56
  * Render the expanded read body for the TUI: color the header, strip the
@@ -32,132 +60,215 @@ const MAX_BYTES = 256 * 1024;
32
60
  * line count diverges). Trailing notices (e.g. truncation) are shown in
33
61
  * `warning`.
34
62
  */
35
- function renderReadBody(raw: string, path: string, theme: any): string {
36
- const lines = raw.split("\n");
37
- if (lines.length === 0) return "";
38
- const out: string[] = [];
39
-
40
- // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
41
- // and/or " · no trailing newline".
42
- let bodyStart = 0;
43
- const h = lines[0].match(/^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/);
44
- if (h) {
45
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
46
- bodyStart = 1;
47
- }
48
-
49
- // Collect anchor rows (full content); the first non-anchor line begins the tail.
50
- const lineNos: string[] = [];
51
- const codeContents: string[] = [];
52
- let tailStart = lines.length;
53
- for (let i = bodyStart; i < lines.length; i++) {
54
- const row = parseHashline(lines[i]);
55
- if (!row) {
56
- tailStart = i;
57
- break;
58
- }
59
- lineNos.push(row.lineNo);
60
- codeContents.push(row.content);
61
- }
62
-
63
- // Syntax-highlight the whole block so multi-line constructs stay correct.
64
- const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
65
- const lang = getLanguageFromPath(path);
66
- let rendered: string[];
67
- if (lang) {
68
- const hl = highlightCode(detabbed.join("\n"), lang);
69
- // Guard against highlighters that reshape line count: fall back to plain.
70
- rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
71
- } else {
72
- rendered = detabbed.map((l) => theme.fg("toolOutput", l));
73
- }
74
- for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
75
- out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
76
- }
77
-
78
- for (let i = tailStart; i < lines.length; i++) {
79
- out.push(theme.fg("warning", lines[i]));
80
- }
81
- return out.join("\n");
63
+ function renderReadBody(raw: string, path: string, theme: Theme): string {
64
+ const lines = raw.split("\n");
65
+ if (lines.length === 0) return "";
66
+ const out: string[] = [];
67
+
68
+ // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
69
+ // and/or " · no trailing newline".
70
+ let bodyStart = 0;
71
+ const h = lines[0].match(READ_HEADER);
72
+ if (h) {
73
+ out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
74
+ bodyStart = 1;
75
+ }
76
+
77
+ // Collect anchor rows (full content); the first non-anchor line begins the tail.
78
+ const lineNos: string[] = [];
79
+ const codeContents: string[] = [];
80
+ let tailStart = lines.length;
81
+ for (let i = bodyStart; i < lines.length; i++) {
82
+ const row = parseHashline(lines[i]);
83
+ if (!row) {
84
+ tailStart = i;
85
+ break;
86
+ }
87
+ lineNos.push(row.lineNo);
88
+ codeContents.push(row.content);
89
+ }
90
+
91
+ // Syntax-highlight the whole block so multi-line constructs stay correct.
92
+ const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
93
+ const lang = getLanguageFromPath(path);
94
+ let rendered: string[];
95
+ if (lang) {
96
+ const hl = highlightCode(detabbed.join("\n"), lang);
97
+ // Guard against highlighters that reshape line count: fall back to plain.
98
+ rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
99
+ } else {
100
+ rendered = detabbed.map((l) => theme.fg("toolOutput", l));
101
+ }
102
+ for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
103
+ out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
104
+ }
105
+
106
+ for (let i = tailStart; i < lines.length; i++) {
107
+ out.push(theme.fg("warning", lines[i]));
108
+ }
109
+ return out.join("\n");
82
110
  }
83
111
 
84
112
  /** Build the read override (a ToolDefinition fragment for registerTool). */
85
- export function makeReadOverride(cwd: string) {
86
- const builtin = createReadToolDefinition(cwd);
87
-
88
- return {
89
- name: "read" as const,
90
- label: "read",
91
- description:
92
- "Read file contents. Text files display per-line content hashes (LINE#HASH│content) in the shared LF view for hashline-verified editing. CRLF line boundaries display as LF; source-code escape sequences remain literal text.",
93
- promptSnippet: "Read files with editable line anchors",
94
- promptGuidelines: [
95
- "Prefer read over shell output for files you intend to edit.",
96
- ],
97
- parameters: builtin.parameters,
98
- renderShell: "default" as const,
99
-
100
- renderCall: builtin.renderCall,
101
-
102
- renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
103
- if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
104
- const content = result.content?.[0];
105
- if (context?.isError) return renderToolError(result, theme);
106
- // Collapsed (not expanded): show nothing — the call line carries the
107
- // title, matching the built-in read's fold behavior.
108
- if (!expanded) return new Text("", 0, 0);
109
- const raw = content?.type === "text" ? content.text : "";
110
- return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
111
- },
112
-
113
- async execute(toolCallId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx?: any) {
114
- // User cancelled → delegate to the built-in (builtin handles abort itself)
115
- if (signal?.aborted) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
116
- const anchors = createAnchorFormatter();
117
-
118
- const absPath = canonicalPath(cwd, params.path as string);
119
- let buf: Buffer;
120
- try {
121
- if (await detectSupportedImageMimeTypeFromFile(absPath)) {
122
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
123
- }
124
- buf = await readFile(absPath);
125
- } catch {
126
- // read error → delegate to the built-in (it has polished error messages)
127
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
128
- }
129
-
130
- // NUL is a text-safety signal, not an exhaustive binary classifier.
131
- if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
132
-
133
- const text = decodeUtf8(buf);
134
- const allLines = splitLines(text);
135
- const totalLines = allLines.length;
136
-
137
- // offset/limit
138
- const offset = (params.offset as number | undefined) ?? 1;
139
- const limit = (params.limit as number | undefined) ?? MAX_LINES;
140
- const startIdx = Math.max(0, offset - 1);
141
- const endIdx = Math.min(totalLines, startIdx + limit);
142
-
143
- const rows = allLines.slice(startIdx, endIdx).map((line, index) => anchors.row(startIdx + index + 1, line));
144
- const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
145
-
146
- const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
147
- // A file whose last line carries no terminator is a byte-level fact that the
148
- // numbered rows cannot show; state it in the header, the one line the model
149
- // never copies into an edit `body`.
150
- const noFinalNewline = hasFinalNewline(text) ? "" : " · no trailing newline";
151
- const tail = truncation.firstLineExceedsLimit
152
- ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
153
- : truncation.truncated ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)` : "";
154
- const header = `${params.path} · ${totalLines} lines${shownFrom}${noFinalNewline}\n`;
155
- const body = truncation.content;
156
-
157
- return {
158
- content: [{ type: "text" as const, text: header + body + tail }],
159
- details: truncation.truncated ? { truncation } : undefined,
160
- };
161
- },
162
- };
113
+ export function makeReadOverride(
114
+ cwd: string,
115
+ config: HashlineEditConfig,
116
+ ): ToolDefinition<
117
+ ReturnType<typeof createReadToolDefinition>["parameters"],
118
+ ReadDetails | undefined
119
+ > {
120
+ const { hashLen } = config;
121
+ const { defaultLimit } = config.read;
122
+ const maxBytes = config.read.maxKiB * 1024;
123
+ const builtin = createReadToolDefinition(cwd);
124
+ const parameters = {
125
+ ...builtin.parameters,
126
+ additionalProperties: false,
127
+ properties: {
128
+ ...builtin.parameters.properties,
129
+ path: { ...builtin.parameters.properties.path, minLength: 1 },
130
+ offset: {
131
+ ...builtin.parameters.properties.offset,
132
+ ...POSITIVE_SAFE_INTEGER,
133
+ description: `1-based line to start from (default ${DEFAULT_OFFSET}).`,
134
+ },
135
+ limit: {
136
+ ...builtin.parameters.properties.limit,
137
+ ...POSITIVE_SAFE_INTEGER,
138
+ description: `Maximum lines to read (default ${defaultLimit}).`,
139
+ },
140
+ },
141
+ };
142
+
143
+ return {
144
+ name: "read" as const,
145
+ label: "read",
146
+ description:
147
+ "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
148
+ promptSnippet: "Read files with editable line anchors",
149
+ promptGuidelines: [
150
+ "Prefer read over shell output for files you intend to edit.",
151
+ "For large files, pass read offset and limit to read only the relevant section.",
152
+ ],
153
+ parameters: parameters as typeof builtin.parameters,
154
+ renderShell: "default" as const,
155
+
156
+ renderCall: builtin.renderCall,
157
+
158
+ renderResult(result, options, theme, context) {
159
+ const { isPartial, expanded } = options;
160
+ if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
161
+ const content = result.content?.[0];
162
+ if (context?.isError) return renderToolError(result, theme);
163
+ if (result.details?.nativeRead) return builtin.renderResult!(result, options, theme, context);
164
+ // Collapsed (not expanded): show nothing — the call line carries the
165
+ // title, matching the built-in read's fold behavior.
166
+ if (!expanded) return new Text("", 0, 0);
167
+ const raw = content?.type === "text" ? content.text : "";
168
+ return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
169
+ },
170
+
171
+ async execute(
172
+ toolCallId: string,
173
+ params: ReadToolInput,
174
+ signal: AbortSignal | undefined,
175
+ onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
176
+ ctx: ExtensionContext,
177
+ ) {
178
+ throwIfCancelled(signal);
179
+ const offset = params.offset ?? DEFAULT_OFFSET;
180
+ const limit = params.limit ?? defaultLimit;
181
+ const anchors = createAnchorFormatter(hashLen);
182
+ const readNative = async () => {
183
+ const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
184
+ return { ...result, details: { ...result.details, nativeRead: true as const } };
185
+ };
186
+
187
+ const absPath = canonicalPath(cwd, params.path as string);
188
+ try {
189
+ if (await detectSupportedImageMimeTypeFromFile(absPath)) {
190
+ return readNative();
191
+ }
192
+ } catch {
193
+ return readNative();
194
+ }
195
+
196
+ const start = offset;
197
+ const rows: string[] = [];
198
+ const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
199
+ let totalRows = 0;
200
+ let totalBytes = 0;
201
+ let outputBytes = 0;
202
+ let truncated = false;
203
+ let firstLineExceedsLimit = false;
204
+ let stats: Awaited<ReturnType<typeof scanTextLines>>;
205
+ try {
206
+ stats = await scanTextLines(
207
+ absPath,
208
+ (number) => number >= start && number - start < limit,
209
+ (line) => {
210
+ const rowBytes =
211
+ line.byteLength +
212
+ line.carriageReturns * crExpansion +
213
+ Buffer.byteLength(anchors.row(line.number, ""));
214
+ totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
215
+ if (truncated) return;
216
+ const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
217
+ if (nextBytes > maxBytes) {
218
+ truncated = true;
219
+ firstLineExceedsLimit = rows.length === 0;
220
+ return;
221
+ }
222
+ rows.push(anchors.row(line.number, line.text!));
223
+ outputBytes = nextBytes;
224
+ },
225
+ { signal, maxLineBytes: maxBytes },
226
+ );
227
+ } catch (error) {
228
+ // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
229
+ if (!signal?.aborted && error instanceof Error && "code" in error) {
230
+ return readNative();
231
+ }
232
+ throw error;
233
+ }
234
+ if (stats.hasNul) return readNative();
235
+ const pagination =
236
+ !truncated && rows.length > 0 && stats.totalLines - start >= limit
237
+ ? {
238
+ start,
239
+ end: start + (rows.length - 1),
240
+ totalLines: stats.totalLines,
241
+ nextOffset: start + rows.length,
242
+ }
243
+ : undefined;
244
+ const truncation = {
245
+ content: rows.join("\n"),
246
+ truncated,
247
+ truncatedBy: truncated ? ("bytes" as const) : null,
248
+ totalLines: totalRows,
249
+ totalBytes,
250
+ outputLines: rows.length,
251
+ outputBytes,
252
+ lastLinePartial: false,
253
+ firstLineExceedsLimit,
254
+ maxLines: totalRows,
255
+ maxBytes,
256
+ };
257
+
258
+ const tail = truncation.firstLineExceedsLimit
259
+ ? `\n… (line ${start} exceeds ${formatKiB(maxBytes)}; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
260
+ : truncation.truncated
261
+ ? `\n… (truncated at ${formatKiB(maxBytes)}; use offset/limit to read more)`
262
+ : pagination
263
+ ? `\n… (showing lines ${pagination.start}-${pagination.end} of ${pagination.totalLines}; use offset ${pagination.nextOffset} to continue)`
264
+ : "";
265
+ const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
266
+ const body = truncation.content;
267
+
268
+ return {
269
+ content: [{ type: "text" as const, text: header + body + tail }],
270
+ details: truncation.truncated ? { truncation } : pagination ? { pagination } : undefined,
271
+ };
272
+ },
273
+ };
163
274
  }