SLOPSHOPPER

cache-warmer

Keep the main conversation's prompt cache warm by automatically forking its last request, tools denied and billed like any request, shortly before the cache…

panebandcommandmodeltimer
★ 18v0.14.0MITupdated 2026-10-23paulbkim-dev/claude-code-cache-warmer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-warmer
│ ┃ Cache warmer ✕ › 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 │ ┃ │ ┃ Cache Warmer ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ paulbkim.dev │ ┃ github.com/paulbkim-dev/claude-code-cach ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › Configuration › /cache-warmer │ ┃ › Analytics ⎿ cache-warmer: Cache warmer opened. │ ┃ › Debug mode · off │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Cache warmer
⢁ ⠄ ⠉⢧⠆⠠⡄ ▀▀▀▀▀▀▀▀▀▀▀▀ ▄▄▄▄▄▄ ▀▀▀▀▀▀▀▀▀▀▀▀ ▄▄▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ Cache Warmer paulbkim.dev github.com/paulbkim-dev/claude-code-cache-warmer › Configuration › Analytics › Debug mode · off
README

<img alt="Clawd, the Claude Code mascot, in the refreshing, warm, and expired states" src="assets/clawd-light.gif" width="274">

cache-warmer

Keeps the Claude Code prompt cache warm during a break, so your next prompt costs less.

Blog post · Website · X

English · 한국어 · 简体中文

What does it do?

Each prompt sends the full conversation to the API. The API keeps the start of the conversation in a prompt cache for 5 minutes or 1 hour. A prompt that reads the cache costs much less and starts faster. After the cache expires, the next prompt writes the full cache again at a higher price.

cache-warmer sends one small refresh shortly before the cache expires, so the cache stays warm. It works like the cache warmer in Pi.

flowchart LR
    subgraph with["With cache-warmer"]
        direction LR
        b1["Prompt"] --> b2["Break"] --> b3["Refresh<br/>keeps the cache"] --> b4["Next prompt<br/>reads the cache"]
    end
    subgraph without["Without cache-warmer"]
        direction LR
        a1["Prompt"] --> a2["Break"] --> a3["Cache expires"] --> a4["Next prompt<br/>writes the cache again"]
    end

Install

claude plugin marketplace add paulbkim-dev/claude-code-cache-warmer
claude plugin install cache-warmer@claude-code-cache-warmer

Restart Claude Code, then type /cache-warmer to open the pane. To stop all warming, run claude plugin disable cache-warmer.

What you see

During a refresh, a band above the prompt shows Clawd, the Claude Code mascot, beside a notice that the mod is resending the cached prompt. It shows the cache time in color (5m cyan, 1h magenta), the refresh interval, and the outcome: yellow while the refresh runs, green when the cache is warm, and red when it expired or failed. A failed refresh names the API error and its status, such as rate_limit 429. During a turn, the band goes 5 seconds after the refresh. In an idle session it stays until your next prompt, with Clawd still after 5 seconds. The pane's main page shows Clawd too.

  • The refresh never enters the conversation. The transcript keeps one notice row per refresh, starting with ☕, and no request sends it to the model.
  • The band has three styles, set on the Configuration page or in the /config row cache-warmer.band: default shows Clawd beside the notice, simplified shows the notice as one line, and off hides the band.
  • Each refresh request starts with [cache-warmer], so a request log or proxy can tell it from your prompts.
  • reduceMotion keeps Clawd still.
  • /cache-warmer preview plays the three states with no refresh.

The pane

/cache-warmer opens and closes a pane with this menu:

Configuration           this session, then defaults for new sessions
Analytics               costs and savings
Debug mode              on or off
  • The pane takes the keyboard when it opens over an empty prompt, with Configuration selected.
  • /cache-warmer on an open pane without the keyboard gives the keyboard back to it; on a pane with the keyboard, it closes the pane.
  • Tab and the arrow keys move between items. Enter opens a page or turns Debug mode on or off. Each page starts with a Back button, and Enter on a setting such as ● 5m ○ 1h moves it to the next option.
  • Escape closes the pane when the pane has focus, or when the prompt is idle and empty.
  • A line below the menu shows the next refresh, or why warming stopped.

Cache time

5 minutes1 hour
Refresh after4m30s54m
Cache write price1.25× input2× input
Warm time when idle, default limit27m30s5h30m
  • The default is 1 hour. Change it under Global on the Configuration page, in the /config row cache-warmer.ttl, or with /cache-warmer 5m or /cache-warmer 1h. The command also sets the current session.
  • The first main-conversation response locks the session's cache time. /clear or a new session unlocks it. While it is locked, the command refuses, and a new default applies to later sessions only.
  • The mod sets CLAUDE_CODE_PROMPT_CACHE_TTL for this Claude Code process, so it overrides promptCacheTtl and the shell. A change applies from the next request, which writes the cache once.
  • FORCE_PROMPT_CACHING_5M=1 keeps the cache at 5 minutes, and the Configuration page says so.
  • A refresh extends both cache times. In a live test on 2026-10-05, it kept a 1-hour cache warm past 60 minutes.
  • A refresh that reads less than half of the prefix counts as expired and stops warming.

When it refreshes

flowchart TD
    due["90% of the cache time is over"] --> rule{"Expected saving<br/>is $0.05 or more?"}
    rule -- No --> skip["No refresh"]
    rule -- Yes --> idle{"Is the session<br/>idle?"}
    idle -- "No, a turn runs" --> send["Refresh"]
    idle -- Yes --> left{"Idle refreshes left?"}
    left -- Yes --> send
    left -- No --> skip

A refresh is due at 90% of the cache time, and it must pass the rule from Pi:

chance of another request before expiry × extra cost to write the prefix again − refresh cost ≥ $0.05

The chance is 100% while a turn runs and 15% while the session is idle. So each model has a break-even prompt size, and a smaller prompt gets no refresh. The stop reason shows both sizes.

While the session is idle, each cache time gets at most its idle limit of refreshes after the last prompt. The limit is 0 to 20, 5 by default, set on the Configuration page or in cache-warmer.idle5m and cache-warmer.idle1h. When the last idle refresh is used, the band warns that warming stopped and shows when the cache expires, until your next prompt. While a turn runs, warming stops 60 minutes after the last prompt, or after two cache times if that is longer.

Warming also stops after compaction, /clear, a model change, a failed or expired refresh, or a timer that fired too late. The next request starts it again.

Debug mode

While debug mode is on, the newest refreshes show under the menu with their age, result, tokens, cost, and estimated saving. The mod also appends one JSON line per refresh and per stop to <config>/cache-warmer/debug/<session id>.jsonl, where <config> is CLAUDE_CONFIG_DIR or ~/.claude.

⚠️ The mod cannot see /rewind. After a rewind, refreshes keep the later prefix warm until the next request.

What it sends and stores

The mod sends each refresh automatically. Each refresh is a fork of the main conversation's last request, sent to the same model with this prompt:

[cache-warmer] Automated prompt cache refresh by the cache-warmer plugin, not a message from the user. Reply with the single word ok.

SendsOnly the refresh requests. No other network requests and no telemetry.
BillsEach refresh counts against your Claude plan or API key, like any request.
SetsCLAUDE_CODE_PROMPT_CACHE_TTL for the running Claude Code process
StoresAll-time totals in the plugin store, one notice row per refresh in the transcript, and the debug log while debug mode is on
StopsSet both idle limits to 0 to stop idle refreshes. Disable the plugin to stop all refreshes.

Credits

The refresh timing, the $0.05 rule, and the idea of an idle limit come from the cache warmer in Pi by Mario Zechner. cache-warmer ports them to a Claude Code mod and counts idle refreshes instead of stopping at 30 minutes. It copies no Pi code.

Support

Report problems at github.com/paulbkim-dev/claude-code-cache-warmer/issues. cache-warmer is released under the MIT License.

Source 6 files
hooks/register.tsx 1206 lines
1import { atom, read, update } from "claude-code";
2import type {
3  Args,
4  ConfigValue,
5  EngineInterface,
6  Frozen,
7  Hook,
8  MatchedEvent,
9  Next,
10  Register,
11  StreamNext,
12  Timer,
13  TurnStepChunk,
14  TurnStepResult,
15} from "claude-code";
16
17import type {
18  AllTime,
19  Anchor,
20  BandStyle,
21  IdleLimits,
22  Notice,
23  NoticeEnding,
24  Page,
25  Refresh,
26  Status,
27  Totals,
28  Ttl,
29  Warming,
30} from "../types";
31import { MASCOT_ROWS, TERMINAL_DEFAULT, cellsOf } from "./mascot";
32import { paneOf } from "./pages";
33import type { Mascot, PaneActions, PaneData } from "./pane";
34import {
35  MASCOT_KEY,
36  bandOf,
37  focusRowsOf,
38  layoutOf,
39  mascotBandOf,
40  rasterOf,
41} from "./pane";
42import type { ForkReply } from "./warmer";
43import {
44  DEFAULT_OUTPUT_TOKENS,
45  IDLE_LIMIT_DEFAULT,
46  TTL_MS,
47  ZERO_TOTALS,
48  addTotals,
49  costOf,
50  deadlineOf,
51  decide,
52  delayOf,
53  formatDuration,
54  formatTokens,
55  horizonOf,
56  isTtl,
57  limitOf,
58  missCostOf,
59  noticeOf,
60  outcomeOf,
61  premiumOf,
62  promptTokensOf,
63  usageOf,
64} from "./warmer";
65
66const PANE = "cache-warmer";
67const CONFIG_KEY = "cache-warmer.ttl";
68const IDLE_KEYS = {
69  "5m": "cache-warmer.idle5m",
70  "1h": "cache-warmer.idle1h",
71} as const;
72const BAND_KEY = "cache-warmer.band";
73const ALL_TIME_KEY = "allTime";
74const FORK_PROMPT =
75  "[cache-warmer] Automated prompt cache refresh by the cache-warmer plugin, not a message from the user. Reply with the single word ok.";
76const NOTICE_MS = 5000;
77const FRAME_MS = 33;
78// The preview's warm and cold notices, in milliseconds after it starts.
79const PREVIEW_WARMED_MS = 6000;
80const PREVIEW_COLD_MS = 11_500;
81// How long before the pane opened a stopped warmer's Clawd fell asleep, so he shows already dozing.
82const DOZED_MS = 2000;
83
84const ttl = atom({ plugin: "cache-warmer", key: "ttl" } as const, "1h");
85const defaultTtl = atom(
86  { plugin: "cache-warmer", key: "defaultTtl" } as const,
87  "1h",
88);
89const isSessionTtl = atom(
90  { plugin: "cache-warmer", key: "isSessionTtl" } as const,
91  false,
92);
93const idleLimits = atom(
94  { plugin: "cache-warmer", key: "idleLimits" } as const,
95  { "5m": IDLE_LIMIT_DEFAULT, "1h": IDLE_LIMIT_DEFAULT },
96);
97const isForced = atom(
98  { plugin: "cache-warmer", key: "isForced" } as const,
99  false,
100);
101const isLocked = atom(
102  { plugin: "cache-warmer", key: "isLocked" } as const,
103  false,
104);
105const isDebug = atom(
106  { plugin: "cache-warmer", key: "isDebug" } as const,
107  false,
108);
109const bandStyle = atom(
110  { plugin: "cache-warmer", key: "bandStyle" } as const,
111  "default",
112);
113const page = atom({ plugin: "cache-warmer", key: "page" } as const, "main");
114const refreshes = atom(
115  { plugin: "cache-warmer", key: "refreshes" } as const,
116  [],
117);
118const status = atom({ plugin: "cache-warmer", key: "status" } as const, {
119  state: "waiting",
120});
121const notice = atom({ plugin: "cache-warmer", key: "notice" } as const, null);
122const totals = atom(
123  { plugin: "cache-warmer", key: "totals" } as const,
124  ZERO_TOTALS,
125);
126const allTime = atom({ plugin: "cache-warmer", key: "allTime" } as const, {
127  ...ZERO_TOTALS,
128  since: 0,
129});
130const now = atom({ plugin: "cache-warmer", key: "now" } as const, 0);
131const warming = atom({ plugin: "cache-warmer", key: "warming" } as const, {
132  anchor: null,
133  isRunning: false,
134  outputTokens: DEFAULT_OUTPUT_TOKENS,
135});
136
137let timer: Timer | undefined;
138let animation: Timer | undefined;
139let ticker: Timer | undefined;
140let hideNotice: Timer | undefined;
141// Notices shown and prompts started this process: a timer ends only the notice
142// it was set for, and a held notice goes with the next prompt.
143let notices = 0;
144let prompts = 0;
145let previewSteps: Timer[] = [];
146let isStill = false;
147// Claude Code's theme, "auto" resolved to "light" or "dark".
148let theme = "dark";
149// The pane's and the band's requestIds while they draw Clawd, each with the
150// color behind him there; blits repaint him in each.
151const sites = new Map<string, number>();
152let paneSince = 0;
153// The pane's Buttons by row as last drawn, and the one holding its focus ring.
154let focusRows: string[][] = [];
155let focused: string | undefined;
156let isPainting = false;
157let syncs = 0;
158// The anchor a refresh has claimed, one object per refresh; schedule() leaves
159// the anchor until chain() records the refresh.
160let forking: { at: number } | undefined;
161// Debug log appends and all-time store updates each run one at a time, since
162// each reads and rewrites the whole value; a failed one is logged and the next runs.
163let debugWrites = Promise.resolve();
164let allTimeWrites = Promise.resolve();
165
166type Scene = Pick<Notice, "mood" | "startedAt" | "since">;
167
168type DebugLine =
169  | (Omit<Refresh, "at"> & { at: string; phase: "run" | "idle"; ttl: Ttl })
170  | { at: string; reason: string };
171
172const effectiveTtl = async ($: EngineInterface): Promise<Ttl> =>
173  (await read($, isForced)) ? "5m" : read($, ttl);
174
175const debugPathOf = async ($: EngineInterface) => {
176  const configDir = await $.env.get("CLAUDE_CONFIG_DIR");
177  const home = await $.env.get("HOME");
178  if (configDir === undefined && home === undefined)
179    throw new Error("neither CLAUDE_CONFIG_DIR nor HOME is set");
180  return `${configDir ?? `${home}/.claude`}/cache-warmer/debug/${await $.session.id()}.jsonl`;
181};
182
183const appendDebug = async ($: EngineInterface, line: DebugLine) => {
184  try {
185    const path = await debugPathOf($);
186    const before = (await $.fs.exists(path)) ? await $.fs.read(path) : "";
187    await $.fs.write(path, `${before}${JSON.stringify(line)}\n`);
188  } catch (error) {
189    $.ui.log(
190      `Cache warmer could not write its debug log: ${error instanceof Error ? error.message : String(error)}`,
191    );
192  }
193};
194
195// While debug mode is on, one JSON line per refresh and per stop; a failed write is logged and warming goes on.
196const logDebug = async ($: EngineInterface, line: DebugLine) => {
197  if (!(await read($, isDebug))) return;
198  debugWrites = debugWrites.then(() => appendDebug($, line));
199  await debugWrites;
200};
201
202// Totals stored before 0.14 lack the bridged and premium fields, which count from zero.
203const storedAllTime = async ($: EngineInterface) => {
204  // SAFETY: only addToAllTime and startSession write ALL_TIME_KEY, each an AllTime that the store's JSON round trip keeps; the spread below fills the fields that totals saved before 0.14 lack.
205  const stored = (await $.store.get(ALL_TIME_KEY)) as AllTime | undefined;
206  return stored && { ...ZERO_TOTALS, ...stored };
207};
208
209const addToAllTime = async ($: EngineInterface, delta: Partial<Totals>) => {
210  const next = addTotals(
211    (await storedAllTime($)) ?? { ...ZERO_TOTALS, since: await $.clock.now() },
212    delta,
213  );
214  await $.store.set(ALL_TIME_KEY, next);
215  await update($, allTime, () => next);
216};
217
218// This session's totals and the all-time totals in $.store take the same delta.
219const addToTotals = async ($: EngineInterface, delta: Partial<Totals>) => {
220  await update($, totals, (current) => addTotals(current, delta));
221  allTimeWrites = allTimeWrites.then(async () => {
222    try {
223      await addToAllTime($, delta);
224    } catch (error) {
225      $.ui.log(
226        `Cache warmer could not save its all-time totals: ${error instanceof Error ? error.message : String(error)}`,
227      );
228    }
229  });
230  await allTimeWrites;
231};
232
233const reportStop = async ($: EngineInterface, reason: string) => {
234  await update($, status, (): Status => ({ state: "stopped", reason }));
235  await logDebug($, {
236    at: new Date(await $.clock.now()).toISOString(),
237    reason,
238  });
239};
240
241// Compaction, /clear, a session's end and a model switch forget the chain:
242// only the next prompt's turn.step starts warming again, and the chain's fee
243// is wasted now, since no prompt will judge it.
244const forget = async ($: EngineInterface, reason: string) => {
245  timer?.cancel();
246  timer = undefined;
247  const { anchor } = await read($, warming);
248  if (anchor && anchor.feeUsd > 0)
249    await addToTotals($, { wastedUsd: anchor.feeUsd });
250  await update($, warming, (current): Warming => ({
251    ...current,
252    anchor: null,
253  }));
254  await reportStop($, reason);
255};
256
257// Stops the chain anchored at `at`, adding `feeUsd` to it, until the next
258// prompt; a prompt that replaced it meanwhile keeps its own warming. A timer
259// left for it finds it stopped. Answers whether it stopped that chain.
260const stopChain = async (
261  $: EngineInterface,
262  at: number,
263  reason: string,
264  feeUsd = 0,
265) => {
266  let isStopped = false;
267  await update($, warming, (state): Warming => {
268    const { anchor } = state;
269    isStopped = anchor?.at === at && !anchor.isStopped;
270    if (!anchor || !isStopped) return state;
271    return {
272      ...state,
273      anchor: { ...anchor, feeUsd: anchor.feeUsd + feeUsd, isStopped: true },
274    };
275  });
276  if (isStopped) await reportStop($, reason);
277  return isStopped;
278};
279
280// A running turn stops at the run horizon; an idle session after its lifetime's idle limit.
281// The anchor is read last, so the timer is set from the anchor as it stands:
282// a refresh that settled while an earlier read waited cannot leave a stale one.
283const schedule = async ($: EngineInterface) => {
284  const prompt = prompts;
285  const limits = await read($, idleLimits);
286  const at = await $.clock.now();
287  const { anchor: current, isRunning, outputTokens } = await read($, warming);
288  if (!current || current.isStopped || current.at === forking?.at) return;
289  const phase = isRunning ? "run" : "idle";
290  const nextAt = current.lastAt + delayOf(current.ttl);
291  const horizon = horizonOf(current.ttl);
292  if (phase === "run" && nextAt > current.at + horizon)
293    return stopChain(
294      $,
295      current.at,
296      `${formatDuration(horizon)} run limit reached`,
297    );
298  const limit = limits[current.ttl];
299  if (phase === "idle" && current.idleRefreshes >= limit) {
300    const isStopped = await stopChain(
301      $,
302      current.at,
303      `${limit} idle refreshes reached`,
304    );
305    // A limit of 0 turned idle warming off on purpose; it needs no warning.
306    if (isStopped && limit > 0) await warnIdleLimit($, current, limit, prompt);
307    return isStopped;
308  }
309  const decision = decide(
310    current.model,
311    current.promptTokens,
312    current.ttl,
313    phase,
314    outputTokens,
315  );
316  if (!decision)
317    return stopChain($, current.at, `no price for ${current.model}`);
318  if (decision.reason) return stopChain($, current.at, decision.reason);
319  timer?.cancel();
320  timer = $.clock.after(Math.max(0, nextAt - at), () => void refresh($));
321  await update($, status, (): Status => ({
322    state: "scheduled",
323    nextAt,
324    phase,
325    expectedUsd: decision.expectedUsd,
326  }));
327};
328
329const isPaneOpen = async ($: EngineInterface) =>
330  (await $.ui.panes()).some((pane) => pane.id === PANE);
331
332// Under "auto", a light background in COLORFGBG means light. Claude Code also
333// asks the terminal under "auto"; plugins cannot read that answer.
334const themeOf = async ($: EngineInterface): Promise<string> => {
335  const chosen = String(
336    (await $.config.list()).find((row) => row.key === "theme")?.value ?? "auto",
337  );
338  if (chosen !== "auto") return chosen;
339  const background = Number((await $.env.get("COLORFGBG"))?.split(";").at(-1));
340  return background === 7 || (background >= 9 && background <= 15)
341    ? "light"
342    : "dark";
343};
344
345// A docked pane is drawn on Claude Code's composerSidebarBackground (as of
346// 2.1.289); its ANSI themes name a terminal color, which a Raster cannot.
347const dockBackgroundOf = (name: string) => {
348  if (name === "dark" || name === "dark-daltonized") return 0x262626;
349  if (name === "light") return 0xf5f5f5;
350  if (name === "light-daltonized") return 0xebebeb;
351  return TERMINAL_DEFAULT;
352};
353
354// Reduced motion draws one frame: Clawd standing, the steam mid-rise.
355const mascotOf = (scene: Scene, at: number, background: number) => {
356  const palette = theme.startsWith("light") ? "light" : "dark";
357  return isStill
358    ? cellsOf(1, scene.mood, 3, palette, background)
359    : cellsOf(
360        (at - scene.startedAt) / 1000,
361        scene.mood,
362        (at - scene.since) / 1000,
363        palette,
364        background,
365      );
366};
367
368// The pane plays the notice while one moves, and otherwise the
369// warmer's state: Clawd sips while it warms and dozes once it stopped.
370const sceneOf = async ($: EngineInterface): Promise<Scene> => {
371  const shown = await liveNoticeOf($);
372  if (shown && shown.heldAt === null) return shown;
373  const isStopped = (await read($, status)).state === "stopped";
374  return {
375    mood: isStopped ? "cold" : "warming",
376    startedAt: paneSince,
377    since: paneSince - DOZED_MS,
378  };
379};
380
381// A refused blit means a site no longer shows Clawd: the pane closed or left
382// the main page, or the band's notice went. Painting there resumes when it
383// draws Clawd again.
384const paint = async ($: EngineInterface) => {
385  if (isPainting || sites.size === 0) return;
386  isPainting = true;
387  try {
388    const at = await $.clock.now();
389    for (const [requestId, background] of sites) {
390      const answer = await $.ui.blit({
391        requestId,
392        key: MASCOT_KEY,
393        cells: mascotOf(await sceneOf($), at, background),
394      });
395      if (answer.deny !== undefined) sites.delete(requestId);
396    }
397  } finally {
398    isPainting = false;
399  }
400};
401
402// Frames run while the pane is open or the band shows Clawd moving with a notice,
403// and the pane's clock ticks only while it is open. A theme change shows from
404// the next start. The latest call decides: one that a later call overtook while
405// it waited leaves the timers alone.
406const syncAnimation = async ($: EngineInterface) => {
407  const call = ++syncs;
408  const shown = await liveNoticeOf($);
409  const isOpen = await isPaneOpen($);
410  const isShown =
411    isOpen ||
412    (shown !== null &&
413      shown.heldAt === null &&
414      (await read($, bandStyle)) === "default");
415  const resolved = isShown && !animation ? await themeOf($) : theme;
416  if (call !== syncs) return;
417  theme = resolved;
418  if (!isOpen) {
419    ticker?.cancel();
420    ticker = undefined;
421  } else ticker ??= $.clock.every(1000, () => void tick($));
422  if (!isShown) {
423    animation?.cancel();
424    animation = undefined;
425  } else if (!animation && !isStill)
426    animation = $.clock.every(FRAME_MS, () => void paint($));
427};
428
429// A fading notice goes; a held one keeps Clawd on the frame he reached and
430// stops the frames. A notice shown since the timer was set is left alone.
431const endNotice = async (
432  $: EngineInterface,
433  shownAs: number,
434  ending: NoticeEnding,
435) => {
436  const at = await $.clock.now();
437  await update($, notice, (current) => {
438    if (!current || shownAs !== notices) return current;
439    return ending === "fades" ? null : { ...current, heldAt: at };
440  });
441  await syncAnimation($);
442};
443
444const showNotice = async (
445  $: EngineInterface,
446  shown: Pick<Notice, "ttl" | "head" | "detail" | "mood">,
447  ending: NoticeEnding,
448  prompt = prompts,
449) => {
450  hideNotice?.cancel();
451  hideNotice = undefined;
452  const shownAs = ++notices;
453  const at = await $.clock.now();
454  await update($, notice, (current): Notice => ({
455    ...shown,
456    ending,
457    startedAt: current?.startedAt ?? at,
458    since: current?.mood === shown.mood ? current.since : at,
459    heldAt: null,
460    prompt,
461  }));
462  await syncAnimation($);
463  if (ending !== "stays" && shownAs === notices)
464    hideNotice = $.clock.after(
465      NOTICE_MS,
466      () => void endNotice($, shownAs, ending),
467    );
468};
469
470// The notice on show: a held one from before the latest prompt is gone, even
471// when it was written after that prompt cleared the notice.
472const liveNoticeOf = async ($: EngineInterface) => {
473  const shown = await read($, notice);
474  return shown && (shown.ending !== "holds" || shown.prompt === prompts)
475    ? shown
476    : null;
477};
478
479// An outcome reached while a turn runs fades; one in an idle session holds until the next prompt.
480const outcomeEndingOf = async ($: EngineInterface): Promise<NoticeEnding> =>
481  (await read($, warming)).isRunning ? "fades" : "holds";
482
483// A notice row: the transcript file keeps it, and no request carries it.
484const appendNotice = async ($: EngineInterface, text: string) => {
485  try {
486    await $.session.append({
487      message: { type: "system", content: [{ type: "text", text }] },
488    });
489  } catch (error) {
490    $.ui.log(
491      `Cache warmer could not record the refresh: ${error instanceof Error ? error.message : String(error)}`,
492    );
493  }
494};
495
496// The last idle refresh warmed the cache once more; after it no refresh comes,
497// and the cache expires a lifetime after it.
498const warnIdleLimit = async (
499  $: EngineInterface,
500  current: Anchor,
501  limit: number,
502  prompt: number,
503) => {
504  // A prompt since the stop restarted warming, so nothing has stopped.
505  if (prompt !== prompts) return;
506  const expiresAt = new Date(current.lastAt + TTL_MS[current.ttl])
507    .toTimeString()
508    .slice(0, 5);
509  const head = "Warming stopped";
510  const detail = `all ${limit} idle refreshes used · cache expires at ${expiresAt}`;
511  await showNotice(
512    $,
513    { ttl: current.ttl, head, detail, mood: "cold" },
514    "holds",
515    prompt,
516  );
517  await appendNotice($, `☕ ${current.ttl} · ${head} · ${detail}`);
518};
519
520const record = async (
521  $: EngineInterface,
522  entry: Refresh,
523  phase: "run" | "idle",
524  entryTtl: Ttl,
525) => {
526  await update($, refreshes, (list) => [...list, entry].slice(-200));
527  await addToTotals($, { refreshes: 1, costUsd: entry.costUsd ?? 0 });
528  await logDebug($, {
529    ...entry,
530    at: new Date(entry.at).toISOString(),
531    phase,
532    ttl: entryTtl,
533  });
534};
535
536// Moves a warm refresh's chain on, when the chain is still current; answers whether it was.
537const extend = async (
538  $: EngineInterface,
539  current: Anchor,
540  entry: Refresh,
541  phase: "run" | "idle",
542) => {
543  let isChained = false;
544  await update($, warming, (state): Warming => {
545    const { anchor } = state;
546    isChained = anchor?.at === current.at && !anchor.isStopped;
547    if (!anchor || !isChained) return state;
548    return {
549      ...state,
550      outputTokens: entry.usage?.output || DEFAULT_OUTPUT_TOKENS,
551      anchor: {
552        ...anchor,
553        lastAt: entry.at,
554        refreshes: anchor.refreshes + 1,
555        idleRefreshes: anchor.idleRefreshes + (phase === "idle" ? 1 : 0),
556        feeUsd: anchor.feeUsd + (entry.costUsd ?? 0),
557      },
558    };
559  });
560  return isChained;
561};
562
563// The chain carries each refresh's fee. A refresh that a prompt overtook
564// during its fork kept nothing that prompt read, so its fee is wasted; so is
565// one whose chain was forgotten. Each check runs inside the write, so a stop
566// or a prompt that lands meanwhile wins.
567const chain = async (
568  $: EngineInterface,
569  current: Anchor,
570  entry: Refresh,
571  phase: "run" | "idle",
572) => {
573  const costUsd = entry.costUsd ?? 0;
574  const isWarmed = entry.result === "warmed";
575  const reason =
576    entry.result === "expired" ? "cache had expired" : "refresh failed";
577  const isChained = isWarmed
578    ? await extend($, current, entry, phase)
579    : await stopChain($, current.at, reason, costUsd);
580  // The anchor holds this refresh now, so scheduling it cannot fork it twice.
581  if (forking?.at === current.at) forking = undefined;
582  if (!isChained) {
583    if (costUsd > 0) await addToTotals($, { wastedUsd: costUsd });
584    return;
585  }
586  if (isWarmed) await schedule($);
587};
588
589const settle = async (
590  $: EngineInterface,
591  current: Anchor,
592  at: number,
593  phase: "run" | "idle",
594  missUsd: number,
595  reply: ForkReply,
596  prompt: number,
597) => {
598  const usage = usageOf(reply.usage);
599  // The fork's own write is its short tail; pricing it at the entry's lifetime overstates it at most.
600  const costUsd = costOf(current.model, usage, current.ttl);
601  const outcome = outcomeOf(reply, usage, current.promptTokens);
602  const savesUsd =
603    outcome.result === "warmed" && costUsd !== null ? missUsd - costUsd : null;
604  const entry: Refresh = {
605    at,
606    model: current.model,
607    usage,
608    costUsd,
609    savesUsd,
610    ...outcome,
611  };
612  await record($, entry, phase, current.ttl);
613  const { head, detail } = noticeOf(entry);
614  await appendNotice($, `☕ ${current.ttl} · ${head} · ${detail}`);
615  await showNotice(
616    $,
617    {
618      ttl: current.ttl,
619      head,
620      detail,
621      mood: entry.result === "warmed" ? "warmed" : "cold",
622    },
623    await outcomeEndingOf($),
624    prompt,
625  );
626  // A prompt that arrived during the fork set a new anchor and its own timer;
627  // the last idle refresh's warning replaces its notice.
628  await chain($, current, entry, phase);
629};
630
631// The fork rejects when the engine refuses to send it, as for a blocked model; no request went out.
632const sendFork = async ($: EngineInterface) => {
633  try {
634    return await $.model.fork({ prompt: FORK_PROMPT });
635  } catch (error) {
636    return error instanceof Error ? error : new Error(String(error));
637  }
638};
639
640const forkFor = async (
641  $: EngineInterface,
642  current: Anchor,
643  phase: "run" | "idle",
644  outputTokens: number,
645) => {
646  const prompt = prompts;
647  const at = await $.clock.now();
648  if (at > deadlineOf(current.lastAt, current.ttl))
649    return stopChain($, current.at, "refresh deadline missed");
650  const decision = decide(
651    current.model,
652    current.promptTokens,
653    current.ttl,
654    phase,
655    outputTokens,
656  );
657  if (!decision)
658    return stopChain($, current.at, `no price for ${current.model}`);
659  if (decision.reason) return stopChain($, current.at, decision.reason);
660  await update($, status, (): Status => ({ state: "refreshing" }));
661  stopPreview();
662  await showNotice(
663    $,
664    {
665      ttl: current.ttl,
666      head: "Refreshing cache",
667      detail: `resending the cached ${formatTokens(current.promptTokens)}-token prompt…`,
668      mood: "warming",
669    },
670    "stays",
671  );
672  const reply = await sendFork($);
673  if (reply instanceof Error) {
674    await showNotice(
675      $,
676      {
677        ttl: current.ttl,
678        head: "Cache refresh refused",
679        detail: reply.message,
680        mood: "cold",
681      },
682      await outcomeEndingOf($),
683      prompt,
684    );
685    return stopChain($, current.at, `refresh refused: ${reply.message}`);
686  }
687  if (!reply.isAnswered && reply.reason === "nothing-to-fork") {
688    await showNotice(
689      $,
690      { ttl: current.ttl, head: "Nothing to warm", detail: "", mood: "cold" },
691      await outcomeEndingOf($),
692      prompt,
693    );
694    return stopChain($, current.at, "nothing to refresh");
695  }
696  await settle($, current, at, phase, decision.missUsd, reply, prompt);
697};
698
699// The refresh claims its anchor until chain() records it there, so a
700// schedule() meanwhile, from a turn that ended, cannot fork it again.
701const refresh = async ($: EngineInterface) => {
702  timer = undefined;
703  const { anchor: current, isRunning, outputTokens } = await read($, warming);
704  if (!current || current.isStopped || current.at === forking?.at) return;
705  const claim = { at: current.at };
706  forking = claim;
707  try {
708    await forkFor($, current, isRunning ? "run" : "idle", outputTokens);
709  } finally {
710    if (forking === claim) forking = undefined;
711  }
712};
713
714const setTtl = async ($: EngineInterface, value: Ttl) => {
715  await $.env.set("CLAUDE_CODE_PROMPT_CACHE_TTL", value);
716  await update($, ttl, () => value);
717};
718
719const describeTtl = async ($: EngineInterface) => {
720  const chosen = await read($, ttl);
721  if (await read($, isForced))
722    return `Cache lifetime ${chosen}, overridden to 5m by FORCE_PROMPT_CACHING_5M.`;
723  return `Cache lifetime ${chosen}; refreshes every ${formatDuration(delayOf(chosen))}. The next request rewrites the cache once.`;
724};
725
726const lockedReason = async ($: EngineInterface) =>
727  (await read($, isLocked))
728    ? `the cache is written at ${await read($, ttl)} for this session; /clear or a new session unlocks it`
729    : undefined;
730
731// A saved default reaches this session only while no response has locked its lifetime.
732const applyDefault = async ($: EngineInterface, value: Ttl) => {
733  await update($, defaultTtl, () => value);
734  if (await read($, isLocked)) return;
735  await update($, isSessionTtl, () => false);
736  await setTtl($, value);
737};
738
739const logDenied = ($: EngineInterface, what: string, reason: string) =>
740  $.ui.log(`Cache warmer could not save the ${what}: ${reason}`);
741
742// The command sets this session and the saved default, and refuses once locked.
743// $.config.set skips this plugin's own config.set hook, so each caller applies the value itself.
744const chooseTtl = async ($: EngineInterface, value: Ttl) => {
745  const locked = await lockedReason($);
746  if (locked) return `Cache lifetime unchanged: ${locked}`;
747  const answer = await $.config.set({ key: CONFIG_KEY, value });
748  if (answer.deny !== undefined)
749    return `Cache lifetime unchanged: ${answer.deny}`;
750  await applyDefault($, value);
751  return describeTtl($);
752};
753
754// The Global page saves the default even while this session is locked.
755const chooseDefault = async ($: EngineInterface, value: Ttl) => {
756  const answer = await $.config.set({ key: CONFIG_KEY, value });
757  if (answer.deny !== undefined)
758    return logDenied($, "default lifetime", answer.deny);
759  await applyDefault($, value);
760};
761
762// The Session page changes this session alone, not the saved default.
763const chooseSessionTtl = async ($: EngineInterface, value: Ttl) => {
764  if (await read($, isLocked)) return;
765  await update($, isSessionTtl, () => true);
766  await setTtl($, value);
767};
768
769// A new limit applies to the warming under way; a refresh in flight schedules itself when it settles.
770const setLimit = async ($: EngineInterface, limitTtl: Ttl, count: number) => {
771  const value = limitOf(count);
772  const answer = await $.config.set({ key: IDLE_KEYS[limitTtl], value });
773  if (answer.deny !== undefined)
774    return logDenied($, `${limitTtl} idle limit`, answer.deny);
775  await update($, idleLimits, (limits) => ({ ...limits, [limitTtl]: value }));
776  if ((await read($, status)).state === "scheduled") await schedule($);
777};
778
779const bandStyleOf = (value: ConfigValue | undefined): BandStyle =>
780  value === "simplified" || value === "off" ? value : "default";
781
782const applyBand = async ($: EngineInterface, value: BandStyle) => {
783  await update($, bandStyle, () => value);
784  await syncAnimation($);
785};
786
787const setBand = async ($: EngineInterface, value: BandStyle) => {
788  const answer = await $.config.set({ key: BAND_KEY, value });
789  if (answer.deny !== undefined) return logDenied($, "band style", answer.deny);
790  await applyBand($, bandStyleOf(answer.value));
791};
792
793const tick = async ($: EngineInterface) => {
794  const at = await $.clock.now();
795  await update($, now, () => at);
796};
797
798// A reload from 0.5 kept state written without the 0.6 fields.
799const migrate = async ($: EngineInterface) => {
800  await update($, totals, (current) => ({ ...ZERO_TOTALS, ...current }));
801  await update($, warming, (current): Warming => ({
802    ...current,
803    anchor: current.anchor && {
804      ...current.anchor,
805      idleRefreshes: current.anchor.idleRefreshes ?? 0,
806      feeUsd: current.anchor.feeUsd ?? 0,
807    },
808  }));
809  // 0.6.3's Debug page is now the menu's toggle.
810  await update($, page, (current) =>
811    ["config", "analytics"].includes(current) ? current : "main",
812  );
813};
814
815const startSession = async (
816  $: EngineInterface,
817  option: Ttl,
818  limits: IdleLimits,
819  band: BandStyle,
820) => {
821  await $.command.register({
822    name: "cache-warmer",
823    description:
824      "Toggle the cache warmer pane, set the prompt cache lifetime, or preview the band",
825    argumentHint: "[5m|1h|preview]",
826  });
827  const forced = await $.env.get("FORCE_PROMPT_CACHING_5M");
828  await update($, isForced, () => forced === "1" || forced === "true");
829  await update($, defaultTtl, () => option);
830  await update($, idleLimits, () => limits);
831  await update($, bandStyle, () => band);
832  // A reload after the first response keeps the lifetime the cache was written
833  // with, and one after a Session page choice keeps that choice.
834  const isKept = (await read($, isLocked)) || (await read($, isSessionTtl));
835  await setTtl($, isKept ? await read($, ttl) : option);
836  await migrate($);
837  const stored = await storedAllTime($);
838  const total = stored ?? { ...ZERO_TOTALS, since: await $.clock.now() };
839  if (!stored) await $.store.set(ALL_TIME_KEY, total);
840  await update($, allTime, () => total);
841  isStill = (await $.config.list()).some(
842    (row) => row.key === "reduceMotion" && row.value === true,
843  );
844  // A reload cancels the old timers: drop a notice left up, re-arm warming
845  // and animate a pane left open.
846  await update($, notice, () => null);
847  await schedule($);
848  paneSince = await $.clock.now();
849  await syncAnimation($);
850};
851
852const stopPreview = () => {
853  for (const step of previewSteps) step.cancel();
854  previewSteps = [];
855};
856
857// Plays the band a refresh shows, without a fork: warming, warmed, then cold.
858const preview = async ($: EngineInterface) => {
859  stopPreview();
860  const shownTtl = await effectiveTtl($);
861  const step = (head: string, mood: Notice["mood"], isDone: boolean) =>
862    showNotice(
863      $,
864      { ttl: shownTtl, head, detail: "preview", mood },
865      isDone ? "fades" : "stays",
866    );
867  await step("Refreshing cache", "warming", false);
868  previewSteps = [
869    $.clock.after(
870      PREVIEW_WARMED_MS,
871      () => void step("Cache warmed", "warmed", false),
872    ),
873    $.clock.after(
874      PREVIEW_COLD_MS,
875      () => void step("Cache had expired", "cold", true),
876    ),
877  ];
878};
879
880const runCommand = async ($: EngineInterface, args: string) => {
881  const arg = args.trim();
882  if (isTtl(arg)) return { text: await chooseTtl($, arg) };
883  if (arg === "preview") {
884    if ((await read($, status)).state === "refreshing")
885      return { text: "A refresh is running; the band shows it now." };
886    await preview($);
887    return { text: "Cache warmer band preview started." };
888  }
889  if (arg) return { text: "Usage: /cache-warmer [5m|1h|preview]" };
890  const shown = (await $.ui.panes()).find((pane) => pane.id === PANE);
891  if (shown?.isFocused) {
892    await $.ui.close({ id: PANE });
893    await syncAnimation($);
894    return { text: "Cache warmer closed." };
895  }
896  // An open pane without the keyboard takes it back on the main page instead of closing.
897  if (!shown) paneSince = await $.clock.now();
898  await update($, page, (): Page => "main");
899  await $.ui.open({
900    id: PANE,
901    title: "Cache warmer",
902    rows: 14,
903    focus: true,
904    closeOnEscape: true,
905  });
906  await syncAnimation($);
907  return { text: shown ? "Cache warmer focused." : "Cache warmer opened." };
908};
909
910// A prompt is kept when it read an entry that would have expired without the
911// refreshes since the last prompt; it avoided rewriting the tokens it read.
912// Otherwise the previous chain's fee is wasted.
913const judgeChain = async (
914  $: EngineInterface,
915  previous: Anchor | null,
916  at: number,
917  cacheRead: number,
918) => {
919  if (!previous) return;
920  const isRead = cacheRead >= previous.promptTokens / 2;
921  const isKept =
922    previous.refreshes > 0 && at - previous.at > TTL_MS[previous.ttl] && isRead;
923  // Without this mod a 5m cache would have expired too, so a kept prompt avoided a 5m rewrite.
924  const keptUsd = isKept ? missCostOf(previous.model, cacheRead, "5m") : null;
925  if (keptUsd !== null) await addToTotals($, { kept: 1, keptUsd });
926  else if (previous.feeUsd > 0)
927    await addToTotals($, { wastedUsd: previous.feeUsd });
928  const isBridged =
929    !isKept &&
930    isRead &&
931    previous.ttl === "1h" &&
932    at - previous.at > TTL_MS["5m"];
933  const bridgedUsd = isBridged
934    ? missCostOf(previous.model, cacheRead, "5m")
935    : null;
936  if (bridgedUsd !== null) await addToTotals($, { bridgedUsd });
937};
938
939const stepTurn = async function* (
940  $: EngineInterface,
941  e: Frozen<Args<"turn.step">>,
942  next: StreamNext<"turn.step">,
943): AsyncGenerator<TurnStepChunk, TurnStepResult> {
944  if (e.agentId !== undefined) return yield* next(e);
945  const at = await $.clock.now();
946  const before = (await read($, warming)).anchor;
947  // The lifetime this request is sent with; a choice made while it runs applies to the next one.
948  const entryTtl = await effectiveTtl($);
949  const result = yield* next(e);
950  if (!result.usage) return result;
951  await update($, isLocked, () => true);
952  const usage = usageOf(result.usage);
953  await judgeChain($, before, at, usage.cacheRead);
954  const premiumUsd =
955    entryTtl === "1h" ? premiumOf(result.usage.model, usage) : null;
956  if (premiumUsd) await addToTotals($, { premiumUsd });
957  // Refreshes that settled while this request ran came after it, so they start the new chain.
958  const after = (await read($, warming)).anchor;
959  const isSameChain = before !== null && after?.at === before.at;
960  const model = result.usage.model;
961  await update($, warming, (current): Warming => ({
962    ...current,
963    anchor: {
964      at,
965      lastAt: at,
966      model,
967      promptTokens: promptTokensOf(usage),
968      ttl: entryTtl,
969      refreshes: isSameChain ? after.refreshes - before.refreshes : 0,
970      idleRefreshes: 0,
971      feeUsd: isSameChain ? after.feeUsd - before.feeUsd : 0,
972      isStopped: false,
973    },
974  }));
975  // A request that read and wrote no cache left nothing to keep warm: prompt caching is off, or the prompt is under the model's minimum.
976  if (usage.cacheRead + usage.cacheWrite === 0)
977    await stopChain($, at, "the last request cached nothing");
978  else await schedule($);
979  return result;
980};
981
982// The next prompt takes down an outcome held from before it; a refresh under
983// way, or a notice shown since, keeps its place. A held notice's timer finds it gone.
984const onTurnStart: Hook<"turn.start"> = async ($, e, next) => {
985  if (e.agentId !== undefined) return next(e);
986  prompts += 1;
987  const prompt = prompts;
988  await update($, warming, (current): Warming => ({
989    ...current,
990    isRunning: true,
991  }));
992  await update($, notice, (current) =>
993    current?.ending === "holds" && current.prompt < prompt ? null : current,
994  );
995  await syncAnimation($);
996  return next(e);
997};
998
999const onTurnComplete: Hook<"turn.complete"> = async ($, e, next) => {
1000  if (e.agentId === undefined) {
1001    await update($, warming, (current): Warming => ({
1002      ...current,
1003      isRunning: false,
1004    }));
1005    await schedule($);
1006  }
1007  return next(e);
1008};
1009
1010// /config saves the default whatever the lock; applyDefault decides whether this session follows.
1011const onTtlConfigSet: Hook<"config.set"> = async ($, e, next) => {
1012  const answer = await next(e);
1013  const value = String(answer.value);
1014  if (answer.deny === undefined && isTtl(value)) await applyDefault($, value);
1015  return answer;
1016};
1017
1018// /config clamps an idle limit to 0..20 before saving it.
1019const setIdleFromConfig = async (
1020  $: EngineInterface,
1021  e: Frozen<Args<"config.set">>,
1022  next: Next<"config.set">,
1023  limitTtl: Ttl,
1024) => {
1025  const answer = await next({ ...e, value: limitOf(e.value) });
1026  if (answer.deny === undefined) {
1027    const value = limitOf(answer.value);
1028    await update($, idleLimits, (limits) => ({ ...limits, [limitTtl]: value }));
1029    if ((await read($, status)).state === "scheduled") await schedule($);
1030  }
1031  return answer;
1032};
1033
1034const renderBand = async (
1035  $: EngineInterface,
1036  e: Frozen<MatchedEvent<"ui.render", { component: "AbovePrompt" }>>,
1037) => {
1038  const shown = await liveNoticeOf($);
1039  const style = await read($, bandStyle);
1040  sites.delete(e.requestId);
1041  if (!shown || e.props.hasSurvey || style === "off") return undefined;
1042  if (
1043    style === "simplified" ||
1044    e.surface !== "terminal" ||
1045    e.props.maxRows < MASCOT_ROWS
1046  )
1047    return bandOf($.ui.resolve(e), shown);
1048  // A held notice draws the frame Clawd stopped on, and takes no blits.
1049  if (shown.heldAt === null) sites.set(e.requestId, TERMINAL_DEFAULT);
1050  const elements = $.ui.resolve(e);
1051  const at = shown.heldAt ?? (await $.clock.now());
1052  const cells = mascotOf(shown, at, TERMINAL_DEFAULT);
1053  return mascotBandOf(elements, shown, rasterOf(elements, cells));
1054};
1055
1056const renderPane = async (
1057  $: EngineInterface,
1058  e: Frozen<
1059    MatchedEvent<"ui.render", { component: "Pane"; requestId: typeof PANE }>
1060  >,
1061) => {
1062  const shown = await read($, page);
1063  const debugOn = await read($, isDebug);
1064  const data: PaneData = {
1065    page: shown,
1066    chosen: await read($, ttl),
1067    saved: await read($, defaultTtl),
1068    limits: await read($, idleLimits),
1069    isForced: await read($, isForced),
1070    isLocked: await read($, isLocked),
1071    isDebug: debugOn,
1072    bandStyle: await read($, bandStyle),
1073    state: await read($, status),
1074    totals: await read($, totals),
1075    allTime: await read($, allTime),
1076    list: await read($, refreshes),
1077    logPath: shown === "main" && debugOn ? await debugPathOf($) : "",
1078    at: Math.max(await read($, now), await $.clock.now()),
1079    width: e.props.bodyColumns,
1080    rows: e.props.scroll.bodyRows,
1081  };
1082  let mascot: Mascot | undefined;
1083  sites.delete(PANE);
1084  const scene = await sceneOf($);
1085  const layout = shown === "main" ? layoutOf(data) : undefined;
1086  if (e.surface === "terminal" && layout) {
1087    const background =
1088      e.props.placement === "dock" ? dockBackgroundOf(theme) : TERMINAL_DEFAULT;
1089    sites.set(PANE, background);
1090    const cells = mascotOf(scene, data.at, background);
1091    mascot = { raster: rasterOf($.ui.resolve(e), cells), layout };
1092  }
1093  const actions: PaneActions = {
1094    open: (next) => void update($, page, () => next),
1095    toggleDebug: () => void update($, isDebug, (current) => !current),
1096    setBand: (value) => void setBand($, value),
1097    chooseDefault: (value) => void chooseDefault($, value),
1098    chooseSession: (value) => void chooseSessionTtl($, value),
1099    setLimit: (limitTtl, count) => void setLimit($, limitTtl, count),
1100  };
1101  const tree = paneOf($.ui.resolve(e), data, actions, mascot);
1102  const drawn = focusRowsOf(tree);
1103  focusRows = drawn.rows;
1104  // A page's autoFocus Button takes the ring without raising ui.focus.
1105  if (!focusRows.flat().includes(focused ?? "")) focused = drawn.initial;
1106  return tree;
1107};
1108
1109// An arrow over a pane taller than its window scrolls it, leaving the focus
1110// behind out of sight; it moves the focus a row instead, which brings it into
1111// view. The wheel, and an arrow past the first or last row, still scroll.
1112const arrowToFocus = async (
1113  $: EngineInterface,
1114  e: Frozen<Args<"ui.scroll">>,
1115  next: Next<"ui.scroll">,
1116) => {
1117  if (e.origin.kind !== "person" || e.pointer || Math.abs(e.by) !== 1)
1118    return next(e);
1119  const index = focusRows.findIndex((row) => row.includes(focused ?? ""));
1120  const from = focusRows[index]?.indexOf(focused ?? "") ?? 0;
1121  const row = focusRows[index + e.by];
1122  const key = row?.[Math.min(from, row.length - 1)];
1123  if (index < 0 || !key) return next(e);
1124  const answer = await $.ui.focus({ requestId: PANE, key });
1125  return answer.deny === undefined ? {} : next(e);
1126};
1127
1128export const register: Register = (on, options) => {
1129  const chosen = String(options.ttl);
1130  const option = isTtl(chosen) ? chosen : "1h";
1131  const limits = {
1132    "5m": limitOf(options.idle5m ?? IDLE_LIMIT_DEFAULT),
1133    "1h": limitOf(options.idle1h ?? IDLE_LIMIT_DEFAULT),
1134  };
1135  const band = bandStyleOf(options.band);
1136  on("session.start", async ($, e, next) => {
1137    await startSession($, option, limits, band);
1138    return next(e);
1139  });
1140  on("command.run", { command: "cache-warmer" }, ($, e) =>
1141    runCommand($, e.args),
1142  );
1143  on("config.set", { key: CONFIG_KEY }, onTtlConfigSet);
1144  on("config.set", { key: "cache-warmer.idle5m" }, ($, e, next) =>
1145    setIdleFromConfig($, e, next, "5m"),
1146  );
1147  on("config.set", { key: "cache-warmer.idle1h" }, ($, e, next) =>
1148    setIdleFromConfig($, e, next, "1h"),
1149  );
1150  on("config.set", { key: BAND_KEY }, async ($, e, next) => {
1151    const answer = await next(e);
1152    if (answer.deny === undefined)
1153      await applyBand($, bandStyleOf(answer.value));
1154    return answer;
1155  });
1156  on("turn.start", onTurnStart);
1157  on("turn.step", async function* ($, e, next) {
1158    return yield* stepTurn($, e, next);
1159  });
1160  on("turn.complete", onTurnComplete);
1161  on("session.compact", async ($, e, next) => {
1162    const answer = await next(e);
1163    if (e.agentId === undefined) await forget($, "conversation compacted");
1164    return answer;
1165  });
1166  // Every ending forgets the chain, so its fee is settled before the process can exit.
1167  on("session.end", async ($, e, next) => {
1168    if (e.reason !== "clear") await forget($, "session ended");
1169    else {
1170      await forget($, "conversation cleared");
1171      await update($, isLocked, () => false);
1172      // /clear starts a new session id without session.start, so it takes the saved default here.
1173      await applyDefault($, await read($, defaultTtl));
1174    }
1175    return next(e);
1176  });
1177  on("classic.PostModelSwitch", async ($, e, next) => {
1178    await forget($, "model switched");
1179    return next(e);
1180  });
1181  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
1182    const answer = await next(e);
1183    if ("deny" in answer) return answer;
1184    const band = await renderBand($, e);
1185    if (!band) return answer;
1186    return (
1187      <>
1188        {band}
1189        {answer}
1190      </>
1191    );
1192  });
1193  on("ui.render", { component: "Pane", requestId: PANE }, renderPane);
1194  on("ui.focus", { component: "Pane", requestId: PANE }, async ($, e, next) => {
1195    const answer = await next(e);
1196    if (answer.deny === undefined) focused = e.element;
1197    return answer;
1198  });
1199  on("ui.scroll", { component: "Pane", requestId: PANE }, arrowToFocus);
1200  on("ui.close", { id: PANE }, async ($, e, next) => {
hooks/mascot.ts 454 lines
1// Clawd, the Claude Code mascot, holding a steaming mug: the pane's animation.
2// Half blocks draw the sprite and braille dots draw the steam, packed as
3// RasterProps cells. A frame depends on time and mood alone, so dropped frames
4// never put it out of step.
5
6import type { Mood } from "../types";
7
8export const MASCOT_COLUMNS = 28;
9export const MASCOT_ROWS = 7;
10
11const WIDTH = MASCOT_COLUMNS;
12const HEIGHT = MASCOT_ROWS * 2;
13const NONE = -1;
14export const TERMINAL_DEFAULT = 0x01000000;
15const SPACE = 0x20;
16const UPPER_HALF = 0x2580;
17const LOWER_HALF = 0x2584;
18const BRAILLE = 0x2800;
19// Braille dot bits, row by row, left dot first.
20const DOTS = [0x01, 0x08, 0x02, 0x10, 0x04, 0x20, 0x40, 0x80];
21
22// Clawd's top-left while standing, in half-block pixels: one column wide, half a row tall.
23const X0 = 0;
24const Y0 = 4;
25
26const BODY = 0xd77757;
27const BODY_LIT = 0xe8916f;
28const BODY_SHADE = 0xb75f41;
29const BODY_DEEP = 0x9c4f35;
30const EYE = 0x1d1512;
31const CERAMIC_LIT = 0xfdfaf5;
32const COFFEE = 0x452818;
33const CREMA = 0x96643f;
34
35type Eyes = "open" | "shut" | "happy";
36
37type Pose = {
38  lift: number;
39  dip: number;
40  eyes: Eyes;
41  look: number;
42  wave: number;
43  sip: number;
44};
45
46type Cell = [glyph: number, foreground: number, background: number];
47type Rect = [x: number, y: number, w: number, h: number];
48type Tones = [
49  edge: number,
50  lit: number,
51  base: number,
52  shade: number,
53  deep: number,
54];
55
56export type Theme = "dark" | "light";
57
58// What sits against the terminal's background. On a light one the mug gets a
59// dark outline, and steam darkens where a dark one has it brighten.
60type Palette = {
61  ceramic: Tones;
62  rim: number;
63  handle: number;
64  steam: [faint: number, dense: number];
65  spark: [bright: number, dim: number];
66  snore: [bright: number, dim: number];
67};
68const DARK: Palette = {
69  ceramic: [0xeee8de, CERAMIC_LIT, 0xeee8de, 0xd3cabd, 0xb3a99b],
70  rim: 0xd6cdbf,
71  handle: 0xd9d1c4,
72  steam: [0x5d6570, 0xf6efe6],
73  spark: [0xffd88a, 0xa77c34],
74  snore: [0xa9bccd, 0x4f5965],
75};
76const LIGHT: Palette = {
77  ceramic: [0x9a9084, CERAMIC_LIT, 0xf1ebe1, 0xcfc5b7, 0x8a8074],
78  rim: 0x9a9084,
79  handle: 0x9a9084,
80  steam: [0xd2d6dc, 0x6a7380],
81  spark: [0xc0820f, 0xe9d3a0],
82  snore: [0x557089, 0xc5ced8],
83};
84// A steam particle in half-block pixels, and how bright it is from 0 to 1.
85type Speck = { x: number; y: number; glow: number };
86// The coffee's top-left and the steam's strength: 1 while hot, 0 once cold.
87type Source = { x: number; y: number; heat: number };
88
89// The mug's width; its handle hangs off the left, where Clawd grips it.
90const MUG_WIDTH = 8;
91
92// Particles from one point on the coffee follow one swaying strand.
93const EMITTERS = [
94  { offset: 1 + 0.2 * (MUG_WIDTH - 2), phase: 0 },
95  { offset: 1 + 0.5 * (MUG_WIDTH - 2), phase: 2.1 },
96  { offset: 1 + 0.8 * (MUG_WIDTH - 2), phase: 4.2 },
97];
98// Seconds between one emitter's particles, and the longest a particle lives.
99const SPAWN = 0.11;
100const LIFE = 2.3;
101const HEART_POINTS = 28;
102
103const SPARKS = [
104  { column: 1, row: 1, delay: 0.1 },
105  { column: 7, row: 0, delay: 0.5 },
106  { column: 13, row: 1, delay: 0.9 },
107  { column: 3, row: 0, delay: 1.5 },
108  { column: 11, row: 0, delay: 1.9 },
109];
110const SPARK_GLYPHS = [0xb7, 0x2b, 0x2a, 0x2b, 0xb7];
111
112const hash = (n: number): number => {
113  let x = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);
114  x ^= x >>> 13;
115  x = Math.imul(x, 0xc2b2ae35);
116  x ^= x >>> 16;
117  return (x >>> 0) / 4294967296;
118};
119
120const smoothstep = (from: number, to: number, x: number): number => {
121  const f = Math.min(1, Math.max(0, (x - from) / (to - from)));
122  return f * f * (3 - 2 * f);
123};
124
125const mix = (from: number, to: number, f: number): number => {
126  const channel = (shift: number) => {
127    const a = (from >> shift) & 0xff;
128    const b = (to >> shift) & 0xff;
129    return Math.round(a + (b - a) * f) << shift;
130  };
131  return channel(16) | channel(8) | channel(0);
132};
133
134const isBlinking = (t: number): boolean => {
135  const slot = Math.floor(t / 3.7);
136  const at = slot * 3.7 + 0.5 + hash(slot) * 2.6;
137  return t >= at && t < at + 0.14;
138};
139
140const idleOf = (t: number): Pose => ({
141  lift: 0,
142  dip: t % 2.8 > 1.6 ? 1 : 0,
143  eyes: isBlinking(t) ? "shut" : "open",
144  look: 0,
145  wave: 0,
146  sip: 0,
147});
148
149// Every 5.6 s: glance at the mug, raise it, sip with eyes shut, lower it.
150const sippingOf = (t: number): Pose => {
151  const pose = idleOf(t);
152  const p = (t + 5.6 - 1.4) % 5.6;
153  if (p >= 1.9) return pose;
154  const raise =
155    p < 0.65 ? smoothstep(0.35, 0.65, p) : 1 - smoothstep(1.45, 1.75, p);
156  return {
157    ...pose,
158    dip: 0,
159    look: p < 0.5 ? 1 : 0,
160    eyes: p >= 0.7 && p < 1.45 ? "shut" : pose.eyes,
161    sip: Math.round(raise * 3),
162  };
163};
164
165// One hop in 0.7 s: crouch, rise two pixels, land in a crouch.
166const hopOf = (x: number): Pick<Pose, "lift" | "dip"> => {
167  if (x < 0.1) return { lift: 0, dip: 1 };
168  if (x < 0.17) return { lift: 1, dip: 0 };
169  if (x < 0.36) return { lift: 2, dip: 0 };
170  if (x < 0.43) return { lift: 1, dip: 0 };
171  if (x < 0.55) return { lift: 0, dip: 1 };
172  return { lift: 0, dip: 0 };
173};
174
175const poseOf = (t: number, mood: Mood, m: number): Pose => {
176  if (mood === "warming") return sippingOf(t);
177  const pose = idleOf(t);
178  if (mood === "cold")
179    return {
180      ...pose,
181      dip: m > 0.5 ? 1 : 0,
182      eyes: m > 0.7 ? "shut" : pose.eyes,
183    };
184  if (m < 1.4) return { ...pose, ...hopOf(m % 0.7), eyes: "happy", wave: 2 };
185  return { ...pose, eyes: m < 2.6 ? "happy" : pose.eyes };
186};
187
188// The heart takes the place of most of the steam while it floats up.
189const heatOf = (mood: Mood, m: number): number => {
190  if (mood === "warmed") return 0.15 + 0.85 * smoothstep(2.2, 3.2, m);
191  if (mood === "cold") return Math.max(0, 1 - m / 1.8);
192  return 1;
193};
194
195const fill = (pixels: Int32Array, [x, y, w, h]: Rect, color: number) => {
196  for (let row = Math.max(0, y); row < Math.min(HEIGHT, y + h); row++)
197    for (let column = Math.max(0, x); column < Math.min(WIDTH, x + w); column++)
198      pixels[row * WIDTH + column] = color;
199};
200
201const eyeOf = (eyes: Eyes, x: number, top: number, inward: number): Rect[] => {
202  if (eyes === "open") return [[x, top + 2, 1, 2]];
203  if (eyes === "shut") return [[Math.min(x, x + inward), top + 3, 2, 1]];
204  return [
205    [x - 1, top + 3, 1, 1],
206    [x, top + 2, 1, 1],
207    [x + 1, top + 3, 1, 1],
208  ];
209};
210
211const drawClawd = (pixels: Int32Array, pose: Pose) => {
212  const top = Y0 - pose.lift + pose.dip;
213  for (const x of [3, 5, 10, 12])
214    fill(pixels, [X0 + x, top + 8, 1, 2 - pose.dip], BODY_SHADE);
215  fill(pixels, [X0 + 2, top, 12, 8], BODY);
216  fill(pixels, [X0 + 2, top, 12, 1], BODY_LIT);
217  fill(pixels, [X0 + 2, top, 1, 7], BODY_LIT);
218  fill(pixels, [X0 + 3, top + 7, 11, 1], BODY_SHADE);
219  fill(pixels, [X0, top + 4 - pose.wave, 2, 2], BODY);
220  for (const [x, inward] of [
221    [4, 1],
222    [11, -1],
223  ] as const)
224    for (const rect of eyeOf(pose.eyes, X0 + x + pose.look, top, inward))
225      fill(pixels, rect, EYE);
226};
227
228// The mug's top-left: the back of its rim, one row above the coffee.
229const mugOf = (pose: Pose) => ({
230  x: X0 + 17,
231  y: Y0 - pose.lift + pose.dip + 1 - pose.sip,
232});
233
234// Columns shade from a highlight at the left to a shadow at the right, so the
235// mug reads as a cylinder; the near lip below the coffee catches the light.
236const toneOf = (i: number, [edge, lit, base, shade, deep]: Tones): number => {
237  if (i === 0) return edge;
238  if (i === 1) return lit;
239  if (i === MUG_WIDTH - 2) return shade;
240  if (i === MUG_WIDTH - 1) return deep;
241  return base;
242};
243const STRIPE_TONES: Tones = [BODY, BODY_LIT, BODY, BODY_SHADE, BODY_DEEP];
244
245// Drawn after the mug, Clawd's right hand covers the outer side of the handle.
246const drawMug = (
247  pixels: Int32Array,
248  pose: Pose,
249  t: number,
250  { ceramic, rim, handle }: Palette,
251) => {
252  const { x, y } = mugOf(pose);
253  fill(pixels, [x + 1, y, MUG_WIDTH - 2, 1], rim);
254  for (let i = 0; i < MUG_WIDTH; i++) {
255    fill(pixels, [x + i, y + 1, 1, 5], toneOf(i, ceramic));
256    fill(pixels, [x + i, y + 4, 1, 1], toneOf(i, STRIPE_TONES));
257  }
258  fill(pixels, [x + 1, y + 1, MUG_WIDTH - 2, 1], COFFEE);
259  const glint = Math.floor(t * 0.8) % (MUG_WIDTH - 2);
260  fill(pixels, [x + 1 + glint, y + 1, 1, 1], CREMA);
261  fill(pixels, [x + 1, y + 2, MUG_WIDTH - 3, 1], CERAMIC_LIT);
262  fill(pixels, [x + 1, y + 6, MUG_WIDTH - 2, 1], ceramic[4]);
263  fill(pixels, [x - 2, y + 2, 2, 1], handle);
264  fill(pixels, [x - 2, y + 3, 1, 2], handle);
265  fill(pixels, [x - 2, y + 5, 2, 1], handle);
266  const top = Y0 - pose.lift + pose.dip;
267  fill(pixels, [X0 + 14, top + 4 - pose.sip, 2, 2], BODY);
268};
269
270// Particles leave the coffee at random speeds and ride one sway field, so
271// those at one height bend together into strands that widen and fade as they rise.
272const steamOf = (t: number, source: Source): Speck[] =>
273  EMITTERS.flatMap(({ offset, phase }, e) => {
274    const specks: Speck[] = [];
275    for (let n = Math.floor((t - LIFE) / SPAWN); n <= t / SPAWN; n++) {
276      const seed = (n * EMITTERS.length + e) * 8;
277      const life = 1.1 + hash(seed + 1) * (LIFE - 1.1);
278      const age = t - (n + 0.7 * hash(seed + 2)) * SPAWN;
279      if (hash(seed) >= source.heat || age <= 0 || age >= life) continue;
280      const h = (2.6 + 1.6 * hash(seed + 3)) * age * (1 - 0.12 * age);
281      const sway =
282        (0.2 + 0.17 * h) * Math.sin(0.85 * h - 2.9 * t + phase) +
283        0.05 * h * Math.sin(0.37 * h - 1.1 * t + 2.3 * phase);
284      const spread = (hash(seed + 4) - 0.5) * (0.2 + 0.3 * h);
285      specks.push({
286        x: source.x + offset + sway + spread + 0.14 * h,
287        y: source.y - h,
288        glow: 0.85 * smoothstep(0, 0.25, age) * (1 - age / life),
289      });
290    }
291    return specks;
292  });
293
294// A steam heart that floats up from the standing mug after a warm refresh,
295// then comes apart.
296const heartOf = (m: number): Speck[] => {
297  const age = m - 0.3;
298  if (age <= 0 || age >= 2.4) return [];
299  const scatter = smoothstep(1.4, 2.4, age);
300  const glow = 0.9 * smoothstep(0, 0.4, age) * (1 - scatter);
301  const cx = X0 + 17 + MUG_WIDTH / 2 + 0.35 * Math.sin(2.2 * age);
302  const cy = Y0 + 0.4 - 1.25 * age;
303  return Array.from({ length: HEART_POINTS }, (_, k) => {
304    const a = (k / HEART_POINTS) * 2 * Math.PI;
305    const hx = 16 * Math.sin(a) ** 3;
306    const hy =
307      13 * Math.cos(a) -
308      5 * Math.cos(2 * a) -
309      2 * Math.cos(3 * a) -
310      Math.cos(4 * a);
311    return {
312      x: cx + 0.14 * hx + scatter * 2.5 * (hash(k * 2) - 0.5),
313      y: cy - 0.125 * hy - scatter * 2 * hash(k * 2 + 1),
314      glow,
315    };
316  });
317};
318
319// Braille cells holding steam: dot bits and the brightest particle in each.
320const dotsOf = (
321  specks: Speck[],
322): Map<number, { bits: number; glow: number }> => {
323  const cells = new Map<number, { bits: number; glow: number }>();
324  for (const { x, y, glow } of specks) {
325    const dx = Math.floor(x * 2);
326    const dy = Math.floor(y * 2);
327    const column = Math.floor(dx / 2);
328    const row = Math.floor(dy / 4);
329    if (
330      glow < 0.06 ||
331      column < 0 ||
332      column >= WIDTH ||
333      row < 0 ||
334      row >= MASCOT_ROWS
335    )
336      continue;
337    const index = row * WIDTH + column;
338    const cell = cells.get(index) ?? { bits: 0, glow: 0 };
339    cell.bits |= DOTS[(dy - row * 4) * 2 + (dx - column * 2)] ?? 0;
340    cell.glow = Math.max(cell.glow, glow);
341    cells.set(index, cell);
342  }
343  return cells;
344};
345
346const cellOf = (
347  pixels: Int32Array,
348  column: number,
349  row: number,
350  steam: { bits: number; glow: number } | undefined,
351  [faint, dense]: Palette["steam"],
352  background: number,
353): Cell => {
354  const top = pixels[row * 2 * WIDTH + column] ?? NONE;
355  const bottom = pixels[(row * 2 + 1) * WIDTH + column] ?? NONE;
356  if (top !== NONE)
357    return [UPPER_HALF, top, bottom === NONE ? background : bottom];
358  if (bottom !== NONE) return [LOWER_HALF, bottom, background];
359  if (!steam) return [SPACE, TERMINAL_DEFAULT, background];
360  const tone = mix(faint, dense, Math.sqrt(steam.glow));
361  return [BRAILLE + steam.bits, tone, background];
362};
363
364// Glyphs drawn over empty cells: sparkles after a warm refresh, and a rising
365// "z" once the cache has gone cold.
366const glyphsOf = (
367  mood: Mood,
368  m: number,
369  { spark, snore }: Palette,
370  background: number,
371): [index: number, cell: Cell][] => {
372  if (mood === "warmed")
373    return SPARKS.flatMap(({ column, row, delay }) => {
374      const life = (m - delay) / 0.8;
375      if (life < 0 || life >= 1) return [];
376      const glyph =
377        SPARK_GLYPHS[Math.floor(life * SPARK_GLYPHS.length)] ?? SPACE;
378      const tone = mix(...spark, Math.abs(life - 0.5) * 2);
379      return [[row * WIDTH + column, [glyph, tone, background]]];
380    });
381  if (mood !== "cold" || m < 1) return [];
382  return [0, 0.9].map((delay) => {
383    const life = ((m - 1 + delay) % 1.8) / 1.8;
384    const index = (1 - Math.round(life)) * WIDTH + 14 + Math.round(life * 2);
385    const glyph = life < 0.5 ? 0x7a : 0x5a;
386    return [index, [glyph, mix(...snore, life), background]];
387  });
388};
389
390const BASE64 =
391  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
392
393// Cells are twelve bytes each, so the length is a multiple of three and needs no padding.
394const base64Of = (bytes: Uint8Array): string => {
395  const out: string[] = [];
396  for (let i = 0; i < bytes.length; i += 3) {
397    const n =
398      ((bytes[i] ?? 0) << 16) |
399      ((bytes[i + 1] ?? 0) << 8) |
400      (bytes[i + 2] ?? 0);
401    out.push(
402      BASE64.charAt((n >> 18) & 63),
403      BASE64.charAt((n >> 12) & 63),
404      BASE64.charAt((n >> 6) & 63),
405      BASE64.charAt(n & 63),
406    );
407  }
408  return out.join("");
409};
410
411// `t` counts seconds since the scene started and `m` seconds since the mood
412// began; `background` fills the cells around Clawd.
413export const cellsOf = (
414  t: number,
415  mood: Mood,
416  m: number,
417  theme: Theme,
418  background: number,
419): string => {
420  const palette = theme === "light" ? LIGHT : DARK;
421  const pose = poseOf(t, mood, m);
422  const pixels = new Int32Array(WIDTH * HEIGHT).fill(NONE);
423  drawClawd(pixels, pose);
424  drawMug(pixels, pose, t, palette);
425  const mug = mugOf(pose);
426  const source = { x: mug.x, y: mug.y + 1, heat: heatOf(mood, m) };
427  const steam = dotsOf([
428    ...steamOf(t, source),
429    ...(mood === "warmed" ? heartOf(m) : []),
430  ]);
431  const words = new Uint32Array(WIDTH * MASCOT_ROWS * 3);
432  for (let row = 0; row < MASCOT_ROWS; row++)
433    for (let column = 0; column < WIDTH; column++) {
434      const index = row * WIDTH + column;
435      words.set(
436        cellOf(
437          pixels,
438          column,
439          row,
440          steam.get(index),
441          palette.steam,
442          background,
443        ),
444        index * 3,
445      );
446    }
447  for (const [index, cell] of glyphsOf(mood, m, palette, background)) {
448    const current = words[index * 3] ?? SPACE;
449    if (current !== UPPER_HALF && current !== LOWER_HALF)
450      words.set(cell, index * 3);
451  }
452  return base64Of(new Uint8Array(words.buffer));
453};
454
hooks/pages.tsx 202 lines
1import type { ElementTable } from "claude-code";
2
3import type { Totals } from "../types";
4import type { Mascot, PaneActions, PaneData } from "./pane";
5import { headerOf, mainPageOf, statusTextOf, tableOf } from "./pane";
6import {
7  MIN_SAVINGS_USD,
8  PRICES_AS_OF,
9  delayOf,
10  formatDuration,
11  formatUsd,
12  idleSpanOf,
13  netSavedOf,
14} from "./warmer";
15
16const TTLS = ["5m", "1h"] as const;
17const BAND_STYLES = ["default", "simplified", "off"] as const;
18
19// One button for a choice among a few options: it marks the current option and a press picks the next.
20const toggleOf = <T extends string>(
21  { Button }: ElementTable,
22  key: string,
23  options: readonly T[],
24  current: T,
25  choose: (value: T) => void,
26) => (
27  <Button
28    key={`toggle:${key}`}
29    label={options
30      .map((value) => `${value === current ? "●" : "○"} ${value}`)
31      .join("  ")}
32    onPress={() =>
33      choose(
34        options[(options.indexOf(current) + 1) % options.length] ?? current,
35      )
36    }
37  />
38);
39
40const LABELS = {
41  ttl: "Lifetime",
42  default: "Default lifetime",
43  band: "Refresh band",
44  "5m": "Idle refreshes, 5m",
45  "1h": "Idle refreshes, 1h",
46};
47const LABEL_WIDTH = Math.max(
48  ...Object.values(LABELS).map((label) => label.length),
49);
50
51// This session's settings, then the defaults new sessions start with.
52const configPageOf = (
53  elements: ElementTable,
54  data: PaneData,
55  actions: PaneActions,
56) => {
57  const { Box, Text, Button } = elements;
58  const { chosen, saved, limits, bandStyle, isForced, isLocked, state, at } =
59    data;
60  const effective = isForced ? "5m" : chosen;
61  const status = statusTextOf(state, at);
62  const label = (text: string) => (
63    <Text>{`${text.padEnd(LABEL_WIDTH)}  `}</Text>
64  );
65  return (
66    <Box flexDirection="column">
67      {headerOf(elements, "Configuration", actions.open)}
68      <Text key="session" bold>
69        This session
70      </Text>
71      <Box key="ttl" flexDirection="row">
72        {label(LABELS.ttl)}
73        {isLocked ? (
74          <Text bold>{chosen}</Text>
75        ) : (
76          toggleOf(elements, "ttl", TTLS, chosen, actions.chooseSession)
77        )}
78        {isLocked && (
79          <Text dimColor>{"  locked: /clear or a new session unlocks it"}</Text>
80        )}
81      </Box>
82      <Text key="interval" dimColor>
83        {`Refreshes every ${formatDuration(delayOf(effective))} · idle limit ${limits[effective]} refreshes`}
84      </Text>
85      {status && (
86        <Text key="status" dimColor>
87          {status}
88        </Text>
89      )}
90      {isForced && (
91        <Text key="forced" color="yellow">
92          {`FORCE_PROMPT_CACHING_5M overrides ${chosen}; the cache lives 5m.`}
93        </Text>
94      )}
95      <Box key="defaults" marginTop={1}>
96        <Text bold>Global</Text>
97      </Box>
98      <Box key="default" flexDirection="row">
99        {label(LABELS.default)}
100        {toggleOf(elements, "default", TTLS, saved, actions.chooseDefault)}
101      </Box>
102      <Box key="band" flexDirection="row">
103        {label(LABELS.band)}
104        {toggleOf(elements, "band", BAND_STYLES, bandStyle, actions.setBand)}
105      </Box>
106      {TTLS.map((ttl) => (
107        <Box key={`idle:${ttl}`} flexDirection="row">
108          {label(LABELS[ttl])}
109          <Button
110            key={`idle:${ttl}:-`}
111            label="−"
112            onPress={() => actions.setLimit(ttl, limits[ttl] - 1)}
113          />
114          <Text>{String(limits[ttl]).padStart(3).padEnd(4)}</Text>
115          <Button
116            key={`idle:${ttl}:+`}
117            label="+"
118            onPress={() => actions.setLimit(ttl, limits[ttl] + 1)}
119          />
120          <Text dimColor>
121            {`  covers ${formatDuration(idleSpanOf(limits[ttl], ttl))} idle`}
122          </Text>
123        </Box>
124      ))}
125      <Text key="note" dimColor>
126        {`Enter switches a setting. Each refresh still needs Pi's ${formatUsd(MIN_SAVINGS_USD)} expected saving.`}
127      </Text>
128    </Box>
129  );
130};
131
132const ANALYTICS_ROWS: [label: string, valueOf: (totals: Totals) => string][] = [
133  ["Refreshes", (totals) => String(totals.refreshes)],
134  ["Warming fee", (totals) => formatUsd(totals.costUsd)],
135  ["  no prompt followed", (totals) => formatUsd(totals.wastedUsd)],
136  ["Prompts kept", (totals) => String(totals.kept)],
137  ["Rewrites avoided", (totals) => formatUsd(totals.keptUsd)],
138  ["1h gaps bridged", (totals) => formatUsd(totals.bridgedUsd)],
139  ["1h write premium", (totals) => formatUsd(totals.premiumUsd)],
140  ["Net saved", (totals) => formatUsd(netSavedOf(totals))],
141];
142
143const BASIS_LINES = [
144  "Compared with Claude Code's 5-minute cache and no refreshes.",
145  "A prompt is kept when it reads the cache after the point where, without refreshes, it would have expired; a 1h gap is bridged when it reads a 1h cache after five minutes with no refresh.",
146  `Avoided and bridged = cached tokens read × (5m write − read price); premium = 1h cache writes × (1h − 5m write price). API list prices (${PRICES_AS_OF}).`,
147];
148
149const analyticsPageOf = (
150  elements: ElementTable,
151  { totals, allTime }: PaneData,
152  actions: PaneActions,
153) => {
154  const { Box, Text } = elements;
155  const lines = tableOf(
156    [
157      ["", "This session", "All time"],
158      ...ANALYTICS_ROWS.map(([label, valueOf]) => [
159        label,
160        valueOf(totals),
161        valueOf(allTime),
162      ]),
163    ],
164    [true, false, false],
165  );
166  return (
167    <Box flexDirection="column">
168      {headerOf(elements, "Analytics", actions.open)}
169      {lines.map((line, index) => (
170        <Text
171          key={`row:${index}`}
172          wrap="truncate-end"
173          dimColor={index === 0}
174          bold={index === lines.length - 1}
175        >
176          {line}
177        </Text>
178      ))}
179      <Text key="since" dimColor>
180        {`All time since ${new Date(allTime.since).toISOString().slice(0, 10)}`}
181      </Text>
182      {BASIS_LINES.map((line, index) => (
183        <Text key={`basis:${index}`} dimColor>
184          {line}
185        </Text>
186      ))}
187    </Box>
188  );
189};
190
191export const paneOf = (
192  elements: ElementTable,
193  data: PaneData,
194  actions: PaneActions,
195  mascot?: Mascot,
196) => {
197  if (data.page === "config") return configPageOf(elements, data, actions);
198  if (data.page === "analytics")
199    return analyticsPageOf(elements, data, actions);
200  return mainPageOf(elements, data, actions, mascot);
201};
202
hooks/pane.tsx 352 lines
1import type { ElementTable, RenderElement, RenderNode } from "claude-code";
2
3import type {
4  AllTime,
5  BandStyle,
6  IdleLimits,
7  Mood,
8  Notice,
9  Page,
10  Refresh,
11  Status,
12  Totals,
13  Ttl,
14} from "../types";
15import { MASCOT_COLUMNS, MASCOT_ROWS } from "./mascot";
16import { delayOf, formatDuration, formatTokens, formatUsd } from "./warmer";
17
18export const MASCOT_KEY = "mascot";
19// Plain text, which terminals link themselves: a Link where OSC 8 is unsupported draws its label and then the URL.
20const REPOSITORY = "github.com/paulbkim-dev/claude-code-cache-warmer";
21// Clawd stands left of the main page's column when this many columns stay beside him, and above it in a narrower pane.
22const SIDE_COLUMNS = 30;
23const SIDE_GAP = 2;
24// The main page's column above its status line besides the repository line: two header rows, a blank row and three menu items.
25const MENU_ROWS = 6;
26const COLUMN_GAP = "  ";
27
28export type PaneData = {
29  page: Page;
30  // This session's lifetime, and the saved default new sessions start with.
31  chosen: Ttl;
32  saved: Ttl;
33  limits: IdleLimits;
34  isForced: boolean;
35  isLocked: boolean;
36  isDebug: boolean;
37  bandStyle: BandStyle;
38  state: Status;
39  totals: Totals;
40  allTime: AllTime;
41  list: Refresh[];
42  logPath: string;
43  at: number;
44  width: number;
45  rows: number;
46};
47
48export type PaneActions = {
49  open: (page: Page) => void;
50  toggleDebug: () => void;
51  setBand: (value: BandStyle) => void;
52  chooseDefault: (value: Ttl) => void;
53  chooseSession: (value: Ttl) => void;
54  setLimit: (ttl: Ttl, count: number) => void;
55};
56
57export const statusTextOf = (state: Status, at: number): string | undefined => {
58  if (state.state === "waiting") return undefined;
59  if (state.state === "refreshing") return "Refreshing now.";
60  if (state.state === "stopped")
61    return `Stopped: ${state.reason}. The next prompt restarts warming.`;
62  const phase = state.phase === "run" ? "turn running" : "idle";
63  return `Next refresh in ${formatDuration(state.nextAt - at)} · ${phase} · expected saving ${formatUsd(state.expectedUsd)}`;
64};
65
66// Rows a text takes wrapped at spaces, a word longer than the width broken across rows.
67const rowsOf = (text: string, width: number) => {
68  let rows = 1;
69  let used = 0;
70  for (const word of text.split(" ")) {
71    const gap = used === 0 ? 0 : 1;
72    if (used + gap + word.length <= width) {
73      used += gap + word.length;
74      continue;
75    }
76    rows += Math.ceil(word.length / width) - (used === 0 ? 1 : 0);
77    used = word.length % width || width;
78  }
79  return rows;
80};
81
82// Lays rows of cells out in columns, each as wide as its widest cell; `isLeft` columns align left.
83export const tableOf = (rows: string[][], isLeft: boolean[]) => {
84  const widths = (rows[0] ?? []).map((_, index) =>
85    Math.max(...rows.map((row) => (row[index] ?? "").length)),
86  );
87  return rows.map((row) =>
88    row
89      .map((cell, index) =>
90        isLeft[index]
91          ? cell.padEnd(widths[index] ?? 0)
92          : cell.padStart(widths[index] ?? 0),
93      )
94      .join(COLUMN_GAP)
95      .trimEnd(),
96  );
97};
98
99// The keys of the Buttons a tree draws, in order, one list per row: a row Box
100// holds its Buttons together, and a Button anywhere else is a row by itself.
101// `initial` is the first autoFocus Button, which the ring starts on.
102export const focusRowsOf = (tree: RenderElement) => {
103  const rows: string[][] = [];
104  let initial: string | undefined;
105  // Text's string children hold no Buttons.
106  const isElement = (node: RenderNode): node is RenderElement =>
107    node instanceof Object;
108  const visit = (node: RenderElement, row: string[] | undefined) => {
109    if (node.type === "Button") {
110      if (node.props.autoFocus) initial ??= node.props.key;
111      if (row) row.push(node.props.key);
112      else rows.push([node.props.key]);
113      return;
114    }
115    if (node.type !== "Box") return;
116    const inner = node.props?.flexDirection === "row" ? [] : undefined;
117    if (inner) rows.push(inner);
118    for (const child of node.children ?? [])
119      if (isElement(child)) visit(child, inner);
120  };
121  visit(tree, undefined);
122  return { rows: rows.filter((row) => row.length > 0), initial };
123};
124
125// The pane and the band draw Clawd under one key; blits repaint him there.
126export const rasterOf = (
127  { Raster }: ElementTable<"terminal">,
128  cells: string,
129) => (
130  <Raster
131    key={MASCOT_KEY}
132    columns={MASCOT_COLUMNS}
133    rows={MASCOT_ROWS}
134    cells={cells}
135  />
136);
137
138const TTL_COLORS = { "5m": "cyan", "1h": "magenta" } satisfies Record<
139  Ttl,
140  string
141>;
142const MOOD_COLORS = {
143  warming: "yellow",
144  warmed: "green",
145  cold: "red",
146} satisfies Record<Mood, string>;
147
148const noticeTextOf = (
149  { Text }: ElementTable,
150  { ttl, head, detail, mood }: Notice,
151  wrap: "truncate-end" | "wrap",
152) => (
153  <Text wrap={wrap}>
154    <Text dimColor>{"☕ cache warmer "}</Text>
155    <Text color={TTL_COLORS[ttl]}>{ttl}</Text>
156    <Text dimColor>{` every ${formatDuration(delayOf(ttl))} · `}</Text>
157    <Text color={MOOD_COLORS[mood]}>{head}</Text>
158    {detail && <Text dimColor>{` · ${detail}`}</Text>}
159  </Text>
160);
161
162// One dim line with the lifetime and the outcome in color.
163export const bandOf = (elements: ElementTable, shown: Notice) =>
164  noticeTextOf(elements, shown, "truncate-end");
165
166// Clawd's raster with the notice wrapped beside him.
167export const mascotBandOf = (
168  elements: ElementTable<"terminal">,
169  shown: Notice,
170  raster: RenderElement,
171) => {
172  const { Box } = elements;
173  return (
174    <Box flexDirection="row" columnGap={2}>
175      {raster}
176      <Box flexDirection="column" justifyContent="center" flexShrink={1}>
177        {noticeTextOf(elements, shown, "wrap")}
178      </Box>
179    </Box>
180  );
181};
182
183// Every sub-page opens with the Back button, which holds the focus first, and its title.
184export const headerOf = (
185  { Box, Text, Button }: ElementTable,
186  title: string,
187  open: (page: Page) => void,
188) => (
189  <Box key="header" flexDirection="row" columnGap={2}>
190    <Button
191      key="back"
192      label="‹ Back"
193      plain
194      autoFocus
195      onPress={() => open("main")}
196    />
197    <Text bold>{title}</Text>
198  </Box>
199);
200
201const DEBUG_HEADER = ["ago", "result", "read", "write", "out", "cost", "saves"];
202const DEBUG_LEFT = DEBUG_HEADER.map((name) => name === "result");
203
204const debugCellsOf = (one: Refresh, at: number) => [
205  formatDuration(at - one.at),
206  one.detail ? `${one.result} (${one.detail})` : one.result,
207  one.usage ? formatTokens(one.usage.cacheRead) : "-",
208  one.usage ? formatTokens(one.usage.cacheWrite) : "-",
209  one.usage ? String(one.usage.output) : "-",
210  one.costUsd === null ? "?" : formatUsd(one.costUsd),
211  one.savesUsd === null ? "" : formatUsd(one.savesUsd),
212];
213
214const logTextOf = (path: string) => `Log: ${path}`;
215
216// Rows the main page's column takes at `width`, all but the debug table's refreshes, which take the rows left.
217const columnRowsOf = (
218  { state, at, isDebug, logPath }: PaneData,
219  width: number,
220) => {
221  const status = statusTextOf(state, at);
222  return (
223    MENU_ROWS +
224    rowsOf(REPOSITORY, width) +
225    (status ? rowsOf(status, width) : 0) +
226    (isDebug ? rowsOf(logTextOf(logPath), width) + 1 : 0)
227  );
228};
229
230// The log path, the column names and the newest refreshes that fit in `room` rows.
231const debugTableOf = (
232  { Text }: ElementTable,
233  { list, logPath, at }: PaneData,
234  room: number,
235) => {
236  const shown = room > 0 ? list.slice(-room) : [];
237  const [columns = "", ...lines] = tableOf(
238    [DEBUG_HEADER, ...shown.map((one) => debugCellsOf(one, at))],
239    DEBUG_LEFT,
240  );
241  return [
242    <Text key="log" dimColor wrap="wrap">
243      {logTextOf(logPath)}
244    </Text>,
245    <Text key="columns" dimColor wrap="truncate-end">
246      {list.length === 0 ? "No refreshes yet." : columns}
247    </Text>,
248    ...lines.map((line, index) => (
249      <Text
250        key={`refresh:${shown[index]?.at ?? index}`}
251        wrap="truncate-end"
252        dimColor={shown[index]?.result !== "warmed"}
253      >
254        {line}
255      </Text>
256    )),
257  ];
258};
259
260type Layout = "beside" | "above";
261
262// Clawd's raster and where layoutOf placed him.
263export type Mascot = { raster: RenderElement; layout: Layout };
264
265// Where Clawd fits on the main page: beside the column, above it with a blank row between, or nowhere.
266// Beside him the column scrolls, so a turn's spinner shrinking an inline pane keeps him drawn.
267export const layoutOf = (data: PaneData): Layout | undefined => {
268  if (
269    data.width - MASCOT_COLUMNS - SIDE_GAP >= SIDE_COLUMNS &&
270    data.rows >= MASCOT_ROWS
271  )
272    return "beside";
273  if (
274    data.width >= MASCOT_COLUMNS &&
275    data.rows >= MASCOT_ROWS + 1 + columnRowsOf(data, data.width)
276  )
277    return "above";
278  return undefined;
279};
280
281export const mainPageOf = (
282  elements: ElementTable,
283  data: PaneData,
284  actions: PaneActions,
285  mascot?: Mascot,
286) => {
287  const { Box, Text, Button } = elements;
288  const layout = mascot?.layout;
289  const width =
290    layout === "beside" ? data.width - MASCOT_COLUMNS - SIDE_GAP : data.width;
291  const status = statusTextOf(data.state, data.at);
292  const item = (key: string, label: string, onPress: () => void) => (
293    <Button
294      key={`menu:${key}`}
295      label={`› ${label}`}
296      plain
297      autoFocus={key === "config" ? true : undefined}
298      onPress={onPress}
299    />
300  );
301  const column = (
302    <Box key="menu" flexDirection="column" width={width}>
303      <Box
304        key="header"
305        flexDirection="column"
306        alignItems="center"
307        marginBottom={1}
308      >
309        <Text bold>Cache Warmer</Text>
310        <Text dimColor>paulbkim.dev</Text>
311        <Text dimColor wrap="wrap">
312          {REPOSITORY}
313        </Text>
314      </Box>
315      {item("config", "Configuration", () => actions.open("config"))}
316      {item("analytics", "Analytics", () => actions.open("analytics"))}
317      {item(
318        "debug",
319        `Debug mode · ${data.isDebug ? "on" : "off"}`,
320        actions.toggleDebug,
321      )}
322      {status && (
323        <Text key="status" dimColor wrap="wrap">
324          {status}
325        </Text>
326      )}
327      {data.isDebug &&
328        debugTableOf(
329          elements,
330          data,
331          data.rows -
332            (layout === "above" ? MASCOT_ROWS + 1 : 0) -
333            columnRowsOf(data, width),
334        )}
335    </Box>
336  );
337  if (!mascot) return column;
338  if (mascot.layout === "beside")
339    return (
340      <Box flexDirection="row" columnGap={SIDE_GAP}>
341        {mascot.raster}
342        {column}
343      </Box>
344    );
345  return (
346    <Box flexDirection="column" alignItems="center" rowGap={1}>
347      {mascot.raster}
348      {column}
349    </Box>
350  );
351};
352
hooks/warmer.ts 329 lines
1import type { ConfigValue, ModelForkResult, ModelUsage } from "claude-code";
2
3import type { Notice, Refresh, Totals, Ttl, Usage } from "../types";
4
5export const PRICES_AS_OF = "2026-10-20";
6
7type Price = { input: number; cacheRead: number; output: number };
8
9const price = (input: number, cacheRead: number, output: number): Price => ({
10  input,
11  cacheRead,
12  output,
13});
14
15// A model priced higher for a prompt over `upTo` tokens, counting input of every kind.
16type Tiered = { upTo: number; short: Price; long: Price };
17
18// USD per million tokens at standard rates, from https://platform.claude.com/docs/en/about-claude/pricing.
19// Cache writes cost 1.25x input for the 5-minute lifetime and 2x for the 1-hour lifetime.
20const PRICES = {
21  "claude-fable-5-1": price(10, 0.25, 50),
22  "claude-mythos-5-1": price(10, 0.25, 50),
23  "claude-fable-5": price(10, 1, 50),
24  "claude-mythos-5": price(10, 1, 50),
25  "claude-opus-5-5": price(4, 0.2, 20),
26  "claude-opus-5": price(5, 0.5, 25),
27  "claude-opus-4-8": price(5, 0.5, 25),
28  "claude-opus-4-7": price(5, 0.5, 25),
29  "claude-opus-4-6": price(5, 0.5, 25),
30  "claude-opus-4-5": price(5, 0.5, 25),
31  "claude-opus-4-1": price(15, 1.5, 75),
32  "claude-opus-4": price(15, 1.5, 75),
33  "claude-sonnet-5-5": price(2, 0.1, 10),
34  "claude-sonnet-5": price(2, 0.2, 10),
35  "claude-sonnet-4-6": price(3, 0.3, 15),
36  "claude-sonnet-4-5": price(3, 0.3, 15),
37  "claude-sonnet-4": price(3, 0.3, 15),
38  "claude-haiku-5-5": {
39    upTo: 100_000,
40    short: price(0.1, 0.01, 0.5),
41    long: price(0.5, 0.05, 2.5),
42  },
43  "claude-haiku-4-5": price(1, 0.1, 5),
44  "claude-3-5-haiku": price(0.8, 0.08, 4),
45} satisfies Record<string, Price | Tiered>;
46
47const WRITE_MULTIPLIER = { "5m": 1.25, "1h": 2 } satisfies Record<Ttl, number>;
48
49export const TTL_MS = { "5m": 300_000, "1h": 3_600_000 } satisfies Record<
50  Ttl,
51  number
52>;
53
54// Pi 1.0.2's rule: send a refresh only when it is expected to save this much.
55export const MIN_SAVINGS_USD = 0.05;
56// Pi's measured chance that a prompt arrives before the entry expires while the session is idle.
57export const IDLE_CONTINUATION = 0.15;
58// A fork has no output cap; Opus 5.5 at high effort answered a refresh in 182 output tokens.
59export const DEFAULT_OUTPUT_TOKENS = 200;
60// The refreshes each lifetime may send while the session is idle, by default and at most.
61export const IDLE_LIMIT_DEFAULT = 5;
62export const IDLE_LIMIT_MAX = 20;
63
64export const ZERO_TOTALS: Totals = {
65  refreshes: 0,
66  costUsd: 0,
67  wastedUsd: 0,
68  kept: 0,
69  keptUsd: 0,
70  bridgedUsd: 0,
71  premiumUsd: 0,
72};
73
74const isPriceKey = (id: string): id is keyof typeof PRICES =>
75  Object.hasOwn(PRICES, id);
76
77// The model as the API, a gateway, Bedrock or Vertex names it: a Bedrock inference
78// profile (`us.anthropic.…-v1:0`), its ARN or Mantle's `anthropic.…`, and Vertex's `…@date`.
79// An application inference profile ARN does not name its model, so it has no price.
80const entryOf = (model: string): Price | Tiered | undefined => {
81  const id = model
82    .replace(/^arn:aws[\w-]*:bedrock:[^/]*\//, "")
83    .replace(/^(?:claude-gateway|anthropic)\//, "")
84    .replace(/^(?:[a-z-]+\.)?anthropic\./, "")
85    .replace(/\[\d+(?:k|m)\]$/, "")
86    .replace(/-v\d+(?::\d+)?$/, "")
87    .replace(/@\d{8}$/, "");
88  const key = isPriceKey(id)
89    ? id
90    : id.match(/^(claude-[a-z0-9-]+?)-\d{8}$/)?.[1];
91  return key !== undefined && isPriceKey(key) ? PRICES[key] : undefined;
92};
93
94const priceAt = (entry: Price | Tiered, promptTokens: number): Price =>
95  "upTo" in entry
96    ? promptTokens > entry.upTo
97      ? entry.long
98      : entry.short
99    : entry;
100
101const rates = (model: string, promptTokens: number): Price | undefined => {
102  const entry = entryOf(model);
103  return entry && priceAt(entry, promptTokens);
104};
105
106// A fork that made a request; the other kind found nothing to fork.
107export type ForkReply = Exclude<ModelForkResult, { reason: "nothing-to-fork" }>;
108
109export const isTtl = (value: string): value is Ttl =>
110  value === "5m" || value === "1h";
111
112export const usageOf = (usage: ModelUsage): Usage => ({
113  input: usage.input_tokens,
114  output: usage.output_tokens,
115  cacheRead: usage.cache_read_input_tokens,
116  cacheWrite: usage.cache_creation_input_tokens,
117});
118
119export const promptTokensOf = (usage: Usage) =>
120  usage.input + usage.cacheRead + usage.cacheWrite;
121
122// Refresh at 90% of the lifetime, leaving at least ten seconds before expiry.
123export const delayOf = (ttl: Ttl) =>
124  Math.floor(Math.min(TTL_MS[ttl] * 0.9, TTL_MS[ttl] - 10_000));
125
126// Pi stops run warming 60 minutes after the last prompt request; the 1-hour
127// lifetime stretches that to two lifetimes so that it warms at all.
128export const horizonOf = (ttl: Ttl) => Math.max(60 * 60_000, 2 * TTL_MS[ttl]);
129
130// A /config value or option as an idle limit: a whole number from 0 to IDLE_LIMIT_MAX.
131export const limitOf = (value: ConfigValue) => {
132  const count = Math.round(Number(value));
133  return Number.isFinite(count)
134    ? Math.min(IDLE_LIMIT_MAX, Math.max(0, count))
135    : IDLE_LIMIT_DEFAULT;
136};
137
138// How long an idle cache stays warm: the limit's refreshes, then one lifetime.
139export const idleSpanOf = (count: number, ttl: Ttl) =>
140  count * delayOf(ttl) + TTL_MS[ttl];
141
142export const addTotals = <T extends Totals>(
143  base: T,
144  delta: Partial<Totals>,
145): T => ({
146  ...base,
147  refreshes: base.refreshes + (delta.refreshes ?? 0),
148  costUsd: base.costUsd + (delta.costUsd ?? 0),
149  wastedUsd: base.wastedUsd + (delta.wastedUsd ?? 0),
150  kept: base.kept + (delta.kept ?? 0),
151  keptUsd: base.keptUsd + (delta.keptUsd ?? 0),
152  bridgedUsd: base.bridgedUsd + (delta.bridgedUsd ?? 0),
153  premiumUsd: base.premiumUsd + (delta.premiumUsd ?? 0),
154});
155
156// Analytics compare with Claude Code's 5-minute cache and no refreshes.
157export const netSavedOf = (totals: Totals) =>
158  totals.keptUsd + totals.bridgedUsd - totals.costUsd - totals.premiumUsd;
159
160// A timer that fires this late would likely find the entry expired and pay a full write.
161export const deadlineOf = (lastAt: number, ttl: Ttl) =>
162  lastAt + delayOf(ttl) + Math.floor((TTL_MS[ttl] - delayOf(ttl)) / 2);
163
164export const costOf = (
165  model: string,
166  usage: Usage,
167  ttl: Ttl,
168): number | null => {
169  const p = rates(model, promptTokensOf(usage));
170  if (!p) return null;
171  return (
172    (usage.input * p.input +
173      usage.cacheWrite * p.input * WRITE_MULTIPLIER[ttl] +
174      usage.cacheRead * p.cacheRead +
175      usage.output * p.output) /
176    1_000_000
177  );
178};
179
180// What a 1h main-conversation request's cache writes cost over 5m ones.
181export const premiumOf = (model: string, usage: Usage): number | null => {
182  const p = rates(model, promptTokensOf(usage));
183  if (!p) return null;
184  return (
185    (usage.cacheWrite *
186      p.input *
187      (WRITE_MULTIPLIER["1h"] - WRITE_MULTIPLIER["5m"])) /
188    1_000_000
189  );
190};
191
192// What losing the entry adds to the next prompt: writing the prefix again instead of reading it.
193export const missCostOf = (
194  model: string,
195  promptTokens: number,
196  ttl: Ttl,
197): number | null => {
198  const p = rates(model, promptTokens);
199  if (!p) return null;
200  return Math.max(
201    0,
202    (promptTokens * (p.input * WRITE_MULTIPLIER[ttl] - p.cacheRead)) /
203      1_000_000,
204  );
205};
206
207export type Decision = {
208  warmUsd: number;
209  missUsd: number;
210  probability: number;
211  expectedUsd: number;
212  isWarm: boolean;
213  // Set when a refresh does not pay: the prompt is under the size where the expected saving reaches MIN_SAVINGS_USD.
214  reason?: string;
215};
216
217const breakEvenAt = (
218  p: Price,
219  ttl: Ttl,
220  probability: number,
221  outputTokens: number,
222): number | null => {
223  const savedPerToken =
224    probability * (p.input * WRITE_MULTIPLIER[ttl] - p.cacheRead) - p.cacheRead;
225  if (savedPerToken <= 0) return null;
226  return Math.ceil(
227    (MIN_SAVINGS_USD * 1_000_000 + outputTokens * p.output) / savedPerToken,
228  );
229};
230
231// A tiered model breaks even in its short tier, or else just over it at the long tier's price.
232const breakEvenOf = (
233  entry: Price | Tiered,
234  ttl: Ttl,
235  probability: number,
236  outputTokens: number,
237): number | null => {
238  if (!("upTo" in entry))
239    return breakEvenAt(entry, ttl, probability, outputTokens);
240  const short = breakEvenAt(entry.short, ttl, probability, outputTokens);
241  if (short !== null && short <= entry.upTo) return short;
242  const long = breakEvenAt(entry.long, ttl, probability, outputTokens);
243  return long === null ? null : Math.max(long, entry.upTo + 1);
244};
245
246export const decide = (
247  model: string,
248  promptTokens: number,
249  ttl: Ttl,
250  phase: "run" | "idle",
251  outputTokens: number,
252): Decision | null => {
253  const entry = entryOf(model);
254  const missUsd = missCostOf(model, promptTokens, ttl);
255  if (!entry || missUsd === null || promptTokens <= 0) return null;
256  const p = priceAt(entry, promptTokens);
257  const warmUsd =
258    (promptTokens * p.cacheRead + outputTokens * p.output) / 1_000_000;
259  const probability = phase === "idle" ? IDLE_CONTINUATION : 1;
260  const expectedUsd = probability * missUsd - warmUsd;
261  const isWarm = expectedUsd >= MIN_SAVINGS_USD;
262  const breakEven = isWarm
263    ? null
264    : breakEvenOf(entry, ttl, probability, outputTokens);
265  const where = `${model} at ${ttl} (${phase})`;
266  const reason = isWarm
267    ? undefined
268    : breakEven === null
269      ? `a refresh never saves on ${where}`
270      : `${formatTokens(promptTokens)} tokens is below the ${formatTokens(breakEven)} break-even on ${where}`;
271  return { warmUsd, missUsd, probability, expectedUsd, isWarm, reason };
272};
273
274// A refresh that read under half the prefix found the entry gone and wrote it again.
275export const outcomeOf = (
276  reply: ForkReply,
277  usage: Usage,
278  promptTokens: number,
279): Pick<Refresh, "result" | "detail"> => {
280  if (usage.cacheRead >= promptTokens / 2) return { result: "warmed" };
281  if (reply.isAnswered) return { result: "expired" };
282  return {
283    result: "failed",
284    detail:
285      reply.reason === "api-error"
286        ? `${reply.error} ${reply.status ?? ""}`.trim()
287        : reply.reason,
288  };
289};
290
291export const noticeOf = (entry: Refresh): Pick<Notice, "head" | "detail"> => {
292  const cost = `${entry.usage ? `read ${formatTokens(entry.usage.cacheRead)} · ` : ""}${entry.costUsd === null ? "cost unknown" : formatUsd(entry.costUsd)}`;
293  if (entry.result === "expired")
294    return {
295      head: "Cache had expired",
296      detail: `the refresh rewrote it · ${cost}`,
297    };
298  if (entry.result === "failed")
299    return {
300      head: "Cache refresh failed",
301      detail: entry.detail ? `${entry.detail} · ${cost}` : cost,
302    };
303  return {
304    head: "Cache warmed",
305    detail: `${cost} · saves ${entry.savesUsd === null ? "unknown" : formatUsd(entry.savesUsd)} vs rewrite`,
306  };
307};
308
309export const formatUsd = (usd: number): string => {
310  const sign = usd < 0 ? "-" : "";
311  const value = Math.abs(usd);
312  return `${sign}$${value > 0 && value < 0.01 ? value.toPrecision(2) : value.toFixed(2)}`;
313};
314
315export const formatTokens = (n: number): string =>
316  n >= 1_000_000
317    ? `${(n / 1_000_000).toFixed(1)}M`
318    : n >= 1000
319      ? `${(n / 1000).toFixed(1)}k`
320      : String(n);
321
322export const formatDuration = (ms: number): string => {
323  const s = Math.max(0, Math.round(ms / 1000));
324  if (s >= 3600)
325    return `${Math.floor(s / 3600)}h${Math.floor((s % 3600) / 60)}m`;
326  if (s >= 60) return `${Math.floor(s / 60)}m${s % 60 ? `${s % 60}s` : ""}`;
327  return `${s}s`;
328};
329
types/index.d.ts 129 lines
1export type Ttl = "5m" | "1h";
2
3export type Usage = {
4  input: number;
5  output: number;
6  cacheRead: number;
7  cacheWrite: number;
8};
9
10export type Refresh = {
11  at: number;
12  model: string;
13  usage: Usage | null;
14  costUsd: number | null;
15  // The rewrite the next prompt avoids, less this refresh's cost; earned only if a prompt follows before expiry.
16  savesUsd: number | null;
17  result: "warmed" | "expired" | "failed";
18  detail?: string;
19};
20
21export type Status =
22  | { state: "waiting" }
23  | {
24      state: "scheduled";
25      nextAt: number;
26      phase: "run" | "idle";
27      expectedUsd: number;
28    }
29  | { state: "refreshing" }
30  | { state: "stopped"; reason: string };
31
32// How Clawd behaves in the pane and the band: sipping while a refresh runs, hopping after
33// a warm one, dozing off over a cold mug after a failure or an expired cache.
34export type Mood = "warming" | "warmed" | "cold";
35
36// How a notice ends: a refresh under way stays until its outcome replaces it,
37// one during a turn fades after a few seconds, and one in an idle session
38// holds still from then on until the next prompt.
39export type NoticeEnding = "stays" | "fades" | "holds";
40
41// The band's line: `head` is the highlighted outcome and `detail` the dim rest.
42// `startedAt` is when the notice appeared, `since` when its mood began and
43// `heldAt` when Clawd stopped moving in a held notice, in epoch milliseconds;
44// `prompt` counts the prompts before the refresh it tells of.
45export type Notice = {
46  ttl: Ttl;
47  head: string;
48  detail: string;
49  mood: Mood;
50  ending: NoticeEnding;
51  startedAt: number;
52  since: number;
53  heldAt: number | null;
54  prompt: number;
55};
56
57export type Totals = {
58  refreshes: number;
59  costUsd: number;
60  // The fees of refresh chains that no kept prompt followed.
61  wastedUsd: number;
62  kept: number;
63  keptUsd: number;
64  // 1h reads a 5m cache would have lost, with no refresh needed.
65  bridgedUsd: number;
66  // What 1h main-conversation cache writes cost over 5m ones.
67  premiumUsd: number;
68};
69
70// Totals across sessions, kept in $.store; `since` is when counting began, in epoch milliseconds.
71export type AllTime = Totals & { since: number };
72
73// The refreshes each lifetime may send while the session is idle.
74export type IdleLimits = { "5m": number; "1h": number };
75
76export type Page = "main" | "config" | "analytics";
77
78// The band above the prompt during a refresh: Clawd beside the notice, the notice as one line, or nothing.
79export type BandStyle = "default" | "simplified" | "off";
80
81// The main conversation's last request: the prefix a fork replays and keeps warm.
82export type Anchor = {
83  at: number;
84  lastAt: number;
85  model: string;
86  promptTokens: number;
87  ttl: Ttl;
88  refreshes: number;
89  // Refreshes sent while the session was idle; the idle limit counts these.
90  idleRefreshes: number;
91  // What this chain's refreshes cost: wasted unless the next prompt is kept.
92  feeUsd: number;
93  isStopped: boolean;
94};
95
96// Kept in state so that a reload, which a lifetime switch causes, can re-arm the timer.
97export type Warming = {
98  anchor: Anchor | null;
99  isRunning: boolean;
100  outputTokens: number;
101};
102
103declare module "claude-code" {
104  interface PluginState {
105    "cache-warmer": {
106      // This session's lifetime; `defaultTtl` is the saved one new sessions start with.
107      ttl: Ttl;
108      defaultTtl: Ttl;
109      // Set when the session page chose `ttl`, so a reload keeps it instead of the default.
110      isSessionTtl: boolean;
111      idleLimits: IdleLimits;
112      isForced: boolean;
113      // Set by the first main-thread response: the lifetime cannot change until /clear or a new session.
114      isLocked: boolean;
115      // While on, the main page lists the newest refreshes and a JSONL log records refreshes and stops.
116      isDebug: boolean;
117      bandStyle: BandStyle;
118      page: Page;
119      refreshes: Refresh[];
120      status: Status;
121      notice: Notice | null;
122      totals: Totals;
123      allTime: AllTime;
124      now: number;
125      warming: Warming;
126    };
127  }
128}
129