@lune_99/pi-compaction 0.0.0-stage → 0.2.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.
@@ -0,0 +1,420 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { ClassifierContext, ClassifierModel, TextContent, Usage } from "@earendil-works/pi-ai";
3
+ import {
4
+ estimateTokens,
5
+ type ExtensionContext,
6
+ type SessionBeforeCompactEvent,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { CompactionPolicy } from "../options.ts";
9
+ import {
10
+ candidateContext,
11
+ chunkResult,
12
+ collectReviewInput,
13
+ indexTools,
14
+ type ProtectedTool,
15
+ type ResultChunk,
16
+ type ToolPair,
17
+ } from "./candidates.ts";
18
+ import { isClassifierOverflow, runRequests } from "./classification.ts";
19
+
20
+ const CHUNK_CHARS = 4_000;
21
+
22
+ const SAFE_TO_DROP_QUESTION = {
23
+ type: "bool",
24
+ instructions:
25
+ "Estimate whether this fragment of a tool result can be omitted from future model context without removing unique information that is still useful for continuing the current task. Judge the fragment relative to the surrounding task context, tool call, arguments, and recorded outcome. A fragment is safe to drop when its useful information is already reflected elsewhere, has been superseded, is merely transient execution detail, or is no longer relevant to the remaining work. Do not preserve a fragment merely because it could hypothetically be useful later. Use the probability to express uncertainty.",
26
+ criteria: {
27
+ true: "Dropping this fragment would not remove unique actionable information needed to continue the task. Its relevant information is already captured elsewhere, superseded, redundant, transient, or irrelevant.",
28
+ false: "This fragment contains unique information that may materially affect subsequent reasoning or actions, such as unresolved findings, current state, required values, errors that still matter, or evidence not preserved elsewhere.",
29
+ },
30
+ } as const;
31
+
32
+ export type ChunkDecision =
33
+ | {
34
+ readonly chunkId: string;
35
+ readonly probability: number;
36
+ readonly action: "keep" | "drop";
37
+ }
38
+ | {
39
+ readonly chunkId: string;
40
+ readonly action: "keep" | "placeholder";
41
+ readonly reason: "classifier-context-window";
42
+ };
43
+
44
+ export interface BudgetFallback {
45
+ readonly candidateId: string;
46
+ readonly stage: "chunks";
47
+ readonly action: "placeholder";
48
+ readonly estimatedTokens: number;
49
+ }
50
+
51
+ export interface ToolReviewReport {
52
+ readonly model: string;
53
+ readonly pricingKnown: boolean;
54
+ readonly protectedTools: readonly ProtectedTool[];
55
+ readonly candidateTools: number;
56
+ readonly chunks: readonly ResultChunk[];
57
+ readonly chunkDecisions: readonly ChunkDecision[];
58
+ readonly removedCalls: readonly string[];
59
+ readonly oversizedRequests: number;
60
+ readonly requests: number;
61
+ readonly requestBudget: number;
62
+ readonly budgetFallbacks: readonly BudgetFallback[];
63
+ readonly usage: readonly Usage[];
64
+ /** Serialized native message payload size, including metadata; not summary prompt tokens. */
65
+ readonly charsBefore: number;
66
+ /** The same size after the per-result truncation cap, before any classifier decision. */
67
+ readonly charsAfterTruncation: number;
68
+ readonly charsAfter: number;
69
+ }
70
+
71
+ export interface ToolReviewProgress {
72
+ readonly stage: "chunks";
73
+ readonly candidateTools: number;
74
+ readonly protectedTools: number;
75
+ readonly completedBatches: number;
76
+ readonly totalBatches: number;
77
+ }
78
+
79
+ export async function reviewToolHistory(
80
+ event: SessionBeforeCompactEvent,
81
+ ctx: ExtensionContext,
82
+ policy: CompactionPolicy,
83
+ classifier: ClassifierModel<string>,
84
+ concurrency: number,
85
+ signal: AbortSignal,
86
+ progress: (update: ToolReviewProgress) => void,
87
+ ): Promise<{
88
+ messagesToSummarize: AgentMessage[];
89
+ turnPrefixMessages: AgentMessage[];
90
+ report: ToolReviewReport;
91
+ }> {
92
+ signal.throwIfAborted();
93
+ if (!Number.isSafeInteger(classifier.contextWindow) || classifier.contextWindow <= 0)
94
+ throw new Error("Classifier contextWindow must be a positive integer");
95
+ const budget = Math.floor(classifier.contextWindow * 0.9);
96
+ const { preparation, projection } = collectReviewInput(event, ctx);
97
+ const index = indexTools(
98
+ preparation.messagesToSummarize,
99
+ preparation.turnPrefixMessages,
100
+ projection,
101
+ preparation.firstKeptEntryId,
102
+ policy,
103
+ );
104
+ const chunks = index.pairs.flatMap((pair) => chunkResult(pair, CHUNK_CHARS));
105
+ const contexts = new Map(
106
+ index.pairs.map((pair) => [pair.id, candidateContext(pair, index.locations)]),
107
+ );
108
+ const decisions = new Map<string, ChunkDecision>();
109
+ const fallbacks: BudgetFallback[] = [];
110
+ const pending: { chunkId: string; request: ClassifierContext }[] = [];
111
+ for (const chunk of chunks) {
112
+ signal.throwIfAborted();
113
+ const request: ClassifierContext = {
114
+ state: { ...contexts.get(chunk.toolCallId)!, result: chunk.text },
115
+ questions: { safeToDrop: SAFE_TO_DROP_QUESTION },
116
+ };
117
+ // Pi estimates chat messages; the margin covers classifier protocol framing.
118
+ const estimatedTokens = Math.ceil(
119
+ estimateTokens({ role: "user", content: JSON.stringify(request), timestamp: 0 }) *
120
+ (4 / 3),
121
+ );
122
+ if (estimatedTokens > budget) {
123
+ decisions.set(chunk.id, {
124
+ chunkId: chunk.id,
125
+ action: "placeholder",
126
+ reason: "classifier-context-window",
127
+ });
128
+ fallbacks.push({
129
+ candidateId: chunk.id,
130
+ stage: "chunks",
131
+ action: "placeholder",
132
+ estimatedTokens,
133
+ });
134
+ } else {
135
+ pending.push({ chunkId: chunk.id, request });
136
+ }
137
+ }
138
+ const results = await runRequests(
139
+ pending.map(({ request }) => request),
140
+ (request, requestSignal) =>
141
+ ctx.modelRegistry.classify(classifier, request, {
142
+ signal: requestSignal,
143
+ // The worker owns bounded transport retries, including normalized error results.
144
+ maxRetries: 0,
145
+ }),
146
+ concurrency,
147
+ signal,
148
+ (completedBatches, totalBatches) =>
149
+ progress({
150
+ stage: "chunks",
151
+ candidateTools: index.pairs.length,
152
+ protectedTools: index.protectedTools.length,
153
+ completedBatches,
154
+ totalBatches,
155
+ }),
156
+ );
157
+ let oversizedRequests = 0;
158
+ results.forEach((result, position) => {
159
+ const chunkId = pending[position]!.chunkId;
160
+ if (isClassifierOverflow(result)) {
161
+ oversizedRequests++;
162
+ decisions.set(chunkId, {
163
+ chunkId,
164
+ action: "keep",
165
+ reason: "classifier-context-window",
166
+ });
167
+ } else {
168
+ const answer = result.answers.safeToDrop!;
169
+ if (answer.type !== "bool")
170
+ throw new Error("Classifier returned an invalid safeToDrop answer");
171
+ const probability = answer.probability;
172
+ decisions.set(chunkId, {
173
+ chunkId,
174
+ probability,
175
+ action: probability >= policy.deleteThreshold ? "drop" : "keep",
176
+ });
177
+ }
178
+ });
179
+ signal.throwIfAborted();
180
+ const chunkDecisions = chunks.map((chunk) => decisions.get(chunk.id)!);
181
+ const { removedCalls, ...filtered } = applyDecisions(
182
+ preparation.messagesToSummarize,
183
+ preparation.turnPrefixMessages,
184
+ index.pairs,
185
+ chunks,
186
+ chunkDecisions,
187
+ );
188
+ const report: ToolReviewReport = {
189
+ model: `${classifier.provider}/${classifier.id}`,
190
+ // Pi Registry classifiers always carry catalog pricing.
191
+ pricingKnown: true,
192
+ protectedTools: index.protectedTools,
193
+ candidateTools: index.pairs.length,
194
+ chunks,
195
+ chunkDecisions,
196
+ removedCalls,
197
+ oversizedRequests,
198
+ requests: pending.length,
199
+ requestBudget: budget,
200
+ budgetFallbacks: fallbacks,
201
+ usage: results.flatMap((result) => (result.usage ? [result.usage] : [])),
202
+ charsBefore: JSON.stringify([
203
+ event.preparation.messagesToSummarize,
204
+ event.preparation.turnPrefixMessages,
205
+ ]).length,
206
+ charsAfterTruncation: JSON.stringify([
207
+ preparation.messagesToSummarize,
208
+ preparation.turnPrefixMessages,
209
+ ]).length,
210
+ charsAfter: JSON.stringify([filtered.messagesToSummarize, filtered.turnPrefixMessages])
211
+ .length,
212
+ };
213
+ return { ...filtered, report };
214
+ }
215
+
216
+ export function applyDecisions(
217
+ history: readonly AgentMessage[],
218
+ prefix: readonly AgentMessage[],
219
+ pairs: readonly ToolPair[],
220
+ chunks: readonly ResultChunk[],
221
+ chunkDecisions: readonly ChunkDecision[],
222
+ ): {
223
+ messagesToSummarize: AgentMessage[];
224
+ turnPrefixMessages: AgentMessage[];
225
+ removedCalls: string[];
226
+ } {
227
+ const chunkById = new Map(chunks.map((chunk) => [chunk.id, chunk]));
228
+ if (chunkById.size !== chunks.length)
229
+ throw new Error("Duplicate chunk IDs in the decision plan");
230
+ const chunkActions = new Map<string, ChunkDecision>();
231
+ for (const decision of chunkDecisions) {
232
+ const chunk = chunkById.get(decision.chunkId);
233
+ if (!chunk || chunkActions.has(decision.chunkId))
234
+ throw new Error(`Unknown or duplicate chunk decision ${decision.chunkId}`);
235
+ chunkActions.set(decision.chunkId, decision);
236
+ }
237
+ const pairById = new Map(pairs.map((pair) => [pair.id, pair]));
238
+ if (pairById.size !== pairs.length) throw new Error("Duplicate candidate call IDs");
239
+ const regions = { history, prefix } as const;
240
+ const removedCalls: string[] = [];
241
+ const rewritten = new Map<AgentMessage, AgentMessage>();
242
+ const droppedResults = new Set<AgentMessage>();
243
+ const droppedCalls = new Map<AgentMessage, Set<string>>();
244
+ for (const pair of pairs) {
245
+ const callRegion = pair.call.region === "retained" ? undefined : regions[pair.call.region];
246
+ const resultRegion =
247
+ pair.result.region === "retained" ? undefined : regions[pair.result.region];
248
+ if (
249
+ !callRegion ||
250
+ !resultRegion ||
251
+ pair.call.region !== pair.result.region ||
252
+ callRegion[pair.call.index] !== pair.call.message ||
253
+ resultRegion[pair.result.index] !== pair.result.message
254
+ ) {
255
+ throw new Error(`Candidate ${pair.id} no longer belongs to its native summary region`);
256
+ }
257
+ const result = pair.result.message;
258
+ if (result.role !== "toolResult") throw new Error(`Missing result for ${pair.id}`);
259
+ const own = chunks.filter((chunk) => chunk.toolCallId === pair.id);
260
+ for (let blockIndex = 0; blockIndex < result.content.length; blockIndex++) {
261
+ const block = result.content[blockIndex]!;
262
+ if (block.type !== "text") throw new Error(`Non-text candidate ${pair.id}`);
263
+ let cursor = 0;
264
+ for (const chunk of own.filter((chunk) => chunk.blockIndex === blockIndex)) {
265
+ if (
266
+ !Number.isSafeInteger(chunk.start) ||
267
+ !Number.isSafeInteger(chunk.end) ||
268
+ chunk.start !== cursor ||
269
+ chunk.end <= chunk.start ||
270
+ chunk.text !== block.text.slice(chunk.start, chunk.end)
271
+ ) {
272
+ throw new Error(`Chunk ${chunk.id} no longer matches the original result`);
273
+ }
274
+ if (!chunkActions.has(chunk.id))
275
+ throw new Error(`Missing decision for ${chunk.id}`);
276
+ cursor = chunk.end;
277
+ }
278
+ if (cursor !== block.text.length)
279
+ throw new Error(`Incomplete coverage of ${pair.id} block ${blockIndex}`);
280
+ }
281
+ if (own.some((chunk) => chunk.blockIndex < 0 || chunk.blockIndex >= result.content.length))
282
+ throw new Error(`Invalid block index for ${pair.id}`);
283
+ if (own.length > 0 && own.every((chunk) => chunkActions.get(chunk.id)?.action === "drop")) {
284
+ removedCalls.push(pair.id);
285
+ droppedResults.add(result);
286
+ const ids = droppedCalls.get(pair.call.message) ?? new Set<string>();
287
+ ids.add(pair.id);
288
+ droppedCalls.set(pair.call.message, ids);
289
+ continue;
290
+ }
291
+ if (
292
+ !own.some((chunk) => {
293
+ const action = chunkActions.get(chunk.id)?.action;
294
+ return action === "drop" || action === "placeholder";
295
+ })
296
+ )
297
+ continue;
298
+ const content: TextContent[] = result.content.map((block, blockIndex) => {
299
+ if (block.type !== "text") throw new Error(`Non-text candidate ${pair.id}`);
300
+ let text = "";
301
+ let omittedStart: number | undefined;
302
+ let omittedEnd = 0;
303
+ let omittedAction: "drop" | "placeholder" | undefined;
304
+ const flush = (): void => {
305
+ if (omittedStart === undefined) return;
306
+ const range = `UTF-16 range ${omittedStart}-${omittedEnd} (${omittedEnd - omittedStart} code units)`;
307
+ text +=
308
+ omittedAction === "placeholder"
309
+ ? `\n[pi-compaction placeholder for ${range}: classifier context window exceeded; content not classified]\n`
310
+ : `\n[pi-compaction omitted ${range}]\n`;
311
+ omittedStart = undefined;
312
+ omittedAction = undefined;
313
+ };
314
+ for (const chunk of own.filter((chunk) => chunk.blockIndex === blockIndex)) {
315
+ const action = chunkActions.get(chunk.id)?.action;
316
+ if (action === "drop" || action === "placeholder") {
317
+ if (omittedAction && omittedAction !== action) flush();
318
+ omittedAction = action;
319
+ omittedStart ??= chunk.start;
320
+ omittedEnd = chunk.end;
321
+ } else {
322
+ flush();
323
+ text += chunk.text;
324
+ }
325
+ }
326
+ flush();
327
+ return text === block.text ? block : { ...block, text };
328
+ });
329
+ rewritten.set(result, { ...result, content });
330
+ }
331
+ // Every decision must belong to a completely validated native result, including before whole-call deletion.
332
+ if (chunks.some((chunk) => !pairById.has(chunk.toolCallId)))
333
+ throw new Error("Chunk belongs to an unknown call");
334
+ const transform = (messages: readonly AgentMessage[]): AgentMessage[] =>
335
+ messages.flatMap((message) => {
336
+ if (droppedResults.has(message)) return [];
337
+ const callIds = droppedCalls.get(message);
338
+ if (callIds) {
339
+ if (message.role !== "assistant")
340
+ throw new Error("Call deletion targets a non-assistant message");
341
+ const content = message.content.filter(
342
+ (block) => block.type !== "toolCall" || !callIds.has(block.id),
343
+ );
344
+ return content.length === 0 ? [] : [{ ...message, content }];
345
+ }
346
+ return [rewritten.get(message) ?? message];
347
+ });
348
+ return {
349
+ messagesToSummarize: transform(history),
350
+ turnPrefixMessages: transform(prefix),
351
+ removedCalls,
352
+ };
353
+ }
354
+
355
+ function countActions(report: ToolReviewReport, action: ChunkDecision["action"]): number {
356
+ return report.chunkDecisions.filter((decision) => decision.action === action).length;
357
+ }
358
+
359
+ export interface ReviewSummary {
360
+ readonly model: string;
361
+ readonly checked: number;
362
+ readonly removedCalls: number;
363
+ readonly droppedFragments: number;
364
+ readonly placeholders: number;
365
+ readonly unreviewed: number;
366
+ readonly charsBefore: number;
367
+ readonly charsAfter: number;
368
+ }
369
+
370
+ /**
371
+ * Collapses a report into disjoint notice counts. Drops inside fully removed
372
+ * calls belong to the call entry, so surviving-call drops never recount them.
373
+ */
374
+ export function summarizeReview(report: ToolReviewReport): ReviewSummary {
375
+ const removed = new Set(report.removedCalls);
376
+ const owners = new Map(report.chunks.map((chunk) => [chunk.id, chunk.toolCallId]));
377
+ let droppedFragments = 0;
378
+ let placeholders = 0;
379
+ let unreviewed = 0;
380
+ for (const decision of report.chunkDecisions) {
381
+ if (decision.action === "placeholder") {
382
+ placeholders++;
383
+ } else if (decision.action === "drop") {
384
+ const owner = owners.get(decision.chunkId);
385
+ if (owner !== undefined && !removed.has(owner)) droppedFragments++;
386
+ } else if ("reason" in decision) {
387
+ unreviewed++;
388
+ }
389
+ }
390
+ return {
391
+ model: report.model,
392
+ checked: report.candidateTools,
393
+ removedCalls: report.removedCalls.length,
394
+ droppedFragments,
395
+ placeholders,
396
+ unreviewed,
397
+ charsBefore: report.charsBefore,
398
+ charsAfter: report.charsAfter,
399
+ };
400
+ }
401
+
402
+ /** Persisted checkpoint record; field names are stored in session files. */
403
+ export function checkpointRecord(report: ToolReviewReport) {
404
+ return {
405
+ model: report.model,
406
+ pricingKnown: report.pricingKnown,
407
+ candidateTools: report.candidateTools,
408
+ protectedTools: report.protectedTools.length,
409
+ removedChunks: countActions(report, "drop"),
410
+ placeholderChunks: countActions(report, "placeholder"),
411
+ requestBudget: report.requestBudget,
412
+ budgetFallbacks: report.budgetFallbacks,
413
+ removedCalls: report.removedCalls.length,
414
+ oversizedRequests: report.oversizedRequests,
415
+ requests: report.requests,
416
+ charsBefore: report.charsBefore,
417
+ charsAfter: report.charsAfter,
418
+ usage: report.usage,
419
+ };
420
+ }