/** * The compaction itself: session_before_compact, for /compact, Pi's * automatic threshold and overflow recovery alike. * * pi-cc-compaction takes a compaction when it can read the prompt cache * (plan.ts): the last answered request of this session is forked (fork.ts), * so the summary costs a summary, not a re-read of the conversation. When no * cache can be read (nothing answered yet, another model, an expired cache, * an API that cannot be forked), Pi's own compaction runs, with Pi's own * settings. Either way the user is told whose compaction it was, and why * not this package's (compactionNotice). * * What is kept verbatim. Claude Code keeps the last API round and summarizes * the rest. Here that round is whatever followed the forked request: its * reply and anything after (tool results, the next prompt, the input that * overflowed). Claude Code says so in the summary: the kept messages were * not seen by it. Overflow recovery needs nothing else: the request that * overflowed never got a reply, so the fork is the one before it, which * fitted the window and whose cache is warm. * * Failures are Claude Code's (2.1.308): a compaction that fails is * cancelled, never handed to another algorithm. A reply that arrived without * a usable summary is asked for once more, stricter, before that counts as a * failure at all; still unusable, Pi's own compaction runs and the notice says * why. Transient errors are retried first, with Pi's retry settings. /compact * shows Claude Code's message; automatic compaction counts the failure, and * three in a row, or three rapid refills in a row, stop it for the session * (breaker.ts). A conversation of fewer than two rounds has nothing to compact. * * A reply cut off by the output cap is used only if it contains a usable * summary. The stored summary carries cached, successful read excerpts or * file references (restore.ts), never fresh filesystem reads. */ import type { ExtensionContext, SessionBeforeCompactResult } from "@earendil-works/pi-coding-agent"; import * as breaker from "./breaker.ts"; import type { PiCcConfig } from "./config.ts"; import { buildForkPayload, forkWithRetry, type RetryPolicy } from "./fork.ts"; import { runtime } from "./patches.ts"; import { forkPlan } from "./plan.ts"; import { CONTINUATION_OPENER, SUMMARY_ONLY_ASK, summaryMessage, summaryRequest } from "./prompt.ts"; import { capturedToolResults, recentFiles, restoreBlocks } from "./restore.ts"; /** Claude Code's messages. */ export const NOT_ENOUGH_MESSAGES = "Not enough messages to compact."; export const COULD_NOT_REDUCE = "Compaction failed \u00b7 conversation could not be reduced below the context limit"; export const ERROR_PREFIX = "Error during compaction: "; export const THRASHING = "Autocompact is thrashing: the context refilled to the limit within 3 turns of the previous compact, 3 times in a row. A file being read or a tool output is likely too large for the context window. Try reading in smaller chunks, or use /clear to start fresh."; export const BREAKER_TRIPPED = "Auto-compaction failed 3 times in a row \u00b7 skipping it for the rest of this session (/compact still works)"; interface EntryLike { id: string; type: string; message?: { role?: string }; } interface ProjectedEntry { sourceEntry: EntryLike; messages: unknown[]; } interface MessageLike { role?: string; content?: unknown; summary?: unknown; /** Calls a tool made while it ran (a codemode script's), as Pi records them on the tool result. */ nestedCalls?: { calls?: Array<{ name?: string }> }; } export interface CompactEventLike { preparation: { tokensBefore: number }; branchEntries?: EntryLike[]; customInstructions?: string; reason?: string; signal?: AbortSignal; } export interface CompactionDetails { engine: "fork"; /** * The model that wrote the summary, named as Pi names it on a reply * (provider, model, responseModel): Pi's compaction entry has no such * field, so usage tools reading the session could not tell. */ provider: string; model: string; responseModel?: string; stopReason: string; /** Fork attempts, retries included. */ attempts: number; restoredFiles: string[]; } export interface CompactDeps { now?: () => number; /** The retry policy; Pi's retry settings by default. */ retry?: RetryPolicy; } type Ctx = Pick; export const FORKED_NOTICE = "Compacted by pi-cc-compaction"; /** Why a session's compaction was handed to Pi, until the notice after it. */ const handedToPi = new Map(); /** * What to say once a compaction is stored: whose it was. Said after Pi has * redrawn the transcript (index.ts), since a line shown during the * compaction vanishes with the redraw. Nothing for a compaction this package * had no part in (turned off, another extension's), or for an idle one, * which idle.ts announces itself. */ export function compactionNotice( sessionId: string, event: { fromExtension?: boolean; compactionEntry?: { details?: unknown } }, options: { idle?: boolean } = {}, ): string | undefined { const reason = handedToPi.get(sessionId); handedToPi.delete(sessionId); if ((event.compactionEntry?.details as { engine?: unknown } | undefined)?.engine === "fork") return options.idle ? undefined : FORKED_NOTICE; if (!event.fromExtension && reason) return options.idle ? undefined : `Compacted by Pi's own compaction \u00b7 ${reason}`; return undefined; } function notify(ctx: Ctx, message: string, level: "info" | "warning" | "error"): void { try { if (ctx.hasUI) ctx.ui.notify(message, level); } catch { // a stale context must never break compaction } } /** Pi's retry settings (retry.enabled, maxRetries, baseDelayMs), from its live settings object when known. */ function piRetryPolicy(): RetryPolicy { const settings = runtime().settings?.getRetrySettings?.(); return { maxRetries: settings?.enabled === false ? 0 : (settings?.maxRetries ?? 3), baseDelayMs: settings?.baseDelayMs ?? 2000, }; } /** Cancel a compaction the way Claude Code reports a failure. */ function fail(ctx: Ctx, sessionId: string, reason: string, message: string): SessionBeforeCompactResult { if (reason === "manual") { notify(ctx, message, "error"); } else { notify(ctx, `Auto-compaction failed: ${message}`, "warning"); if (breaker.noteFailure(sessionId)) notify(ctx, BREAKER_TRIPPED, "warning"); } return { cancel: true }; } /** An earlier summary's tool list, where the summary message puts it: right after the opener. */ const CARRIED_TOOLS = new RegExp( `^${CONTINUATION_OPENER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n\\n([^<]*)`, ); /** The names Claude Code keeps: 1-256 characters, no angle brackets, commas, control characters or double spaces. */ const TOOL_NAME = /^(?!.*\s{2})[^<>,\p{C}\u2028\u2029]{1,256}$/u; /** * Tools the conversation called, and those an earlier summary listed, as * Claude Code collects them: a tag anywhere else (a message, a tool result * showing this code, a summary's body) lists nothing. */ function toolNamesOf(messages: MessageLike[]): string[] { const names = new Set(); const add = (name: unknown) => { if (typeof name === "string") names.add(name.trim()); }; for (const message of messages) { // A script's calls are listed too: the model called codemode, the script // called the rest, and the summary should name what the conversation used. for (const call of message.nestedCalls?.calls ?? []) add(call.name); if (message.role === "assistant" && Array.isArray(message.content)) { for (const block of message.content as Array<{ type?: string; name?: string }>) { if (block?.type === "toolCall") add(block.name); } } if (message.role === "compactionSummary" && typeof message.summary === "string") { const listed = CARRIED_TOOLS.exec(message.summary)?.[1]; if (listed) for (const name of listed.split(",")) names.add(name.trim()); } } return [...names].filter((name) => TOOL_NAME.test(name)).sort(); } /** * The session_before_compact handler: the compaction to store, a cancel, or * undefined to let Pi compact (Claude Code's compaction off, or no cache to read). */ export async function handleCompaction( event: CompactEventLike, ctx: Ctx, config: Pick, deps: CompactDeps = {}, ): Promise { const sessionId = ctx.sessionManager.getSessionId(); handedToPi.delete(sessionId); if (!config.compaction || !ctx.model) return undefined; const reason = event.reason ?? "manual"; if (reason !== "manual" && breaker.isOpen(sessionId)) return { cancel: true }; if (reason === "threshold" && breaker.noteAutoCompaction(sessionId)) { notify(ctx, THRASHING, "warning"); return { cancel: true }; } const plan = forkPlan(sessionId, ctx.model as { provider?: string; id?: string; api?: string }, (deps.now ?? Date.now)()); const branch = event.branchEntries ?? (ctx.sessionManager.getBranch() as EntryLike[]); const leafIndex = plan.ok ? branch.findIndex((entry) => entry.id === plan.capture.leafId) : -1; // No cache can be read: Pi's own compaction runs, with Pi's own settings; // the notice after it says why. if (!plan.ok) { handedToPi.set(sessionId, plan.reason); return undefined; } // The captured request cannot be matched to this branch (a fork away): Pi // would compact with the keepRecentTokens:1 the settings patch already // answered with, keeping one message - so this is cancelled instead. if (leafIndex === -1 || branch.slice(leafIndex + 1).some((entry) => entry.type === "compaction")) { notify(ctx, "pi-cc-compaction: the last answered request is not on this branch \u00b7 the compaction was cancelled", "warning"); return { cancel: true }; } const projected = ctx.sessionManager.buildSessionProjection().entries as unknown as ProjectedEntry[]; const firstKeptEntryId = branch[leafIndex + 1]?.id ?? null; const keptAt = firstKeptEntryId === null ? -1 : projected.findIndex((entry) => entry.sourceEntry.id === firstKeptEntryId); const summarized = (keptAt === -1 ? projected : projected.slice(0, keptAt)).flatMap((entry) => entry.messages) as MessageLike[]; const kept = (keptAt === -1 ? [] : projected.slice(keptAt)).flatMap((entry) => entry.messages) as MessageLike[]; // Claude Code compacts two rounds or more: one assistant response is a round. const rounds = [...summarized, ...kept].filter((message) => message.role === "assistant").length; if (rounds < 2) return fail(ctx, sessionId, reason, NOT_ENOUGH_MESSAGES); const ask = summaryRequest(event.customInstructions); const api = (ctx.model as { api: string }).api; const payload = buildForkPayload(api, plan.capture.payload, ask); if (!payload) return fail(ctx, sessionId, reason, `${ERROR_PREFIX}the request could not be extended`); const result = await forkWithRetry( ctx, payload, event.signal, deps.retry ?? piRetryPolicy(), (current) => buildForkPayload(api, current, SUMMARY_ONLY_ASK), ); if (event.signal?.aborted) return { cancel: true }; if (!result.ok) { // The fork could not produce a summary. Pi's own compaction still can, so // it runs, and the notice after it carries this reason (whose reply, how it // stopped, what it wrote at both ends). Pi chose the cut point before it // asked for this compaction, with the keepRecentTokens this package answers // while a fork is planned (index.ts), so the fallback keeps the last round // rather than Pi's usual 20K - everything else is still in Pi's summary. if (result.unusableSummary) { handedToPi.set(sessionId, result.reason); return undefined; } return fail(ctx, sessionId, reason, result.overflow ? COULD_NOT_REDUCE : `${ERROR_PREFIX}${result.reason}`); } const messages = [...summarized, ...kept]; const restoredFiles = recentFiles(messages, kept, ctx.cwd); const summary = summaryMessage({ reply: result.reply, toolNames: toolNamesOf([...summarized, ...kept]), transcriptPath: ctx.sessionManager.getSessionFile() ?? undefined, keptMessages: kept.length > 0, restored: restoreBlocks(restoredFiles, { messages, cwd: ctx.cwd, readCache: capturedToolResults(api, plan.capture.payload) }), }); const model = ctx.model as { provider: string; id: string }; const details: CompactionDetails = { engine: "fork", provider: result.provider || model.provider, model: result.model || model.id, ...(result.responseModel ? { responseModel: result.responseModel } : {}), stopReason: result.stopReason, attempts: result.attempts, restoredFiles, }; return { compaction: { summary, // null: Pi records a compaction that keeps nothing before it (appendCompaction // stores the compaction's own id); the hook's type says string only. firstKeptEntryId: firstKeptEntryId as string, tokensBefore: event.preparation.tokensBefore, usage: result.usage as NonNullable["usage"], details, }, }; }