@criogaid/pi-hashline-edit 0.12.0 → 0.13.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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -8,7 +8,7 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
9
  import { join } from "node:path";
10
10
  import { createActionFusionExecutor } from "./action-fusion.ts";
11
- import { makeWriteOverride } from "./tool-factories.testing.ts";
11
+ import { makeWriteOverride, DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
12
12
  import { makeReplaceTool } from "./tool-factories.testing.ts";
13
13
  import type { SuccessReport } from "./report-schema.ts";
14
14
  import { callTool, createToolContext } from "./tool-call.testing.ts";
@@ -52,6 +52,30 @@ test("command content includes images → report text joins only text blocks", a
52
52
  }
53
53
  });
54
54
 
55
+ test("oversized command diagnostic → bounds model output and retains the original command card", async (t) => {
56
+ const dir = await mkdtemp(join(tmpdir(), "hashline-command-budget-"));
57
+ t.after(() => rm(dir, { recursive: true, force: true }));
58
+ const budget = DEFAULT_OUTPUT_BUDGETS;
59
+ const output = `opening\n${"x".repeat(budget.fieldBytes * 2)}\nlast line`;
60
+ const executeTool: SessionCommand = async () =>
61
+ commandCompletion({ content: [{ type: "text", text: output }] }, true);
62
+ let displayedOutput: unknown;
63
+ const fusion = createActionFusionExecutor((progress) => {
64
+ if (progress.command === "failed") displayedOutput = progress.result?.content[0];
65
+ });
66
+ const result = await callTool(
67
+ makeWriteOverride(dir, fusion),
68
+ { path: "file.txt", content: "saved", mode: "create", then_run: { command: "check" } },
69
+ { ctx: { ...(await createToolContext(dir, t)), executeTool } },
70
+ );
71
+ const report = reportOf({ content: result.content }, "write");
72
+ assert.equal(report?.then_run?.status, "failed");
73
+ const shown = report.then_run.output;
74
+ assert.ok(shown && Buffer.byteLength(shown) <= budget.fieldBytes);
75
+ assert.ok(shown.startsWith("opening\n") && shown.endsWith("\nlast line"));
76
+ assert.deepEqual(displayedOutput, { type: "text", text: output });
77
+ });
78
+
55
79
  for (const [name, before, after] of [
56
80
  ["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
57
81
  ["CRLF", "guard\r\nold\r\ntail\r\n", "guard\r\nnew\r\ntail\r\n"],
@@ -26,7 +26,7 @@ import {
26
26
  type FailureContext,
27
27
  type ReportDetails,
28
28
  } from "./report.ts";
29
- import { causeOf } from "./report-cause.ts";
29
+ import { boundedText, causeOf } from "./report-cause.ts";
30
30
  import type { OutputBudgets } from "./budgets.ts";
31
31
 
32
32
  /** Final success carries tool details; final failure carries only its report; neither carries progress. */
@@ -136,7 +136,12 @@ export function finalizeMutation<TDetails extends object, TTool extends Mutation
136
136
  ...facts,
137
137
  freshness: fresh ? undefined : observation.freshness,
138
138
  freshnessError: causeOf(observation.error, budget.fieldBytes),
139
- then_run: command ? { status: command.status, ...(output ? { output } : {}) } : undefined,
139
+ then_run: command
140
+ ? {
141
+ status: command.status,
142
+ ...(output ? { output: boundedText(output, budget.fieldBytes) } : {}),
143
+ }
144
+ : undefined,
140
145
  progressError: causeOf(command?.progressError, budget.fieldBytes),
141
146
  } as SuccessReport;
142
147
  return reportResult(report, [], details);
@@ -2,7 +2,7 @@
2
2
  * Shared execution pipeline for the file mutation tools (edit, replace, write).
3
3
  *
4
4
  * `mutationToolBase` assembles the definition every mutation tool shares:
5
- * then_run's field, description, and guideline when Action Fusion is on,
5
+ * then_run's field and guideline when Action Fusion is on,
6
6
  * argument preparation, strict sampling, and execution. Each tool supplies its schema, text,
7
7
  * semantic checks, and `run`, and adds its own renderers.
8
8
  *
@@ -28,7 +28,6 @@ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/p
28
28
  import type { Static, TObject, TProperties } from "typebox";
29
29
  import {
30
30
  ACTION_FUSION_GUIDELINES,
31
- withThenRunDescription,
32
31
  withThenRunSchema,
33
32
  type createActionFusionExecutor,
34
33
  type FusedMutation,
@@ -98,7 +97,7 @@ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends Mutati
98
97
 
99
98
  /**
100
99
  * The definition every mutation tool shares. Action Fusion adds then_run to the
101
- * schema, description, and guidelines only when it is on; arguments are prepared
100
+ * schema and guidelines only when it is on; arguments are prepared
102
101
  * against the parameters Pi registers; `execute` queues and publishes one
103
102
  * validated call, then runs its then_run command when fused.
104
103
  */
@@ -113,7 +112,7 @@ export function mutationToolBase<
113
112
  return {
114
113
  name: tool,
115
114
  label: tool,
116
- description: withThenRunDescription(spec.description, actionFusion),
115
+ description: spec.description,
117
116
  promptSnippet: spec.promptSnippet,
118
117
  promptGuidelines: [
119
118
  ...(spec.promptGuidelines ?? []),
@@ -33,7 +33,8 @@ function wrongHash(text: string): string {
33
33
 
34
34
  test("byte budget sizes include fractional KiB → round to one decimal and preserve whole units", () => {
35
35
  for (const [bytes, expected] of [
36
- [outputBudgetsFor(200_000).readBytes, "195.3 KiB"],
36
+ [outputBudgetsFor(200_000).readBytes, "48.8 KiB"],
37
+ [outputBudgetsFor(200_000).grepBytes, "24.4 KiB"],
37
38
  [outputBudgetsFor(200_000).blockBytes, "48.8 KiB"],
38
39
  [outputBudgetsFor(200_000).fieldBytes, "12.2 KiB"],
39
40
  [16 * 1024, "16 KiB"],
@@ -107,6 +108,7 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
107
108
  [small, large].map((budget) =>
108
109
  grepOutput({
109
110
  cwd: process.cwd(),
111
+ missing: [],
110
112
  anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen),
111
113
  context: 0,
112
114
  outputMode: "files",
package/src/pi/path.ts CHANGED
@@ -10,7 +10,9 @@ import { isAbsolute, join, relative, resolve, sep } from "node:path";
10
10
  import { fileURLToPath, pathToFileURL } from "node:url";
11
11
 
12
12
  const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
13
- const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
13
+ const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/is;
14
+ const LOCALHOST_UNC_PATH = /^\\\\(localhost)\\/i;
15
+ const LOCALHOST_UNC_URL = /^file:\/\/\/\/localhost\//i;
14
16
 
15
17
  /** Resolve model-supplied paths with the same input conventions as Pi's built-in file tools. */
16
18
  export function canonicalPath(cwd: string, path: string): string {
@@ -32,8 +34,18 @@ export function canonicalPath(cwd: string, path: string): string {
32
34
  ) {
33
35
  normalized = join(homedir(), normalized.slice(2));
34
36
  }
35
- if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
36
- return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
37
+ if (normalized.startsWith("file://")) {
38
+ // Parse the four-slash UNC form with a dotted host so URL parsing retains the
39
+ // authority and fileURLToPath applies its Windows separator checks.
40
+ const localhost = process.platform === "win32" && LOCALHOST_UNC_URL.test(normalized);
41
+ normalized = localhost
42
+ ? fileURLToPath(normalized.replace(LOCALHOST_UNC_URL, "file://localhost./")).replace(
43
+ /^\\\\localhost\.\\/,
44
+ "\\\\localhost\\",
45
+ )
46
+ : fileURLToPath(normalized);
47
+ }
48
+ return resolve(cwd, normalized);
37
49
  }
38
50
 
39
51
  /** Return a readable path that resolves back to the same file through the tools' input syntax. */
@@ -49,5 +61,7 @@ export function serializePath(cwd: string, path: string): string {
49
61
  if (canonicalPath(cwd, candidate) === absolute) return candidate;
50
62
  if (local && canonicalPath(cwd, `./${candidate}`) === absolute) return `./${candidate}`;
51
63
  }
52
- return pathToFileURL(absolute).href;
64
+ const url = pathToFileURL(absolute);
65
+ const localhost = LOCALHOST_UNC_PATH.exec(absolute)?.[1];
66
+ return localhost === undefined ? url.href : `file:////${localhost}${url.pathname}`;
53
67
  }
package/src/pi/pi.test.ts CHANGED
@@ -66,6 +66,28 @@ test("canonicalPath follows Pi's Windows shell-path conventions", () => {
66
66
  }
67
67
  });
68
68
 
69
+ test("Windows drive-rooted input → uses the workspace volume", {
70
+ skip: process.platform !== "win32",
71
+ }, () => {
72
+ for (const drive of ["C:", "D:"]) {
73
+ for (const input of ["/docs/file.txt", "\\docs\\file.txt"]) {
74
+ assert.equal(canonicalPath(`${drive}/workspace`, input), `${drive}\\docs\\file.txt`);
75
+ }
76
+ }
77
+ });
78
+
79
+ test("Windows shell drive paths with Unicode line separators → preserve the filename", {
80
+ skip: process.platform !== "win32",
81
+ }, () => {
82
+ const cwd = resolve("/cwd");
83
+ for (const prefix of ["/c", "/mnt/c", "/cygdrive/c"]) {
84
+ for (const separator of ["\u2028", "\u2029"]) {
85
+ const name = `before${separator}after.txt`;
86
+ assert.equal(canonicalPath(cwd, `${prefix}/src/${name}`), join("C:/src", name));
87
+ }
88
+ }
89
+ });
90
+
69
91
  test("file tools share Pi-style URL and @ path resolution", async () => {
70
92
  const dir = await mkdtemp(join(tmpdir(), "hashline-path-"));
71
93
  try {
@@ -0,0 +1,119 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { test } from "node:test";
7
+ import * as pi from "@earendil-works/pi-coding-agent";
8
+ import { callTool } from "./tool-call.testing.ts";
9
+ import { loadConfig } from "./config.ts";
10
+ import { outputBudgetsFor } from "./budgets.ts";
11
+ import { reportOf } from "./report.ts";
12
+
13
+ test("read delegation → only images and NUL use native read on the canonical target", async (t) => {
14
+ const dir = await mkdtemp(join(tmpdir(), "hashline-read-delegation-"));
15
+ t.after(() => rm(dir, { recursive: true, force: true }));
16
+ type Native = ReturnType<typeof pi.createReadToolDefinition>;
17
+ let beforeNative: (() => Promise<void>) | undefined;
18
+ const execute = t.mock.fn(async (native: Native, ...args: Parameters<Native["execute"]>) => {
19
+ await beforeNative?.();
20
+ return native.execute(...args);
21
+ });
22
+ t.mock.module("@earendil-works/pi-coding-agent", {
23
+ namedExports: {
24
+ ...pi,
25
+ createReadToolDefinition: (...args: Parameters<typeof pi.createReadToolDefinition>) => {
26
+ const native = pi.createReadToolDefinition(...args);
27
+ return {
28
+ ...native,
29
+ execute: (...args: Parameters<Native["execute"]>) => execute(native, ...args),
30
+ };
31
+ },
32
+ },
33
+ });
34
+ const { makeReadOverride } = await import("./read-tool.ts");
35
+ const tool = makeReadOverride({
36
+ cwd: dir,
37
+ config: loadConfig(dir),
38
+ budgets: () => outputBudgetsFor(undefined),
39
+ });
40
+ const image = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
41
+ await writeFile(join(dir, "image.gif"), image);
42
+ await writeFile(join(dir, "nul.txt"), "first\0\nsecond\n");
43
+ await writeFile(join(dir, "invalid.txt"), Buffer.from([0xff]));
44
+ await mkdir(join(dir, "directory"));
45
+ for (const [path, error, native] of [
46
+ ["image.gif", undefined, true],
47
+ ["nul.txt", undefined, true],
48
+ ["missing.txt", "PATH_NOT_FOUND", false],
49
+ ["directory", "NOT_REGULAR_FILE", false],
50
+ ["nul.txt/child", process.platform === "win32" ? "PATH_NOT_FOUND" : "FILESYSTEM_ERROR", false],
51
+ ["invalid.txt", "UNSUPPORTED_ENCODING", false],
52
+ ] as const) {
53
+ await t.test(path, async () => {
54
+ const before = execute.mock.callCount();
55
+ const params = { path, offset: 1, limit: 1 };
56
+ const result = await callTool(tool, { ...params, anchors: false });
57
+ assert.equal(execute.mock.callCount(), before + Number(native));
58
+ assert.equal(result.isError === true, error !== undefined);
59
+ assert.equal(reportOf(result, "read")?.error, error);
60
+ if (native) {
61
+ assert.deepEqual(execute.mock.calls.at(-1)?.arguments[2], {
62
+ ...params,
63
+ path: join(dir, path),
64
+ });
65
+ assert.equal(result.details?.nativeRead, true);
66
+ }
67
+ });
68
+ }
69
+
70
+ await t.test(
71
+ "encoded Unicode path and different context cwd → delegates the exact file",
72
+ async () => {
73
+ const other = join(dir, "other");
74
+ await mkdir(other);
75
+ for (const [name, bytes] of [
76
+ ["image\u202f.gif", image],
77
+ ["nul\u202f.txt", Buffer.from("exact\0target")],
78
+ ] as const) {
79
+ await writeFile(join(dir, name), bytes);
80
+ await writeFile(join(dir, name.replace("\u202f", " ")), "wrong normalized target");
81
+ const result = await callTool(
82
+ tool,
83
+ { path: pathToFileURL(join(dir, name)).href },
84
+ { ctx: { cwd: other } },
85
+ );
86
+ assert.equal(result.isError, undefined);
87
+ assert.equal(result.details?.nativeRead, true);
88
+ if (name.endsWith(".gif"))
89
+ assert.ok(result.content.some((block) => block.type === "image"));
90
+ else
91
+ assert.equal(
92
+ result.content[0]?.type === "text" && result.content[0].text,
93
+ bytes.toString(),
94
+ );
95
+ }
96
+ const result = await callTool(tool, { path: "@nul.txt" }, { ctx: { cwd: other } });
97
+ assert.equal(result.isError, undefined);
98
+ assert.equal(
99
+ result.content[0]?.type === "text" && result.content[0].text,
100
+ "first\0\nsecond\n",
101
+ );
102
+ },
103
+ );
104
+
105
+ await t.test(
106
+ "canonical target disappears before native read → does not open a filename variant",
107
+ async () => {
108
+ const target = join(dir, "shot 9 AM.txt");
109
+ await writeFile(target, "original\0target");
110
+ await writeFile(join(dir, "shot 9\u202fAM.txt"), "wrong variant");
111
+ beforeNative = () => rm(target);
112
+ const result = await callTool(tool, { path: "shot 9 AM.txt" });
113
+ beforeNative = undefined;
114
+ assert.equal(result.isError, true);
115
+ assert.equal(reportOf(result, "read")?.error, "PATH_NOT_FOUND");
116
+ assert.deepEqual(reportOf(result, "read")?.missing, [target]);
117
+ },
118
+ );
119
+ });
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Override read: recognized images and NUL-containing files delegate to Pi's
3
- * built-in read; valid UTF-8 text outputs "lineNo#hash│content".
3
+ * built-in read; other valid UTF-8 text has a header and formatted rows.
4
+ * `anchors: false` omits the row prefixes.
4
5
  *
5
6
  * Hashes are computed from the current content on the fly — nothing is stored.
6
7
  * The hash is `(line number, content)`, recomputed and checked at edit time, so
@@ -9,6 +10,8 @@
9
10
  * @module pi-hashline-edit/pi
10
11
  */
11
12
 
13
+ import { constants } from "node:fs";
14
+ import { access, readFile, stat } from "node:fs/promises";
12
15
  import {
13
16
  createReadToolDefinition,
14
17
  detectSupportedImageMimeTypeFromFile,
@@ -28,7 +31,7 @@ import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./
28
31
  import { canonicalPath, serializePath } from "./path.ts";
29
32
  import { renderToolError, reportLines, splitReport } from "./render.ts";
30
33
  import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
31
- import { errnoCode } from "../core/errors.ts";
34
+ import { HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
32
35
  import { throwIfCancelled } from "./error-text.ts";
33
36
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
34
37
  import { formatByteSize } from "./budgets.ts";
@@ -40,6 +43,9 @@ const DEFAULT_OFFSET = 1;
40
43
  /** Pi's read details for a delegated native read; the report states this read's own facts. */
41
44
  type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDetails>;
42
45
 
46
+ /** Pi's read arguments plus this override's own. */
47
+ type ReadInput = ReadToolInput & { anchors?: boolean };
48
+
43
49
  /**
44
50
  * First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
45
51
  * ` · no trailing newline`. A missing final newline is a byte-level fact the
@@ -59,12 +65,19 @@ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no traili
59
65
 
60
66
  /**
61
67
  * Render the expanded read body for the TUI: color the header, strip the
62
- * `LINE#HASH│` prefix from every anchor line to ` N: content`, and
68
+ * `LINE#HASH│` prefix from every anchor line to ` N: content` (rows read with
69
+ * `anchors: false` have no prefix and are numbered from the header's offset), and
63
70
  * syntax-highlight the code block by the file's language (falls back to a
64
71
  * single `toolOutput` color when the language is unknown or the highlight
65
72
  * line count diverges). Notices are report facts, rendered from the report.
66
73
  */
67
- function renderReadBody(raw: string, path: string, theme: Theme): string {
74
+ function renderReadBody(
75
+ raw: string,
76
+ path: string,
77
+ anchored: boolean,
78
+ lineTooLong: boolean,
79
+ theme: Theme,
80
+ ): string {
68
81
  const lines = raw.split("\n");
69
82
  const out: string[] = [];
70
83
 
@@ -77,11 +90,18 @@ function renderReadBody(raw: string, path: string, theme: Theme): string {
77
90
  bodyStart = 1;
78
91
  }
79
92
 
80
- // Collect anchor rows (full content).
93
+ // Collect rows (full content).
81
94
  const lineNos: string[] = [];
82
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;
83
101
  for (let i = bodyStart; i < lines.length; i++) {
84
- const row = parseHashline(lines[i]);
102
+ const row = anchored
103
+ ? parseHashline(lines[i])
104
+ : { lineNo: String(firstLine + i - bodyStart), content: lines[i] };
85
105
  if (!row) break;
86
106
  lineNos.push(row.lineNo);
87
107
  codeContents.push(row.content);
@@ -134,6 +154,12 @@ export function makeReadOverride({
134
154
  description: `Maximum lines to read (default ${defaultLimit}).`,
135
155
  }),
136
156
  ),
157
+ anchors: Type.Optional(
158
+ Type.Boolean({
159
+ 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).",
161
+ }),
162
+ ),
137
163
  },
138
164
  { additionalProperties: false },
139
165
  );
@@ -142,9 +168,15 @@ export function makeReadOverride({
142
168
  name: "read" as const,
143
169
  label: "read",
144
170
  description:
145
- "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
171
+ "Read a file. Images return as attachments. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
146
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
+ ],
147
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,
148
180
  prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
149
181
  constrainedSampling: STRICT_SAMPLING,
150
182
  renderShell: "default" as const,
@@ -164,7 +196,13 @@ export function makeReadOverride({
164
196
  const raw = content[0]?.type === "text" ? content[0].text : "";
165
197
  return new Text(
166
198
  [
167
- renderReadBody(raw, String(context.args?.path ?? ""), theme),
199
+ renderReadBody(
200
+ raw,
201
+ String(context.args?.path ?? ""),
202
+ (context.args as ReadInput | undefined)?.anchors !== false,
203
+ report !== undefined && "lineTooLong" in report && report.lineTooLong !== undefined,
204
+ theme,
205
+ ),
168
206
  ...(report ? reportLines(report, theme) : []),
169
207
  ].join("\n"),
170
208
  0,
@@ -174,7 +212,7 @@ export function makeReadOverride({
174
212
 
175
213
  async execute(
176
214
  toolCallId: string,
177
- params: ReadToolInput,
215
+ { anchors: anchored, ...params }: ReadInput,
178
216
  signal: AbortSignal | undefined,
179
217
  onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
180
218
  ctx: ExtensionToolContext,
@@ -187,80 +225,90 @@ export function makeReadOverride({
187
225
  const start = params.offset ?? DEFAULT_OFFSET;
188
226
  const limit = params.limit ?? defaultLimit;
189
227
  const anchors = createAnchorFormatter(hashLen);
228
+ const formatRow =
229
+ anchored === false
230
+ ? (_line: number, content: string) => displayCarriageReturns(content)
231
+ : anchors.row;
190
232
  const report = { tool: "read" as const, path: params.path };
233
+ const absPath = canonicalPath(cwd, params.path);
191
234
  const readNative = async () => {
192
- const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
193
- return reportResult(report, result.content, {
194
- ...result.details,
195
- nativeRead: true as const,
235
+ // Bind I/O to our target: native resolution may normalize or try filename variants.
236
+ const native = createReadToolDefinition(cwd, {
237
+ operations: {
238
+ access: () => access(absPath, constants.R_OK),
239
+ readFile: () => readFile(absPath),
240
+ detectImageMimeType: () => detectSupportedImageMimeTypeFromFile(absPath),
241
+ },
196
242
  });
243
+ const result = await native.execute(
244
+ toolCallId,
245
+ { ...params, path: absPath },
246
+ signal,
247
+ onUpdate,
248
+ ctx,
249
+ );
250
+ return {
251
+ ...reportResult(report, result.content, {
252
+ ...result.details,
253
+ nativeRead: true as const,
254
+ }),
255
+ structuredContent: result.structuredContent,
256
+ };
197
257
  };
198
258
 
199
- const absPath = canonicalPath(cwd, params.path);
200
- try {
201
- if (await detectSupportedImageMimeTypeFromFile(absPath)) {
202
- return readNative();
203
- }
204
- } catch {
205
- return readNative();
259
+ if ((await stat(absPath)).isDirectory()) {
260
+ throw new HashlineError("NOT_REGULAR_FILE", PATH_ERROR_MESSAGES.NOT_REGULAR_FILE);
206
261
  }
262
+ if (await detectSupportedImageMimeTypeFromFile(absPath)) return readNative();
207
263
 
208
264
  const rows: string[] = [];
209
265
  const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
210
266
  let outputBytes = 0;
211
- let truncated = false;
212
- let firstLineExceedsLimit = false;
213
- let stats: Awaited<ReturnType<typeof scanTextLines>>;
214
- try {
215
- stats = await scanTextLines(
216
- absPath,
217
- (number) => number >= start && number - start < limit,
218
- (line) => {
219
- if (truncated) return;
220
- const rowBytes =
221
- line.byteLength +
222
- line.carriageReturns * crExpansion +
223
- Buffer.byteLength(anchors.row(line.number, ""));
224
- const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
225
- if (nextBytes > maxBytes) {
226
- truncated = true;
227
- firstLineExceedsLimit = rows.length === 0;
228
- return;
229
- }
230
- rows.push(anchors.row(line.number, line.text!));
231
- outputBytes = nextBytes;
232
- },
233
- { signal, maxLineBytes: maxBytes },
234
- );
235
- } catch (error) {
236
- // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
237
- if (!signal?.aborted && errnoCode(error) !== undefined) {
238
- return readNative();
239
- }
240
- throw error;
241
- }
267
+ let firstOmittedLine: number | undefined;
268
+ const stats = await scanTextLines(
269
+ absPath,
270
+ (number) => number >= start && number - start < limit,
271
+ (line) => {
272
+ if (firstOmittedLine !== undefined) return;
273
+ 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;
280
+ return;
281
+ }
282
+ rows.push(formatRow(line.number, line.text!));
283
+ outputBytes = nextBytes;
284
+ },
285
+ { signal, maxLineBytes: maxBytes },
286
+ );
242
287
  if (stats.hasNul) return readNative();
243
- // Rows were returned and more remain. A caller's own limit is a chosen window: its header
244
- // and rows already show where it ends, so only a window the extension cut (default limit
245
- // or byte budget) gets a report.
246
- const nextOffset =
247
- (params.limit === undefined || truncated) &&
248
- rows.length > 0 &&
249
- start + rows.length <= stats.totalLines
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
250
292
  ? start + rows.length
251
293
  : undefined;
294
+ const nextOffset = firstLineTooLong
295
+ ? undefined
296
+ : (firstOmittedLine ?? nextAfterDefaultLimit);
252
297
  const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
253
298
  const limitText = formatByteSize(maxBytes);
254
299
 
255
- return reportResult(
300
+ const result = reportResult(
256
301
  {
257
302
  ...report,
258
303
  nextOffset,
259
- outputLimit: truncated && !firstLineExceedsLimit ? limitText : undefined,
260
- lineTooLong: firstLineExceedsLimit ? limitText : undefined,
304
+ outputLimit:
305
+ firstOmittedLine !== undefined && !firstLineTooLong ? limitText : undefined,
306
+ lineTooLong: firstLineTooLong ? limitText : undefined,
261
307
  },
262
308
  [{ type: "text" as const, text: header + rows.join("\n") }],
263
309
  );
310
+ const text = result.content.flatMap((block) => (block.type === "text" ? [block.text] : []));
311
+ return { ...result, structuredContent: text.join("\n") };
264
312
  });
265
313
  },
266
314
  };