fix(compact): move force tier to agent_settled

Manual compaction (ctx.compact) aborts the active run and never
resumes the interrupted turn (Pi 1.5.2 agent-session.js:2321-2327),
so triggering it from turn_end destroyed in-progress agent work.
The force tier now fires at agent_settled, where ctx.isIdle() is
guaranteed and compaction aborts nothing; Pi's built-in mid-run
threshold check stays the actor and preserves runs.

Also: the settled handler awaits compaction completion so prompts
deferred from settled handlers cannot race an in-flight compaction;
per-field config validation falls back to defaults (null token
values previously zeroed thresholds via Math.min, strings silently
NaN-disabled them); the cached token count is cleared on
session_compact so stale pre-compaction counts cannot re-trigger.

Adds harness.ts: 15-test mock harness (node --test, type
stripping, zero deps) covering both regressions, locks, cooldown,
validation, and cycle resets. README corrected accordingly.
This commit is contained in:
AlexKucera committed 2026-11-15 19:27:40 +01:00
1 parent 2c6d98995a
commit a6cfb51626
3 files changed
+332 -71

No files matched your search

+7 -6
View File
@@ -1,6 +1,6 @@
# Smart Compact
**Two-tier context management for [Pi](https://github.com/earendil-works/pi): a gentle heads-up to the agent when context fills up, and a deliberate compaction at a clean turn boundary before the window is exhausted. Designed to compose with pi-lcm and pi-dcp instead of fighting them.**
**Two-tier context management for [Pi](https://github.com/earendil-works/pi): a gentle heads-up to the agent when context fills up, and a deliberate compaction when the session settles, well before the window is exhausted. Designed to compose with pi-lcm and pi-dcp instead of fighting them.**
## Why Smart Compact
@@ -14,9 +14,9 @@ Smart Compact adds the two missing tiers:
| Tier | Trigger | Action |
|------|---------|--------|
| **Warn** | `min(warnTokens, warnFraction × window)` — default 100k or 55% | One-shot `custom_message` into the context (invisible in the UI, ~60 tokens): prefer targeted searches over full files, consolidate findings, keep key facts stated explicitly. |
| **Force** | `min(forceTokens, forceFraction × window)` — default 200k or 80% | `ctx.compact()` at a clean turn boundary, with a UI notification. Always fires *before* Pi's built-in threshold compaction. |
| **Force** | `min(forceTokens, forceFraction × window)` — default 200k or 80% | `ctx.compact()` at the `agent_settled` boundary — the first moment no run is active, so nothing in progress is aborted. With a UI notification. |
The fractional floors keep both tiers correctly ordered on any window size. On a 128k model: warn ≈ 70k, force ≈ 102k, built-in emergency at 112k. On a 200k model: warn 100k, force 160k, built-in at 184k. The absolute values act as ceilings for very large windows.
The fractional floors keep both tiers correctly ordered on any window size. On a 128k model: warn ≈ 70k, force ≈ 102k, built-in emergency at 112k. On a 200k model: warn 100k, force 160k, built-in at 184k. The absolute values act as ceilings for very large windows. When `(1 − forceFraction) × window > reserveTokens` (defaults: windows above ~82k) the force threshold sits below the built-in trigger, but execution order is not guaranteed: a run that crosses both thresholds before settling lets Pi's built-in check compact first — which is safe, it preserves the run.
## Compatibility
@@ -30,13 +30,13 @@ This is the design center. Smart Compact deliberately touches only the events th
[pi-dcp](https://www.npmjs.com/package/@davecodes/pi-dcp) nudges the model (30k soft / 70k hard by default) toward its `compress` tool, which shrinks old tool results in place. Smart Compact's warn message uses deliberately different language — general frugality and advance notice, not compress-the-tool — so the model doesn't get two copies of the same instruction. It also copies DCP's two hardening patterns:
- **Null-token window.** `ctx.getContextUsage().tokens` returns `null` immediately after compaction (before the first post-compaction response). The last non-null value is cached and used as a fallback.
- **Null-token window.** `ctx.getContextUsage().tokens` returns `null` immediately after compaction (before the first post-compaction response). The last non-null value is cached and used as a fallback — and the cache is cleared on `session_compact`, so a stale pre-compaction count cannot re-trigger the force tier.
- **Cycle reset.** State resets on `session_compact`, so the warn can fire once per compaction cycle rather than once per session. This also catches `/compact`, `/lcm compact`, and Pi's own threshold/overflow compactions.
## Guards
- Warn fires once per cycle (`warnedThisCycle` flag).
- Force is once per cycle with an in-flight lock, plus a 60s cooldown after a failed compaction. Pi's overflow recovery remains the final backstop.
- Force fires only at `agent_settled` (never mid-run), once per cycle with an in-flight lock, plus a 60s cooldown after a failed compaction. Mid-run, Pi's built-in threshold check and overflow recovery remain the actors and preserve the run.
- `continue: true` on the warn entry only forces a model request if the run was ending anyway — mid-run it rides along with the next request free.
## Configuration
@@ -81,10 +81,11 @@ Pi discovers `*/index.ts` one level deep, following the symlink. Reload with `/r
- **Warn is a `custom_message`, not a system-prompt addendum.** Dynamic prompt addendum changes break provider prompt caching; an in-conversation message costs ~60 tokens once and is a valid compaction cut point.
- **Force uses `ctx.compact()` rather than returning a compaction from `session_before_compact`** so pi-lcm (or any other compaction-owning extension) stays in charge of summary generation.
- **Force runs at `agent_settled`, not `turn_end`.** `ctx.compact()` aborts any active run and never resumes the interrupted turn, so triggering it mid-run would destroy agent work. At `agent_settled` the session is idle (`ctx.isIdle()` is guaranteed) and compaction aborts nothing.
- **Thresholds are computed per turn** from `ctx.getContextUsage()`, so model switches mid-session (e.g. to a different window size) take effect immediately.
## Verification
- Loads clean under Pi 1.5.2 (`pi -p` smoke test).
- 16/16 mock-harness assertions: warn fires once per cycle at the effective threshold; force calls `ctx.compact` before the built-in trigger on both 200k and 128k windows; in-flight and failure-cooldown guards; null-token fallback; cycle reset on `session_compact`; status command output.
- 14-test committed harness: `node --test harness.ts` (Node ≥ 22.18 with type stripping). Covers warn-once-per-cycle at the effective threshold, force only at `agent_settled` (never from `turn_end`, not when busy), awaiting compaction completion in the settled handler, the in-flight lock and failure cooldown, the stale-token guard after `session_compact`, per-field config validation (`null`/string/zero/oversized values), cycle reset, `enabled: false`, and the status command.
- Live-session validation of the first real 100k crossing is still pending — the warn message is a single string in `index.ts` if the wording needs tuning.
+223
View File
@@ -0,0 +1,223 @@
/**
* smart-compact mock-harness — run with: node --test harness.ts
* (Node ≥ 22.18 with built-in TypeScript type stripping.)
*
* Drives the extension against a mock Pi: turn_end / agent_settled /
* session_compact events, controllable getContextUsage(), and a ctx.compact
* recorder. Config is injected per scenario via a temp project
* .pi/settings.json (all fields set, so the user's global file cannot leak
* into assertions).
*/
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import smartCompact from "./index.ts";
interface CtxOverrides {
tokens: number | null;
window: number;
onCompact?: (opts: any) => void;
idle?: boolean;
}
function load(settings: Record<string, unknown>) {
const dir = mkdtempSync(path.join(tmpdir(), "smart-compact-test-"));
mkdirSync(path.join(dir, ".pi"));
writeFileSync(
path.join(dir, ".pi", "settings.json"),
JSON.stringify({ smartCompact: settings }),
);
const prevCwd = process.cwd();
process.chdir(dir);
const pi: any = {
handlers: {} as Record<string, any>,
commands: {} as Record<string, any>,
on(name: string, fn: any) {
this.handlers[name] = fn;
},
registerCommand(name: string, def: any) {
this.commands[name] = def;
},
};
try {
smartCompact(pi);
} finally {
process.chdir(prevCwd);
rmSync(dir, { recursive: true, force: true });
}
return pi;
}
function makeCtx({ tokens, window, onCompact, idle = true }: CtxOverrides) {
const calls: { compact: number; notified: string[] } = { compact: 0, notified: [] };
return {
calls,
ctx: {
isIdle: () => idle,
getContextUsage: () => ({ tokens, contextWindow: window }),
ui: { notify: (msg: string) => calls.notified.push(msg) },
compact: (opts: any) => {
calls.compact++;
(onCompact ?? ((o: any) => o?.onComplete?.({})))(opts);
},
},
};
}
const fire = async (pi: any, name: string, ctx: any, event: any = { entries: [] }) =>
await pi.handlers[name](event, ctx);
const FULL = { enabled: true, warnTokens: 60_000, forceTokens: 90_000, warnFraction: 0.55, forceFraction: 0.8 };
// With window 100k: warnAt = min(60k, 55k) = 55k, forceAt = min(90k, 80k) = 80k.
test("warn fires once per cycle at the effective threshold", async () => {
const pi = load(FULL);
const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 });
const first = await fire(pi, "turn_end", ctx);
assert.equal(first.entries.at(-1).customType, "smart-compact-notice");
assert.equal(first.entries.at(-1).display, false);
assert.equal(first.continue, true);
assert.match(first.entries.at(-1).content, /56k tokens/);
const second = await fire(pi, "turn_end", ctx);
assert.equal(second, undefined);
});
test("below warn threshold: no message", async () => {
const pi = load(FULL);
const { ctx } = makeCtx({ tokens: 40_000, window: 100_000 });
assert.equal(await fire(pi, "turn_end", ctx), undefined);
});
test("force tier never triggers from turn_end (mid-run compaction aborts work)", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 95_000, window: 100_000 }); // above forceAt
await fire(pi, "turn_end", ctx);
assert.equal(calls.compact, 0);
});
test("force fires at agent_settled above the effective threshold", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 });
const result = await fire(pi, "agent_settled", ctx, {});
assert.equal(result, undefined); // notification event — no entries returned
assert.equal(calls.compact, 1);
assert.match(calls.notified.join("\n"), /85k/);
});
test("force does not fire at agent_settled below the threshold", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 60_000, window: 100_000 }); // above warn, below force
await fire(pi, "agent_settled", ctx, {});
assert.equal(calls.compact, 0);
});
test("in-flight lock prevents a second compaction before onComplete", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: () => {} }); // never completes
const first = fire(pi, "agent_settled", ctx, {}); // handler pends until a callback fires
await fire(pi, "agent_settled", ctx, {}); // blocked by the in-flight lock
assert.equal(calls.compact, 1);
});
test("failed compaction starts the cooldown; no immediate retry", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: (o) => o?.onError?.(new Error("x")) });
await fire(pi, "agent_settled", ctx, {});
await fire(pi, "agent_settled", ctx, {});
assert.equal(calls.compact, 1);
});
test("stale pre-compaction token count does not re-trigger force", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 });
await fire(pi, "agent_settled", ctx, {}); // compacts, onComplete releases lock
await fire(pi, "session_compact", { getContextUsage: () => ({ tokens: null, contextWindow: 100_000 }) });
// Usage still null right after compaction (no assistant response yet):
const { ctx: nullCtx, calls: nullCalls } = makeCtx({ tokens: null, window: 100_000 });
await fire(pi, "agent_settled", nullCtx, {});
assert.equal(nullCalls.compact, 0); // cache was cleared, not stale
assert.equal(calls.compact, 1);
});
test("warn re-arms after session_compact starts a new cycle", async () => {
const pi = load(FULL);
const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 });
assert.notEqual(await fire(pi, "turn_end", ctx), undefined);
await fire(pi, "session_compact", {});
assert.notEqual(await fire(pi, "turn_end", ctx), undefined);
});
test("invalid config values fall back per field (null ≠ 0, strings ≠ NaN)", async () => {
const pi = load({ enabled: true, warnTokens: null, forceTokens: "big", warnFraction: 0, forceFraction: 1.5 } as any);
// Defaults: warnAt = min(100k, .55×100k) = 55k, forceAt = min(200k, .8×100k) = 80k.
const below = makeCtx({ tokens: 79_999, window: 100_000 });
await fire(pi, "agent_settled", below.ctx, {});
assert.equal(below.calls.compact, 0);
const above = makeCtx({ tokens: 80_000, window: 100_000 });
await fire(pi, "agent_settled", above.ctx, {});
assert.equal(above.calls.compact, 1);
// The old Math.min(null, …) → 0 bug would compact on ANY token count:
const tiny = makeCtx({ tokens: 1, window: 100_000 });
await fire(pi, "agent_settled", tiny.ctx, {});
assert.equal(tiny.calls.compact, 0);
});
test("invalid warn-side config falls back per field, verified via turn_end", async () => {
const pi = load({ enabled: true, warnTokens: null, forceTokens: 90_000, warnFraction: "high", forceFraction: 0.8 } as any);
// Defaults: warnAt = min(100k, 0.55 × window).
const fracLimited = makeCtx({ tokens: 54_999, window: 100_000 }); // 0.55×100k = 55k < 100k absolute
assert.equal(await fire(pi, "turn_end", fracLimited.ctx), undefined);
const atFractional = makeCtx({ tokens: 55_000, window: 100_000 });
assert.notEqual(await fire(pi, "turn_end", atFractional.ctx), undefined);
// New cycle + absolute-limited window: 0.55×400k = 220k > 100k absolute floor.
await fire(pi, "session_compact", {});
const absLimited = makeCtx({ tokens: 99_999, window: 400_000 });
assert.equal(await fire(pi, "turn_end", absLimited.ctx), undefined);
const atAbsolute = makeCtx({ tokens: 100_000, window: 400_000 });
assert.notEqual(await fire(pi, "turn_end", atAbsolute.ctx), undefined);
});
test("enabled: false registers nothing", () => {
const pi = load({ ...FULL, enabled: false });
assert.equal(Object.keys(pi.handlers).length, 0);
assert.equal(Object.keys(pi.commands).length, 0);
});
test("status command reports thresholds and crossed indicators", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 });
await pi.commands["smart-compact"].handler(undefined, ctx);
const text = calls.notified.join("\n");
assert.match(text, /smart-compact enabled/);
assert.match(text, /warn threshold:\s+55k \(crossed\)/);
assert.match(text, /force threshold:\s+80k/);
assert.doesNotMatch(text, /force threshold:.*crossed/);
});
test("force does not fire when settled reports not idle", async () => {
const pi = load(FULL);
const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, idle: false });
await fire(pi, "agent_settled", ctx, {});
assert.equal(calls.compact, 0);
});
test("settled handler awaits compaction completion before finishing", async () => {
const pi = load(FULL);
let finish!: (cb: "onComplete" | "onError") => void;
const { ctx, calls } = makeCtx({
tokens: 85_000,
window: 100_000,
onCompact: (o) => { finish = (cb) => o[cb]?.({}); },
});
const pending = fire(pi, "agent_settled", ctx, {});
let handlerDone = false;
pending.then(() => { handlerDone = true; });
await new Promise((r) => setImmediate(r));
assert.equal(handlerDone, false); // handler still awaiting the compaction
assert.equal(calls.compact, 1);
finish("onComplete");
await pending;
assert.equal(handlerDone, true);
});
+102 -65
View File
@@ -5,9 +5,17 @@
* custom_message telling the agent to be economical. Once per compaction
* cycle. Invisible to the user UI (display: false).
* Tier 2 (force): when context crosses the force threshold, trigger
* ctx.compact() at a clean turn boundary — deliberately BEFORE Pi's
* emergency threshold compaction (window − reserveTokens) fires. Once
* per cycle, with a cooldown on failure.
* ctx.compact() at the agent_settled boundary — the first point where no
* run is active. ctx.compact() aborts any active run and never resumes
* the interrupted turn, so it must NOT be called from turn_end mid-run.
* Mid-run, Pi's built-in threshold check (window − reserveTokens) remains
* the actor and preserves the run; our force fires before the next prompt
* instead. Under that condition the force threshold sits below the
* built-in trigger (window − reserveTokens; defaults: window > ~82k),
* but ordering is not guaranteed: a run that crosses both thresholds
* before settling lets Pi's built-in check compact first — safely, it
* preserves the run.
* Once per cycle, with a cooldown on failure.
*
* Compatibility with other extensions in this setup:
* - pi-lcm: LCM owns session_before_compact (DAG summaries). This
@@ -20,7 +28,9 @@
* on session_compact. We do the same reset, and our warn message
* deliberately does not duplicate DCP's compress-the-tool language.
* ctx.getContextUsage().tokens is null right after compaction, so we
* cache the last non-null value (same workaround DCP uses).
* cache the last non-null value (same workaround DCP uses) — and clear
* that cache on session_compact, because a stale pre-compaction count
* would immediately re-trigger the force tier.
*
* Config (~/.pi/agent/settings.json or project .pi/settings.json):
* "smartCompact": {
@@ -31,21 +41,14 @@
* "forceFraction": 0.8 // effective force = min(forceTokens, fraction × window)
* }
* Fractions keep the tiers correctly ordered on models with smaller
* windows (e.g. 128k) — force always fires before Pi's built-in
* threshold compaction, never after the window is already exhausted.
* windows (e.g. 128k). Invalid values (wrong type, non-finite, out of
* range) fall back per field to the defaults above — a null or string
* token count must neither zero the threshold nor silently NaN it away.
*/
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
interface SmartCompactUserConfig {
enabled?: boolean;
warnTokens?: number;
forceTokens?: number;
warnFraction?: number;
forceFraction?: number;
}
interface SmartCompactConfig {
enabled: boolean;
warnTokens: number;
@@ -62,9 +65,12 @@ const DEFAULTS: SmartCompactConfig = {
forceFraction: 0.8,
};
/** Project .pi/settings.json overrides the global file, mirroring pi-lcm. */
/**
* Project .pi/settings.json overrides the global file, mirroring pi-lcm.
* Each field is validated; invalid values fall back to that field's default.
*/
function resolveConfig(): SmartCompactConfig {
const read = (file: string): Partial<SmartCompactUserConfig> => {
const read = (file: string): Partial<SmartCompactConfig> => {
try {
const raw = fs.readFileSync(file, "utf-8");
const parsed = JSON.parse(raw);
@@ -73,11 +79,21 @@ function resolveConfig(): SmartCompactConfig {
return {};
}
};
const merged: Partial<SmartCompactUserConfig> = {
const merged: Partial<SmartCompactConfig> = {
...read(path.join(os.homedir(), ".pi", "agent", "settings.json")),
...read(path.join(process.cwd(), ".pi", "settings.json")),
};
return { ...DEFAULTS, ...merged };
const num = (value: unknown, ok: (n: number) => boolean): number | undefined => {
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
return ok(value) ? value : undefined;
};
return {
enabled: typeof merged.enabled === "boolean" ? merged.enabled : DEFAULTS.enabled,
warnTokens: num(merged.warnTokens, (n) => n > 0) ?? DEFAULTS.warnTokens,
forceTokens: num(merged.forceTokens, (n) => n > 0) ?? DEFAULTS.forceTokens,
warnFraction: num(merged.warnFraction, (n) => n > 0 && n <= 1) ?? DEFAULTS.warnFraction,
forceFraction: num(merged.forceFraction, (n) => n > 0 && n <= 1) ?? DEFAULTS.forceFraction,
};
}
const FAILURE_COOLDOWN_MS = 60_000;
@@ -95,53 +111,26 @@ export default function smartCompact(pi: any) {
const effective = (absolute: number, fraction: number, window?: number | null): number =>
window && window > 0 ? Math.min(absolute, Math.floor(fraction * window)) : absolute;
pi.on("turn_end", async (event: any, ctx: any) => {
/** Track tokens through the null-usage window that follows compaction. */
const currentTokens = (ctx: any): { tokens: number | null; window: number | null } => {
const usage = ctx.getContextUsage?.();
if (usage?.tokens !== null && usage?.tokens !== undefined) {
lastKnownTokens = usage.tokens;
}
const tokens = usage?.tokens ?? lastKnownTokens;
if (tokens === null || tokens === undefined) return;
return {
tokens: usage?.tokens ?? lastKnownTokens,
window: usage?.contextWindow ?? null,
};
};
// ── Tier 1: one-shot heads-up to the agent ─────────────────────
// Complements pi-dcp's compress nudges (no compress-tool language)
// and gives advance notice before forced compaction.
pi.on("turn_end", async (event: any, ctx: any) => {
const { tokens, window } = currentTokens(ctx);
if (tokens === null) return;
const window = usage?.contextWindow ?? null;
const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
// ── Tier 2: force compaction at a clean turn boundary ──────────
// Runs before Pi's own threshold check (window − reserveTokens)
// thanks to forceFraction < 1 − reserve/window. ctx.compact()
// triggers LCM's session_before_compact hook when installed.
const cooldownActive = Date.now() - lastForceFailureAt < FAILURE_COOLDOWN_MS;
if (tokens >= forceAt && !forceInFlight && !cooldownActive) {
forceInFlight = true;
warnedThisCycle = true; // warning is moot now
try {
ctx.ui?.notify?.(
`smart-compact: ${Math.round(tokens / 1000)}k tokens — compacting`,
"info",
);
} catch {
/* notification is best-effort */
}
ctx.compact({
// Used only if LCM declines and Pi's default compaction runs.
customInstructions:
"Thorough summary: preserve file paths, symbols, line anchors, " +
"decisions with rationale, and open tasks.",
onComplete: () => {
forceInFlight = false;
},
onError: () => {
forceInFlight = false;
lastForceFailureAt = Date.now();
},
});
return;
}
// ── Tier 1: one-shot heads-up to the agent ─────────────────────
// Complements pi-dcp's compress nudges (no compress-tool language)
// and gives advance notice before forced compaction.
if (!warnedThisCycle && tokens >= warnAt) {
warnedThisCycle = true;
const pct = window ? ` (~${Math.round((tokens / window) * 100)}% of window)` : "";
@@ -164,11 +153,61 @@ export default function smartCompact(pi: any) {
}
});
// ── Tier 2: force compaction once the session has settled ──────────
// agent_settled is the first point where no run is active (ctx.isIdle()
// is true there), so ctx.compact() aborts nothing. Never call it from
// turn_end: manual compaction aborts the active run and does not resume
// the interrupted turn.
pi.on("agent_settled", async (_event: any, ctx: any) => {
if (forceInFlight) return;
if (Date.now() - lastForceFailureAt < FAILURE_COOLDOWN_MS) return;
if (ctx.isIdle && !ctx.isIdle()) return;
const { tokens, window } = currentTokens(ctx);
if (tokens === null) return; // unknown after compaction — wait for fresh usage
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
if (tokens < forceAt) return;
forceInFlight = true;
warnedThisCycle = true; // warning is moot now
try {
ctx.ui?.notify?.(
`smart-compact: ${Math.round(tokens / 1000)}k tokens — compacting`,
"info",
);
} catch {
/* notification is best-effort */
}
// Await completion: prompts deferred from agent_settled (and print-mode
// message loops) must resume after the compaction finishes, not race it.
await new Promise<void>((resolve) => {
ctx.compact({
// Used only if LCM declines and Pi's default compaction runs.
customInstructions:
"Thorough summary: preserve file paths, symbols, line anchors, " +
"decisions with rationale, and open tasks.",
onComplete: () => {
forceInFlight = false;
resolve();
},
onError: () => {
forceInFlight = false;
lastForceFailureAt = Date.now();
resolve();
},
});
});
});
// New cycle after ANY compaction — manual (/compact, /lcm compact),
// forced (ours), threshold (Pi's), or overflow recovery.
// forced (ours), threshold (Pi's), or overflow recovery. The token
// cache must be cleared too: usage reads null until the next assistant
// response, and the stale pre-compaction count would re-trigger force.
const resetCycle = () => {
warnedThisCycle = false;
forceInFlight = false;
lastKnownTokens = null;
};
pi.on("session_compact", async () => resetCycle());
pi.on("session_compact_failed", async () => {
@@ -180,16 +219,14 @@ export default function smartCompact(pi: any) {
pi.registerCommand?.("smart-compact", {
description: "Show smart-compact thresholds and current state",
handler: async (_args: string | undefined, ctx: any) => {
const usage = ctx.getContextUsage?.();
const window = usage?.contextWindow ?? null;
const tokens = usage?.tokens ?? lastKnownTokens;
const { tokens, window } = currentTokens(ctx);
const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
const lines = [
`smart-compact ${cfg.enabled ? "enabled" : "DISABLED"}`,
"smart-compact enabled",
` tokens now: ${tokens === null ? "unknown" : `${Math.round(tokens / 1000)}k`}`,
` window: ${window ? `${Math.round(window / 1000)}k` : "unknown"}`,
` warn threshold: ${Math.round(warnAt / 1000)}k${tokens !== null ? tokens >= warnAt ? " (crossed)" : "" : ""}`,
` warn threshold: ${Math.round(warnAt / 1000)}k${tokens !== null && tokens >= warnAt ? " (crossed)" : ""}`,
` force threshold: ${Math.round(forceAt / 1000)}k${tokens !== null && tokens >= forceAt ? " (crossed)" : ""}`,
` warned this cycle: ${warnedThisCycle}`,
` force in flight: ${forceInFlight}`,