@lune_99/pi-compaction 0.1.0 → 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.
- package/CHANGELOG.md +24 -0
- package/README.md +8 -6
- package/docs/compaction-review.png +0 -0
- package/docs/compaction-review.svg +10 -7
- package/docs/compaction-settings.png +0 -0
- package/docs/compaction-settings.svg +11 -10
- package/package.json +15 -6
- package/src/compaction-controller.ts +86 -17
- package/src/extension.ts +10 -4
- package/src/index.ts +5 -2
- package/src/options.ts +20 -1
- package/src/settings/schema.ts +20 -5
- package/src/settings/section.ts +11 -3
- package/src/tool-review/candidates.ts +14 -3
- package/src/tool-review/classification.ts +58 -10
- package/src/tool-review/review.ts +18 -40
- package/src/ui/review-notice.ts +469 -0
- package/docs/design.md +0 -444
|
@@ -1,9 +1,8 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1
2
|
import type { ClassifierContext, ClassifierModel, ClassifierResult } from "@earendil-works/pi-ai";
|
|
2
3
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
import type { ModelReference } from "@lune_99/pi-lune-extensions-core/panel";
|
|
4
5
|
|
|
5
|
-
const REQUEST_CONCURRENCY = 2;
|
|
6
|
-
|
|
7
6
|
export type Classify = (
|
|
8
7
|
context: ClassifierContext,
|
|
9
8
|
signal: AbortSignal,
|
|
@@ -24,8 +23,8 @@ export async function resolveClassifier(
|
|
|
24
23
|
if (!model)
|
|
25
24
|
throw new Error(
|
|
26
25
|
reference
|
|
27
|
-
? `Classifier ${reference.provider}/${reference.id} is unavailable. Configure its provider in Pi, or select Automatic in
|
|
28
|
-
: "No classifier is available. Configure a classifier provider in Pi with /login or its environment credentials, then refresh
|
|
26
|
+
? `Classifier ${reference.provider}/${reference.id} is unavailable. Configure its provider in Pi, or select Automatic in /lune-core-settings → Compaction → Classifier model.`
|
|
27
|
+
: "No classifier is available. Configure a classifier provider in Pi with /login or its environment credentials, then refresh the list in /lune-core-settings → Compaction → Classifier model.",
|
|
29
28
|
);
|
|
30
29
|
return model;
|
|
31
30
|
}
|
|
@@ -61,13 +60,65 @@ export function validateAnswers(result: ClassifierResult, context: ClassifierCon
|
|
|
61
60
|
}
|
|
62
61
|
}
|
|
63
62
|
|
|
64
|
-
|
|
63
|
+
const MAX_TRANSPORT_RETRIES = 2;
|
|
64
|
+
const TRANSPORT_RETRY_DELAY_MS = 500;
|
|
65
|
+
// Provider bodies can contain transport words even when account limits make retries futile.
|
|
66
|
+
const NON_RETRYABLE_PROVIDER_LIMIT_ERROR =
|
|
67
|
+
/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/iu;
|
|
68
|
+
const TRANSIENT_TRANSPORT_ERROR =
|
|
69
|
+
/\b(?:UND_ERR_(?:SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT)|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN)\b|fetch failed|other side closed|network.?error|connection.?(?:error|reset|refused|closed|lost)|getaddrinfo|upstream.?connect|reset before headers|socket (?:hang up|connection was closed)|timed? out|timeout|\bterminated\b|websocket.?(?:closed|error)|ended without|stream ended before (?:message_stop|a terminal response event)|http2 request did not get a response|pending stream has been canceled/iu;
|
|
70
|
+
|
|
71
|
+
function isTransientTransportError(message: string): boolean {
|
|
72
|
+
return (
|
|
73
|
+
!NON_RETRYABLE_PROVIDER_LIMIT_ERROR.test(message) && TRANSIENT_TRANSPORT_ERROR.test(message)
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function classifyWithRetry(
|
|
78
|
+
context: ClassifierContext,
|
|
79
|
+
classify: Classify,
|
|
80
|
+
signal: AbortSignal,
|
|
81
|
+
): Promise<ClassifierResult> {
|
|
82
|
+
for (let attempt = 0; ; attempt++) {
|
|
83
|
+
signal.throwIfAborted();
|
|
84
|
+
let message: string;
|
|
85
|
+
try {
|
|
86
|
+
// Snapshot before another request can reuse the provider's response object.
|
|
87
|
+
const result = structuredClone(await classify(context, signal));
|
|
88
|
+
signal.throwIfAborted();
|
|
89
|
+
if (result.stopReason !== "error" || isClassifierOverflow(result)) return result;
|
|
90
|
+
message = result.errorMessage ?? "";
|
|
91
|
+
if (attempt >= MAX_TRANSPORT_RETRIES || !isTransientTransportError(message))
|
|
92
|
+
return result;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
if (
|
|
96
|
+
attempt >= MAX_TRANSPORT_RETRIES ||
|
|
97
|
+
!(error instanceof Error) ||
|
|
98
|
+
error.name === "AbortError" ||
|
|
99
|
+
!isTransientTransportError(error.message)
|
|
100
|
+
)
|
|
101
|
+
throw error;
|
|
102
|
+
message = error.message;
|
|
103
|
+
}
|
|
104
|
+
const delayMs = TRANSPORT_RETRY_DELAY_MS * 2 ** attempt;
|
|
105
|
+
console.warn(
|
|
106
|
+
`[pi-compaction] Classifier transport retry ${attempt + 1}/${MAX_TRANSPORT_RETRIES} in ${delayMs}ms: ${message}`,
|
|
107
|
+
);
|
|
108
|
+
await delay(delayMs, undefined, { signal });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A terminal request failure aborts its siblings; context overflow is a result, not a failure. */
|
|
65
113
|
export async function runRequests(
|
|
66
114
|
requests: readonly ClassifierContext[],
|
|
67
115
|
classify: Classify,
|
|
116
|
+
concurrency: number,
|
|
68
117
|
signal: AbortSignal,
|
|
69
118
|
progress: (completed: number, total: number) => void,
|
|
70
119
|
): Promise<readonly ClassifierResult[]> {
|
|
120
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1)
|
|
121
|
+
throw new Error("Classifier concurrency must be a positive integer");
|
|
71
122
|
signal.throwIfAborted();
|
|
72
123
|
const cancel = new AbortController();
|
|
73
124
|
const requestSignal = AbortSignal.any([signal, cancel.signal]);
|
|
@@ -82,8 +133,7 @@ export async function runRequests(
|
|
|
82
133
|
const index = cursor++;
|
|
83
134
|
const request = requests[index]!;
|
|
84
135
|
try {
|
|
85
|
-
|
|
86
|
-
const result = structuredClone(await classify(request, requestSignal));
|
|
136
|
+
const result = await classifyWithRetry(request, classify, requestSignal);
|
|
87
137
|
requestSignal.throwIfAborted();
|
|
88
138
|
if (!isClassifierOverflow(result)) validateAnswers(result, request);
|
|
89
139
|
results[index] = result;
|
|
@@ -97,9 +147,7 @@ export async function runRequests(
|
|
|
97
147
|
}
|
|
98
148
|
}
|
|
99
149
|
};
|
|
100
|
-
await Promise.all(
|
|
101
|
-
Array.from({ length: Math.min(REQUEST_CONCURRENCY, requests.length) }, worker),
|
|
102
|
-
);
|
|
150
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, requests.length) }, worker));
|
|
103
151
|
signal.throwIfAborted();
|
|
104
152
|
if (cancel.signal.aborted) throw failure;
|
|
105
153
|
return results;
|
|
@@ -63,11 +63,15 @@ export interface ToolReviewReport {
|
|
|
63
63
|
readonly usage: readonly Usage[];
|
|
64
64
|
/** Serialized native message payload size, including metadata; not summary prompt tokens. */
|
|
65
65
|
readonly charsBefore: number;
|
|
66
|
+
/** The same size after the per-result truncation cap, before any classifier decision. */
|
|
67
|
+
readonly charsAfterTruncation: number;
|
|
66
68
|
readonly charsAfter: number;
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
export interface ToolReviewProgress {
|
|
70
72
|
readonly stage: "chunks";
|
|
73
|
+
readonly candidateTools: number;
|
|
74
|
+
readonly protectedTools: number;
|
|
71
75
|
readonly completedBatches: number;
|
|
72
76
|
readonly totalBatches: number;
|
|
73
77
|
}
|
|
@@ -77,6 +81,7 @@ export async function reviewToolHistory(
|
|
|
77
81
|
ctx: ExtensionContext,
|
|
78
82
|
policy: CompactionPolicy,
|
|
79
83
|
classifier: ClassifierModel<string>,
|
|
84
|
+
concurrency: number,
|
|
80
85
|
signal: AbortSignal,
|
|
81
86
|
progress: (update: ToolReviewProgress) => void,
|
|
82
87
|
): Promise<{
|
|
@@ -135,11 +140,19 @@ export async function reviewToolHistory(
|
|
|
135
140
|
(request, requestSignal) =>
|
|
136
141
|
ctx.modelRegistry.classify(classifier, request, {
|
|
137
142
|
signal: requestSignal,
|
|
143
|
+
// The worker owns bounded transport retries, including normalized error results.
|
|
138
144
|
maxRetries: 0,
|
|
139
145
|
}),
|
|
146
|
+
concurrency,
|
|
140
147
|
signal,
|
|
141
148
|
(completedBatches, totalBatches) =>
|
|
142
|
-
progress({
|
|
149
|
+
progress({
|
|
150
|
+
stage: "chunks",
|
|
151
|
+
candidateTools: index.pairs.length,
|
|
152
|
+
protectedTools: index.protectedTools.length,
|
|
153
|
+
completedBatches,
|
|
154
|
+
totalBatches,
|
|
155
|
+
}),
|
|
143
156
|
);
|
|
144
157
|
let oversizedRequests = 0;
|
|
145
158
|
results.forEach((result, position) => {
|
|
@@ -190,6 +203,10 @@ export async function reviewToolHistory(
|
|
|
190
203
|
event.preparation.messagesToSummarize,
|
|
191
204
|
event.preparation.turnPrefixMessages,
|
|
192
205
|
]).length,
|
|
206
|
+
charsAfterTruncation: JSON.stringify([
|
|
207
|
+
preparation.messagesToSummarize,
|
|
208
|
+
preparation.turnPrefixMessages,
|
|
209
|
+
]).length,
|
|
193
210
|
charsAfter: JSON.stringify([filtered.messagesToSummarize, filtered.turnPrefixMessages])
|
|
194
211
|
.length,
|
|
195
212
|
};
|
|
@@ -382,45 +399,6 @@ export function summarizeReview(report: ToolReviewReport): ReviewSummary {
|
|
|
382
399
|
};
|
|
383
400
|
}
|
|
384
401
|
|
|
385
|
-
function compactSize(chars: number): string {
|
|
386
|
-
return chars >= 1000 ? `${Math.round(chars / 1000)}k` : `${chars}`;
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
function pluralize(count: number, singular: string, plural: string): string {
|
|
390
|
-
return `${count} ${count === 1 ? singular : plural}`;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
export function formatReviewNotice(report: ToolReviewReport): string {
|
|
394
|
-
const summary = summarizeReview(report);
|
|
395
|
-
const head = `◇ Tool review · ${summary.model} · ${pluralize(summary.checked, "call", "calls")} checked`;
|
|
396
|
-
if (summary.checked === 0) return `${head} · ${compactSize(summary.charsAfter)}`;
|
|
397
|
-
const edits: string[] = [];
|
|
398
|
-
if (summary.removedCalls > 0)
|
|
399
|
-
edits.push(`${pluralize(summary.removedCalls, "call", "calls")} deleted`);
|
|
400
|
-
if (summary.droppedFragments > 0)
|
|
401
|
-
edits.push(
|
|
402
|
-
`${pluralize(summary.droppedFragments, "result fragment", "result fragments")} deleted`,
|
|
403
|
-
);
|
|
404
|
-
if (summary.placeholders > 0)
|
|
405
|
-
edits.push(
|
|
406
|
-
`${pluralize(summary.placeholders, "result fragment", "result fragments")} replaced with a placeholder`,
|
|
407
|
-
);
|
|
408
|
-
if (summary.unreviewed > 0)
|
|
409
|
-
edits.push(
|
|
410
|
-
`${pluralize(summary.unreviewed, "result fragment", "result fragments")} kept without review`,
|
|
411
|
-
);
|
|
412
|
-
if (edits.length === 0) edits.push("no change");
|
|
413
|
-
const percent =
|
|
414
|
-
summary.charsBefore > 0
|
|
415
|
-
? Math.round(((summary.charsBefore - summary.charsAfter) / summary.charsBefore) * 100)
|
|
416
|
-
: 0;
|
|
417
|
-
const size =
|
|
418
|
-
summary.charsBefore === summary.charsAfter || percent <= 0
|
|
419
|
-
? compactSize(summary.charsAfter)
|
|
420
|
-
: `${compactSize(summary.charsBefore)}→${compactSize(summary.charsAfter)} (-${percent}%)`;
|
|
421
|
-
return `${head}: ${edits.join(" · ")} · ${size}`;
|
|
422
|
-
}
|
|
423
|
-
|
|
424
402
|
/** Persisted checkpoint record; field names are stored in session files. */
|
|
425
403
|
export function checkpointRecord(report: ToolReviewReport) {
|
|
426
404
|
return {
|
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { visibleWidth, type Component } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { CompactionRunListener, CompactionRunUpdate } from "../compaction-controller.ts";
|
|
4
|
+
import type { ProtectedTool } from "../tool-review/candidates.ts";
|
|
5
|
+
import { summarizeReview, type ToolReviewReport } from "../tool-review/review.ts";
|
|
6
|
+
|
|
7
|
+
/** Widget key of the progress row and custom type of the saved result entry. */
|
|
8
|
+
export const REVIEW_NOTICE_WIDGET = "lune-compaction-review";
|
|
9
|
+
export const REVIEW_ENTRY_TYPE = "lune-compaction-review";
|
|
10
|
+
|
|
11
|
+
/** Below this width an expanded entry collapses to one row; at or above it, the result row joins the call row. */
|
|
12
|
+
export const COMPACT_NOTICE_WIDTH = 48;
|
|
13
|
+
/** At or above this width an expanded entry gives calls and results their own rows. */
|
|
14
|
+
export const FULL_NOTICE_WIDTH = 72;
|
|
15
|
+
|
|
16
|
+
const TITLE = "Tool review";
|
|
17
|
+
|
|
18
|
+
export type ProtectedCategory = "recent" | "error" | "not-permitted" | "nested" | "media" | "other";
|
|
19
|
+
|
|
20
|
+
const PROTECTED_CATEGORIES: readonly (readonly [ProtectedCategory, readonly string[]])[] = [
|
|
21
|
+
["recent", ["retained-region"]],
|
|
22
|
+
["error", ["error-result"]],
|
|
23
|
+
["not-permitted", ["tool-not-deletable"]],
|
|
24
|
+
["nested", ["incomplete-nested-calls", "nested-tool-not-deletable", "nested-call-failed"]],
|
|
25
|
+
["media", ["non-text-result"]],
|
|
26
|
+
];
|
|
27
|
+
const CATEGORY_ORDER: readonly ProtectedCategory[] = [
|
|
28
|
+
...PROTECTED_CATEGORIES.map(([category]) => category),
|
|
29
|
+
"other",
|
|
30
|
+
];
|
|
31
|
+
const CATEGORY_LABELS: Record<ProtectedCategory, string> = {
|
|
32
|
+
recent: "recent",
|
|
33
|
+
error: "error",
|
|
34
|
+
"not-permitted": "not permitted",
|
|
35
|
+
nested: "nested",
|
|
36
|
+
media: "media",
|
|
37
|
+
other: "other",
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Saved in a custom session entry; field names are stored in session files. */
|
|
41
|
+
export interface ToolReviewRecord {
|
|
42
|
+
readonly version: 1;
|
|
43
|
+
readonly model: string;
|
|
44
|
+
readonly candidateTools: number;
|
|
45
|
+
readonly protectedTools: number;
|
|
46
|
+
/** Each protected call counts once, under its first matching category; largest first. */
|
|
47
|
+
readonly protectedReasons: readonly {
|
|
48
|
+
readonly category: ProtectedCategory;
|
|
49
|
+
readonly count: number;
|
|
50
|
+
}[];
|
|
51
|
+
readonly removedCalls: number;
|
|
52
|
+
/** Drops in calls that survive; drops inside removed calls belong to the call count. */
|
|
53
|
+
readonly droppedFragments: number;
|
|
54
|
+
readonly placeholders: number;
|
|
55
|
+
readonly unreviewed: number;
|
|
56
|
+
readonly charsBefore: number;
|
|
57
|
+
/** After the per-result truncation cap, before any classifier decision. */
|
|
58
|
+
readonly charsAfterTruncation: number;
|
|
59
|
+
readonly charsAfter: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function protectedReasons(tools: readonly ProtectedTool[]): ToolReviewRecord["protectedReasons"] {
|
|
63
|
+
const counts = new Map<ProtectedCategory, number>();
|
|
64
|
+
for (const tool of tools) {
|
|
65
|
+
const category =
|
|
66
|
+
PROTECTED_CATEGORIES.find(([, reasons]) =>
|
|
67
|
+
reasons.some((reason) => tool.reasons.includes(reason)),
|
|
68
|
+
)?.[0] ?? "other";
|
|
69
|
+
counts.set(category, (counts.get(category) ?? 0) + 1);
|
|
70
|
+
}
|
|
71
|
+
// Array.prototype.sort is stable, so equal counts keep the category priority order.
|
|
72
|
+
return CATEGORY_ORDER.flatMap((category) => {
|
|
73
|
+
const count = counts.get(category);
|
|
74
|
+
return count ? [{ category, count }] : [];
|
|
75
|
+
}).sort((left, right) => right.count - left.count);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function toolReviewRecord(report: Readonly<ToolReviewReport>): ToolReviewRecord {
|
|
79
|
+
const summary = summarizeReview(report);
|
|
80
|
+
return {
|
|
81
|
+
version: 1,
|
|
82
|
+
model: report.model,
|
|
83
|
+
candidateTools: report.candidateTools,
|
|
84
|
+
protectedTools: report.protectedTools.length,
|
|
85
|
+
protectedReasons: protectedReasons(report.protectedTools),
|
|
86
|
+
removedCalls: summary.removedCalls,
|
|
87
|
+
droppedFragments: summary.droppedFragments,
|
|
88
|
+
placeholders: summary.placeholders,
|
|
89
|
+
unreviewed: summary.unreviewed,
|
|
90
|
+
charsBefore: report.charsBefore,
|
|
91
|
+
charsAfterTruncation: report.charsAfterTruncation,
|
|
92
|
+
charsAfter: report.charsAfter,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const COUNT_FIELDS = [
|
|
97
|
+
"candidateTools",
|
|
98
|
+
"protectedTools",
|
|
99
|
+
"removedCalls",
|
|
100
|
+
"droppedFragments",
|
|
101
|
+
"placeholders",
|
|
102
|
+
"unreviewed",
|
|
103
|
+
"charsBefore",
|
|
104
|
+
"charsAfterTruncation",
|
|
105
|
+
"charsAfter",
|
|
106
|
+
] as const satisfies readonly (keyof ToolReviewRecord)[];
|
|
107
|
+
|
|
108
|
+
function isCount(value: unknown): value is number {
|
|
109
|
+
return Number.isSafeInteger(value) && (value as number) >= 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Session files can be edited by hand or written by another version; render only what was validated. */
|
|
113
|
+
export function parseToolReviewRecord(data: unknown): ToolReviewRecord {
|
|
114
|
+
const record = data as Partial<Record<keyof ToolReviewRecord, unknown>> | null;
|
|
115
|
+
if (
|
|
116
|
+
typeof record !== "object" ||
|
|
117
|
+
record === null ||
|
|
118
|
+
record.version !== 1 ||
|
|
119
|
+
typeof record.model !== "string" ||
|
|
120
|
+
!COUNT_FIELDS.every((field) => isCount(record[field])) ||
|
|
121
|
+
!Array.isArray(record.protectedReasons) ||
|
|
122
|
+
!record.protectedReasons.every(
|
|
123
|
+
(entry: unknown) =>
|
|
124
|
+
typeof entry === "object" &&
|
|
125
|
+
entry !== null &&
|
|
126
|
+
CATEGORY_ORDER.includes((entry as { category: ProtectedCategory }).category) &&
|
|
127
|
+
isCount((entry as { count: unknown }).count),
|
|
128
|
+
)
|
|
129
|
+
) {
|
|
130
|
+
throw new Error("Malformed tool review record");
|
|
131
|
+
}
|
|
132
|
+
return record as ToolReviewRecord;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export type ReviewProgressState = "preparing" | "reviewing" | "summarizing";
|
|
136
|
+
|
|
137
|
+
export interface ReviewProgressView {
|
|
138
|
+
readonly state: ReviewProgressState;
|
|
139
|
+
/** Known once the review has indexed the summarized history. */
|
|
140
|
+
readonly calls?: { readonly total: number; readonly reviewed: number };
|
|
141
|
+
readonly batches?: { readonly completed: number; readonly total: number };
|
|
142
|
+
/** Known once every classifier decision is applied. */
|
|
143
|
+
readonly result?: ToolReviewRecord;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const PROGRESS_STATES: Partial<Record<CompactionRunUpdate["stage"], ReviewProgressState>> = {
|
|
147
|
+
preparing: "preparing",
|
|
148
|
+
chunks: "reviewing",
|
|
149
|
+
summarizing: "summarizing",
|
|
150
|
+
"awaiting-commit": "summarizing",
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** Undefined once the run has settled: a running notice never outlives its compaction. */
|
|
154
|
+
export function reviewProgressView(update: CompactionRunUpdate): ReviewProgressView | undefined {
|
|
155
|
+
const state = PROGRESS_STATES[update.stage];
|
|
156
|
+
if (!state) return undefined;
|
|
157
|
+
return {
|
|
158
|
+
state,
|
|
159
|
+
...(update.candidateTools === undefined || update.protectedTools === undefined
|
|
160
|
+
? {}
|
|
161
|
+
: {
|
|
162
|
+
calls: {
|
|
163
|
+
total: update.candidateTools + update.protectedTools,
|
|
164
|
+
reviewed: update.candidateTools,
|
|
165
|
+
},
|
|
166
|
+
}),
|
|
167
|
+
...(state === "reviewing"
|
|
168
|
+
? { batches: { completed: update.completedBatches, total: update.totalBatches } }
|
|
169
|
+
: {}),
|
|
170
|
+
...(update.jev ? { result: toolReviewRecord(update.jev) } : {}),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A part of a row; lower ranks give way first, and an attached part follows its anchor with a space. */
|
|
175
|
+
interface Part {
|
|
176
|
+
readonly text: string;
|
|
177
|
+
readonly rank: number;
|
|
178
|
+
readonly attached?: boolean;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface Row {
|
|
182
|
+
/** Complete variants from richest to shortest, tried after every part has given way. */
|
|
183
|
+
readonly leads: readonly string[];
|
|
184
|
+
readonly parts: readonly Part[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function compose(lead: string, parts: readonly Part[], separator: string): string {
|
|
188
|
+
return parts.reduce(
|
|
189
|
+
(line, part, index) =>
|
|
190
|
+
line + (part.attached ? " " : index === 0 && !lead.trim() ? "" : separator) + part.text,
|
|
191
|
+
lead,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The richest complete row that fits, never a cut one; undefined when an indented row has nothing left. */
|
|
196
|
+
function fitRow(row: Row, width: number, separator: string): string | undefined {
|
|
197
|
+
const kept = [...row.parts];
|
|
198
|
+
for (;;) {
|
|
199
|
+
const line = compose(row.leads[0]!, kept, separator);
|
|
200
|
+
if (visibleWidth(line) <= width)
|
|
201
|
+
return kept.length > 0 || row.leads[0]!.trim() ? line : undefined;
|
|
202
|
+
if (kept.length === 0) break;
|
|
203
|
+
let lowest = 0;
|
|
204
|
+
for (let index = 1; index < kept.length; index++)
|
|
205
|
+
if (kept[index]!.rank <= kept[lowest]!.rank) lowest = index;
|
|
206
|
+
let end = lowest + 1;
|
|
207
|
+
while (kept[end]?.attached) end++;
|
|
208
|
+
kept.splice(lowest, end - lowest);
|
|
209
|
+
}
|
|
210
|
+
return row.leads.slice(1).find((lead) => lead.trim() && visibleWidth(lead) <= width);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function size(chars: number): string {
|
|
214
|
+
if (chars >= 999_500) return `${(chars / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
|
|
215
|
+
return chars >= 1000 ? `${Math.round(chars / 1000)}k` : `${chars}`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function saved(chars: number): string {
|
|
219
|
+
return chars > 0 ? `−${size(chars)}` : chars < 0 ? `+${size(-chars)}` : "±0";
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function count(value: number, singular: string, plural = `${singular}s`): string {
|
|
223
|
+
return `${value} ${value === 1 ? singular : plural}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function leads(glyph: string, theme: Theme): readonly string[] {
|
|
227
|
+
const marker = theme.fg("accent", glyph);
|
|
228
|
+
return [`${marker} ${TITLE}`, marker];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** `−3 calls · −13 fragments · 989k → 515k`, with the edits outranking the size. */
|
|
232
|
+
function resultParts(record: ToolReviewRecord): Part[] {
|
|
233
|
+
const edits: Part[] = [];
|
|
234
|
+
if (record.removedCalls > 0)
|
|
235
|
+
edits.push({ text: `−${count(record.removedCalls, "call")}`, rank: 9 });
|
|
236
|
+
if (record.droppedFragments > 0)
|
|
237
|
+
edits.push({ text: `−${count(record.droppedFragments, "fragment")}`, rank: 8 });
|
|
238
|
+
if (record.placeholders > 0)
|
|
239
|
+
edits.push({ text: count(record.placeholders, "placeholder"), rank: 5 });
|
|
240
|
+
if (record.unreviewed > 0)
|
|
241
|
+
edits.push({ text: `${record.unreviewed} kept unreviewed`, rank: 5 });
|
|
242
|
+
if (edits.length === 0) edits.push({ text: "nothing removed", rank: 9 });
|
|
243
|
+
return [
|
|
244
|
+
...edits,
|
|
245
|
+
{ text: `${size(record.charsBefore)} → ${size(record.charsAfter)}`, rank: 6 },
|
|
246
|
+
];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** One row that keeps the editor in place: preparing, request progress, then the edits while the summary runs. */
|
|
250
|
+
export function reviewProgressLine(view: ReviewProgressView, width: number, theme: Theme): string {
|
|
251
|
+
if (width < 1) return "";
|
|
252
|
+
const muted = (text: string): string => theme.fg("muted", text);
|
|
253
|
+
const parts: Part[] = [];
|
|
254
|
+
if (view.state !== "reviewing") parts.push({ text: muted(view.state), rank: 7 });
|
|
255
|
+
if (view.state === "summarizing" && view.result) parts.push(...resultParts(view.result));
|
|
256
|
+
else if (view.calls)
|
|
257
|
+
parts.push(
|
|
258
|
+
{ text: muted(count(view.calls.total, "call")), rank: 2 },
|
|
259
|
+
{ text: muted(`${view.calls.reviewed} in review`), rank: 4 },
|
|
260
|
+
);
|
|
261
|
+
if (view.batches)
|
|
262
|
+
parts.push({
|
|
263
|
+
text: muted(`${view.batches.completed}/${view.batches.total} requests`),
|
|
264
|
+
rank: 6,
|
|
265
|
+
});
|
|
266
|
+
return fitRow({ leads: leads("◐", theme), parts }, width, muted(" · ")) ?? "";
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The saved result under Pi's compaction summary. Collapsed it is one row of edits and size;
|
|
271
|
+
* expanded it adds the classifier, the call counts and the truncation/classifier split.
|
|
272
|
+
*/
|
|
273
|
+
export function reviewEntryLines(
|
|
274
|
+
record: ToolReviewRecord,
|
|
275
|
+
width: number,
|
|
276
|
+
theme: Theme,
|
|
277
|
+
expanded: boolean,
|
|
278
|
+
): string[] {
|
|
279
|
+
if (width < 1) return [];
|
|
280
|
+
const muted = (text: string): string => theme.fg("muted", text);
|
|
281
|
+
const separator = muted(" · ");
|
|
282
|
+
const lead = leads("◇", theme);
|
|
283
|
+
const result = resultParts(record);
|
|
284
|
+
if (!expanded) return [fitRow({ leads: lead, parts: result }, width, separator) ?? ""];
|
|
285
|
+
const calls: Part[] = [
|
|
286
|
+
{ text: muted(count(record.candidateTools + record.protectedTools, "call")), rank: 2 },
|
|
287
|
+
{ text: muted(`${record.candidateTools} reviewed`), rank: 4 },
|
|
288
|
+
{ text: muted(`${record.protectedTools} protected`), rank: 3 },
|
|
289
|
+
];
|
|
290
|
+
if (record.protectedReasons.length > 0)
|
|
291
|
+
calls.push({
|
|
292
|
+
text: muted(
|
|
293
|
+
`(${record.protectedReasons.map((reason) => `${reason.count} ${CATEGORY_LABELS[reason.category]}`).join(" · ")})`,
|
|
294
|
+
),
|
|
295
|
+
rank: 1,
|
|
296
|
+
attached: true,
|
|
297
|
+
});
|
|
298
|
+
const split: Part[] = [
|
|
299
|
+
{
|
|
300
|
+
text: muted(`truncation ${saved(record.charsBefore - record.charsAfterTruncation)}`),
|
|
301
|
+
rank: 3,
|
|
302
|
+
},
|
|
303
|
+
{
|
|
304
|
+
text: muted(`classifier ${saved(record.charsAfterTruncation - record.charsAfter)}`),
|
|
305
|
+
rank: 4,
|
|
306
|
+
},
|
|
307
|
+
];
|
|
308
|
+
const head: Row = { leads: lead, parts: [{ text: muted(record.model), rank: 0 }] };
|
|
309
|
+
const rows: Row[] =
|
|
310
|
+
width < COMPACT_NOTICE_WIDTH
|
|
311
|
+
? [{ leads: lead, parts: [...result, ...split, ...calls] }]
|
|
312
|
+
: width < FULL_NOTICE_WIDTH
|
|
313
|
+
? [head, { leads: [" "], parts: [...result, ...split, ...calls] }]
|
|
314
|
+
: [
|
|
315
|
+
head,
|
|
316
|
+
{ leads: [" "], parts: calls },
|
|
317
|
+
{ leads: [" "], parts: [...result, ...split] },
|
|
318
|
+
];
|
|
319
|
+
return rows.flatMap((row) => fitRow(row, width, separator) ?? []);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Pi adds no padding around custom entries; one column lines the entry up with Pi's own notices. */
|
|
323
|
+
const ENTRY_PADDING = " ";
|
|
324
|
+
|
|
325
|
+
class ReviewEntryComponent implements Component {
|
|
326
|
+
private readonly record: ToolReviewRecord;
|
|
327
|
+
private readonly theme: Theme;
|
|
328
|
+
private readonly expanded: boolean;
|
|
329
|
+
|
|
330
|
+
constructor(record: ToolReviewRecord, theme: Theme, expanded: boolean) {
|
|
331
|
+
this.record = record;
|
|
332
|
+
this.theme = theme;
|
|
333
|
+
this.expanded = expanded;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
render(width: number): string[] {
|
|
337
|
+
return reviewEntryLines(
|
|
338
|
+
this.record,
|
|
339
|
+
width - ENTRY_PADDING.length,
|
|
340
|
+
this.theme,
|
|
341
|
+
this.expanded,
|
|
342
|
+
).map((line) => ENTRY_PADDING + line);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
invalidate(): void {}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
class ReviewProgressComponent implements Component {
|
|
349
|
+
private view: ReviewProgressView;
|
|
350
|
+
private broken = false;
|
|
351
|
+
private readonly theme: () => Theme;
|
|
352
|
+
private readonly onRenderError: (error: unknown) => void;
|
|
353
|
+
private readonly onDispose: () => void;
|
|
354
|
+
|
|
355
|
+
constructor(
|
|
356
|
+
view: ReviewProgressView,
|
|
357
|
+
theme: () => Theme,
|
|
358
|
+
onRenderError: (error: unknown) => void,
|
|
359
|
+
onDispose: () => void,
|
|
360
|
+
) {
|
|
361
|
+
this.view = view;
|
|
362
|
+
this.theme = theme;
|
|
363
|
+
this.onRenderError = onRenderError;
|
|
364
|
+
this.onDispose = onDispose;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
setView(view: ReviewProgressView): void {
|
|
368
|
+
this.view = view;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
render(width: number): string[] {
|
|
372
|
+
if (this.broken) return [];
|
|
373
|
+
try {
|
|
374
|
+
return [reviewProgressLine(this.view, width, this.theme())];
|
|
375
|
+
} catch (error) {
|
|
376
|
+
this.broken = true;
|
|
377
|
+
this.onRenderError(error);
|
|
378
|
+
return [];
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
invalidate(): void {}
|
|
383
|
+
|
|
384
|
+
dispose(): void {
|
|
385
|
+
this.onDispose();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** RPC has no width to measure against; 80 keeps the row inside a typical client pane. */
|
|
390
|
+
const RPC_NOTICE_WIDTH = 80;
|
|
391
|
+
|
|
392
|
+
/** RPC renders the string form of a widget, so nothing resolves a theme. */
|
|
393
|
+
const unstyledTheme = { fg: (_color: string, text: string) => text } as unknown as Theme;
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Shows review progress above the editor only while a compaction runs, then saves the result
|
|
397
|
+
* as a transcript entry under Pi's compaction summary, where it scrolls away with the conversation.
|
|
398
|
+
*/
|
|
399
|
+
export function createReviewNotice(pi: ExtensionAPI): CompactionRunListener {
|
|
400
|
+
// Pi passes its live theme, so colors follow a theme switch when the entry is rebuilt.
|
|
401
|
+
pi.registerEntryRenderer(REVIEW_ENTRY_TYPE, (entry, options, theme) => {
|
|
402
|
+
return new ReviewEntryComponent(parseToolReviewRecord(entry.data), theme, options.expanded);
|
|
403
|
+
});
|
|
404
|
+
let mounted: { component: ReviewProgressComponent; requestRender: () => void } | undefined;
|
|
405
|
+
let shown = false;
|
|
406
|
+
const showProgress = (view: ReviewProgressView | undefined, ctx: ExtensionContext): void => {
|
|
407
|
+
// RPC ignores widget factories but renders string lines, so send the same row as text.
|
|
408
|
+
if (ctx.mode === "rpc") {
|
|
409
|
+
ctx.ui.setWidget(
|
|
410
|
+
REVIEW_NOTICE_WIDGET,
|
|
411
|
+
view ? [reviewProgressLine(view, RPC_NOTICE_WIDTH, unstyledTheme)] : undefined,
|
|
412
|
+
{ placement: "aboveEditor" },
|
|
413
|
+
);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (!view) {
|
|
417
|
+
if (shown) ctx.ui.setWidget(REVIEW_NOTICE_WIDGET, undefined);
|
|
418
|
+
shown = false;
|
|
419
|
+
mounted = undefined;
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
shown = true;
|
|
423
|
+
if (mounted) {
|
|
424
|
+
mounted.component.setView(view);
|
|
425
|
+
mounted.requestRender();
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
ctx.ui.setWidget(
|
|
429
|
+
REVIEW_NOTICE_WIDGET,
|
|
430
|
+
(tui, theme) => {
|
|
431
|
+
const component = new ReviewProgressComponent(
|
|
432
|
+
view,
|
|
433
|
+
() => theme,
|
|
434
|
+
(error) => {
|
|
435
|
+
console.error("[pi-compaction] Review progress failed to render", error);
|
|
436
|
+
// Pi is mid-render; replacing a widget now would edit the tree it is drawing.
|
|
437
|
+
queueMicrotask(() => {
|
|
438
|
+
if (mounted?.component !== component) return;
|
|
439
|
+
try {
|
|
440
|
+
ctx.ui.setWidget(REVIEW_NOTICE_WIDGET, undefined);
|
|
441
|
+
} catch (clearError) {
|
|
442
|
+
console.error(
|
|
443
|
+
"[pi-compaction] Review progress cleanup failed",
|
|
444
|
+
clearError,
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
},
|
|
449
|
+
() => {
|
|
450
|
+
if (mounted?.component === component) mounted = undefined;
|
|
451
|
+
},
|
|
452
|
+
);
|
|
453
|
+
mounted = { component, requestRender: () => tui.requestRender() };
|
|
454
|
+
return component;
|
|
455
|
+
},
|
|
456
|
+
{ placement: "aboveEditor" },
|
|
457
|
+
);
|
|
458
|
+
};
|
|
459
|
+
return (update, ctx) => {
|
|
460
|
+
if (!ctx.hasUI) return;
|
|
461
|
+
showProgress(update && reviewProgressView(update), ctx);
|
|
462
|
+
if (update?.stage === "complete" && update.jev) {
|
|
463
|
+
// Appending inside session_compact puts the entry right after the checkpoint, before
|
|
464
|
+
// any queued prompt. Pi's rebuild then draws it after the retained messages, directly
|
|
465
|
+
// above the live summary; a deferred append could land after a queued prompt instead.
|
|
466
|
+
pi.appendEntry(REVIEW_ENTRY_TYPE, toolReviewRecord(update.jev));
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
}
|