@criogaid/pi-hashline-edit 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,21 +1,25 @@
1
1
  /**
2
- * forget: the model drops read/grep results it no longer needs from model context.
2
+ * forget: the model drops tagged inspection output it no longer needs from context.
3
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.
4
+ * Direct read/grep results and codemode outputs containing successful inspections
5
+ * are tagged when they meet the output budget. Nested read/grep results lose their
6
+ * tags before reaching the script: Pi persists only the script's final output,
7
+ * which is forgotten as one result even when the script transforms or mixes data.
8
+ * A tag is the `resultId` fact of the result's report (report.ts), owned by
9
+ * forget alone. Before each request, the `context` handler records the tagged results
10
+ * of the previous response, the only ones forget may name. Other named ids are reported
11
+ * without blocking the rest, since no later response can forget them either. At
12
+ * `turn_end` of a completed response, branch-local context edits replace each named
13
+ * result with a receipt report.
11
14
  * The tool call and any facts saved in forget's note remain in context.
12
15
  *
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.
16
+ * Restricting forget to the previous response bounds how much of the next request
17
+ * changes, and how often: it differs from the earliest replaced result on, which covers
18
+ * later results of the same batch, the response that requested the edit, and its tool
19
+ * results. Messages before that result are unchanged. Editing an older result would
20
+ * change every later message, and forgetting one batch across several responses would
21
+ * change the request once per response. Raw session entries stay intact; navigating
22
+ * before the edit shows the original result again.
19
23
  *
20
24
  * @module pi-hashline-edit/pi
21
25
  */
@@ -30,26 +34,61 @@ import type {
30
34
  } from "@earendil-works/pi-coding-agent";
31
35
  import { Text } from "@earendil-works/pi-tui";
32
36
  import { Type, type Static } from "typebox";
33
- import { FORGET_MIN_BYTES, formatKiB } from "./budgets.ts";
37
+ import {
38
+ defaultOutputBudgets,
39
+ FORGET_MIN_BYTES,
40
+ formatKiB,
41
+ type OutputBudgetProvider,
42
+ } from "./budgets.ts";
34
43
  import { renderToolError } from "./render.ts";
44
+ import {
45
+ decodeReport,
46
+ reportOf,
47
+ reportResult,
48
+ runTool,
49
+ type Report,
50
+ type ReportDetails,
51
+ } from "./report.ts";
52
+ import type { SuccessReport } from "./report-schema.ts";
53
+ import { HashlineError } from "../core/errors.ts";
35
54
  import { createArgumentPreparer } from "./argument-validation.ts";
36
55
 
37
56
  const RESULT_ID = "r[0-9a-f]{5}";
38
- const RESULT_TAG = new RegExp(`^\\[result ${RESULT_ID}\\]$`);
57
+ const CODEMODE_FORGET_SCOPE = "entire codemode output, including all text and images";
58
+ const CODEMODE_FORGET_RECEIPT = "codemode · entire output";
39
59
 
40
60
  /** Short id shown to the model; it only has to be unique within one tool batch. */
41
61
  function resultId(toolCallId: string): string {
42
62
  return `r${createHash("sha256").update(toolCallId).digest("hex").slice(0, 5)}`;
43
63
  }
44
64
 
45
- function resultTag(toolCallId: string): string {
46
- return `[result ${resultId(toolCallId)}]`;
65
+ type ResultContent = AgentToolResult<unknown>["content"];
66
+
67
+ /** A success report of a tool whose results can be tagged. */
68
+ type TaggedReport = Extract<SuccessReport, { tool: "read" | "grep" | "codemode" }>;
69
+
70
+ /** The report if it carries the call's id; the wire schema admits resultId only on taggable successes. */
71
+ function tagOf(report: Report | undefined, toolCallId: string): TaggedReport | undefined {
72
+ return report?.resultId === resultId(toolCallId) ? (report as TaggedReport) : undefined;
47
73
  }
48
74
 
49
- type ResultContent = AgentToolResult<unknown>["content"];
75
+ /** The report the model saw tagged: the result's last block, naming the call's id. */
76
+ function taggedReport(
77
+ content: ResultContent,
78
+ toolCallId: string,
79
+ toolName: string,
80
+ ): TaggedReport | undefined {
81
+ const last = content.at(-1);
82
+ return last?.type === "text" ? tagOf(decodeReport(last.text, toolName), toolCallId) : undefined;
83
+ }
50
84
 
51
- function isResultTag(block: ResultContent[number] | undefined, toolCallId: string): boolean {
52
- return block?.type === "text" && block.text === resultTag(toolCallId);
85
+ /** Text results below the threshold save too little to be worth forgetting; images always qualify. */
86
+ function worthForgetting(content: ResultContent): boolean {
87
+ const bytes = content.reduce(
88
+ (sum, block) => sum + (block.type === "text" ? Buffer.byteLength(block.text) : 0),
89
+ 0,
90
+ );
91
+ return content.some((block) => block.type === "image") || bytes >= FORGET_MIN_BYTES;
53
92
  }
54
93
 
55
94
  /** Pattern text shown in a grep receipt before it is cut with an ellipsis. */
@@ -60,7 +99,7 @@ const MAX_RECEIPT_PATTERN_CHARS = 60;
60
99
  * to the model, so the forget card can name what was forgotten without adding context.
61
100
  */
62
101
  export interface ForgetReceiptDetails {
63
- forgetReceipt?: string;
102
+ readonly forgetReceipt?: string;
64
103
  }
65
104
 
66
105
  function plural(count: number, noun: string, pluralForm = `${noun}s`): string {
@@ -96,39 +135,31 @@ export function grepReceipt(
96
135
  }
97
136
 
98
137
  /**
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.
138
+ * Build a successful read/grep result, tagged when forgetting is enabled and the
139
+ * result is eligible. Only then evaluate createReceipt and keep its display text in details.
101
140
  */
102
- export function withResultTag<T extends { content: ResultContent; details?: unknown }>(
141
+ export function withResultTag<TDetails extends object | undefined>(
103
142
  toolCallId: string,
104
- result: T,
143
+ parts: {
144
+ report: Extract<TaggedReport, { tool: "read" | "grep" }>;
145
+ payload: ResultContent;
146
+ details?: TDetails;
147
+ },
105
148
  enabled: boolean,
106
149
  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;
150
+ ): AgentToolResult<TDetails & ReportDetails & ForgetReceiptDetails> {
151
+ const { report, payload, details } = parts;
152
+ const untagged = reportResult(report, payload, details);
153
+ if (!enabled || !worthForgetting(untagged.content)) return untagged;
154
+ return reportResult({ ...report, resultId: resultId(toolCallId) }, payload, {
155
+ ...details,
156
+ forgetReceipt: createReceipt(),
157
+ } as TDetails & ForgetReceiptDetails);
125
158
  }
126
159
 
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) };
160
+ /** Every tagged result carries its receipt; optional chaining only keeps foreign details from throwing. */
161
+ function receiptOf(details: unknown): string {
162
+ return (details as ForgetReceiptDetails | undefined)?.forgetReceipt as string;
132
163
  }
133
164
 
134
165
  const forgetSchema = Type.Object(
@@ -136,7 +167,7 @@ const forgetSchema = Type.Object(
136
167
  ids: Type.Array(Type.String({ pattern: `^${RESULT_ID}$` }), {
137
168
  minItems: 1,
138
169
  uniqueItems: true,
139
- description: "Result ids to forget, from the [result rXXXXX] tags of the previous step.",
170
+ description: "resultId values to forget.",
140
171
  }),
141
172
  note: Type.Optional(
142
173
  Type.String({
@@ -149,16 +180,77 @@ const forgetSchema = Type.Object(
149
180
  { additionalProperties: false },
150
181
  );
151
182
  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 }[] };
183
+ /** One line per forgotten result. */
184
+ type ForgetDetails = { forgotten?: { id: string; receipt: string }[] } & Partial<ReportDetails>;
154
185
 
155
186
  /** Register the forget tool and the context hooks that apply it. */
156
- export function registerForgetTool(pi: ExtensionAPI): void {
187
+ export function registerForgetTool(
188
+ pi: ExtensionAPI,
189
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
190
+ ): void {
157
191
  // 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 }>();
192
+ let forgettable = new Map<string, { toolCallId: string; receipt: string }>();
159
193
  // Results named by forget during the current response, applied at its turn_end.
160
194
  let pending = new Set<string>();
161
195
 
196
+ pi.on("tool_result", (event) => {
197
+ if (
198
+ !event.parentToolCallId ||
199
+ (event.toolName !== "read" && event.toolName !== "grep") ||
200
+ !taggedReport(event.content, event.toolCallId, event.toolName)
201
+ )
202
+ return;
203
+ // A nested id cannot identify a transcript entry: rebuild the report without it.
204
+ const report = tagOf(reportOf(event), event.toolCallId);
205
+ if (!report) return;
206
+ const { forgetReceipt: _receipt, ...details } = (event.details ?? {}) as ForgetReceiptDetails;
207
+ const result = reportResult(
208
+ { ...report, resultId: undefined },
209
+ event.content.slice(0, -1),
210
+ details,
211
+ );
212
+ // Preserve structured results while removing the tag.
213
+ return { ...result, structuredContent: event.structuredContent };
214
+ });
215
+
216
+ pi.on("message_end", (event) => {
217
+ const message = event.message;
218
+ if (
219
+ message.role !== "toolResult" ||
220
+ message.toolName !== "codemode" ||
221
+ message.isError ||
222
+ !message.nestedCalls?.calls.some(
223
+ (call) =>
224
+ call.status === "ok" &&
225
+ (call.name === "read" ||
226
+ (call.name === "grep" &&
227
+ call.arguments !== undefined &&
228
+ (call.arguments.outputMode == null || call.arguments.outputMode === "content"))),
229
+ )
230
+ )
231
+ return;
232
+ if (!worthForgetting(message.content)) return;
233
+ // The codemode output is not ours: its tag is a report of forget facts alone.
234
+ const tag = reportResult(
235
+ {
236
+ tool: "codemode",
237
+ resultId: resultId(message.toolCallId),
238
+ forgetScope: CODEMODE_FORGET_SCOPE,
239
+ },
240
+ message.content,
241
+ );
242
+ return {
243
+ message: {
244
+ ...message,
245
+ content: tag.content,
246
+ details: {
247
+ ...(message.details as object | undefined),
248
+ forgetReceipt: CODEMODE_FORGET_RECEIPT,
249
+ },
250
+ },
251
+ };
252
+ });
253
+
162
254
  pi.on("context", (event) => {
163
255
  forgettable = new Map();
164
256
  const lastAssistant = event.messages.findLastIndex((message) => message.role === "assistant");
@@ -169,7 +261,7 @@ export function registerForgetTool(pi: ExtensionAPI): void {
169
261
  if (
170
262
  message.role !== "toolResult" ||
171
263
  message.isError ||
172
- !isResultTag(message.content.at(-1), message.toolCallId)
264
+ !taggedReport(message.content, message.toolCallId, message.toolName)
173
265
  )
174
266
  return;
175
267
  const id = resultId(message.toolCallId);
@@ -195,16 +287,17 @@ export function registerForgetTool(pi: ExtensionAPI): void {
195
287
  (candidate) => candidate.role === "toolResult" && targets.has(candidate.toolCallId),
196
288
  );
197
289
  if (message?.role !== "toolResult") continue;
290
+ const tagged = taggedReport(message.content, message.toolCallId, message.toolName);
291
+ if (!tagged) continue;
198
292
  entries.push({
199
293
  type: "context_edit",
200
294
  targetId: sourceEntry.id,
201
295
  replacement: {
202
- content: [
203
- {
204
- type: "text",
205
- text: `[Result ${resultId(message.toolCallId)}: content forgotten; rerun the call to see it again.]`,
206
- },
207
- ],
296
+ content: reportResult({
297
+ tool: tagged.tool,
298
+ resultId: tagged.resultId,
299
+ contentForgotten: true,
300
+ }).content,
208
301
  },
209
302
  });
210
303
  }
@@ -214,13 +307,14 @@ export function registerForgetTool(pi: ExtensionAPI): void {
214
307
  pi.registerTool({
215
308
  name: "forget",
216
309
  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",
310
+ description: `Remove tagged inspection output from your context. Only results of your previous response whose report has a resultId (${formatKiB(FORGET_MIN_BYTES)} or larger, or images) can be forgotten; later responses cannot forget them. After this response each selected result's entire content, including its report, is replaced with a forgotten receipt. A codemode resultId covers its entire output, including other results printed by the script. Files and session history are unchanged.`,
311
+ promptSnippet: "Forget tagged inspection output you no longer need",
219
312
  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.",
313
+ "In the response right after results with a resultId, forget each one unless you will need its text after that response's tool results return; anchors you pass to edit in that same response are already in the edit call, so using them is no reason to keep it. First copy any facts you still need into note.",
314
+ "Make that one forget call alongside the response's other tool calls, naming every result to forget; when the response makes no other tool call, skip forget.",
221
315
  ],
222
316
  parameters: forgetSchema,
223
- prepareArguments: createArgumentPreparer("forget", forgetSchema),
317
+ prepareArguments: createArgumentPreparer("forget", forgetSchema, undefined, budgets),
224
318
  renderShell: "default" as const,
225
319
  renderCall(args: ForgetParams, theme: Theme) {
226
320
  let text =
@@ -233,36 +327,41 @@ export function registerForgetTool(pi: ExtensionAPI): void {
233
327
  },
234
328
  renderResult(result, { expanded }, theme, context) {
235
329
  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,
330
+ const lines = (result.details?.forgotten ?? []).map(
331
+ ({ id, receipt }) =>
332
+ (expanded ? theme.fg("dim", `${id} · `) : "") + theme.fg("toolOutput", receipt),
247
333
  );
334
+ const notForgettable = result.details?.report?.notForgettable ?? [];
335
+ if (notForgettable.length > 0)
336
+ lines.push(theme.fg("warning", `not forgettable: ${notForgettable.join(", ")}`));
337
+ return new Text(lines.join("\n"), 0, 0);
248
338
  },
249
339
  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(", ")}.` : ""}`,
340
+ return runTool("forget", { budget: budgets() }, async () => {
341
+ // Forget what can be forgotten: no later response could retry the rest.
342
+ const named = params.ids.filter((id) => forgettable.has(id));
343
+ const notForgettable = params.ids.filter((id) => !forgettable.has(id));
344
+ if (named.length === 0)
345
+ throw new HashlineError(
346
+ "NOT_FORGETTABLE",
347
+ "No id names a tagged result of the previous response.",
348
+ { facts: { notForgettable } },
349
+ );
350
+ const forgotten = named.map((id) => {
351
+ const { toolCallId, receipt } = forgettable.get(id)!;
352
+ pending.add(toolCallId);
353
+ return { id, receipt };
354
+ });
355
+ return reportResult(
356
+ {
357
+ tool: "forget",
358
+ forgotten: named,
359
+ ...(notForgettable.length > 0 ? { notForgettable } : {}),
360
+ },
361
+ [],
362
+ { forgotten },
255
363
  );
256
- }
257
- const forgotten = params.ids.map((id) => {
258
- const { toolCallId, receipt } = forgettable.get(id)!;
259
- pending.add(toolCallId);
260
- return { id, receipt };
261
364
  });
262
- return {
263
- content: [{ type: "text" as const, text: `Forgot ${params.ids.join(", ")}.` }],
264
- details: { forgotten },
265
- };
266
365
  },
267
366
  } satisfies ToolDefinition<typeof forgetSchema, ForgetDetails>);
268
367
  }