@criogaid/pi-hashline-edit 0.6.1 → 0.8.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/README.md +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
package/src/pi/forget-tool.ts
DELETED
|
@@ -1,268 +0,0 @@
|
|
|
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
|
-
}
|
package/src/pi/forget.test.ts
DELETED
|
@@ -1,343 +0,0 @@
|
|
|
1
|
-
import assert from "node:assert/strict";
|
|
2
|
-
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { test } from "node:test";
|
|
5
|
-
import { FORGET_MIN_BYTES } from "./budgets.ts";
|
|
6
|
-
import { withResultTag } from "./forget-tool.ts";
|
|
7
|
-
import { DEFAULT_CONFIG } from "./config.ts";
|
|
8
|
-
import {
|
|
9
|
-
assertForgotten,
|
|
10
|
-
finish,
|
|
11
|
-
forgetCall,
|
|
12
|
-
openForgetSession,
|
|
13
|
-
SESSION_TIMEOUT_MS,
|
|
14
|
-
taggedResultId,
|
|
15
|
-
toolResponse,
|
|
16
|
-
toolResult,
|
|
17
|
-
} from "./forget.testing.ts";
|
|
18
|
-
|
|
19
|
-
const LOG_BODY = `build payload ${"x".repeat(FORGET_MIN_BYTES)}\nlast line\n`;
|
|
20
|
-
const PNG = Buffer.from(
|
|
21
|
-
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
|
|
22
|
-
"base64",
|
|
23
|
-
);
|
|
24
|
-
|
|
25
|
-
for (const { name, filename, body, receiptSuffix } of [
|
|
26
|
-
{ name: "ordinary log", filename: "build.log", body: LOG_BODY, receiptSuffix: " · lines 1–2" },
|
|
27
|
-
{
|
|
28
|
-
name: "NUL log containing a row-like source line",
|
|
29
|
-
filename: "build.log",
|
|
30
|
-
body: `${LOG_BODY}\0\n1│source text\n`,
|
|
31
|
-
receiptSuffix: "",
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
name: "UTF-8 log containing a Unicode line separator",
|
|
35
|
-
filename: "build.log",
|
|
36
|
-
body: `before\u2028${LOG_BODY}`,
|
|
37
|
-
receiptSuffix: " · lines 1–2",
|
|
38
|
-
},
|
|
39
|
-
{ name: "PNG image", filename: "picture.png", body: PNG, receiptSuffix: " · image" },
|
|
40
|
-
]) {
|
|
41
|
-
test(`${name} read then forgotten → the next request contains only a receipt`, {
|
|
42
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
43
|
-
}, async (t) => {
|
|
44
|
-
const f = await openForgetSession(t);
|
|
45
|
-
await writeFile(join(f.cwd, filename), body);
|
|
46
|
-
await f.prompt(
|
|
47
|
-
toolResponse(f.read("read-log", filename)),
|
|
48
|
-
(messages) => toolResponse(forgetCall(messages, "read-log")),
|
|
49
|
-
finish,
|
|
50
|
-
);
|
|
51
|
-
const original = toolResult(f.requests[1], "read-log");
|
|
52
|
-
const id = taggedResultId(original);
|
|
53
|
-
assert.ok(id);
|
|
54
|
-
if (typeof body === "string") {
|
|
55
|
-
for (const line of body.trimEnd().split("\n")) {
|
|
56
|
-
assert.ok(
|
|
57
|
-
original.content.some((block) => block.type === "text" && block.text.includes(line)),
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
} else {
|
|
61
|
-
assert.ok(original.content.some((block) => block.type === "image"));
|
|
62
|
-
}
|
|
63
|
-
assert.equal(f.requests.length, 3, "A standalone forget must allow the model to continue");
|
|
64
|
-
const forgotten = toolResult(f.requests[2], "read-log");
|
|
65
|
-
const remainingText = forgotten.content
|
|
66
|
-
.filter((block) => block.type === "text")
|
|
67
|
-
.map((block) => block.text)
|
|
68
|
-
.join("\n");
|
|
69
|
-
assert.ok(
|
|
70
|
-
!remainingText.includes("build payload"),
|
|
71
|
-
"Consumed file content must not be sent again",
|
|
72
|
-
);
|
|
73
|
-
assert.ok(!remainingText.includes(filename), "File headers are forgotten with the body");
|
|
74
|
-
assertForgotten(forgotten, id);
|
|
75
|
-
const receipt = `${join(f.cwd, filename)}${receiptSuffix}`;
|
|
76
|
-
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
|
|
77
|
-
assert.ok(f.renderForgetCard().includes(receipt));
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
test("forget in a mixed tool batch → work continues and unselected results stay intact", {
|
|
82
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
83
|
-
}, async (t) => {
|
|
84
|
-
const f = await openForgetSession(t);
|
|
85
|
-
for (const filename of ["build.log", "test.log", "keep.log"]) {
|
|
86
|
-
await writeFile(join(f.cwd, filename), LOG_BODY);
|
|
87
|
-
}
|
|
88
|
-
await writeFile(join(f.cwd, "next.txt"), "next task");
|
|
89
|
-
await f.prompt(
|
|
90
|
-
toolResponse(
|
|
91
|
-
f.read("selected"),
|
|
92
|
-
f.read("selected-too", "test.log"),
|
|
93
|
-
f.read("kept", "keep.log"),
|
|
94
|
-
),
|
|
95
|
-
(messages) =>
|
|
96
|
-
toolResponse(forgetCall(messages, "selected", "selected-too"), f.read("next", "next.txt")),
|
|
97
|
-
finish,
|
|
98
|
-
);
|
|
99
|
-
assert.equal(f.requests.length, 3);
|
|
100
|
-
for (const callId of ["selected", "selected-too"]) {
|
|
101
|
-
const id = taggedResultId(toolResult(f.requests[1], callId));
|
|
102
|
-
assert.ok(id);
|
|
103
|
-
assertForgotten(toolResult(f.requests[2], callId), id);
|
|
104
|
-
}
|
|
105
|
-
assert.deepEqual(toolResult(f.requests[2], "kept"), toolResult(f.requests[1], "kept"));
|
|
106
|
-
assert.equal(toolResult(f.requests[2], "next").isError, false);
|
|
107
|
-
const expected = ["selected", "selected-too"].map((callId, index) => ({
|
|
108
|
-
id: taggedResultId(toolResult(f.requests[1], callId)),
|
|
109
|
-
receipt: `${join(f.cwd, index === 0 ? "build.log" : "test.log")} · lines 1–2`,
|
|
110
|
-
}));
|
|
111
|
-
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: expected });
|
|
112
|
-
const displayed = f.renderForgetCard();
|
|
113
|
-
assert.equal(displayed.split("\n")[0].trimEnd(), `forget · ${expected.length} results`);
|
|
114
|
-
assert.doesNotMatch(displayed, /Forgotten ·/);
|
|
115
|
-
const expanded = f.renderForgetCard(true);
|
|
116
|
-
for (const { id, receipt } of expected) {
|
|
117
|
-
assert.ok(id);
|
|
118
|
-
assert.ok(displayed.includes(receipt));
|
|
119
|
-
assert.ok(!displayed.includes(id));
|
|
120
|
-
assert.ok(expanded.includes(`${id} · ${receipt}`));
|
|
121
|
-
}
|
|
122
|
-
assert.ok(!displayed.includes("keep.log"));
|
|
123
|
-
const payload = JSON.stringify(await f.requestPayload(2));
|
|
124
|
-
assert.doesNotMatch(payload, /"forgetReceipt"|"forgotten":/);
|
|
125
|
-
for (const { receipt } of expected) assert.ok(!payload.includes(receipt));
|
|
126
|
-
const response = toolResult(f.requests[2], "forget-call");
|
|
127
|
-
assert.deepEqual(response.content, f.rawResult("forget-call").content);
|
|
128
|
-
for (const block of response.content) {
|
|
129
|
-
if (block.type === "text") assert.ok(payload.includes(block.text));
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
|
|
133
|
-
for (const mode of ["pagination", "byte truncation"] as const) {
|
|
134
|
-
test(`read stops at ${mode} → forget receipt names only the returned lines`, {
|
|
135
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
136
|
-
}, async (t) => {
|
|
137
|
-
const f = await openForgetSession(t);
|
|
138
|
-
const path = join(f.cwd, "build.log");
|
|
139
|
-
const maxReadBytes = DEFAULT_CONFIG.read.maxKiB * 1024;
|
|
140
|
-
const trailingLine = mode === "byte truncation" ? "y".repeat(maxReadBytes) : "next page";
|
|
141
|
-
await writeFile(path, `skip this line\n${LOG_BODY}${trailingLine}\n`);
|
|
142
|
-
const read = f.read("read-log");
|
|
143
|
-
await f.prompt(
|
|
144
|
-
toolResponse({
|
|
145
|
-
...read,
|
|
146
|
-
arguments: { ...read.arguments, offset: 2, limit: mode === "pagination" ? 2 : 3 },
|
|
147
|
-
}),
|
|
148
|
-
(messages) => toolResponse(forgetCall(messages, "read-log")),
|
|
149
|
-
finish,
|
|
150
|
-
);
|
|
151
|
-
const id = taggedResultId(toolResult(f.requests[1], "read-log"));
|
|
152
|
-
assert.ok(id);
|
|
153
|
-
const receipt = `${path} · lines 2–3${mode === "byte truncation" ? " · truncated" : ""}`;
|
|
154
|
-
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
|
|
155
|
-
assert.ok(f.renderForgetCard().includes(receipt));
|
|
156
|
-
assertForgotten(toolResult(f.requests[2], "read-log"), id);
|
|
157
|
-
const details = f.rawResult("read-log").details;
|
|
158
|
-
assert.ok(details && typeof details === "object");
|
|
159
|
-
assert.ok(mode === "pagination" ? "pagination" in details : "truncation" in details);
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
test("forget with a note → calls, saved facts, source bytes and raw session remain", {
|
|
164
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
165
|
-
}, async (t) => {
|
|
166
|
-
const f = await openForgetSession(t);
|
|
167
|
-
const path = join(f.cwd, "build.log");
|
|
168
|
-
const note = "Build failed during dependency installation.";
|
|
169
|
-
const read = f.read("read-log");
|
|
170
|
-
await writeFile(path, LOG_BODY);
|
|
171
|
-
await f.prompt(
|
|
172
|
-
toolResponse(read),
|
|
173
|
-
(messages) => {
|
|
174
|
-
const call = forgetCall(messages, "read-log");
|
|
175
|
-
return toolResponse({ ...call, arguments: { ...call.arguments, note } });
|
|
176
|
-
},
|
|
177
|
-
finish,
|
|
178
|
-
);
|
|
179
|
-
const calls = f.requests[2].flatMap((message) =>
|
|
180
|
-
message.role === "assistant"
|
|
181
|
-
? message.content.filter((block) => block.type === "toolCall")
|
|
182
|
-
: [],
|
|
183
|
-
);
|
|
184
|
-
assert.deepEqual(
|
|
185
|
-
calls.find((call) => call.id === read.id),
|
|
186
|
-
read,
|
|
187
|
-
);
|
|
188
|
-
assert.equal(calls.find((call) => call.name === "forget")?.arguments.note, note);
|
|
189
|
-
const original = f.sessionManager
|
|
190
|
-
.getEntries()
|
|
191
|
-
.find(
|
|
192
|
-
(entry) =>
|
|
193
|
-
entry.type === "message" &&
|
|
194
|
-
entry.message.role === "toolResult" &&
|
|
195
|
-
entry.message.toolCallId === read.id,
|
|
196
|
-
);
|
|
197
|
-
assert.ok(original?.type === "message" && original.message.role === "toolResult");
|
|
198
|
-
assert.deepEqual(original.message.content, toolResult(f.requests[1], read.id).content);
|
|
199
|
-
assert.equal(await readFile(path, "utf8"), LOG_BODY);
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
for (const invalid of ["old result", "unknown result"] as const) {
|
|
203
|
-
test(`eligible id combined with ${invalid} → the whole forget call is rejected`, {
|
|
204
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
205
|
-
}, async (t) => {
|
|
206
|
-
const f = await openForgetSession(t);
|
|
207
|
-
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
208
|
-
await f.prompt(
|
|
209
|
-
toolResponse(f.read("old")),
|
|
210
|
-
toolResponse(f.read("current")),
|
|
211
|
-
(messages) => {
|
|
212
|
-
const current = forgetCall(messages, "current");
|
|
213
|
-
const currentId = taggedResultId(toolResult(messages, "current"));
|
|
214
|
-
assert.ok(currentId);
|
|
215
|
-
const old = taggedResultId(toolResult(messages, "old"));
|
|
216
|
-
assert.ok(old);
|
|
217
|
-
const invalidId = invalid === "old result" ? old : "r00000";
|
|
218
|
-
assert.notEqual(taggedResultId(toolResult(messages, "current")), invalidId);
|
|
219
|
-
return toolResponse({ ...current, arguments: { ids: [currentId, invalidId] } });
|
|
220
|
-
},
|
|
221
|
-
finish,
|
|
222
|
-
);
|
|
223
|
-
assert.equal(toolResult(f.requests[3], "forget-call").isError, true);
|
|
224
|
-
for (const id of ["old", "current"]) {
|
|
225
|
-
assert.deepEqual(toolResult(f.requests[3], id), toolResult(f.requests[2], id));
|
|
226
|
-
}
|
|
227
|
-
assert.ok(!f.sessionManager.getEntries().some((entry) => entry.type === "context_edit"));
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
for (const invalid of [
|
|
232
|
-
"empty ids",
|
|
233
|
-
"duplicate ids",
|
|
234
|
-
"malformed id",
|
|
235
|
-
"multiple invalid fields",
|
|
236
|
-
] as const) {
|
|
237
|
-
test(`${invalid} from a model call → schema rejection leaves the result intact`, {
|
|
238
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
239
|
-
}, async (t) => {
|
|
240
|
-
const f = await openForgetSession(t);
|
|
241
|
-
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
242
|
-
await f.prompt(
|
|
243
|
-
toolResponse(f.read("read-log")),
|
|
244
|
-
(messages) => {
|
|
245
|
-
const id = taggedResultId(toolResult(messages, "read-log"));
|
|
246
|
-
assert.ok(id);
|
|
247
|
-
const ids =
|
|
248
|
-
invalid === "empty ids"
|
|
249
|
-
? []
|
|
250
|
-
: invalid === "duplicate ids"
|
|
251
|
-
? [id, id]
|
|
252
|
-
: ["not-a-result-id"];
|
|
253
|
-
return toolResponse({
|
|
254
|
-
type: "toolCall",
|
|
255
|
-
id: "forget-call",
|
|
256
|
-
name: "forget",
|
|
257
|
-
arguments: invalid === "multiple invalid fields" ? { ids, note: "" } : { ids },
|
|
258
|
-
});
|
|
259
|
-
},
|
|
260
|
-
finish,
|
|
261
|
-
);
|
|
262
|
-
const rejection = toolResult(f.requests[2], "forget-call");
|
|
263
|
-
assert.equal(rejection.isError, true);
|
|
264
|
-
if (invalid === "multiple invalid fields") {
|
|
265
|
-
const text = rejection.content
|
|
266
|
-
.filter((block) => block.type === "text")
|
|
267
|
-
.map((block) => block.text)
|
|
268
|
-
.join("\n");
|
|
269
|
-
assert.match(text, /\n - ids/);
|
|
270
|
-
assert.match(text, /\n - note:/);
|
|
271
|
-
}
|
|
272
|
-
assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
function collidingToolCallIds() {
|
|
277
|
-
const maxCandidateCalls = 20_000;
|
|
278
|
-
const seen = new Map<string, string>();
|
|
279
|
-
for (let index = 0; index < maxCandidateCalls; index++) {
|
|
280
|
-
const callId = `call_collision_${index}`;
|
|
281
|
-
const id = taggedResultId(
|
|
282
|
-
withResultTag(
|
|
283
|
-
callId,
|
|
284
|
-
{ content: [{ type: "text", text: LOG_BODY }] },
|
|
285
|
-
true,
|
|
286
|
-
() => "build.log",
|
|
287
|
-
),
|
|
288
|
-
);
|
|
289
|
-
assert.ok(id);
|
|
290
|
-
const earlier = seen.get(id);
|
|
291
|
-
if (earlier) return [earlier, callId];
|
|
292
|
-
seen.set(id, callId);
|
|
293
|
-
}
|
|
294
|
-
throw new Error("No colliding public result tags found within the fixture search bound");
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
for (const batch of ["same batch", "older visible batch"] as const) {
|
|
298
|
-
test(`distinct read calls have colliding tags in the ${batch} → neither result is forgotten`, {
|
|
299
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
300
|
-
}, async (t) => {
|
|
301
|
-
const f = await openForgetSession(t);
|
|
302
|
-
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
303
|
-
// Find real call ids that collide, then let actual reads produce the tagged results.
|
|
304
|
-
const [first, second] = collidingToolCallIds();
|
|
305
|
-
const reads =
|
|
306
|
-
batch === "same batch"
|
|
307
|
-
? [toolResponse(f.read(first), f.read(second))]
|
|
308
|
-
: [toolResponse(f.read(first)), toolResponse(f.read(second))];
|
|
309
|
-
await f.prompt(
|
|
310
|
-
...reads,
|
|
311
|
-
(messages) => {
|
|
312
|
-
assert.equal(
|
|
313
|
-
taggedResultId(toolResult(messages, first)),
|
|
314
|
-
taggedResultId(toolResult(messages, second)),
|
|
315
|
-
);
|
|
316
|
-
return toolResponse(forgetCall(messages, second));
|
|
317
|
-
},
|
|
318
|
-
finish,
|
|
319
|
-
);
|
|
320
|
-
const before = f.requests[reads.length];
|
|
321
|
-
const after = f.requests[reads.length + 1];
|
|
322
|
-
assert.equal(toolResult(after, "forget-call").isError, true);
|
|
323
|
-
assert.deepEqual(toolResult(after, first), toolResult(before, first));
|
|
324
|
-
assert.deepEqual(toolResult(after, second), toolResult(before, second));
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
test("model output is truncated while requesting forget → Pi rejects the call and retains the result", {
|
|
329
|
-
timeout: SESSION_TIMEOUT_MS,
|
|
330
|
-
}, async (t) => {
|
|
331
|
-
const f = await openForgetSession(t);
|
|
332
|
-
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
333
|
-
await f.prompt(
|
|
334
|
-
toolResponse(f.read("read-log")),
|
|
335
|
-
(messages) => ({
|
|
336
|
-
content: [forgetCall(messages, "read-log")],
|
|
337
|
-
stopReason: "length",
|
|
338
|
-
}),
|
|
339
|
-
finish,
|
|
340
|
-
);
|
|
341
|
-
assert.equal(toolResult(f.requests[2], "forget-call").isError, true);
|
|
342
|
-
assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
|
|
343
|
-
});
|