Replace the /smart-compact notify() text with a ctx.ui.custom overlay panel (the /dcp context look): usage bar, threshold rows with crossed indicators, cycle flags, esc/enter/q/ctrl+c dismissal (keybindings-aware with a raw kitty/legacy fallback set), and notify() fallback for print/RPC mode. Hardened by a fresh-context reviewer fanout (ponytail/security/general): kitty explicit-modifier close forms added, render() now honors the requested width exactly with a degenerate-narrow fallback, label width simplified. Harness gains a ctx.ui.custom mock; 22 tests green.
380 lines
15 KiB
TypeScript
380 lines
15 KiB
TypeScript
/**
|
||
* smart-compact — two-tier context management.
|
||
*
|
||
* Tier 1 (warn): when context crosses the warn threshold, inject a short
|
||
* 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 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
|
||
* extension NEVER registers that event; ctx.compact() routes through
|
||
* LCM's hook automatically, so forced compactions get the DAG summary.
|
||
* customInstructions only matter if LCM declines (< minMessages) and
|
||
* Pi's default compaction runs instead.
|
||
* - @davecodes/pi-dcp: DCP nudges the model to call its `compress` tool
|
||
* (30k soft / 70k hard by default) and resets its own nudge tracking
|
||
* 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) — 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": {
|
||
* "enabled": true,
|
||
* "warnTokens": 100000, // absolute warn floor
|
||
* "forceTokens": 200000, // absolute force floor
|
||
* "warnFraction": 0.55, // effective warn = min(warnTokens, fraction × window)
|
||
* "forceFraction": 0.8 // effective force = min(forceTokens, fraction × window)
|
||
* }
|
||
* Fractions keep the tiers correctly ordered on models with smaller
|
||
* 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 SmartCompactConfig {
|
||
enabled: boolean;
|
||
warnTokens: number;
|
||
forceTokens: number;
|
||
warnFraction: number;
|
||
forceFraction: number;
|
||
}
|
||
|
||
const DEFAULTS: SmartCompactConfig = {
|
||
enabled: true,
|
||
warnTokens: 100_000,
|
||
forceTokens: 200_000,
|
||
warnFraction: 0.55,
|
||
forceFraction: 0.8,
|
||
};
|
||
|
||
/**
|
||
* 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<SmartCompactConfig> => {
|
||
try {
|
||
const raw = fs.readFileSync(file, "utf-8");
|
||
const parsed = JSON.parse(raw);
|
||
return parsed?.smartCompact ?? {};
|
||
} catch {
|
||
return {};
|
||
}
|
||
};
|
||
const merged: Partial<SmartCompactConfig> = {
|
||
...read(path.join(os.homedir(), ".pi", "agent", "settings.json")),
|
||
...read(path.join(process.cwd(), ".pi", "settings.json")),
|
||
};
|
||
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;
|
||
|
||
/** A panel row: plain text plus optional theme color name / bold title. */
|
||
interface StatusRow {
|
||
text: string;
|
||
color?: string;
|
||
bold?: boolean;
|
||
}
|
||
|
||
/**
|
||
* Raw input sequences that close the status overlay — legacy forms plus
|
||
* Kitty-protocol CSI-u forms. With the kitty keyboard protocol active (Pi
|
||
* enables it when the terminal supports it) ESC arrives as \x1b[27u, not a
|
||
* bare \x1b byte, which is why raw matching alone misses it. Primary close
|
||
* detection is keybindings.matches("tui.select.cancel"/"confirm"), which
|
||
* normalizes every form and honors user remaps; this set is the fallback
|
||
* when keybindings is unavailable.
|
||
*/
|
||
const CLOSE_KEYS = new Set([
|
||
"\x1b",
|
||
"\r",
|
||
"\n",
|
||
"q",
|
||
"\x03",
|
||
"\x1b[27u", // escape (kitty)
|
||
"\x1b[27;1u", // escape, explicit modifier field (kitty)
|
||
"\x1b[13u", // enter (kitty)
|
||
"\x1b[13;1u", // enter, explicit modifier field (kitty)
|
||
"\x1b[113u", // q (kitty)
|
||
"\x1b[113;1u", // q, explicit modifier field (kitty)
|
||
"\x1b[99;5u", // ctrl+c (kitty)
|
||
]);
|
||
|
||
/**
|
||
* Centered bordered overlay in the /dcp context style: dark slab, themed
|
||
* border, dim footer hint. Resolves when the user closes the panel
|
||
* (esc / enter / q / ctrl+c). Falls back to notify() where ctx.ui.custom
|
||
* is unavailable (print/RPC mode).
|
||
*
|
||
* Dependency-free on purpose: rows are truncated and padded as PLAIN text
|
||
* before theming, so no ANSI-aware width math is needed; panel content uses
|
||
* single-width characters only.
|
||
*/
|
||
async function showStatusPanel(ctx: any, title: string, rows: StatusRow[]): Promise<void> {
|
||
const custom = ctx.ui?.custom;
|
||
if (typeof custom !== "function") {
|
||
ctx.ui?.notify?.([title, ...rows.map((r) => r.text)].join("\n"), "info");
|
||
return;
|
||
}
|
||
await custom(
|
||
(tui: any, theme: any, keybindings: any, done: (result?: unknown) => void) => {
|
||
const lines: StatusRow[] = [
|
||
{ text: title, color: "accent", bold: true },
|
||
{ text: "" },
|
||
...rows,
|
||
{ text: "" },
|
||
{ text: "esc/enter/q to close", color: "dim" },
|
||
];
|
||
const border = (s: string) => theme.fg("borderAccent", s);
|
||
// Dark slab via raw 256-color ANSI (color 234); reads as a distinct
|
||
// panel on every shipped theme. \x1b[49m resets background only.
|
||
const bg = (s: string) => `\x1b[48;5;234m${s}\x1b[49m`;
|
||
let cached: string[] | undefined;
|
||
let cachedWidth = -1;
|
||
|
||
return {
|
||
render(width: number): string[] {
|
||
const w = Math.max(1, width);
|
||
if (cached && cachedWidth === w) return cached;
|
||
// Degenerate narrow (below the border+padding floor): plain
|
||
// truncated lines, so the panel never exceeds the given width.
|
||
if (w < 6) {
|
||
const narrow = lines.map((row) => (row.text.length > w ? row.text.slice(0, w) : row.text));
|
||
cachedWidth = w;
|
||
cached = narrow;
|
||
return narrow;
|
||
}
|
||
const innerWidth = w - 4; // 2 border glyphs + 2 padding spaces
|
||
const out: string[] = [bg(border(`┌${"─".repeat(w - 2)}┐`))];
|
||
for (const row of lines) {
|
||
const text = row.text.length > innerWidth ? row.text.slice(0, innerWidth) : row.text;
|
||
const content = row.bold ? theme.bold(text) : text;
|
||
const styled = row.color ? theme.fg(row.color, content) : content;
|
||
const padSpaces = " ".repeat(Math.max(0, innerWidth - text.length));
|
||
out.push(bg(`${border("│")} ${styled}${padSpaces} ${border("│")}`));
|
||
}
|
||
out.push(bg(border(`└${"─".repeat(w - 2)}┘`)));
|
||
cachedWidth = w;
|
||
cached = out;
|
||
return out;
|
||
},
|
||
invalidate(): void {
|
||
cached = undefined; // theme may have changed; rebuild themed strings
|
||
},
|
||
handleInput(data: string): void {
|
||
const binding = (id: string) => keybindings?.matches?.(data, id) === true;
|
||
// cancel = escape/ctrl+c, confirm = enter (default bindings),
|
||
// protocol-normalized by pi-tui's parser inside keybindings.matches.
|
||
if (binding("tui.select.cancel") || binding("tui.select.confirm") || CLOSE_KEYS.has(data)) {
|
||
done(undefined);
|
||
tui.requestRender();
|
||
}
|
||
},
|
||
};
|
||
},
|
||
{
|
||
overlay: true,
|
||
overlayOptions: { width: "70%", minWidth: 50, maxHeight: "85%", anchor: "center", margin: 2 },
|
||
},
|
||
);
|
||
}
|
||
|
||
export default function smartCompact(pi: any) {
|
||
const cfg = resolveConfig();
|
||
if (!cfg.enabled) return;
|
||
|
||
let warnedThisCycle = false;
|
||
let forceInFlight = false;
|
||
let lastForceFailureAt = 0;
|
||
let lastKnownTokens: number | null = null;
|
||
|
||
/** min(absolute, fraction × window); absolute-only when window unknown. */
|
||
const effective = (absolute: number, fraction: number, window?: number | null): number =>
|
||
window && window > 0 ? Math.min(absolute, Math.floor(fraction * window)) : absolute;
|
||
|
||
/** 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;
|
||
}
|
||
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 warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
|
||
if (!warnedThisCycle && tokens >= warnAt) {
|
||
warnedThisCycle = true;
|
||
const pct = window ? ` (~${Math.round((tokens / window) * 100)}% of window)` : "";
|
||
return {
|
||
entries: [
|
||
...(event.entries ?? []),
|
||
{
|
||
type: "custom_message",
|
||
customType: "smart-compact-notice",
|
||
content:
|
||
`[context notice] Context is at ${Math.round(tokens / 1000)}k tokens${pct}. ` +
|
||
"Be economical now: prefer targeted searches and read ranges over full files, " +
|
||
"and consolidate findings as you go. Auto-compaction will run before the window " +
|
||
"fills — keep key facts stated explicitly in your replies.",
|
||
display: false,
|
||
},
|
||
],
|
||
continue: true, // only forces a request if the run was ending anyway
|
||
};
|
||
}
|
||
});
|
||
|
||
// ── 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. 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 () => {
|
||
forceInFlight = false;
|
||
// Keep warnedThisCycle set — context is still large; don't re-nag.
|
||
});
|
||
|
||
// ── Debug/status command ─────────────────────────────────────────
|
||
// Shows a centered bordered overlay (the /dcp context look): current
|
||
// tokens, a usage bar, both effective thresholds, and cycle flags.
|
||
// Dismissed with esc / enter / q / ctrl+c; notify() remains the
|
||
// fallback where ctx.ui.custom is unavailable (print/RPC mode).
|
||
pi.registerCommand?.("smart-compact", {
|
||
description: "Show smart-compact thresholds and current state",
|
||
handler: async (_args: string | undefined, ctx: any) => {
|
||
const { tokens, window } = currentTokens(ctx);
|
||
const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
|
||
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
|
||
const fmt = (n: number): string => `${Math.round(n / 1000)}k`;
|
||
|
||
const rows: StatusRow[] = [];
|
||
const add = (l: string, value: string, color?: string) =>
|
||
rows.push({ text: `${l} ${value}`, color });
|
||
// Longest label literal used below; keeps the value column aligned.
|
||
const labelWidth = "warned this cycle".length;
|
||
const pad = (l: string) => l.padEnd(labelWidth, " ");
|
||
|
||
add(pad("tokens now"), tokens === null ? "unknown" : fmt(tokens));
|
||
add(pad("window"), window ? fmt(window) : "unknown");
|
||
|
||
// Usage bar with threshold-colored fill, only when the ratio is known.
|
||
if (tokens !== null && window && window > 0) {
|
||
const cells = 24;
|
||
const ratio = Math.min(1, tokens / window);
|
||
const filled = Math.round(cells * ratio);
|
||
const barColor = tokens >= forceAt ? "error" : tokens >= warnAt ? "warning" : undefined;
|
||
rows.push({
|
||
text: `${"█".repeat(filled)}${"░".repeat(cells - filled)} ${Math.round(ratio * 100)}% of window`,
|
||
color: barColor,
|
||
});
|
||
}
|
||
|
||
add(
|
||
pad("warn threshold"),
|
||
`${fmt(warnAt)}${tokens !== null && tokens >= warnAt ? " (crossed)" : ""}`,
|
||
tokens !== null && tokens >= warnAt ? "warning" : undefined,
|
||
);
|
||
add(
|
||
pad("force threshold"),
|
||
`${fmt(forceAt)}${tokens !== null && tokens >= forceAt ? " (crossed)" : ""}`,
|
||
tokens !== null && tokens >= forceAt ? "error" : undefined,
|
||
);
|
||
add(pad("warned this cycle"), String(warnedThisCycle));
|
||
add(pad("force in flight"), String(forceInFlight));
|
||
|
||
await showStatusPanel(ctx, "smart-compact status", rows);
|
||
},
|
||
});
|
||
}
|