@criogaid/pi-hashline-edit 0.10.0 → 0.12.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 (103) hide show
  1. package/README.md +21 -7
  2. package/README.zh-CN.md +22 -8
  3. package/package.json +7 -6
  4. package/src/core/AGENTS.md +2 -2
  5. package/src/core/apply.test.ts +4 -4
  6. package/src/core/apply.ts +3 -3
  7. package/src/core/character-set.test.ts +2 -3
  8. package/src/core/character-set.ts +1 -1
  9. package/src/core/ranges.test.ts +2 -1
  10. package/src/core/ranges.ts +1 -1
  11. package/src/core/regex.ts +6 -2
  12. package/src/core/replace.test.ts +51 -0
  13. package/src/core/replace.ts +10 -4
  14. package/src/core/types.ts +1 -1
  15. package/src/index.ts +9 -9
  16. package/src/integration/config-registration.test.ts +8 -10
  17. package/src/integration/fusion-dispatch.test.ts +2 -2
  18. package/src/integration/grep-errors.test.ts +3 -3
  19. package/src/integration/grep-flags.test.ts +5 -5
  20. package/src/integration/grep-js-completeness.test.ts +12 -11
  21. package/src/integration/grep-line-candidates.test.ts +5 -3
  22. package/src/integration/grep-matrix.test.ts +5 -4
  23. package/src/integration/grep-order.test.ts +4 -4
  24. package/src/integration/grep-path-matrix.test.ts +5 -4
  25. package/src/integration/grep-prefilter-coverage.test.ts +17 -5
  26. package/src/integration/grep-process-limits.test.ts +2 -4
  27. package/src/integration/grep-regex.test.ts +10 -10
  28. package/src/integration/grep-rg.test.ts +93 -48
  29. package/src/integration/grep-scan-budget.test.ts +8 -8
  30. package/src/integration/grep-translation.test.ts +8 -7
  31. package/src/integration/large-text.test.ts +5 -5
  32. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  33. package/src/integration/mutation-file-types.testing.ts +4 -4
  34. package/src/integration/npm-package.test.ts +12 -10
  35. package/src/integration/npm-package.testing.ts +151 -4
  36. package/src/integration/publication-read-changes.test.ts +54 -54
  37. package/src/integration/read-changes.test.ts +4 -4
  38. package/src/integration/replace-worker-boundary.test.ts +1 -1
  39. package/src/integration/report-replay.test.ts +9 -6
  40. package/src/integration/utf8-errors.test.ts +4 -4
  41. package/src/pi/AGENTS.md +13 -12
  42. package/src/pi/action-fusion.test.ts +125 -105
  43. package/src/pi/action-fusion.testing.ts +38 -0
  44. package/src/pi/action-fusion.ts +9 -21
  45. package/src/pi/argument-diagnostics.ts +4 -3
  46. package/src/pi/argument-format.test.ts +19 -18
  47. package/src/pi/argument-validation.test.ts +281 -139
  48. package/src/pi/argument-validation.ts +21 -31
  49. package/src/pi/budgets.ts +1 -4
  50. package/src/pi/codemode.test.ts +7 -2
  51. package/src/pi/config.test.ts +2 -1
  52. package/src/pi/config.ts +8 -3
  53. package/src/pi/diagnostic-buffer.test.ts +23 -13
  54. package/src/pi/edit-tool.ts +48 -63
  55. package/src/pi/error-text.ts +7 -2
  56. package/src/pi/execute.test.ts +178 -157
  57. package/src/pi/failure-context.test.ts +5 -4
  58. package/src/pi/failure-context.ts +1 -1
  59. package/src/pi/failure-path.test.ts +37 -37
  60. package/src/pi/file-commit.test.ts +47 -19
  61. package/src/pi/file-commit.ts +36 -9
  62. package/src/pi/fusion-card.test.ts +22 -21
  63. package/src/pi/fusion-card.ts +9 -5
  64. package/src/pi/grep-candidates.test.ts +18 -20
  65. package/src/pi/grep-candidates.ts +13 -17
  66. package/src/pi/grep-matrix.test.ts +3 -3
  67. package/src/pi/grep-order.test.ts +12 -11
  68. package/src/pi/grep-output.ts +45 -17
  69. package/src/pi/grep-reread.ts +7 -2
  70. package/src/pi/grep-rg.testing.ts +70 -0
  71. package/src/pi/grep-scope.ts +10 -10
  72. package/src/pi/grep-search.ts +8 -11
  73. package/src/pi/grep-tool.ts +40 -53
  74. package/src/pi/grep.test.ts +141 -116
  75. package/src/pi/model-budgets.test.ts +2 -1
  76. package/src/pi/mutation-outcome.testing.ts +0 -1
  77. package/src/pi/mutation-result.test.ts +8 -8
  78. package/src/pi/mutation-result.ts +1 -1
  79. package/src/pi/mutation-runner.ts +10 -6
  80. package/src/pi/output-budgets.test.ts +53 -31
  81. package/src/pi/pi.test.ts +18 -13
  82. package/src/pi/read-tool.ts +13 -18
  83. package/src/pi/read.test.ts +67 -41
  84. package/src/pi/registration.test.ts +25 -19
  85. package/src/pi/render.test.ts +94 -32
  86. package/src/pi/render.ts +7 -4
  87. package/src/pi/replace-regex.ts +1 -1
  88. package/src/pi/replace-tool.ts +6 -16
  89. package/src/pi/replace.test.ts +45 -34
  90. package/src/pi/report-failure.testing.ts +9 -1
  91. package/src/pi/report-schema.ts +225 -86
  92. package/src/pi/report.test.ts +81 -87
  93. package/src/pi/report.ts +35 -22
  94. package/src/pi/result-safety.test.ts +121 -100
  95. package/src/pi/rg-process.test.ts +2 -2
  96. package/src/pi/rg-process.ts +9 -15
  97. package/src/pi/rg-regex.test.ts +13 -0
  98. package/src/pi/rg-regex.ts +2 -2
  99. package/src/pi/schema.ts +23 -0
  100. package/src/pi/tool-factories.testing.ts +59 -0
  101. package/src/pi/write-tool.ts +9 -15
  102. package/src/pi/write.test.ts +30 -31
  103. package/src/testing/run-tests.ts +1 -1
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
3
+ import { MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
4
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
4
5
  import { openTestSession } from "../testing/session.testing.ts";
5
6
  import { registerModelBudgets } from "./model-budgets.ts";
6
7
 
@@ -15,7 +15,6 @@ export function publishedMutation<T extends object | undefined>(
15
15
  publication: "PUBLISHED",
16
16
  publishedRevision: revision,
17
17
  observedRevision: revision,
18
- created: false,
19
18
  },
20
19
  };
21
20
  }
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
3
4
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
@@ -7,8 +8,8 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
9
  import { join } from "node:path";
9
10
  import { createActionFusionExecutor } from "./action-fusion.ts";
10
- import { makeWriteOverride } from "./write-tool.ts";
11
- import { makeReplaceTool } from "./replace-tool.ts";
11
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
12
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
12
13
  import type { SuccessReport } from "./report-schema.ts";
13
14
  import { callTool, createToolContext } from "./tool-call.testing.ts";
14
15
  import { reportOf } from "./report.ts";
@@ -30,20 +31,19 @@ test("command content includes images → report text joins only text blocks", a
30
31
  const dir = await mkdtemp(join(tmpdir(), "hashline-command-content-"));
31
32
  try {
32
33
  const path = join(dir, "file.txt");
33
- const fusion = createActionFusionExecutor(async () => ({
34
- status: "succeeded",
35
- result: {
34
+ const executeTool: SessionCommand = async () =>
35
+ commandCompletion({
36
36
  content: [
37
37
  { type: "text", text: "first" },
38
38
  { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
39
39
  { type: "text", text: "second" },
40
40
  ],
41
- },
42
- }));
41
+ });
42
+ const fusion = createActionFusionExecutor(() => {});
43
43
  const result = await callTool(
44
44
  makeWriteOverride(dir, fusion),
45
45
  { path, content: "saved\n", mode: "create", then_run: { command: "check" } },
46
- { ctx: await createToolContext(dir, t) },
46
+ { ctx: { ...(await createToolContext(dir, t)), executeTool } },
47
47
  );
48
48
  assert.equal(reportOf(result, "write")?.then_run?.output, "first\nsecond");
49
49
  assert.equal(await readFile(path, "utf8"), "saved\n");
@@ -48,7 +48,7 @@ export function generateMutationDetails(before: string, after: string) {
48
48
  /** The facts a mutation tool states about its own outcome. */
49
49
  export type MutationFacts<TTool extends MutationToolName = MutationToolName> = {
50
50
  [T in TTool]: SuccessFacts<T> & {
51
- [K in Exclude<"matches" | "created", keyof SuccessFacts<T>>]?: never;
51
+ [K in Exclude<"matches", keyof SuccessFacts<T>>]?: never;
52
52
  };
53
53
  }[TTool];
54
54
 
@@ -54,10 +54,16 @@ import {
54
54
  import { canonicalPath } from "./path.ts";
55
55
  import { throwIfCancelled } from "./error-text.ts";
56
56
  import { runTool } from "./report.ts";
57
- import type { OutputBudgetProvider, OutputBudgets } from "./budgets.ts";
57
+ import type { OutputBudgets } from "./budgets.ts";
58
+ import type { ToolEnvironment } from "./config.ts";
58
59
  import { STRICT_SAMPLING } from "./schema.ts";
59
60
 
60
- export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
61
+ type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
62
+
63
+ /** A mutation tool's registration environment; fusion is undefined when Action Fusion is off. */
64
+ export interface MutationToolEnvironment extends ToolEnvironment {
65
+ readonly fusion: ActionFusionExecutor | undefined;
66
+ }
61
67
 
62
68
  /** Result details shared by the read-modify-write tools. */
63
69
  type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
@@ -73,11 +79,9 @@ export interface MutationTarget {
73
79
  type MutationParams<P extends TProperties> = Static<TObject<P>> & { readonly path: string };
74
80
 
75
81
  /** What a mutation tool supplies to the shared definition; renderers stay with the tool. */
76
- interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName> {
82
+ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName>
83
+ extends MutationToolEnvironment {
77
84
  readonly tool: TTool;
78
- readonly cwd: string;
79
- readonly fusion: ActionFusionExecutor | undefined;
80
- readonly budgets: OutputBudgetProvider;
81
85
  /** Parameters without then_run, which Action Fusion adds. */
82
86
  readonly schema: TObject<P>;
83
87
  readonly description: string;
@@ -1,3 +1,5 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { runRegexReplacements } from "./replace-regex.ts";
1
3
  import assert from "node:assert/strict";
2
4
  import { test } from "node:test";
3
5
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -11,15 +13,13 @@ import { openTestSession } from "../testing/session.testing.ts";
11
13
  import { createAnchorFormatter } from "./anchor-format.ts";
12
14
  import { formatArgumentError } from "./argument-error.ts";
13
15
  import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
14
- import { DEFAULT_CONFIG } from "./config.ts";
15
- import { makeEditOverride } from "./edit-tool.ts";
16
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
17
+ import { makeEditOverride } from "./tool-factories.testing.ts";
16
18
  import { describeEditFailure } from "./failure-context.ts";
17
- import { assembleGrepOutput } from "./grep-output.ts";
19
+ import { grepOutput } from "./grep-output.ts";
18
20
  import { registerModelBudgets } from "./model-budgets.ts";
19
21
  import { describeMutationFailure } from "./mutation-result.ts";
20
- import { decodeReport, reportOf } from "./report.ts";
21
- import { decodeWorkerReply } from "./replace-regex.ts";
22
- import { restoreWorkerError } from "./regex-worker-contract.ts";
22
+ import { reportOf } from "./report.ts";
23
23
  import { workerFailure } from "./report-cause.ts";
24
24
  import { callTool } from "./tool-call.testing.ts";
25
25
 
@@ -52,14 +52,14 @@ test("byte budget sizes include fractional KiB → round to one decimal and pres
52
52
 
53
53
  test("model budget grows → argument issues remain complete JSON with counted omissions", () => {
54
54
  const issues = Array.from({ length: 100 }, (_, index) => ({
55
- field: `edits[${index}].body`,
55
+ field: `steps[${index}].lines`,
56
56
  reason: "中文🙂".repeat(100),
57
57
  fix: "Supply a line.",
58
58
  }));
59
59
  const reports = [outputBudgetsFor(1), small, large].map((budget) => {
60
60
  const text = formatArgumentError(issues, false, budget);
61
61
  assert.ok(Buffer.byteLength(text) <= budget.blockBytes);
62
- const report = decodeReport(text, "edit");
62
+ const report = reportOf({ content: [{ type: "text", text }] }, "edit");
63
63
  assert.ok(report);
64
64
  assert.equal((report.issues?.length ?? 0) + (report.omittedIssues ?? 0), issues.length);
65
65
  return report;
@@ -99,23 +99,32 @@ test("model row allowance grows → anchor failures return complete observations
99
99
  }
100
100
  });
101
101
 
102
- test("model budget grows → grep payload and diagnostics use that call's allowances", () => {
103
- const payload = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3)).join("\n");
102
+ test("model budget grows → grep payload and diagnostics use that call's allowances", async () => {
103
+ const paths = Array.from({ length: 3_000 }, () => "中文🙂".repeat(3));
104
+ const payload = paths.join("\n");
104
105
  const warning = "opening\n" + "中文🙂".repeat(800) + "\nfinal cause";
105
- const outputs = [small, large].map((budget) =>
106
- assembleGrepOutput({
107
- formatted: {
108
- blocks: [{ lines: payload.split("\n") }],
109
- matches: 3_000,
110
- files: 1,
111
- },
112
- warnings: [warning],
113
- searchFacts: {},
114
- outputMode: "content",
115
- matchLimitReached: false,
116
- effectiveLimit: 3_000,
117
- budget,
118
- }),
106
+ const outputs = await Promise.all(
107
+ [small, large].map((budget) =>
108
+ grepOutput({
109
+ cwd: process.cwd(),
110
+ anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen),
111
+ context: 0,
112
+ outputMode: "files",
113
+ search: {
114
+ files: paths.map((path) => ({
115
+ filePath: join(process.cwd(), path),
116
+ rows: [],
117
+ snapshot: { revision: "", validUtf8: true },
118
+ })),
119
+ scanLimitReached: false,
120
+ matchLimitReached: false,
121
+ },
122
+ warnings: [{ reason: warning }],
123
+ effectiveLimit: 3_000,
124
+ literalPipe: false,
125
+ budget,
126
+ }),
127
+ ),
119
128
  );
120
129
  assert.equal(outputs[0].facts.outputLimit, formatByteSize(small.grepBytes));
121
130
  assert.equal(outputs[1].payload, payload);
@@ -129,13 +138,26 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
129
138
  }
130
139
  });
131
140
 
132
- test("worker error reaches the tool → text is bounded once using the selected model", () => {
141
+ test("worker error reaches the tool → text is bounded once using the selected model", async (t) => {
133
142
  const text = "中文🙂".repeat(800);
134
- const reply = decodeWorkerReply(
135
- workerFailure(new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) })),
143
+ const reply = workerFailure(
144
+ new HashlineError("REGEX_WORKER_FAILED", text, { cause: new Error(text) }),
136
145
  );
137
- assert.ok(reply && "error" in reply);
138
- const error = restoreWorkerError(reply.error);
146
+ t.mock.method(Worker.prototype, "postMessage", function (this: Worker) {
147
+ queueMicrotask(() => this.emit("message", reply));
148
+ });
149
+ let error: unknown;
150
+ try {
151
+ await runRegexReplacements(
152
+ "source",
153
+ [{ find: "source", replace: "target", literal: false }],
154
+ 5_000,
155
+ undefined,
156
+ );
157
+ assert.fail("Worker failure must reject");
158
+ } catch (failure) {
159
+ error = failure;
160
+ }
139
161
  const reports = [small, large].map((budget) =>
140
162
  describeMutationFailure("replace", error, { budget }),
141
163
  );
@@ -171,7 +193,7 @@ test("model switches while a mutation waits → failure uses its starting budget
171
193
  try {
172
194
  const running = callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
173
195
  path,
174
- edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
196
+ steps: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
175
197
  });
176
198
  await session.setModel({ ...model, id: "large", contextWindow: 1_048_576 });
177
199
  assert.equal(budgets().readBytes, large.readBytes);
@@ -182,7 +204,7 @@ test("model switches while a mutation waits → failure uses its starting budget
182
204
  const next = reportOf(
183
205
  await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
184
206
  path,
185
- edits: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
207
+ steps: [{ action: "delete", anchor: `1#${wrongHash(text)}` }],
186
208
  }),
187
209
  "edit",
188
210
  );
package/src/pi/pi.test.ts CHANGED
@@ -4,16 +4,17 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
4
4
  import { tmpdir, homedir } from "node:os";
5
5
  import { computeLineHash } from "../core/hash.ts";
6
6
  import { createActionFusionExecutor } from "./action-fusion.ts";
7
- import { makeEditOverride } from "./edit-tool.ts";
8
- import { makeGrepOverride } from "./grep-tool.ts";
9
- import { makeReadOverride } from "./read-tool.ts";
10
- import { makeReplaceTool } from "./replace-tool.ts";
11
- import { makeWriteOverride } from "./write-tool.ts";
7
+ import { commandCompletion } from "./action-fusion.testing.ts";
8
+ import { makeEditOverride } from "./tool-factories.testing.ts";
9
+ import { makeGrepOverride } from "./tool-factories.testing.ts";
10
+ import { makeReadOverride } from "./tool-factories.testing.ts";
11
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
12
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
12
13
  import { canonicalPath } from "./path.ts";
13
14
  import { join, resolve } from "node:path";
14
15
  import { pathToFileURL } from "node:url";
15
16
  import { callTool } from "./tool-call.testing.ts";
16
- import { DEFAULT_CONFIG } from "./config.ts";
17
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
17
18
 
18
19
  test("canonicalPath resolves relative and absolute", () => {
19
20
  const cwd = resolve("/cwd");
@@ -95,8 +96,8 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
95
96
  makeEditOverride(dir, DEFAULT_CONFIG),
96
97
  {
97
98
  path: `@${url}`,
98
- edits: [
99
- { action: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, body: ["edited"] },
99
+ steps: [
100
+ { action: "replace", anchor: `1#${computeLineHash(1, "after", 4)}`, lines: ["edited"] },
100
101
  ],
101
102
  },
102
103
  { toolCallId: "edit", ctx },
@@ -110,10 +111,14 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
110
111
  assert.match(matches.content[0].text, /edited/);
111
112
  assert.equal(await readFile(file, "utf8"), "edited\n");
112
113
  let commands = 0;
113
- const fusion = createActionFusionExecutor(async () => {
114
- commands++;
115
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
116
- });
114
+ const fusion = createActionFusionExecutor(() => {});
115
+ const fusionContext = {
116
+ cwd: dir,
117
+ executeTool: async () => {
118
+ commands++;
119
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
120
+ },
121
+ };
117
122
  await callTool(
118
123
  makeWriteOverride(dir, fusion),
119
124
  {
@@ -122,7 +127,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
122
127
  mode: "overwrite",
123
128
  then_run: { command: "check" },
124
129
  },
125
- { toolCallId: "fused", ctx },
130
+ { toolCallId: "fused", ctx: fusionContext },
126
131
  );
127
132
  assert.equal(commands, 1);
128
133
  } finally {
@@ -31,8 +31,8 @@ import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
31
31
  import { errnoCode } from "../core/errors.ts";
32
32
  import { throwIfCancelled } from "./error-text.ts";
33
33
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
34
- import { defaultOutputBudgets, formatByteSize, type OutputBudgetProvider } from "./budgets.ts";
35
- import type { HashlineEditConfig } from "./config.ts";
34
+ import { formatByteSize } from "./budgets.ts";
35
+ import type { ToolEnvironment } from "./config.ts";
36
36
  import { createArgumentPreparer } from "./argument-validation.ts";
37
37
 
38
38
  const DEFAULT_OFFSET = 1;
@@ -44,7 +44,7 @@ type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDet
44
44
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
45
45
  * ` · no trailing newline`. A missing final newline is a byte-level fact the
46
46
  * numbered rows cannot show, so the header, which the model never copies into an
47
- * edit `body`, states it. READ_HEADER is the TUI's parser for this exact line.
47
+ * edit `lines`, states it. READ_HEADER is the TUI's parser for this exact line.
48
48
  */
49
49
  function formatReadHeader(
50
50
  path: string,
@@ -106,11 +106,11 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
106
106
  }
107
107
 
108
108
  /** Build the read override (a ToolDefinition fragment for registerTool). */
109
- export function makeReadOverride(
110
- cwd: string,
111
- config: HashlineEditConfig,
112
- budgets: OutputBudgetProvider = defaultOutputBudgets,
113
- ): ToolDefinition<
109
+ export function makeReadOverride({
110
+ cwd,
111
+ config,
112
+ budgets,
113
+ }: ToolEnvironment): ToolDefinition<
114
114
  ReturnType<typeof createReadToolDefinition>["parameters"],
115
115
  ReadDetails | undefined
116
116
  > {
@@ -155,7 +155,7 @@ export function makeReadOverride(
155
155
  const { isPartial, expanded } = options;
156
156
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
157
157
  if (context.isError) return renderToolError(result, "read", theme, expanded);
158
- const { content, report } = splitReport(result);
158
+ const { content, report } = splitReport(result, "read");
159
159
  if (result.details?.nativeRead)
160
160
  return builtin.renderResult!({ ...result, content }, options, theme, context);
161
161
  // Collapsed (not expanded): show nothing — the call line carries the
@@ -243,16 +243,11 @@ export function makeReadOverride(
243
243
  // Rows were returned and more remain. A caller's own limit is a chosen window: its header
244
244
  // and rows already show where it ends, so only a window the extension cut (default limit
245
245
  // or byte budget) gets a report.
246
- const pagination =
246
+ const nextOffset =
247
247
  (params.limit === undefined || truncated) &&
248
248
  rows.length > 0 &&
249
249
  start + rows.length <= stats.totalLines
250
- ? {
251
- start,
252
- end: start + (rows.length - 1),
253
- totalLines: stats.totalLines,
254
- nextOffset: start + rows.length,
255
- }
250
+ ? start + rows.length
256
251
  : undefined;
257
252
  const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
258
253
  const limitText = formatByteSize(maxBytes);
@@ -260,9 +255,9 @@ export function makeReadOverride(
260
255
  return reportResult(
261
256
  {
262
257
  ...report,
263
- pagination,
258
+ nextOffset,
264
259
  outputLimit: truncated && !firstLineExceedsLimit ? limitText : undefined,
265
- lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
260
+ lineTooLong: firstLineExceedsLimit ? limitText : undefined,
266
261
  },
267
262
  [{ type: "text" as const, text: header + rows.join("\n") }],
268
263
  );
@@ -4,14 +4,16 @@ import assert from "node:assert/strict";
4
4
  import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
+ import { pathToFileURL } from "node:url";
7
8
  import { initTheme } from "@earendil-works/pi-coding-agent";
8
9
  import type { Theme } from "@earendil-works/pi-coding-agent";
9
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
10
- import { makeReadOverride } from "./read-tool.ts";
11
+ import { makeReadOverride } from "./tool-factories.testing.ts";
11
12
  import { computeLineHash } from "../core/hash.ts";
12
13
  import { callTool } from "./tool-call.testing.ts";
13
- import { DEFAULT_CONFIG } from "./config.ts";
14
- import { DEFAULT_OUTPUT_BUDGETS, formatByteSize } from "./budgets.ts";
14
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
15
+ import { formatByteSize } from "./budgets.ts";
16
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
15
17
  import { reportOf } from "./report.ts";
16
18
  import { createAnchorFormatter } from "./anchor-format.ts";
17
19
 
@@ -87,6 +89,46 @@ test("read execute: Pi-supported images without NUL bypass text decoding", async
87
89
  }
88
90
  }));
89
91
 
92
+ test("file URLs escape special filenames → text and delegated reads open the exact file", async (t) => {
93
+ await withDir(async (dir) => {
94
+ const tool = makeReadOverride(dir, DEFAULT_CONFIG);
95
+ const cases = [
96
+ { name: "text.txt", bytes: Buffer.from("first\nsecond\n"), native: false },
97
+ { name: "binary.bin", bytes: Buffer.from("first\0\nsecond\n"), native: true },
98
+ {
99
+ name: "image.gif",
100
+ bytes: Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64"),
101
+ native: true,
102
+ },
103
+ ];
104
+ for (const { name, bytes, native } of cases) {
105
+ await t.test(name, async () => {
106
+ const path = join(dir, `space\u202Fname #% ${name}`);
107
+ await writeFile(path, bytes);
108
+ const result = await callTool(tool, { path: pathToFileURL(path).href });
109
+ assert.equal(result.isError, undefined);
110
+ assert.equal(result.details?.nativeRead === true, native);
111
+ if (name === "image.gif") {
112
+ assert.ok(result.content.some((block) => block.type === "image"));
113
+ } else {
114
+ const text = result.content.find((block) => block.type === "text")?.text;
115
+ assert.ok(text);
116
+ assert.ok(text.includes(native ? "first\0" : "│first"));
117
+ assert.ok(text.includes("second"));
118
+ if (!native) {
119
+ const header = text.split("\n")[0];
120
+ const returnedPath = header.slice(0, header.lastIndexOf(" · "));
121
+ const reread = await callTool(tool, { path: returnedPath });
122
+ assert.equal(reread.isError, undefined);
123
+ assert.deepEqual(reread.content, result.content);
124
+ }
125
+ }
126
+ assert.deepEqual(await readFile(path), bytes);
127
+ });
128
+ }
129
+ });
130
+ });
131
+
90
132
  test("read execute: a missing final newline is stated in the header", async () => {
91
133
  await withDir(async (dir) => {
92
134
  await writeFile(join(dir, "f.txt"), "line1\nline2");
@@ -146,10 +188,7 @@ test("read reports an oversized first row without suggesting an ineffective retr
146
188
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "long.txt" });
147
189
  assert.doesNotMatch(result.content[0].text, /^\d+#/m);
148
190
  assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
149
- assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
150
- line: 1,
151
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
152
- });
191
+ assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
153
192
  assert.match(reportOf(result, "read")?.next ?? "", /chunks.*bash.*replace/);
154
193
  }));
155
194
 
@@ -158,14 +197,14 @@ test("read preserves empty files and explicit limits above the native default",
158
197
  await writeFile(join(dir, "empty.txt"), "");
159
198
  const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
160
199
  assert.match(empty.content[0].text, /0 lines/);
161
- assert.equal(reportOf(empty, "read")?.pagination, undefined);
200
+ assert.equal(reportOf(empty, "read")?.nextOffset, undefined);
162
201
  await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
163
202
  const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
164
203
  path: "many.txt",
165
204
  limit: 2001,
166
205
  });
167
206
  assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
168
- assert.equal(reportOf(many, "read")?.pagination, undefined);
207
+ assert.equal(reportOf(many, "read")?.nextOffset, undefined);
169
208
  }));
170
209
 
171
210
  test("read window end chosen by caller or default → only the default offers optional continuation", async () =>
@@ -185,14 +224,14 @@ test("read window end chosen by caller or default → only the default offers op
185
224
  assert.match(result.content[0].text, new RegExp(`large\\.txt · ${totalLines} lines`));
186
225
  assert.match(result.content[0].text, new RegExp(`\\n${end}#[0-9A-Z]+│line${end}`));
187
226
  assert.doesNotMatch(result.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│`));
188
- const pagination = { start: 1, end, totalLines, nextOffset: end + 1 };
227
+ const nextOffset = end + 1;
189
228
  const report = reportOf(result, "read");
190
229
  assert.ok(report);
191
230
  if (limit === undefined) {
192
- assert.deepEqual(report.pagination, pagination);
193
- assert.match(report.next ?? "", /if you need more lines.*offset.*pagination\.nextOffset/i);
231
+ assert.equal(report.nextOffset, nextOffset);
232
+ assert.match(report.next ?? "", /if you need more lines.*offset.*nextOffset/i);
194
233
  } else {
195
- assert.equal(Object.hasOwn(report, "pagination"), false);
234
+ assert.equal(Object.hasOwn(report, "nextOffset"), false);
196
235
  assert.equal(Object.hasOwn(report, "next"), false);
197
236
  }
198
237
  }
@@ -209,26 +248,20 @@ test("read pagination supports offset windows and stops suggesting continuation
209
248
  );
210
249
  const read = makeReadOverride(dir, DEFAULT_CONFIG);
211
250
  const page = await call(read, { path: "pages.txt", offset: start });
212
- assert.match(reportOf(page, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
213
- assert.deepEqual(reportOf(page, "read")?.pagination, {
214
- start,
215
- end,
216
- totalLines,
217
- nextOffset: end + 1,
218
- });
219
- const pagination = reportOf(page, "read")?.pagination;
220
- assert.ok(pagination);
251
+ assert.match(reportOf(page, "read")?.next ?? "", /offset.*nextOffset/);
252
+ const nextOffset = reportOf(page, "read")?.nextOffset;
253
+ assert.ok(nextOffset);
221
254
  const next = await call(read, {
222
255
  path: "pages.txt",
223
- offset: pagination.nextOffset,
256
+ offset: nextOffset,
224
257
  });
225
258
  assert.match(next.content[0].text, new RegExp(`\\n${end + 1}#[0-9A-Z]+│line${end + 1}`));
226
259
  assert.match(next.content[0].text, new RegExp(`\\n${totalLines}#[0-9A-Z]+│line${totalLines}`));
227
- assert.equal(reportOf(next, "read")?.pagination, undefined);
260
+ assert.equal(reportOf(next, "read")?.nextOffset, undefined);
228
261
  assert.equal(reportOf(next, "read")?.next, undefined);
229
262
  for (const offset of [totalLines - DEFAULT_CONFIG.read.defaultLimit + 1, totalLines + 1]) {
230
263
  const result = await call(read, { path: "pages.txt", offset });
231
- assert.equal(reportOf(result, "read")?.pagination, undefined);
264
+ assert.equal(reportOf(result, "read")?.nextOffset, undefined);
232
265
  assert.equal(reportOf(result, "read")?.next, undefined);
233
266
  }
234
267
  }));
@@ -288,14 +321,9 @@ test("read byte truncation retains its budget and a continuation after complete
288
321
  path: "large.txt",
289
322
  limit: 2,
290
323
  });
291
- assert.deepEqual(reportOf(result, "read")?.pagination, {
292
- start: 1,
293
- end: 1,
294
- totalLines: 3,
295
- nextOffset: 2,
296
- });
324
+ assert.equal(reportOf(result, "read")?.nextOffset, 2);
297
325
  assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
298
- assert.match(reportOf(result, "read")?.next ?? "", /offset.*pagination\.nextOffset/);
326
+ assert.match(reportOf(result, "read")?.next ?? "", /offset.*nextOffset/);
299
327
  assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
300
328
  }));
301
329
 
@@ -310,10 +338,7 @@ test("read bounds oversized selected lines while reporting limits and preserving
310
338
  assert.equal(reportOf(result, "read")?.lineTooLong, undefined);
311
339
  assert.equal(reportOf(result, "read")?.outputLimit, formatByteSize(DEFAULT_READ_MAX_BYTES));
312
340
  const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
313
- assert.deepEqual(reportOf(oversized, "read")?.lineTooLong, {
314
- line: 2,
315
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
316
- });
341
+ assert.equal(reportOf(oversized, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
317
342
  assert.doesNotMatch(oversized.content[0].text, /^\d+#/m);
318
343
  const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
319
344
  assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
@@ -325,10 +350,7 @@ test("read budgets visible standalone CR characters using rendered UTF-8 bytes",
325
350
  const content = "\r".repeat(90_000);
326
351
  await writeFile(join(dir, "cr.txt"), content);
327
352
  const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
328
- assert.deepEqual(reportOf(result, "read")?.lineTooLong, {
329
- line: 1,
330
- limit: formatByteSize(DEFAULT_READ_MAX_BYTES),
331
- });
353
+ assert.equal(reportOf(result, "read")?.lineTooLong, formatByteSize(DEFAULT_READ_MAX_BYTES));
332
354
  assert.doesNotMatch(result.content[0].text, /^\d+#/m);
333
355
  }));
334
356
 
@@ -363,7 +385,7 @@ test("read accepts safe offsets and limits whose sum exceeds the safe integer ra
363
385
  offset,
364
386
  limit: Number.MAX_SAFE_INTEGER,
365
387
  });
366
- assert.equal(reportOf(result, "read")?.pagination, undefined);
388
+ assert.equal(reportOf(result, "read")?.nextOffset, undefined);
367
389
  assert.doesNotMatch(result.content[0].text, /to continue|│first/);
368
390
  if (offset <= 3) assert.match(result.content[0].text, /│third/);
369
391
  else assert.doesNotMatch(result.content[0].text, /│/);
@@ -401,6 +423,10 @@ test("Unicode line separators in a read path or middle row → renders every fol
401
423
  lastComponent: undefined,
402
424
  invalidate() {},
403
425
  executionStarted: true,
426
+ durationMs: undefined,
427
+ outputPad: 1,
428
+ keyText: () => "",
429
+ keyHint: (_key, description) => description,
404
430
  argsComplete: true,
405
431
  isPartial: false,
406
432
  expanded: true,