@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.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/docs/compaction-review.png +0 -0
- package/docs/compaction-review.svg +12 -0
- package/docs/compaction-settings.png +0 -0
- package/docs/compaction-settings.svg +25 -0
- package/package.json +65 -5
- package/src/compaction-controller.ts +383 -0
- package/src/extension.ts +45 -0
- package/src/index.ts +37 -0
- package/src/options.ts +88 -0
- package/src/settings/schema.ts +84 -0
- package/src/settings/section.ts +162 -0
- package/src/tool-review/candidates.ts +326 -0
- package/src/tool-review/classification.ts +154 -0
- package/src/tool-review/review.ts +420 -0
- package/src/ui/review-notice.ts +469 -0
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import type { StreamFn } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { clampThinkingLevel, contentText, lazyStream, type Usage } from "@earendil-works/pi-ai";
|
|
3
|
+
import {
|
|
4
|
+
compact,
|
|
5
|
+
type ExtensionAPI,
|
|
6
|
+
type ExtensionContext,
|
|
7
|
+
type SessionBeforeCompactEvent,
|
|
8
|
+
type SessionBeforeCompactResult,
|
|
9
|
+
} from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type { ModelReference } from "@lune_99/pi-lune-extensions-core/panel";
|
|
11
|
+
import { validateOptions, type ConfigurationProvider } from "./options.ts";
|
|
12
|
+
import { resolveClassifier } from "./tool-review/classification.ts";
|
|
13
|
+
import {
|
|
14
|
+
checkpointRecord,
|
|
15
|
+
reviewToolHistory,
|
|
16
|
+
type ToolReviewProgress,
|
|
17
|
+
type ToolReviewReport,
|
|
18
|
+
} from "./tool-review/review.ts";
|
|
19
|
+
|
|
20
|
+
export const COMPACTION_POLICY_VERSION = "lune-jev-v5";
|
|
21
|
+
|
|
22
|
+
export type CompactionStage =
|
|
23
|
+
| "preparing"
|
|
24
|
+
| "chunks"
|
|
25
|
+
| "summarizing"
|
|
26
|
+
| "awaiting-commit"
|
|
27
|
+
| "complete"
|
|
28
|
+
| "failed"
|
|
29
|
+
| "cancelled";
|
|
30
|
+
|
|
31
|
+
export interface CompactionRun {
|
|
32
|
+
readonly id: number;
|
|
33
|
+
readonly sessionId: string;
|
|
34
|
+
readonly leafId: string | null;
|
|
35
|
+
readonly reason: SessionBeforeCompactEvent["reason"];
|
|
36
|
+
summaryModel?: ModelReference;
|
|
37
|
+
policyVersion?: string;
|
|
38
|
+
readonly startedAt: number;
|
|
39
|
+
stage: CompactionStage;
|
|
40
|
+
completedBatches: number;
|
|
41
|
+
totalBatches: number;
|
|
42
|
+
finishedAt?: number;
|
|
43
|
+
error?: Error;
|
|
44
|
+
jev?: ToolReviewReport;
|
|
45
|
+
summaryUsage?: Usage;
|
|
46
|
+
summary?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What a presentation layer sees of a reviewed run; the report is shared, not copied. */
|
|
50
|
+
export interface CompactionRunUpdate {
|
|
51
|
+
readonly runId: number;
|
|
52
|
+
readonly stage: CompactionStage;
|
|
53
|
+
/** `provider/id`, known once the classifier is resolved. */
|
|
54
|
+
readonly reviewModel?: string;
|
|
55
|
+
readonly candidateTools?: number;
|
|
56
|
+
readonly protectedTools?: number;
|
|
57
|
+
readonly completedBatches: number;
|
|
58
|
+
readonly totalBatches: number;
|
|
59
|
+
readonly jev?: Readonly<ToolReviewReport>;
|
|
60
|
+
readonly error?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Receives every visible change of a reviewed run, and `undefined` when its notice no longer applies. */
|
|
64
|
+
export type CompactionRunListener = (
|
|
65
|
+
update: CompactionRunUpdate | undefined,
|
|
66
|
+
ctx: ExtensionContext,
|
|
67
|
+
) => void;
|
|
68
|
+
|
|
69
|
+
export interface CompactionControllerOptions {
|
|
70
|
+
readonly onRunChange?: CompactionRunListener;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Route summaries through Pi's registry and reject any split response that did not finish normally. */
|
|
74
|
+
export function createSummaryStream(
|
|
75
|
+
ctx: ExtensionContext,
|
|
76
|
+
signal: AbortSignal,
|
|
77
|
+
assertActive: () => void,
|
|
78
|
+
): StreamFn {
|
|
79
|
+
return (model, context, options) => {
|
|
80
|
+
assertActive();
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
// Pi owns routing, authentication, output limits and error-event construction.
|
|
83
|
+
// Validate each split-turn response before native compact can combine it with another summary.
|
|
84
|
+
return lazyStream(model, async () => {
|
|
85
|
+
const response = await ctx.modelRegistry
|
|
86
|
+
.streamSimple(model, context, { ...options, signal, maxRetries: 0 })
|
|
87
|
+
.result();
|
|
88
|
+
assertActive();
|
|
89
|
+
signal.throwIfAborted();
|
|
90
|
+
if (response.stopReason !== "stop")
|
|
91
|
+
throw new Error(
|
|
92
|
+
`Summary ${response.stopReason}: ${response.errorMessage ?? "generation did not finish normally"}`,
|
|
93
|
+
);
|
|
94
|
+
if (!contentText(response.content).trim())
|
|
95
|
+
throw new Error("Summary returned empty text");
|
|
96
|
+
// Native compact rejects tool calls and writes the checkpoint through Pi's session lifecycle.
|
|
97
|
+
return (async function* () {
|
|
98
|
+
yield { type: "done" as const, reason: "stop" as const, message: response };
|
|
99
|
+
})();
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Owns every compaction run of one extension instance: its abort controller, generation and commit tracking. */
|
|
105
|
+
export class CompactionController {
|
|
106
|
+
private generation = 0;
|
|
107
|
+
private sequence = 0;
|
|
108
|
+
private active: AbortController | undefined;
|
|
109
|
+
private run: CompactionRun | undefined;
|
|
110
|
+
private readonly unregister: (() => void)[] = [];
|
|
111
|
+
private readonly getConfiguration: ConfigurationProvider;
|
|
112
|
+
private readonly onRunChange: CompactionRunListener | undefined;
|
|
113
|
+
|
|
114
|
+
constructor(
|
|
115
|
+
pi: ExtensionAPI,
|
|
116
|
+
getConfiguration: ConfigurationProvider,
|
|
117
|
+
options: CompactionControllerOptions = {},
|
|
118
|
+
) {
|
|
119
|
+
this.getConfiguration = getConfiguration;
|
|
120
|
+
this.onRunChange = options.onRunChange;
|
|
121
|
+
const retire = (ctx: ExtensionContext): void => {
|
|
122
|
+
this.invalidate();
|
|
123
|
+
this.publish(ctx, undefined);
|
|
124
|
+
};
|
|
125
|
+
this.unregister.push(
|
|
126
|
+
pi.on("session_before_compact", (event, ctx) => this.beforeCompact(event, ctx)),
|
|
127
|
+
pi.on("session_start", (_event, ctx) => {
|
|
128
|
+
retire(ctx);
|
|
129
|
+
this.run = undefined;
|
|
130
|
+
}),
|
|
131
|
+
pi.on("session_shutdown", (_event, ctx) => retire(ctx)),
|
|
132
|
+
pi.on("session_before_switch", (_event, ctx) => retire(ctx)),
|
|
133
|
+
pi.on("session_before_fork", (_event, ctx) => retire(ctx)),
|
|
134
|
+
pi.on("session_before_tree", (_event, ctx) => retire(ctx)),
|
|
135
|
+
pi.on("session_compact", (event, ctx) => {
|
|
136
|
+
const run = this.awaitingCommit(ctx);
|
|
137
|
+
if (!run) return;
|
|
138
|
+
const details = event.compactionEntry.details as
|
|
139
|
+
| { luneCompaction?: { runId?: number } }
|
|
140
|
+
| undefined;
|
|
141
|
+
if (
|
|
142
|
+
details?.luneCompaction?.runId !== run.id ||
|
|
143
|
+
event.compactionEntry.summary !== run.summary
|
|
144
|
+
) {
|
|
145
|
+
run.stage = "failed";
|
|
146
|
+
run.error = new Error(
|
|
147
|
+
"Another compaction handler replaced the generated checkpoint",
|
|
148
|
+
);
|
|
149
|
+
this.report(ctx, run.error);
|
|
150
|
+
} else {
|
|
151
|
+
run.stage = "complete";
|
|
152
|
+
}
|
|
153
|
+
run.finishedAt = Date.now();
|
|
154
|
+
if (run.jev) this.publish(ctx, run);
|
|
155
|
+
}),
|
|
156
|
+
pi.on("session_compact_failed", (event, ctx) => {
|
|
157
|
+
const run = this.awaitingCommit(ctx);
|
|
158
|
+
if (!run) return;
|
|
159
|
+
run.stage = event.aborted ? "cancelled" : "failed";
|
|
160
|
+
run.finishedAt = Date.now();
|
|
161
|
+
if (!event.aborted) {
|
|
162
|
+
run.error = new Error(
|
|
163
|
+
event.errorMessage ?? "Pi failed to commit the generated checkpoint",
|
|
164
|
+
);
|
|
165
|
+
this.report(ctx, run.error);
|
|
166
|
+
}
|
|
167
|
+
if (run.jev) this.publish(ctx, run);
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
getRun(): Readonly<CompactionRun> | undefined {
|
|
173
|
+
if (!this.run) return undefined;
|
|
174
|
+
// Inspection must not let a future UI mutate private model choices or decision/cost records.
|
|
175
|
+
const { error, ...data } = this.run;
|
|
176
|
+
const snapshot = structuredClone(data);
|
|
177
|
+
return Object.freeze(error === undefined ? snapshot : { ...snapshot, error });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private awaitingCommit(ctx: ExtensionContext): CompactionRun | undefined {
|
|
181
|
+
const run = this.run;
|
|
182
|
+
return run?.stage === "awaiting-commit" &&
|
|
183
|
+
run.sessionId === ctx.sessionManager.getSessionId()
|
|
184
|
+
? run
|
|
185
|
+
: undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private invalidate(): void {
|
|
189
|
+
this.generation++;
|
|
190
|
+
this.active?.abort(new DOMException("Compaction session was retired", "AbortError"));
|
|
191
|
+
if (this.run?.stage === "awaiting-commit") {
|
|
192
|
+
this.run.stage = "cancelled";
|
|
193
|
+
this.run.finishedAt = Date.now();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private publish(
|
|
198
|
+
ctx: ExtensionContext,
|
|
199
|
+
run: CompactionRun | undefined,
|
|
200
|
+
progress?: { readonly reviewModel: string; readonly review?: ToolReviewProgress },
|
|
201
|
+
): void {
|
|
202
|
+
if (!this.onRunChange) return;
|
|
203
|
+
const update: CompactionRunUpdate | undefined = run && {
|
|
204
|
+
runId: run.id,
|
|
205
|
+
stage: run.stage,
|
|
206
|
+
reviewModel: run.jev?.model ?? progress?.reviewModel,
|
|
207
|
+
candidateTools: run.jev?.candidateTools ?? progress?.review?.candidateTools,
|
|
208
|
+
protectedTools: run.jev?.protectedTools.length ?? progress?.review?.protectedTools,
|
|
209
|
+
completedBatches: run.completedBatches,
|
|
210
|
+
totalBatches: run.totalBatches,
|
|
211
|
+
jev: run.jev,
|
|
212
|
+
error: run.error?.message,
|
|
213
|
+
};
|
|
214
|
+
try {
|
|
215
|
+
this.onRunChange(update, ctx);
|
|
216
|
+
} catch (listenerError) {
|
|
217
|
+
// Presentation must never fail or retry a compaction.
|
|
218
|
+
console.warn("[pi-compaction] Run listener failed", listenerError);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private report(ctx: ExtensionContext, error: Error): void {
|
|
223
|
+
// Error reporting must not turn a cancel result into a swallowed hook exception.
|
|
224
|
+
console.error("[pi-compaction]", error);
|
|
225
|
+
if (ctx.hasUI) {
|
|
226
|
+
try {
|
|
227
|
+
ctx.ui.notify(`Lune compaction failed: ${error.message}`, "error");
|
|
228
|
+
} catch (notificationError) {
|
|
229
|
+
console.error("[pi-compaction] Error notification failed", notificationError);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async beforeCompact(
|
|
235
|
+
event: SessionBeforeCompactEvent,
|
|
236
|
+
ctx: ExtensionContext,
|
|
237
|
+
): Promise<SessionBeforeCompactResult> {
|
|
238
|
+
if (this.active || this.run?.stage === "awaiting-commit") {
|
|
239
|
+
this.report(ctx, new Error("A Lune compaction operation is already active"));
|
|
240
|
+
return { cancel: true };
|
|
241
|
+
}
|
|
242
|
+
const generation = this.generation;
|
|
243
|
+
const cancel = new AbortController();
|
|
244
|
+
this.active = cancel;
|
|
245
|
+
const run: CompactionRun = {
|
|
246
|
+
id: ++this.sequence,
|
|
247
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
248
|
+
leafId: ctx.sessionManager.getLeafId(),
|
|
249
|
+
reason: event.reason,
|
|
250
|
+
startedAt: Date.now(),
|
|
251
|
+
stage: "preparing",
|
|
252
|
+
completedBatches: 0,
|
|
253
|
+
totalBatches: 0,
|
|
254
|
+
};
|
|
255
|
+
const previousRun = this.run;
|
|
256
|
+
this.run = run;
|
|
257
|
+
let reviewing = false;
|
|
258
|
+
const signal = AbortSignal.any([event.signal, cancel.signal]);
|
|
259
|
+
const assertActive = (): void => {
|
|
260
|
+
signal.throwIfAborted();
|
|
261
|
+
if (
|
|
262
|
+
generation !== this.generation ||
|
|
263
|
+
ctx.sessionManager.getSessionId() !== run.sessionId ||
|
|
264
|
+
ctx.sessionManager.getLeafId() !== run.leafId
|
|
265
|
+
) {
|
|
266
|
+
cancel.abort(
|
|
267
|
+
new DOMException("Compaction session changed before commit", "AbortError"),
|
|
268
|
+
);
|
|
269
|
+
signal.throwIfAborted();
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
try {
|
|
273
|
+
assertActive();
|
|
274
|
+
// Freeze resolved configuration before any request so a split turn cannot mix settings.
|
|
275
|
+
const configuration = structuredClone(await this.getConfiguration(ctx));
|
|
276
|
+
assertActive();
|
|
277
|
+
if (configuration === null) {
|
|
278
|
+
// Disabling interception is a configured mode, never a response to failure.
|
|
279
|
+
this.run = previousRun;
|
|
280
|
+
this.publish(ctx, undefined);
|
|
281
|
+
return {};
|
|
282
|
+
}
|
|
283
|
+
validateOptions(configuration);
|
|
284
|
+
run.summaryModel = configuration.summaryModel;
|
|
285
|
+
run.policyVersion = COMPACTION_POLICY_VERSION;
|
|
286
|
+
const model = ctx.modelRegistry.find(
|
|
287
|
+
configuration.summaryModel.provider,
|
|
288
|
+
configuration.summaryModel.id,
|
|
289
|
+
);
|
|
290
|
+
if (!model)
|
|
291
|
+
throw new Error(
|
|
292
|
+
`Summary model ${configuration.summaryModel.provider}/${configuration.summaryModel.id} is not registered`,
|
|
293
|
+
);
|
|
294
|
+
const thinkingLevel = clampThinkingLevel(model, configuration.summaryThinkingLevel);
|
|
295
|
+
// Native compact reads preparation without mutating it; only the review replaces these message arrays.
|
|
296
|
+
const preparation = { ...event.preparation };
|
|
297
|
+
if (configuration.jev.enabled) {
|
|
298
|
+
reviewing = true;
|
|
299
|
+
this.publish(ctx, run);
|
|
300
|
+
const classifier = await resolveClassifier(configuration.jev.model, ctx, signal);
|
|
301
|
+
assertActive();
|
|
302
|
+
const reviewModel = `${classifier.provider}/${classifier.id}`;
|
|
303
|
+
this.publish(ctx, run, { reviewModel });
|
|
304
|
+
const reviewed = await reviewToolHistory(
|
|
305
|
+
event,
|
|
306
|
+
ctx,
|
|
307
|
+
configuration.policy,
|
|
308
|
+
classifier,
|
|
309
|
+
configuration.jev.concurrency,
|
|
310
|
+
signal,
|
|
311
|
+
(update) => {
|
|
312
|
+
assertActive();
|
|
313
|
+
run.stage = update.stage;
|
|
314
|
+
run.completedBatches = update.completedBatches;
|
|
315
|
+
run.totalBatches = update.totalBatches;
|
|
316
|
+
this.publish(ctx, run, { reviewModel, review: update });
|
|
317
|
+
},
|
|
318
|
+
);
|
|
319
|
+
assertActive();
|
|
320
|
+
preparation.messagesToSummarize = reviewed.messagesToSummarize;
|
|
321
|
+
preparation.turnPrefixMessages = reviewed.turnPrefixMessages;
|
|
322
|
+
run.jev = reviewed.report;
|
|
323
|
+
} else {
|
|
324
|
+
// A notice from an earlier review would describe a checkpoint this run replaces.
|
|
325
|
+
this.publish(ctx, undefined);
|
|
326
|
+
}
|
|
327
|
+
assertActive();
|
|
328
|
+
run.stage = "summarizing";
|
|
329
|
+
if (run.jev) this.publish(ctx, run);
|
|
330
|
+
const result = await compact(
|
|
331
|
+
preparation,
|
|
332
|
+
model,
|
|
333
|
+
undefined,
|
|
334
|
+
undefined,
|
|
335
|
+
event.customInstructions,
|
|
336
|
+
signal,
|
|
337
|
+
thinkingLevel,
|
|
338
|
+
createSummaryStream(ctx, signal, assertActive),
|
|
339
|
+
);
|
|
340
|
+
assertActive();
|
|
341
|
+
run.summaryUsage = result.usage;
|
|
342
|
+
run.summary = result.summary;
|
|
343
|
+
run.stage = "awaiting-commit";
|
|
344
|
+
const details = result.details as { readFiles: string[]; modifiedFiles: string[] };
|
|
345
|
+
return {
|
|
346
|
+
compaction: {
|
|
347
|
+
...result,
|
|
348
|
+
details: {
|
|
349
|
+
...details,
|
|
350
|
+
luneCompaction: {
|
|
351
|
+
runId: run.id,
|
|
352
|
+
policyVersion: COMPACTION_POLICY_VERSION,
|
|
353
|
+
summaryModel: configuration.summaryModel,
|
|
354
|
+
summaryThinkingLevel: thinkingLevel,
|
|
355
|
+
reason: event.reason,
|
|
356
|
+
jev: run.jev ? checkpointRecord(run.jev) : { enabled: false },
|
|
357
|
+
},
|
|
358
|
+
},
|
|
359
|
+
},
|
|
360
|
+
};
|
|
361
|
+
} catch (error) {
|
|
362
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
363
|
+
const cancelled =
|
|
364
|
+
signal.aborted || generation !== this.generation || failure.name === "AbortError";
|
|
365
|
+
run.stage = cancelled ? "cancelled" : "failed";
|
|
366
|
+
run.finishedAt = Date.now();
|
|
367
|
+
if (!cancelled) {
|
|
368
|
+
run.error = failure;
|
|
369
|
+
this.report(ctx, failure);
|
|
370
|
+
}
|
|
371
|
+
// A retired session already cleared its notice; its context must not draw a new one.
|
|
372
|
+
if (reviewing && generation === this.generation) this.publish(ctx, run);
|
|
373
|
+
return { cancel: true };
|
|
374
|
+
} finally {
|
|
375
|
+
if (this.active === cancel) this.active = undefined;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
dispose(): void {
|
|
380
|
+
this.invalidate();
|
|
381
|
+
for (const unregister of this.unregister.splice(0)) unregister();
|
|
382
|
+
}
|
|
383
|
+
}
|
package/src/extension.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { bindSettings } from "@lune_99/pi-lune-extensions-core/settings";
|
|
3
|
+
import { registerSettingsPanel } from "@lune_99/pi-lune-extensions-core/panel";
|
|
4
|
+
import { ResourceScope } from "@lune_99/pi-lune-extensions-core/resources";
|
|
5
|
+
import { CompactionController } from "./compaction-controller.ts";
|
|
6
|
+
import { resolveCompactionSettings } from "./settings/schema.ts";
|
|
7
|
+
import { compactionSettings, createCompactionPanel } from "./settings/section.ts";
|
|
8
|
+
import { createReviewNotice } from "./ui/review-notice.ts";
|
|
9
|
+
|
|
10
|
+
export async function installConfiguredCompaction(pi: ExtensionAPI) {
|
|
11
|
+
const resources = new ResourceScope();
|
|
12
|
+
resources.defer(pi.on("session_shutdown", () => resources.dispose()));
|
|
13
|
+
try {
|
|
14
|
+
const settings = resources.use(bindSettings(pi, compactionSettings));
|
|
15
|
+
resources.use(
|
|
16
|
+
registerSettingsPanel(
|
|
17
|
+
createCompactionPanel(() => pi.getAllTools()),
|
|
18
|
+
settings,
|
|
19
|
+
),
|
|
20
|
+
);
|
|
21
|
+
const controller = resources.use(
|
|
22
|
+
new CompactionController(
|
|
23
|
+
pi,
|
|
24
|
+
async (ctx) => {
|
|
25
|
+
const view = await settings.view(ctx);
|
|
26
|
+
return resolveCompactionSettings(view.snapshot(), ctx);
|
|
27
|
+
},
|
|
28
|
+
{ onRunChange: createReviewNotice(pi) },
|
|
29
|
+
),
|
|
30
|
+
);
|
|
31
|
+
return { controller, dispose: () => resources.dispose() };
|
|
32
|
+
} catch (error) {
|
|
33
|
+
try {
|
|
34
|
+
await resources.dispose();
|
|
35
|
+
} catch (cleanupError) {
|
|
36
|
+
// eslint-disable-next-line preserve-caught-error -- AggregateError.errors retains both failures.
|
|
37
|
+
throw new AggregateError([error, cleanupError], "Compaction setup and cleanup failed");
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export default async function luneCompaction(pi: ExtensionAPI): Promise<void> {
|
|
44
|
+
await installConfiguredCompaction(pi);
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionFactory } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { CompactionController } from "./compaction-controller.ts";
|
|
3
|
+
import type { ConfigurationProvider } from "./options.ts";
|
|
4
|
+
import { createReviewNotice } from "./ui/review-notice.ts";
|
|
5
|
+
|
|
6
|
+
export type {
|
|
7
|
+
CompactionController,
|
|
8
|
+
CompactionRun,
|
|
9
|
+
CompactionRunListener,
|
|
10
|
+
CompactionRunUpdate,
|
|
11
|
+
CompactionStage,
|
|
12
|
+
} from "./compaction-controller.ts";
|
|
13
|
+
export { DEFAULT_CLASSIFIER_CONCURRENCY, DEFAULT_COMPACTION_POLICY } from "./options.ts";
|
|
14
|
+
export type {
|
|
15
|
+
CompactionOptions,
|
|
16
|
+
CompactionPolicy,
|
|
17
|
+
ConfigurationProvider,
|
|
18
|
+
JevOptions,
|
|
19
|
+
} from "./options.ts";
|
|
20
|
+
export type { ProtectedTool, ResultChunk } from "./tool-review/candidates.ts";
|
|
21
|
+
export type { BudgetFallback, ChunkDecision, ToolReviewReport } from "./tool-review/review.ts";
|
|
22
|
+
|
|
23
|
+
export function installCompaction(
|
|
24
|
+
pi: ExtensionAPI,
|
|
25
|
+
getConfiguration: ConfigurationProvider,
|
|
26
|
+
): CompactionController {
|
|
27
|
+
return new CompactionController(pi, getConfiguration, { onRunChange: createReviewNotice(pi) });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Embedded consumers own configuration; the standalone Pi entry uses Core settings. */
|
|
31
|
+
export function createCompactionExtension(
|
|
32
|
+
getConfiguration: ConfigurationProvider,
|
|
33
|
+
): ExtensionFactory {
|
|
34
|
+
return (pi) => {
|
|
35
|
+
installCompaction(pi, getConfiguration);
|
|
36
|
+
};
|
|
37
|
+
}
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { ModelThinkingLevel } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { ModelReference } from "@lune_99/pi-lune-extensions-core/panel";
|
|
4
|
+
|
|
5
|
+
export interface CompactionPolicy {
|
|
6
|
+
readonly deleteThreshold: number;
|
|
7
|
+
/** Tool names explicitly allowed to lose their whole call. */
|
|
8
|
+
readonly deletableTools: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** A null model selects the first available Pi classifier at run time. */
|
|
12
|
+
export type JevOptions =
|
|
13
|
+
| { readonly enabled: false }
|
|
14
|
+
| {
|
|
15
|
+
readonly enabled: true;
|
|
16
|
+
readonly model: ModelReference | null;
|
|
17
|
+
/** Classifier requests in flight at once during a review. */
|
|
18
|
+
readonly concurrency: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export interface CompactionOptions {
|
|
22
|
+
readonly summaryModel: ModelReference;
|
|
23
|
+
readonly summaryThinkingLevel: ModelThinkingLevel;
|
|
24
|
+
readonly jev: JevOptions;
|
|
25
|
+
readonly policy: CompactionPolicy;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Explicit null disables Lune interception and leaves the native Pi operation untouched. */
|
|
29
|
+
export type ConfigurationProvider = (
|
|
30
|
+
ctx: ExtensionContext,
|
|
31
|
+
) => CompactionOptions | null | Promise<CompactionOptions | null>;
|
|
32
|
+
|
|
33
|
+
export const DEFAULT_COMPACTION_POLICY: CompactionPolicy = Object.freeze({
|
|
34
|
+
deleteThreshold: 0.7,
|
|
35
|
+
deletableTools: Object.freeze([
|
|
36
|
+
"read",
|
|
37
|
+
"grep",
|
|
38
|
+
"find",
|
|
39
|
+
"ls",
|
|
40
|
+
"codemode",
|
|
41
|
+
"bash",
|
|
42
|
+
"edit",
|
|
43
|
+
"powershell",
|
|
44
|
+
"tool_search",
|
|
45
|
+
]),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
export const DEFAULT_CLASSIFIER_CONCURRENCY = 2;
|
|
49
|
+
// A terminal request failure cancels the review, so the cap bounds rate-limit failures.
|
|
50
|
+
export const MAX_CLASSIFIER_CONCURRENCY = 16;
|
|
51
|
+
|
|
52
|
+
/** Embedded providers bypass settings schema validation, so every operation rechecks its options. */
|
|
53
|
+
export function validateOptions(options: CompactionOptions): void {
|
|
54
|
+
const identity = options.summaryModel;
|
|
55
|
+
if (!identity.provider.trim() || !identity.id.trim())
|
|
56
|
+
throw new Error("A summary model must be explicitly selected");
|
|
57
|
+
const policy = options.policy;
|
|
58
|
+
if (
|
|
59
|
+
!Number.isFinite(policy.deleteThreshold) ||
|
|
60
|
+
policy.deleteThreshold < 0 ||
|
|
61
|
+
policy.deleteThreshold > 1
|
|
62
|
+
) {
|
|
63
|
+
throw new Error("deleteThreshold must be between 0 and 1, inclusive");
|
|
64
|
+
}
|
|
65
|
+
if (
|
|
66
|
+
new Set(policy.deletableTools).size !== policy.deletableTools.length ||
|
|
67
|
+
policy.deletableTools.some((name) => !name.trim())
|
|
68
|
+
) {
|
|
69
|
+
throw new Error("deletableTools must contain unique, non-empty tool names");
|
|
70
|
+
}
|
|
71
|
+
if (
|
|
72
|
+
options.jev.enabled &&
|
|
73
|
+
options.jev.model &&
|
|
74
|
+
(!options.jev.model.provider.trim() || !options.jev.model.id.trim())
|
|
75
|
+
) {
|
|
76
|
+
throw new Error("Classifier reference must contain a provider and model id");
|
|
77
|
+
}
|
|
78
|
+
if (
|
|
79
|
+
options.jev.enabled &&
|
|
80
|
+
(!Number.isSafeInteger(options.jev.concurrency) ||
|
|
81
|
+
options.jev.concurrency < 1 ||
|
|
82
|
+
options.jev.concurrency > MAX_CLASSIFIER_CONCURRENCY)
|
|
83
|
+
) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Classifier concurrency must be an integer from 1 to ${MAX_CLASSIFIER_CONCURRENCY}`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { SettingsView, DeepReadonly } from "@lune_99/pi-lune-extensions-core/settings";
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_CLASSIFIER_CONCURRENCY,
|
|
6
|
+
DEFAULT_COMPACTION_POLICY,
|
|
7
|
+
MAX_CLASSIFIER_CONCURRENCY,
|
|
8
|
+
validateOptions,
|
|
9
|
+
type CompactionOptions,
|
|
10
|
+
} from "../options.ts";
|
|
11
|
+
|
|
12
|
+
export const SETTINGS_ID = "pi-compaction";
|
|
13
|
+
|
|
14
|
+
const modelReference = () =>
|
|
15
|
+
Type.Union(
|
|
16
|
+
[
|
|
17
|
+
Type.Null(),
|
|
18
|
+
Type.Object(
|
|
19
|
+
{ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) },
|
|
20
|
+
{ additionalProperties: false },
|
|
21
|
+
),
|
|
22
|
+
],
|
|
23
|
+
{ default: null },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
export const compactionSchema = Type.Object(
|
|
27
|
+
{
|
|
28
|
+
enabled: Type.Boolean({ default: true }),
|
|
29
|
+
summaryModel: modelReference(),
|
|
30
|
+
summaryThinkingLevel: Type.Enum(
|
|
31
|
+
["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const,
|
|
32
|
+
{ type: "string", default: "off" },
|
|
33
|
+
),
|
|
34
|
+
jevEnabled: Type.Boolean({ default: false }),
|
|
35
|
+
classifier: modelReference(),
|
|
36
|
+
classifierConcurrency: Type.Integer({
|
|
37
|
+
minimum: 1,
|
|
38
|
+
maximum: MAX_CLASSIFIER_CONCURRENCY,
|
|
39
|
+
default: DEFAULT_CLASSIFIER_CONCURRENCY,
|
|
40
|
+
}),
|
|
41
|
+
policy: Type.Object(
|
|
42
|
+
{
|
|
43
|
+
deleteThreshold: Type.Number({ minimum: 0, maximum: 1 }),
|
|
44
|
+
deletableTools: Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true }),
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
default: {
|
|
48
|
+
...DEFAULT_COMPACTION_POLICY,
|
|
49
|
+
deletableTools: [...DEFAULT_COMPACTION_POLICY.deletableTools],
|
|
50
|
+
},
|
|
51
|
+
additionalProperties: false,
|
|
52
|
+
},
|
|
53
|
+
),
|
|
54
|
+
},
|
|
55
|
+
{ additionalProperties: false },
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export type CompactionSettings = Static<typeof compactionSchema>;
|
|
59
|
+
export type CompactionSettingsView = SettingsView<typeof compactionSchema>;
|
|
60
|
+
|
|
61
|
+
export function resolveCompactionSettings(
|
|
62
|
+
settings: DeepReadonly<CompactionSettings>,
|
|
63
|
+
session?: Pick<ExtensionContext, "model" | "thinkingLevel">,
|
|
64
|
+
): CompactionOptions | null {
|
|
65
|
+
if (!settings.enabled) return null;
|
|
66
|
+
const summaryModel = settings.summaryModel ?? session?.model;
|
|
67
|
+
if (!summaryModel) throw new Error("No session model is available for the compaction summary");
|
|
68
|
+
const options: CompactionOptions = {
|
|
69
|
+
summaryModel: { provider: summaryModel.provider, id: summaryModel.id },
|
|
70
|
+
summaryThinkingLevel: settings.summaryModel
|
|
71
|
+
? settings.summaryThinkingLevel
|
|
72
|
+
: (session?.thinkingLevel ?? "off"),
|
|
73
|
+
policy: { ...settings.policy, deletableTools: [...settings.policy.deletableTools] },
|
|
74
|
+
jev: settings.jevEnabled
|
|
75
|
+
? {
|
|
76
|
+
enabled: true,
|
|
77
|
+
model: settings.classifier,
|
|
78
|
+
concurrency: settings.classifierConcurrency,
|
|
79
|
+
}
|
|
80
|
+
: { enabled: false },
|
|
81
|
+
};
|
|
82
|
+
validateOptions(options);
|
|
83
|
+
return options;
|
|
84
|
+
}
|