@lune_99/pi-compaction 0.0.0-stage → 0.1.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/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
- "name": "@lune_99/pi-compaction",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@lune_99/pi-compaction",
3
+ "version": "0.1.0",
4
+ "description": "Model-selectable native Pi compaction with classifier-reviewed tool history",
5
+ "type": "module",
6
+ "files": [
7
+ "src",
8
+ "docs",
9
+ "README.md",
10
+ "CHANGELOG.md",
11
+ "LICENSE"
12
+ ],
13
+ "exports": {
14
+ ".": "./src/index.ts"
15
+ },
16
+ "scripts": {
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "node --experimental-strip-types --test 'test/**/*.test.ts'",
19
+ "prepublishOnly": "npm run typecheck && npm test",
20
+ "docs:images": "node --experimental-strip-types tools/make-doc-images.mjs"
21
+ },
22
+ "engines": {
23
+ "node": ">=22.19.0"
24
+ },
25
+ "license": "MIT",
26
+ "author": "Nouvelle-Lune",
27
+ "peerDependencies": {
28
+ "@earendil-works/pi-agent-core": ">=1.0.4",
29
+ "@earendil-works/pi-ai": ">=1.0.4",
30
+ "@earendil-works/pi-coding-agent": ">=1.0.4"
31
+ },
32
+ "devDependencies": {
33
+ "@earendil-works/pi-agent-core": "1.3.0",
34
+ "@earendil-works/pi-ai": "1.3.0",
35
+ "@earendil-works/pi-coding-agent": "1.3.0",
36
+ "@types/node": "^22.20.2",
37
+ "typescript": "5.9.3"
38
+ },
39
+ "dependencies": {
40
+ "@lune_99/pi-lune-extensions-core": "^0.1.0"
41
+ },
42
+ "pi": {
43
+ "extensions": [
44
+ "./src/extension.ts"
45
+ ],
46
+ "image": "./docs/compaction-settings.png"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/Nouvelle-Lune/lune-pi.git",
51
+ "directory": "packages/pi-compaction"
52
+ },
53
+ "homepage": "https://github.com/Nouvelle-Lune/lune-pi/tree/main/packages/pi-compaction#readme",
54
+ "bugs": {
55
+ "url": "https://github.com/Nouvelle-Lune/lune-pi/issues"
56
+ }
57
+ }
@@ -0,0 +1,314 @@
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
+ formatReviewNotice,
16
+ reviewToolHistory,
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
+ /** Route summaries through Pi's registry and reject any split response that did not finish normally. */
50
+ export function createSummaryStream(
51
+ ctx: ExtensionContext,
52
+ signal: AbortSignal,
53
+ assertActive: () => void,
54
+ ): StreamFn {
55
+ return (model, context, options) => {
56
+ assertActive();
57
+ signal.throwIfAborted();
58
+ // Pi owns routing, authentication, output limits and error-event construction.
59
+ // Validate each split-turn response before native compact can combine it with another summary.
60
+ return lazyStream(model, async () => {
61
+ const response = await ctx.modelRegistry
62
+ .streamSimple(model, context, { ...options, signal, maxRetries: 0 })
63
+ .result();
64
+ assertActive();
65
+ signal.throwIfAborted();
66
+ if (response.stopReason !== "stop")
67
+ throw new Error(
68
+ `Summary ${response.stopReason}: ${response.errorMessage ?? "generation did not finish normally"}`,
69
+ );
70
+ if (!contentText(response.content).trim())
71
+ throw new Error("Summary returned empty text");
72
+ // Native compact rejects tool calls and writes the checkpoint through Pi's session lifecycle.
73
+ return (async function* () {
74
+ yield { type: "done" as const, reason: "stop" as const, message: response };
75
+ })();
76
+ });
77
+ };
78
+ }
79
+
80
+ /** Owns every compaction run of one extension instance: its abort controller, generation and commit tracking. */
81
+ export class CompactionController {
82
+ private generation = 0;
83
+ private sequence = 0;
84
+ private active: AbortController | undefined;
85
+ private run: CompactionRun | undefined;
86
+ private readonly unregister: (() => void)[] = [];
87
+ private readonly getConfiguration: ConfigurationProvider;
88
+
89
+ constructor(pi: ExtensionAPI, getConfiguration: ConfigurationProvider) {
90
+ this.getConfiguration = getConfiguration;
91
+ this.unregister.push(
92
+ pi.on("session_before_compact", (event, ctx) => this.beforeCompact(event, ctx)),
93
+ pi.on("session_start", () => {
94
+ this.invalidate();
95
+ this.run = undefined;
96
+ }),
97
+ pi.on("session_shutdown", () => this.invalidate()),
98
+ pi.on("session_before_switch", () => this.invalidate()),
99
+ pi.on("session_before_fork", () => this.invalidate()),
100
+ pi.on("session_before_tree", () => this.invalidate()),
101
+ pi.on("session_compact", (event, ctx) => {
102
+ const run = this.awaitingCommit(ctx);
103
+ if (!run) return;
104
+ const details = event.compactionEntry.details as
105
+ | { luneCompaction?: { runId?: number } }
106
+ | undefined;
107
+ if (
108
+ details?.luneCompaction?.runId !== run.id ||
109
+ event.compactionEntry.summary !== run.summary
110
+ ) {
111
+ run.stage = "failed";
112
+ run.error = new Error(
113
+ "Another compaction handler replaced the generated checkpoint",
114
+ );
115
+ this.report(ctx, run.error);
116
+ } else {
117
+ run.stage = "complete";
118
+ }
119
+ run.finishedAt = Date.now();
120
+ }),
121
+ pi.on("session_compact_failed", (event, ctx) => {
122
+ const run = this.awaitingCommit(ctx);
123
+ if (!run) return;
124
+ run.stage = event.aborted ? "cancelled" : "failed";
125
+ run.finishedAt = Date.now();
126
+ if (!event.aborted) {
127
+ run.error = new Error(
128
+ event.errorMessage ?? "Pi failed to commit the generated checkpoint",
129
+ );
130
+ this.report(ctx, run.error);
131
+ }
132
+ }),
133
+ );
134
+ }
135
+
136
+ getRun(): Readonly<CompactionRun> | undefined {
137
+ if (!this.run) return undefined;
138
+ // Inspection must not let a future UI mutate private model choices or decision/cost records.
139
+ const { error, ...data } = this.run;
140
+ const snapshot = structuredClone(data);
141
+ return Object.freeze(error === undefined ? snapshot : { ...snapshot, error });
142
+ }
143
+
144
+ private awaitingCommit(ctx: ExtensionContext): CompactionRun | undefined {
145
+ const run = this.run;
146
+ return run?.stage === "awaiting-commit" &&
147
+ run.sessionId === ctx.sessionManager.getSessionId()
148
+ ? run
149
+ : undefined;
150
+ }
151
+
152
+ private invalidate(): void {
153
+ this.generation++;
154
+ this.active?.abort(new DOMException("Compaction session was retired", "AbortError"));
155
+ if (this.run?.stage === "awaiting-commit") {
156
+ this.run.stage = "cancelled";
157
+ this.run.finishedAt = Date.now();
158
+ }
159
+ }
160
+
161
+ private report(ctx: ExtensionContext, error: Error): void {
162
+ // Error reporting must not turn a cancel result into a swallowed hook exception.
163
+ console.error("[pi-compaction]", error);
164
+ if (ctx.hasUI) {
165
+ try {
166
+ ctx.ui.notify(`Lune compaction failed: ${error.message}`, "error");
167
+ } catch (notificationError) {
168
+ console.error("[pi-compaction] Error notification failed", notificationError);
169
+ }
170
+ }
171
+ }
172
+
173
+ async beforeCompact(
174
+ event: SessionBeforeCompactEvent,
175
+ ctx: ExtensionContext,
176
+ ): Promise<SessionBeforeCompactResult> {
177
+ if (this.active || this.run?.stage === "awaiting-commit") {
178
+ this.report(ctx, new Error("A Lune compaction operation is already active"));
179
+ return { cancel: true };
180
+ }
181
+ const generation = this.generation;
182
+ const cancel = new AbortController();
183
+ this.active = cancel;
184
+ const run: CompactionRun = {
185
+ id: ++this.sequence,
186
+ sessionId: ctx.sessionManager.getSessionId(),
187
+ leafId: ctx.sessionManager.getLeafId(),
188
+ reason: event.reason,
189
+ startedAt: Date.now(),
190
+ stage: "preparing",
191
+ completedBatches: 0,
192
+ totalBatches: 0,
193
+ };
194
+ const previousRun = this.run;
195
+ this.run = run;
196
+ const signal = AbortSignal.any([event.signal, cancel.signal]);
197
+ const assertActive = (): void => {
198
+ signal.throwIfAborted();
199
+ if (
200
+ generation !== this.generation ||
201
+ ctx.sessionManager.getSessionId() !== run.sessionId ||
202
+ ctx.sessionManager.getLeafId() !== run.leafId
203
+ ) {
204
+ cancel.abort(
205
+ new DOMException("Compaction session changed before commit", "AbortError"),
206
+ );
207
+ signal.throwIfAborted();
208
+ }
209
+ };
210
+ try {
211
+ assertActive();
212
+ // Freeze resolved configuration before any request so a split turn cannot mix settings.
213
+ const configuration = structuredClone(await this.getConfiguration(ctx));
214
+ assertActive();
215
+ if (configuration === null) {
216
+ // Disabling interception is a configured mode, never a response to failure.
217
+ this.run = previousRun;
218
+ return {};
219
+ }
220
+ validateOptions(configuration);
221
+ run.summaryModel = configuration.summaryModel;
222
+ run.policyVersion = COMPACTION_POLICY_VERSION;
223
+ const model = ctx.modelRegistry.find(
224
+ configuration.summaryModel.provider,
225
+ configuration.summaryModel.id,
226
+ );
227
+ if (!model)
228
+ throw new Error(
229
+ `Summary model ${configuration.summaryModel.provider}/${configuration.summaryModel.id} is not registered`,
230
+ );
231
+ const thinkingLevel = clampThinkingLevel(model, configuration.summaryThinkingLevel);
232
+ // Native compact reads preparation without mutating it; only the review replaces these message arrays.
233
+ const preparation = { ...event.preparation };
234
+ if (configuration.jev.enabled) {
235
+ const reviewed = await reviewToolHistory(
236
+ event,
237
+ ctx,
238
+ configuration.policy,
239
+ await resolveClassifier(configuration.jev.model, ctx, signal),
240
+ signal,
241
+ (update) => {
242
+ assertActive();
243
+ run.stage = update.stage;
244
+ run.completedBatches = update.completedBatches;
245
+ run.totalBatches = update.totalBatches;
246
+ },
247
+ );
248
+ assertActive();
249
+ preparation.messagesToSummarize = reviewed.messagesToSummarize;
250
+ preparation.turnPrefixMessages = reviewed.turnPrefixMessages;
251
+ run.jev = reviewed.report;
252
+ if (ctx.hasUI) {
253
+ try {
254
+ const theme = ctx.ui.theme;
255
+ ctx.ui.notify(theme.fg("dim", formatReviewNotice(reviewed.report)), "info");
256
+ } catch (notificationError) {
257
+ console.warn("[pi-compaction] Notification failed", notificationError);
258
+ }
259
+ }
260
+ }
261
+ assertActive();
262
+ run.stage = "summarizing";
263
+ const result = await compact(
264
+ preparation,
265
+ model,
266
+ undefined,
267
+ undefined,
268
+ event.customInstructions,
269
+ signal,
270
+ thinkingLevel,
271
+ createSummaryStream(ctx, signal, assertActive),
272
+ );
273
+ assertActive();
274
+ run.summaryUsage = result.usage;
275
+ run.summary = result.summary;
276
+ run.stage = "awaiting-commit";
277
+ const details = result.details as { readFiles: string[]; modifiedFiles: string[] };
278
+ return {
279
+ compaction: {
280
+ ...result,
281
+ details: {
282
+ ...details,
283
+ luneCompaction: {
284
+ runId: run.id,
285
+ policyVersion: COMPACTION_POLICY_VERSION,
286
+ summaryModel: configuration.summaryModel,
287
+ summaryThinkingLevel: thinkingLevel,
288
+ reason: event.reason,
289
+ jev: run.jev ? checkpointRecord(run.jev) : { enabled: false },
290
+ },
291
+ },
292
+ },
293
+ };
294
+ } catch (error) {
295
+ const failure = error instanceof Error ? error : new Error(String(error));
296
+ const cancelled =
297
+ signal.aborted || generation !== this.generation || failure.name === "AbortError";
298
+ run.stage = cancelled ? "cancelled" : "failed";
299
+ run.finishedAt = Date.now();
300
+ if (!cancelled) {
301
+ run.error = failure;
302
+ this.report(ctx, failure);
303
+ }
304
+ return { cancel: true };
305
+ } finally {
306
+ if (this.active === cancel) this.active = undefined;
307
+ }
308
+ }
309
+
310
+ dispose(): void {
311
+ this.invalidate();
312
+ for (const unregister of this.unregister.splice(0)) unregister();
313
+ }
314
+ }
@@ -0,0 +1,39 @@
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
+
9
+ export async function installConfiguredCompaction(pi: ExtensionAPI) {
10
+ const resources = new ResourceScope();
11
+ resources.defer(pi.on("session_shutdown", () => resources.dispose()));
12
+ try {
13
+ const settings = resources.use(bindSettings(pi, compactionSettings));
14
+ resources.use(
15
+ registerSettingsPanel(
16
+ createCompactionPanel(() => pi.getAllTools()),
17
+ settings,
18
+ ),
19
+ );
20
+ const controller = resources.use(
21
+ new CompactionController(pi, async (ctx) => {
22
+ const view = await settings.view(ctx);
23
+ return resolveCompactionSettings(view.snapshot(), ctx);
24
+ }),
25
+ );
26
+ return { controller, dispose: () => resources.dispose() };
27
+ } catch (error) {
28
+ try {
29
+ await resources.dispose();
30
+ } catch (cleanupError) {
31
+ throw new AggregateError([error, cleanupError], "Compaction setup and cleanup failed");
32
+ }
33
+ throw error;
34
+ }
35
+ }
36
+
37
+ export default async function luneCompaction(pi: ExtensionAPI): Promise<void> {
38
+ await installConfiguredCompaction(pi);
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
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
+
5
+ export type {
6
+ CompactionController,
7
+ CompactionRun,
8
+ CompactionStage,
9
+ } from "./compaction-controller.ts";
10
+ export { DEFAULT_COMPACTION_POLICY } from "./options.ts";
11
+ export type {
12
+ CompactionOptions,
13
+ CompactionPolicy,
14
+ ConfigurationProvider,
15
+ JevOptions,
16
+ } from "./options.ts";
17
+ export type { ProtectedTool, ResultChunk } from "./tool-review/candidates.ts";
18
+ export type { BudgetFallback, ChunkDecision, ToolReviewReport } from "./tool-review/review.ts";
19
+
20
+ export function installCompaction(
21
+ pi: ExtensionAPI,
22
+ getConfiguration: ConfigurationProvider,
23
+ ): CompactionController {
24
+ return new CompactionController(pi, getConfiguration);
25
+ }
26
+
27
+ /** Embedded consumers own configuration; the standalone Pi entry uses Core settings. */
28
+ export function createCompactionExtension(
29
+ getConfiguration: ConfigurationProvider,
30
+ ): ExtensionFactory {
31
+ return (pi) => {
32
+ installCompaction(pi, getConfiguration);
33
+ };
34
+ }
package/src/options.ts ADDED
@@ -0,0 +1,69 @@
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
+ | { readonly enabled: true; readonly model: ModelReference | null };
15
+
16
+ export interface CompactionOptions {
17
+ readonly summaryModel: ModelReference;
18
+ readonly summaryThinkingLevel: ModelThinkingLevel;
19
+ readonly jev: JevOptions;
20
+ readonly policy: CompactionPolicy;
21
+ }
22
+
23
+ /** Explicit null disables Lune interception and leaves the native Pi operation untouched. */
24
+ export type ConfigurationProvider = (
25
+ ctx: ExtensionContext,
26
+ ) => CompactionOptions | null | Promise<CompactionOptions | null>;
27
+
28
+ export const DEFAULT_COMPACTION_POLICY: CompactionPolicy = Object.freeze({
29
+ deleteThreshold: 0.7,
30
+ deletableTools: Object.freeze([
31
+ "read",
32
+ "grep",
33
+ "find",
34
+ "ls",
35
+ "codemode",
36
+ "bash",
37
+ "edit",
38
+ "powershell",
39
+ "tool_search",
40
+ ]),
41
+ });
42
+
43
+ /** Embedded providers bypass settings schema validation, so every operation rechecks its options. */
44
+ export function validateOptions(options: CompactionOptions): void {
45
+ const identity = options.summaryModel;
46
+ if (!identity.provider.trim() || !identity.id.trim())
47
+ throw new Error("A summary model must be explicitly selected");
48
+ const policy = options.policy;
49
+ if (
50
+ !Number.isFinite(policy.deleteThreshold) ||
51
+ policy.deleteThreshold < 0 ||
52
+ policy.deleteThreshold > 1
53
+ ) {
54
+ throw new Error("deleteThreshold must be between 0 and 1, inclusive");
55
+ }
56
+ if (
57
+ new Set(policy.deletableTools).size !== policy.deletableTools.length ||
58
+ policy.deletableTools.some((name) => !name.trim())
59
+ ) {
60
+ throw new Error("deletableTools must contain unique, non-empty tool names");
61
+ }
62
+ if (
63
+ options.jev.enabled &&
64
+ options.jev.model &&
65
+ (!options.jev.model.provider.trim() || !options.jev.model.id.trim())
66
+ ) {
67
+ throw new Error("Classifier reference must contain a provider and model id");
68
+ }
69
+ }
@@ -0,0 +1,69 @@
1
+ import { Type, StringEnum, type Static } from "@earendil-works/pi-ai";
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 { DEFAULT_COMPACTION_POLICY, validateOptions, type CompactionOptions } from "../options.ts";
5
+
6
+ export const SETTINGS_ID = "pi-compaction";
7
+
8
+ const modelReference = () =>
9
+ Type.Union(
10
+ [
11
+ Type.Null(),
12
+ Type.Object(
13
+ { provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) },
14
+ { additionalProperties: false },
15
+ ),
16
+ ],
17
+ { default: null },
18
+ );
19
+
20
+ export const compactionSchema = Type.Object(
21
+ {
22
+ enabled: Type.Boolean({ default: true }),
23
+ summaryModel: modelReference(),
24
+ summaryThinkingLevel: StringEnum(
25
+ ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const,
26
+ { default: "off" },
27
+ ),
28
+ jevEnabled: Type.Boolean({ default: false }),
29
+ classifier: modelReference(),
30
+ policy: Type.Object(
31
+ {
32
+ deleteThreshold: Type.Number({ minimum: 0, maximum: 1 }),
33
+ deletableTools: Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true }),
34
+ },
35
+ {
36
+ default: {
37
+ ...DEFAULT_COMPACTION_POLICY,
38
+ deletableTools: [...DEFAULT_COMPACTION_POLICY.deletableTools],
39
+ },
40
+ additionalProperties: false,
41
+ },
42
+ ),
43
+ },
44
+ { additionalProperties: false },
45
+ );
46
+
47
+ export type CompactionSettings = Static<typeof compactionSchema>;
48
+ export type CompactionSettingsView = SettingsView<typeof compactionSchema>;
49
+
50
+ export function resolveCompactionSettings(
51
+ settings: DeepReadonly<CompactionSettings>,
52
+ session?: Pick<ExtensionContext, "model" | "thinkingLevel">,
53
+ ): CompactionOptions | null {
54
+ if (!settings.enabled) return null;
55
+ const summaryModel = settings.summaryModel ?? session?.model;
56
+ if (!summaryModel) throw new Error("No session model is available for the compaction summary");
57
+ const options: CompactionOptions = {
58
+ summaryModel: { provider: summaryModel.provider, id: summaryModel.id },
59
+ summaryThinkingLevel: settings.summaryModel
60
+ ? settings.summaryThinkingLevel
61
+ : (session?.thinkingLevel ?? "off"),
62
+ policy: { ...settings.policy, deletableTools: [...settings.policy.deletableTools] },
63
+ jev: settings.jevEnabled
64
+ ? { enabled: true, model: settings.classifier }
65
+ : { enabled: false },
66
+ };
67
+ validateOptions(options);
68
+ return options;
69
+ }