Token-saver mod: quiet bash, trim output, cache band, /tokens, cold-cache compaction veto, priced model-switch guard, keep-warm pings, agents that re-read…

Fewer tokens per turn, and a Context pane that tells the truth.
A Claude Code mod (an in-process plugin of function hooks) that quiets noisy commands before they run, trims huge output before Claude reads it, refuses a /compact that would re-send a cold cache, keeps the prompt cache warm while you think, prices your skills per turn, and shows a receipt it can stand behind. MIT. Works in the terminal, the desktop app, and on a phone.
claude plugin marketplace add dbrownjave/claude-token-saver
claude plugin install token-saver@token-saver
That installs the mod, from a terminal, at user scope; the desktop app picks it up too. For the Python modules and the settings preflight as well, clone and run the installer:
git clone https://github.com/dbrownjave/claude-token-saver && cd claude-token-saver && ./install.sh
Then open a new session and type /tokens.
<img src="site/img/pane-terminal-dark.png" width="720" alt="The Context pane in the Claude Code terminal after /tokens: context fill against the 1M window, the auto-compact mark, cache warmth, and Clear, Compact and Later buttons.">
/tokens in the terminal, real screenshot. Light or dark follows your GitHub theme; the pane follows your terminal's Theme.
True numbers. The pane's Saved figure counts only what the plugin itself did: trimmed output, compactions it vetoed, and keep-warm pings net of their cost. Claude's own prompt-cache reads are shown beside it and never added in; a session with 150k cache reads and nothing trimmed says Saved 0 tokens, and a test holds it to that. Estimates carry a ≈. Dollars appear only on API billing with a rate derived from your bill, never on a subscription.
Docs: docs/claude-mods.md is a full reference for writing Claude Code mods, written from the engine's own type definitions. The repo carries two skills so Claude knows how to edit this mod (mod-authoring) and ship it (release). Site: site/index.html. Contributing: CONTRIBUTING.md.
Each engineer installs this on their own machine and turns on only the modules they want. Nothing is forced. A bare install copies files and enables zero modules.
unzip claude-token-saver.zip
cd claude-token-saver
./install.sh
That is the whole install. No questions. It:
~/.claude/token-saver/.claude plugin install when your Claude Code accepts it. The marketplace is registered from a staged copy under ~/.claude/token-saver/pack, so you can delete the download afterwards. If the build refuses the mod, the Python hooks cover the same ground and it says so.settings.json. Hooks you already have stay. For each one that overlaps, it prints one line saying how the two coexist, or that it left ours off (for example when you already have a status line). Nothing of yours is edited or reordered.While it works, an ASCII gold coin spins above the step list, a progress bar with a tick per step and a pill naming the current step fills underneath it, and each step ticks as it lands. It is a lit, textured disc in the spirit of David Haubner's ASCII Bitcoin animation, without the B; --size sets its height and --emblem T puts a raised letter on the face. On a pipe, in CI, or with --plain (or TOKEN_SAVER_PLAIN=1) you get plain lines instead. NO_COLOR is honored. python3 scripts/coin.py --demo shows it without installing anything.
Run it again after updating the pack; it restages the mod and Claude picks it up on the next session or /reload-plugins. ./install.sh --dry-run shows the plan without writing. ./install.sh --pick is the module picker if you want to choose. ./install.sh --uninstall removes the mod, our hooks, rules and skills, and leaves everything else.
Requires python3 (stdlib only). On Windows there is no bash; run the same one-shot directly:
python manage.py setup
Build the zip you hand to others with scripts/dist.sh. It runs the self-test, validates the mod, and writes dist/claude-token-saver-<version>.zip from a whitelist.
Other entry points:
./install.sh --list
./install.sh --enable cache-guard
./install.sh --disable trim-output
./install.sh --project --enable rules,quiet-bash # one repo only
python3 manage.py status
Mods are in-process plugins. They can rewrite a tool call and draw UI. Settings hooks cannot. ./install.sh installs it for you; these are the manual equivalents:
claude plugin marketplace add .
claude plugin install token-saver@token-saver
# session already open:
# /reload-plugins
Or one session, no marketplace:
claude --plugin-dir ./plugins/token-saver
Toggles live on the plugin, not in a settings splice: quietBash, trimOutput, cacheBand, compactHint, compactGuard, longCacheTtl, keepWarm, keepWarmPings, modelGuard. They show up as rows in /config. Disable the whole thing with /plugin disable token-saver@token-saver.
The mod registers a progress tool. When Claude runs a job with stages, it calls the tool as each stage starts, waits, fails or ends, and a bar appears above the prompt.
The bar is a port of the Effort slider's own shader from the Claude app: a 14 px squared track of tiny rounded cells in three rows, lit by bursts that race out from the head every 0.3–0.75 s as Manhattan-distance wavefronts, a five-step white→ink ramp with breathing top cells, and a charged bed that deepens toward the head and fades over the first quarter. Tuned brighter than the slider. The stage and count ride in a gradient pill in the bar's own colour, trailing the head; there is no status icon, the colour and the pill's ✕ / ? / ✓ carry state. Purple running, amber waiting, red failed, green done. A finished row keeps sparking faintly for a minute, then holds still. Frames are a pure function of the band's 70 ms tick, so they are deterministic and testable.
In the terminal the same cells draw as a one-row Raster of half-block squares with a coloured text pill; where Raster is missing, small-square glyphs. × removes a row; remove: true from the tool does the same. /loadout actions use the same rows: one stage per skill, green when done, gone eight seconds later. The status line reads "Progress" while any bar is up.
A settings hook can only add a note before /compact. The mod sits on the compaction itself:
| Trigger | What happens |
|---|---|
/compact, cache warm | Runs. The keep-list (task, files touched, decisions, failing tests, next steps, exact errors) is appended to the summarizer's instructions. |
/compact, cache cold | Refused. One line names the idle time and the tokens a compaction would re-send, and points at /handoff then /clear. |
/compact force | Runs anyway. Keep-list still appended. |
| auto-compaction | Never refused. Keep-list appended. Blocking it would let the window overflow. |
| idle compaction (Claude Code 2.1.299+) | Never refused. Keep-list appended. The pane names it as Claude Code's own work, with the before and after size, and never counts it in Saved. Keep-warm stops for that stretch, since the prefix it would re-read is gone. Claude Code runs it on the 1-hour cache, for sessions over 200k tokens (CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, 100k floor), about 54 minutes after the last reply. Opt out with "idleCompaction": false. |
| subagent transcripts | Left alone. |
Idle compaction card (the fourth card in the pane, and a row in /tokens list). It counts down from your last reply to when Claude Code would compact the session, about 54 minutes on the one-hour cache, with a bar that fills as the moment nears. It reads the same settings Claude Code does. It says Off when "idleCompaction": false, auto-compact is off, or DISABLE_COMPACT is set. It waits with a size bar while the session is under the floor (200k, or your CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, never under 100k), and says when the session is on the 5-minute cache, where it never runs. The time is marked ≈ because Claude Code can tune the moment.
"Cold" means idle longer than the prompt-cache TTL since the last response. The TTL follows Claude Code: a reply's cache writes say 5 minutes or 1 hour, a model switch reports it, and an idle compaction only happens on the 1-hour cache. Until one of those is seen it is 5 minutes. longCacheTtl forces 1 hour. /tokens shows which state you are in.
Keep-warm (keepWarm, on by default) applies only to API billing with the 5-minute TTL, and turns itself off once Claude Code is seen on the 1-hour cache. While you are idle, it re-reads the session's own cached prefix with one tiny request ($.model.fork) about 75 seconds before the cache lapses. A read costs about 0.1× the input price and restarts the TTL. Your next message then hits the cache instead of paying a 1.25× re-write.
keepWarmPings pings per idle stretch (default 5, about 20 minutes, the break-even if you come back half the time)./tokens and the Context pane book what the pings cost and the re-writes they avoided, so the net can be negative if you stay away.The app's own "Switch model?" dialog has no number in it. The mod sits on the switch (PreModelSwitch), which carries the context size, whether the cache is warm, and the engine's own list-price estimate of re-caching that context on the target model:
| Switch | What happens |
|---|---|
| cache cold | Goes through. One toast: free, the next message re-reads everything either way. |
| cache warm, under 20k tokens | Goes through. One toast: cheap, N tokens re-read once. |
| cache warm, 20k tokens or more | One dialog with the cost (tokens at 1.25× the input price, in dollars at the target model's list price, or as % of the 5-hour window on a subscription) and three buttons: Switch, One message, Stay. |
| One message | The switch is refused, but the next reply alone goes to the other model. The session stays put, so its warm cache survives every turn after it. The status line under the prompt says so until that turn ends. |
| Stay | The switch is refused. The Receipt books the cold re-write you did not pay (142k tokens held → 177k at 1.25×), on the same basis as a vetoed compaction. |
| Switch | Goes through. The Receipt lists the cold re-read as paid, never as a saving. |
| subagents, SDK and Remote Control switches | Never questioned. |
The Context pane's Cache card carries the same figure before you open the model menu ("Switch model ≈ $0.53", or "cheap", or "free"), priced at this session's own rate; the dialog uses the engine's estimate for the target model. modelGuard: false turns the whole guard off.
Every term the Context pane uses (context, the prompt cache, re-cache, keep-warm, marks, what was saved) has one definition, kept in plugins/token-saver/hooks/glossary.js: what it is, its live value in your session, and what to do. Press ? in the pane to number its parts and explain each one with your numbers; More in the glossary → opens the full glossary at that term. /tokens learn prints the whole glossary as text, and /tokens learn <term> (an id or a name, such as cache or keep-warm) prints just that term. Money appears only on API billing with a known rate, never on a subscription.
Dev loop: claude plugin validate ./plugins/token-saver then claude plugin test ./plugins/token-saver.
| What | Where it works |
|---|---|
| Quiet bash + trim | CLI, Desktop, VS Code panel, claude -p |
| Cache band above the prompt | CLI and Desktop only. The Context pane closed into one row: a short fire bar, the percent in your threshold colour, the cache cells and what the cache means for your next message, what was saved, ⌄ to open the pane and × to hide the band (/tokens show brings it back). Past a mark, the cache-aware hint sits on a second line. On a narrow terminal it drops the "Reuses" figure first, then the bar. VS Code does not draw mod UI; use its cache clock. |
/tokens | Opens the Context pane. Closed: Context 96k / 200k (48%) in the app's own Context window style (the figures grey, the bar in your threshold colour), one full-width bar drawn with the pack's fire shader (ticks at your marks, the auto-compact buffer dim at the end), the cache (five tiny cells and what it means for your next message) and what was saved, then Clear / Compact / Later with the recommended one highlighted; Compact is drawn unavailable while the cache is cold. ⌄ opens: Saved (tokens, the share of input cut, dollars on the API only, a Receipt line by line), three cards (your next mark with messages to go at the recent growth per message, keep-warm on the API or the five-hour window on a subscription, the cache), Claude's working memory by kind like /context, and groups (MCP tools, memory files with duplicates flagged, custom agents, skills) whose buttons run /mcp, /memory, /agents, /loadout. Worth is shown in the currency you pay in; never a dollar on a subscription. cardBars in /config calms the card bars to an ember. /tokens list prints the text form; hide and show toggle the band. |
| Threshold toast | Once per threshold crossed (40, 60, 75 percent by default), with the cache-aware hint. |
| First-run welcome | One toast the first time the mod loads on a machine, saying what is now on. |
| Compaction guard | Everywhere the mod loads. |
/loadout | Opens a pane: every skill with cost per turn and last use, a Park button on each active one, Link here / Unpark on each parked one, Park N unused in the header. Esc closes. /loadout list is the text form. CLI and Desktop; the VS Code panel gets the text. |
Same ~/.claude/token-saver/quiet.json as the Python hook. Do not run both quiet-bash implementations at once or commands get rewritten twice.
The mod does not touch the system prompt every turn. That would bust the cache. The band hint does not type a command into the box. Your marks live in ~/.claude/token-saver/thresholds.json, copied once and never overwritten. Defaults: 40% note, 60% /handoff then /clear, 75% /compact if warm and a new chat if cold. /context in VS Code stays the category grid. The panel will not draw this band. /tokens prints the same hint. Enabling the Python quiet-bash hook while the mod is on is refused. dash shows cache read vs cache write per session. That is request accounting, not a bill. The named miss cause stays on /usage.
Python dash / bench stay. Mods do not read history.
./install.sh --enable statusline,quiet-map
| Module | What it does |
|---|---|
statusline | CLI status bar: ● cache 98% 1h 12m ctx 41% or ▲ COLD +461k if you type. Does not overwrite an existing statusLine. VS Code’s chat panel already has a cache clock — this is for the terminal. |
quiet-map | Copies ~/.claude/token-saver/quiet.json if you do not already have one. Edit it to add pnpm, kubectl, company wrappers. Never overwritten on reinstall. |
dash now ranks the noisiest Bash commands from your last week of transcripts (count, est. tokens, whether a quiet.json rule already covers them).
Add your own rewrite:
{
"id": "kubectl-get",
"pattern": "^kubectl\\s+get\\b",
"unless": ["-o name"],
"append": " -o name",
"enabled": true
}
Every skill under ~/.claude/skills costs tokens on every turn: its name and description sit in the system prompt's skill listing. The body only loads when you invoke it. Thirty skills is a few hundred tokens a turn, forever.
./install.sh skills # active skills, tokens/turn, last use, · = unused 30+ days
./install.sh skills pick # interactive: choose what to park
./install.sh skills park gsap-* # by name, glob, @group, or 'unused'
In a session with the mod: /loadout opens the pane; /loadout gsap-* parks; /loadout back gsap-react brings one back everywhere; /loadout link gsap-react for this repo only. Instant, no model turn. The picker needs a TTY so it stays in the terminal.
| Action | What happens | Undo |
|---|---|---|
park | Moves the skill (or its symlink) to ~/.claude/skills-parked/ and records where it came from in .parked.json. | unpark |
unpark | Moves it back to its original place. | park |
link | Symlinks a parked skill into this repo's .claude/skills/. Loads only when you work here. | unlink |
unlink | Removes that symlink only. The skill stays parked. | link |
Nothing is ever deleted. Changes take effect in the next session (/clear or restart). "Last use" comes from a ripgrep over your local transcripts for Skill calls, run through the claude binary (BSD grep takes 30s on a big transcript dir) and cached for an hour (--rescan to refresh). It is a hint, not a bill. Parked skills that still get used are called out so you can link them where they belong. Links are machine-local: add .claude/skills/<name> to .gitignore if teammates do not have the parked skill.
The /token-saver skill routes skill bloat here and is told never to move skill folders by hand.
You should not have to run an installer per session. Three things close the loop:
| Where | What | Cost |
|---|---|---|
| Session start (mod) | Reads the repo's manifests, names parked skills that fit, shows one toast and a log line. | 0 tokens |
Session start (Python session-audit hook) | Same one line, appended to the budget line so Claude knows too. | ~30 tokens, only when there is a match |
/repo-skills skill | When you ask "do we have a skill for X" or start GSAP/SwiftUI/Higgsfield work, Claude runs skills.py suggest --for "X", tells you what fits, and links it on a yes. | loads on demand |
./install.sh skills suggest # parked skills that fit this repo
./install.sh skills suggest --for "scroll animation"
Signals: package.json deps, tsconfig.json, Package.swift, *.xcodeproj, *.swift, pyproject.toml, requirements.txt, Cargo.toml, go.mod, Gemfile, Podfile, Tailwind configs, and libraries referenced from an index.html. Dependency names and file types are strong signals. Aliases (next→react, three→3d, gsap→animation) and broad words (javascript, frontend) are weak hints: they can nudge a ranking but never put a skill in the link command. Matching is on skill names and descriptions, not bodies. Already-active matches are listed first so Claude uses what is loaded.
The session-start toast shows once a day per repo; the log line shows every time. Needs python3 or python on PATH.
Self-test (temp dir, never touches ~/.claude):
python3 scripts/test_skills.py
./install.sh dash # free — tokens from your local Claude Code sessions
./install.sh dash --watch # refresh every 2s
./install.sh bench # free — hook compression: used / saved / result preview
./install.sh bench --live # A/B against Claude (asks first; spends tokens)
Same via Python:
python3 scripts/tui.py dash
python3 scripts/tui.py bench
python3 scripts/tui.py bench --live --prompt "git status then name the 3 newest files"
| Command | Calls Claude? | What “saved” means |
|---|---|---|
dash | no | Real tokens your past sessions used. Does not invent a savings %. |
bench | no | Tokens the hooks strip from command output (used vs after). Shows the trimmed result. |
bench --live | yes, twice | OFF arm vs ON arm. Shows tokens, $, and both result texts so you can judge quality. |
Live A/B is capped at 4 turns and $0.50 per arm. Tools are read-only plus Bash. Confirm before it spends.
| Path | Scope | |
|---|---|---|
| Files | ~/.claude/token-saver/ | You, all repos |
| Hooks spliced into | ~/.claude/settings.json | You, all repos |
| Rules (if enabled) | ~/.claude/rules/token-budget.md | You, all repos |
| Skill (if enabled) | ~/.claude/skills/token-saver/ | You, all repos |
| State | ~/.claude/token-saver/enabled.json | What you turned on |
Your existing hooks stay. We only add or remove entries whose command path contains token-saver/. A timestamped backup of settings.json is written before each change.
Claude Code on the web / cloud VMs does not see ~/.claude. This pack is for the local CLI/desktop app.
./install.sh --project --enable rules,quiet-bash
Writes hooks into .claude/settings.local.json (gitignored) and files into .claude/token-saver/.
Recommended (on if you press Enter):
| id | What it does |
|---|---|
rules | Standing policy: /clear on topic change, @file, Haiku subagents |
skill | /token-saver — loads only when you ask about tokens |
session-audit | Short budget line at session start |
quiet-bash | Rewrites git status / git log / tests to short output |
trim-output | Caps huge successful bash stdout (never trims failures) |
Opt-in (off until you enable them):
| id | What it does |
|---|---|
compact-keep | Keep-list injected before /compact |
cache-guard | Asks before a mid-session model switch when the cache is warm |
slim-startup | Caps bash at 8k chars; sets CLAUDE_CODE_DISABLE_ARTIFACT=1 (reversible) |
deny-secrets | Blocks Read on .env, secrets/, node_modules |
thinking-cap | MAX_THINKING_TOKENS=8000 |
no-connectors | Disables claude.ai connectors (only if you do not use Slack/Jira/etc) |
no-remote | Disables remote-control tool defs |
slim-startup does not write enableArtifact: false. That key can turn Artifacts off in a way you cannot turn back on from another file. The env var is reversible: disable the module and it is removed.
IT can put the zip on an internal drive and say:
Install it yourself. Recommended:
./install.sh --enable rules,skill,quiet-bash,session-audit
Each engineer still chooses. Nobody’s repo settings change unless they pass --project.
Open a new Claude Code session and run /context. That is the before/after measurement.
/token-saver if you enabled the skill
/mcp disable unused servers (biggest startup win after Artifacts)
/clear new task
/compact only while the cache is warm
trim-output depends on updatedToolOutput, which has been flaky on some 2.1.x builds. quiet-bash is the reliable layer.PreModelSwitch event. If the app still shows its own "Switch model?" dialog first, tick "Don't ask again" there; the mod's priced dialog is the one with the buttons that matter.settings.json stays.hooks/register.js 3285 lines1/**
2 * Token-saver mod. In-process plugin of function hooks.
3 *
4 * Sandbox rules: a hooks module may import only its own files and
5 * "claude-code". No node:* imports, no process/env globals. Files go through
6 * $.fs, environment through $.env, time through $.clock.
7 *
8 * VS Code's chat panel runs these hooks but does not draw UI.
9 */
10
11import { GLOSSARY } from './glossary.js'
12
13const LIMIT = 8000
14const HEAD = 2500
15const TAIL = 1500
16const MINUTE = 60 * 1000
17const TTL_SHORT = 5 * MINUTE
18const TTL_LONG = 60 * MINUTE
19const SWITCH_CHEAP = 20_000 // a model switch under this many context tokens gets a toast, not a dialog
20const BAND_TICK = 30 * 1000
21const KEEP_WARM_TICK = 15 * 1000
22const KEEP_WARM_LEAD = 75 * 1000 // the TTL runs from a request's start and a fork takes seconds: ping well before it lapses
23const IDLE_COMPACT_AT = 0.9 // Claude Code fires at 90% of the one-hour TTL (its default; tunable 50–95% on its side)
24const IDLE_COMPACT_MIN = 200_000 // its size floor; CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS moves it, never under 100k
25const IDLE_COMPACT_AFTER = 25 * MINUTE // Claude Code's idle compaction fires at 50–95% of the one-hour TTL; an in-turn auto-compaction comes seconds after a step
26const KEEP_WARM_PROMPT ='Keep-alive ping from the token-saver plugin. Reply with a single period and nothing else.'
27
28const DEFAULT_RULES = [
29 { id: 'git-status', pattern: '^git\\s+status\\b', unless: ['-sb', '-s'], replace: 'git status -sb' },
30 { id: 'git-log', pattern: '^git\\s+log\\b', unless: ['--oneline'], replace: 'git log --oneline -20' },
31 { id: 'git-diff', pattern: '^git\\s+diff\\s*$', replace: 'git diff --stat' },
32 { id: 'pytest', pattern: '^pytest\\b', unless: ['-q'], append: ' -q --tb=short' },
33 { id: 'npm-test', pattern: '^npm\\s+test\\b', unless: ['--reporter', '-- '], append: ' -- --reporter=dot' },
34 { id: 'pnpm-test', pattern: '^pnpm\\s+test\\b', unless: ['--reporter', '-- '], append: ' -- --reporter=dot' },
35 { id: 'cargo-test', pattern: '^cargo\\s+test\\b', unless: ['--quiet', '-q'], append: ' --quiet' },
36]
37
38const DEFAULT_LEVELS = [
39 { id: 'watch', pct: 40, hint: 'note' },
40 { id: 'handoff', pct: 60, hint: 'new-conversation' },
41 { id: 'compact', pct: 75, hint: 'compact-if-warm' },
42]
43
44const KEEP =
45 'When compacting, keep: current task, files touched, decisions, failing tests, ' +
46 'next steps, exact error messages. Drop: raw tool output, resolved errors, ' +
47 'exploratory file reads, repeated logs.'
48
49// Module state. A reload starts these over; nothing here needs to survive one.
50let lastUsage = null
51let lastStepAt = 0
52let savedChars = 0
53let rewrites = 0
54let vetoes = 0
55let rules = DEFAULT_RULES
56let levels = DEFAULT_LEVELS
57let pythonQuietOn = false
58let bandHidden = false
59let bandSurface = 'terminal' // where the band last drew: the desktop's native buttons drop a press that spans a redraw
60const totals = { turns: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, keptOut: 0, vetoTokens: 0, switchHeld: 0, switchPaid: 0, oneShot: 0, agentLapses: 0, agentLapseTok: 0 } // this session, from turn.step usage
61/**
62 * Subagent cache lapses. Every subagent request gets the 5-minute cache TTL, even where the main thread has an hour.
63 * An agent that idles past 5 minutes mid-run (a test suite, a build, a CI wait) re-writes its whole context at 1.25×
64 * on its next step. The mod cannot set a TTL; it measures the lapses and says which agent file would pay for
65 * `experimental.cacheTtl: 1h` (writes at 2× instead of 1.25×, so only agents that actually lapse come out ahead).
66 * - `agents`: the running ones, agentId → record; dropped when the agent answers
67 * - `agentTypes`: this session's sums per agent type (Explore, Plan, …), what the pane and /tokens read
68 * - `$.store` `lapses:<type>`: week and lifetime counts, so a line can say "3 times this week"
69 */
70const agents = new Map() // agentId → { type, model, lastStepAt, lapses, lapseWrite, otherWrite, steps }
71const agentTypes = new Map() // type → { lapses, lapseWrite, otherWrite, runs }
72let agentWeeks = {} // type → weekCount, read from $.store once per loadContext
73const LAPSE_RE = 1.15 // a lapse write at 1.25× that a longer cache would have made a hit at 0.1×
74const LONG_PREMIUM = 0.75 // what every other write would have cost extra at the 1-hour price (2× − 1.25×)
75let oneShot = null // { model } while the next main-thread turn goes to another model and the session stays put
76let limitBase = null // { pct, tokens } when the five-hour window was first seen: tokens per % of window
77let monthSaved = { key: '', tok: 0, usd: 0, sessionTok: 0, sessionUsd: 0 } // carried in $.store across sessions
78let announcedPct = 0 // highest threshold already toasted this session
79/**
80 * Keep-warm: while you are idle, re-read the session's own cached prefix ($.model.fork) shortly before the 5-minute TTL
81 * lapses, so your next message hits the cache instead of re-writing it. A read costs 0.1× fresh input and refreshes the
82 * TTL; a lapse costs a 1.25× re-write, so a ping pays while pings × 0.1 < chance-you-return × 1.15. The cap (default 5,
83 * about 20 minutes) assumes about even odds. Costs and savings are booked in fresh-input-token equivalents.
84 */
85const keepWarm = { on: false, want: false, streak: 0, pings: 0, misses: 0, costTok: 0, savedTok: 0, busy: false, refreshedAt: 0, stopped: '' }
86/**
87 * The engine's prompt-cache TTL. The mod API has no read for it, so it is learned: a main-thread step's usage may carry
88 * the write buckets (cache_creation.ephemeral_1h / _5m_input_tokens), a model switch carries cache_ttl, and Claude
89 * Code's idle compaction runs only on the one-hour cache (weakest: never overrides the other two). Until one is seen
90 * the TTL is 5 minutes. `longCacheTtl` forces one hour. On one hour, keep-warm turns itself off.
91 */
92const engineTtl = { value: '', via: '' } // '1h' | '5m' | '' (not seen yet)
93let longTtlOption = false
94function ttlNow() { return longTtlOption || engineTtl.value === '1h' ? TTL_LONG : TTL_SHORT }
95/** Record a TTL the engine reported. Returns true when the TTL in force changed. */
96function noteEngineTtl(value, via) {
97 if (value !== '1h' && value !== '5m') return false
98 if (via === 'idle compaction' && engineTtl.via && engineTtl.via !== via) return false
99 const before = ttlNow()
100 engineTtl.value = value
101 engineTtl.via = via
102 keepWarm.on = keepWarm.want && !keepWarm.stopped && ttlNow() !== TTL_LONG
103 return ttlNow() !== before
104}
105/** '1h' or '5m' from a response's cache-write buckets, '' when it wrote nothing or the buckets are absent. */
106function ttlOfUsage(u) {
107 const cc = u && u.cache_creation
108 if (!cc || typeof cc !== 'object') return ''
109 if ((Number(cc.ephemeral_1h_input_tokens) || 0) > 0) return '1h'
110 if ((Number(cc.ephemeral_5m_input_tokens) || 0) > 0) return '5m'
111 return ''
112}
113let inTurn = false
114/** Claude Code's idle compaction as your settings configure it, and the last one seen this session. */
115const idleCfg = { off: '', minTokens: IDLE_COMPACT_MIN, minSet: false }
116let idleDone = null // { at, before, after } until the next reply
117
118/** Read what Claude Code itself reads: idleCompaction and autoCompactEnabled, the size floor, the compaction kill switches. */
119async function loadIdleConfig($) {
120 let s = null
121 try { s = await $.settings.read() } catch { s = null }
122 const env = (s && s.env) || {}
123 let raw, kill
124 try { raw = await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS') } catch { raw = undefined }
125 try { kill = (await $.env.get('DISABLE_COMPACT')) || (await $.env.get('DISABLE_AUTO_COMPACT')) } catch { kill = '' }
126 if (raw === undefined || raw === null || raw === '') raw = env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS
127 const n = raw === undefined || raw === null || raw === '' ? NaN : Number(raw)
128 idleCfg.minSet = Number.isFinite(n)
129 idleCfg.minTokens = idleCfg.minSet ? Math.max(100_000, n) : IDLE_COMPACT_MIN
130 idleCfg.off = s && s.idleCompaction === false ? 'setting'
131 : (s && s.autoCompactEnabled === false) || kill || env.DISABLE_COMPACT || env.DISABLE_AUTO_COMPACT ? 'auto-compact' : ''
132}
133
134/**
135 * The Idle compaction section: when Claude Code would compact this session while you are away, as your settings have it.
136 * It runs only on the one-hour cache, above the size floor, about 54 minutes after the last reply. Time is an estimate (≈):
137 * Claude Code may tune the moment, and it skips when the cache already lapsed or you are near a usage limit.
138 */
139function idleView(used, ttl, clock, autoCompactOn) {
140 const at = Math.round(IDLE_COMPACT_AT * TTL_LONG)
141 const atMin = Math.round(at / MINUTE)
142 const floor = `${fmtK(idleCfg.minTokens)} tokens${idleCfg.minSet ? ' (your setting)' : ''}`
143 const v = (accent, tone, fill, strong, foot, ink = 'inactive', state = '', leftMin = 0) => ({ accent, tone, bar: { fill, ink }, strong, foot, state, leftMin })
144 if (idleCfg.off === 'setting') return v('Off', 'inactive', 0, 'Off in your settings', '"idleCompaction": false', 'inactive', 'off')
145 if (idleCfg.off === 'auto-compact' || autoCompactOn === false) return v('Off', 'inactive', 0, 'Off: auto-compact is off', 'It runs only while auto-compact is on', 'inactive', 'off')
146 if (idleDone) {
147 const sizes = Number.isFinite(idleDone.before) && Number.isFinite(idleDone.after) ? `${fmtK(idleDone.before)} → ${fmtK(idleDone.after)}` : 'Summarized'
148 return v('Done', 'success', 1, `Compacted ${sizes}`, "Claude Code's own work, not counted in Saved", 'success', 'done')
149 }
150 if (ttl !== TTL_LONG) {
151 return engineTtl.value === '5m'
152 ? v('Not here', 'inactive', 0, 'Needs the one-hour cache', 'This session caches for 5 minutes', 'inactive', 'not-here')
153 : v('Waiting', 'inactive', 0, 'Needs the one-hour cache', 'Learned from the next reply', 'inactive', 'waiting')
154 }
155 if (!clock || !clock.known) return v('Waiting', 'inactive', 0, 'Starts after the first reply', `Then ≈${atMin}m after each reply, from ${floor}`, 'inactive', 'waiting')
156 if (used < idleCfg.minTokens) {
157 return v('Too small', 'inactive', used / idleCfg.minTokens, `${fmtK(used)} of ${fmtK(idleCfg.minTokens)}`, `Runs from ${floor}`, 'inactive', 'small')
158 }
159 if (inTurn) return v('Paused', 'inactive', 0, 'Claude is working', `The clock restarts at the reply: ≈${atMin}m`, 'inactive', 'paused')
160 const left = at - clock.idleMs
161 if (left > 0) {
162 const leftMin = Math.max(1, Math.ceil(left / MINUTE))
163 return v(`≈${leftMin}m`, PAL.WARM, clock.idleMs / at, `≈${leftMin}m left`, `${fmtK(used)} becomes a summary ≈${atMin}m after your last reply`, 'grad', 'counting', leftMin)
164 }
165 if (clock.warm) return v('Due', PAL.WARM, 1, 'Due now', 'Claude Code compacts in the last minutes of the cache', 'grad', 'due')
166 return v('Skipped', 'inactive', 0, 'Did not run this break', 'The cache lapsed first, or Claude Code has not turned it on for you', 'inactive', 'skipped')
167}
168// Progress rows above the prompt, driven by the `progress` tool the model calls.
169const PROGRESS_TOOL = 'mcp__token-saver__progress'
170const progressRows = new Map() // id -> { id, label, stage, step, total, state, target, shown, note }
171let progressTicker = null
172const STATE_COLOR = { running: '#8b7cf6', waiting: '#d9a441', failed: '#e5484d', done: '#30a46c' }
173const STATE_GLYPH = { running: '●', waiting: '?', failed: '!', done: '✓' }
174const SKILLS_PANE = 'loadout'
175let skillsData = null // last `skills.py status --json`
176let skillsBusy = false
177let skillsMsg = '' // last action's one-line result, shown in the pane footer
178
179async function readJson($, path) {
180 try {
181 return JSON.parse(await $.fs.read(path))
182 } catch {
183 return null
184 }
185}
186
187/** Home config first, project config overrides it. Missing files are fine. */
188async function homeDir($) {
189 return (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
190}
191
192/** python3, then python (Windows installs often ship only `python`). */
193async function runPython($, args, init) {
194 let lastErr
195 for (const exe of ['python3', 'python']) {
196 try {
197 return await $.process.run([exe, ...args], init)
198 } catch (err) {
199 lastErr = err
200 }
201 }
202 throw lastErr
203}
204
205/**
206 * One child process, streamed. Tries python3 then python. Yields { stream, text } pieces
207 * and finally { code }. Throws before the first piece when neither interpreter starts.
208 */
209async function* spawnPython($, args, init) {
210 let lastErr
211 for (const exe of ['python3', 'python']) {
212 let yielded = false
213 try {
214 for await (const piece of $.process.spawn({ argv: [exe, ...args], ...init })) {
215 yielded = true
216 yield piece
217 }
218 return
219 } catch (err) {
220 lastErr = err
221 if (yielded) throw err
222 }
223 }
224 throw lastErr
225}
226
227async function loadConfig($, cwd) {
228 await loadIdleConfig($)
229 const home = await homeDir($)
230 const dirs = []
231 if (home) dirs.push(`${home}/.claude/token-saver`)
232 if (cwd) dirs.push(`${cwd}/.claude/token-saver`)
233 rules = DEFAULT_RULES
234 levels = DEFAULT_LEVELS
235 for (const dir of dirs) {
236 const q = await readJson($, `${dir}/quiet.json`)
237 if (q && Array.isArray(q.rewrites) && q.rewrites.length) rules = q.rewrites
238 const t = await readJson($, `${dir}/thresholds.json`)
239 if (t && Array.isArray(t.levels) && t.levels.length) levels = t.levels
240 }
241 pythonQuietOn = false
242 if (home) {
243 const settings = await readJson($, `${home}/.claude/settings.json`)
244 pythonQuietOn = !!settings && JSON.stringify(settings.hooks || {}).includes('quiet_bash.py')
245 }
246}
247
248function quiet(cmd) {
249 if (!cmd || /&&|\|\||\||;/.test(cmd)) return null
250 if (/\brm\b|\bsudo\b|\bdd\b|\bmkfs\b|>\s|\/dev\//.test(cmd)) return null
251 for (const rule of rules) {
252 if (rule.enabled === false || !rule.pattern) continue
253 let re
254 try {
255 re = new RegExp(rule.pattern)
256 } catch {
257 continue
258 }
259 if (!re.test(cmd)) continue
260 if ((rule.unless || []).some((u) => cmd.includes(u))) continue
261 const next = rule.replace || (rule.append ? cmd + rule.append : null)
262 if (!next || next === cmd) return null
263 return { id: rule.id || 'custom', next }
264 }
265 return null
266}
267
268function trim(text) {
269 if (typeof text !== 'string' || text.length <= LIMIT) return text
270 const dropped = text.length - HEAD - TAIL
271 return text.slice(0, HEAD) + `\n…[token-saver trimmed ${dropped} chars]…\n` + text.slice(-TAIL)
272}
273
274function fmt(n) {
275 if (!n) return '0'
276 if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
277 if (n >= 1000) return (n / 1000).toFixed(1) + 'k'
278 return String(n)
279}
280
281function mins(ms) {
282 return Math.max(1, Math.round(ms / MINUTE))
283}
284
285/** 'claude-opus-5-5' → 'Opus 5.5'; an alias or unknown id is shown as given. */
286function modelName(id) {
287 const m = /^claude-([a-z]+)-(\d+)(?:-(\d+))?/.exec(String(id || ''))
288 if (!m) return String(id || 'the other model')
289 return `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
290}
291
292/** How this session pays: API dollars, or a subscription's 5-hour window (tokens per % of it, once the window has moved). */
293async function billing($) {
294 let u = null
295 try { u = await $.session.usage() } catch { /* no usage API */ }
296 const priced = !!(u && u.cost && Number.isFinite(u.cost.usd))
297 const five = (u && u.rateLimits || []).find((r) => r.kind === 'five_hour') || null
298 const inputAll = totals.input + totals.cacheRead + totals.cacheWrite
299 const tokPerPct = limitBase && five && five.percentUsed - limitBase.pct >= 1 ? (inputAll - limitBase.tokens) / (five.percentUsed - limitBase.pct) : 0
300 return { priced, tokPerPct }
301}
302
303/**
304 * A subscription on usage credits: a five-hour window exists and is either spent (100%) or billed beside (a dollar
305 * cost next to a window). A plain API key has no five-hour window. The engine ignores a 1-hour subagent cacheTtl
306 * while on credits, so the recommendation is not made there; the measurements still are.
307 */
308function onCredits(usage) {
309 const five = (usage && usage.rateLimits || []).find((r) => r.kind === 'five_hour') || null
310 if (!five) return false
311 return Number(five.percentUsed) >= 100 || !!(usage.cost && Number.isFinite(usage.cost.usd))
312}
313
314/** ISO week key, UTC: 2026-W41. */
315function isoWeek(ms) {
316 const d = new Date(ms)
317 const day = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()))
318 const dow = day.getUTCDay() || 7
319 day.setUTCDate(day.getUTCDate() + 4 - dow)
320 const jan1 = new Date(Date.UTC(day.getUTCFullYear(), 0, 1))
321 const week = Math.ceil(((day - jan1) / 86_400_000 + 1) / 7)
322 return `${day.getUTCFullYear()}-W${String(week).padStart(2, '0')}`
323}
324
325/** A finished subagent run folds into its type's session sums; a run that lapsed also rolls into the store's week count. */
326async function rollAgent($, rec) {
327 const t = agentTypes.get(rec.type) || { lapses: 0, lapseWrite: 0, otherWrite: 0, runs: 0 }
328 t.lapses += rec.lapses; t.lapseWrite += rec.lapseWrite; t.otherWrite += rec.otherWrite; t.runs += 1
329 agentTypes.set(rec.type, t)
330 if (!rec.lapses) return
331 try {
332 const key = `lapses:${rec.type}`, weekKey = isoWeek(await $.clock.now())
333 const prev = (await $.store.get(key)) || {}
334 const sameWeek = prev.weekKey === weekKey
335 const next = {
336 weekKey, weekCount: (sameWeek ? Number(prev.weekCount) || 0 : 0) + rec.lapses, weekTok: (sameWeek ? Number(prev.weekTok) || 0 : 0) + Math.round(rec.lapseWrite * 1.25),
337 allCount: (Number(prev.allCount) || 0) + rec.lapses, allTok: (Number(prev.allTok) || 0) + Math.round(rec.lapseWrite * 1.25),
338 }
339 await $.store.set(key, next)
340 agentWeeks[rec.type] = next.weekCount
341 } catch { /* no store */ }
342}
343
344/** Week counts per agent type from the store, for "lapsed 3 times this week". */
345async function loadAgentWeeks($, now) {
346 const out = {}
347 try {
348 const weekKey = isoWeek(now)
349 for (const key of await $.store.keys()) {
350 if (!key.startsWith('lapses:')) continue
351 const v = await $.store.get(key)
352 if (v && v.weekKey === weekKey) out[key.slice(7)] = Number(v.weekCount) || 0
353 }
354 } catch { /* no store */ }
355 return out
356}
357
358/** One question, 2-4 labels: `$.ui.ask` where the engine has it, else the AskUserQuestion tool call it stands for. Rejects when dismissed. */
359async function askUser($, question, labels, header) {
360 try {
361 return await $.ui.ask(question, { options: labels, header })
362 } catch (err) {
363 if (!(err instanceof TypeError)) throw err // dismissed, or a -p run: the caller's business
364 }
365 // an engine without $.ui.ask: the AskUserQuestion tool call it stands for (the tool's arguments sit beside `tool`)
366 const r = await $.tool.call({ tool: 'AskUserQuestion', questions: [{ question, header, options: labels.map((l) => ({ label: l, description: l })), multiSelect: false }] })
367 if (!r || r.deny) throw new Error((r && r.deny) || 'dismissed')
368 const answers = r.result && r.result.answers
369 const v = answers && (answers[question] !== undefined ? answers[question] : Object.values(answers)[0])
370 if (typeof v !== 'string') throw new Error('dismissed')
371 return v
372}
373
374function sentOf(u) {
375 if (!u) return 0
376 return (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0)
377}
378
379function hitPct(u) {
380 const sent = sentOf(u)
381 return sent ? Math.round((100 * ((u && u.cache_read_input_tokens) || 0)) / sent) : 0
382}
383
384/** Live context fill from the engine; falls back to the last step's usage. */
385async function contextOf($) {
386 try {
387 const usage = await $.session.usage()
388 const c = usage && usage.context
389 if (c && typeof c.window === 'number' && c.window > 0) {
390 const tokens = typeof c.tokens === 'number' ? c.tokens : sentOf(lastUsage)
391 const percent =
392 typeof c.percent === 'number' ? c.percent : Math.min(100, Math.round((100 * tokens) / c.window))
393 return { tokens, window: c.window, percent }
394 }
395 } catch {
396 /* no session bound (tests) or older engine */
397 }
398 const tokens = sentOf(lastUsage)
399 return { tokens, window: 0, percent: 0 }
400}
401
402function cacheClock(now, ttl) {
403 if (!lastStepAt) return { known: false, warm: false, idleMs: 0, leftMs: 0 }
404 const idleMs = Math.max(0, now - Math.max(lastStepAt, keepWarm.refreshedAt)) // a keep-warm ping refreshes the TTL too
405 return { known: true, warm: idleMs < ttl, idleMs, leftMs: Math.max(0, ttl - idleMs) }
406}
407
408/** Whether a keep-warm ping is due now, else why not. Pure: every input is passed in. */
409function keepWarmDue(w, now, lastStep, ttl, maxPings, turnRunning) {
410 if (!w.on) return 'off'
411 if (turnRunning) return 'turn running'
412 if (w.busy) return 'busy'
413 if (!lastStep) return 'no response yet'
414 const idle = now - Math.max(lastStep, w.refreshedAt)
415 if (idle >= ttl) return 'lapsed'
416 if (ttl - idle > KEEP_WARM_LEAD) return 'not yet'
417 if (w.streak >= maxPings) return 'cap'
418 return 'ping'
419}
420
421/** One input-token-equivalent figure for what a call cost: write 1.25×, read 0.1×, output 5×. */
422function billedTok(u) {
423 if (!u) return 0
424 return Math.round((u.input_tokens || 0) + 1.25 * (u.cache_creation_input_tokens || 0) + 0.1 * (u.cache_read_input_tokens || 0) + 5 * (u.output_tokens || 0))
425}
426
427async function tickKeepWarm($, ttl, maxPings) {
428 const now = await $.clock.now()
429 if (keepWarmDue(keepWarm, now, lastStepAt, ttl, maxPings, inTurn) !== 'ping') return
430 keepWarm.busy = true
431 try {
432 // API billing only: a subscription already caches the main thread for an hour, and a ping would spend plan quota
433 let u = null
434 try { u = await $.session.usage() } catch { /* no usage API */ }
435 if (!(u && u.cost && Number.isFinite(u.cost.usd))) { keepWarm.stopped = 'not API billing'; keepWarm.on = false; return }
436 const r = await $.model.fork({ prompt: KEEP_WARM_PROMPT })
437 if (r.usage) keepWarm.costTok += billedTok(r.usage)
438 if (!r.isAnswered && r.reason === 'nothing-to-fork') return
439 keepWarm.pings += 1
440 keepWarm.streak += 1
441 const read = (r.usage && r.usage.cache_read_input_tokens) || 0
442 if (r.isAnswered && read >= 0.8 * sentOf(r.usage)) keepWarm.refreshedAt = now
443 else { keepWarm.misses += 1; keepWarm.streak = Infinity } // already lapsed (model switch, eviction) or failed: stop paying this stretch
444 try { $.ui.invalidate('ui.render') } catch { /* no UI */ }
445 } finally {
446 keepWarm.busy = false
447 }
448}
449
450function levelFor(pct) {
451 return levels.filter((l) => Number(l.pct) <= pct).sort((a, b) => Number(b.pct) - Number(a.pct))[0]
452}
453
454function hintFor(pct, clock) {
455 const hit = levelFor(pct)
456 if (!hit) return ''
457 if (hit.hint === 'note') return `past your ${hit.pct}% (${hit.id}) — note decisions`
458 if (hit.hint === 'new-conversation') return `past your ${hit.pct}% (${hit.id}) — /handoff then /clear`
459 if (hit.hint === 'compact-if-warm' && clock.warm) {
460 return `past your ${hit.pct}% (${hit.id}), cache warm ${mins(clock.leftMs)}m — /compact is cheap`
461 }
462 if (hit.hint === 'compact-if-warm') {
463 return `past your ${hit.pct}% (${hit.id}), cache cold — /handoff then /clear, don't /compact`
464 }
465 return `past your ${hit.pct}% (${hit.id})`
466}
467
468async function refreshSkills($, cwd) {
469 skillsBusy = true
470 try { $.ui.invalidate('ui.render') } catch { /* no UI */ }
471 try {
472 const args = [`${$.plugin.root}/scripts/skills.py`, 'status', '--json']
473 if (cwd) args.push('--project', cwd)
474 const r = await runPython($, args, { timeoutMs: 60_000 })
475 if (r.exitCode !== 0) throw new Error((r.stderr || r.stdout || `exit ${r.exitCode}`).trim().split('\n')[0])
476 skillsData = JSON.parse(r.stdout)
477 } catch (err) {
478 skillsData = { error: err && err.message ? err.message : String(err) }
479 }
480 skillsBusy = false
481 try { $.ui.invalidate('ui.render') } catch { /* no UI */ }
482}
483
484/** Expand globs, @groups and 'unused' against the last status, so each skill can be its own stage. */
485function expandSkillNames(verb, names) {
486 if (!skillsData || skillsData.error) return names
487 const active = (skillsData.active || []).map((x) => x.name)
488 const parked = (skillsData.parked || []).map((x) => x.name)
489 const pool = verb === 'park' ? active : verb === 'unlink' ? (skillsData.project_links || []) : parked
490 const out = []
491 for (const raw of names) {
492 let hits
493 if (raw === 'unused') hits = (skillsData.unused || []).filter((n) => pool.includes(n))
494 else if (raw.startsWith('@')) hits = pool.filter((n) => n.split('-')[0] === raw.slice(1))
495 else if (/[*?[]/.test(raw)) {
496 const re = new RegExp('^' + raw.replace(/[.+^${}()|\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
497 hits = pool.filter((n) => re.test(n))
498 } else hits = [raw]
499 for (const h of hits) if (!out.includes(h)) out.push(h)
500 }
501 return out
502}
503
504const VERB_LABEL = { park: 'Park', unpark: 'Bring back', link: 'Link here', unlink: 'Unlink' }
505
506async function actSkills($, verb, names, cwd) {
507 if (skillsBusy) return
508 skillsBusy = true
509 const list = expandSkillNames(verb, names)
510 const total = list.length
511 const rowId = 'loadout'
512 const label = `${VERB_LABEL[verb] || verb} ${total} skill${total === 1 ? '' : 's'}`
513 applyProgress({ id: rowId, label, stage: list[0] || verb, step: 1, total, state: 'running', percent: 0 })
514 skillsMsg = `${label}…`
515 try { $.ui.status('Progress'); $.ui.invalidate('ui.render') } catch { /* no UI */ }
516 let ok = 0
517 let skipped = 0
518 let summary = ''
519 const onLine = (line) => {
520 // skills.py --progress prints `>> i/n name ok|skip` as each skill lands; one process, many stages.
521 const m = /^>> (\d+)\/(\d+) (\S+) (ok|skip)$/.exec(line.trim())
522 if (m) {
523 const i = Number(m[1]), n = Number(m[2])
524 if (m[4] === 'ok') ok += 1
525 else skipped += 1
526 applyProgress({ id: rowId, stage: m[3], step: Math.min(i + 1, n), total: n, state: 'running', percent: (i / n) * 100 })
527 try { $.ui.invalidate('ui.render') } catch { /* no UI */ }
528 } else if (line.trim() && !line.startsWith(' skip')) {
529 summary = line.trim().replace(/\s+→\s+\S+$/, '')
530 }
531 }
532 try {
533 const args = [`${$.plugin.root}/scripts/skills.py`, verb, ...list, '--no-usage', '--progress']
534 if (cwd) args.push('--project', cwd)
535 let streamed = false
536 try {
537 let buf = ''
538 for await (const piece of spawnPython($, args, { cwd: cwd || undefined })) {
539 streamed = true
540 if (typeof piece.text === 'string') {
541 buf += piece.text
542 let nl
543 while ((nl = buf.indexOf('\n')) >= 0) {
544 onLine(buf.slice(0, nl))
545 buf = buf.slice(nl + 1)
546 }
547 }
548 }
549 if (buf.trim()) onLine(buf)
550 } catch (err) {
551 if (streamed) throw err
552 // No streaming on this build: one batch run, start and finish only.
553 const r = await runPython($, args, { timeoutMs: 90_000 })
554 for (const line of (r.stdout || r.stderr || '').split('\n')) onLine(line)
555 }
556 const failed = skipped > 0 && ok === 0
557 const row = applyProgress({ id: rowId, stage: skipped ? `${skipped} skipped` : 'Done', step: total, total, state: failed ? 'failed' : 'done', percent: 100 })
558 if (row) row.expireAt = Date.now() + (skipped ? 15000 : 8000)
559 skillsMsg = summary || `${label}: ${ok} done${skipped ? `, ${skipped} skipped` : ''}`
560 try { $.ui.toast(`${skillsMsg} · loads after /clear`, { timeoutMs: 8000 }) } catch { /* no UI */ }
561 } catch (err) {
562 skillsMsg = `could not run skills.py: ${err && err.message ? err.message : String(err)}`
563 const row = applyProgress({ id: rowId, stage: 'error', state: 'failed', percent: 100 })
564 if (row) row.expireAt = Date.now() + 15000
565 }
566 skillsBusy = false
567 try { $.ui.invalidate('ui.render') } catch { /* no UI */ }
568 await refreshSkills($, cwd)
569}
570
571function clamp01(x) {
572 return Math.max(0, Math.min(1, x))
573}
574
575/** Apply one `progress` call to the rows. Returns the row, or null when removed. */
576function applyProgress(e) {
577 const id = String(e.id || 'job')
578 if (e.remove) {
579 progressRows.delete(id)
580 return null
581 }
582 const row = progressRows.get(id) || { id, label: id, stage: '', step: 0, total: 0, state: 'running', target: 0, shown: 0, note: '' }
583 if (typeof e.label === 'string' && e.label) row.label = e.label
584 if (typeof e.stage === 'string') row.stage = e.stage
585 if (Number.isFinite(e.total)) row.total = Math.max(0, Math.floor(e.total))
586 if (Number.isFinite(e.step)) row.step = Math.max(0, Math.floor(e.step))
587 if (typeof e.state === 'string' && STATE_COLOR[e.state]) row.state = e.state
588 if (typeof e.note === 'string') row.note = e.note
589 if (Number.isFinite(e.percent)) row.target = clamp01(e.percent / 100)
590 else if (row.total > 0) row.target = clamp01((Math.max(1, row.step) - 1) / row.total)
591 if (row.state === 'done') {
592 row.target = 1
593 if (row.total > 0) row.step = row.total
594 if (!row.stage) row.stage = 'Done'
595 }
596 const liveNow = row.state === 'running' || row.state === 'waiting'
597 if (!liveNow && row.settledAt === undefined) row.settledAt = progressTick * TICK_S
598 if (liveNow) row.settledAt = undefined
599 progressRows.set(id, row)
600 return row
601}
602
603function pillText(row) {
604 if (row.plain) return row.stage || '' // a gauge: just the figure, no state prefix
605 const lead = row.state === 'done' ? '✓ ' : row.state === 'failed' ? '✕ ' : row.state === 'waiting' ? '? ' : ''
606 const count = row.total > 0 ? ` ${Math.max(1, Math.min(row.step || 1, row.total))}/${row.total}` : ''
607 return `${lead}${row.stage || row.label}${count}`
608}
609
610/** Shared by every surface: the dot-matrix palette. Deterministic, so a frame never flickers between redraws. */
611function hexRgb(hex) {
612 const n = parseInt(hex.slice(1), 16)
613 return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
614}
615function rgbHex(r, g, b) {
616 return '#' + [r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')
617}
618/** `color` scaled toward black by `f` (0..1), mixed a touch toward the track so the dim end still reads as the state. */
619function shade(hex, f) {
620 const [r, g, b] = hexRgb(hex)
621 const t = Math.max(0, Math.min(1, f))
622 return rgbHex(0x2b + (r - 0x2b) * t, 0x2b + (g - 0x2b) * t, 0x30 + (b - 0x30) * t)
623}
624/** A small integer hash of a grid position; ~15% of filled squares sit one step dimmer. */
625function dotHash(col, row, salt) {
626 let x = (col * 374761393 + row * 668265263 + salt * 2246822519) | 0
627 x = Math.imul(x ^ (x >>> 13), 1274126177)
628 return (x ^ (x >>> 16)) >>> 0
629}
630let progressTick = 0 // advanced by the band ticker, 70 ms apiece; every frame is a pure function of it
631const TICK_S = 0.07
632const LOOP_DT = 2 * TICK_S // desktop: a bar's own loop holds a frame this long (the desktop drew every other tick)
633const LOOP_N = 21 // ... and this many frames: 2.94 s, one period of the calm pulse, so the loop closes
634
635/**
636 * The Effort slider's own recipe (its fragment shader, ported): a grid of small rounded cells; bursts
637 * race out from the head as Manhattan-distance wavefronts with per-cell jitter; energy quantizes to a
638 * five-step ramp from white to the state's hot ink; top-step cells breathe; a charged bed deepens
639 * toward the head and stays once reached; the left quarter fades. Tuned brighter than the slider
640 * (ink floor .25, ceiling 1, gain 1.4, lifted bed) at the person's request.
641 */
642const SH = {
643 SPEED_LO: 20, SPEED_HI: 36, RANGE_LO: 10, RANGE_HI: 55, DENSITY_LO: 0.30, DENSITY_HI: 0.85, JITTER: 0.10,
644 HEAD_GAIN: 1.25, HEAD_DECAY: 5, BODY_GAIN: 0.65, BODY_LO: 3.3, BODY_HI: 0.77, AMP_LO: 0.55, MAX_AGE: 5,
645 RAMP_POW: 1.4, BREATH_DIP: 0.28, BREATH_BASE: 2.4, BREATH_VARY: 1.4,
646 inkFloor: 0.25, inkCeil: 1, gain: 1.4, chargeMax: 1, mask: 0.25, fadeUp: 0.7, burstRamp: 2, sparkleFor: 60,
647}
648const INKS = {
649 running: { hot: [0.70, 0.65, 1.00], c0: [0.78, 0.66, 1.00], c1: [0.55, 0.42, 0.95] },
650 waiting: { hot: [1.00, 0.82, 0.48], c0: [1.00, 0.80, 0.40], c1: [0.80, 0.55, 0.18] },
651 failed: { hot: [1.00, 0.60, 0.63], c0: [1.00, 0.50, 0.54], c1: [0.85, 0.25, 0.30] },
652 done: { hot: [0.62, 0.94, 0.76], c0: [0.45, 0.90, 0.68], c1: [0.20, 0.65, 0.45] },
653 cold: { hot: [0.70, 0.70, 0.74], c0: [0.52, 0.52, 0.57], c1: [0.33, 0.33, 0.38] },
654 orange: { hot: [1.00, 0.74, 0.50], c0: [1.00, 0.62, 0.36], c1: [0.80, 0.40, 0.20] },
655 blue: { hot: [0.62, 0.76, 1.00], c0: [0.45, 0.62, 0.98], c1: [0.22, 0.40, 0.80] },
656 green: { hot: [0.66, 0.90, 0.66], c0: [0.48, 0.78, 0.48], c1: [0.25, 0.50, 0.28] },
657 yellow: { hot: [0.98, 0.86, 0.45], c0: [0.86, 0.72, 0.28], c1: [0.60, 0.48, 0.14] },
658}
659const BAR_H = 14, BAR_ROWS = 3, BAR_RADIUS = 4
660
661function hash21(x, y) {
662 const v = Math.sin(x * 127.1 + y * 311.7) * 43758.5453
663 return v - Math.floor(v)
664}
665const mixN = (a, b, t) => a + (b - a) * t
666const smooth = (a, b, x) => { const t = Math.max(0, Math.min(1, (x - a) / (b - a))); return t * t * (3 - 2 * t) }
667const toHex = (c) => '#' + c.map((v) => Math.max(0, Math.min(255, Math.round(v * 255))).toString(16).padStart(2, '0')).join('')
668
669function rowSeed(row) {
670 return (hash21(row.id.length, row.id.charCodeAt(0) || 7) * 512) | 0
671}
672
673/**
674 * The burst schedule, deterministic: burst i fires at a hashed interval after burst i-1, at the head,
675 * with a strength that ramps up over the first two seconds. A finished row switches to faint sparks at
676 * random points along the fill for `sparkleFor` seconds, then holds still. Returns the live bursts.
677 */
678function burstsAt(row, t, seed) {
679 const live = row.live === true || row.state === 'running' || row.state === 'waiting'
680 const out = []
681 if (live) {
682 let T = 0
683 for (let i = 0; i < 400 && T <= t; i++) {
684 const gap = 0.3 + 0.45 * hash21(seed + i * 1.7, 3.3)
685 if (T >= t - SH.MAX_AGE) {
686 const k = Math.min(T / SH.burstRamp, 1)
687 const e = 0.6 + 0.4 * row.shown
688 const gain = Math.min((0.15 + 0.7 * e) * (0.45 + 0.55 * k), 1) * (0.85 + 0.3 * hash21(seed + i * 2.9, 5.1))
689 out.push({ t: T, x: row.shown + (hash21(seed + i * 4.1, 7.7) - 0.5) * 0.08, y: 0.35 + 0.3 * hash21(seed + i * 6.3, 9.9), k: gain })
690 }
691 T += gap
692 }
693 } else {
694 const t0 = row.settledAt || 0
695 out.push({ t: t0, x: row.shown, y: 0.5, k: 0.9 }) // the one front that charges the bed
696 if (row.state === 'done' && t - t0 < SH.sparkleFor) {
697 let T = t0 + 1.2
698 for (let i = 0; i < 200 && T <= t; i++) {
699 if (T >= t - SH.MAX_AGE) out.push({ t: T, x: row.shown * (0.08 + 0.92 * hash21(seed + i * 3.7, 2.2)), y: 0.2 + 0.6 * hash21(seed + i * 5.3, 4.4), k: 0.3 + 0.15 * hash21(seed + i * 1.3, 6.6) })
700 T += 0.5 + 0.7 * hash21(seed + i * 2.1, 8.8)
701 }
702 }
703 }
704 return out.slice(-8)
705}
706
707/** Colour of one cell as [r,g,b] 0..1 composited over the track, or null where nothing paints. */
708function shadeCell(row, cx, cy, cols, rows, t, bursts, seed, pitchPx, W) {
709 const live = row.live === true || row.state === 'running' || row.state === 'waiting'
710 const pos = Math.max(row.shown, 0.02)
711 const px = (cx + 0.5) * pitchPx
712 if (px > pos * W + pitchPx) return null
713 const L = live ? Math.min(t / SH.fadeUp, 1) : 1
714 const jitter = (hash21(cx + 41.7 + seed, cy + 41.7 + seed) - 0.5) * 2 * SH.JITTER
715 const vary = 0.35 + 0.65 * hash21(cx + 13.7 + seed, cy + 13.7 + seed)
716 let energy = 0, charged = 0
717 for (const b of bursts) {
718 const age = t - b.t
719 if (age < 0 || age > SH.MAX_AGE) continue
720 const ox = Math.floor((b.x * W) / pitchPx), oy = Math.floor(b.y * rows)
721 const manh = Math.abs(cx - ox) + Math.abs(cy - oy)
722 const range = mixN(SH.RANGE_LO, SH.RANGE_HI, b.k)
723 const falloff = Math.exp(-manh / (range * 0.85)), reach = Math.exp(-Math.max(manh - range, 0) * 0.12)
724 const tt = age - manh / mixN(SH.SPEED_LO, SH.SPEED_HI, b.k) - jitter
725 charged = Math.max(charged, smooth(0, 0.15, tt) * reach)
726 if (tt < 0) continue
727 if (hash21(cx + 7.3 + seed + b.t, cy + 7.3 + seed + b.t) > mixN(SH.DENSITY_LO, SH.DENSITY_HI, b.k)) continue
728 const head = SH.HEAD_GAIN * Math.exp(-tt * SH.HEAD_DECAY), body = SH.BODY_GAIN * Math.exp(-tt * mixN(SH.BODY_LO, SH.BODY_HI, b.k))
729 energy += (head + body) * mixN(SH.AMP_LO, 1, b.k) * falloff * reach * vary
730 }
731 if (!live && t - (row.settledAt || 0) > 1.6) charged = 1 // a finished row keeps its bed
732 const lumA = hash21(cx + 8.8 + seed, cy + 8.8 + seed), lumB = hash21(cx + 88.8 + seed, cy + 88.8 + seed)
733 const lum = Math.pow(mixN(lumA, lumB, 0.5 + 0.5 * Math.sin(t * 0.35 + lumA * 6.2832)), 1.9)
734 const stream = 0.9 + 0.16 * Math.sin(t * 1.3 + cx * 0.45 + lumB * 2)
735 const e = Math.min(Math.max(energy, 0), 1) * L * mixN(0.16, 1, lum) * stream * SH.gain
736 let ink = INKS[row.state] || INKS.running
737 if (row.segments) { const f = px / W; const sg = row.segments.find((x) => f <= x.end) || row.segments[row.segments.length - 1]; if (sg) ink = INKS[sg.ink] || ink }
738 const g = Math.max(0, Math.min(1, px / Math.max(pos * W, 1)))
739 const chargeA = SH.chargeMax * Math.pow(g, 1.1) * charged * L
740 const lv = (e > 0.04) + (e > 0.2) + (e > 0.4) + (e > 0.6) + (e > 0.8)
741 let alpha = lv <= 0 ? 0 : mixN(SH.inkFloor, SH.inkCeil, (lv - 1) / 4)
742 if (lv >= 5) {
743 const period = SH.BREATH_BASE + SH.BREATH_VARY * hash21(cx + 3.1 + seed, cy + 3.1 + seed)
744 alpha *= 1 - SH.BREATH_DIP * 0.5 * (1 + Math.sin((t * 6.2832) / period + hash21(cx + 5.5 + seed, cy + 5.5 + seed) * 6.2832))
745 }
746 const a = alpha + chargeA * (1 - alpha)
747 if (a <= 0) return null
748 const q = Math.pow(lv / 5, SH.RAMP_POW)
749 const m = SH.mask ? Math.min(1, px / (SH.mask * W)) : 1
750 return [0, 1, 2].map((i) => {
751 const inkc = mixN(1, ink.hot[i], q)
752 const bed = mixN(ink.c0[i], ink.c1[i], g)
753 const col = inkc * alpha + bed * chargeA * (1 - alpha)
754 return Math.min(1, rgb01(PAL.PROG_TRACK)[i] * (1 - a * m) + col * m)
755 })
756}
757
758/** Desktop and the web surfaces: the slider's cells at 14 px, squared corners, a gradient text pill trailing the head. */
759function progressSvg(row, width, marks = []) {
760 const W = Math.max(160, Math.floor(width)), H = BAR_H, rows = BAR_ROWS
761 const pitch = H / rows, cellHalf = (3 / 4) * pitch / 2, cols = Math.ceil(W / pitch)
762 const t = progressTick * TICK_S
763 const seed = rowSeed(row)
764 const bursts = burstsAt(row, t, seed)
765 const squares = []
766 for (let cy = 0; cy < rows; cy++) {
767 for (let cx = 0; cx < cols; cx++) {
768 const c = shadeCell(row, cx, cy, cols, rows, t, bursts, seed, pitch, W)
769 if (!c) continue
770 const x = (cx + 0.5) * pitch - cellHalf, y = (cy + 0.5) * pitch - cellHalf
771 squares.push(`<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${(cellHalf * 2).toFixed(1)}" height="${(cellHalf * 2).toFixed(1)}" rx="0.9" fill="${toHex(c)}"/>`)
772 }
773 }
774 const label = pillText(row)
775 const ink = INKS[row.state] || INKS.running
776 const pw = Math.min(W - 4, Math.round(label.length * 6.1 + 14))
777 const headX = Math.max(row.shown, 0.02) * W
778 const px = headX + pw + 2 <= W ? headX : Math.max(2, W - pw - 2) // trail the head; flip behind it at the right end
779 const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<')
780 const gid = `g${row.id.replace(/[^a-z0-9]/gi, '')}`
781 return (
782 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
783 `<defs><clipPath id="c${gid}"><rect width="${W}" height="${H}" rx="${BAR_RADIUS}"/></clipPath>` +
784 `<linearGradient id="${gid}" x1="0" x2="1"><stop offset="0" stop-color="${toHex(ink.c0)}"/><stop offset="1" stop-color="${toHex(ink.c1)}"/></linearGradient></defs>` +
785 `<rect width="${W}" height="${H}" rx="${BAR_RADIUS}" fill="${PAL.PROG_TRACK}"/>` +
786 `<g clip-path="url(#c${gid})">${squares.join('')}${marks.map((m) => `<rect x="${(m.frac * W - 0.5).toFixed(1)}" y="2" width="1" height="${H - 4}" fill="${m.color || PAL.PROG_MARK}" opacity="0.9"/>`).join('')}</g>` +
787 `<rect x="${px.toFixed(1)}" y="1" width="${pw}" height="${H - 2}" rx="${BAR_RADIUS}" fill="url(#${gid})"/>` +
788 `<text x="${(px + pw / 2).toFixed(1)}" y="${H / 2 + 3.5}" text-anchor="middle" font-family="-apple-system, Inter, Segoe UI, sans-serif" font-size="10" font-weight="600" fill="#ffffff">${esc(label)}</text>` +
789 `</svg>`
790 )
791}
792
793/** Standard base64 of a byte array; the sandbox has no Buffer and toBase64 is not everywhere yet. */
794function base64(bytes) {
795 const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
796 let out = ''
797 for (let i = 0; i < bytes.length; i += 3) {
798 const a = bytes[i], b = bytes[i + 1], c = bytes[i + 2]
799 const n = (a << 16) | ((b || 0) << 8) | (c || 0)
800 out += A[(n >> 18) & 63] + A[(n >> 12) & 63] + (b === undefined ? '=' : A[(n >> 6) & 63]) + (c === undefined ? '=' : A[n & 63])
801 }
802 return out
803}
804/** One-row Raster cells: a half-block square on every even global column, a blank gap between. `colorAt(col)` gives
805 * 0xRRGGBB or null for the bare track. `offset` is the global index of this segment's first column. */
806function rasterCells(columns, colorAt, offset = 0) {
807 const DEFAULT = 0x01000000
808 const words = new Uint32Array(columns * 3)
809 let i = 0
810 for (let c = 0; c < columns; c++) {
811 const g = c + offset
812 const col = colorAt(g)
813 if (col === -2) { words[i++] = 0x2502; words[i++] = parseInt(PAL.PROG_DIM.slice(1), 16); words[i++] = DEFAULT } // │ a mark
814 else if (g % 2 === 1) { words[i++] = 0x20; words[i++] = DEFAULT; words[i++] = DEFAULT } // gap column
815 else { words[i++] = 0x2580; words[i++] = col === null ? parseInt(PAL.PROG_BARE.slice(1), 16) : col; words[i++] = DEFAULT } // ▀ square, dim on the bare track
816 }
817 return base64(new Uint8Array(words.buffer))
818}
819
820/** The terminal: the same cells, one row, split around a coloured text pill that trails the head. */
821function progressTrackText(row, cells, h, Text, Raster, marks = []) {
822 const t = progressTick * TICK_S
823 const seed = rowSeed(row)
824 const bursts = burstsAt(row, t, seed)
825 const ink = INKS[row.state] || INKS.running
826 const label = ` ${pillText(row)} `
827 const pillW = Math.min(cells, label.length)
828 const head = Math.round(cells * Math.max(row.shown, 0.02))
829 const pillX = head + pillW <= cells ? head : Math.max(0, cells - pillW)
830 const thumb = h(Text, { color: '#ffffff', backgroundColor: toHex(ink.c1), bold: true }, label.slice(0, pillW))
831 const markCols = new Set(marks.map((m) => Math.max(0, Math.min(cells - 1, Math.round(m.frac * cells)))))
832 const colorAt = (x) => {
833 if (markCols.has(x)) return -2
834 const c = shadeCell(row, x, 0, cells, 1, t, bursts, seed, 1, cells)
835 if (!c) return null
836 return parseInt(toHex(c).slice(1), 16)
837 }
838 if (typeof Raster === 'function') {
839 const parts = []
840 if (pillX > 0) parts.push(h(Raster, { key: `progress-dots:${row.id}:l`, columns: pillX, rows: 1, cells: rasterCells(pillX, colorAt, 0) }))
841 parts.push(thumb)
842 const rest = cells - pillX - pillW
843 if (rest > 0) parts.push(h(Raster, { key: `progress-dots:${row.id}:r`, columns: rest, rows: 1, cells: rasterCells(rest, colorAt, pillX + pillW) }))
844 return parts
845 }
846 const parts = []
847 let run = '', runProps = null, runKey = ''
848 const flush = () => { if (run) { parts.push(h(Text, runProps, run)); run = '' } }
849 for (let x = 0; x < cells; x++) {
850 if (x === pillX) { flush(); parts.push(thumb); x += pillW - 1; continue }
851 const c = colorAt(x)
852 const key = c === null ? 'u' : c === -2 ? 'm' : toHex([(c >> 16) / 255, ((c >> 8) & 255) / 255, (c & 255) / 255])
853 const props = c === null ? { color: PAL.DOT_UNFILLED } : c === -2 ? { color: PAL.PROG_DIM } : { color: key }
854 if (key !== runKey) { flush(); runKey = key; runProps = props }
855 run += c === null ? '·' : c === -2 ? '│' : '▪'
856 }
857 flush()
858 return parts
859}
860
861function progressSettled() {
862 for (const r of progressRows.values()) if (Math.abs(r.target - r.shown) > 0.004) return false
863 return true
864}
865
866// ---------------------------------------------------------------------------
867// The Context pane (/tokens): the pack's own dashboard, drawn to the M4 design (design/m4.js). Closed: the title with
868// the fill, the context bar (F1 fire, ink in the threshold colour), the cache and saved line, Clear / Compact / Later.
869// Open: what was saved, three cards (next mark, billing, cache), Claude's working memory by kind, drill-down groups.
870const CONTEXT_PANE = 'context'
871const BREAKDOWN_TTL = 10 * 1000 // $.session.usage({ breakdown: 'summary' }) is cached this long; redraws cost nothing
872let ctxCache = { at: 0, usage: null }
873let ctxLoading = null
874let ctxBusy = false
875let ctxMsg = ''
876let ctxPaneOpen = false
877let ctxExpanded = false
878let ctxReceipt = false
879let ctxPopped = false // desktop: the Pane was opened by the band's ⤢ (cleared when it closes)
880const ctxGroups = new Set() // which drill-down groups are open
881let homeCache = null // $HOME, read once, to shorten memory-file paths
882/** Context added per message: tokens at turn.complete less tokens at turn.start, the last five. */
883const growth = []
884let turnStartTokens = null
885const GROWTH_KEEP = 5
886
887/** Threshold colour by marks crossed: calm blue, then amber, Claude orange, red. Theme keys for Text. */
888const ACC = ['permission', 'warning', 'claude', 'error']
889/**
890 * Every hex the mod draws, per palette (design/theme/claude-themes.json: desktop.dark/light, cli.dark/light).
891 * `hex` is the theme keys per surface: the desktop paints theme names one grey, so its Text gets these; the
892 * terminal keeps names for Text and uses its row for the bars' ink. The rest are the bars' tracks, ticks and inks.
893 */
894const PALETTES = {
895 dark: {
896 hex: {
897 terminal: { permission: '#b1b9f9', warning: '#ffc107', claude: '#d77757', error: '#ff6b80', success: '#4eba65', text: '#ffffff', inactive: '#999999', subtle: '#505050' },
898 desktop: { permission: '#74abe2', warning: '#fab219', claude: '#d97757', error: '#dd5353', success: '#65bb30', text: '#faf9f5', inactive: '#9c9a92', subtle: '#4a4945' },
899 },
900 CACHE_GRAD: ['#629cde', '#a8a38c', '#da934b'],
901 CACHE_TRACK: '#2e2d29',
902 WARM: '#ce9466',
903 COLD: '#629cde',
904 BAR_TRACK: '#2a2a2e',
905 BUFFER_CELL: '#45454b',
906 // Desktop: the pane's ground lifted 7% toward the text, and the buffer 30% on toward faint, as design/m4.html draws them
907 DESK_TRACK: '#353533',
908 DESK_BUFFER: '#545350',
909 MARK_TICK: '#c2c0b6',
910 AUTO_TICK: '#7d7b75',
911 /** Claude's working memory: one family around Claude's orange, so it never reads as a signal colour. */
912 MEM: { messages: '#e07a52', mcp: '#f2a07b', skills: '#c6613f', system: '#f6c9a8', tools: '#9e9a97', memory: '#b98b72', agents: '#d9a888', other: '#a8968a', buffer: '#64635e', free: '#46453f' },
913 // progress rows: unfilled dots, the bar's ground, its marks, a dim mark cell
914 DOT_UNFILLED: '#3a3a40',
915 PROG_TRACK: '#2a2a2e',
916 PROG_MARK: '#d4d3cf',
917 PROG_DIM: '#9a9aa0',
918 PROG_BARE: '#33333a',
919 },
920 light: {
921 hex: {
922 terminal: { permission: '#5769f7', warning: '#966c1e', claude: '#d77757', error: '#ab2b3f', success: '#2c7a39', text: '#000000', inactive: '#666666', subtle: '#afafaf' },
923 desktop: { permission: '#1b67b2', warning: '#966c1e', claude: '#c6613f', error: '#b53333', success: '#2f7613', text: '#141413', inactive: '#73726c', subtle: '#b0aea6' },
924 },
925 CACHE_GRAD: ['#2f78c8', '#8c8672', '#c4711f'],
926 CACHE_TRACK: '#e6e4da',
927 WARM: '#b86a33',
928 COLD: '#2f78c8',
929 BAR_TRACK: '#e2e2e6',
930 BUFFER_CELL: '#c4c4ca',
931 // Desktop light: bg-400 for the ground, the buffer a step darker
932 DESK_TRACK: '#e8e6dc',
933 DESK_BUFFER: '#cfcdc3',
934 MARK_TICK: '#3d3d3a',
935 AUTO_TICK: '#8a8880',
936 MEM: { messages: '#d0643c', mcp: '#e08559', skills: '#b04f2c', system: '#e9a77c', tools: '#8a8682', memory: '#a1715a', agents: '#c78a63', other: '#94826f', buffer: '#c9c7be', free: '#e3e1d7' },
937 DOT_UNFILLED: '#d4d4da',
938 PROG_TRACK: '#e2e2e6',
939 PROG_MARK: '#3d3d3a',
940 PROG_DIM: '#8a8a90',
941 PROG_BARE: '#d0d0d6',
942 },
943}
944/** The palette the drawing in progress reads. Set by usePal() right before each synchronous draw. */
945let PAL = PALETTES.dark
946let themeOption = 'auto' // plugin option: auto | dark | light
947let cliTheme = null // the terminal's /config Theme row (dark, light, light-daltonized, auto, ...)
948let fgbgLight = null // COLORFGBG says the terminal's ground is light (for Theme auto)
949/** dark or light for a surface. auto: the terminal follows its /config Theme; the desktop gives a mod no signal, so dark. */
950function themeMode(term) {
951 if (themeOption === 'dark' || themeOption === 'light') return themeOption
952 if (term && cliTheme) {
953 if (/^light/.test(cliTheme)) return 'light'
954 if (/^dark/.test(cliTheme)) return 'dark'
955 if (cliTheme === 'auto' && fgbgLight !== null) return fgbgLight ? 'light' : 'dark'
956 }
957 return 'dark'
958}
959function usePal(term) {
960 PAL = PALETTES[themeMode(term)]
961 return PAL
962}
963/** The ui.hex the drawing passes: a hex goes through, a theme key becomes this palette's hex for the surface. */
964const hexFor = (term) => { const pal = usePal(term).hex[term ? 'terminal' : 'desktop']; return (k) => (String(k).startsWith('#') ? k : pal[k] || pal.inactive) }
965/** COLORFGBG "fg;bg" (or "fg;x;bg"): bg 7 or 9-15 is a light ground. */
966function fgbgIsLight(v) {
967 const bg = Number(String(v || '').split(';').pop())
968 return Number.isFinite(bg) && String(v).includes(';') ? bg === 7 || (bg >= 9 && bg <= 15) : null
969}
970let themeRead = false
971async function readTheme($) {
972 themeRead = true
973 try {
974 const rows = await $.config.list()
975 const row = Array.isArray(rows) && rows.find((r) => r && (r.key ?? r.id) === 'theme')
976 if (row && typeof row.value === 'string') cliTheme = row.value.replace(/\s*\(.*\)$/, '')
977 } catch { /* no config here */ }
978 try { fgbgLight = fgbgIsLight(await $.env.get('COLORFGBG')) } catch { fgbgLight = null }
979}
980const MEM_RANK = ['messages', 'mcp', 'skills', 'system', 'tools', 'memory', 'agents', 'other']
981const BAR_PAD = 8 // desktop: px of air above and below the context bar, as design/m4.html's 10 px gaps
982const INNER_PAD = 5 // desktop: the same air, smaller, for the Saved, card and memory bars inside the open pane
983const PX = 8.1 // desktop px per pane body column: two screenshots measured 8.16 (800 px text over 98 columns); a hair under, so a bar never overflows
984const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
985
986/** 484000 → "484k", 1000000 → "1M", 1500000 → "1.5M". */
987function fmtK(n) {
988 if (!n || n < 0) return '0'
989 if (n >= 999_500) {
990 const m = n / 1_000_000
991 const s = m >= 10 ? String(Math.round(m)) : m.toFixed(1).replace(/\.0$/, '')
992 return s + 'M'
993 }
994 if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k'
995 return String(Math.round(n))
996}
997
998function pct100(x) {
999 return Number.isFinite(x) ? Math.max(0, Math.min(100, Math.round(x))) : 0
1000}
1001
1002const cap1 = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s)
1003const rgb01 = (hex) => hexRgb(hex).map((v) => v / 255)
1004const mixHex = (a, b, t) => toHex(mix3(rgb01(a), rgb01(b), t))
1005const gradAt = (f) => (f < 0.5 ? mixHex(PAL.CACHE_GRAD[0], PAL.CACHE_GRAD[1], f / 0.5) : mixHex(PAL.CACHE_GRAD[1], PAL.CACHE_GRAD[2], (f - 0.5) / 0.5))
1006const avgGrowth = () => (growth.length ? growth.reduce((a, b) => a + b, 0) / growth.length : 0)
1007function crossedAt(p) {
1008 return Math.min(3, levels.filter((l) => Number(l.pct) <= p).length)
1009}
1010function seedOf(s) {
1011 let x = 7
1012 for (let i = 0; i < s.length; i++) x = (x * 31 + s.charCodeAt(i)) % 997
1013 return x
1014}
1015
1016// ---- F1 "Comet", ported from design/fire/F1.js: a white-hot core at the head, a flickering body, wind-blown
1017// tongues and embers carried left, cooling white → hot → c0 → c1 into a calm bed. Pure: a frame is a function of t.
1018const FC = {
1019 CORE: 2.2, NOSE: 1.5, ZONE: 175, BODY_LEN: 17, TONGUE_LEN: 80, WIND: 170, BODY_CELL: 7, TONGUE_CELL: 30,
1020 EMBER_GAP: 0.018, EMBER_V_LO: 150, EMBER_V_HI: 310, EMBER_D_LO: 30, EMBER_D_HI: 165, EMBER_SPREAD: 1.6, STREAK: 1.1, TICK: 0.07,
1021 BED_LO: 0.55, BED_HI: 0.86,
1022}
1023const WHITE = [1, 1, 1]
1024function mix3(a, b, t) {
1025 return [mixN(a[0], b[0], t), mixN(a[1], b[1], t), mixN(a[2], b[2], t)]
1026}
1027function vnoise(u, row) {
1028 const i = Math.floor(u), f = u - i, s = f * f * (3 - 2 * f)
1029 return mixN(hash21(i, row), hash21(i + 1, row), s)
1030}
1031/** The heat ramp: 0 is the bed (or the track ahead), then c1, c0, hot, white, in four even steps. */
1032function f1Ramp(h, base, ink) {
1033 if (h <= 0) return base
1034 if (h >= 1) return WHITE
1035 const k = h * 4, i = Math.floor(k), f = k - i
1036 const stops = [base, ink.c1, ink.c0, ink.hot, WHITE]
1037 return mix3(stops[i], stops[i + 1], f)
1038}
1039/** A bar for the shader. `ink` from one colour: hot = toward white, c0 = itself, c1 = toward black. */
1040function inkOf(hex) {
1041 const c = rgb01(hex)
1042 return { hot: mix3(c, WHITE, 0.45), c0: c, c1: mix3(c, [0, 0, 0], 0.35) }
1043}
1044function fireBar(geo, shown, live, seed, ink, trackHex) {
1045 const s = Math.max(Math.min(shown, 1), 0.02)
1046 return { W: geo.W, H: geo.H, rows: geo.rows, pitch: geo.pitch, cols: geo.cols, shown: s, head: s * geo.W, live, seed, wind: 1, ink, track: rgb01(trackHex) }
1047}
1048function f1Frame(bar, t) {
1049 const { W, pitch, rows, cols, head, live, seed } = bar
1050 const U = Math.sqrt((W * pitch) / (826 * 3.5))
1051 const wind = Math.max(bar.wind ?? 1, 0.05)
1052 const hc = Math.max(0, Math.round(head / pitch - 0.5))
1053 const zone = FC.ZONE * U
1054 const lo = Math.max(0, Math.floor((head - zone) / pitch)), hi = Math.min(cols - 1, hc + 2)
1055 const n = Math.max(0, hi - lo + 1)
1056 const heat = new Float32Array(rows * n)
1057 const mid = (rows - 1) / 2
1058 const pulse = live ? 0.93 + 0.07 * Math.sin(t * 23 + seed) * Math.sin(t * 9.7) : 0.5 + 0.08 * Math.sin(t * 2.1)
1059 const drift = live ? FC.WIND * U * wind * t : 0
1060 for (let cy = 0; cy < rows; cy++) {
1061 const off = Math.abs(cy - mid) / Math.max(mid, 1)
1062 const rowK = 1 - 0.35 * off
1063 for (let cx = lo; cx <= hi; cx++) {
1064 const p = (cx + 0.5) * pitch, d = head - p
1065 let h
1066 if (d < -0.5 * pitch) {
1067 h = d >= -FC.NOSE * pitch ? (live ? 0.8 : 0.5) * pulse * (1 - 0.7 * off) : 0
1068 } else if (d <= FC.CORE * pitch) {
1069 h = live ? (d < 0.3 * pitch ? 1 - 0.12 * off : 1) * pulse + 0.05 : 0.62 + pulse * 0.2
1070 } else {
1071 const du = d / U
1072 const u = (p + drift) / U
1073 const flick = vnoise(u / FC.BODY_CELL, cy * 7.3 + seed)
1074 const body = Math.exp(-(du - (FC.CORE * pitch) / U) / (FC.BODY_LEN * rowK)) * (live ? 0.62 + 0.5 * flick : 0.75)
1075 let tongue = 0
1076 if (live) {
1077 const tn = vnoise((u + (1.3 * drift) / U) / FC.TONGUE_CELL, cy * 3.1 + seed * 0.37)
1078 const s = clamp01((tn - 0.48) / 0.3)
1079 tongue = s * s * Math.exp(-du / (FC.TONGUE_LEN * rowK)) * 1.2
1080 }
1081 h = Math.max(body, tongue)
1082 }
1083 heat[cy * n + (cx - lo)] = Math.min(h, 1)
1084 }
1085 }
1086 if (live) {
1087 const span = FC.EMBER_D_HI / FC.EMBER_V_LO / wind
1088 const iHi = Math.floor(t / FC.EMBER_GAP), iLo = Math.max(0, Math.floor((t - span) / FC.EMBER_GAP) - 1)
1089 for (let i = iLo; i <= iHi; i++) {
1090 const born = (i + 0.8 * hash21(i, seed + 1.7)) * FC.EMBER_GAP
1091 const age = t - born
1092 if (age < 0) continue
1093 const hv = hash21(i, seed + 5.3), hd = hash21(i, seed + 9.1), hy = hash21(i, seed + 13.9)
1094 const v = mixN(FC.EMBER_V_LO, FC.EMBER_V_HI, hv) * U * wind
1095 const reach = mixN(FC.EMBER_D_LO, FC.EMBER_D_HI, hd * hd) * U
1096 const life = reach / v
1097 if (age >= life) continue
1098 const k = age / life
1099 const x = head - FC.CORE * pitch - v * age
1100 if (x < 0) continue
1101 const y0 = mid + (hy - 0.5) * rows * 0.7
1102 const y = Math.max(0, Math.min(rows - 1, mid + (y0 - mid) * (1 + FC.EMBER_SPREAD * k)))
1103 const cy = Math.round(y)
1104 const h0 = (0.85 + 0.3 * hash21(i, seed + 21.1)) * Math.pow(1 - k, 0.7)
1105 const tail = v * FC.TICK * FC.STREAK
1106 const c0 = Math.floor(x / pitch), c1 = Math.floor((x + tail) / pitch)
1107 for (let c = c0; c <= c1; c++) {
1108 if (c < lo || c > hi) continue
1109 const along = c1 > c0 ? (c - c0) / (c1 - c0) : 0
1110 const hh = h0 * (1 - 0.65 * along)
1111 const j = cy * n + (c - lo)
1112 if (hh > heat[j]) heat[j] = hh
1113 }
1114 }
1115 }
1116 return { lo, hi, n, heat }
1117}
1118function f1Shade(cx, cy, bar, s) {
1119 const { pitch, head, ink, track } = bar
1120 const p = (cx + 0.5) * pitch
1121 const h = cx >= s.lo && cx <= s.hi ? s.heat[cy * s.n + (cx - s.lo)] : 0
1122 if (p > head + 0.5 * pitch) return h <= 0 ? null : f1Ramp(h, track, ink)
1123 const g = Math.min(p / Math.max(head, 1), 1)
1124 const a = mixN(FC.BED_LO, FC.BED_HI, g) * (0.94 + 0.06 * hash21(cx, cy + bar.seed))
1125 const bed = mix3(track, mix3(ink.c1, ink.c0, 0.3 * g * g), a)
1126 return f1Ramp(h, bed, ink)
1127}
1128/** The head's soft glow: one radial gradient, screen-blended (desktop only). */
1129function f1Glow(bar, t) {
1130 const U = Math.sqrt((bar.W * bar.pitch) / (826 * 3.5))
1131 const live = bar.live
1132 const pulse = live ? 0.9 + 0.1 * Math.sin(t * 23 + bar.seed) * Math.sin(t * 9.7) : 0.85 + 0.15 * Math.sin(t * 2.1)
1133 return { x: bar.head - (live ? 12 : 4) * U, y: bar.H / 2, rx: (live ? 38 : 14) * U, ry: bar.H * (live ? 0.95 : 0.7), rgb: mix3(WHITE, bar.ink.hot, live ? 0.35 : 0.8), alpha: (live ? 0.34 : 0.14) * pulse }
1134}
1135
1136// ---- Cell bars, per surface: an Svg of rounded squares on the desktop, a half-block Raster on the terminal.
1137/** Where a bar's cells sit. Desktop: `size` px wide, pitch = H / rows. Terminal: `size` columns, two half-block rows. */
1138function geoOf(term, size, H, rows) {
1139 if (term) {
1140 const cols = Math.max(1, Math.min(512, Math.floor(size)))
1141 return { term: true, cols, rows: 2, pitch: 8, H: 16, W: cols * 8 }
1142 }
1143 const W = Math.max(20, Math.floor(size)), pitch = H / rows
1144 return { term: false, W, H, rows, pitch, cols: Math.ceil(W / pitch) }
1145}
1146/**
1147 * One bar. `colorAt(cx, cy)` → [r,g,b] in 0..1, or null for the bare track. `o.ticks`: [{ frac, color, w }] drawn on
1148 * top; `o.glow` (desktop): an f1Glow. Returns null where the surface has neither Svg nor Raster.
1149 *
1150 * The desktop never redraws a bar to animate it (a redraw drops a press), so a desktop bar animates by itself, with
1151 * SMIL inside the Svg, and loops until the next drawing. Two ways:
1152 * `o.anim` { n, dt, at(t) → { colorAt, glow } }: a flip-book of n frames dt apart (the fire); a cell whose colour
1153 * changes gets an <animate> of its fill, a still cell is one <use>. Trimmed to fewer frames if the document would
1154 * pass the Svg limit.
1155 * `o.glint` { from, to, dur, sigma, peak, end }: cells drawn as runs of one colour under a mask of the cell shapes,
1156 * and a soft white band (a Gaussian, `sigma` px wide, `peak` opacity) sweeps from x `from` to `to` every `dur` s,
1157 * over the cells left of `end` px. `colorAt` gives the still colours.
1158 * Neither depends on the clock: the frames run from t = 0 and the sweep starts at its left, so the document is the same
1159 * string from one drawing to the next while the figures hold. That matters: a scroll of the pane is a redraw (its
1160 * `scroll.offset` is a prop), and an Svg whose source has not changed is left running; a changed one is loaded afresh,
1161 * which froze and jumped the bar on every scroll tick.
1162 */
1163function cellBar(ui, key, geo, colorAt, o = {}) {
1164 const track = o.track || PAL.BAR_TRACK
1165 if (geo.term) {
1166 const trackN = parseInt(track.slice(1), 16)
1167 const num = (c) => (c ? parseInt(toHex(c).slice(1), 16) : trackN)
1168 const ticks = new Map((o.ticks || []).map((m) => [Math.max(0, Math.min(geo.cols - 1, Math.floor(m.frac * geo.cols))), m.color]))
1169 if (typeof ui.Raster === 'function') {
1170 const words = new Uint32Array(geo.cols * 3)
1171 for (let cx = 0, i = 0; cx < geo.cols; cx++) {
1172 const a = colorAt(cx, 0), b = colorAt(cx, 1), tk = ticks.get(cx)
1173 if (tk) { words[i++] = 0x2502; words[i++] = parseInt(tk.slice(1), 16); words[i++] = num(b) } // │ a mark
1174 else { words[i++] = 0x2580; words[i++] = num(a); words[i++] = num(b) } // ▀ top cell fg, bottom bg
1175 }
1176 return h(ui.Raster, { key, columns: geo.cols, rows: 1, cells: base64(new Uint8Array(words.buffer)) })
1177 }
1178 const parts = []
1179 let run = '', runKey = '', runProps = null
1180 for (let cx = 0; cx < geo.cols; cx++) {
1181 const tk = ticks.get(cx)
1182 const a = tk || toHex(colorAt(cx, 0) || rgb01(track)), b = toHex(colorAt(cx, 1) || rgb01(track))
1183 const k = `${a}${b}${tk ? '|' : ''}`
1184 if (k !== runKey) { if (run) parts.push(h(ui.Text, runProps, run)); run = ''; runKey = k; runProps = { color: a, backgroundColor: b } }
1185 run += tk ? '│' : '▀'
1186 }
1187 if (run) parts.push(h(ui.Text, runProps, run))
1188 return h(ui.Box, { flexDirection: 'row' }, ...parts)
1189 }
1190 if (typeof ui.Svg !== 'function') return null
1191 const { W, H, pitch, rows, cols } = geo
1192 // one cell shape, placed with <use>; the markup stays small because a desktop drawing may hold a whole loop of frames
1193 const half = 0.375 * pitch, size = (half * 2).toFixed(2), rx = Math.min(0.9, half * 0.35).toFixed(2)
1194 const sid = key.replace(/[^a-z0-9]/gi, ''), cid = `c${sid}`
1195 const rowY = (cy) => ((cy + 0.5) * pitch - half).toFixed(2)
1196 const cellX = (cx) => ((cx + 0.5) * pitch - half).toFixed(1)
1197 const ticks = (o.ticks || []).map((m) => `<rect x="${(m.frac * W - (m.w || 1.5) / 2).toFixed(1)}" y="0" width="${m.w || 1.5}" height="${H}" fill="${m.color}"/>`)
1198 const pad = o.padY || 0, HH = H + 2 * pad
1199 const wrap = (defs, body) => `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${HH}" viewBox="0 ${-pad} ${W} ${HH}"><defs>${defs}</defs>` +
1200 `<rect width="${W}" height="${H}" rx="${o.radius ?? Math.min(4, H / 2)}" fill="${track}"/>${body}${ticks.join('')}</svg>`hooks/glossary.js 133 lines1/**
2 * The glossary: one source for every term the Context pane uses (ported from design/glossary.js, wording kept).
3 * The pane's Explain and Glossary views and `/tokens learn` read it. Each term: what it is, its live value in this
4 * session (from L, the live numbers), and what to do. A live line built from a missing number is dropped by the
5 * caller (see glossaryFor in register.js), never shown as "undefined".
6 *
7 * Writing rules: no "turn" or "prefix"; every term says why you would care; at most two sentences before the action.
8 */
9export function GLOSSARY(L) {
10 return [
11 { group:'Basics', terms:[
12 { id:'context', name:'Context',
13 what:'Everything Claude reads before it answers: your messages, its replies, tool output, and the instructions and tools that load with every conversation.',
14 live:`${L.used} of ${L.win} tokens (${L.pct}%).`,
15 todo:'Keep one task per conversation, so it stays small.' },
16 { id:'window', name:'Context window',
17 what:'The most Claude can hold at once. Near the end it compacts on its own, and answers get slower and dearer before that.',
18 live:`${L.win} tokens for this model.` },
19 { id:'tokens', name:'Tokens',
20 what:'The unit Claude reads and bills in. A token is roughly three quarters of a word.',
21 live:`This conversation is ${L.used} tokens.` },
22 { id:'requests', name:'Messages and requests',
23 what:'You send a message; while working on it Claude makes a request each time it uses a tool. Every request reads the whole context again.',
24 live:`${L.requests} requests so far this session.` },
25 { id:'estimate', name:'Estimates (≈)',
26 what:'Money figures are worked out from your rate per million tokens. Your bill is the real number.',
27 live:L.api ? `At ${L.rate} per million input tokens.` : 'Subscription: shown as tokens and share of your 5-hour window, never dollars.' },
28 ] },
29 { group:'Working memory', terms:[
30 { id:'messages', name:'Messages',
31 what:'Your messages, Claude’s replies and the results of the tools it used. The part that grows as you work.',
32 live:`${L.messages} (${L.messagesPct}).`,
33 todo:'Start a fresh conversation when the topic changes.' },
34 { id:'mcp', name:'MCP tools',
35 what:'Descriptions of the tools your connected MCP servers offer. They load with every request, used or not.',
36 live:`${L.mcp} (${L.mcpPct}) from ${L.mcpServers} servers.`,
37 todo:'/mcp: turn off the servers you do not use here.' },
38 { id:'deferred', name:'Deferred tools',
39 what:'Tools that load only when Claude first uses one. Until then they cost nothing, so they show a dash instead of a share.',
40 live:`${L.mcpDeferred} MCP and ${L.sysDeferred} system tools waiting.` },
41 { id:'skills', name:'Skills',
42 what:'A one-line description of each skill you have, so Claude knows it can use it. The full skill loads only when used.',
43 live:`${L.skills} from ${L.skillCount} skills.`,
44 todo:'/loadout: park the skills you never call.' },
45 { id:'system', name:'System prompt and system tools',
46 what:'Claude Code’s own instructions and built-in tools. The same in every conversation; you cannot trim them.',
47 live:`${L.system} + ${L.sysTools}.` },
48 { id:'memoryfiles', name:'Memory files',
49 what:'CLAUDE.md, AGENTS.md and rules files. Loaded into every conversation, so every line costs on every request.',
50 live:`${L.memory} from ${L.memoryCount} files${L.memoryTwice ? '; one is loaded twice' : ''}.`,
51 todo:'/memory: drop the duplicate, and keep these files short.' },
52 { id:'buffer', name:'Autocompact buffer',
53 what:'Room kept free so Claude can write its summary before the window runs out.',
54 live:`${L.buffer} reserved.` },
55 { id:'free', name:'Free space',
56 what:'What is left before auto-compact starts.',
57 live:`${L.free} left.` },
58 ] },
59 { group:'Cache', terms:[
60 { id:'cache', name:'Prompt cache',
61 what:'Anthropic keeps a copy of your conversation for a while after each request. Reusing that copy costs a tenth of reading it fresh, and Claude starts answering sooner.',
62 live:L.cacheLine,
63 todo:'Reply while it is warm, and avoid changes that break it (switching model, editing CLAUDE.md, turning MCP servers on or off).' },
64 { id:'warmth', name:'Very warm, warm, chill, cold, frozen',
65 what:'Very warm, warm and chill: the copy is there, freshest first. Cold: the last minutes before it lapses (the last third of a 5-minute cache). Frozen: it lapsed, so the next request pays to store everything again.',
66 live:L.cacheState },
67 { id:'ttl', name:'Cache lifetime',
68 what:'How long the copy lasts after it was last used: five minutes, or an hour on some plans. Every reuse starts the clock again.',
69 live:`${L.ttl} on this session.` },
70 { id:'recache', name:'Re-cache',
71 what:'Storing the whole conversation again after the cache lapsed. It costs 1.25 times the normal price, on every token.',
72 live:L.api ? `Would cost ≈ ${L.coldCost} right now.` : `Would re-process ${L.used} right now.` },
73 { id:'hit', name:'Hit rate',
74 what:'How much of the last request came from the cache. High is good; a sudden drop means something broke it.',
75 live:`${L.hit}% on the last request.` },
76 { id:'keepwarm', name:'Keep-warm',
77 what:'While you are away, the plugin sends a tiny request just before the cache lapses, so it stays warm. API billing only; it stops after a few tries.',
78 live:L.api ? (L.keepWarmOn ? `On: ${L.pings} of ${L.pingCap} pings used this break.` : `Off: ${L.keepWarmWhy}.`) : 'Off: a subscription already keeps the cache for an hour.' },
79 ] },
80 { group:'Actions', terms:[
81 { id:'clear', name:'Clear',
82 what:'Starts a fresh conversation. Free and instant, but Claude forgets everything not written down.',
83 todo:'Write a handoff first.' },
84 { id:'compact', name:'Compact',
85 what:'Replaces the conversation with a summary, so you keep going with less. It reads everything one more time, so it is cheap only while the cache is warm.',
86 live:L.cacheWarm ? 'Warm now: compacting is cheap.' : 'Cold now: Clear is cheaper.' },
87 { id:'handoff', name:'Handoff',
88 what:'A short note of where you are and what comes next, so a fresh conversation picks up without you explaining again.',
89 todo:'Write one before you Clear.' },
90 { id:'marks', name:'Marks',
91 what:'Your thresholds. At watch, note decisions as you go; at handoff, write one and Clear; at compact, compact while warm.',
92 live:L.nextMark,
93 todo:'Change them in thresholds.json.' },
94 { id:'autocompact', name:'Auto-compact',
95 what:'Claude Code compacts on its own near the end of the window, whether the cache is warm or not.',
96 live:`At ${L.auto}%.` },
97 ] },
98 { group:'Savings', terms:[
99 { id:'saved', name:'Saved',
100 what:'Tokens the plugin itself kept off your bill this session: trimmed output, compactions it vetoed, and keep-warm net of its pings. Claude\'s own prompt cache is not counted.',
101 live:L.api ? `${L.saved} tokens ≈ ${L.savedUsd}.` : `${L.saved} tokens.` },
102 { id:'cut', name:'Cut % of input',
103 what:'Saved, divided by what you would have sent without the plugin.',
104 live:`${L.share}% this session.` },
105 { id:'cachereads', name:'Prompt cache',
106 what:'Tokens Claude served from its own cache at a tenth of the price. That happens with or without the plugin, so it is shown for context and never counted as saved.',
107 live:`${L.cacheRead} read this session.` },
108 { id:'trimmed', name:'Trimmed output',
109 what:'Long tool output cut to its start and end before Claude reads it. What was cut never enters the conversation, so it is never sent again.',
110 live:`${L.keptOut}, kept out of ${L.keptRequests} requests.` },
111 { id:'rewrites', name:'Quiet rewrites',
112 what:'Noisy commands changed to their quiet versions before they run, such as git status with short output.',
113 live:`${L.rewrites} this session.` },
114 { id:'blocked', name:'Cold compaction blocked',
115 what:'The plugin stops a compaction that would pay to store everything again while the cache is cold.',
116 live:`${L.vetoes} blocked, ${L.vetoTok} saved.` },
117 { id:'agents', name:'Agents',
118 what:'Each agent Claude starts remembers what it has read for 5 minutes. If one step takes longer (a build, a test run), its next step re-reads everything at full price. The plugin counts those re-reads; it cannot stop them.',
119 live:L.agentLapses ? `${L.agentLapses} re-read${L.agentLapses === 1 ? '' : 's'} after a long wait, ${L.agentLapseTok} tokens, not counted as saved.` : 'None this session.',
120 todo:L.agentLine || '' },
121 ] },
122 { group:'Billing', terms:[
123 { id:'api', name:'API billing',
124 what:'You pay per token. The pane shows dollars, worked out from your rate.' },
125 { id:'subscription', name:'Subscription',
126 what:'Your plan has usage limits instead of a bill. The pane shows tokens and your share of the 5-hour window, never dollars.' },
127 { id:'window5h', name:'5-hour window',
128 what:'Your plan’s rolling usage limit. When it is full you wait for it to reset.',
129 live:`${L.windowUsage}% used, resets in ${L.windowResets}.` },
130 ] },
131]
132}
133