SLOPSHOPPER

warm-compact

Compacts an idle session just before its prompt cache goes cold, or keeps the cache warm while you're away, so your next prompt doesn't re-read the whole…

spinnercommandtoaststatuspromptmodel
v0.4.1MITupdated 2026-10-17ziedgithub/claude-code-mods/warm-compact
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · warm-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 › /warm-compact ⎿ warm-compact: Warm compact is off for this session. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ⟨Claude Code's own drawing⟩ off Warm compact on Keep warm

Draws

Prompt hint
⟨Claude Code's own drawing⟩ off
README

warm-compact

Compacts an idle session just before its prompt cache goes cold, or keeps the cache warm while you're away.

It is separate from Claude Code's own auto-compact, which compacts when the context window fills up. warm-compact acts on time instead: it compacts when you've been away long enough for the cache to lapse, even when the window is far from full.

Recent Claude Code versions also compact an idle session on their own, about 54 minutes into an hour-long cache. That would compact before warm compact's turn, and whatever keep warm did: a keep warm renewal doesn't count as a new request for it. So the first time warm-compact starts, it turns Claude Code's idle compaction off, by adding "idleCompaction": false to your user settings (~/.claude/settings.json), and says so in the transcript. If you set it to false yourself, or a policy does, it's left as it is; a project's own setting speaks for that project only, so your user settings are still written. If the file can't be read or written, it's left alone and tried again next session. It does this once: turn idle compaction back on afterwards, with the toggle in /config or in the file, and it stays on. Uninstalling warm-compact doesn't put it back: remove the line to have Claude Code's own idle compaction again.

Claude Code caches the conversation for 5 minutes or an hour after each request, depending on your account. If you come back after that, your next prompt re-reads the whole conversation uncached, which is the most expensive way to read it. warm-compact compacts the session a minute before the cache lapses, while the compaction itself can still read the conversation from the cache. Your next prompt then starts from a short summary.

When it compacts

  • Only when the session is idle. Nothing is running, the prompt box is empty, and you haven't typed in it, or emptied it, for a minute, as with Claude Code's own idle compaction. Typing anything holds it off; once you stop, it waits that minute, counts down again, and compacts if the cache still holds by then.
  • Only a large conversation. Below 50,000 tokens, reading the conversation uncached costs little, so it's left alone.
  • Only with auto-compact on. If you've turned Claude Code's auto-compact off, warm compact leaves the session alone too, and says so once. It's checked when a compaction comes due and again as it starts, so turning auto-compact off during a pause counts.
  • Not near a rate limit. When 90% or more of a usage limit is used (the five-hour or the weekly one, or a gateway's spend limit), a compaction or a renewal would spend what you have left, so that pause is left alone, with a line in the transcript saying so. The figures are the last response's; a limit that has reset since doesn't count.
  • Once per pause. After a compaction, nothing happens again until your next prompt.
  • After anyone's compaction. Your /compact, or Claude Code's own, starts the wait over. Where an organization manages Claude Code, plugins are not told of a compaction: warm-compact still leaves the compacted conversation alone until your next prompt, and doesn't take its first, uncached read for a sign of a short cache.
  • Same model. The cache belongs to one model, so after a /model switch there's nothing left to keep warm.
  • Not after a sleep. If the computer slept, or Claude Code stalled, while you were away, the cache may have lapsed meanwhile, so that pause is left alone and a line in the transcript says so.

For the 30 seconds before it compacts, the status line under the prompt counts down: ⇊ compacting in 23s, before the cache goes cold · type to hold.

When you come back, a line in the transcript tells you what happened, for example Compacted at 14:32 (120k → 4k tokens), just before the prompt cache went cold. That line is for you only: it isn't sent to the model. If the compaction found the cache already gone, the line says so, because then it saved nothing.

Two of those in a row and warm compact stands down until Claude Code updates, and says so, once it knows how long your account caches (until then, a compaction finding the cache gone may only mean a 5-minute cache): on some Claude Code versions the compaction misses a cache that is still warm, so every compaction would cost a full re-read. While it stands down its chip shows off: /warm-compact on, or a click on the chip, tries again. Each Claude Code version counts its own misses, so a session still on an older version after an update doesn't reset the newer one's count.

The cache duration Claude Code is set to comes first. Claude Code caches the conversation for an hour on a Claude subscription within its usage limits, and for 5 minutes otherwise, renewing those 5 minutes on its own for an hour after you were last active. Compactions can't read a cache kept alive that way, so the hour is what warm-compact needs. You can pick it with "promptCacheTtl": "1h" in ~/.claude/settings.json; 1-hour cache writes cost more than 5-minute ones. warm-compact reads that setting, and the CLAUDE_CODE_PROMPT_CACHE_TTL and FORCE_PROMPT_CACHING_5M variables that override it:

  • An hour picked: warm-compact knows the duration, with nothing to learn.
  • 5 minutes picked: warm-compact stands down for as long as it stays picked, and says why when a compaction would have come.
  • Nothing picked: it learns the duration as below, and a stand-down after two missed compactions suggests the setting.

Changing the setting starts the missed compactions over.

Whether your account caches for 5 minutes or an hour is learned from the requests themselves and remembered between sessions: the first request after a pause of 6 to 59 minutes shows it, and two such pauses in a row must agree before it changes. A compaction or a renewal that still finds the cache warm 59 minutes on shows an hour too. Until they do, it assumes an hour, as a Claude subscription has.

Headless runs (claude -p) are left alone.

With context-bar installed, a mark after its cache countdown says what warm-compact will do if you stay away: ⇊ for a compaction, ♨ for a keep warm renewal. Hover it to see when. context-bar also counts down on the cache duration warm-compact learned, so the two always agree.

Turning it off for a session

Two chips sit side by side on one row under the prompt, below the mode line, a row they share with the chips of any other mod that puts its own there:

⏸ manual mode on · ? for shortcuts
 on   Warm compact   off  Keep warm

Click Warm compact to turn it off for this session, and again to turn it back on. Turning it off during the countdown cancels it.

The same from the prompt:

/warm-compact        flips it
/warm-compact off    turns it off
/warm-compact on     turns it on
/warm-compact stats  shows what it saved

A new session, a /clear or a /resume starts with it on, and with keep warm off.

Keep warm: renew the cache instead

A compaction keeps your session cheap, but it trades the conversation for a summary. Keep warm keeps the whole conversation instead: a minute before the cache lapses, it renews it with one tiny request that re-reads the conversation from the cache. That request costs about a tenth of the conversation's size in tokens (a twentieth on Opus 5.5) and starts the cache's clock again. Coming back to a cold cache would cost twice its size.

It's off by default, because it spends tokens while you're away. Turn it on with the Keep warm chip, or from the prompt:

/keep-warm        flips it
/keep-warm on     turns it on
/keep-warm off    turns it off
  • It renews the cache at most twice per pause (two hours on an hour-long cache), then warm compact takes over, if it's on. The keepWarmRenewals option changes how many times.
  • A renewal is invisible. It adds nothing to the conversation and the model never sees it; a line in the transcript, Kept the prompt cache warm at 14:32 (1 of 2)., is for you. Text left in the prompt box doesn't hold it off.
  • Every renewal is checked. One that fails (an API error, a dropped connection) says nothing about the cache: warm compact takes over at once (if it's on, and auto-compact too), and keep warm tries again next pause. One that finds the cache gone wrote the conversation back to it itself, for five minutes at least: warm compact takes over a minute before that copy lapses. Either way, the compaction waits for you as its own does when you're typing, and if the cache lapses first it's dropped, with a line in the transcript saying so. A renewal that a prompt of yours overtakes only counts its cost.
  • Some models can't be renewed. On Sonnet 5.5, with Claude Code 2.1.289, the renewal request differs slightly from the session's own and misses the cache. Keep warm notices the first miss and leaves that model to warm compact until Claude Code updates (once it knows how long your account caches, as above).
  • How long a renewal holds the cache is learned the first time you come back, or renew again, after one. If it turns out to be only 5 minutes on your account, keeping an hour-long cache warm would cost more than compacting, so keep warm stands down and says so.

Renewals count in /warm-compact stats too: each costs its request, and the last one before you come back is credited with the re-read it spared.

What it saved

/warm-compact stats adds up what the compactions saved, for this session, the last 7 days and all time:

              compactions  renewals  came back  net saved
This session            1         0          1      +222k
Last 7 days             5         3          6      +1.4M
All time                9         5         11      +2.6M

Savings are counted in input tokens, the unit the API prices everything against: writing a token to an hour-long cache costs 2 of them (1.25 for a 5-minute cache), reading one from the cache 0.1 (0.05 on Opus 5.5, 0.025 on Fable 5.1), and generating one 5.

  • Once you come back to a session, the compaction is credited with the re-read it spared you: the whole conversation written to the cache again. Against that it is charged its own request (reading the conversation from the cache and writing the summary) and writing the summary to the cache when you return.
  • A session you never come back to is charged the compaction alone.
  • Every request after your return reads a smaller conversation too. That saving is left out, so the tally errs low.

On a Claude subscription you don't pay per token, but the same tokens count toward your usage limits.

Options

In /config, or in ~/.claude/settings.json under pluginConfigs:

OptionDefaultWhat it does
minTokens50000The smallest conversation it compacts, in tokens
leadSeconds60How long before the cache lapses a compaction or a renewal starts (20 at least)
keepWarmRenewals2With keep warm on, how many times the cache is renewed in one pause before warm compact takes over

Install

claude plugin marketplace add ziedgithub/claude-code-mods && claude plugin install warm-compact@zied-mods

Needs Claude Code 2.1.296 or later.

Then restart Claude Code.

See the repository README for running it from a clone.

Source 9 files
hooks/register.tsx 737 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { CacheTtl, CompactionRecord, CompactionUsage, Kept, LastRequest, Upcoming } from '../types'
5import { FIVE_MINUTES_TEXT, HINT_TEXT, TTL_SETTING, configuredTtl } from './cache-setting'
6import { OFF_TEXT, SETTING, settingsPath, withIdleCompactionOff } from './idle-compaction'
7import { LATE_MS, MIN_LEAD_MS, WARN_MS, isInTime, isWake, limitText, nearLimit, plan, startOf, upcoming, warnText } from './plan'
8import { MAX_RECORDS, clockTime, compactionHit, isCacheMissed, noticeText, recordsOf, statsText } from './savings'
9import { DEFAULT_TTL, TTL_MS, hitPercent, inferRenewTtl, inferTtl, inputTokens, isCacheTtl } from './shared/cache-ttl'
10import { CHIP_ROW_KEY, splitChipRow } from './shared/chips'
11import { tap } from './shared/stream'
12
13const TICK_MS = 1000
14const CACHE_TTL_KEY = 'cacheTtl'
15const RECORDS_KEY = 'compactions'
16const RENEW_TTL_KEY = 'renewTtl'
17// The models a renewal could not read the conversation from the cache on, each with the
18// engine version that failed: tried again once the engine changes
19const RENEW_MISSES_KEY = 'renewMisses'
20// Compactions in a row that found the cache gone, which a pause still within the TTL should
21// not, counted for each engine version apart, as two may run at once after an update: from
22// COMPACT_MISSES_TO on, warm compact stands down on that version. Claude Code has sent its compaction a conversation the cache did not
23// hold while a fork of the same moment read it whole
24const COMPACT_MISSES_KEY = 'compactMisses'
25const COMPACT_MISSES_TO = 2
26// The TTL last picked for Claude Code, 'auto' when left to it: misses counted under another one
27// start over
28const CONFIGURED_TTL_KEY = 'configuredTtl'
29const STAND_DOWN_TEXT = 'Warm compact: its last'
30const WAKE_TEXT = 'warm-compact left this pause alone: the computer slept, or Claude Code stalled, and the prompt cache may have lapsed meanwhile'
31// The fork that renews the cache asks for as little as it can
32const RENEW_PROMPT = 'Reply with the single word: ok'
33// A renewal that read less of its request from the cache than this missed the entry
34const RENEW_HIT_FROM = 90
35const DEFAULT_MIN_TOKENS = 50_000
36const DEFAULT_LEAD_SECONDS = 60
37const DEFAULT_MAX_RENEWALS = 2
38const DONE_TEXT = 'Compacted before the prompt cache went cold'
39const DROPPED_TEXT = 'Warm compact could not take over before the prompt cache lapsed: the next prompt reads the conversation uncached.'
40const AUTO_COMPACT_OFF_TEXT = 'Warm compact leaves this session alone while auto-compact is off: turn auto-compact on in /config to have it back.'
41// Whether it turned Claude Code's own idle compaction off once: after that, the setting is the
42// person's, /config's toggle among others
43const IDLE_OFF_KEY = 'idleCompactionOff'
44// Someone who edited the prompt box this recently is taken to be back, as Claude Code's own
45// idle compaction takes them, even with the box emptied again
46const PRESENT_MS = 60_000
47const COMMAND = 'warm-compact'
48const KEEP_WARM_COMMAND = 'keep-warm'
49const COMPACT_LABEL = 'Warm compact'
50const KEEP_WARM_LABEL = 'Keep warm'
51const ON_COLOR = '#238636'
52const OFF_COLOR = '#6e7681'
53
54const last = atom({ plugin: 'warm-compact', key: 'last' } as const, null)
55const isTurnRunning = atom({ plugin: 'warm-compact', key: 'isTurnRunning' } as const, false)
56const isEnabled = atom({ plugin: 'warm-compact', key: 'isEnabled' } as const, true)
57const isKeepWarm = atom({ plugin: 'warm-compact', key: 'isKeepWarm' } as const, false)
58const kept = atom({ plugin: 'warm-compact', key: 'kept' } as const, null)
59const pendingRecord = atom({ plugin: 'warm-compact', key: 'pendingRecord' } as const, null)
60const learned = atom({ plugin: 'warm-compact', key: 'ttl' } as const, null)
61const inStore = atom({ plugin: 'warm-compact', key: 'upcoming' } as const, null)
62const tried = atom({ plugin: 'warm-compact', key: 'triedFor' } as const, null)
63const standsDown = atom({ plugin: 'warm-compact', key: 'standsDown' } as const, false)
64
65let cacheTtl: CacheTtl = DEFAULT_TTL
66// Whether a read ever told the TTL, or it is still the default: until one does, a compaction or
67// a first renewal that finds the cache gone may only show a five-minute cache, and counts against
68// neither Claude Code nor the model
69let isTtlKnown = false
70// The TTL picked for Claude Code, which no read is needed to tell, or null when left to it
71let configured: CacheTtl | null = null
72let shownStatus: string | undefined
73// A tick still running when the next comes: the next leaves it be, as two compactions at once
74// would compact twice
75let isTicking = false
76// The renewal or compaction last tried, named by the request and the renewals since: one
77// try each, whatever came of it. Kept in the plugin's state, which a reload of the mod keeps as
78// it keeps the request, so a pause left alone after a sleep stays alone
79let triedFor: string | null = null
80// The try a renewal handed over to a compaction, and how long the entry it plans on holds: the
81// clock starts that compaction as it would its own, or drops it once the entry lapses
82let handover: { attempt: string; ttl: CacheTtl } | null = null
83let maxRenewals = DEFAULT_MAX_RENEWALS
84// Until a read after a renewal shows otherwise, it holds the entry as long as a request does
85let renewTtl: CacheTtl | null = null
86let renewMisses: Record<string, string> = {}
87let compactMisses: Record<string, number> = {}
88// A TTL read once that differs from the one held, until a second read agrees with it
89let pendingTtl: CacheTtl | null = null
90let lastTickAt: number | null = null
91// When the person last edited the prompt box, or emptied it, and whether it held a draft at
92// the last tick: emptying it by Esc or Ctrl+C is no edit the engine tells of
93let editedAt: number | null = null
94let hadDraft = false
95// Whether auto-compact was on, as last asked for which try and when: the engine counts it in a
96// breakdown of the window, too much to ask every second, so it is asked as a compaction comes
97// in store, again for its countdown, and again as it starts
98let autoCompact: { attempt: string; at: number; isOn: boolean } | null = null
99let engineVersion = ''
100// Each reason keep warm stood down is said once a session
101const saidOnce = new Set<string>()
102let minTokens = DEFAULT_MIN_TOKENS
103let leadMs = DEFAULT_LEAD_SECONDS * 1000
104
105const numberOr = (value: unknown, fallback: number): number =>
106  typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback
107
108const showStatus = ($: EngineInterface, text: string | undefined): void => {
109  if (text === shownStatus) return
110  shownStatus = text
111  $.ui.status(text)
112}
113
114// Other mods read what it learned instead of learning it again: context-bar's countdown
115// follows it, so the two never disagree
116const publishTtl = async ($: EngineInterface): Promise<void> => {
117  await update($, learned, () => ({ cache: cacheTtl, renew: renewTtl }))
118}
119
120// Written when it differs from what the state holds, as the clock asks every second. The engine
121// empties every plugin's state as a session ends, a /clear's or a /resume's too, with no
122// session.start after: what it learned is published again then, and so is whether it stands down
123const publishUpcoming = async ($: EngineInterface, next: Upcoming | null): Promise<void> => {
124  if (JSON.stringify(await read($, inStore)) === JSON.stringify(next)) return
125  await update($, inStore, () => next)
126}
127
128const republish = async ($: EngineInterface): Promise<void> => {
129  if ((await read($, learned)) === null) await publishTtl($)
130  const isDown = compactBlock() !== null
131  if ((await read($, standsDown)) !== isDown) await update($, standsDown, () => isDown)
132}
133
134// The engine keeps its TTL to itself: a request after a long enough pause tells it, and it
135// is kept between sessions since it holds for the account
136// One read can mislead: a prompt changed meanwhile misses whatever the TTL, so two in a row
137// must agree before it changes
138const learnTtl = async ($: EngineInterface, ttl: CacheTtl | null): Promise<void> => {
139  if (ttl === null || configured !== null) return
140  if (ttl === cacheTtl) {
141    pendingTtl = null
142    if (!isTtlKnown) {
143      isTtlKnown = true
144      await $.store.set(CACHE_TTL_KEY, ttl)
145    }
146    return
147  }
148  if (pendingTtl !== ttl) {
149    pendingTtl = ttl
150    return
151  }
152  pendingTtl = null
153  cacheTtl = ttl
154  isTtlKnown = true
155  await $.store.set(CACHE_TTL_KEY, ttl)
156  await publishTtl($)
157}
158
159// A compaction, or a first renewal, that read the request's entry warm 59 minutes on shows an
160// hour-long cache: what a pause never as long as a telling one, nor longer than one, shows. Warm
161// as a renewal counts it, past the tools and the system prompt other sessions keep cached. It
162// outweighs a single telling read that said otherwise
163const confirmHour = async ($: EngineInterface, hit: number): Promise<void> => {
164  if (hit < RENEW_HIT_FROM || cacheTtl !== '1h') return
165  pendingTtl = null
166  if (isTtlKnown) return
167  isTtlKnown = true
168  await $.store.set(CACHE_TTL_KEY, cacheTtl)
169}
170
171// A compaction leaves a new prefix, which the cache has none of yet
172const forgetRequest = async ($: EngineInterface): Promise<void> => {
173  await update($, last, prev => (prev === null ? prev : { ...prev, at: null }))
174  await update($, kept, () => null)
175}
176
177// A person who turned auto-compact off wants no compaction they did not ask for, as Claude
178// Code's own idle compaction takes it. `maxAgeMs`: how old an answer for the try may be, 0 for
179// none but this moment's
180const isAutoCompactOn = async ($: EngineInterface, attempt: string, maxAgeMs: number): Promise<boolean> => {
181  const now = await $.clock.now()
182  if (autoCompact === null || autoCompact.attempt !== attempt || now - autoCompact.at > maxAgeMs) {
183    const { context } = await $.session.usage({ breakdown: 'summary' })
184    autoCompact = { attempt, at: now, isOn: context.breakdown?.isAutoCompactEnabled ?? true }
185  }
186  return autoCompact.isOn
187}
188
189// A fork re-sends the main thread's last request with one more message after it: it reads
190// the conversation from the cache, which renews the entry, and leaves the transcript as
191// it was. Resolves when the request started and what it cost, null when there was nothing
192// to fork, or why it failed: an error or an abort, which says nothing of the cache
193type Renewal = { at: number; usage: CompactionUsage } | { at: number; failure: string }
194
195const renewCache = async ($: EngineInterface): Promise<Renewal | null> => {
196  const at = await $.clock.now()
197  const result = await $.model.fork({ prompt: RENEW_PROMPT })
198  if (result.isAnswered || result.reason === 'empty-reply') {
199    return compactionHit(result.usage) === null ? { at, failure: 'nothing counted' } : { at, usage: result.usage }
200  }
201  if (result.reason === 'nothing-to-fork') return null
202  if (result.reason === 'api-error') return { at, failure: `an API error${result.status === null ? '' : ` ${result.status}`}` }
203  return { at, failure: 'it was cut short' }
204}
205
206// A renewal that missed the entry wrote the conversation to the cache again itself, for five
207// minutes at least: a compaction before that reads it from there. One missing after an earlier
208// renewal shows that renewal held five minutes; a first one, that this model's renewals miss.
209// The compaction that takes over is the clock's to start, with every check its own has, and
210// only with auto-compact on, as asked then and there. A renewal a prompt overtook while it ran
211// leaves the pause to that prompt, its cost counted
212// `previous`: the renewals before this one, as the tick saw them, which a prompt sent meanwhile clears
213const renew = async ($: EngineInterface, model: string, isCompactOn: boolean, attempt: string, requestAt: number | null, previous: Kept | null): Promise<void> => {
214  const renewal = await renewCache($)
215  if (renewal === null) return
216  const isOvertaken = (await read($, last))?.at !== requestAt || (await read($, isTurnRunning))
217  const isTakingOver = async (): Promise<boolean> => isCompactOn && (await isAutoCompactOn($, attempt, 0))
218  const takeoverText = (isOn: boolean): string => (isOn ? ', so warm compact takes over' : '')
219  // The cache was likely still there: nothing is learned, and a compaction may still read it
220  if ('failure' in renewal) {
221    if (isOvertaken) return
222    const isOn = await isTakingOver()
223    $.ui.log(`Keep warm: the renewal at ${clockTime(renewal.at)} failed (${renewal.failure})${takeoverText(isOn)}.`)
224    if (isOn) handover = { attempt, ttl: renewTtl ?? cacheTtl }
225    return
226  }
227  const { usage } = renewal
228  const record: CompactionRecord = {
229    kind: 'renewal',
230    at: renewal.at,
231    sessionId: await $.session.id(),
232    model,
233    ttl: cacheTtl,
234    before: usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens,
235    after: 0,
236    usage,
237    isReturned: false,
238  }
239  await addRecord($, record)
240  const hit = compactionHit(usage) ?? 0
241  if (previous !== null) await learnRenewTtl($, inferRenewTtl(previous.at, previous.tokens, usage.cache_read_input_tokens, record.before, renewal.at))
242  if (hit < RENEW_HIT_FROM && previous === null && isTtlKnown) await noteRenewMiss($, model)
243  if (previous === null) await confirmHour($, hit)
244  if (isOvertaken) return
245  if (hit < RENEW_HIT_FROM) {
246    const isOn = await isTakingOver()
247    $.ui.log(`Keep warm: the renewal at ${clockTime(renewal.at)} found the prompt cache gone${takeoverText(isOn)}.`)
248    // The entry is now the one the renewal wrote, with the same count: the try stays the same,
249    // and the next read says how long a renewal's entry lasts, not the request's
250    await update($, kept, () => ({ at: renewal.at, count: previous?.count ?? 0, tokens: record.before }))
251    if (isOn) handover = { attempt, ttl: renewTtl === '1h' ? '1h' : '5m' }
252    return
253  }
254  const count = (previous?.count ?? 0) + 1
255  await update($, kept, () => ({ at: renewal.at, count, tokens: record.before }))
256  await update($, pendingRecord, () => renewal.at)
257  $.ui.log(`Kept the prompt cache warm at ${clockTime(renewal.at)} (${count} of ${maxRenewals}).`)
258}
259
260const addRecord = async ($: EngineInterface, record: CompactionRecord): Promise<void> => {
261  const records = recordsOf(await $.store.get(RECORDS_KEY))
262  await $.store.set(RECORDS_KEY, [...records, record].slice(-MAX_RECORDS))
263}
264
265// The session going on after a compaction, or while a renewal still holds the cache, is
266// when the re-read it spared would have been paid
267const markReturned = async ($: EngineInterface): Promise<void> => {
268  const at = await read($, pendingRecord)
269  if (at === null) return
270  await update($, pendingRecord, () => null)
271  const records = recordsOf(await $.store.get(RECORDS_KEY))
272  const now = await $.clock.now()
273  const isKept = (r: CompactionRecord): boolean => r.kind !== 'renewal' || now < r.at + TTL_MS[renewTtl ?? r.ttl]
274  await $.store.set(RECORDS_KEY, records.map(r => (r.at === at && isKept(r) ? { ...r, isReturned: true } : r)))
275}
276
277const sayOnce = ($: EngineInterface, text: string): void => {
278  if (saidOnce.has(text)) return
279  saidOnce.add(text)
280  $.ui.log(text)
281}
282
283const learnRenewTtl = async ($: EngineInterface, ttl: CacheTtl | null): Promise<void> => {
284  if (ttl === null || ttl === renewTtl) return
285  renewTtl = ttl
286  await $.store.set(RENEW_TTL_KEY, ttl)
287  await publishTtl($)
288}
289
290const noteRenewMiss = async ($: EngineInterface, model: string): Promise<void> => {
291  renewMisses = { ...renewMisses, [model]: engineVersion }
292  await $.store.set(RENEW_MISSES_KEY, renewMisses)
293}
294
295// Why keep warm cannot help here, or null when it can: a renewal that holds five minutes
296// would cost more than a compaction to cover an hour-long cache, and a model whose renewals
297// missed would pay for the whole conversation each time
298const keepWarmBlock = (model: string, isCompactOn: boolean): string | null => {
299  const then = isCompactOn ? ', so warm compact takes over.' : ', so it stands down.'
300  if (cacheTtl === '1h' && renewTtl === '5m') return `Keep warm: a renewal holds this account's cache for 5 minutes only${then}`
301  if (renewMisses[model] === engineVersion) return `Keep warm: renewals can't read the conversation from the cache on ${model}${then}`
302  return null
303}
304
305// The stored counts, by version; one kept before they were, `{ version, count }`, is read as one
306// version's. Versions with none in a row are left out
307const missesOf = (value: unknown): Record<string, number> => {
308  if (typeof value !== 'object' || value === null) return {}
309  const record = value as Record<string, unknown>
310  if (typeof record.version === 'string' && typeof record.count === 'number') return record.count > 0 ? { [record.version]: record.count } : {}
311  return Object.fromEntries(Object.entries(record).filter((entry): entry is [string, number] => typeof entry[1] === 'number' && entry[1] > 0))
312}
313
314// Picked, five minutes stands it down for as long as it stays picked. Left to Claude Code, the
315// way out is said too
316const compactBlock = (): string | null => {
317  if (configured === '5m') return FIVE_MINUTES_TEXT
318  const count = compactMisses[engineVersion] ?? 0
319  if (count < COMPACT_MISSES_TO) return null
320  const fix = configured === null ? ` ${HINT_TEXT};` : ''
321  return `${STAND_DOWN_TEXT} ${count} compactions couldn't read the conversation from the prompt cache, so it stands down.${fix} /${COMMAND} on tries again.`
322}
323
324// Read as each session starts and each turn does, as /config may change it meanwhile. One that
325// differs from the last seen starts the misses over. Left to Claude Code again, the TTL is what
326// reads had told
327const readConfigured = async ($: EngineInterface): Promise<void> => {
328  let next: CacheTtl | null
329  try {
330    next = configuredTtl(await $.env.get('FORCE_PROMPT_CACHING_5M'), await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'), (await $.settings.read())[TTL_SETTING])
331  } catch {
332    return
333  }
334  const wasConfigured = configured !== null
335  configured = next
336  if (next !== null) {
337    cacheTtl = next
338    isTtlKnown = true
339    pendingTtl = null
340  } else if (wasConfigured) {
341    const stored = await $.store.get(CACHE_TTL_KEY)
342    cacheTtl = isCacheTtl(stored) ? stored : DEFAULT_TTL
343    isTtlKnown = isCacheTtl(stored)
344  }
345  const stored = await $.store.get(CONFIGURED_TTL_KEY)
346  if ((isCacheTtl(stored) ? stored : null) !== next) {
347    await $.store.set(CONFIGURED_TTL_KEY, next ?? 'auto')
348    compactMisses = {}
349    await $.store.set(COMPACT_MISSES_KEY, compactMisses)
350    for (const text of saidOnce) if (text.startsWith(STAND_DOWN_TEXT)) saidOnce.delete(text)
351  }
352  if (next !== null || wasConfigured) await publishTtl($)
353  await update($, standsDown, () => compactBlock() !== null)
354}
355
356// Other sessions count too, on this version or another: each change goes on from the stored counts
357const setMisses = async ($: EngineInterface, count: number): Promise<void> => {
358  const { [engineVersion]: _, ...others } = missesOf(await $.store.get(COMPACT_MISSES_KEY))
359  compactMisses = count > 0 ? { ...others, [engineVersion]: count } : others
360  await $.store.set(COMPACT_MISSES_KEY, compactMisses)
361  await update($, standsDown, () => compactBlock() !== null)
362  // A count started over may stand down again, and say so again
363  if (count === 0) for (const text of saidOnce) if (text.startsWith(STAND_DOWN_TEXT)) saidOnce.delete(text)
364}
365
366// Only a compaction the request's own entry should still have held tells: after a renewal,
367// what the cache held is the renewal's to say
368const noteCompaction = async ($: EngineInterface, usage: CompactionUsage | null): Promise<void> => {
369  const hit = compactionHit(usage)
370  if (hit === null) return
371  await confirmHour($, hit)
372  if (!isTtlKnown) return
373  const stored = missesOf(await $.store.get(COMPACT_MISSES_KEY))
374  await setMisses($, isCacheMissed(usage) ? (stored[engineVersion] ?? 0) + 1 : 0)
375  const block = compactBlock()
376  if (block !== null) sayOnce($, block)
377}
378
379// A plugin's own compaction skips its own hooks, so the request is forgotten here. The toast
380// is for someone watching; the transcript line is for whoever comes back
381const compact = async ($: EngineInterface, model: string, tokens: number, isAfterRenewal: boolean): Promise<void> => {
382  showStatus($, undefined)
383  try {
384    const result = await $.session.compact()
385    if (result.skip !== undefined) return
386    await forgetRequest($)
387    const record: CompactionRecord = {
388      at: await $.clock.now(),
389      sessionId: await $.session.id(),
390      model,
391      ttl: cacheTtl,
392      before: result.tokensBefore ?? tokens,
393      after: result.tokensAfter ?? result.usage?.output_tokens ?? 0,
394      usage: result.usage ?? null,
395      isReturned: false,
396    }
397    await addRecord($, record)
398    await update($, pendingRecord, () => record.at)
399    $.ui.toast(DONE_TEXT)
400    $.ui.log(noticeText(record, result.tokensBefore !== undefined && result.tokensAfter !== undefined))
401    if (!isAfterRenewal) await noteCompaction($, record.usage)
402  } catch {
403    // A turn began meanwhile, and renews the cache by itself
404  }
405}
406
407// Padded alike, so the labels after the chips line up
408export const chipLabel = (isOn: boolean): string => ` ${(isOn ? 'on' : 'off').padEnd(3)} `
409
410// `/warm-compact` flips it, `/warm-compact on` and `off` set it
411export const switchedTo = (args: string, isOn: boolean): boolean | null => {
412  const word = args.trim().toLowerCase()
413  if (word === '') return !isOn
414  if (word === 'on' || word === 'off') return word === 'on'
415  return null
416}
417
418const turnText = (name: string, isOn: boolean): string => `${name} is ${isOn ? 'on' : 'off'} for this session.`
419
420// Turned off mid-countdown, the countdown goes at once
421// Turned on by hand, it tries again after standing down
422const turn = async ($: EngineInterface, isOn: boolean): Promise<void> => {
423  await update($, isEnabled, () => isOn)
424  if (isOn && compactBlock() !== null) await setMisses($, 0)
425  if (!isOn) showStatus($, undefined)
426}
427
428const turnKeepWarm = async ($: EngineInterface, isOn: boolean): Promise<void> => {
429  await update($, isKeepWarm, () => isOn)
430}
431
432// Once off in the person's own settings or a policy's, it stays as it is. Another source (a
433// project's, a flag's) speaks for that place only, so the user settings are still written. It is
434// done once: turned back on afterwards, in /config or the file, it stays on. A settings file that
435// will not read, parse or write is left as it is, and tried again next session
436const turnOffIdleCompaction = async ($: EngineInterface): Promise<void> => {
437  try {
438    if ((await $.store.get(IDLE_OFF_KEY)) === true) return
439    const isOff = async (source: 'user' | 'policy'): Promise<boolean> => (await $.settings.read({ source }))[SETTING] === false
440    if (!(await isOff('user')) && !(await isOff('policy'))) {
441      const path = settingsPath(await $.env.get('CLAUDE_CONFIG_DIR'), (await $.env.get('HOME')) ?? '')
442      const next = withIdleCompactionOff((await $.fs.read(path)) as string)
443      if (next === null) return
444      await $.fs.write(path, next)
445      $.ui.log(OFF_TEXT)
446    }
447    await $.store.set(IDLE_OFF_KEY, true)
448  } catch {
449    // Left for next session
450  }
451}
452
453const markTried = async ($: EngineInterface, attempt: string): Promise<void> => {
454  triedFor = attempt
455  await update($, tried, () => attempt)
456}
457
458// One tick at a time: one still running (a renewal, a compaction) has the next leave it be, all
459// but the time it came, which tells a sleep from a long tick
460const tick = async ($: EngineInterface): Promise<void> => {
461  if (isTicking) {
462    lastTickAt = await $.clock.now()
463    return
464  }
465  isTicking = true
466  try {
467    await tickOnce($)
468  } finally {
469    isTicking = false
470  }
471}
472
473const tickOnce = async ($: EngineInterface): Promise<void> => {
474  const now = await $.clock.now()
475  const sleptMs = isWake(lastTickAt, now) ? now - (lastTickAt ?? now) : 0
476  lastTickAt = now
477  await republish($)
478  triedFor = await read($, tried)
479  const isDraft = (await $.prompt.read()).text.trim() !== ''
480  if (hadDraft && !isDraft) editedAt = now
481  hadDraft = isDraft
482  const isCompactWanted = await read($, isEnabled)
483  let isKeepWarmOn = await read($, isKeepWarm)
484  if (!isCompactWanted && !isKeepWarmOn) {
485    await publishUpcoming($, null)
486    return
487  }
488  const request = await read($, last)
489  const renewals = await read($, kept)
490  const attempt = `${request?.at ?? ''}:${renewals?.count ?? 0}`
491  if (handover?.attempt !== attempt) handover = null
492  const { context, rateLimits } = await $.session.usage()
493  const compactBlocked = isCompactWanted ? compactBlock() : null
494  const isCompactOn = isCompactWanted && compactBlocked === null
495  const model = await $.session.model()
496  const block = isKeepWarmOn ? keepWarmBlock(model, isCompactOn) : null
497  if (block !== null) isKeepWarmOn = false
498  const moment = {
499    now,
500    ttl: cacheTtl,
501    leadMs,
502    model,
503    tokens: context.tokens,
504    minTokens,
505    isTurnRunning: await read($, isTurnRunning),
506    isCompactOn,
507    isKeepWarmOn,
508    maxRenewals,
509    kept: renewals,
510    renewTtl: renewTtl ?? cacheTtl,
511    heldUntil: isDraft ? Infinity : editedAt === null ? null : editedAt + PRESENT_MS,
512  }
513  // What the cache did while the computer slept is unknown, so that pause is left alone
514  if (sleptMs > 0 && (triedFor !== attempt || handover !== null)) {
515    await markTried($, attempt)
516    handover = null
517    // A sleep during a turn, at a permission prompt say, leaves no pause to speak of
518    if (!moment.isTurnRunning && upcoming(request, moment) !== null) $.ui.log(`${WAKE_TEXT} (${Math.round(sleptMs / 60_000)} min).`)
519  }
520  const limit = nearLimit(rateLimits, now)
521  // A handover near a rate limit is left alone at once, and said so
522  if (handover !== null && limit !== null) {
523    await markTried($, attempt)
524    handover = null
525    $.ui.log(limitText(limit))
526  }
527  // A renewal's try handed over to a compaction is the compaction's alone, on the entry it planned on
528  const live = handover === null ? moment : { ...moment, isKeepWarmOn: false, renewTtl: handover.ttl }
529  const isTried = triedFor === attempt && handover === null
530  // One try each, none near a rate limit or with auto-compact found off this pause (or last
531  // found off, while a turn runs and nothing is asked), and none past
532  // its time: nothing more is in store then. A compaction held off shows when it would start
533  const coming = isTried || limit !== null ? null : upcoming(request, live)
534  if (coming?.kind === 'compact' && !moment.isTurnRunning) await isAutoCompactOn($, attempt, Infinity)
535  const isComing = coming !== null && isInTime(coming, moment.heldUntil, now) && !(coming.kind === 'compact' && autoCompact !== null && !autoCompact.isOn && (autoCompact.attempt === attempt || moment.isTurnRunning))
536  await publishUpcoming($, isComing ? { ...coming, at: startOf(coming, moment.heldUntil) } : null)
537  // A handover the entry lapsed on, held off all along or come too late, is dropped, and said
538  // so; one a prompt overtook is the prompt's
539  if (handover !== null && coming !== null && !moment.isTurnRunning && now > coming.expiresAt - LATE_MS) {
540    handover = null
541    $.ui.log(DROPPED_TEXT)
542  }
543  let next = isTried ? { kind: 'idle' as const } : plan(request, live)
544  // Near a rate limit, the pause is left alone, before a countdown starts
545  if (next.kind !== 'idle' && limit !== null) {
546    await markTried($, attempt)
547    handover = null
548    next = { kind: 'idle' }
549    $.ui.log(limitText(limit))
550  }
551  // With auto-compact off, so is warm compact: asked again for the countdown, and as it starts
552  if ((next.kind === 'warn' || next.kind === 'compact') && !(await isAutoCompactOn($, attempt, next.kind === 'compact' ? 0 : WARN_MS))) {
553    await markTried($, attempt)
554    handover = null
555    next = { kind: 'idle' }
556    sayOnce($, AUTO_COMPACT_OFF_TEXT)
557  }
558  if (next.kind === 'warn') showStatus($, warnText(next.inMs))
559  else showStatus($, undefined)
560  if (next.kind === 'idle' && compactBlocked !== null && triedFor !== attempt && plan(request, { ...moment, isCompactOn: true }).kind === 'compact') {
561    await markTried($, attempt)
562    sayOnce($, compactBlocked)
563  }
564  // Keep warm standing down says why as its renewal would have come, whatever else left the pause
565  // alone then: warm compact off or stood down, auto-compact off, a rate limit. A compaction still
566  // to come, held off, says it takes over as it starts
567  if (next.kind === 'idle' && block !== null && !(isComing && coming?.kind === 'compact') && plan(request, { ...moment, isKeepWarmOn: true }).kind === 'renew') sayOnce($, keepWarmBlock(model, false) ?? block)
568  if (next.kind === 'idle' || next.kind === 'warn') return
569  const isHandover = handover !== null
570  await markTried($, attempt)
571  handover = null
572  if (block !== null) sayOnce($, block)
573  // Whether auto-compact is on is asked as the compaction a renewal hands over to comes due
574  if (next.kind === 'renew') await renew($, model, isCompactOn, attempt, request?.at ?? null, renewals)
575  // After a renewal, what the cache held is the renewal's to say, not the compaction's
576  else await compact($, model, context.tokens ?? 0, renewals !== null || isHandover)
577}
578
579export const register: Register = (on, options) => {
580  minTokens = numberOr(options.minTokens, DEFAULT_MIN_TOKENS)
581  leadMs = Math.max(MIN_LEAD_MS, numberOr(options.leadSeconds, DEFAULT_LEAD_SECONDS) * 1000)
582  maxRenewals = Math.round(numberOr(options.keepWarmRenewals, DEFAULT_MAX_RENEWALS))
583
584  on('session.start', async ($, e, next) => {
585    const result = await next(e)
586    if (!e.isInteractive) return result
587    const stored = await $.store.get(CACHE_TTL_KEY)
588    if (isCacheTtl(stored)) {
589      cacheTtl = stored
590      isTtlKnown = true
591    }
592    const storedRenewTtl = await $.store.get(RENEW_TTL_KEY)
593    if (isCacheTtl(storedRenewTtl)) renewTtl = storedRenewTtl
594    const misses = await $.store.get(RENEW_MISSES_KEY)
595    if (typeof misses === 'object' && misses !== null) renewMisses = misses as Record<string, string>
596    compactMisses = missesOf(await $.store.get(COMPACT_MISSES_KEY))
597    engineVersion = (await $.session.version()).version
598    await readConfigured($)
599    await publishTtl($)
600    await $.command.register({ name: COMMAND, description: 'Compact before the prompt cache goes cold: on or off for this session (nothing flips it), or stats for what it saved' })
601    await $.command.register({ name: KEEP_WARM_COMMAND, description: 'Keep the prompt cache warm while you are away, instead of compacting at once: on or off for this session (nothing flips it)' })
602    $.clock.every(TICK_MS, () => void tick($))
603    await turnOffIdleCompaction($)
604    return result
605  })
606
607  // A subagent's turn is neither the main one running nor the person coming back. Claude Code
608  // 2.1.302 names it in `agentId`, which 2.1.296's contract has not
609  on('turn.start', async ($, e, next) => {
610    if ((e as { agentId?: string }).agentId !== undefined) return next(e)
611    await update($, isTurnRunning, () => true)
612    await readConfigured($)
613    await markReturned($)
614    return next(e)
615  })
616
617  on('turn.complete', async ($, e, next) => {
618    if (e.agentId === undefined) await update($, isTurnRunning, () => false)
619    return next(e)
620  })
621
622  // The person's own hand on the prompt box: a key or a paste. A recall from the history leaves
623  // a draft, which says as much; `prompt.change`, which would tell of it, does not load on
624  // Claude Code 2.1.296
625  on('prompt.edit', async ($, e, next) => {
626    void $.clock.now().then(at => {
627      editedAt = at
628    })
629    return next(e)
630  })
631
632  // Each main-thread request renews the cache; the first after a message says how much of
633  // the conversation was still cached when it was sent. Unless a compaction went first: then it
634  // is the first over a new prefix, and says nothing of the TTL. Where an organization manages
635  // Claude Code, `session.compact` passes over the plugins a person installs, and the engine
636  // having no measure of the window yet is all that tells of it, a `/compact` while idle or an
637  // auto-compact at the turn's start. Until that request, the missing measure leaves the pause
638  // alone too. A request the API ran tools of its own in (an advisor) reports usage summed over
639  // its steps, which tells nothing and is no entry's size: it is learned from once it is answered
640  on('turn.step', async function* ($, e, next) {
641    if (e.agentId !== undefined) return yield* next(e)
642    const model = await $.session.model()
643    const requestAt = await $.clock.now()
644    const isNewPrefix = (await $.session.usage()).context.tokens === undefined
645    const telling: { read: { prev: LastRequest | null; renewed: Kept | null; cacheRead: number; tokens: number } | null } = { read: null }
646    const result = yield* tap(next(e), async chunk => {
647      if (chunk.kind !== 'stop' || chunk.usage === null) return
648      const tokens = inputTokens(chunk.usage)
649      const prev = await read($, last)
650      const renewed = await read($, kept)
651      if (e.index === 0 && hitPercent(chunk.usage) !== null && !isNewPrefix) telling.read = { prev, renewed, cacheRead: chunk.usage.cache_read_input_tokens, tokens }
652      await update($, last, () => ({ at: requestAt, model, tokens }))
653      await update($, kept, () => null)
654    })
655    if ((result.serverToolUses ?? []).length > 0) {
656      await update($, last, prev => (prev === null ? prev : { ...prev, tokens: undefined }))
657      return result
658    }
659    const seen = telling.read
660    // A renewal since the last request held the entry meanwhile: what this read found says how
661    // long a renewal's lasts, not a request's
662    if (seen?.prev != null && seen.renewed === null) await learnTtl($, inferTtl(seen.prev, model, seen.cacheRead, seen.tokens, requestAt))
663    if (seen?.renewed != null && cacheTtl === '1h') await learnRenewTtl($, inferRenewTtl(seen.renewed.at, seen.renewed.tokens, seen.cacheRead, seen.tokens, requestAt))
664    return result
665  })
666
667  // Anyone's compaction of the main conversation that stands changes the prefix; one
668  // computed ahead or vetoed leaves it, and a subagent's leaves the main one
669  on('session.compact', async ($, e, next) => {
670    const result = await next(e)
671    if (e.trigger !== 'precompute' && e.agentId === undefined && result.skip === undefined) await forgetRequest($)
672    return result
673  })
674
675  on('command.run', { command: COMMAND }, async ($, e) => {
676    if (e.args.trim().toLowerCase() === 'stats') {
677      return { text: statsText(recordsOf(await $.store.get(RECORDS_KEY)), await $.clock.now(), await $.session.id()) }
678    }
679    // Flipped from what the chip shows: stood down, it is off, and the flip tries again
680    const isOn = switchedTo(e.args, (await read($, isEnabled)) && !(await read($, standsDown)))
681    if (isOn === null) return { text: `Usage: /${COMMAND} [on|off|stats]` }
682    await turn($, isOn)
683    return { text: turnText('Warm compact', isOn) }
684  })
685
686  on('command.run', { command: KEEP_WARM_COMMAND }, async ($, e) => {
687    const isOn = switchedTo(e.args, await read($, isKeepWarm))
688    if (isOn === null) return { text: `Usage: /${KEEP_WARM_COMMAND} [on|off]` }
689    await turnKeepWarm($, isOn)
690    return { text: turnText('Keep warm', isOn) }
691  })
692
693  // The chips go on the row of chips under the hint line, which the engine still draws: the
694  // one another mod's chips already started, or a row of their own
695  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
696    const { above, chips } = splitChipRow(await next(e))
697    const { Box, Text, Button } = $.ui.resolve(e)
698    // Stood down, it shows off, and a press tries again
699    const isCompactOn = (await read($, isEnabled)) && !(await read($, standsDown))
700    const isKeepWarmOn = await read($, isKeepWarm)
701    return (
702      <Box flexDirection="column">
703        {above}
704        <Box key={CHIP_ROW_KEY} columnGap={2} flexWrap="wrap">
705          {chips}
706          <Box gap={1}>
707            <Box backgroundColor={isCompactOn ? ON_COLOR : OFF_COLOR}>
708              <Button key="toggle" label={chipLabel(isCompactOn)} plain onPress={() => void turn($, !isCompactOn)} />
709            </Box>
710            <Text dimColor>{COMPACT_LABEL}</Text>
711          </Box>
712          <Box gap={1}>
713            <Box backgroundColor={isKeepWarmOn ? ON_COLOR : OFF_COLOR}>
714              <Button key="keep-warm" label={chipLabel(isKeepWarmOn)} plain onPress={() => void turnKeepWarm($, !isKeepWarmOn)} />
715            </Box>
716            <Text dimColor>{KEEP_WARM_LABEL}</Text>
717          </Box>
718        </Box>
719      </Box>
720    )
721  })
722
723  // A /clear or a /resume goes on in this process with another conversation, which starts as a
724  // new session does: nothing to come back to, and both switches as they start
725  on('session.end', async ($, e, next) => {
726    if (e.reason === 'clear' || e.reason === 'resume') {
727      await update($, last, () => null)
728      await update($, kept, () => null)
729      await update($, pendingRecord, () => null)
730      await update($, isEnabled, () => true)
731      await update($, isKeepWarm, () => false)
732      saidOnce.clear()
733    }
734    return next(e)
735  })
736}
737
hooks/cache-setting.ts 25 lines
1// Claude Code picks how long the main conversation stays cached: an hour on a Claude
2// subscription within its limits, five minutes otherwise. Someone can pick for it, and what they
3// pick wins, in this order: FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, then
4// `promptCacheTtl` in the settings. Five minutes, kept alive by Claude Code's own touches, holds
5// the conversation for its requests, but its compactions read none of it
6
7import type { CacheTtl } from '../types'
8
9export const TTL_SETTING = 'promptCacheTtl'
10
11export const FIVE_MINUTES_TEXT = `Warm compact: Claude Code is set to cache the conversation for 5 minutes, which compactions can't read from, so it stands down.`
12
13// Said with a stand-down when the choice was left to Claude Code
14export const HINT_TEXT = `"${TTL_SETTING}": "1h" in your settings can fix this`
15
16// As Claude Code reads a boolean variable
17const isSet = (value: string | undefined): boolean => value !== undefined && ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase())
18
19// The TTL picked for Claude Code, or null when it is left to choose
20export const configuredTtl = (force5m: string | undefined, envTtl: string | undefined, setting: unknown): CacheTtl | null => {
21  if (isSet(force5m)) return '5m'
22  if (envTtl === '5m' || envTtl === '1h') return envTtl
23  return setting === '5m' || setting === '1h' ? setting : null
24}
25
hooks/idle-compaction.ts 28 lines
1// Claude Code compacts an idle session on its own too, about 54 minutes into an hour-long
2// cache. It arms once per request of the main conversation, and a renewal is a fork, which
3// does not count as one: it would compact whatever keep warm did, and before warm compact's
4// own turn. Its one switch is `idleCompaction` in the settings, absent meaning on, so the mod
5// turns it off in the user's settings while it is installed
6
7export const SETTING = 'idleCompaction'
8
9export const OFF_TEXT = `warm-compact turned off Claude Code's own idle compaction ("${SETTING}": false in your user settings), so the two never compact the same pause.`
10
11// The user settings file, where the engine keeps them: under CLAUDE_CONFIG_DIR, or ~/.claude
12export const settingsPath = (configDir: string | undefined, home: string): string =>
13  `${configDir !== undefined && configDir !== '' ? configDir.replace(/\/+$/, '') : `${home}/.claude`}/settings.json`
14
15// The settings file with the switch off, or null when it already is, or when the file is not a
16// JSON object, which is left as it stands rather than rewritten
17export const withIdleCompactionOff = (text: string): string | null => {
18  let settings: unknown
19  try {
20    settings = JSON.parse(text)
21  } catch {
22    return null
23  }
24  if (typeof settings !== 'object' || settings === null || Array.isArray(settings)) return null
25  if ((settings as Record<string, unknown>)[SETTING] === false) return null
26  return `${JSON.stringify({ ...settings, [SETTING]: false }, null, 2)}\n`
27}
28
hooks/plan.ts 98 lines
1import type { CacheTtl, Kept, LastRequest, Upcoming } from '../types'
2import { TTL_MS } from './shared/cache-ttl'
3
4const SECOND_MS = 1000
5
6// The countdown shows this long before the compaction starts
7export const WARN_MS = 30 * SECOND_MS
8// A compaction or a renewal started this close to the lapse may reach the API after it, and
9// miss: none starts later
10export const LATE_MS = 15 * SECOND_MS
11// The shortest lead: past LATE_MS, a few ticks to start in, as ticks fall anywhere in a second
12export const MIN_LEAD_MS = LATE_MS + 5 * SECOND_MS
13// Ticks come a second apart. A longer gap is the computer asleep or the process stalled:
14// what the cache did meanwhile is unknown, Claude Code's keep-alive having stopped with it
15export const WAKE_GAP_MS = 30 * SECOND_MS
16
17export type Moment = {
18  now: number
19  ttl: CacheTtl
20  leadMs: number
21  // The session's model now: the cache entry is per model
22  model: string
23  // The conversation's size as the last response measured it
24  tokens: number | undefined
25  minTokens: number
26  isTurnRunning: boolean
27  isCompactOn: boolean
28  isKeepWarmOn: boolean
29  // The most renewals in one pause, after which a compaction takes over
30  maxRenewals: number
31  kept: Kept | null
32  // How long a renewal holds the entry, which may be less than a request's TTL
33  renewTtl: CacheTtl
34  // Until when someone back holds a compaction off: a minute past their last edit of the prompt
35  // box, or for as long as a draft sits in it (Infinity); null when nobody is
36  heldUntil: number | null
37}
38
39export type Plan = { kind: 'idle' } | { kind: 'warn'; inMs: number } | { kind: 'compact' } | { kind: 'renew' }
40
41const IDLE: Plan = { kind: 'idle' }
42
43// Each request renews the entry, so it lapses one TTL after the last, or after the last
44// renewal keep warm made. Before it does, keep warm renews it again, up to `maxRenewals`
45// times in a pause, and then a compaction takes over. Either starts `leadMs` ahead, while
46// its own request can still read the conversation from the cache. A switched model has none
47// of the conversation cached, and a small conversation costs little to read cold. What the
48// pause holds, whatever the time, is what other mods show: context-bar beside its countdown
49export const upcoming = (last: LastRequest | null, m: Moment): Upcoming | null => {
50  if (last === null || last.at === null || last.model !== m.model) return null
51  if (m.tokens === undefined || m.tokens < m.minTokens) return null
52  const renewals = m.kept?.count ?? 0
53  const kind = m.isKeepWarmOn && renewals < m.maxRenewals ? 'renew' : m.isCompactOn ? 'compact' : null
54  if (kind === null) return null
55  const ttlMs = m.kept === null ? TTL_MS[m.ttl] : TTL_MS[m.renewTtl]
56  const expiresAt = (m.kept?.at ?? last.at) + ttlMs
57  return { kind, at: expiresAt - Math.min(m.leadMs, ttlMs - WARN_MS), expiresAt }
58}
59
60// When what is in store starts: someone back holds a compaction off until the hold is over; a
61// renewal goes on, as it keeps the cache for them
62export const startOf = (next: Upcoming, heldUntil: number | null): number =>
63  next.kind === 'compact' && heldUntil !== null ? Math.max(next.at, heldUntil) : next.at
64
65// Whether it can still start in time, now or when due
66export const isInTime = (next: Upcoming, heldUntil: number | null, now: number): boolean =>
67  Math.max(startOf(next, heldUntil), now) <= next.expiresAt - LATE_MS
68
69// A compaction is announced for WARN_MS before it starts, held off or not; a renewal changes
70// nothing anyone sees. A turn renews the entry by itself
71export const plan = (last: LastRequest | null, m: Moment): Plan => {
72  const next = m.isTurnRunning ? null : upcoming(last, m)
73  if (next === null || !isInTime(next, m.heldUntil, m.now)) return IDLE
74  const at = startOf(next, m.heldUntil)
75  if (m.now >= at) return { kind: next.kind }
76  if (next.kind === 'compact' && m.now >= at - WARN_MS) return { kind: 'warn', inMs: at - m.now }
77  return IDLE
78}
79
80// Near a rate limit, what a compaction or a renewal would spend is better left to the person,
81// as Claude Code's own idle compaction leaves it
82export const LIMIT_FROM = 90
83
84const LIMIT_NAMES: Record<string, string> = { five_hour: 'five-hour', seven_day: 'weekly', spend_limit: 'spend' }
85
86// The first rate-limit window used past LIMIT_FROM, or null. The figures are the last
87// response's, so a window that has reset since no longer counts
88export const nearLimit = <L extends { kind: string; percentUsed: number; resetsAt?: string }>(limits: readonly L[], now: number): L | null =>
89  limits.find(l => l.percentUsed >= LIMIT_FROM && !(l.resetsAt !== undefined && Date.parse(l.resetsAt) <= now)) ?? null
90
91export const limitText = (limit: { kind: string; percentUsed: number }): string =>
92  `warm-compact left this pause alone: ${Math.round(limit.percentUsed)}% of your ${LIMIT_NAMES[limit.kind] ?? limit.kind.replace(/_/g, ' ')} limit is used.`
93
94export const warnText = (inMs: number): string => `⇊ compacting in ${Math.ceil(inMs / SECOND_MS)}s, before the cache goes cold · type to hold`
95
96// Whether the tick at `now` follows one long enough ago that the computer slept between
97export const isWake = (lastTickAt: number | null, now: number): boolean => lastTickAt !== null && now - lastTickAt > WAKE_GAP_MS
98
hooks/savings.ts 149 lines
1import type { CacheTtl, CompactionRecord, CompactionUsage } from '../types'
2
3const DAY_MS = 24 * 60 * 60_000
4const WEEK_MS = 7 * DAY_MS
5export const MAX_RECORDS = 1000
6// What the API charges, in multiples of a plain input token: a cache write at each TTL,
7// and output, on every current model
8const WRITE_COST: Record<CacheTtl, number> = { '5m': 1.25, '1h': 2 }
9const OUTPUT_COST = 5
10// A cache read is a tenth of an input token, less on the newest models
11const READ_COSTS: readonly [RegExp, number][] = [
12  [/fable-5-1|mythos-5-1/, 0.025],
13  [/opus-5-5/, 0.05],
14]
15const DEFAULT_READ_COST = 0.1
16// Below this share read from the cache, the compaction's request found the entry gone. A miss
17// still reads the tools and the system prompt other sessions keep cached, half of a small
18// conversation; a warm compaction leaves only its last reply and its own prompt uncached
19const WARM_FROM = 80
20
21export const readCost = (model: string): number => READ_COSTS.find(([pattern]) => pattern.test(model))?.[1] ?? DEFAULT_READ_COST
22
23const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
24
25const isUsage = (value: unknown): value is CompactionUsage => {
26  if (typeof value !== 'object' || value === null) return false
27  const usage = value as Record<string, unknown>
28  return ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'].every(key => isNumber(usage[key]))
29}
30
31export const isRecord = (value: unknown): value is CompactionRecord => {
32  if (typeof value !== 'object' || value === null) return false
33  const record = value as Record<string, unknown>
34  return (
35    (record.kind === undefined || record.kind === 'renewal') &&
36    isNumber(record.at) &&
37    typeof record.sessionId === 'string' &&
38    typeof record.model === 'string' &&
39    (record.ttl === '5m' || record.ttl === '1h') &&
40    isNumber(record.before) &&
41    isNumber(record.after) &&
42    (record.usage === null || isUsage(record.usage)) &&
43    typeof record.isReturned === 'boolean'
44  )
45}
46
47export const recordsOf = (stored: unknown): CompactionRecord[] => (Array.isArray(stored) ? stored.filter(isRecord) : [])
48
49// What a compaction's request read from the cache, out of all it was answered over
50export const compactionHit = (usage: CompactionUsage | null): number | null => {
51  if (usage === null) return null
52  const total = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
53  return total === 0 ? null : Math.round((usage.cache_read_input_tokens / total) * 100)
54}
55
56export const isCacheMissed = (usage: CompactionUsage | null): boolean => {
57  const hit = compactionHit(usage)
58  return hit !== null && hit < WARM_FROM
59}
60
61export type Saving = { avoided: number; spent: number }
62
63// In input-token equivalents. Coming back to a cold cache writes the whole conversation
64// to it again. A renewal read the conversation instead, and wrote only its own tail, for
65// five minutes. After a compaction, the summary is written on the way back, and the
66// compaction itself read the conversation and wrote the summary. What was never gone back
67// to, or went cold anyway, spared nothing and paid for itself. Requests after the first
68// back read a smaller conversation too, which is left out, so the tally errs low
69export const savingOf = (record: CompactionRecord): Saving => {
70  const write = WRITE_COST[record.ttl]
71  const usage = record.usage
72  if (record.kind === 'renewal') {
73    const renewal =
74      usage === null
75        ? readCost(record.model) * record.before
76        : readCost(record.model) * usage.cache_read_input_tokens +
77          WRITE_COST['5m'] * usage.cache_creation_input_tokens +
78          usage.input_tokens +
79          OUTPUT_COST * usage.output_tokens
80    return { avoided: record.isReturned ? write * record.before : 0, spent: renewal }
81  }
82  const compaction =
83    usage === null
84      ? readCost(record.model) * record.before + OUTPUT_COST * record.after
85      : readCost(record.model) * usage.cache_read_input_tokens +
86        write * usage.cache_creation_input_tokens +
87        usage.input_tokens +
88        OUTPUT_COST * usage.output_tokens
89  if (!record.isReturned) return { avoided: 0, spent: compaction }
90  return { avoided: write * record.before, spent: compaction + write * record.after }
91}
92
93export const formatTokens = (tokens: number): string => {
94  const size = Math.abs(tokens)
95  if (size >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`
96  if (size >= 1000) return `${Math.round(tokens / 1000)}k`
97  return String(Math.round(tokens))
98}
99
100const signed = (tokens: number): string => (tokens >= 0 ? `+${formatTokens(tokens)}` : `-${formatTokens(-tokens)}`)
101
102type Row = { label: string; records: CompactionRecord[] }
103
104const rowText = ({ label, records }: Row): string => {
105  const savings = records.map(savingOf)
106  const net = savings.reduce((sum, s) => sum + s.avoided - s.spent, 0)
107  const returned = records.filter(r => r.isReturned).length
108  const renewals = records.filter(r => r.kind === 'renewal').length
109  return [
110    label.padEnd(14),
111    String(records.length - renewals).padStart(11),
112    String(renewals).padStart(10),
113    String(returned).padStart(11),
114    (records.length === 0 ? '-' : signed(net)).padStart(11),
115  ].join('')
116}
117
118export const statsText = (records: readonly CompactionRecord[], now: number, sessionId: string): string => {
119  const rows: Row[] = [
120    { label: 'This session', records: records.filter(r => r.sessionId === sessionId) },
121    { label: 'Last 7 days', records: records.filter(r => now - r.at < WEEK_MS) },
122    { label: 'All time', records: [...records] },
123  ]
124  return [
125    'Savings, in input tokens (a cache write at 1h counts as 2, a cache read as 0.1 or less):',
126    '',
127    `${''.padEnd(14)}${'compactions'.padStart(11)}${'renewals'.padStart(10)}${'came back'.padStart(11)}${'net saved'.padStart(11)}`,
128    ...rows.map(rowText),
129    '',
130    'A compaction, or the last renewal before you came back, counts once its session goes on: the re-read it spared is set against what it cost. What was never gone back to counts its cost alone.',
131  ].join('\n')
132}
133
134const pad = (n: number): string => String(n).padStart(2, '0')
135
136export const clockTime = (at: number): string => {
137  const date = new Date(at)
138  return `${pad(date.getHours())}:${pad(date.getMinutes())}`
139}
140
141// The transcript's lasting line, for whoever comes back to the session
142export const noticeText = (record: CompactionRecord, hasSizes: boolean): string => {
143  const sizes = hasSizes ? ` (${formatTokens(record.before)} → ${formatTokens(record.after)} tokens)` : ''
144  if (isCacheMissed(record.usage)) {
145    return `Compacted at ${clockTime(record.at)}${sizes}, but the prompt cache had already lapsed, so this one saved nothing.`
146  }
147  return `Compacted at ${clockTime(record.at)}${sizes}, just before the prompt cache went cold. The conversation goes on from the summary.`
148}
149
hooks/shared/cache-ttl.ts 86 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5// The mod's own contract names the two TTLs, for the values it keeps
6import type { CacheTtl } from '../../types'
7
8const MINUTE_MS = 60_000
9
10export const TTL_MS: Record<CacheTtl, number> = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS }
11// What the engine picks for a main thread that may cache for an hour, which a session on a
12// Claude subscription does, until a request shows otherwise
13export const DEFAULT_TTL: CacheTtl = '1h'
14// Past a TTL by this much, a request's hit or miss is the entry's lapse and not a race
15const TTL_MARGIN_MS = 30_000
16// What a request read from the cache is set against the entry the last read left, all that read
17// was answered over: one that holds is read whole, whatever is added after it (a long message
18// pasted in), and one that lapsed leaves only the tools and the system prompt other sessions keep
19// cached, some 25k tokens, half a small conversation, a fifth of a large one. So under half of
20// the entry read found it gone, and only 80% or more of an entry large enough that the shared
21// part cannot reach it found it whole
22const WARM_FROM = 80
23const COLD_BELOW = 50
24const TELLING_TOKENS = 50_000
25// Past a renewal, a read this warm found the conversation, and one this cold found only
26// the tools and the system prompt, which other sessions keep cached
27const RENEWED_FROM = 90
28const LAPSED_BELOW = 50
29
30type RequestUsage = { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
31
32// All the input the request was answered over: what was read, what was written, and what went
33// uncached
34export const inputTokens = (usage: RequestUsage): number => usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
35
36// The share of the prompt the cache served, out of all its input
37export const hitPercent = (usage: RequestUsage): number | null => {
38  const total = inputTokens(usage)
39  return total === 0 ? null : Math.round((usage.cache_read_input_tokens / total) * 100)
40}
41
42export const isCacheTtl = (value: unknown): value is CacheTtl => value === '5m' || value === '1h'
43
44// Only a pause longer than five minutes and shorter than an hour tells the two TTLs apart
45const isTelling = (pause: number): boolean =>
46  pause >= TTL_MS['5m'] + TTL_MARGIN_MS && pause <= TTL_MS['1h'] - TTL_MARGIN_MS
47
48// A conversation only grows between two requests: a later one answered over less than this share of
49// the entry, or reading more than SERVED_ABOVE of it, went through something the figures do not
50// show (a request whose usage is summed over its own server-side steps, as an advisor's is; a
51// compaction or a /clear no hook was told of), and tells nothing
52const SHRUNK_BELOW = 90
53const SERVED_ABOVE = 150
54
55// The share of an entry of `tokens` a later request of `requestTokens` read, or null with no
56// entry to set it against, or none the two figures can be trusted for
57const servedOf = (read: number, tokens: number | undefined, requestTokens: number): number | null => {
58  if (tokens === undefined || tokens <= 0 || requestTokens * 100 < tokens * SHRUNK_BELOW) return null
59  const served = Math.round((read / tokens) * 100)
60  return served > SERVED_ABOVE ? null : served
61}
62
63// `last`: the main thread's last request, when it left (null once a compaction changed the
64// prefix), on which model, and all it was answered over. `read`: what the request after it read
65// from the cache, out of the `tokens` it was answered over. Past a telling pause, an entry still read means an hour, one gone means five
66// minutes. A miss can also come from a prompt that changed meanwhile (an edited CLAUDE.md, a
67// server connected), which a long pause with a hit corrects, unless compactions take each pause
68export const inferTtl = (last: { at: number | null; model: string; tokens?: number }, model: string, read: number, tokens: number, requestAt: number): CacheTtl | null => {
69  if (last.at === null || last.model !== model || !isTelling(requestAt - last.at)) return null
70  const served = servedOf(read, last.tokens, tokens)
71  if (served === null) return null
72  if (served < COLD_BELOW) return '5m'
73  return served >= WARM_FROM && (last.tokens ?? 0) >= TELLING_TOKENS ? '1h' : null
74}
75
76// A renewal (a plugin's fork of the conversation) reads the entry without the hour-long TTL a
77// session's own requests ask for. Whether it holds the entry, of `tokens`, an hour or five
78// minutes shows in what a read of `readTokens` a telling pause after it finds
79export const inferRenewTtl = (renewedAt: number, tokens: number | undefined, read: number, readTokens: number, readAt: number): CacheTtl | null => {
80  if (!isTelling(readAt - renewedAt)) return null
81  const served = servedOf(read, tokens, readTokens)
82  if (served === null) return null
83  if (served >= RENEWED_FROM && (tokens ?? 0) >= TELLING_TOKENS) return '1h'
84  return served < LAPSED_BELOW ? '5m' : null
85}
86
hooks/shared/chips.ts 24 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5import type { RenderElement, RenderNode } from 'claude-code'
6
7// The mods that put on/off chips under the hint line share one row of them, whichever are
8// loaded: each leaves its chips in a Box under this key, and the one drawn over it adds its
9// own to that row instead of starting another
10export const CHIP_ROW_KEY = 'mod-chip-row'
11
12// What the plugins beneath and the engine drew, as the rows above the chip row and the chips
13// already in it: a column ending in that row, or else the drawing whole with no chips yet
14export const splitChipRow = (beneath: RenderElement): { above: RenderNode[]; chips: RenderNode[] } => {
15  if (beneath.type === 'Box' && beneath.props?.flexDirection === 'column') {
16    const rows = beneath.children ?? []
17    const last = rows.at(-1)
18    if (typeof last === 'object' && last.type === 'Box' && last.props?.key === CHIP_ROW_KEY) {
19      return { above: rows.slice(0, -1), chips: last.children ?? [] }
20    }
21  }
22  return { above: [beneath], chips: [] }
23}
24
hooks/shared/stream.ts 14 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5// Passes the response on as it streams, seeing each chunk on the way
6export async function* tap<T, R>(stream: AsyncGenerator<T, R>, see: (chunk: T) => Promise<void>): AsyncGenerator<T, R> {
7  for (;;) {
8    const step = await stream.next()
9    if (step.done === true) return step.value
10    await see(step.value)
11    yield step.value
12  }
13}
14
types/index.d.ts 69 lines
1export type CacheTtl = '5m' | '1h'
2// The last main-thread request, which renewed the cache entry the next prompt would read.
3// `at`: when it was made, null once a compaction or a /clear changed the prefix.
4// `model`: the session's model then, the one the entry belongs to.
5// `tokens`: all it was answered over, the size of the entry it left
6export type LastRequest = { at: number | null; model: string; tokens?: number }
7// The renewals keep warm made since the last request: the latest's start, how many, and the
8// size of the entry the latest left
9export type Kept = { at: number; count: number; tokens?: number }
10// What it learned of the account's prompt cache: how long a request's entry lasts, and a
11// renewal's once a read after one told (null: as long as a request's). Other mods read it
12// rather than learn it again, so the session has one figure
13export type LearnedTtl = { cache: CacheTtl; renew: CacheTtl | null }
14// What the pause holds if the person stays away: a renewal or a compaction, when it starts and
15// when the cache entry it acts on lapses
16export type Upcoming = { kind: 'compact' | 'renew'; at: number; expiresAt: number }
17
18// What a compaction's own request was answered over, as the API reports it
19export type CompactionUsage = {
20  input_tokens: number
21  output_tokens: number
22  cache_read_input_tokens: number
23  cache_creation_input_tokens: number
24}
25
26// One compaction or cache renewal warm-compact made, kept across sessions to tally what
27// they saved. `kind`: absent for a compaction.
28// `before`, `after`: the conversation's size in tokens either side of a compaction, or the
29// size a renewal read (`after` 0).
30// `usage`: its request's, when the engine reported one.
31// `isReturned`: whether the session went on afterwards with what it kept, which is when the
32// re-read it spared would have been paid
33export type CompactionRecord = {
34  kind?: 'renewal'
35  at: number
36  sessionId: string
37  model: string
38  ttl: CacheTtl
39  before: number
40  after: number
41  usage: CompactionUsage | null
42  isReturned: boolean
43}
44
45declare module 'claude-code' {
46  interface PluginState {
47    'warm-compact': {
48      last: LastRequest | null
49      isTurnRunning: boolean
50      // Whether it compacts at all in this session: the footer chip and /warm-compact flip it
51      isEnabled: boolean
52      // Whether it renews the cache in compaction's place: the footer's second chip and
53      // /keep-warm flip it
54      isKeepWarm: boolean
55      kept: Kept | null
56      // When this session's latest compaction or renewal ran, until the session goes on
57      pendingRecord: number | null
58      // Null until it loaded in an interactive session
59      ttl: LearnedTtl | null
60      // Null while it has nothing in store: both off, a small conversation, a new prefix
61      upcoming: Upcoming | null
62      // The try last made or left alone, as `${request at}:${renewals}`
63      triedFor: string | null
64      // Whether it stands down on this Claude Code version, which its chip shows as off
65      standsDown: boolean
66    }
67  }
68}
69