@pinet/model-aware-compaction 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Will Porcellini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @pinet/model-aware-compaction
2
+
3
+ A Pi extension that triggers proactive compaction at different active-context token limits for different models. It adapts Pi's shipped `trigger-compact.ts` example to multi-model and subagent workloads.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:@pinet/model-aware-compaction
9
+ ```
10
+
11
+ For local development from a clone of this repository, load the source directly:
12
+
13
+ ```bash
14
+ pi --extension /path/to/extensions/model-aware-compaction/index.ts
15
+ ```
16
+
17
+ ## Configure
18
+
19
+ The extension is disabled by default. Add this to project `.pi/settings.json` or global `~/.pi/agent/settings.json`:
20
+
21
+ ```json
22
+ {
23
+ "model-aware-compaction": {
24
+ "enabled": true,
25
+ "rules": [
26
+ { "model": "openai/gpt-5-mini", "activeContextTokens": 100000 },
27
+ { "model": "anthropic/claude-sonnet-4-6", "activeContextTokens": 100000 },
28
+ { "model": "example-proxy/*", "activeContextTokens": 136000 }
29
+ ],
30
+ "customInstructions": "Preserve decisions, files changed, validation results, and next steps.",
31
+ "debug": false
32
+ }
33
+ }
34
+ ```
35
+
36
+ Rules are evaluated in order. `*` wildcards are supported, such as `example-proxy/*`.
37
+
38
+ ## Behavior
39
+
40
+ After each `turn_end`, the extension reads `ctx.getContextUsage()` and the active `ctx.model`. When usage first exceeds the matching rule's `activeContextTokens`, it calls `ctx.compact()`. It prevents duplicate calls while compaction is in flight and re-arms after usage drops below the threshold, the model changes, a session starts, or compaction fails.
41
+
42
+ Run `/model-aware-compaction-status` to inspect the active model, usage, matched threshold, state, and loaded rules.
43
+
44
+ ## Limitation
45
+
46
+ Pi's extension API makes `ctx.compact()` fire-and-forget. This package is therefore proactive best effort, not an atomic `compact-before-next-provider-request` barrier. Debug logs make trigger/completion/failure visible so that race behavior can be measured. Upstream model-specific settings or an awaitable/deferred compaction seam would provide a stronger guarantee.
47
+
48
+ ## Development
49
+
50
+ ```bash
51
+ pnpm --filter @pinet/model-aware-compaction lint
52
+ pnpm --filter @pinet/model-aware-compaction typecheck
53
+ pnpm --filter @pinet/model-aware-compaction test
54
+ pnpm --filter @pinet/model-aware-compaction build
55
+ ```
@@ -0,0 +1,20 @@
1
+ import type { CompactionRule } from "./helpers.js";
2
+ export declare const SETTINGS_KEY = "model-aware-compaction";
3
+ export interface ModelAwareCompactionConfig {
4
+ enabled?: boolean;
5
+ rules?: Array<{
6
+ model?: string;
7
+ activeContextTokens?: number;
8
+ }>;
9
+ customInstructions?: string;
10
+ debug?: boolean;
11
+ }
12
+ export interface ResolvedConfig {
13
+ enabled: boolean;
14
+ rules: CompactionRule[];
15
+ customInstructions?: string;
16
+ debug: boolean;
17
+ sourcePath: string | null;
18
+ }
19
+ export declare function resolveConfig(raw?: ModelAwareCompactionConfig | null, sourcePath?: string | null): ResolvedConfig;
20
+ export declare function loadConfig(cwd?: string, agentDir?: string): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,53 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import { join } from "node:path";
4
+ export const SETTINGS_KEY = "model-aware-compaction";
5
+ const DEFAULT_RULES = [
6
+ { model: "openai/gpt-5-mini", activeContextTokens: 100_000 },
7
+ { model: "anthropic/claude-sonnet-4-6", activeContextTokens: 100_000 },
8
+ ];
9
+ function parseSettings(path) {
10
+ if (!fs.existsSync(path))
11
+ return null;
12
+ try {
13
+ const parsed = JSON.parse(fs.readFileSync(path, "utf8"));
14
+ const value = parsed[SETTINGS_KEY];
15
+ if (!value || typeof value !== "object" || Array.isArray(value))
16
+ return null;
17
+ return { raw: value, sourcePath: `${path}#${SETTINGS_KEY}` };
18
+ }
19
+ catch (error) {
20
+ console.error(`[${SETTINGS_KEY}] Failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`);
21
+ return null;
22
+ }
23
+ }
24
+ export function resolveConfig(raw, sourcePath = null) {
25
+ const configured = Array.isArray(raw?.rules)
26
+ ? raw.rules.flatMap((rule) => {
27
+ const model = typeof rule.model === "string" ? rule.model.trim() : "";
28
+ const tokens = rule.activeContextTokens;
29
+ return model && typeof tokens === "number" && Number.isInteger(tokens) && tokens > 0
30
+ ? [{ model, activeContextTokens: tokens }]
31
+ : [];
32
+ })
33
+ : [];
34
+ const customInstructions = typeof raw?.customInstructions === "string" && raw.customInstructions.trim()
35
+ ? raw.customInstructions.trim()
36
+ : undefined;
37
+ return {
38
+ enabled: raw?.enabled === true,
39
+ rules: configured.length > 0 ? configured : DEFAULT_RULES,
40
+ customInstructions,
41
+ debug: raw?.debug === true,
42
+ sourcePath,
43
+ };
44
+ }
45
+ export function loadConfig(cwd = process.cwd(), agentDir = join(os.homedir(), ".pi", "agent")) {
46
+ const project = parseSettings(join(cwd, ".pi", "settings.json"));
47
+ if (project)
48
+ return resolveConfig(project.raw, project.sourcePath);
49
+ const global = parseSettings(join(agentDir, "settings.json"));
50
+ if (global)
51
+ return resolveConfig(global.raw, global.sourcePath);
52
+ return resolveConfig();
53
+ }
@@ -0,0 +1,25 @@
1
+ export interface ModelIdentity {
2
+ provider?: string;
3
+ id?: string;
4
+ }
5
+ export interface CompactionRule {
6
+ model: string;
7
+ activeContextTokens: number;
8
+ }
9
+ export interface CompactionDecision {
10
+ modelKey: string | null;
11
+ limit: number | null;
12
+ shouldCompact: boolean;
13
+ reason: "disabled" | "unknown-model" | "no-rule" | "usage-unavailable" | "below-limit" | "already-triggered" | "in-flight" | "over-limit";
14
+ }
15
+ export declare function modelKey(model: ModelIdentity | undefined): string | null;
16
+ export declare function matchesModel(pattern: string, key: string): boolean;
17
+ export declare function limitForModel(rules: CompactionRule[], key: string): number | null;
18
+ export declare function decideCompaction(input: {
19
+ enabled: boolean;
20
+ model: ModelIdentity | undefined;
21
+ tokens: number | null | undefined;
22
+ rules: CompactionRule[];
23
+ inFlight: boolean;
24
+ triggeredModelKey: string | null;
25
+ }): CompactionDecision;
@@ -0,0 +1,38 @@
1
+ export function modelKey(model) {
2
+ const provider = model?.provider?.trim().toLowerCase();
3
+ const id = model?.id?.trim().toLowerCase();
4
+ if (!provider || !id)
5
+ return null;
6
+ const normalizedId = id.startsWith(`${provider}/`) ? id.slice(provider.length + 1) : id;
7
+ return `${provider}/${normalizedId}`;
8
+ }
9
+ export function matchesModel(pattern, key) {
10
+ const normalized = pattern.trim().toLowerCase();
11
+ if (!normalized)
12
+ return false;
13
+ const escaped = normalized.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*");
14
+ return new RegExp(`^${escaped}$`).test(key);
15
+ }
16
+ export function limitForModel(rules, key) {
17
+ return rules.find((rule) => matchesModel(rule.model, key))?.activeContextTokens ?? null;
18
+ }
19
+ export function decideCompaction(input) {
20
+ const key = modelKey(input.model);
21
+ if (!input.enabled)
22
+ return { modelKey: key, limit: null, shouldCompact: false, reason: "disabled" };
23
+ if (!key)
24
+ return { modelKey: null, limit: null, shouldCompact: false, reason: "unknown-model" };
25
+ const limit = limitForModel(input.rules, key);
26
+ if (limit === null)
27
+ return { modelKey: key, limit: null, shouldCompact: false, reason: "no-rule" };
28
+ if (input.tokens === null || input.tokens === undefined || !Number.isFinite(input.tokens)) {
29
+ return { modelKey: key, limit, shouldCompact: false, reason: "usage-unavailable" };
30
+ }
31
+ if (input.tokens <= limit)
32
+ return { modelKey: key, limit, shouldCompact: false, reason: "below-limit" };
33
+ if (input.inFlight)
34
+ return { modelKey: key, limit, shouldCompact: false, reason: "in-flight" };
35
+ if (input.triggeredModelKey === key)
36
+ return { modelKey: key, limit, shouldCompact: false, reason: "already-triggered" };
37
+ return { modelKey: key, limit, shouldCompact: true, reason: "over-limit" };
38
+ }
@@ -0,0 +1,2 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ export default function modelAwareCompaction(pi: ExtensionAPI): void;
package/dist/index.js ADDED
@@ -0,0 +1,87 @@
1
+ import { loadConfig } from "./config.js";
2
+ import { decideCompaction, modelKey } from "./helpers.js";
3
+ const LOG_PREFIX = "[model-aware-compaction]";
4
+ export default function modelAwareCompaction(pi) {
5
+ const api = pi;
6
+ let inFlight = false;
7
+ let triggeredModelKey = null;
8
+ const rearm = () => {
9
+ triggeredModelKey = null;
10
+ };
11
+ pi.on("session_start", rearm);
12
+ pi.on("model_select", rearm);
13
+ pi.on("turn_end", (_event, rawCtx) => {
14
+ const ctx = rawCtx;
15
+ const config = loadConfig(ctx.cwd);
16
+ const usage = ctx.getContextUsage?.();
17
+ const decision = decideCompaction({
18
+ enabled: config.enabled,
19
+ model: ctx.model,
20
+ tokens: usage?.tokens,
21
+ rules: config.rules,
22
+ inFlight,
23
+ triggeredModelKey,
24
+ });
25
+ if (decision.reason === "below-limit" && triggeredModelKey === decision.modelKey) {
26
+ triggeredModelKey = null;
27
+ }
28
+ if (!decision.shouldCompact || !ctx.compact || !decision.modelKey || decision.limit === null)
29
+ return;
30
+ inFlight = true;
31
+ triggeredModelKey = decision.modelKey;
32
+ const details = `model=${decision.modelKey} tokens=${usage?.tokens ?? "unknown"} limit=${decision.limit}`;
33
+ if (config.debug) {
34
+ console.error(`${LOG_PREFIX} triggered ${details}`);
35
+ if (ctx.hasUI)
36
+ ctx.ui.notify(`Model-aware compaction started (${details})`, "info");
37
+ }
38
+ ctx.compact({
39
+ customInstructions: config.customInstructions,
40
+ onComplete: () => {
41
+ inFlight = false;
42
+ if (config.debug) {
43
+ console.error(`${LOG_PREFIX} completed ${details}`);
44
+ if (ctx.hasUI)
45
+ ctx.ui.notify(`Model-aware compaction completed (${details})`, "info");
46
+ }
47
+ },
48
+ onError: (error) => {
49
+ inFlight = false;
50
+ triggeredModelKey = null;
51
+ console.error(`${LOG_PREFIX} failed ${details}: ${error.message}`);
52
+ if (config.debug && ctx.hasUI)
53
+ ctx.ui.notify(`Model-aware compaction failed: ${error.message}`, "error");
54
+ },
55
+ });
56
+ });
57
+ pi.registerCommand("model-aware-compaction-status", {
58
+ description: "Show model-aware proactive compaction status",
59
+ handler: async (_args, rawCtx) => {
60
+ const ctx = rawCtx;
61
+ const config = loadConfig(ctx.cwd);
62
+ const key = modelKey(ctx.model);
63
+ const usage = ctx.getContextUsage?.();
64
+ const decision = decideCompaction({
65
+ enabled: config.enabled,
66
+ model: ctx.model,
67
+ tokens: usage?.tokens,
68
+ rules: config.rules,
69
+ inFlight,
70
+ triggeredModelKey,
71
+ });
72
+ const lines = [
73
+ "**Model-aware compaction**",
74
+ "",
75
+ `- enabled: ${config.enabled ? "yes" : "no"}`,
76
+ `- current model: ${key ?? "unknown"}`,
77
+ `- current tokens: ${usage?.tokens ?? "unknown"}`,
78
+ `- matched limit: ${decision.limit ?? "none"}`,
79
+ `- state: ${inFlight ? "compacting" : decision.reason}`,
80
+ `- config: ${config.sourcePath ?? "defaults (disabled)"}`,
81
+ "- rules:",
82
+ ...config.rules.map((rule) => ` - ${rule.model}: ${rule.activeContextTokens}`),
83
+ ];
84
+ api.sendMessage({ customType: "model-aware-compaction.status", content: lines.join("\n"), display: true }, { triggerTurn: false });
85
+ },
86
+ });
87
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@pinet/model-aware-compaction",
3
+ "version": "0.2.1",
4
+ "type": "module",
5
+ "description": "Pi extension for proactive model-aware context compaction thresholds",
6
+ "author": "Will Porcellini <5994936+gugu91@users.noreply.github.com>",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/gugu91/extensions.git",
11
+ "directory": "model-aware-compaction"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "README.md",
27
+ "LICENSE",
28
+ "dist/"
29
+ ],
30
+ "keywords": [
31
+ "pi-package",
32
+ "compaction",
33
+ "context-window"
34
+ ],
35
+ "pi": {
36
+ "extensions": [
37
+ "./dist/index.js"
38
+ ]
39
+ },
40
+ "scripts": {
41
+ "build": "node ../scripts/build-package.mjs",
42
+ "prepack": "pnpm run build",
43
+ "lint": "eslint . --ext .ts",
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "vitest run"
46
+ },
47
+ "dependencies": {},
48
+ "peerDependencies": {
49
+ "@earendil-works/pi-coding-agent": ">=0.74.0"
50
+ }
51
+ }