SLOPSHOPPER

smart-compact

Keeps an idle session's prompt cache warm, or compacts it just before it expires, whichever is cheaper, and says on the status line whether the next prompt is…

rowscommandstatusmodeltimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · smart-compact
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /cache ⎿ smart-compact: smart-compact · smart · Claude · TTL 1h (plan) ⎿ smart-compact: cache none · 97k tokens ⎿ smart-compact: saved <$0.01 this session · <$0.01 all time (list price) ⎿ smart-compact: learned summary ~8k · after ~40k · compaction cache hit 90% ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<img alt="claude-modpack: eight Claude Code mods, each measured on real tasks before it shipped, built to work together. statusline, smart-compact, delegate, cells, eta, seek, draft, route." src="assets/banner-light.svg" width="880">

<h3>Install in Claude Code</h3>

/plugin install modpack --marketplace HarzerHeribert/claude-modpack

Answer y, then run /modpack:setup to set everything up step by step.<br> Or from your terminal, guided through both steps: bash <(curl -fsSL https://raw.githubusercontent.com/HarzerHeribert/claude-modpack/main/install.sh) (read it first).<br> Prefer doing it by hand? SETUP.md has every step.

Release License: MIT Claude Code 2.1.296 Quality: no loss seen 8 mods Lab notes

Claude Code with fewer wasted steps, and a clear view of what it's doing.

Eight free add-ons that work on their own. One command installs them, and there is nothing new to learn.<br> Every number on this page was measured, including where it doesn't help.

Install · What you get · Honest numbers · The site: ideas and evidence · Lab notes · Questions

<img alt="Animated: the cost per job with and without the pack, as bars that grow: in a long session $0.44 against $0.29 (−33%), bigger jobs in a fresh session $0.55 against $0.51 (−8%), quick questions in a fresh session $0.23 against $0.24 (+2%, about even); then what was measured since: −17% on 12 jobs beyond code with the pack as 0.7.0 ships it, −22% on a feature a cheaper model builds from your plan, −11% writing to a word limit in one draft, and compacting a 70k-token session in 4 ms instead of 15 s with the summary written ahead; then 2,550 graded runs, no quality loss seen." src="assets/numbers.gif" width="880">

Why it saves

Every time Claude takes a step (reads a file, makes an edit, runs the tests), it reads your whole conversation again. That re-reading is most of what a session costs, and it grows the longer you work. So the cheapest step is the one Claude never has to take.

The pack takes out steps that need no thinking. Several edits and their test run as one step. A search for a name in your code comes back with the exact answer. And when you approve a plan, a cheaper model does the building while Claude checks the result. The work comes out the same; Claude just gets there in fewer round trips.

What you get

<img alt="A real Claude Code session with the pack, six moments cut together, each with a caption: a bar and a finish time for long jobs (eta); several edits and the test run in one step (cells); an approved plan built by a cheaper model and checked (delegate); asked for at most 300 words, one draft that fits (draft); compacted at once, its summary written ahead, with that setting on (smart-compact); every mod with a switch that acts at once (/mods). Under the prompt throughout, the status line: model, context, the plan's 5-hour and weekly use." src="assets/demo-tour.gif" width="880">

Always know where your plan stands

One line under the prompt: the model, how full the conversation is, and how much of your plan's 5-hour and weekly limits you have used, with when each one resets. Long jobs get a progress bar and a finish time above the prompt. And when you step away, your session is kept ready, or tidied up before it goes cold, whichever costs less; the line tells you which.

These are the statusline, eta and smart-compact mods.

No waiting when a conversation gets long

When a conversation fills up, Claude Code summarizes it so the work can go on, and you wait while it writes: 15 seconds at 67k tokens and 102 seconds at 436k in our sessions. Turn on compacting after a turn (afterTurnPayback) and smart-compact compacts a long conversation shortly after a turn ends, when that pays back soon. Its summary is written in the background as the turn ends, so the compaction itself takes 3 to 5 ms. Against /compact from the same session, the next job cost 14% less, at full marks in 16 of 18 runs against 14 of 18 (lab note 15).

That's the smart-compact mod (compacting after a turn is off until you turn it on).

Several changes in one step, and you can still undo them

Claude makes several edits and runs the tests as one step, and you watch each part happen in a live card. Every edit still goes through Claude Code's own edit tool: you see each change, and /rewind undoes it.

That's the cells mod.

A cheaper model builds what you approved

When you approve a plan, Claude hands the building to Sonnet, a cheaper model, and checks its work before reporting back. In our tests that made a feature 22% cheaper and new tests 26% cheaper, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 27% and 33%). You can watch the helper work in its card, and /delegate shows every step it took.

That's the delegate mod.

Optional: feature work goes to the cheaper model by itself

An optional mod, off until you turn it on, and the one that needs an outside classifier model: an API key for TypeSafe's Jev or ScaleDown. That classifier reads each prompt you send. Only when it is feature or test work is Claude told to hand it straight to delegate's worker: the worker reads the code and builds, delegate checks the result itself, and Claude reports after two steps of its own. On a TypeScript feature that made the job 51% cheaper and 42% faster than the pack alone, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 57%); everything else stays with Claude. The classifier is an outside service (TypeSafe's Jev or ScaleDown), so this is off until you turn it on and give it a key: from then on, the start of each prompt goes to it, in the US, to be classified. In real sessions it saves less than on the benchmark: in the author's, the turns it would hand off were 13% of the spend, so at most 4 to 7% saved, nearer 3 to 6% with the hand-offs that were not feature or test work; more if most of your work is building features, and less if you already plan in plan mode, where delegate hands an approved plan to the worker without route.

That's the route mod (optional; it needs an outside classifier and its key).

Fewer, leaner steps when Claude looks around

Before Claude changes anything, it looks around your code, and everything it reads stays in the conversation, read again with every later step. Beside the first prompt you send in a session, and again as the session grows, the pack passes on your preference to look around in few, lean steps: the searches it can already name in one go, the lines that matter rather than whole files, nothing read twice. Against the pack without it, that made jobs 12% cheaper in a fresh session, 16% on a TypeScript library and 10 to 16% in long sessions, at the same quality. It runs on your machine and sends nothing anywhere.

That's the seek mod.

Writing to a word limit, in one draft

Ask for a text of at most so many words, and Claude tends to write all of it, count, find it a third too long, and write all of it again, several times. With a limit in your prompt, the pack passes on your preference to give each part its share and aim a little under, to keep every fact you asked for (and say so if they cannot all fit), and after each write it shows the word count and, when the text is well over, each section's target, so one more write lands it. On six writing tasks that made them 11% cheaper at the same quality. Without a word limit in your prompt it does nothing.

That's the draft mod.

You stay in control

/mods lists the eight and turns any of them on or off, right away, with a click or by typing, such as /mods statusline off. When something can't fully work on your computer, the pack tells you once, with the command that fixes it. When another plugin's permission or notification hook hangs (Warp's does outside the Warp terminal), the pack stops waiting for it after 10 seconds, so Claude Code can't freeze, and tells you which one it was. It keeps itself up to date (or only lets you know, if you prefer).

That's the modpack plugin, which installs the other eight.

Install

In Claude Code, type:

/plugin install modpack --marketplace HarzerHeribert/claude-modpack

Answer y to add the marketplace, then pick where to install it. That installs all eight. Then, in the project you work in:

/modpack:setup

It checks your machine, asks once what you want on (route stays off unless you say yes), sets each mod up in order, and checks that each one works. Done. /mods shows what's on.

By hand instead: SETUP.md has every step.

Each mod installs on its own the same way, for example /plugin install smart-compact --marketplace HarzerHeribert/claude-modpack. delegate and cells use a language server where you have one installed and work without it: Language servers.

Honest numbers

We measured the pack on Claude Opus 5.5 doing seven real jobs in an open-source project (click), from a one-line lookup to building a feature, on two days, 13 and 15 October. Every result was checked by hidden tests. The same jobs ran with the pack and without it, and we compared what they cost at API prices.

Cost per jobWithoutWith the pack
In a long session (Claude has already read the whole project)$0.44$0.29−33%
Bigger jobs in a long session (a feature, tests, a rename)$0.91$0.57−37%
In a fresh session$0.37$0.35−4%
Bigger jobs in a fresh session$0.55$0.51−8%, and 15% faster
Quick questions in a fresh session$0.23$0.24+2%, about even
  • Where it doesn't help: quick questions in a brand-new session. The pack's tools come along with every step, and a three-step lookup has little to save: 5% more one day, 4% less the next, about even.
  • Writing tests: the pack alone saves nothing there (−2%, 12 runs each way): every step waits on the last test run. route hands it to the worker instead (−36% to −46%, below).
  • Nothing got worse: all 224 runs behind this table produced a correct result, with the pack and without.
  • The 95% ranges: long session −39% to −27%; fresh −7% to −1%; bigger jobs fresh −12% to −3%; quick questions −1% to +6%. The long session is two runs per job each day, and the days differ: −26% on one, −40% on the other, mostly from the feature (plain needed 12 requests one day, 16 the next).
  • The same on other code: on a TypeScript library (chrono) the pack cost 7.6% less (−12% to −3%) and took fewer steps on all eight jobs. On 30 real bug reports from SWE-bench Verified it fixed 30 against 29, with 23% fewer steps; the cost, −12%, is not certain at one attempt per bug (−33% to +12%). On PocketBase, Trail-Code's own 15 tasks: −21% with 0.6.0, at one run per task as Trail-Code ran them (the average task −18%, between −27% and −8%; lab notes 3).
  • Beyond click, new in 0.7.0: on 12 tasks in a React and TypeScript app, a small service to run and fix, and documents and data to write and analyse, the pack as 0.7.0 ships it cost 17% less than plain Claude Code (−22% to −12%, 48 runs, all but four at full marks): web code −28%, operating software −8%, prose and data −5% (−10% to +1%), so prose is where it does least.
  • A plan handed to a cheaper model: −22% on a feature, −26% on tests, against Opus doing it alone with the pack (16 runs, all correct).
  • With route turned on: a further −14% on click's eight jobs (route 0.1). With 0.6.0's verified hand-offs, against the pack in the same batch on TypeScript: a feature −51% and 42% faster, writing tests −36%; Claude itself takes 2 steps instead of 6 to 11 (24 runs, all correct).
  • Corrected 16 Oct: worker costs were undercounted. A worker's transcript records its output as each response began, and our bench counted it from there, so every number with a hand-off in it came out too good. Corrected from Claude Code's own totals: a planned feature −22% (was −27%), tests −26% (was −33%), route on click −14% (was −17%), the TypeScript feature −51% (was −57%). Every saving is still a saving, a smaller one. The table above has no hand-offs and did not change. Each claim, old and new: CORRECTION-1016.md.
  • With seek (new in 0.6.0, measured against the pack rather than plain Claude Code, so not in the table above): −12% fresh on click, −16% on TypeScript, −10% to −16% in long sessions (seek, below).
  • With draft (new in 0.8.0, measured against the pack): −10.7% on six writing tasks, from −14.9% to −6.3%, at the same quality (0.987 against 0.990), and no run over its word limit (draft, below).
  • Two days, two versions: the 13 October runs used the pack as of 0.3.0 and Claude Code 2.1.296, the 15 October runs 0.4.0 and 2.1.299. What changed in the pack between them (on/off switches, setup, messages shown when a worker is refused) never reached the model in these runs: its first request was 26.7k tokens plain and 30.6k with the pack on both days. The second day's plain runs were done twice, because the first try had the pack installed by mistake: lab notes 8 tells how we caught it.

<img alt="Cost per task, plain Claude Code against the modpack, in a fresh session and in a session already holding 216k tokens." src="assets/cost-light.svg" width="880">

<img alt="Model requests per task, plain Claude Code against the modpack: 3.2 against 5.6 in a session already holding 216k tokens." src="assets/requests-light.svg" width="880">

<img alt="Cost per task, Opus alone against a plan handed to a worker: feature work 22% less, tests 26% less." src="assets/delegate-light.svg" width="880">

How we measured, every run's record, and the scripts to run it all again are in benchmarks/, starting with SUITE.md. What we tried that did not make it is in the lab notes (as Markdown), among it a 10,000-star code graph, Trail-Code, which installed into Claude Code saved nothing we could measure: alone −1.8% against plain Claude Code (−5.9% to +2.7%), beside the pack +13% (lab notes 3). Not measured: what smart-compact saves you while you're away (worked out from prices, not tested) and Windows.

Questions

Will Claude's work get worse? Not that we have seen. Every run is graded by hidden tests or fixed rules, and the same jobs run with the pack and without it. In the batches that did both, 6 of 349 runs without the pack and 8 of 407 with it fell short of full marks. Of all 2,586 graded runs that ship with this release, 96 fell short: seven on one TypeScript explanation whose answers sometimes leave out one term of its list, with the pack and without; five with Trail-Code, whose hook replaced the answer; seven with Haiku as the main model, in two experiments we dropped; one TypeScript type question; and six on PocketBase. There, two questions left out terms of their answer key in both arms, and plain Claude Code missed one term of a third. On that third question the pack scored 0: lsp-plus held a search while Go's language server was still loading, Claude Code moved it to the background, and Claude's last message answered the notice that followed instead of the question. lsp-plus 0.4.2 then gave the language server 8 seconds at most, and lsp-plus has since left the pack. Seven more are 0.7.0's: five on one prose revision whose checks are strict, in every arm, plain Claude Code too; one runbook and one rename. And 22 are 0.8.0's: nine in the writing tasks, three with draft and three without in one batch and three more with draft in the next (a removed command named as current, a follow-up missing from a brief); thirteen in the compaction benchmark, spread over every arm, ten of them one option check of one task and three a rename that kept a deprecated alias of the old name. Six are 0.9.0's, from the benchmark of the summary written ahead against /compact: five that same option check, two with the summary written ahead and three with /compact, and one rename under /compact that left the old name in one file. And 29 ship with the lab notes of 19 October: 28 from draft's first writing batches, with draft and without, graded before three of their graders were fixed (a removed command named in a history sentence, a code-span check, a stale base; lab note 13), and one with steer, a system-prompt experiment we did not ship. And six ship with 0.9.3, from the next-task benchmark of two shorter summaries, three each: the same option check three times, and the rename three times (twice a docstring note naming the old name, once the old name left in one file). Apart from the PocketBase run, the pack changes how many steps Claude takes, not whether it gets there.

Where did lsp-plus go? It left the pack in 0.7.0. Measured twice, 120 runs on renames and traces in click, a TypeScript library and a React app and on web, operating and prose work, the pack cost no more without it (−1.8% and −1.6%, both ranges across zero), and it kept a language server running per language in every session, hundreds of MB each. Its answer to a grep came from the language server, and in untyped code a server finds about half the uses of a name, where a plain word search finds them all (lab notes 12). The update removes it once and says so in one line; installed again on purpose, it stays. Its last version, 0.4.2, is in this repository's v0.6.1 tag.

Is it safe? It's open source (MIT), so every line is here to read. Code that Claude runs inside a cell runs in a sandbox with no network access. Edits go through Claude Code's own edit tool, so your usual permission prompts and /rewind still apply. The pack sends nothing anywhere except a once-a-day check on GitHub for a new release, which you can turn off, and, only if you turn route on, the start of each prompt to the classifier you chose (TypeSafe or ScaleDown).

Does the pack add anything to my prompts? Your prompt itself is never changed. Beside it, Claude can get a short note in your name: seek's setting to look around in few, lean steps (with the first prompt of a session, and again after a compaction), and, only if you turn route on, the order to hand feature or test work to the worker; delegate gives the same order when you approve a plan of 20 lines or more. A subagent Claude starts gets cells' and seek's settings at the end of its task, since your prompts never reach it. /mods seek off and /mods route off stop theirs; subagents: false in cells or seek stops theirs for subagents.

I'm on a Pro or Max plan. Does this help me? You don't pay per job, but every step counts against your 5-hour and weekly limits. We measured cost at API prices, not plan usage, so we can't promise a number. Fewer, lighter steps should leave more of your limits, and the status line shows exactly where you stand.

Does it work in the desktop app? Yes, cards, progress and the status line included. One limit: in auto mode the desktop app doesn't let an add-on start a helper model, so plans aren't handed off there (turn route off there too); in manual mode, or in the terminal, they are. Windows hasn't been tested yet.

How do I turn it off? /mods switches each part off or on, right away. /plugin removes them.

Were any of these numbers wrong? Yes, the hand-off ones. On 16 October we found that our bench had counted a worker's output only as each of its responses began, so every saving that involved a worker came out too large: a planned feature was −27% and is −22%. They are corrected here, the old and new number side by side in CORRECTION-1016.md. The pack-against-plain numbers had no workers and stand.

What does it cost? Nothing. It's free and open source.

The mods in depth

One line under the prompt, drawn in Claude Code's own hint row so the mode indicator and the status share it:

⏵⏵ auto mode on       Opus 5.5 xhigh   412k ━━━━━━──────   5h 34% ↺2h14   7d 12% ↺3d   ● ready · cold in 44m
  • Its own segments: the model and its effort, the context against the auto-compact point (a highlight sweeps along it while Claude works), and how much of the plan's 5-hour and 7-day windows is used, with when each resets: quiet under half, plain past it, amber from 80%.
  • Other mods' segments: a mod calls $.statusline.set({ id, priority, parts, short?, side? }) and lists statusline among its dependencies. A part is text, a countdown ({ until, prefix?, warnMs? }, counted by the line) or a spinner ({ spin: true }), so a mod sends a segment when it changes, not every second. $.statusline.remove({ id }) takes it off.
  • Narrow terminals drop the least important first: the model, then the windows' resets, the windows, the gauge, and another mod's countdown before its own words.
  • Published pages: a pill on the left lists the pages this session published with the Artifact tool.
  • Phone and IDE: where no line is drawn, the same line is the session's status text, in a session the phone or IDE hosts. A terminal session watched over Remote Control (/rc) from the desktop app, the web or the phone gets no mod drawing and no status text as of Claude Code 2.1.296.
OptionDefault
enabledtruefalse turns the mod off; /mods does it for all of the pack.
placementlinetail: appended dim to Claude Code's hint. band: above the prompt. off.
limitsalwayshalf: a plan window only once it is half used. off: never.
animatetrueThe highlight along the gauge.

An idle session's prompt cache expires after its TTL: 1 hour on a subscription, 5 minutes in ove

Source 5 files
hooks/register.tsx 801 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, PluginOptions, Register, SessionCompactResult } from 'claude-code'
3
4import type { SmartCompactCache, SmartCompactWorld } from '../types'
5import { READY_ID, plainText, readySegment } from './line'
6import { SUMMARY_HEAD, SUMMARY_LINE, compactedWith, finishedSummary, isEnded, markOf, summaryPrompt, whyNotWith } from './summary'
7import {
8  DEFAULT_LEARNED,
9  TTL_5M,
10  addEvidence,
11  costsOf,
12  decide,
13  duration,
14  ema,
15  marginMs,
16  observeTtl,
17  paybackRequests,
18  pricingFor,
19  resolveTtl,
20  tokens,
21  usd,
22  writeMultiplier,
23} from './policy'
24import type { Decision, Learned, Policy, Situation, Strategy, TtlEvidence, TtlSetting } from './policy'
25
26type Engine = EngineInterface
27
28type Options = {
29  policy: Policy
30  cacheTtl: TtlSetting
31  instructions: string
32  /** Compact after a turn when that pays back within this many later requests; 0 never does. */
33  afterTurnPayback: number
34  /** Write that compaction's summary ahead, in the background, so the compaction itself is instant. */
35  prepare: boolean
36}
37
38/** Without prepare: after a turn, wait this long before compacting, so a quick follow-up does not wait for a summary. */
39const AFTER_TURN_GRACE_MS = 20_000
40
41/**
42 * A summary a fork wrote ahead (see prepare): its text, how many of the conversation's messages it read, the last of
43 * them (markOf), what writing it cost, and the context then.
44 */
45type Prepared = { text: string; covered: number; mark: string; usage: ModelUsage; contextTokens: number }
46
47const INITIAL_CACHE: SmartCompactCache = {
48  phase: 'none',
49  ttlMs: TTL_5M,
50  ttlSource: 'api',
51  plan: 'none',
52  why: '',
53  keptAlive: 0,
54  keptAliveUsd: 0,
55  savedUsd: 0,
56  isPaused: false,
57}
58
59const INITIAL_WORLD: SmartCompactWorld = {
60  isWorking: false,
61  limits: [],
62  isAutoCompactOn: true,
63}
64
65const CACHE = atom({ plugin: 'smart-compact', key: 'cache' } as const, INITIAL_CACHE)
66const WORLD = atom({ plugin: 'smart-compact', key: 'world' } as const, INITIAL_WORLD)
67
68/** 'learned' held what the engine's compactions taught too (0.2 and older): left behind, smart-compact starts over. */
69const LEARNED_KEY = 'learnedOwn'
70const EVIDENCE_KEY = 'ttlEvidence'
71const SAVED_KEY = 'savedUsd'
72
73const KEEPALIVE_PROMPT =
74  'Automated prompt-cache keep-alive, not a message from the user. Reply with the single word: ok'
75
76function pick<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
77  return allowed.find(a => a === value) ?? fallback
78}
79
80function num(value: unknown, fallback: number): number {
81  return typeof value === 'number' && Number.isFinite(value) ? value : fallback
82}
83
84function readOptions(o: PluginOptions): Options {
85  const strategies = ['smart', 'compact', 'keepalive', 'off'] as const
86
87  return {
88    policy: {
89      strategy: pick<Strategy>(o.strategy, strategies, 'smart'),
90      minSavingsUsd: num(o.minSavingsUsd, 0.25),
91      compactPenaltyUsd: num(o.compactPenaltyUsd, 0.5),
92      minCompactTokens: num(o.minCompactTokens, 100_000),
93      maxIdleMs: num(o.maxIdleHours, 12) * 60 * 60_000,
94    },
95    cacheTtl: pick<TtlSetting>(o.cacheTtl, ['auto', '5m', '1h'], 'auto'),
96    instructions: typeof o.compactInstructions === 'string' ? o.compactInstructions : '',
97    afterTurnPayback: num(o.afterTurnPayback, 0),
98    prepare: o.prepare !== false,
99  }
100}
101
102/** What a request cost at list price, from the counts the API reported. */
103function spend(usage: ModelUsage, model: string | undefined, ttlMs: number): number {
104  const p = pricingFor(model)
105  const w = writeMultiplier(ttlMs)
106
107  return (
108    (usage.input_tokens * p.input +
109      usage.cache_creation_input_tokens * p.input * w +
110      usage.cache_read_input_tokens * p.cacheRead +
111      usage.output_tokens * p.output) /
112    1e6
113  )
114}
115
116function promptTokens(usage: ModelUsage): number {
117  return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
118}
119
120let options: Options = readOptions({})
121
122let learned: Learned = DEFAULT_LEARNED
123let evidence: TtlEvidence | undefined
124// The main turns started, so a check scheduled after one turn knows when another has begun.
125let turnSeq = 0
126let isActing = false
127let isTicking = false
128let isAfterCompact = false
129let lastPublished = ''
130/** Without the statusline mod, the segment is the session's status text. */
131let isOwnText = false
132/** Failed attempts at the current edge, and when to try again. */
133let failures = 0
134let retryAt: number | undefined
135/** The summary a fork wrote ahead (see prepare), for smart-compact's next compaction. */
136let prepared: Prepared | undefined
137let isPreparing = false
138/** While smart-compact's own compaction runs: the summary offered to it, and the one its hook answered with. */
139let isCompacting = false
140let offer: Prepared | undefined
141let usedPrepared: Prepared | undefined
142let ownResult: SessionCompactResult | undefined
143
144async function getCache($: Engine): Promise<SmartCompactCache> {
145  return { ...INITIAL_CACHE, ...(await read($, CACHE)) }
146}
147
148async function getWorld($: Engine): Promise<SmartCompactWorld> {
149  return { ...INITIAL_WORLD, ...(await read($, WORLD)) }
150}
151
152function setCache($: Engine, change: (c: SmartCompactCache) => Partial<SmartCompactCache>) {
153  return update($, CACHE, value => {
154    const c = { ...INITIAL_CACHE, ...value }
155    return { ...c, ...change(c) }
156  })
157}
158
159function setWorld($: Engine, change: (w: SmartCompactWorld) => Partial<SmartCompactWorld>) {
160  return update($, WORLD, value => {
161    const w = { ...INITIAL_WORLD, ...value }
162    return { ...w, ...change(w) }
163  })
164}
165
166function policyFor(world: SmartCompactWorld): Policy {
167  // Auto-compaction switched off reads as "never compact for me".
168  const isCompactionOff = !world.isAutoCompactOn && options.policy.strategy === 'smart'
169  return isCompactionOff ? { ...options.policy, strategy: 'keepalive' } : options.policy
170}
171
172function situation(c: SmartCompactCache, at: number, canCompact: boolean): Situation {
173  return {
174    contextTokens: c.contextTokens ?? 0,
175    ttlMs: c.ttlMs,
176    pricing: pricingFor(c.model),
177    learned,
178    keptAliveUsd: c.keptAliveUsd,
179    idleMs: at - (c.idleSince ?? at),
180    canCompact,
181  }
182}
183
184async function addSaved($: Engine, amount: number) {
185  if (amount === 0) return
186
187  const lifetime = num(await $.store.get(SAVED_KEY), 0)
188  await $.store.set(SAVED_KEY, lifetime + amount)
189  await setCache($, c => ({ savedUsd: c.savedUsd + amount }))
190}
191
192async function load($: Engine) {
193  const stored = await $.store.get(LEARNED_KEY)
194  const seen = await $.store.get(EVIDENCE_KEY)
195
196  if (stored !== null && typeof stored === 'object') {
197    learned = { ...DEFAULT_LEARNED, ...(stored as Partial<Learned>) }
198  }
199  if (seen !== null && typeof seen === 'object') {
200    evidence = seen as TtlEvidence
201  }
202}
203
204async function refreshWorld($: Engine, isDeep: boolean) {
205  const usage = await $.session.usage(isDeep ? { breakdown: 'summary' } : undefined)
206  const breakdown = usage.context.breakdown
207  await setWorld($, () => ({
208    limits: usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt === undefined ? undefined : Date.parse(l.resetsAt) })),
209    ...(breakdown === undefined ? {} : { isAutoCompactOn: breakdown.isAutoCompactEnabled }),
210  }))
211  // After a reload or a resume the cache has a size before any response.
212  const known = usage.context.tokens
213  if (known !== undefined) {
214    await setCache($, c => (c.contextTokens === undefined && c.phase === 'none' ? { contextTokens: known } : {}))
215  }
216}
217
218/** Settles the TTL and what will happen at the TTL's edge, for the line. */
219async function replan($: Engine) {
220  const now = await $.clock.now()
221  const world = await getWorld($)
222  const ttl = resolveTtl(options.cacheTtl, evidence, world.limits, now)
223  const c = await getCache($)
224
225  if (c.phase !== 'warm' || c.warmAt === undefined || c.contextTokens === undefined) {
226    await setCache($, () => ({ ttlMs: ttl.ms, ttlSource: ttl.source, actAt: undefined }))
227    return
228  }
229
230  const edge = c.warmAt + ttl.ms - marginMs(ttl.ms)
231  const actAt = retryAt !== undefined && retryAt > edge ? retryAt : edge
232  const d = decide(policyFor(world), situation({ ...c, ttlMs: ttl.ms }, actAt, true))
233
234  await setCache($, () => ({ ttlMs: ttl.ms, ttlSource: ttl.source, actAt, plan: d.action, why: d.why }))
235}
236
237async function keepAlive($: Engine, c: SmartCompactCache, d: Decision) {
238  const startedAt = await $.clock.now()
239  const r = await $.model.fork({ prompt: KEEPALIVE_PROMPT })
240
241  if (!r.isAnswered && r.reason === 'nothing-to-fork') {
242    await setCache($, () => ({ phase: 'none', plan: 'none', actAt: undefined }))
243    return
244  }
245  if (!r.isAnswered && (r.reason === 'api-error' || r.reason === 'aborted')) {
246    throw new Error(r.reason === 'api-error' ? `API error ${r.status}` : 'aborted')
247  }
248
249  const n = c.contextTokens ?? 0
250  const cost = spend(r.usage, c.model, c.ttlMs)
251  const credit = (x: SmartCompactCache) => ({
252    lapseUsd: x.credit?.lapseUsd ?? d.costs.lapse,
253    spentUsd: (x.credit?.spentUsd ?? 0) + cost,
254  })
255
256  if (r.usage.cache_read_input_tokens >= 0.8 * n) {
257    await setCache($, x => ({
258      phase: 'warm',
259      warmAt: startedAt,
260      keptAlive: x.keptAlive + 1,
261      keptAliveUsd: x.keptAliveUsd + cost,
262      credit: credit(x),
263    }))
264  } else {
265    // The entry was gone before its time: the TTL is shorter than assumed.
266    if (c.ttlMs > TTL_5M) {
267      evidence = addEvidence(evidence, '5m', startedAt)
268      await $.store.set(EVIDENCE_KEY, evidence)
269    }
270    const isRewritten = r.usage.cache_creation_input_tokens >= 0.8 * n
271    await setCache($, x => ({
272      phase: isRewritten ? 'warm' : 'cold',
273      warmAt: isRewritten ? startedAt : x.warmAt,
274      keptAliveUsd: x.keptAliveUsd + cost,
275      credit: undefined,
276    }))
277    await addSaved($, -cost - (c.credit?.spentUsd ?? 0))
278    $.ui.log(`smart-compact: the cache had already expired; keep-alive cost ${usd(cost)}`)
279  }
280}
281
282/** Compacts; false when a hook vetoed it, so this edge is left alone. */
283async function compactNow($: Engine, c: SmartCompactCache, d: Decision): Promise<boolean> {
284  const startedAt = await $.clock.now()
285  const { r, used } = await compactOwn($, c.contextTokens ?? 0)
286
287  if (r.skip !== undefined) {
288    await setCache($, () => ({ phase: 'warm', plan: 'lapse', why: `compaction skipped: ${r.skip}`, actAt: undefined }))
289    return false
290  }
291
292  // A summary written ahead was paid for then, and is counted with the compaction that used it.
293  const usage = used?.usage ?? r.usage
294  const cost = usage === undefined ? d.costs.compact : spend(usage, c.model, c.ttlMs)
295  const left = (c.warmAt ?? startedAt) + c.ttlMs - startedAt
296
297  await setCache($, x => ({
298    phase: 'compacted',
299    credit: { lapseUsd: x.credit?.lapseUsd ?? d.costs.lapse, spentUsd: (x.credit?.spentUsd ?? 0) + cost },
300  }))
301  $.ui.log(
302    `smart-compact: compacted ${tokens(c.contextTokens ?? 0)}` +
303      (r.tokensAfter === undefined ? '' : ` → ${tokens(r.tokensAfter)}`) +
304      ` while idle${used === undefined ? '' : ', at once with the summary written ahead'}, ${duration(left)} before the cache expired` +
305      ` (re-caching it would have cost ${usd(d.costs.lapse)})`,
306  )
307  return true
308}
309
310/**
311 * After a compaction, from `/compact`, the engine's own or smart-compact's: start over. Only smart-compact's own
312 * (`isOwn`) are learned from: the engine's are another kind (its early summaries keep everything since they were
313 * written, a cold one rewrites the cache), and learning from them priced smart-compact's own as dear as theirs.
314 */
315async function compacted($: Engine, result: { usage?: ModelUsage; tokensAfter?: number }, isOwn: boolean) {
316  // Whatever compacted, a summary written ahead no longer reads like the conversation.
317  prepared = undefined
318  if (isOwn && result.usage !== undefined) {
319    const prompt = promptTokens(result.usage)
320    learned = {
321      summaryTokens: ema(learned.summaryTokens, result.usage.output_tokens),
322      postCompactTokens: learned.postCompactTokens,
323      compactCacheShare:
324        prompt > 0 ? ema(learned.compactCacheShare, result.usage.cache_read_input_tokens / prompt) : learned.compactCacheShare,
325    }
326    await $.store.set(LEARNED_KEY, learned)
327  }
328
329  isAfterCompact = isOwn
330  await setCache($, () => ({ phase: 'compacted', contextTokens: undefined, warmAt: undefined, plan: 'none', why: '', actAt: undefined }))
331  // The window was re-read: the threshold may move with it.
332  await refreshWorld($, true).catch(() => undefined)
333}
334
335/** Whether the person has typed something in the prompt box: a compaction would hold their prompt. */
336async function hasDraft($: Engine): Promise<boolean> {
337  const box = await $.prompt.read().catch(() => undefined)
338  return (box?.text ?? '').trim() !== ''
339}
340
341async function isAgentBusy($: Engine): Promise<boolean> {
342  const agents = await $.agent.list().catch(() => [])
343  return agents.some(a => a.status === 'running' || a.status === 'pending' || a.status === 'waiting')
344}
345
346/** Whether compacting after this turn pays back within afterTurnPayback later requests: how soon, else undefined. */
347async function afterTurnWorth($: Engine): Promise<{ payback: number; context: number } | undefined> {
348  if (isActing || options.afterTurnPayback <= 0) return undefined
349  const c = await getCache($)
350  const world = await getWorld($)
351  const policy = policyFor(world)
352  if (world.isWorking || c.isPaused || c.phase === 'compacted' || c.phase === 'acting') return undefined
353  if (policy.strategy === 'off' || policy.strategy === 'keepalive') return undefined
354  const context = c.contextTokens ?? 0
355  if (context < policy.minCompactTokens) return undefined
356  const payback = paybackRequests(context, c.ttlMs, pricingFor(c.model), learned)
357  return payback > options.afterTurnPayback ? undefined : { payback, context }
358}
359
360/**
361 * After a turn, in a long session: compact when the compaction pays back within afterTurnPayback later requests.
362 * Measured (compact_bench, 18 Oct): no quality lost between turns; on Opus at 224k a compaction costs about $0.34 and
363 * saves about $0.036 a request; in the person's sessions, after 62% of prompts past 250k twenty or more requests
364 * followed. Never mid-turn (the engine refuses), never over running agents, never twice in a row. This is the way
365 * without prepare, or when a summary could not be written ahead: the engine summarizes 20 s after the turn, not over a
366 * draft, and a prompt sent while it runs waits for it.
367 */
368async function afterTurn($: Engine, seq: number) {
369  if (seq !== turnSeq) return
370  const worth = await afterTurnWorth($)
371  if (worth === undefined) return
372  if ((await hasDraft($)) || (await isAgentBusy($)) || seq !== turnSeq) return
373  await compactAfterTurn($, worth)
374}
375
376/**
377 * With prepare (the default): at the end of a turn after which compacting pays back soon, a fork of the session writes
378 * the summary in the background. It reads the session's own cache, as the engine's /compact does, and nobody waits for
379 * it. Once it is there and the session idle, the compaction is instant: the summary, then every message since the
380 * turn's last request, as they are. If the next prompt comes first, it waits for the end of that turn.
381 *
382 * Called from turn.complete itself, before a queued prompt or notice can start the next turn: the fork then reads
383 * this turn's last request, the one the messages read here end with. The fork is not awaited.
384 */
385async function prepare($: Engine, seq: number) {
386  if (isPreparing) return
387  const c = await getCache($)
388  if (prepared !== undefined && !isFresh(prepared, c.contextTokens ?? 0)) prepared = undefined
389  // Out of turn.complete's own frame: /compact, which a summary written ahead goes through, is refused inside a hook
390  // the turn waits on.
391  if (prepared !== undefined) return void $.clock.after(0, () => void install($).catch(() => undefined))
392  const worth = await afterTurnWorth($)
393  if (worth === undefined) return
394  const read = await $.session.messages({})
395  const messages = Array.isArray(read) ? read : []
396  // The fork reads the turn's last request: every message up to the last on the person's side (a prompt or results).
397  let last = messages.length - 1
398  while (last >= 0 && messages[last]?.role !== 'user') last -= 1
399  const mark = messages[last]
400  if (mark === undefined) return
401
402  isPreparing = true
403  void $.model
404    .fork({ prompt: summaryPrompt(options.instructions) })
405    .then(async r => {
406      const text = r.isAnswered ? finishedSummary(r.text) : undefined
407      if (text === undefined || !r.isAnswered) {
408        const length = r.isAnswered ? r.text.trim().length : 0
409        const why = !r.isAnswered
410          ? r.reason
411          : length === 0
412            ? 'empty'
413            : isEnded(r.text)
414              ? 'not a summary: fewer than four of its six parts'
415              : `cut off after ${length.toLocaleString('en-US')} characters`
416        $.ui.log(`smart-compact: the summary could not be written ahead (${why}); compacting after the turn as /compact does`)
417        $.clock.after(AFTER_TURN_GRACE_MS, () => void afterTurn($, seq).catch(() => undefined))
418        return
419      }
420      prepared = { text, covered: last + 1, mark: markOf(mark), usage: r.usage, contextTokens: worth.context }
421      await install($)
422    })
423    .catch(() => undefined)
424    .finally(() => {
425      isPreparing = false
426    })
427}
428
429/** Whether a summary written ahead still pays: the conversation has grown by less than half since. */
430function isFresh(p: Prepared, context: number): boolean {
431  return context - p.contextTokens <= p.contextTokens / 2
432}
433
434/** Compacts with the summary written ahead, when that still pays back and the session is idle; else after a later turn. */
435async function install($: Engine) {
436  if (prepared === undefined) return
437  const worth = await afterTurnWorth($)
438  if (worth === undefined || (await isAgentBusy($))) return
439  await compactAfterTurn($, worth)
440}
441
442async function compactAfterTurn($: Engine, worth: { payback: number; context: number }) {
443  const { payback, context } = worth
444  isActing = true
445  await setCache($, () => ({ phase: 'acting', plan: 'compact', why: `pays back after about ${Math.ceil(payback)} requests` }))
446  await publish($).catch(() => undefined)
447  try {
448    const { r, used } = await compactOwn($, context)
449    if (r.skip !== undefined) {
450      await setCache($, () => ({ phase: 'warm', plan: 'none', why: `compaction skipped: ${r.skip}` }))
451      return
452    }
453    const after = r.tokensAfter ?? learned.postCompactTokens
454    $.ui.log(
455      `smart-compact: compacted ${tokens(context)} → ${used === undefined ? '' : 'about '}${tokens(after)} ` +
456        (used === undefined ? 'after the turn' : 'at once, with a summary written in the background after the turn') +
457        `: each later request reads ${tokens(Math.max(0, context - after))} less, so it pays back after about ` +
458        `${Math.ceil(payback)} requests`,
459    )
460  } catch (err) {
461    await setCache($, x => ({ phase: x.phase === 'acting' ? 'warm' : x.phase, plan: 'none', why: '' }))
462    // The next prompt came first (the engine compacts only between turns): a summary written ahead waits for its end.
463    if (prepared === undefined || !(await getWorld($)).isWorking) {
464      $.ui.log(`smart-compact: compacting after the turn failed (${err instanceof Error ? err.message : String(err)})`)
465    }
466  } finally {
467    isActing = false
468    await publish($).catch(() => undefined)
469  }
470}
471
472/**
473 * smart-compact's own compaction. A summary written ahead, still fresh, is offered to the session.compact hook, which
474 * answers with it at once when the conversation still holds what it read; else the engine summarizes as /compact
475 * does. It is learned from here: the hook leaves smart-compact's own compactions to this.
476 */
477async function compactOwn($: Engine, context: number): Promise<{ r: SessionCompactResult; used?: Prepared }> {
478  isCompacting = true
479  offer = prepared !== undefined && isFresh(prepared, context) ? prepared : undefined
480  ownResult = undefined
481  try {
482    // $.session.compact runs through every hook but the caller's, so smart-compact's own session.compact hook, the one
483    // that answers with the summary written ahead, never sees it: that compaction goes through /compact, which it does.
484    const r =
485      offer === undefined
486        ? await $.session.compact(options.instructions ? { instructions: options.instructions } : {})
487        : await $.command
488            .run({ command: 'compact', args: options.instructions })
489            .then(() => ownResult ?? { skip: 'the compaction did not run' })
490    const used = usedPrepared
491    if (r.skip === undefined) await compacted($, used === undefined ? r : { usage: used.usage }, true)
492    return { r, used }
493  } finally {
494    isCompacting = false
495    offer = undefined
496    usedPrepared = undefined
497  }
498}
499
500async function act($: Engine, c: SmartCompactCache, world: SmartCompactWorld, now: number) {
501  const d = decide(policyFor(world), situation(c, now, !(await hasDraft($)) && !(await isAgentBusy($))))
502
503  if (d.action !== 'keepalive' && d.action !== 'compact') {
504    // Nothing worth doing: the cache lapses, and so does what was spent.
505    await setCache($, () => ({ plan: d.action, why: d.why, actAt: undefined }))
506    return
507  }
508
509  isActing = true
510  await setCache($, () => ({ phase: 'acting', plan: d.action, why: d.why }))
511  await publish($).catch(() => undefined)
512
513  let isDone = false
514
515  try {
516    isDone = d.action === 'keepalive' ? (await keepAlive($, c, d), true) : await compactNow($, c, d)
517    failures = 0
518    retryAt = undefined
519  } catch (err) {
520    // Back off, and give the edge up after three tries.
521    failures += 1
522    retryAt = failures < 3 ? now + 20_000 : undefined
523    const reason = err instanceof Error ? err.message : String(err)
524    await setCache($, x => ({
525      phase: x.phase === 'acting' ? 'warm' : x.phase,
526      actAt: retryAt,
527      ...(retryAt === undefined ? { plan: 'lapse' as const, why: `${d.action} failed: ${reason}` } : {}),
528    }))
529    $.ui.log(`smart-compact: ${d.action} failed (${reason})${retryAt === undefined ? '; giving up' : '; retrying in 20s'}`)
530  } finally {
531    isActing = false
532    await publish($).catch(() => undefined)
533  }
534
535  if (isDone) await replan($)
536}
537
538/**
539 * Puts the segment on the statusline mod's line when it changed. Without that mod the same words
540 * are the session's status text, said again every tick so the countdown moves.
541 */
542async function publish($: Engine) {
543  const now = await $.clock.now()
544  const segment = readySegment(await getCache($), { now, isWorking: (await getWorld($)).isWorking })
545  const key = JSON.stringify(segment ?? null)
546  if (key === lastPublished && !isOwnText) return
547  try {
548    if (segment === undefined) await $.statusline.remove({ id: READY_ID })
549    else await $.statusline.set(segment)
550    if (isOwnText) $.ui.status(undefined)
551    isOwnText = false
552  } catch {
553    // No statusline mod in this session: the session's status text says it.
554    $.ui.status(segment === undefined ? undefined : plainText(segment, now))
555    isOwnText = segment !== undefined
556  }
557  lastPublished = key
558}
559
560async function tick($: Engine) {
561  if (isTicking || isActing) return
562  isTicking = true
563
564  try {
565    const now = await $.clock.now()
566    const c = await getCache($)
567    const world = await getWorld($)
568    if (c.phase === 'warm' && c.warmAt !== undefined && !world.isWorking) {
569      const expiry = c.warmAt + c.ttlMs
570
571      if (now >= expiry) {
572        // Asleep past the edge, or nothing was worth doing: count what was spent.
573        await setCache($, () => ({ phase: 'cold', plan: 'none', why: 'expired', actAt: undefined, credit: undefined }))
574        await addSaved($, -(c.credit?.spentUsd ?? 0))
575        return
576      }
577
578      const isOn = !c.isPaused && options.policy.strategy !== 'off'
579      if (isOn && c.actAt !== undefined && now >= c.actAt) {
580        await act($, c, world, now)
581        return
582      }
583
584    }
585
586  } finally {
587    isTicking = false
588    await publish($).catch(() => undefined)
589  }
590}
591
592async function onMainResponse($: Engine, startedAt: number, index: number, usage: ModelUsage & { model: string }) {
593  const n = promptTokens(usage)
594  const c = await getCache($)
595
596  const isSameMain = c.phase !== 'compacted' && c.model === usage.model
597  if (index === 0 && isSameMain && c.warmAt !== undefined && c.contextTokens !== undefined) {
598    const seen = observeTtl(startedAt - c.warmAt, c.contextTokens, usage)
599    if (seen !== undefined) {
600      evidence = addEvidence(evidence, seen, startedAt)
601      await $.store.set(EVIDENCE_KEY, evidence)
602    }
603  }
604
605  // The person is back: settle what keeping the cache cost against a lapse.
606  if (index === 0 && c.credit !== undefined) {
607    const p = pricingFor(usage.model)
608    const rewrite = (usage.cache_creation_input_tokens * p.input * writeMultiplier(c.ttlMs)) / 1e6
609    const isHit = usage.cache_read_input_tokens >= 0.5 * (c.contextTokens ?? 0)
610    const saved =
611      c.phase === 'compacted'
612        ? c.credit.lapseUsd - c.credit.spentUsd - rewrite
613        : isHit
614          ? c.credit.lapseUsd - c.credit.spentUsd
615          : -c.credit.spentUsd
616    await addSaved($, saved)
617  }
618
619  if (isAfterCompact) {
620    isAfterCompact = false
621    learned = { ...learned, postCompactTokens: ema(learned.postCompactTokens, n) }
622    await $.store.set(LEARNED_KEY, learned)
623  }
624
625  await setCache($, () => ({ phase: 'warm', model: usage.model, contextTokens: n, warmAt: startedAt, credit: undefined }))
626}
627
628export const register: Register = (on, rawOptions) => {
629  if (rawOptions.enabled === false) return
630  options = readOptions(rawOptions)
631  learned = DEFAULT_LEARNED
632  evidence = undefined
633  failures = 0
634  retryAt = undefined
635  prepared = undefined
636
637  on('session.start', async ($, e, next) => {
638    await $.command.register({
639      name: 'cache',
640      description: 'Prompt cache: what idling costs, and what smart-compact will do about it',
641      argumentHint: '[pause | resume | keepalive]',
642    })
643
644    await load($)
645    // A reload mid-action leaves no action running.
646    await setCache($, c => (c.phase === 'acting' ? { phase: 'warm' } : {}))
647    await refreshWorld($, true).catch(() => undefined)
648    await replan($)
649    $.clock.every(1_000, () => void tick($))
650
651    return next(e)
652  })
653
654  on('classic.SessionStart', async ($, e, next) => {
655    const seconds = e.seconds_since_last_response
656    const isResumed = e.source === 'resume' || e.source === 'fork'
657
658    if (isResumed && seconds !== undefined && e.context_tokens) {
659      const now = await $.clock.now()
660      await setCache($, () => ({
661        phase: e.prompt_cache_likely_expired ? 'cold' : 'warm',
662        warmAt: now - seconds * 1000,
663        contextTokens: e.context_tokens,
664        model: e.model,
665        idleSince: now - seconds * 1000,
666      }))
667      await replan($)
668    }
669
670    return next(e)
671  }).catch(($, e, next) => next(e))
672
673  on('session.end', { reason: 'clear' }, async ($, e, next) => {
674    prepared = undefined
675    await setCache($, c => ({ ...INITIAL_CACHE, savedUsd: c.savedUsd, isPaused: c.isPaused }))
676    return next(e)
677  })
678
679  on('turn.start', async ($, e, next) => {
680    if ((e as { agentId?: string }).agentId === undefined) turnSeq += 1
681    failures = 0
682    retryAt = undefined
683    await setWorld($, () => ({ isWorking: true }))
684    await setCache($, () => ({ actAt: undefined, idleSince: undefined, keptAlive: 0, keptAliveUsd: 0 }))
685    await publish($).catch(() => undefined)
686    return next(e)
687  })
688
689  on('turn.step', async function* ($, e, next) {
690    const startedAt = await $.clock.now()
691    const result = yield* next(e)
692
693    if (e.agentId === undefined && result.usage !== null) {
694      await onMainResponse($, startedAt, e.index, result.usage)
695    }
696
697    return result
698  })
699
700  on('turn.complete', async ($, e, next) => {
701    const result = await next(e)
702    if (e.agentId !== undefined) return result
703
704    const now = await $.clock.now()
705    await setWorld($, () => ({ isWorking: false }))
706    await setCache($, () => ({ idleSince: now, keptAlive: 0, keptAliveUsd: 0 }))
707    await refreshWorld($, false)
708    await replan($)
709    const seq = turnSeq
710    if (options.prepare) await prepare($, seq).catch(() => undefined)
711    else $.clock.after(AFTER_TURN_GRACE_MS, () => void afterTurn($, seq).catch(() => undefined))
712
713    return result
714  })
715
716  // The summary written ahead stands in the conversation as a message on the person's side: drawn as one line, the way
717  // Claude Code draws its own summary, and in full under ctrl+o.
718  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
719    if (e.props.isExpanded || !e.props.text.startsWith(SUMMARY_HEAD)) return next(e)
720    return next({ ...e, props: { ...e.props, text: SUMMARY_LINE } })
721  })
722
723  on('session.compact', async ($, e, next) => {
724    // smart-compact's own compaction, offered a summary written ahead: answered with it at once when the conversation
725    // still holds every message the summary read; the messages since stay as they are.
726    const p = offer
727    if (p !== undefined && e.agentId === undefined) {
728      offer = undefined
729      const isOwn = e.trigger === 'plugin' || e.trigger === 'manual'
730      const messages = isOwn ? compactedWith(p.text, p.covered, p.mark, e.messages) : undefined
731      if (messages !== undefined) {
732        usedPrepared = p
733        ownResult = { messages }
734        return { messages }
735      }
736      // It no longer does (something else compacted, or a rewind): the engine summarizes afresh.
737      prepared = undefined
738      $.ui.log(
739        `smart-compact: the summary written ahead was not used (${
740          isOwn ? whyNotWith(p.covered, p.mark, e.messages) : `the compaction came as ${e.trigger}`
741        }); Claude Code summarizes afresh`,
742      )
743    }
744    const result = await next(e)
745    if (isCompacting && e.agentId === undefined) ownResult = result
746    // smart-compact's own compactions are learned from in compactOwn; the engine's are not learned from at all.
747    if (e.agentId !== undefined || e.trigger === 'precompute' || result.skip !== undefined || isCompacting) return result
748    await compacted($, result, false)
749    return result
750  }).catch(($, e, next) => next(e))
751
752  on('command.run', { command: 'cache' }, async ($, e) => {
753    const arg = e.args.trim().toLowerCase()
754
755    if (arg === 'pause' || arg === 'resume') {
756      await setCache($, () => ({ isPaused: arg === 'pause' }))
757      return { text: arg === 'pause' ? 'smart-compact paused for this session.' : 'smart-compact resumed.' }
758    }
759
760    const now = await $.clock.now()
761    const c = await getCache($)
762    const world = await getWorld($)
763
764    if (arg === 'keepalive') {
765      if (c.phase !== 'warm' || world.isWorking) return { text: 'Nothing to keep warm right now.' }
766      const d = decide({ ...options.policy, strategy: 'keepalive', minSavingsUsd: 0 }, situation(c, now, false))
767      await keepAlive($, c, d)
768      await replan($)
769      const after = await getCache($)
770      return { text: `Kept warm: ${duration(after.warmAt === undefined ? 0 : after.warmAt + after.ttlMs - now)} left.` }
771    }
772
773    const p = pricingFor(c.model)
774    const lifetime = num(await $.store.get(SAVED_KEY), 0)
775    const lines = [
776      `smart-compact · ${options.policy.strategy}${c.isPaused ? ' (paused)' : ''} · ${p.label} · TTL ${duration(c.ttlMs)} (${c.ttlSource})`,
777    ]
778
779    if (c.contextTokens !== undefined && c.warmAt !== undefined && c.phase === 'warm') {
780      const costs = costsOf(c.contextTokens, c.ttlMs, p, learned)
781      lines.push(`cache   warm, ${duration(c.warmAt + c.ttlMs - now)} left · ${tokens(c.contextTokens)} tokens`)
782      if (c.actAt !== undefined) lines.push(`next    ${c.plan} in ${duration(c.actAt - now)}: ${c.why}`)
783      lines.push(
784        `costs   lapse ${usd(costs.lapse)} · keep-alive ${usd(costs.keepAlive)} · ` +
785          `compact ${usd(costs.compact)} + ${usd(options.policy.compactPenaltyUsd)} for lost detail`,
786      )
787    } else {
788      lines.push(`cache   ${c.phase}${c.contextTokens === undefined ? '' : ` · ${tokens(c.contextTokens)} tokens`}`)
789    }
790
791    if (c.keptAlive > 0) lines.push(`idle    ${c.keptAlive} keep-alive(s), ${usd(c.keptAliveUsd)}`)
792    lines.push(`saved   ${usd(Math.max(0, c.savedUsd))} this session · ${usd(Math.max(0, lifetime))} all time (list price)`)
793    lines.push(
794      `learned summary ~${tokens(learned.summaryTokens)} · after ~${tokens(learned.postCompactTokens)} · ` +
795        `compaction cache hit ${Math.round(learned.compactCacheShare * 100)}%`,
796    )
797
798    return { text: lines.join('\n') }
799  })
800}
801
hooks/line.ts 62 lines
1// smart-compact's segment on the status line: whether the next prompt reads a
2// warm cache, so it is cheap, or a cold one. The statusline mod draws it at the
3// right edge, where the eye lands; what changes by itself (the countdown, the
4// spinner while the mod acts, the blink before it does) is declared so, and the
5// line moves it. Without the statusline mod, the same words are the session's
6// status text.
7
8import type { SmartCompactCache } from '../types'
9import { duration } from './policy'
10
11export type Tone = 'accent' | 'good' | 'text' | 'label' | 'faint' | 'warn' | 'alert'
12
13/** The statusline mod's part shapes: text (that may blink), a countdown, a spinner. */
14export type ReadyPart =
15  | { text: string; tone: Tone; blink?: { from: number; to: number } }
16  | { until: number; tone: Tone; prefix?: string; warnMs?: number }
17  | { spin: true; tone: Tone }
18
19export type ReadySegment = { id: string; priority: number; parts: ReadyPart[]; short?: ReadyPart[]; side?: 'start' | 'end'; calm?: boolean }
20
21export const READY_ID = 'smart-compact:ready'
22
23const text = (t: string, tone: Tone): ReadyPart => ({ text: t, tone })
24
25/**
26 * 'ready' while the next prompt reads a warm cache, with what ends that once it will (a lapse, or
27 * a compaction within ten minutes); while smart-compact keeps it warm, nothing more. Cold is
28 * amber: the next prompt pays to read the whole context again. Undefined before any request.
29 */
30export function readySegment(cache: SmartCompactCache, m: { now: number; isWorking: boolean }): ReadySegment | undefined {
31  const of = (parts: ReadyPart[], short?: ReadyPart[], calm = false): ReadySegment => ({ id: READY_ID, priority: 0, side: 'end', parts, ...(short ? { short } : {}), ...(calm ? { calm } : {}) })
32  // Past its edge a warm cache is cold, whether or not the tick has said so.
33  const isExpired = cache.warmAt !== undefined && cache.warmAt + cache.ttlMs <= m.now
34
35  if (cache.isPaused) return of([text('◌', 'faint'), text(' paused', 'label')])
36  if (cache.phase === 'acting') return of([{ spin: true, tone: 'accent' }, text(cache.plan === 'compact' ? ' compacting' : ' keeping warm', 'label')])
37  if (cache.phase === 'compacted') return of([text('◌', 'accent'), text(' compacted', 'label')])
38  if (cache.phase === 'cold' || (cache.phase === 'warm' && !m.isWorking && isExpired)) return of([text('○', 'warn'), text(' cold', 'warn')])
39  if (cache.phase === 'warm' && m.isWorking) return of([text('●', 'good')], undefined, true)
40  if (cache.phase !== 'warm' || cache.warmAt === undefined) return undefined
41
42  const edge = cache.warmAt + cache.ttlMs
43  // A blink in the last twenty seconds before the mod acts.
44  const dot: ReadyPart = cache.actAt === undefined ? text('●', 'good') : { text: '●', tone: 'good', blink: { from: cache.actAt - 20_000, to: cache.actAt } }
45  const short = [dot, text(' ready', 'label')]
46  // Routine: warm with more than five minutes to go and nothing about to be done.
47  const isCalm = edge - m.now > 5 * 60_000
48
49  if (cache.plan === 'compact' && cache.actAt !== undefined && cache.actAt - m.now < 10 * 60_000) {
50    return of([...short, { until: cache.actAt, prefix: ' · compacts in ', tone: 'label' }], short)
51  }
52  if (cache.plan !== 'keepalive' && cache.plan !== 'compact') {
53    return of([...short, { until: edge, prefix: ' · cold in ', tone: 'label', warnMs: 5 * 60_000 }], short, isCalm)
54  }
55  return of(short, undefined, isCalm)
56}
57
58/** The segment as one plain string at 'now': what the session's status text says without the statusline mod. */
59export function plainText(segment: ReadySegment, now: number): string {
60  return segment.parts.map(p => ('spin' in p ? '◐' : 'until' in p ? (p.prefix ?? '') + duration(p.until - now) : p.text)).join('')
61}
62
hooks/summary.ts 114 lines
1// The summary smart-compact writes ahead, by a fork of the session, for its own compactions. The compaction bench
2// (pilot/delegate-bench/compact_bench.py, arm PREP) reads SUMMARY_PROMPT and SUMMARY_HEAD from this file, so what it
3// measures is this text.
4
5import type { SessionMessage } from 'claude-code'
6
7// Since 0.3.2 the summary lets context shift: what is superseded, closed, obsolete, one-off or finished fades to a line
8// or goes, and an earlier summary is pruned rather than copied forward. Over 12 compactions (canary2.py) it kept the
9// facts 0.3.1's prompt kept at under half the size; 0.3.1's grew to 34k characters and carried what was obsolete.
10export const SUMMARY_PROMPT = `This message is from the smart-compact plugin, not from the person. Write the summary this conversation will be compacted to: it replaces every message above, and the messages that come after this point stay as they are. Answer with the summary alone, in text; do not call any tool.
11
12Write it so that the work can go on from the summary without the conversation:
131. Requests and intent: everything the person asked for that still holds, in order, quoting their own words for each instruction, constraint, preference and correction.
142. Decisions: what was decided and why, and what was tried or ruled out.
153. Files and code: each file that still matters, with its path, what is in it or what changed, and the functions or lines involved. Paste code only for work still in progress, or where the exact text matters and cannot be read again from disk.
164. Errors and fixes: each error met, its cause, and how it was fixed.
175. Facts: measurements, results, numbers, versions, names, commands, links and IDs that later work may need, exactly.
186. State: what is done, what is in progress, what is still to do, and the agreed next step, if any.
19
20Be specific and complete about what still holds. What mattered for earlier work need not stay, so let go of what no longer bears on the work:
21- superseded: a value, rule or plan replaced by a newer one: give the newer one only;
22- closed: a task, deadline, blocker or open item that is done or resolved: one line under State saying it is closed;
23- obsolete: what the person said no longer holds, such as notes they called outdated or a rule they dropped: leave out its content, at most one line saying it is gone. A file deleted or moved is not obsolete by that alone: what it said that still holds can no longer be read again here, so keep it;
24- one-off: an instruction meant for a single change: once that change is made, it is done, not a standing rule;
25- finished work: what was built and where, in a line or two, without its code.
26A summary from an earlier compaction, at the top of the conversation, is material like the rest: carry forward what still holds, not all of it. Keep every other fact the person gave, even one said in passing; when in doubt whether something still holds, keep it.`
27
28export const SUMMARY_HEAD = `This conversation was compacted by smart-compact. The summary below covers its earlier part. It was written in the background before the messages that follow it, which are kept as they were: where they differ from it, they are the newer.`
29
30/** The summary's row in the transcript, as Claude Code draws its own: one line; in full under ctrl+o. */
31export const SUMMARY_LINE = 'Compacted by smart-compact, with a summary written ahead (ctrl+o to see it)'
32
33/** The summary's last line: a reply that does not end with it was cut off, and is not used. */
34export const SUMMARY_END = 'End of summary.'
35
36/** The fork's prompt, with the person's compactInstructions after it and the end line last. */
37export function summaryPrompt(instructions: string): string {
38  const prompt = instructions.trim() === '' ? SUMMARY_PROMPT : `${SUMMARY_PROMPT}\n\nAlso keep: ${instructions.trim()}`
39  return `${prompt}\n\nEnd it with this line alone: ${SUMMARY_END}`
40}
41
42/** A line that opens one of SUMMARY_PROMPT's six parts, as a heading or a numbered item, by its first word. */
43export const SUMMARY_PART = /^[\s#>*_-]*(?:\d+[.)]\s*)?[*_]*(requests|decisions|files|errors|facts|state)\b/gim
44
45/**
46 * The summary in a fork's reply, without its end line; undefined without one, or with fewer than four of the six parts.
47 * On 19 Oct a reply stopped after 1,300 characters, inside the first of its six parts, and replaced 300k of
48 * conversation as if it were whole; and in the canary bench a Haiku fork took the prompt for an injection and wrote a
49 * status note instead, which replaced its conversation and the facts in it.
50 */
51export function finishedSummary(reply: string): string | undefined {
52  if (!isEnded(reply)) return undefined
53  const text = reply.trimEnd().split('\n').slice(0, -1).join('\n').trim()
54  const parts = new Set(Array.from(text.matchAll(SUMMARY_PART), m => m[1]?.toLowerCase()))
55  return parts.size >= 4 ? text : undefined
56}
57
58/** Whether a reply's last line is the end line. */
59export function isEnded(reply: string): boolean {
60  const bare = (s: string) => s.replace(/[*_`>#.\s]/g, '').toLowerCase()
61  return bare(reply.trimEnd().split('\n').pop() ?? '') === bare(SUMMARY_END)
62}
63
64/** The message the summary stands in as, first in the compacted conversation. */
65export function summaryMessage(summary: string): SessionMessage {
66  return { role: 'user', text: `${SUMMARY_HEAD}\n\n${summary}`, toolUses: [] }
67}
68
69/** What tells one message from another, so a compaction can check the conversation still holds what the summary read. */
70export function markOf(m: SessionMessage): string {
71  const ids = [...m.toolUses.map(t => t.tool_use_id), ...(m.toolResults ?? []).map(t => t.tool_use_id)]
72  return `${m.role}|${m.text.length}|${m.text.slice(0, 200)}|${ids.join(',')}`
73}
74
75/**
76 * The compacted conversation from a summary written ahead over the first `covered` messages, the last of them marked
77 * `mark`: the summary, then every message after that one, as they are (each keeping the engine's handle). The marked
78 * message is looked for where it was read, else wherever it is now when it is there once (the hook's list can count
79 * differently from the one read). Undefined when the conversation no longer holds it (another compaction, a rewind)
80 * or has nothing after it.
81 */
82export function compactedWith(
83  summary: string,
84  covered: number,
85  mark: string,
86  messages: readonly SessionMessage[] | undefined,
87): SessionMessage[] | undefined {
88  const end = messages === undefined ? undefined : endOf(covered, mark, messages)
89  if (messages === undefined || end === undefined || end >= messages.length - 1) return undefined
90  return [summaryMessage(summary), ...messages.slice(end + 1)]
91}
92
93function endOf(covered: number, mark: string, messages: readonly SessionMessage[]): number | undefined {
94  const read = messages[covered - 1]
95  if (read !== undefined && markOf(read) === mark) return covered - 1
96  const found = messages.flatMap((m, i) => (markOf(m) === mark ? [i] : []))
97  return found.length === 1 ? found[0] : undefined
98}
99
100/** Why compactedWith gives undefined for these messages, for the log: counts, roles and lengths, never the text. */
101export function whyNotWith(covered: number, mark: string, messages: readonly SessionMessage[] | undefined): string {
102  if (messages === undefined) return 'the compaction came without the messages'
103  const end = endOf(covered, mark, messages)
104  if (end !== undefined) return `nothing came after the message it ended on, ${end + 1} of ${messages.length}`
105  const found = messages.filter(m => markOf(m) === mark).length
106  if (found > 1) return `${found} of the ${messages.length} messages look like the one it ended on`
107  const read = messages[covered - 1]
108  const [role, length] = mark.split('|', 2)
109  return (
110    `none of the ${messages.length} messages is the one it ended on (${role}, ${length} chars, message ${covered} when read` +
111    (read === undefined ? ')' : `; message ${covered} is now ${read.role}, ${read.text.length} chars)`)
112  )
113}
114
hooks/policy.ts 325 lines
1// What to do with an idle session's prompt cache just before it expires.
2//
3// Three options, priced in list-price USD:
4//   lapse      let it expire; the next prompt re-writes the whole prefix
5//   keepalive  re-send the prefix once (a fork); a cache read refreshes the TTL
6//   compact    summarize while the cache is still warm; the next prompt then
7//              re-writes only the small summary
8//
9// Keep-alives are cheap but recur every TTL, compaction is a one-off but loses
10// detail. So `smart` keeps the cache warm until the keep-alives would have
11// cost as much as compacting (plus a price on the lost detail), then compacts:
12// the ski-rental rule, never worse than twice the best choice in hindsight.
13
14export const TTL_5M = 5 * 60_000
15export const TTL_1H = 60 * 60_000
16
17/** List prices, USD per million tokens (Anthropic API, cached 2026-10-06). */
18export type Pricing = {
19  label: string
20  input: number
21  output: number
22  cacheRead: number
23  /** Haiku 5.5 charges more once a prompt passes 100K tokens. */
24  long?: { above: number; input: number; output: number; cacheRead: number }
25}
26
27const PRICES: ReadonlyArray<readonly [RegExp, Pricing]> = [
28  [/(fable|mythos)-5-1/, { label: 'Fable 5.1', input: 10, output: 50, cacheRead: 0.25 }],
29  [/(fable|mythos)-5/, { label: 'Fable 5', input: 10, output: 50, cacheRead: 1 }],
30  [/opus-5-5/, { label: 'Opus 5.5', input: 4, output: 20, cacheRead: 0.2 }],
31  [/opus-5/, { label: 'Opus 5', input: 5, output: 25, cacheRead: 0.5 }],
32  [/opus-4-(\d)/, { label: 'Opus 4', input: 5, output: 25, cacheRead: 0.5 }],
33  [/sonnet-5-5/, { label: 'Sonnet 5.5', input: 2, output: 10, cacheRead: 0.2 }],
34  [/sonnet-5/, { label: 'Sonnet 5', input: 2, output: 10, cacheRead: 0.2 }],
35  [/sonnet-4/, { label: 'Sonnet 4', input: 3, output: 15, cacheRead: 0.3 }],
36  [
37    /haiku-5-5/,
38    {
39      label: 'Haiku 5.5',
40      input: 0.1,
41      output: 0.5,
42      cacheRead: 0.01,
43      long: { above: 100_000, input: 0.5, output: 2.5, cacheRead: 0.05 },
44    },
45  ],
46  [/haiku/, { label: 'Haiku 4.5', input: 1, output: 5, cacheRead: 0.1 }],
47]
48
49const FALLBACK: Pricing = { label: 'Claude', input: 5, output: 25, cacheRead: 0.5 }
50
51export function pricingFor(model: string | undefined): Pricing {
52  const id = (model ?? '').toLowerCase().replace(/\./g, '-')
53  const hit = PRICES.find(([pattern]) => pattern.test(id))
54
55  if (hit) {
56    // Opus 4.x: name the minor version the id carries.
57    const minor = /opus-4-(\d)/.exec(id)?.[1]
58    return minor ? { ...hit[1], label: `Opus 4.${minor}` } : hit[1]
59  }
60
61  return { ...FALLBACK, label: model ?? FALLBACK.label }
62}
63
64/** Cache writes cost 1.25x input on the 5-minute TTL, 2x on the 1-hour one. */
65export function writeMultiplier(ttlMs: number): number {
66  return ttlMs > TTL_5M ? 2 : 1.25
67}
68
69function perToken(p: Pricing, promptTokens: number) {
70  const r = p.long && promptTokens > p.long.above ? p.long : p
71  return { input: r.input / 1e6, output: r.output / 1e6, cacheRead: r.cacheRead / 1e6 }
72}
73
74/** What compaction has been seen to produce, learned across sessions. */
75export type Learned = {
76  /** Output tokens of a compaction (the summary, with its thinking). */
77  summaryTokens: number
78  /** Context of the first request after a compaction. */
79  postCompactTokens: number
80  /** Share of a compaction's prompt the cache served (0..1). */
81  compactCacheShare: number
82}
83
84export const DEFAULT_LEARNED: Learned = {
85  summaryTokens: 8_000,
86  postCompactTokens: 40_000,
87  compactCacheShare: 0.9,
88}
89
90/** A keep-alive asks for one word; adaptive thinking may add a little. */
91export const KEEPALIVE_OUTPUT_TOKENS = 300
92
93export type Costs = {
94  /** Re-writing the whole prefix when the user comes back to a cold cache. */
95  lapse: number
96  /** One keep-alive: a cache read of the prefix and a one-word reply. */
97  keepAlive: number
98  /** Compacting now, and re-writing the summary when the user comes back. */
99  compact: number
100}
101
102export function costsOf(
103  contextTokens: number,
104  ttlMs: number,
105  pricing: Pricing,
106  learned: Learned,
107): Costs {
108  const w = writeMultiplier(ttlMs)
109  const at = perToken(pricing, contextTokens)
110  const after = Math.min(learned.postCompactTokens, contextTokens)
111  const share = Math.min(1, Math.max(0, learned.compactCacheShare))
112
113  const compactRequest =
114    contextTokens * (share * at.cacheRead + (1 - share) * w * at.input) +
115    learned.summaryTokens * at.output
116  const rewriteSummary = after * w * perToken(pricing, after).input
117
118  return {
119    lapse: contextTokens * w * at.input,
120    keepAlive: contextTokens * at.cacheRead + KEEPALIVE_OUTPUT_TOKENS * at.output,
121    compact: compactRequest + rewriteSummary,
122  }
123}
124
125/**
126 * How many later requests a compaction needs to pay for itself: what it costs (the summary request and the rewrite of
127 * what is left) against what each later request saves by reading the smaller context. Infinity where nothing is saved.
128 * Lost detail is not priced here: measured on 18 Oct (compact_bench, 72 runs), a compaction between turns lost none.
129 */
130export function paybackRequests(contextTokens: number, ttlMs: number, pricing: Pricing, learned: Learned): number {
131  const costs = costsOf(contextTokens, ttlMs, pricing, learned)
132  const after = Math.min(learned.postCompactTokens, contextTokens)
133  const saved = (contextTokens - after) * perToken(pricing, contextTokens).cacheRead
134  return saved > 0 ? costs.compact / saved : Number.POSITIVE_INFINITY
135}
136
137export type Strategy = 'smart' | 'compact' | 'keepalive' | 'off'
138
139export type Policy = {
140  strategy: Strategy
141  /** Below this re-cache cost, let the cache lapse: not worth acting on. */
142  minSavingsUsd: number
143  /** What losing the conversation's detail to a summary is worth avoiding. */
144  compactPenaltyUsd: number
145  /** Never compact a context smaller than this. */
146  minCompactTokens: number
147  /** Stop keeping the cache warm after this long idle. */
148  maxIdleMs: number
149}
150
151export type Situation = {
152  contextTokens: number
153  ttlMs: number
154  pricing: Pricing
155  learned: Learned
156  /** Spent on keep-alives since the session went idle. */
157  keptAliveUsd: number
158  idleMs: number
159  /** False while the prompt holds a draft or agents still run. */
160  canCompact: boolean
161}
162
163export type Action = 'keepalive' | 'compact' | 'lapse' | 'none'
164
165export type Decision = { action: Action; why: string; costs: Costs }
166
167export function decide(policy: Policy, s: Situation): Decision {
168  const costs = costsOf(s.contextTokens, s.ttlMs, s.pricing, s.learned)
169  const answer = (action: Action, why: string): Decision => ({ action, why, costs })
170
171  if (policy.strategy === 'off') {
172    return answer('none', 'off')
173  }
174
175  if (costs.lapse < policy.minSavingsUsd) {
176    return answer('lapse', `re-caching costs only ${usd(costs.lapse)}`)
177  }
178
179  const compactAll = costs.compact + policy.compactPenaltyUsd
180  const compactPays =
181    policy.strategy !== 'keepalive' &&
182    s.contextTokens >= policy.minCompactTokens &&
183    compactAll < costs.lapse
184  const affords = (budget: number) => s.keptAliveUsd + costs.keepAlive <= budget
185  const bridge = 'compaction waits for the draft or the agents'
186
187  if (policy.strategy === 'compact') {
188    if (compactPays && s.canCompact) {
189      return answer('compact', `saves ~${usd(costs.lapse - costs.compact)}`)
190    }
191    if (compactPays && affords(costs.lapse - compactAll)) {
192      return answer('keepalive', bridge)
193    }
194    return answer('lapse', compactPays ? 'compaction blocked' : 'compaction would not pay')
195  }
196
197  // Rent (keep warm) until renting has cost what buying (compacting) would.
198  const budget = compactPays ? compactAll : costs.lapse / 2
199
200  if (s.idleMs < policy.maxIdleMs && affords(budget)) {
201    return answer('keepalive', `${usd(costs.keepAlive)} keeps ${usd(costs.lapse)} of cache`)
202  }
203  if (compactPays && s.canCompact) {
204    return answer('compact', `kept warm for ${usd(s.keptAliveUsd)}; compacting saves the rest`)
205  }
206  if (compactPays && affords(costs.lapse)) {
207    return answer('keepalive', bridge)
208  }
209
210  return answer('lapse', 'keeping it warm no longer pays')
211}
212
213/** When to act: early enough that the request starts before the entry lapses. */
214export function marginMs(ttlMs: number): number {
215  return ttlMs > TTL_5M ? 150_000 : 45_000
216}
217
218export type TtlSetting = 'auto' | '5m' | '1h'
219
220export type TtlEvidence = { ttl: '5m' | '1h'; at: number; count: number }
221
222export type RateLimit = { kind: string; percentUsed: number }
223
224export type Ttl = { ms: number; source: string }
225
226const EVIDENCE_TTL_MS = 14 * 24 * 60 * 60_000
227
228/**
229 * The TTL the session's requests use. Claude Code caches subscription traffic
230 * for an hour and drops to five minutes in overage; API-key traffic defaults
231 * to five minutes. What a cache hit or miss after a gap showed wins over that.
232 */
233export function resolveTtl(
234  setting: TtlSetting,
235  evidence: TtlEvidence | undefined,
236  limits: readonly RateLimit[],
237  now: number,
238): Ttl {
239  if (setting !== 'auto') {
240    return { ms: setting === '1h' ? TTL_1H : TTL_5M, source: 'set' }
241  }
242
243  const plan = limits.filter(l => l.kind === 'five_hour' || l.kind === 'seven_day')
244
245  if (plan.some(l => l.percentUsed >= 100)) {
246    return { ms: TTL_5M, source: 'overage' }
247  }
248
249  const isFresh = evidence !== undefined && now - evidence.at < EVIDENCE_TTL_MS
250  const isTrusted = isFresh && (evidence.ttl === '1h' || evidence.count >= 2)
251
252  if (isTrusted) {
253    return { ms: evidence.ttl === '1h' ? TTL_1H : TTL_5M, source: 'observed' }
254  }
255
256  return plan.length > 0 ? { ms: TTL_1H, source: 'plan' } : { ms: TTL_5M, source: 'api' }
257}
258
259export type CacheUsage = {
260  cache_read_input_tokens: number
261  cache_creation_input_tokens: number
262}
263
264/**
265 * What a request after a gap says about the TTL: a hit past five minutes
266 * can only be the hour-long one; a full re-write well inside the hour points
267 * at five minutes (or an invalidated prefix, hence two sightings are needed).
268 */
269export function observeTtl(
270  gapMs: number,
271  previousTokens: number,
272  usage: CacheUsage,
273): '5m' | '1h' | undefined {
274  if (previousTokens < 4_096) {
275    return undefined
276  }
277
278  const read = usage.cache_read_input_tokens / previousTokens
279  const wrote = usage.cache_creation_input_tokens / previousTokens
280
281  if (gapMs > TTL_5M + 60_000 && read >= 0.5) {
282    return '1h'
283  }
284  if (gapMs > TTL_5M + 15_000 && gapMs < TTL_1H - 5 * 60_000 && read < 0.2 && wrote >= 0.5) {
285    return '5m'
286  }
287
288  return undefined
289}
290
291export function addEvidence(
292  previous: TtlEvidence | undefined,
293  ttl: '5m' | '1h',
294  now: number,
295): TtlEvidence {
296  const count = previous?.ttl === ttl ? previous.count + 1 : 1
297  return { ttl, at: now, count }
298}
299
300/** Moves a learned average toward a new sighting. */
301export function ema(previous: number, sample: number, weight = 0.3): number {
302  return Math.round((previous * (1 - weight) + sample * weight) * 1000) / 1000
303}
304
305export function usd(value: number): string {
306  if (value < 0.01) return '<$0.01'
307  return value < 10 ? `$${value.toFixed(2)}` : `$${Math.round(value)}`
308}
309
310export function tokens(n: number): string {
311  if (n < 1_000) return `${n}`
312  if (n < 100_000) return `${(n / 1_000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`
313  if (n < 1_000_000) return `${Math.round(n / 1_000)}k`
314  return `${(n / 1_000_000).toFixed(2).replace(/0$/, '')}M`
315}
316
317export function duration(ms: number): string {
318  const s = Math.max(0, Math.round(ms / 1000))
319  if (s < 600) return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
320  const m = Math.round(s / 60)
321  if (m < 60) return `${m}m`
322  const h = Math.floor(m / 60)
323  return m % 60 === 0 ? `${h}h` : `${h}h${String(m % 60).padStart(2, '0')}`
324}
325
types/index.d.ts 54 lines
1export type SmartCompactPhase = 'none' | 'warm' | 'acting' | 'cold' | 'compacted'
2
3export type SmartCompactPlan = 'keepalive' | 'compact' | 'lapse' | 'none'
4
5/** The main thread's prompt cache, as the controller tracks it. */
6export type SmartCompactCache = {
7  phase: SmartCompactPhase
8  /** API id of the model that answered last, e.g. `claude-opus-5-5`. */
9  model?: string
10  /** Prompt tokens of the main thread's last request: what a lapse re-writes. */
11  contextTokens?: number
12  /** When the last request that read or wrote the prefix started (ms). */
13  warmAt?: number
14  ttlMs: number
15  ttlSource: string
16  /** What happens at `actAt`, and why. */
17  plan: SmartCompactPlan
18  why: string
19  actAt?: number
20  /** When the session last went idle, and what keeping it warm has cost since. */
21  idleSince?: number
22  keptAlive: number
23  keptAliveUsd: number
24  /**
25   * What lapsing would have cost and what the mod spent instead, credited to
26   * `savedUsd` only once the person comes back and the next request runs.
27   */
28  credit?: { lapseUsd: number; spentUsd: number }
29  /** This session's savings, net of keep-alives and compactions. */
30  savedUsd: number
31  /** `/cache pause`: draw, but never act. */
32  isPaused: boolean
33}
34
35export type SmartCompactLimit = { kind: string; percentUsed: number; resetsAt?: number }
36
37/** What the controller reads of the session beside its cache. */
38export type SmartCompactWorld = {
39  isWorking: boolean
40  /** Off reads as "never compact for me". */
41  isAutoCompactOn: boolean
42  /** The plan's windows: a subscription's cache lives an hour, an API key's five minutes. */
43  limits: SmartCompactLimit[]
44}
45
46declare module 'claude-code' {
47  interface PluginState {
48    'smart-compact': {
49      cache: SmartCompactCache
50      world: SmartCompactWorld
51    }
52  }
53}
54