@criogaid/pi-hashline-edit 0.11.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.
- package/LICENSE +1 -0
- package/README.md +73 -17
- package/README.zh-CN.md +74 -18
- package/package.json +8 -7
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +15 -2
- package/src/core/apply.ts +6 -10
- package/src/core/case-fold.test.ts +16 -25
- package/src/core/case-fold.ts +4 -4
- package/src/core/character-set.test.ts +1 -6
- package/src/core/character-set.ts +7 -61
- package/src/core/regex.ts +2 -32
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- package/src/core/search-analysis.test.ts +66 -61
- package/src/core/search-analysis.ts +24 -39
- package/src/core/search-matrix.test.ts +2 -2
- package/src/core/search-matrix.testing.ts +6 -16
- package/src/core/search-schema.ts +0 -1
- package/src/core/search.test.ts +6 -19
- package/src/core/search.ts +10 -8
- package/src/index.ts +28 -3
- package/src/integration/config-registration.test.ts +77 -4
- package/src/integration/fusion-dispatch.test.ts +47 -2
- package/src/integration/grep-errors.test.ts +31 -0
- package/src/integration/grep-flags.test.ts +13 -196
- package/src/integration/grep-js-completeness.test.ts +41 -8
- package/src/integration/grep-line-candidates.test.ts +4 -33
- package/src/integration/grep-matrix.test.ts +1 -1
- package/src/integration/grep-path-matrix.test.ts +59 -65
- package/src/integration/grep-prefilter-coverage.test.ts +26 -8
- package/src/integration/grep-process-limits.test.ts +46 -0
- package/src/integration/grep-regex.test.ts +7 -2
- package/src/integration/grep-rg.test.ts +106 -12
- package/src/integration/grep-translation.test.ts +14 -7
- package/src/integration/model-budget-lifecycle.test.ts +41 -2
- package/src/integration/npm-package.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +147 -1
- package/src/integration/replace-package.testing.ts +2 -2
- package/src/integration/report-replay.test.ts +4 -0
- package/src/pi/AGENTS.md +23 -15
- package/src/pi/action-fusion.test.ts +38 -4
- package/src/pi/action-fusion.ts +23 -19
- package/src/pi/argument-diagnostics.ts +28 -48
- package/src/pi/argument-validation.test.ts +103 -6
- package/src/pi/argument-validation.ts +55 -31
- package/src/pi/budgets.ts +19 -10
- package/src/pi/config.test.ts +1 -1
- package/src/pi/diagnostic-buffer.test.ts +1 -0
- package/src/pi/edit-tool.ts +3 -3
- package/src/pi/execute.test.ts +4 -0
- package/src/pi/failure-context.test.ts +24 -3
- package/src/pi/failure-context.ts +36 -42
- package/src/pi/failure-path.test.ts +8 -3
- package/src/pi/file-commit.test.ts +109 -52
- package/src/pi/file-commit.ts +62 -56
- package/src/pi/fusion-card.ts +12 -7
- package/src/pi/grep-candidates.test.ts +5 -5
- package/src/pi/grep-candidates.ts +80 -48
- package/src/pi/grep-matrix.test.ts +14 -29
- package/src/pi/grep-order.test.ts +132 -9
- package/src/pi/grep-output.ts +173 -48
- package/src/pi/grep-render.ts +40 -34
- package/src/pi/grep-rg.testing.ts +9 -6
- package/src/pi/grep-scope.ts +51 -29
- package/src/pi/grep-search.ts +96 -71
- package/src/pi/grep-tool.ts +28 -34
- package/src/pi/grep.test.ts +348 -83
- package/src/pi/model-budgets.test.ts +56 -6
- package/src/pi/model-budgets.ts +7 -4
- package/src/pi/mutation-result.test.ts +25 -1
- package/src/pi/mutation-result.ts +7 -2
- package/src/pi/mutation-runner.ts +4 -5
- package/src/pi/output-budgets.test.ts +3 -1
- package/src/pi/path.ts +18 -4
- package/src/pi/pi.test.ts +22 -0
- package/src/pi/read-delegation.test.ts +119 -0
- package/src/pi/read-tool.ts +109 -61
- package/src/pi/read.test.ts +351 -17
- package/src/pi/regex-worker.test.ts +42 -0
- package/src/pi/regex-worker.ts +17 -11
- package/src/pi/registration.test.ts +157 -102
- package/src/pi/render.test.ts +97 -0
- package/src/pi/render.ts +9 -9
- package/src/pi/replace-tool.ts +5 -2
- package/src/pi/report-schema.ts +75 -37
- package/src/pi/report.test.ts +73 -31
- package/src/pi/report.ts +12 -5
- package/src/pi/rg-process.ts +41 -5
- package/src/pi/rg-regex.test.ts +12 -39
- package/src/pi/rg-regex.ts +31 -79
- package/src/pi/text-stream.test.ts +3 -0
- package/src/pi/text-stream.ts +1 -1
- package/src/testing/regex-translation-corpus.ts +39 -96
package/src/pi/model-budgets.ts
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { outputBudgetsFor, type OutputBudgetProvider } from "./budgets.ts";
|
|
4
4
|
|
|
5
|
-
/** Retain Pi's
|
|
5
|
+
/** Retain Pi's live model getter; the headless SDK can reload without emitting session_start. */
|
|
6
6
|
export function registerModelBudgets(pi: ExtensionAPI): OutputBudgetProvider {
|
|
7
7
|
let context: ExtensionContext | undefined;
|
|
8
|
-
|
|
9
|
-
context
|
|
10
|
-
}
|
|
8
|
+
const capture = (_event: unknown, ctx: ExtensionContext) => {
|
|
9
|
+
context ??= ctx;
|
|
10
|
+
};
|
|
11
|
+
pi.on("session_start", capture);
|
|
12
|
+
// Pi emits this before argument preparation, including for nested calls.
|
|
13
|
+
pi.on("tool_execution_start", capture);
|
|
11
14
|
return () => outputBudgetsFor(context?.model?.contextWindow);
|
|
12
15
|
}
|
|
@@ -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
|
|
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
|
|
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,
|
|
@@ -58,7 +57,7 @@ import type { OutputBudgets } from "./budgets.ts";
|
|
|
58
57
|
import type { ToolEnvironment } from "./config.ts";
|
|
59
58
|
import { STRICT_SAMPLING } from "./schema.ts";
|
|
60
59
|
|
|
61
|
-
|
|
60
|
+
type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
|
|
62
61
|
|
|
63
62
|
/** A mutation tool's registration environment; fusion is undefined when Action Fusion is off. */
|
|
64
63
|
export interface MutationToolEnvironment extends ToolEnvironment {
|
|
@@ -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
|
|
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:
|
|
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, "
|
|
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])(?:\/(.*))?$/
|
|
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://"))
|
|
36
|
-
|
|
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
|
-
|
|
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
|
+
});
|
package/src/pi/read-tool.ts
CHANGED
|
@@ -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
|
|
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 {
|
|
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
|
|
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(
|
|
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
|
|
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 =
|
|
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(
|
|
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:
|
|
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
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
200
|
-
|
|
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
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
-
//
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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
|
-
|
|
300
|
+
const result = reportResult(
|
|
256
301
|
{
|
|
257
302
|
...report,
|
|
258
303
|
nextOffset,
|
|
259
|
-
outputLimit:
|
|
260
|
-
|
|
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
|
};
|