@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,166 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
7
+ import { applyEdits } from "../core/apply.ts";
8
+ import { HashlineError } from "../core/errors.ts";
9
+ import { computeLineHash } from "../core/hash.ts";
10
+ import { createAnchorFormatter } from "./anchor-format.ts";
11
+ import { formatArgumentError } from "./argument-error.ts";
12
+ import { outputBudgetsFor } from "./budgets.ts";
13
+ import { DEFAULT_CONFIG } from "./config.ts";
14
+ import { makeEditOverride } from "./edit-tool.ts";
15
+ import { describeEditFailure } from "./failure-context.ts";
16
+ import { assembleGrepOutput } from "./grep-output.ts";
17
+ import { createOutputBudgetProvider } from "./model-budgets.ts";
18
+ import { describeFailure, decodeReport, reportOf } from "./report.ts";
19
+ import { decodeWorkerReply } from "./replace-worker-contract.ts";
20
+ import { restoreWorkerError } from "./regex-worker-contract.ts";
21
+ import { workerFailure } from "./report-cause.ts";
22
+ import { callTool } from "./tool-call.testing.ts";
23
+
24
+ const small = outputBudgetsFor(65_536);
25
+ const large = outputBudgetsFor(1_048_576);
26
+
27
+ function wrongHash(text: string): string {
28
+ const hash = computeLineHash(1, text, DEFAULT_CONFIG.hashLen);
29
+ return (hash[0] === "0" ? "1" : "0") + hash.slice(1);
30
+ }
31
+
32
+ test("model budget grows → argument issues remain complete JSON with counted omissions", () => {
33
+ const issues = Array.from({ length: 100 }, (_, index) => ({
34
+ field: `edits[${index}].body`,
35
+ reason: "中文🙂".repeat(100),
36
+ fix: "Supply a line.",
37
+ }));
38
+ const reports = [outputBudgetsFor(1), small, large].map((budget) => {
39
+ const text = formatArgumentError("edit", issues, false, budget);
40
+ assert.ok(Buffer.byteLength(text) <= budget.blockBytes);
41
+ const report = decodeReport(text);
42
+ assert.ok(report);
43
+ assert.equal((report.issues?.length ?? 0) + (report.omittedIssues ?? 0), issues.length);
44
+ return report;
45
+ });
46
+ assert.ok((reports[2].issues?.length ?? 0) > (reports[1].issues?.length ?? 0));
47
+ });
48
+
49
+ test("model row allowance grows → anchor failures return complete observations instead of omitted rows", () => {
50
+ const text = "中文🙂".repeat(800);
51
+ const applied = applyEdits(
52
+ text,
53
+ [{ op: "delete", start: { line: 1, hash: wrongHash(text) } }],
54
+ DEFAULT_CONFIG.hashLen,
55
+ 0,
56
+ );
57
+ assert.equal(applied.ok, false);
58
+ if (applied.ok) return;
59
+ const snapshot = { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) };
60
+ const reports = [small, large].map((budget) => {
61
+ const report = describeFailure(
62
+ "edit",
63
+ describeEditFailure(applied.failure, snapshot, false, budget),
64
+ { mutation: true, budget },
65
+ );
66
+ assert.equal(report.error, "ANCHOR_MISMATCH");
67
+ return report;
68
+ });
69
+ assert.ok(reports[0].failures?.[0].observedOmitted);
70
+ assert.equal(reports[0].failures?.[0].observed, undefined);
71
+ assert.equal(reports[1].failures?.[0].observed, snapshot.anchors.row(1, text));
72
+ assert.equal(reports[1].failures?.[0].observedOmitted, undefined);
73
+ for (const report of reports) {
74
+ assert.equal(report.publication, "NOT_PUBLISHED");
75
+ assert.ok(report.next?.includes("intended target"));
76
+ }
77
+ });
78
+
79
+ test("model budget grows → grep payload and diagnostics use that call's allowances", () => {
80
+ const payload = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3)).join("\n");
81
+ const warning = "opening\n" + "中文🙂".repeat(800) + "\nfinal cause";
82
+ const outputs = [small, large].map((budget) =>
83
+ assembleGrepOutput({
84
+ formatted: {
85
+ blocks: [payload],
86
+ linesTruncated: false,
87
+ invalidUtf8: [],
88
+ matches: 3_000,
89
+ files: 1,
90
+ },
91
+ warnings: [warning],
92
+ outputMode: "content",
93
+ matchLimitReached: false,
94
+ effectiveLimit: 3_000,
95
+ budget,
96
+ }),
97
+ );
98
+ assert.ok(outputs[0].facts.outputLimit);
99
+ assert.equal(outputs[1].payload, payload);
100
+ assert.equal(outputs[1].facts.outputLimit, undefined);
101
+ assert.ok(Buffer.byteLength(outputs[0].facts.diagnostics!) <= small.fieldBytes);
102
+ assert.equal(outputs[1].facts.diagnostics, warning);
103
+ for (const output of outputs) {
104
+ assert.ok(output.facts.diagnostics?.startsWith("opening"));
105
+ assert.ok(output.facts.diagnostics?.endsWith("final cause"));
106
+ assert.ok(!output.facts.diagnostics?.includes("\uFFFD"));
107
+ }
108
+ });
109
+
110
+ test("worker error reaches the tool → text is bounded once using the selected model", () => {
111
+ const text = "中文🙂".repeat(800);
112
+ const reply = decodeWorkerReply(
113
+ workerFailure(new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) })),
114
+ );
115
+ assert.ok(reply && "error" in reply);
116
+ const error = restoreWorkerError(reply.error);
117
+ const reports = [small, large].map((budget) =>
118
+ describeFailure("replace", error, { mutation: true, budget }),
119
+ );
120
+ assert.ok(Buffer.byteLength(reports[0].message!) <= small.fieldBytes);
121
+ assert.ok(Buffer.byteLength(reports[0].cause!.message) <= small.fieldBytes);
122
+ assert.equal(reports[1].message, text);
123
+ assert.equal(reports[1].cause?.message, text);
124
+ });
125
+
126
+ test("model switches while a mutation waits → failure uses its starting budget snapshot", async (t) => {
127
+ const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
128
+ t.after(() => rm(dir, { recursive: true, force: true }));
129
+ const path = join(dir, "queued.txt");
130
+ const text = "中文🙂".repeat(800);
131
+ await writeFile(path, text);
132
+ let model = { provider: "local", id: "small", contextWindow: 65_536 };
133
+ const budgets = createOutputBudgetProvider(() => model);
134
+ const entered = Promise.withResolvers<void>();
135
+ const release = Promise.withResolvers<void>();
136
+ const holding = withFileMutationQueue(path, async () => {
137
+ entered.resolve();
138
+ await release.promise;
139
+ });
140
+ await entered.promise;
141
+ try {
142
+ const running = callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
143
+ path,
144
+ edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
145
+ });
146
+ model = { ...model, id: "large", contextWindow: 1_048_576 };
147
+ assert.equal(budgets().readBytes, large.readBytes);
148
+ release.resolve();
149
+ const report = reportOf(await running);
150
+ assert.ok(report?.failures?.[0].observedOmitted);
151
+ assert.equal(report.failures[0].observed, undefined);
152
+ const next = reportOf(
153
+ await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
154
+ path,
155
+ edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
156
+ }),
157
+ );
158
+ assert.equal(
159
+ next?.failures?.[0].observed,
160
+ createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(1, text),
161
+ );
162
+ } finally {
163
+ release.resolve();
164
+ await holding;
165
+ }
166
+ });
package/src/pi/path.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Path canonicalization and lossless re-serialization for cross-platform tool
3
+ * input.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
1
8
  import { homedir } from "node:os";
2
9
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
10
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -26,22 +26,25 @@ import { Type } from "typebox";
26
26
  import { scanTextLines } from "./text-stream.ts";
27
27
  import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
28
28
  import { canonicalPath } from "./path.ts";
29
- import { renderToolError } from "./render.ts";
30
- import {
31
- type ForgetReceiptDetails,
32
- readReceipt,
33
- withoutResultTag,
34
- withResultTag,
35
- } from "./forget-tool.ts";
29
+ import { renderToolError, reportLines, withoutReport } from "./render.ts";
30
+ import { type ForgetReceiptDetails, readReceipt, withResultTag } from "./forget-tool.ts";
36
31
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
32
+ import { errnoCode } from "../core/errors.ts";
37
33
  import { throwIfCancelled } from "./error-text.ts";
38
- import { formatKiB } from "./budgets.ts";
34
+ import { runTool, type Report, type ReportDetails } from "./report.ts";
35
+ import { defaultOutputBudgets, formatKiB, type OutputBudgetProvider } from "./budgets.ts";
39
36
  import type { HashlineEditConfig } from "./config.ts";
40
37
  import { createArgumentPreparer } from "./argument-validation.ts";
41
38
 
42
39
  const DEFAULT_OFFSET = 1;
43
40
 
44
- type ReadDetails = ReadToolDetails & { nativeRead?: true } & ForgetReceiptDetails;
41
+ type ReadDetails = ReadToolDetails & {
42
+ nativeRead?: true;
43
+ pagination?: NonNullable<Report["pagination"]>;
44
+ } & ForgetReceiptDetails &
45
+ Partial<ReportDetails>;
46
+ /** The read card shows the forget id only on the forget card. */
47
+ const READ_CARD_SHOWN = new Set(["resultId"]);
45
48
 
46
49
  /**
47
50
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
@@ -65,8 +68,7 @@ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no traili
65
68
  * `LINE#HASH│` prefix from every anchor line to ` N: content`, and
66
69
  * syntax-highlight the code block by the file's language (falls back to a
67
70
  * single `toolOutput` color when the language is unknown or the highlight
68
- * line count diverges). Trailing notices (e.g. truncation) are shown in
69
- * `warning`.
71
+ * line count diverges). Notices are report facts, rendered from the report.
70
72
  */
71
73
  function renderReadBody(raw: string, path: string, theme: Theme): string {
72
74
  const lines = raw.split("\n");
@@ -82,16 +84,12 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
82
84
  bodyStart = 1;
83
85
  }
84
86
 
85
- // Collect anchor rows (full content); the first non-anchor line begins the tail.
87
+ // Collect anchor rows (full content).
86
88
  const lineNos: string[] = [];
87
89
  const codeContents: string[] = [];
88
- let tailStart = lines.length;
89
90
  for (let i = bodyStart; i < lines.length; i++) {
90
91
  const row = parseHashline(lines[i]);
91
- if (!row) {
92
- tailStart = i;
93
- break;
94
- }
92
+ if (!row) break;
95
93
  lineNos.push(row.lineNo);
96
94
  codeContents.push(row.content);
97
95
  }
@@ -111,9 +109,6 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
111
109
  out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
112
110
  }
113
111
 
114
- for (let i = tailStart; i < lines.length; i++) {
115
- out.push(theme.fg("warning", lines[i]));
116
- }
117
112
  return out.join("\n");
118
113
  }
119
114
 
@@ -121,13 +116,13 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
121
116
  export function makeReadOverride(
122
117
  cwd: string,
123
118
  config: HashlineEditConfig,
119
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
124
120
  ): ToolDefinition<
125
121
  ReturnType<typeof createReadToolDefinition>["parameters"],
126
122
  ReadDetails | undefined
127
123
  > {
128
124
  const { hashLen } = config;
129
125
  const { defaultLimit } = config.read;
130
- const maxBytes = config.read.maxKiB * 1024;
131
126
  const builtin = createReadToolDefinition(cwd);
132
127
  // A TypeBox object, not a spread of Pi's plain JSON schema: argument diagnostics pick
133
128
  // single fields from it, which needs TypeBox's own schema kinds.
@@ -137,7 +132,7 @@ export function makeReadOverride(
137
132
  offset: Type.Optional(
138
133
  Type.Number({
139
134
  ...POSITIVE_SAFE_INTEGER,
140
- description: `1-based line to start from (default ${DEFAULT_OFFSET}).`,
135
+ description: `1-based line to start from (default ${DEFAULT_OFFSET}). For a large file, set offset and limit to read only the relevant section.`,
141
136
  }),
142
137
  ),
143
138
  limit: Type.Optional(
@@ -154,14 +149,10 @@ export function makeReadOverride(
154
149
  name: "read" as const,
155
150
  label: "read",
156
151
  description:
157
- "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
152
+ "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF. Use read, not shell output, for files you will edit.",
158
153
  promptSnippet: "Read files with editable line anchors",
159
- promptGuidelines: [
160
- "Prefer read over shell output for files you intend to edit.",
161
- "For large files, pass read offset and limit to read only the relevant section.",
162
- ],
163
154
  parameters: parameters as typeof builtin.parameters,
164
- prepareArguments: createArgumentPreparer("read", parameters),
155
+ prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
165
156
  renderShell: "default" as const,
166
157
 
167
158
  renderCall: builtin.renderCall,
@@ -169,15 +160,23 @@ export function makeReadOverride(
169
160
  renderResult(result, options, theme, context) {
170
161
  const { isPartial, expanded } = options;
171
162
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
172
- const content = result.content?.[0];
173
163
  if (context?.isError) return renderToolError(result, theme, expanded);
174
164
  if (result.details?.nativeRead)
175
- return builtin.renderResult!(withoutResultTag(result), options, theme, context);
165
+ return builtin.renderResult!(withoutReport(result), options, theme, context);
176
166
  // Collapsed (not expanded): show nothing — the call line carries the
177
167
  // title, matching the built-in read's fold behavior.
178
168
  if (!expanded) return new Text("", 0, 0);
169
+ const content = withoutReport(result).content[0];
179
170
  const raw = content?.type === "text" ? content.text : "";
180
- return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
171
+ const report = result.details?.report;
172
+ return new Text(
173
+ [
174
+ renderReadBody(raw, String(context?.args?.path ?? ""), theme),
175
+ ...(report ? reportLines(report, theme, READ_CARD_SHOWN) : []),
176
+ ].join("\n"),
177
+ 0,
178
+ 0,
179
+ );
181
180
  },
182
181
 
183
182
  async execute(
@@ -187,120 +186,135 @@ export function makeReadOverride(
187
186
  onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
188
187
  ctx: ExtensionToolContext,
189
188
  ) {
190
- throwIfCancelled(signal);
191
- const offset = params.offset ?? DEFAULT_OFFSET;
192
- const limit = params.limit ?? defaultLimit;
193
- const anchors = createAnchorFormatter(hashLen);
194
- const readNative = async () => {
195
- const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
189
+ const budget = budgets();
190
+ const maxBytes =
191
+ config.read.maxKiB === undefined ? budget.readBytes : config.read.maxKiB * 1024;
192
+ return runTool("read", { path: params.path, signal, budget }, async () => {
193
+ throwIfCancelled(signal);
194
+ const start = params.offset ?? DEFAULT_OFFSET;
195
+ const limit = params.limit ?? defaultLimit;
196
+ const anchors = createAnchorFormatter(hashLen);
197
+ const report = { tool: "read" as const, path: params.path };
198
+ const readNative = async () => {
199
+ const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
200
+ return withResultTag(
201
+ toolCallId,
202
+ {
203
+ report,
204
+ payload: result.content,
205
+ details: { ...result.details, nativeRead: true as const },
206
+ },
207
+ config.forget,
208
+ () =>
209
+ readReceipt(
210
+ params.path,
211
+ result.content.some((block) => block.type === "image")
212
+ ? { image: true }
213
+ : undefined,
214
+ ),
215
+ );
216
+ };
217
+
218
+ const absPath = canonicalPath(cwd, params.path);
219
+ try {
220
+ if (await detectSupportedImageMimeTypeFromFile(absPath)) {
221
+ return readNative();
222
+ }
223
+ } catch {
224
+ return readNative();
225
+ }
226
+
227
+ const rows: string[] = [];
228
+ const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
229
+ let totalRows = 0;
230
+ let totalBytes = 0;
231
+ let outputBytes = 0;
232
+ let truncated = false;
233
+ let firstLineExceedsLimit = false;
234
+ let stats: Awaited<ReturnType<typeof scanTextLines>>;
235
+ try {
236
+ stats = await scanTextLines(
237
+ absPath,
238
+ (number) => number >= start && number - start < limit,
239
+ (line) => {
240
+ const rowBytes =
241
+ line.byteLength +
242
+ line.carriageReturns * crExpansion +
243
+ Buffer.byteLength(anchors.row(line.number, ""));
244
+ totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
245
+ if (truncated) return;
246
+ const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
247
+ if (nextBytes > maxBytes) {
248
+ truncated = true;
249
+ firstLineExceedsLimit = rows.length === 0;
250
+ return;
251
+ }
252
+ rows.push(anchors.row(line.number, line.text!));
253
+ outputBytes = nextBytes;
254
+ },
255
+ { signal, maxLineBytes: maxBytes },
256
+ );
257
+ } catch (error) {
258
+ // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
259
+ if (!signal?.aborted && errnoCode(error) !== undefined) {
260
+ return readNative();
261
+ }
262
+ throw error;
263
+ }
264
+ if (stats.hasNul) return readNative();
265
+ // Rows were returned and more remain, whether the line limit or the byte budget stopped them.
266
+ const pagination =
267
+ rows.length > 0 && start + rows.length <= stats.totalLines
268
+ ? {
269
+ start,
270
+ end: start + (rows.length - 1),
271
+ totalLines: stats.totalLines,
272
+ nextOffset: start + rows.length,
273
+ }
274
+ : undefined;
275
+ // Pi's ReadToolDetails truncation shape; this read stops only at the byte limit.
276
+ const truncation = {
277
+ content: rows.join("\n"),
278
+ truncated,
279
+ truncatedBy: truncated ? ("bytes" as const) : null,
280
+ totalLines: totalRows,
281
+ totalBytes,
282
+ outputLines: rows.length,
283
+ outputBytes,
284
+ lastLinePartial: false,
285
+ firstLineExceedsLimit,
286
+ maxLines: totalRows,
287
+ maxBytes,
288
+ };
289
+
290
+ const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
291
+ const limitText = formatKiB(maxBytes);
292
+
196
293
  return withResultTag(
197
294
  toolCallId,
198
- { ...result, details: { ...result.details, nativeRead: true as const } },
295
+ {
296
+ report: {
297
+ ...report,
298
+ pagination,
299
+ truncatedAt: truncated && !firstLineExceedsLimit ? limitText : undefined,
300
+ lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
301
+ },
302
+ payload: [{ type: "text" as const, text: header + truncation.content }],
303
+ details: {
304
+ ...(truncated ? { truncation } : {}),
305
+ ...(pagination ? { pagination } : {}),
306
+ },
307
+ },
199
308
  config.forget,
200
309
  () =>
201
310
  readReceipt(
202
311
  params.path,
203
- result.content.some((block) => block.type === "image") ? { image: true } : undefined,
312
+ rows.length > 0
313
+ ? { start, end: start + rows.length - 1, truncated: truncation.truncated }
314
+ : undefined,
204
315
  ),
205
316
  );
206
- };
207
-
208
- const absPath = canonicalPath(cwd, params.path as string);
209
- try {
210
- if (await detectSupportedImageMimeTypeFromFile(absPath)) {
211
- return readNative();
212
- }
213
- } catch {
214
- return readNative();
215
- }
216
-
217
- const start = offset;
218
- const rows: string[] = [];
219
- const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
220
- let totalRows = 0;
221
- let totalBytes = 0;
222
- let outputBytes = 0;
223
- let truncated = false;
224
- let firstLineExceedsLimit = false;
225
- let stats: Awaited<ReturnType<typeof scanTextLines>>;
226
- try {
227
- stats = await scanTextLines(
228
- absPath,
229
- (number) => number >= start && number - start < limit,
230
- (line) => {
231
- const rowBytes =
232
- line.byteLength +
233
- line.carriageReturns * crExpansion +
234
- Buffer.byteLength(anchors.row(line.number, ""));
235
- totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
236
- if (truncated) return;
237
- const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
238
- if (nextBytes > maxBytes) {
239
- truncated = true;
240
- firstLineExceedsLimit = rows.length === 0;
241
- return;
242
- }
243
- rows.push(anchors.row(line.number, line.text!));
244
- outputBytes = nextBytes;
245
- },
246
- { signal, maxLineBytes: maxBytes },
247
- );
248
- } catch (error) {
249
- // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
250
- if (!signal?.aborted && error instanceof Error && "code" in error) {
251
- return readNative();
252
- }
253
- throw error;
254
- }
255
- if (stats.hasNul) return readNative();
256
- const pagination =
257
- !truncated && rows.length > 0 && stats.totalLines - start >= limit
258
- ? {
259
- start,
260
- end: start + (rows.length - 1),
261
- totalLines: stats.totalLines,
262
- nextOffset: start + rows.length,
263
- }
264
- : undefined;
265
- const truncation = {
266
- content: rows.join("\n"),
267
- truncated,
268
- truncatedBy: truncated ? ("bytes" as const) : null,
269
- totalLines: totalRows,
270
- totalBytes,
271
- outputLines: rows.length,
272
- outputBytes,
273
- lastLinePartial: false,
274
- firstLineExceedsLimit,
275
- maxLines: totalRows,
276
- maxBytes,
277
- };
278
-
279
- const tail = truncation.firstLineExceedsLimit
280
- ? `\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)`
281
- : truncation.truncated
282
- ? `\n… (truncated at ${formatKiB(maxBytes)}; use offset/limit to read more)`
283
- : pagination
284
- ? `\n… (showing lines ${pagination.start}-${pagination.end} of ${pagination.totalLines}; use offset ${pagination.nextOffset} to continue)`
285
- : "";
286
- const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
287
- const body = truncation.content;
288
-
289
- return withResultTag(
290
- toolCallId,
291
- {
292
- content: [{ type: "text" as const, text: header + body + tail }],
293
- details: truncation.truncated ? { truncation } : pagination ? { pagination } : undefined,
294
- },
295
- config.forget,
296
- () =>
297
- readReceipt(
298
- params.path,
299
- rows.length > 0
300
- ? { start, end: start + rows.length - 1, truncated: truncation.truncated }
301
- : undefined,
302
- ),
303
- );
317
+ });
304
318
  },
305
319
  };
306
320
  }