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

+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}`,