@criogaid/pi-hashline-edit 0.5.1 → 0.6.1
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/README.md +51 -15
- package/package.json +6 -6
- package/src/core/apply.test.ts +66 -16
- package/src/core/apply.ts +36 -19
- package/src/core/lines.ts +3 -3
- package/src/index.ts +2 -0
- package/src/integration/forget-grep.test.ts +98 -0
- package/src/integration/fusion-dispatch.test.ts +343 -0
- package/src/integration/grep-rg.test.ts +269 -33
- package/src/integration/mutation-file-types.test.ts +44 -0
- package/src/pi/action-fusion.test.ts +71 -128
- package/src/pi/action-fusion.ts +83 -45
- package/src/pi/argument-validation.test.ts +136 -0
- package/src/pi/argument-validation.ts +102 -0
- package/src/pi/budgets.ts +4 -1
- package/src/pi/config.test.ts +1 -0
- package/src/pi/config.ts +4 -0
- package/src/pi/directory-sync.test.ts +1 -1
- package/src/pi/edit-tool.ts +55 -36
- package/src/pi/execute.test.ts +185 -645
- package/src/pi/extension-loading.test.ts +34 -0
- package/src/pi/extension-loading.testing.ts +15 -0
- package/src/pi/failure-context.test.ts +4 -3
- package/src/pi/failure-path.test.ts +3 -3
- package/src/pi/file-commit.test.ts +24 -17
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/file-snapshot.test.ts +24 -0
- package/src/pi/forget-tool.ts +268 -0
- package/src/pi/forget.test.ts +343 -0
- package/src/pi/forget.testing.ts +273 -0
- package/src/pi/grep-output.ts +57 -28
- package/src/pi/grep-search.ts +35 -12
- package/src/pi/grep-tool.ts +28 -9
- package/src/pi/grep.test.ts +173 -152
- package/src/pi/mutation-result.test.ts +23 -0
- package/src/pi/mutation-runner.ts +8 -4
- package/src/pi/path.ts +16 -2
- package/src/pi/pi.test.ts +3 -2
- package/src/pi/read-tool.ts +58 -26
- package/src/pi/read.test.ts +361 -0
- package/src/pi/registration.test.ts +115 -2
- package/src/pi/render.test.ts +45 -14
- package/src/pi/replace-tool.ts +18 -27
- package/src/pi/replace.test.ts +8 -107
- package/src/pi/result-safety.test.ts +123 -149
- package/src/pi/rg-match-bytes.ts +95 -0
- package/src/pi/rg-process.test.ts +40 -59
- package/src/pi/rg-text-view.ts +52 -5
- package/src/pi/tool-call.testing.ts +50 -0
- package/src/pi/tool-prompts.ts +15 -0
- package/src/pi/write-tool.ts +17 -26
- package/src/pi/write.test.ts +70 -61
- package/src/pi/e2e-scenarios.test.ts +0 -361
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { execFile as execFileCallback } from "node:child_process";
|
|
2
|
+
import { cp, mkdir, mkdtemp, rm, symlink } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import manifest from "../../package.json" with { type: "json" };
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
|
|
10
|
+
const execFile = promisify(execFileCallback);
|
|
11
|
+
const LOAD_TIMEOUT_MS = 30_000;
|
|
12
|
+
|
|
13
|
+
test("extension installed without devDependencies → loads through Pi's virtual modules", async (t) => {
|
|
14
|
+
const root = await mkdtemp(join(tmpdir(), "hashline-extension-"));
|
|
15
|
+
t.after(() => rm(root, { recursive: true, force: true }));
|
|
16
|
+
const repository = fileURLToPath(new URL("../../", import.meta.url));
|
|
17
|
+
await cp(join(repository, "src"), join(root, "src"), { recursive: true });
|
|
18
|
+
await cp(join(repository, "package.json"), join(root, "package.json"));
|
|
19
|
+
// Link only declared runtime packages; their own transitive dependencies stay resolvable.
|
|
20
|
+
for (const dependency of Object.keys(manifest.dependencies)) {
|
|
21
|
+
const destination = join(root, "node_modules", dependency);
|
|
22
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
23
|
+
await symlink(join(repository, "node_modules", dependency), destination, "junction");
|
|
24
|
+
}
|
|
25
|
+
const entry = join(root, "src", "index.ts");
|
|
26
|
+
await execFile(
|
|
27
|
+
process.execPath,
|
|
28
|
+
[fileURLToPath(new URL("./extension-loading.testing.ts", import.meta.url)), entry],
|
|
29
|
+
{
|
|
30
|
+
env: { ...process.env, NODE_OPTIONS: "", NODE_PATH: "" },
|
|
31
|
+
timeout: LOAD_TIMEOUT_MS,
|
|
32
|
+
},
|
|
33
|
+
);
|
|
34
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Run in a fresh Node process so global loaders and module caches cannot supply devDependencies.
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { createJiti } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/jiti-static-loader.js";
|
|
5
|
+
import { VIRTUAL_MODULES } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/virtual-modules.js";
|
|
6
|
+
|
|
7
|
+
const entry = process.argv[2];
|
|
8
|
+
assert.throws(() => createRequire(entry).resolve("typebox/type"), { code: "MODULE_NOT_FOUND" });
|
|
9
|
+
const jiti = createJiti(import.meta.url, {
|
|
10
|
+
moduleCache: false,
|
|
11
|
+
virtualModules: VIRTUAL_MODULES,
|
|
12
|
+
tryNative: false,
|
|
13
|
+
});
|
|
14
|
+
const factory = await jiti.import<unknown>(entry, { default: true });
|
|
15
|
+
assert.equal(typeof factory, "function");
|
|
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { computeLineHash } from "../core/hash.ts";
|
|
4
4
|
import type { AnchorFailure } from "../core/types.ts";
|
|
5
|
+
import { MAX_BLOCK_BYTES } from "./budgets.ts";
|
|
5
6
|
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
6
7
|
import { formatAmbiguousCandidateNeighborhoods } from "./failure-context.ts";
|
|
7
8
|
|
|
@@ -86,7 +87,7 @@ test("ambiguous context uses the same first eight candidates as the detail list"
|
|
|
86
87
|
});
|
|
87
88
|
|
|
88
89
|
test("ambiguous context preserves complete rows at the byte budget", () => {
|
|
89
|
-
const exact = "x".repeat(
|
|
90
|
+
const exact = "x".repeat(MAX_BLOCK_BYTES - Buffer.byteLength("1#XXXX│\n"));
|
|
90
91
|
const lines = [exact, "target", "last"];
|
|
91
92
|
const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
|
|
92
93
|
assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact, 4)}│${exact}\n`));
|
|
@@ -143,10 +144,10 @@ test("unique candidates inside ambiguous neighborhoods retain the candidate row
|
|
|
143
144
|
});
|
|
144
145
|
|
|
145
146
|
test("neighborhoods keep shorter later rows when the remaining budget cannot fit a row", () => {
|
|
146
|
-
const lines = ["x".repeat(
|
|
147
|
+
const lines = ["x".repeat(MAX_BLOCK_BYTES - 100), "y".repeat(200), "target", "other"];
|
|
147
148
|
const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
|
|
148
149
|
assert.deepEqual([...output.shownLines], [1, 3, 4]);
|
|
149
150
|
assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
|
|
150
151
|
const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
|
|
151
|
-
assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <=
|
|
152
|
+
assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= MAX_BLOCK_BYTES);
|
|
152
153
|
});
|
|
@@ -37,7 +37,7 @@ test("published post-processing failure skips command and preserves publication
|
|
|
37
37
|
const updates: any[] = [];
|
|
38
38
|
const fusion = createActionFusionExecutor(async () => {
|
|
39
39
|
commanded = true;
|
|
40
|
-
return "never";
|
|
40
|
+
return { status: "succeeded", output: "never" };
|
|
41
41
|
});
|
|
42
42
|
await assert.rejects(
|
|
43
43
|
fusion({
|
|
@@ -130,7 +130,7 @@ test("queue is released after a failed command", async () =>
|
|
|
130
130
|
const fusion = createActionFusionExecutor(async () => {
|
|
131
131
|
calls++;
|
|
132
132
|
if (calls === 1) throw new Error("first command failed");
|
|
133
|
-
return "ok";
|
|
133
|
+
return { status: "succeeded", output: "ok" };
|
|
134
134
|
});
|
|
135
135
|
const first = fusion({
|
|
136
136
|
toolCallId: "first",
|
|
@@ -168,7 +168,7 @@ test("successful command finalizes anchors and retains completed progress", asyn
|
|
|
168
168
|
const target = join(dir, "finalize.txt");
|
|
169
169
|
const progress: any[] = [];
|
|
170
170
|
const fusion = createActionFusionExecutor(
|
|
171
|
-
async () => "command finished",
|
|
171
|
+
async () => ({ status: "succeeded", output: "command finished" }),
|
|
172
172
|
(event) => progress.push(event),
|
|
173
173
|
);
|
|
174
174
|
const completed = await fusion({
|
|
@@ -225,7 +225,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
|
|
|
225
225
|
dir,
|
|
226
226
|
createActionFusionExecutor(async () => {
|
|
227
227
|
commandRuns++;
|
|
228
|
-
return "ok";
|
|
228
|
+
return { status: "succeeded", output: "ok" };
|
|
229
229
|
}),
|
|
230
230
|
);
|
|
231
231
|
try {
|
|
@@ -235,6 +235,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
|
|
|
235
235
|
{
|
|
236
236
|
path: target,
|
|
237
237
|
content: "replacement\n",
|
|
238
|
+
mode: "overwrite",
|
|
238
239
|
then_run: { command: "deterministic-command" },
|
|
239
240
|
},
|
|
240
241
|
{ toolCallId: "shared-failure", ctx: { cwd: dir } },
|
|
@@ -270,7 +271,12 @@ test("Windows shared access failure preserves the target, skips then_run, and re
|
|
|
270
271
|
assert.equal(await readFile(target, "utf8"), "original\n");
|
|
271
272
|
const result = await callTool(
|
|
272
273
|
tool,
|
|
273
|
-
{
|
|
274
|
+
{
|
|
275
|
+
path: target,
|
|
276
|
+
content: "replacement\n",
|
|
277
|
+
mode: "overwrite",
|
|
278
|
+
then_run: { command: "deterministic-command" },
|
|
279
|
+
},
|
|
274
280
|
{ toolCallId: "shared-retry", ctx: { cwd: dir } },
|
|
275
281
|
);
|
|
276
282
|
assert.match(
|
|
@@ -328,7 +334,7 @@ test("commit rejects lossy UTF-8 output before modifying or creating files", asy
|
|
|
328
334
|
for (const content of ["\ud800", "\udfff", "before\ud800after"]) {
|
|
329
335
|
for (const path of [existing, missing]) {
|
|
330
336
|
await assert.rejects(
|
|
331
|
-
commitFile(path, content),
|
|
337
|
+
commitFile(path, content, { mode: path === existing ? "overwrite" : "create" }),
|
|
332
338
|
(error: any) =>
|
|
333
339
|
error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message),
|
|
334
340
|
);
|
|
@@ -337,7 +343,7 @@ test("commit rejects lossy UTF-8 output before modifying or creating files", asy
|
|
|
337
343
|
assert.equal(await readFile(existing, "utf8"), "original\n");
|
|
338
344
|
await assert.rejects(readFile(missing), { code: "ENOENT" });
|
|
339
345
|
const content = "\uFEFFvalid 😀\r\n";
|
|
340
|
-
const result = await commitFile(existing, content);
|
|
346
|
+
const result = await commitFile(existing, content, { mode: "overwrite" });
|
|
341
347
|
assert.deepEqual(await readFile(existing), Buffer.from(content));
|
|
342
348
|
assert.equal(result.publishedRevision, byteRevision(Buffer.from(content)));
|
|
343
349
|
}));
|
|
@@ -349,16 +355,17 @@ test("identical commits preserve the file and still enforce mode, revision, and
|
|
|
349
355
|
await writeFile(target, content);
|
|
350
356
|
const before = await stat(target);
|
|
351
357
|
const revision = await fileRevision(target);
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
358
|
+
const result = await commitFile(target, content, {
|
|
359
|
+
mode: "overwrite",
|
|
360
|
+
expectedRevision: revision,
|
|
361
|
+
});
|
|
362
|
+
assert.deepEqual(result, {
|
|
363
|
+
created: false,
|
|
364
|
+
baseRevision: revision,
|
|
365
|
+
publishedRevision: revision,
|
|
366
|
+
observedRevision: revision,
|
|
367
|
+
publication: "NOT_PUBLISHED",
|
|
368
|
+
});
|
|
362
369
|
const after = await stat(target);
|
|
363
370
|
assert.deepEqual(
|
|
364
371
|
[after.ino, after.mtimeMs, after.ctimeMs],
|
|
@@ -366,11 +373,11 @@ test("identical commits preserve the file and still enforce mode, revision, and
|
|
|
366
373
|
);
|
|
367
374
|
await assert.rejects(commitFile(target, content, { mode: "create" }), /already exists/);
|
|
368
375
|
await assert.rejects(
|
|
369
|
-
commitFile(target, content, { expectedRevision: "stale" }),
|
|
376
|
+
commitFile(target, content, { mode: "overwrite", expectedRevision: "stale" }),
|
|
370
377
|
/expectedRevision/,
|
|
371
378
|
);
|
|
372
379
|
await assert.rejects(
|
|
373
|
-
commitFile(target, content, { signal: AbortSignal.abort() }),
|
|
380
|
+
commitFile(target, content, { mode: "overwrite", signal: AbortSignal.abort() }),
|
|
374
381
|
(error: unknown) =>
|
|
375
382
|
error instanceof FileMutationError && error.publication === "NOT_PUBLISHED",
|
|
376
383
|
);
|
|
@@ -378,7 +385,7 @@ test("identical commits preserve the file and still enforce mode, revision, and
|
|
|
378
385
|
commitFile(join(dir, "missing"), "", { mode: "overwrite" }),
|
|
379
386
|
/does not exist/,
|
|
380
387
|
);
|
|
381
|
-
const created = await commitFile(join(dir, "empty"), "");
|
|
388
|
+
const created = await commitFile(join(dir, "empty"), "", { mode: "create" });
|
|
382
389
|
assert.equal(created.created, true);
|
|
383
390
|
assert.equal(created.publication, "PUBLISHED");
|
|
384
391
|
}));
|
package/src/pi/file-commit.ts
CHANGED
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
mkdir,
|
|
5
5
|
mkdtemp,
|
|
6
6
|
open,
|
|
7
|
-
readFile,
|
|
8
7
|
realpath,
|
|
9
8
|
rename,
|
|
10
9
|
rm,
|
|
11
10
|
stat,
|
|
12
11
|
link,
|
|
13
12
|
} from "node:fs/promises";
|
|
13
|
+
import { constants, type Stats } from "node:fs";
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
15
15
|
import { createHash } from "node:crypto";
|
|
16
16
|
import { decodeEditableText, unwritableTextReason } from "../core/text.ts";
|
|
@@ -21,7 +21,7 @@ export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
|
|
|
21
21
|
export type CommitMode = "create" | "overwrite";
|
|
22
22
|
|
|
23
23
|
export interface CommitOptions {
|
|
24
|
-
mode
|
|
24
|
+
mode: CommitMode;
|
|
25
25
|
expectedRevision?: string;
|
|
26
26
|
signal?: AbortSignal;
|
|
27
27
|
/** Caller-supplied revision of the current file, skipping the readFile + SHA-256 in inspectTarget. */
|
|
@@ -60,16 +60,43 @@ export function byteRevision(content: string | Uint8Array): string {
|
|
|
60
60
|
return createHash("sha256").update(content).digest("hex");
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
function requireRegularFile(target: Stats): void {
|
|
64
|
+
if (!target.isFile()) throw prepareError("target is not a regular file");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Check the opened object before reading; a FIFO must not block even if the path changed. */
|
|
68
|
+
async function readRegularFile(path: string, signal?: AbortSignal): Promise<Buffer> {
|
|
69
|
+
throwIfCancelled(signal);
|
|
70
|
+
const flags = constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NONBLOCK);
|
|
71
|
+
const handle = await open(path, flags);
|
|
72
|
+
try {
|
|
73
|
+
requireRegularFile(await handle.stat());
|
|
74
|
+
return await handle.readFile({ signal });
|
|
75
|
+
} finally {
|
|
76
|
+
await handle.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
63
80
|
export async function fileRevision(path: string): Promise<string> {
|
|
64
|
-
return byteRevision(await
|
|
81
|
+
return byteRevision(await readRegularFile(path));
|
|
65
82
|
}
|
|
66
83
|
|
|
67
84
|
/** Decode and bind a mutation snapshot to the exact bytes read. */
|
|
68
|
-
export async function readEditableSnapshot(
|
|
85
|
+
export async function readEditableSnapshot(
|
|
86
|
+
path: string,
|
|
87
|
+
displayPath: string,
|
|
88
|
+
signal?: AbortSignal,
|
|
89
|
+
) {
|
|
69
90
|
try {
|
|
70
|
-
const bytes = await
|
|
91
|
+
const bytes = await readRegularFile(path, signal);
|
|
71
92
|
return { text: decodeEditableText(bytes), baseRevision: byteRevision(bytes) };
|
|
72
93
|
} catch (error) {
|
|
94
|
+
if (signal?.aborted)
|
|
95
|
+
throw prepareError(
|
|
96
|
+
`${OPERATION_ABORTED} before apply; ${displayPath} was not changed.`,
|
|
97
|
+
error,
|
|
98
|
+
);
|
|
99
|
+
if (error instanceof FileMutationError) throw error;
|
|
73
100
|
throw new Error(`Error reading ${displayPath}: ${errorMessage(error)}`);
|
|
74
101
|
}
|
|
75
102
|
}
|
|
@@ -144,7 +171,7 @@ async function inspectTarget(path: string, knownBeforeRevision?: string): Promis
|
|
|
144
171
|
} catch (error) {
|
|
145
172
|
throw prepareError(`unable to inspect target: ${errorMessage(error)}`, error);
|
|
146
173
|
}
|
|
147
|
-
|
|
174
|
+
requireRegularFile(target);
|
|
148
175
|
if (target.nlink > 1)
|
|
149
176
|
throw prepareError("target has multiple hard links; refusing to split the link set");
|
|
150
177
|
|
|
@@ -246,7 +273,7 @@ async function syncDirectory(path: string): Promise<void> {
|
|
|
246
273
|
export async function commitFile(
|
|
247
274
|
path: string,
|
|
248
275
|
content: string,
|
|
249
|
-
options: CommitOptions
|
|
276
|
+
options: CommitOptions,
|
|
250
277
|
): Promise<CommitResult> {
|
|
251
278
|
// Tools reject such input in prepareArguments, but a transformation can still produce it
|
|
252
279
|
// (a regex without `u` can split a surrogate pair), so publication keeps the final check.
|
|
@@ -254,11 +281,11 @@ export async function commitFile(
|
|
|
254
281
|
if (unwritable) throw prepareError(unwritable);
|
|
255
282
|
const bytes = Buffer.from(content, "utf8");
|
|
256
283
|
const target = await inspectTarget(path, options.knownBeforeRevision);
|
|
257
|
-
const mode = options
|
|
284
|
+
const { mode } = options;
|
|
258
285
|
if (mode === "create" && target.existed)
|
|
259
286
|
throw prepareError("target already exists; use mode=overwrite");
|
|
260
287
|
if (mode === "overwrite" && !target.existed)
|
|
261
|
-
throw prepareError("target does not exist; use mode=create
|
|
288
|
+
throw prepareError("target does not exist; use mode=create");
|
|
262
289
|
if (mode === "create" && options.expectedRevision !== undefined)
|
|
263
290
|
throw prepareError("expectedRevision cannot be combined with mode=create");
|
|
264
291
|
if (
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import { FileMutationError, readEditableSnapshot } from "./file-commit.ts";
|
|
7
|
+
|
|
8
|
+
test("snapshot cancelled while opening → rejects as an unpublished cancellation", async (t) => {
|
|
9
|
+
const directory = await mkdtemp(join(tmpdir(), "hashline-snapshot-"));
|
|
10
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
11
|
+
const path = join(directory, "file.txt");
|
|
12
|
+
await writeFile(path, "before\n");
|
|
13
|
+
const controller = new AbortController();
|
|
14
|
+
const reading = readEditableSnapshot(path, "file.txt", controller.signal);
|
|
15
|
+
controller.abort();
|
|
16
|
+
await assert.rejects(
|
|
17
|
+
reading,
|
|
18
|
+
(error: unknown) =>
|
|
19
|
+
error instanceof FileMutationError &&
|
|
20
|
+
error.publication === "NOT_PUBLISHED" &&
|
|
21
|
+
error.message.startsWith("Operation aborted"),
|
|
22
|
+
);
|
|
23
|
+
assert.equal(await readFile(path, "utf8"), "before\n");
|
|
24
|
+
});
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* forget: the model drops read/grep results it no longer needs from model context.
|
|
3
|
+
*
|
|
4
|
+
* The decision is made after the model has seen a result, and only in the response
|
|
5
|
+
* that first sees it. read and grep tag results of at least FORGET_MIN_BYTES (and any
|
|
6
|
+
* image) with a `[result rXXXXX]` block derived from the tool call id. Before each
|
|
7
|
+
* request, the `context` handler records the tagged results that follow the last
|
|
8
|
+
* assistant message: the batch the coming response is the first to see. forget may
|
|
9
|
+
* name only those ids. At `turn_end` of a completed response, Pi's branch-local
|
|
10
|
+
* context edits replace each named result's entire content with a forgotten receipt.
|
|
11
|
+
* The tool call and any facts saved in forget's note remain in context.
|
|
12
|
+
*
|
|
13
|
+
* Restricting forget to the newest batch bounds how much of the next request changes:
|
|
14
|
+
* it differs from the earliest replaced result on, which covers later results of the
|
|
15
|
+
* same batch, the response that requested the edit, and its tool results. Messages
|
|
16
|
+
* before that result are unchanged. Editing an older result would change every
|
|
17
|
+
* later message. Raw session entries stay intact; navigating before the edit shows
|
|
18
|
+
* the original result again.
|
|
19
|
+
*
|
|
20
|
+
* @module pi-hashline-edit/pi
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
25
|
+
import type {
|
|
26
|
+
ContextEditEntryDraft,
|
|
27
|
+
ExtensionAPI,
|
|
28
|
+
Theme,
|
|
29
|
+
ToolDefinition,
|
|
30
|
+
} from "@earendil-works/pi-coding-agent";
|
|
31
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
32
|
+
import { Type, type Static } from "typebox";
|
|
33
|
+
import { FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
|
|
34
|
+
import { renderToolError } from "./render.ts";
|
|
35
|
+
import { createArgumentPreparer } from "./argument-validation.ts";
|
|
36
|
+
|
|
37
|
+
const RESULT_ID = "r[0-9a-f]{5}";
|
|
38
|
+
const RESULT_TAG = new RegExp(`^\\[result ${RESULT_ID}\\]$`);
|
|
39
|
+
|
|
40
|
+
/** Short id shown to the model; it only has to be unique within one tool batch. */
|
|
41
|
+
function resultId(toolCallId: string): string {
|
|
42
|
+
return `r${createHash("sha256").update(toolCallId).digest("hex").slice(0, 5)}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function resultTag(toolCallId: string): string {
|
|
46
|
+
return `[result ${resultId(toolCallId)}]`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type ResultContent = AgentToolResult<unknown>["content"];
|
|
50
|
+
|
|
51
|
+
function isResultTag(block: ResultContent[number] | undefined, toolCallId: string): boolean {
|
|
52
|
+
return block?.type === "text" && block.text === resultTag(toolCallId);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Pattern text shown in a grep receipt before it is cut with an ellipsis. */
|
|
56
|
+
const MAX_RECEIPT_PATTERN_CHARS = 60;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Display-only receipt for a tagged result, kept in its details. Pi does not send details
|
|
60
|
+
* to the model, so the forget card can name what was forgotten without adding context.
|
|
61
|
+
*/
|
|
62
|
+
export interface ForgetReceiptDetails {
|
|
63
|
+
forgetReceipt?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function plural(count: number, noun: string, pluralForm = `${noun}s`): string {
|
|
67
|
+
return `${count} ${count === 1 ? noun : pluralForm}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `path · lines A–B` for anchored text, `path · image` for images, `path` otherwise. */
|
|
71
|
+
export function readReceipt(
|
|
72
|
+
path: string,
|
|
73
|
+
shown: { image: true } | { start: number; end: number; truncated: boolean } | undefined,
|
|
74
|
+
): string {
|
|
75
|
+
if (!shown) return path;
|
|
76
|
+
if ("image" in shown) return `${path} · image`;
|
|
77
|
+
return `${path} · lines ${shown.start}–${shown.end}${shown.truncated ? " · truncated" : ""}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `grep /pattern/ · N matches in M files`, with limit and incomplete-search notes. */
|
|
81
|
+
export function grepReceipt(
|
|
82
|
+
patterns: readonly string[],
|
|
83
|
+
matches: number,
|
|
84
|
+
files: number,
|
|
85
|
+
notes: { limitReached: boolean; incomplete: boolean },
|
|
86
|
+
): string {
|
|
87
|
+
const joined = patterns.join(" | ");
|
|
88
|
+
const pattern =
|
|
89
|
+
joined.length > MAX_RECEIPT_PATTERN_CHARS
|
|
90
|
+
? `${joined.slice(0, MAX_RECEIPT_PATTERN_CHARS)}…`
|
|
91
|
+
: joined;
|
|
92
|
+
let receipt = `grep /${pattern}/ · ${plural(matches, "match", "matches")} in ${plural(files, "file")}`;
|
|
93
|
+
if (notes.limitReached) receipt += " · limit reached";
|
|
94
|
+
if (notes.incomplete) receipt += " · incomplete";
|
|
95
|
+
return receipt;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Tag a successful read/grep result when forgetting is enabled and the result is
|
|
100
|
+
* eligible. Only then evaluate createReceipt and keep its display text in details.
|
|
101
|
+
*/
|
|
102
|
+
export function withResultTag<T extends { content: ResultContent; details?: unknown }>(
|
|
103
|
+
toolCallId: string,
|
|
104
|
+
result: T,
|
|
105
|
+
enabled: boolean,
|
|
106
|
+
createReceipt: () => string,
|
|
107
|
+
): T {
|
|
108
|
+
if (!enabled) return result;
|
|
109
|
+
const bytes = result.content.reduce(
|
|
110
|
+
(sum, block) => sum + (block.type === "text" ? Buffer.byteLength(block.text) : 0),
|
|
111
|
+
0,
|
|
112
|
+
);
|
|
113
|
+
const hasImage = result.content.some((block) => block.type === "image");
|
|
114
|
+
if (!hasImage && bytes < FORGET_MIN_BYTES) return result;
|
|
115
|
+
return {
|
|
116
|
+
...result,
|
|
117
|
+
content: [...result.content, { type: "text" as const, text: resultTag(toolCallId) }],
|
|
118
|
+
details: { ...(result.details as object | undefined), forgetReceipt: createReceipt() },
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function receiptOf(details: unknown): string | undefined {
|
|
123
|
+
const receipt = (details as ForgetReceiptDetails | undefined)?.forgetReceipt;
|
|
124
|
+
return typeof receipt === "string" ? receipt : undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Drop the tag block before handing a result to a renderer that shows every text block. */
|
|
128
|
+
export function withoutResultTag<T extends { content: ResultContent }>(result: T): T {
|
|
129
|
+
const last = result.content.at(-1);
|
|
130
|
+
if (last?.type !== "text" || !RESULT_TAG.test(last.text)) return result;
|
|
131
|
+
return { ...result, content: result.content.slice(0, -1) };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const forgetSchema = Type.Object(
|
|
135
|
+
{
|
|
136
|
+
ids: Type.Array(Type.String({ pattern: `^${RESULT_ID}$` }), {
|
|
137
|
+
minItems: 1,
|
|
138
|
+
uniqueItems: true,
|
|
139
|
+
description: "Result ids to forget, from the [result rXXXXX] tags of the previous step.",
|
|
140
|
+
}),
|
|
141
|
+
note: Type.Optional(
|
|
142
|
+
Type.String({
|
|
143
|
+
minLength: 1,
|
|
144
|
+
description:
|
|
145
|
+
"Conclusions needed for subsequent work, kept in context. Omit when none; do not restate the read or forget action.",
|
|
146
|
+
}),
|
|
147
|
+
),
|
|
148
|
+
},
|
|
149
|
+
{ additionalProperties: false },
|
|
150
|
+
);
|
|
151
|
+
type ForgetParams = Static<typeof forgetSchema>;
|
|
152
|
+
/** One line per forgotten result; receipt is absent for results tagged before receipts existed. */
|
|
153
|
+
type ForgetDetails = { forgotten: { id: string; receipt?: string }[] };
|
|
154
|
+
|
|
155
|
+
/** Register the forget tool and the context hooks that apply it. */
|
|
156
|
+
export function registerForgetTool(pi: ExtensionAPI): void {
|
|
157
|
+
// Tagged results of the batch the current response is the first to see, by id.
|
|
158
|
+
let forgettable = new Map<string, { toolCallId: string; receipt?: string }>();
|
|
159
|
+
// Results named by forget during the current response, applied at its turn_end.
|
|
160
|
+
let pending = new Set<string>();
|
|
161
|
+
|
|
162
|
+
pi.on("context", (event) => {
|
|
163
|
+
forgettable = new Map();
|
|
164
|
+
const lastAssistant = event.messages.findLastIndex((message) => message.role === "assistant");
|
|
165
|
+
// Every tag still visible, older batches included: an id the model can see on more
|
|
166
|
+
// than one result cannot name a single one, so none of them is forgettable.
|
|
167
|
+
const visible = new Map<string, number>();
|
|
168
|
+
event.messages.forEach((message, index) => {
|
|
169
|
+
if (
|
|
170
|
+
message.role !== "toolResult" ||
|
|
171
|
+
message.isError ||
|
|
172
|
+
!isResultTag(message.content.at(-1), message.toolCallId)
|
|
173
|
+
)
|
|
174
|
+
return;
|
|
175
|
+
const id = resultId(message.toolCallId);
|
|
176
|
+
visible.set(id, (visible.get(id) ?? 0) + 1);
|
|
177
|
+
if (index > lastAssistant)
|
|
178
|
+
forgettable.set(id, {
|
|
179
|
+
toolCallId: message.toolCallId,
|
|
180
|
+
receipt: receiptOf(message.details),
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
for (const [id, count] of visible) if (count > 1) forgettable.delete(id);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
pi.on("turn_end", (event) => {
|
|
187
|
+
const targets = pending;
|
|
188
|
+
pending = new Set();
|
|
189
|
+
if (event.outcome !== "completed" || targets.size === 0) return;
|
|
190
|
+
const entries: ContextEditEntryDraft[] = [];
|
|
191
|
+
for (const { sourceEntry, messages } of event.context.contextEntries) {
|
|
192
|
+
if (sourceEntry.type !== "message") continue;
|
|
193
|
+
// Edit what the model saw: the projected message, which carries the tag.
|
|
194
|
+
const message = messages.find(
|
|
195
|
+
(candidate) => candidate.role === "toolResult" && targets.has(candidate.toolCallId),
|
|
196
|
+
);
|
|
197
|
+
if (message?.role !== "toolResult") continue;
|
|
198
|
+
entries.push({
|
|
199
|
+
type: "context_edit",
|
|
200
|
+
targetId: sourceEntry.id,
|
|
201
|
+
replacement: {
|
|
202
|
+
content: [
|
|
203
|
+
{
|
|
204
|
+
type: "text",
|
|
205
|
+
text: `[Result ${resultId(message.toolCallId)}: content forgotten; rerun the call to see it again.]`,
|
|
206
|
+
},
|
|
207
|
+
],
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
if (entries.length > 0) return { entries };
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
pi.registerTool({
|
|
215
|
+
name: "forget",
|
|
216
|
+
label: "forget",
|
|
217
|
+
description: `Remove read or grep results from your context once you have taken what you need. Only results from the previous step tagged [result rXXXXX] (${formatKiB(FORGET_MIN_BYTES)} or larger, or images) can be forgotten. After this response each selected result's entire content, including headers and notices, is replaced with a forgotten receipt. Save facts you still need in note. Files and session history are unchanged.`,
|
|
218
|
+
promptSnippet: "Forget read or grep results you no longer need",
|
|
219
|
+
promptGuidelines: [
|
|
220
|
+
"Right after a read or grep result tagged [result rXXXXX], call forget with its id if you will not need any of its content again; put facts you still need in note. Results from earlier steps cannot be forgotten.",
|
|
221
|
+
],
|
|
222
|
+
parameters: forgetSchema,
|
|
223
|
+
prepareArguments: createArgumentPreparer("forget", forgetSchema),
|
|
224
|
+
renderShell: "default" as const,
|
|
225
|
+
renderCall(args: ForgetParams, theme: Theme) {
|
|
226
|
+
let text =
|
|
227
|
+
theme.fg("toolTitle", theme.bold("forget")) +
|
|
228
|
+
(Array.isArray(args?.ids)
|
|
229
|
+
? theme.fg("dim", ` · ${plural(args.ids.length, "result")}`)
|
|
230
|
+
: "");
|
|
231
|
+
if (typeof args?.note === "string") text += `\n${theme.fg("dim", args.note)}`;
|
|
232
|
+
return new Text(text, 0, 0);
|
|
233
|
+
},
|
|
234
|
+
renderResult(result, { expanded }, theme, context) {
|
|
235
|
+
if (context?.isError) return renderToolError(result, theme, expanded);
|
|
236
|
+
const forgotten = result.details?.forgotten ?? [];
|
|
237
|
+
return new Text(
|
|
238
|
+
forgotten
|
|
239
|
+
.map(
|
|
240
|
+
({ id, receipt }) =>
|
|
241
|
+
(expanded && receipt ? theme.fg("dim", `${id} · `) : "") +
|
|
242
|
+
theme.fg("toolOutput", receipt ?? id),
|
|
243
|
+
)
|
|
244
|
+
.join("\n"),
|
|
245
|
+
0,
|
|
246
|
+
0,
|
|
247
|
+
);
|
|
248
|
+
},
|
|
249
|
+
async execute(_toolCallId: string, params: ForgetParams) {
|
|
250
|
+
const unknown = params.ids.filter((id) => !forgettable.has(id));
|
|
251
|
+
if (unknown.length > 0) {
|
|
252
|
+
const available = [...forgettable.keys()];
|
|
253
|
+
throw new Error(
|
|
254
|
+
`Cannot forget ${unknown.join(", ")}: only tagged read or grep results from the previous step can be forgotten.${available.length ? ` Available: ${available.join(", ")}.` : ""}`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
const forgotten = params.ids.map((id) => {
|
|
258
|
+
const { toolCallId, receipt } = forgettable.get(id)!;
|
|
259
|
+
pending.add(toolCallId);
|
|
260
|
+
return { id, receipt };
|
|
261
|
+
});
|
|
262
|
+
return {
|
|
263
|
+
content: [{ type: "text" as const, text: `Forgot ${params.ids.join(", ")}.` }],
|
|
264
|
+
details: { forgotten },
|
|
265
|
+
};
|
|
266
|
+
},
|
|
267
|
+
} satisfies ToolDefinition<typeof forgetSchema, ForgetDetails>);
|
|
268
|
+
}
|