co-mono/packages/coding-agent/examples/extensions/trigger-compact.ts
Mario Zechner 7eb969ddb1 fix(coding-agent): show unknown context usage after compaction, fix multi-compaction boundary
After compaction, context token count is unknown until the next LLM
response. Instead of showing stale pre-compaction values or heuristic
estimates, the footer now shows ?/200k.

ContextUsage.tokens and ContextUsage.percent are now number | null
(breaking change). Removed usageTokens, trailingTokens, lastUsageIndex
from ContextUsage (internal details).

Also fixed _checkCompaction() using .find() (first compaction) instead
of getLatestCompactionEntry() (latest), which caused incorrect overflow
detection with multiple compactions.

Closes #1382
2026-02-12 18:35:09 +01:00

40 lines
1 KiB
TypeScript

import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
const COMPACT_THRESHOLD_TOKENS = 100_000;
export default function (pi: ExtensionAPI) {
const triggerCompaction = (ctx: ExtensionContext, customInstructions?: string) => {
if (ctx.hasUI) {
ctx.ui.notify("Compaction started", "info");
}
ctx.compact({
customInstructions,
onComplete: () => {
if (ctx.hasUI) {
ctx.ui.notify("Compaction completed", "info");
}
},
onError: (error) => {
if (ctx.hasUI) {
ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
}
},
});
};
pi.on("turn_end", (_event, ctx) => {
const usage = ctx.getContextUsage();
if (!usage || usage.tokens === null || usage.tokens <= COMPACT_THRESHOLD_TOKENS) {
return;
}
triggerCompaction(ctx);
});
pi.registerCommand("trigger-compact", {
description: "Trigger compaction immediately",
handler: async (args, ctx) => {
const instructions = args.trim() || undefined;
triggerCompaction(ctx, instructions);
},
});
}