@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Override read: recognized images and NUL-containing files delegate to Pi's
3
- * built-in read; other valid UTF-8 text has a header and formatted rows.
4
- * `anchors: false` omits the row prefixes.
3
+ * built-in read; other valid UTF-8 text is a header and anchored rows, or with
4
+ * `anchors: false` the lines alone.
5
5
  *
6
6
  * Hashes are computed from the current content on the fly — nothing is stored.
7
7
  * The hash is `(line number, content)`, recomputed and checked at edit time, so
@@ -17,40 +17,57 @@ import {
17
17
  detectSupportedImageMimeTypeFromFile,
18
18
  getLanguageFromPath,
19
19
  highlightCode,
20
- type ReadToolInput,
21
20
  type ReadToolDetails,
22
- type ExtensionToolContext,
23
21
  type Theme,
24
22
  type ToolDefinition,
25
23
  } from "@earendil-works/pi-coding-agent";
26
- import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
24
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
25
+ import type { ImageContent } from "@earendil-works/pi-ai";
27
26
  import { Text } from "@earendil-works/pi-tui";
28
- import { Type } from "typebox";
27
+ import { IsString, IsUnion, Type, type TSchema } from "typebox";
29
28
  import { scanTextLines } from "./text-stream.ts";
30
29
  import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
31
- import { canonicalPath, serializePath } from "./path.ts";
30
+ import { serializePath } from "./path.ts";
32
31
  import { renderToolError, reportLines, splitReport } from "./render.ts";
33
32
  import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
34
- import { HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
35
- import { throwIfCancelled } from "./error-text.ts";
33
+ import { HashlineError } from "../core/errors.ts";
34
+ import { requireRegularFile } from "./file-read.ts";
35
+ import { callSignal, throwIfCancelled } from "./error-text.ts";
36
36
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
37
+ import { SCRIPT_OUTPUT_SCHEMAS } from "./report-schema.ts";
37
38
  import { formatByteSize } from "./budgets.ts";
38
39
  import type { ToolEnvironment } from "./config.ts";
39
- import { createArgumentPreparer } from "./argument-validation.ts";
40
+ import { createArgumentBoundary, noArgumentProduct } from "./argument-validation.ts";
40
41
 
41
42
  const DEFAULT_OFFSET = 1;
42
43
 
43
- /** Pi's read details for a delegated native read; the report states this read's own facts. */
44
- type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDetails>;
44
+ /**
45
+ * Pi's read details for a delegated native read; the report states this read's own facts.
46
+ * `header` is the header line of a read with `anchors: false`: the TUI shows it and the
47
+ * result text omits it.
48
+ */
49
+ type ReadDetails = (ReadToolDetails & { nativeRead?: true; header?: string }) &
50
+ Partial<ReportDetails>;
45
51
 
46
- /** Pi's read arguments plus this override's own. */
47
- type ReadInput = ReadToolInput & { anchors?: boolean };
52
+ // Pi's public factory erases the output type. Its toReadOutput emits only these variants.
53
+ type NativeReadOutput = string | (Pick<ImageContent, keyof ImageContent> & { note: string });
54
+
55
+ /** This read's output schema: its own text result, and each result of Pi's read other than plain text. */
56
+ function readOutputSchema(native: TSchema | undefined): TSchema {
57
+ const nativeVariants = native !== undefined && IsUnion(native) ? native.anyOf : [];
58
+ return Type.Union([
59
+ SCRIPT_OUTPUT_SCHEMAS.read,
60
+ ...nativeVariants.filter((variant) => !IsString(variant)),
61
+ ]);
62
+ }
48
63
 
49
64
  /**
50
- * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
65
+ * Header line: `<path> · <N> line(s)`, optionally ` (from line <offset>)` and
51
66
  * ` · no trailing newline`. A missing final newline is a byte-level fact the
52
67
  * numbered rows cannot show, so the header, which the model never copies into an
53
- * edit `lines`, states it. READ_HEADER is the TUI's parser for this exact line.
68
+ * edit `lines`, states it. An anchored read's text starts with this line; a read with
69
+ * `anchors: false` carries it in `details`. READ_HEADER is the TUI's parser for this
70
+ * exact line.
54
71
  */
55
72
  function formatReadHeader(
56
73
  path: string,
@@ -59,9 +76,10 @@ function formatReadHeader(
59
76
  finalNewline: boolean,
60
77
  ): string {
61
78
  const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
62
- return `${path} · ${totalLines} lines${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
79
+ const count = `${totalLines} line${totalLines === 1 ? "" : "s"}`;
80
+ return `${path} · ${count}${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
63
81
  }
64
- const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/s;
82
+ const READ_HEADER = /^(.+?) · ((\d+) lines?(?: \(from line (\d+)\))?(?: · no trailing newline)?)$/s;
65
83
 
66
84
  /**
67
85
  * Render the expanded read body for the TUI: color the header, strip the
@@ -72,70 +90,66 @@ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no traili
72
90
  * line count diverges). Notices are report facts, rendered from the report.
73
91
  */
74
92
  function renderReadBody(
75
- raw: string,
93
+ text: string,
76
94
  path: string,
77
- anchored: boolean,
78
- lineTooLong: boolean,
95
+ plainHeader: string | undefined,
96
+ lineTooLong: string | undefined,
79
97
  theme: Theme,
80
98
  ): string {
81
- const lines = raw.split("\n");
82
- const out: string[] = [];
99
+ const plain = plainHeader !== undefined;
100
+ // Interpolation also coerces text supplied by result hooks for unanchored reads.
101
+ const lines = (plain ? `${plainHeader}\n${text}` : text).split("\n");
102
+ const header = READ_HEADER.exec(lines[0]);
103
+ const out = header ? [theme.fg("success", header[1]) + theme.fg("dim", ` · ${header[2]}`)] : [];
83
104
 
84
- // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
85
- // and/or " · no trailing newline".
86
- let bodyStart = 0;
87
- const h = lines[0].match(READ_HEADER);
88
- if (h) {
89
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
90
- bodyStart = 1;
91
- }
105
+ const firstLine = Number(header?.[4] ?? DEFAULT_OFFSET);
106
+ // Unanchored text cannot distinguish zero rows from one empty row. Use the read's metadata.
107
+ let bodyStart = Number(header !== null);
108
+ if (plain && (lineTooLong !== undefined || firstLine > Number(header?.[3] ?? 0)))
109
+ bodyStart = lines.length;
92
110
 
93
- // Collect rows (full content).
111
+ const parseRow = plain
112
+ ? (content: string, index: number) => ({
113
+ lineNo: String(firstLine + index - bodyStart),
114
+ content,
115
+ })
116
+ : parseHashline;
94
117
  const lineNos: string[] = [];
95
- const codeContents: string[] = [];
96
- const firstLine = Number(/\(from line (\d+)\)/.exec(h?.[2] ?? "")?.[1] ?? DEFAULT_OFFSET);
97
- const totalLines = Number(/^(\d+) lines/.exec(h?.[2] ?? "")?.[1] ?? 0);
98
- // Unanchored rows carry no marker, so no rows and one empty row are the same text: a window
99
- // past the last line or a first line over the byte limit shows no row.
100
- if (!anchored && (lineTooLong || firstLine > totalLines)) bodyStart = lines.length;
118
+ const detabbed: string[] = [];
101
119
  for (let i = bodyStart; i < lines.length; i++) {
102
- const row = anchored
103
- ? parseHashline(lines[i])
104
- : { lineNo: String(firstLine + i - bodyStart), content: lines[i] };
120
+ const row = parseRow(lines[i], i);
105
121
  if (!row) break;
106
122
  lineNos.push(row.lineNo);
107
- codeContents.push(row.content);
123
+ detabbed.push(row.content.replace(/\t/g, " "));
108
124
  }
109
125
 
110
- // Syntax-highlight the whole block so multi-line constructs stay correct.
111
- const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
126
+ // Highlight the entire block for multi-line constructs; fall back if rows cannot be aligned.
112
127
  const lang = getLanguageFromPath(path);
113
- let rendered: string[];
114
- if (lang) {
115
- const hl = highlightCode(detabbed.join("\n"), lang);
116
- // Guard against highlighters that reshape line count: fall back to plain.
117
- rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
118
- } else {
119
- rendered = detabbed.map((l) => theme.fg("toolOutput", l));
120
- }
128
+ const highlighted = lang ? highlightCode(detabbed.join("\n"), lang) : undefined;
129
+ const rendered =
130
+ highlighted?.length === detabbed.length
131
+ ? highlighted
132
+ : detabbed.map((line) => theme.fg("toolOutput", line));
133
+ // Line numbers ascend, so the last one is the widest.
134
+ const lineNoWidth = lineNos.at(-1)?.length ?? 0;
121
135
  for (let i = 0; i < rendered.length; i++) {
122
- out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
136
+ out.push(theme.fg("dim", ` ${lineNos[i].padStart(lineNoWidth)}: `) + rendered[i]);
123
137
  }
124
138
 
125
139
  return out.join("\n");
126
140
  }
127
141
 
142
+ const BYTES_PER_KIB = 1024;
143
+
128
144
  /** Build the read override (a ToolDefinition fragment for registerTool). */
129
- export function makeReadOverride({
130
- cwd,
131
- config,
132
- budgets,
133
- }: ToolEnvironment): ToolDefinition<
134
- ReturnType<typeof createReadToolDefinition>["parameters"],
135
- ReadDetails | undefined
136
- > {
145
+ export function makeReadOverride(
146
+ { cwd, config, budgets }: ToolEnvironment,
147
+ readAutoResize: () => boolean,
148
+ ) {
137
149
  const { hashLen } = config;
138
- const { defaultLimit } = config.read;
150
+ const { defaultLimit, maxKiB } = config.read;
151
+ // An explicit read.maxKiB caps read output; otherwise the selected model's budget does.
152
+ const configuredBytes = maxKiB === undefined ? undefined : maxKiB * BYTES_PER_KIB;
139
153
  const builtin = createReadToolDefinition(cwd);
140
154
  // A TypeBox object, not a spread of Pi's plain JSON schema: argument diagnostics pick
141
155
  // single fields from it, which needs TypeBox's own schema kinds.
@@ -157,50 +171,56 @@ export function makeReadOverride({
157
171
  anchors: Type.Optional(
158
172
  Type.Boolean({
159
173
  description:
160
- "false omits LINE#HASH│ prefixes for files you will not edit, saving about a third of the tokens. The header stays and standalone CR displays as ␍ (default true).",
174
+ "false returns the lines as they are in the file, with no header or LINE#HASH│ prefixes, for text you will read or parse but not edit; about a third fewer tokens (default true).",
161
175
  }),
162
176
  ),
163
177
  },
164
178
  { additionalProperties: false },
165
179
  );
166
180
 
181
+ const boundary = createArgumentBoundary(parameters, cwd, budgets, () => noArgumentProduct);
167
182
  return {
168
183
  name: "read" as const,
169
184
  label: "read",
170
185
  description:
171
- "Read a file. Images return as attachments. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
172
- promptSnippet: "Read files with editable line anchors",
173
- promptGuidelines: [
174
- "In codemode, use tools.bash (cat, git show) for raw file text. Hashline-formatted read and grep content results include headers and show CRLF as LF. Files containing NUL go to native read without a Hashline header.",
175
- ],
176
- parameters: parameters as typeof builtin.parameters,
177
- // Codemode scripts receive structuredContent: Pi's image block for a delegated image, the
178
- // result text otherwise.
179
- outputSchema: builtin.outputSchema,
180
- prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
186
+ "Read a file's text; images return as attachments. Lines show as LINE#HASH│content anchors for edit after one header line; anchors: false returns the lines alone. CRLF line endings show as LF and standalone CR as ␍.",
187
+ promptSnippet: "Read file text, with line anchors for edit",
188
+ promptGuidelines: ["Files containing NUL go to native read without a Hashline header."],
189
+ parameters,
190
+ // Scripts receive the report's object for text, and Pi's image block for a delegated image.
191
+ outputSchema: readOutputSchema(builtin.outputSchema),
192
+ prepareArguments: boundary.prepareArguments,
181
193
  constrainedSampling: STRICT_SAMPLING,
182
194
  renderShell: "default" as const,
183
195
 
184
196
  renderCall: builtin.renderCall,
185
197
 
186
- renderResult(result, options, theme, context) {
198
+ renderResult(
199
+ result,
200
+ options,
201
+ theme,
202
+ context: Parameters<NonNullable<typeof builtin.renderResult>>[3],
203
+ ) {
187
204
  const { isPartial, expanded } = options;
188
205
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
189
- if (context.isError) return renderToolError(result, "read", theme, expanded);
206
+ if (context.isError) return renderToolError(result, "read", theme, expanded, context);
190
207
  const { content, report } = splitReport(result, "read");
191
208
  if (result.details?.nativeRead)
192
209
  return builtin.renderResult!({ ...result, content }, options, theme, context);
193
210
  // Collapsed (not expanded): show nothing — the call line carries the
194
211
  // title, matching the built-in read's fold behavior.
195
212
  if (!expanded) return new Text("", 0, 0);
196
- const raw = content[0]?.type === "text" ? content[0].text : "";
213
+ const payload = content[0];
214
+ const text = payload?.type === "text" ? payload.text : "";
215
+ // Only a read with `anchors: false` carries its header in details, which records the call
216
+ // that ran; arguments Pi cannot coerce do not describe it.
197
217
  return new Text(
198
218
  [
199
219
  renderReadBody(
200
- raw,
220
+ text,
201
221
  String(context.args?.path ?? ""),
202
- (context.args as ReadInput | undefined)?.anchors !== false,
203
- report !== undefined && "lineTooLong" in report && report.lineTooLong !== undefined,
222
+ result.details?.header,
223
+ report?.lineTooLong,
204
224
  theme,
205
225
  ),
206
226
  ...(report ? reportLines(report, theme) : []),
@@ -211,105 +231,120 @@ export function makeReadOverride({
211
231
  },
212
232
 
213
233
  async execute(
214
- toolCallId: string,
215
- { anchors: anchored, ...params }: ReadInput,
216
- signal: AbortSignal | undefined,
217
- onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
218
- ctx: ExtensionToolContext,
219
- ) {
234
+ toolCallId,
235
+ input,
236
+ piSignal,
237
+ onUpdate,
238
+ ctx,
239
+ ): Promise<AgentToolResult<ReadDetails | undefined>> {
240
+ const {
241
+ args,
242
+ paths: [{ absolutePath: absPath }],
243
+ } = boundary.afterHooks(input);
244
+ const { anchors: anchored, ...params } = args;
245
+ const signal = callSignal(piSignal);
220
246
  const budget = budgets();
221
- const maxBytes =
222
- config.read.maxKiB === undefined ? budget.readBytes : config.read.maxKiB * 1024;
247
+ const maxBytes = configuredBytes ?? budget.readBytes;
223
248
  return runTool("read", { path: params.path, signal, budget }, async () => {
224
249
  throwIfCancelled(signal);
225
250
  const start = params.offset ?? DEFAULT_OFFSET;
226
251
  const limit = params.limit ?? defaultLimit;
227
- const anchors = createAnchorFormatter(hashLen);
228
- const formatRow =
229
- anchored === false
230
- ? (_line: number, content: string) => displayCarriageReturns(content)
231
- : anchors.row;
252
+ const plain = anchored === false;
253
+ const formatRow = plain
254
+ ? (_line: number, content: string) => displayCarriageReturns(content)
255
+ : createAnchorFormatter(hashLen).row;
232
256
  const report = { tool: "read" as const, path: params.path };
233
- const absPath = canonicalPath(cwd, params.path);
234
257
  const readNative = async () => {
235
258
  // Bind I/O to our target: native resolution may normalize or try filename variants.
236
259
  const native = createReadToolDefinition(cwd, {
260
+ autoResizeImages: readAutoResize(),
237
261
  operations: {
238
262
  access: () => access(absPath, constants.R_OK),
239
263
  readFile: () => readFile(absPath),
264
+ // Recheck the delegated read's target, which can change after the dispatch probe.
240
265
  detectImageMimeType: () => detectSupportedImageMimeTypeFromFile(absPath),
241
266
  },
242
267
  });
243
268
  const result = await native.execute(
244
269
  toolCallId,
245
270
  { ...params, path: absPath },
246
- signal,
271
+ piSignal,
247
272
  onUpdate,
248
273
  ctx,
249
274
  );
250
- return {
251
- ...reportResult(report, result.content, {
252
- ...result.details,
253
- nativeRead: true as const,
254
- }),
255
- structuredContent: result.structuredContent,
256
- };
275
+ const delegated = reportResult(report, result.content, budget, {
276
+ details: { ...result.details, nativeRead: true as const },
277
+ });
278
+ // Pi gives scripts an image as its image block; delegated text is the report's `text`.
279
+ const output = result.structuredContent as NativeReadOutput;
280
+ return typeof output === "string"
281
+ ? delegated
282
+ : { ...delegated, structuredContent: output };
257
283
  };
258
284
 
259
- if ((await stat(absPath)).isDirectory()) {
260
- throw new HashlineError("NOT_REGULAR_FILE", PATH_ERROR_MESSAGES.NOT_REGULAR_FILE);
261
- }
285
+ // Opening a FIFO or device can block before any cancellation check runs.
286
+ requireRegularFile(await stat(absPath));
262
287
  if (await detectSupportedImageMimeTypeFromFile(absPath)) return readNative();
263
288
 
264
289
  const rows: string[] = [];
265
290
  const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
266
- let outputBytes = 0;
267
- let firstOmittedLine: number | undefined;
291
+ let remainingBytes = maxBytes + 1; // The first row has no preceding LF.
292
+ let budgetExceeded = false;
268
293
  const stats = await scanTextLines(
269
294
  absPath,
270
- (number) => number >= start && number - start < limit,
271
- (line) => {
272
- if (firstOmittedLine !== undefined) return;
295
+ (number) => !budgetExceeded && number >= start && number - start < limit,
296
+ ({ number, byteLength, carriageReturns, text }) => {
273
297
  const rowBytes =
274
- line.byteLength +
275
- line.carriageReturns * crExpansion +
276
- Buffer.byteLength(formatRow(line.number, ""));
277
- const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
278
- if (nextBytes > maxBytes) {
279
- firstOmittedLine = line.number;
298
+ byteLength + carriageReturns * crExpansion + Buffer.byteLength(formatRow(number, ""));
299
+ const cost = rowBytes + 1;
300
+ if (cost > remainingBytes) {
301
+ budgetExceeded = true;
280
302
  return;
281
303
  }
282
- rows.push(formatRow(line.number, line.text!));
283
- outputBytes = nextBytes;
304
+ rows.push(formatRow(number, text));
305
+ remainingBytes -= cost;
306
+ },
307
+ {
308
+ signal,
309
+ // A line longer than the whole budget ends the window.
310
+ bound: { maxBytes, onExceeded: () => (budgetExceeded = true) },
284
311
  },
285
- { signal, maxLineBytes: maxBytes },
286
312
  );
287
313
  if (stats.hasNul) return readNative();
288
- // A byte cutoff can shorten any window; a caller's line limit alone needs no continuation.
289
- const firstLineTooLong = firstOmittedLine === start;
290
- const nextAfterDefaultLimit =
291
- params.limit === undefined && rows.length > 0 && start + rows.length <= stats.totalLines
292
- ? start + rows.length
293
- : undefined;
294
- const nextOffset = firstLineTooLong
295
- ? undefined
296
- : (firstOmittedLine ?? nextAfterDefaultLimit);
297
- const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
298
- const limitText = formatByteSize(maxBytes);
314
+ // Rows without a header show no rows and one empty row as the same text, so a window that
315
+ // starts past the last line is a failure. An empty file read from its first line is empty text.
316
+ if (plain && start > Math.max(stats.totalLines, DEFAULT_OFFSET)) {
317
+ throw new HashlineError("OFFSET_PAST_END", "Offset is past the last line.", {
318
+ facts: { totalLines: stats.totalLines },
319
+ ...(stats.totalLines === 0 ? { next: "emptyFile" as const } : {}),
320
+ });
321
+ }
322
+ const nextOffset = start + rows.length;
323
+ const hasMoreLines = rows.length > 0 && nextOffset <= stats.totalLines;
324
+ const limitText = budgetExceeded ? formatByteSize(maxBytes) : undefined;
325
+ const limitFact =
326
+ rows.length === 0 ? { lineTooLong: limitText } : { outputLimit: limitText };
327
+ const header = formatReadHeader(
328
+ serializePath(cwd, absPath),
329
+ stats.totalLines,
330
+ start,
331
+ stats.finalNewline,
332
+ );
333
+ const body = rows.join("\n");
334
+ const text = plain ? body : `${header}\n${body}`;
299
335
 
300
- const result = reportResult(
336
+ return reportResult(
301
337
  {
302
338
  ...report,
303
- nextOffset,
304
- outputLimit:
305
- firstOmittedLine !== undefined && !firstLineTooLong ? limitText : undefined,
306
- lineTooLong: firstLineTooLong ? limitText : undefined,
339
+ nextOffset: hasMoreLines ? nextOffset : undefined,
340
+ callShowsNextOffset: !budgetExceeded && params.limit !== undefined ? true : undefined,
341
+ ...limitFact,
307
342
  },
308
- [{ type: "text" as const, text: header + rows.join("\n") }],
343
+ [{ type: "text", text }],
344
+ budget,
345
+ { details: plain ? { header } : undefined },
309
346
  );
310
- const text = result.content.flatMap((block) => (block.type === "text" ? [block.text] : []));
311
- return { ...result, structuredContent: text.join("\n") };
312
347
  });
313
348
  },
314
- };
349
+ } satisfies ToolDefinition<typeof parameters, ReadDetails | undefined>;
315
350
  }
@@ -12,7 +12,7 @@ export async function withRegexWorker<Input, Result, Output>(
12
12
  entry: URL,
13
13
  decode: (value: unknown) => RegexWorkerReply<Result> | undefined,
14
14
  timeoutMs: number,
15
- signal: AbortSignal | undefined,
15
+ signal: AbortSignal,
16
16
  execute: (run: (input: Input) => Promise<Result>) => Promise<Output>,
17
17
  resourceLimits?: ResourceLimits,
18
18
  ): Promise<Output> {
@@ -23,14 +23,20 @@ export async function withRegexWorker<Input, Result, Output>(
23
23
  );
24
24
  const worker = new Worker(bootstrap, { resourceLimits });
25
25
  let failure: Error | undefined;
26
- let pending: { resolve: (result: Result) => void; reject: (error: Error) => void } | undefined;
27
- let timer: ReturnType<typeof setTimeout> | undefined;
26
+ /** The request awaiting a reply, with its timeout. */
27
+ let pending:
28
+ | {
29
+ readonly resolve: (result: Result) => void;
30
+ readonly reject: (error: Error) => void;
31
+ readonly timer: ReturnType<typeof setTimeout>;
32
+ }
33
+ | undefined;
28
34
  let termination: ReturnType<Worker["terminate"]> | undefined;
29
35
  const terminate = () => (termination ??= worker.terminate());
30
36
  const clear = () => {
31
- clearTimeout(timer);
32
37
  const previous = pending;
33
38
  pending = undefined;
39
+ clearTimeout(previous?.timer);
34
40
  return previous;
35
41
  };
36
42
  const fail = (error: Error) => {
@@ -62,15 +68,14 @@ export async function withRegexWorker<Input, Result, Output>(
62
68
  }),
63
69
  ),
64
70
  );
65
- signal?.addEventListener("abort", abort, { once: true });
71
+ signal.addEventListener("abort", abort, { once: true });
66
72
  // Keep dispatch asynchronous so cancellation can be observed before posting a request.
67
73
  const run = (input: Input): Promise<Result> =>
68
74
  Promise.resolve().then(() => {
69
75
  throwIfCancelled(signal);
70
76
  if (failure) throw failure;
71
77
  return new Promise<Result>((resolve, reject) => {
72
- pending = { resolve, reject };
73
- timer = setTimeout(() => {
78
+ const timer = setTimeout(() => {
74
79
  fail(
75
80
  new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
76
81
  facts: { timeoutMs },
@@ -79,6 +84,7 @@ export async function withRegexWorker<Input, Result, Output>(
79
84
  // A grep caller may still be scanning for NUL after evaluation times out.
80
85
  void terminate();
81
86
  }, timeoutMs);
87
+ pending = { resolve, reject, timer };
82
88
  worker.postMessage(input);
83
89
  });
84
90
  });
@@ -86,7 +92,7 @@ export async function withRegexWorker<Input, Result, Output>(
86
92
  return await execute(run);
87
93
  } finally {
88
94
  clear();
89
- signal?.removeEventListener("abort", abort);
95
+ signal.removeEventListener("abort", abort);
90
96
  await terminate();
91
97
  }
92
98
  }