SLOPSHOPPER

token-tax-weather

Context weather, turn cache telemetry, and generation speed in the band; warming state, session savings, and rate discount on the status line. Includes…

bandcommandstatuspromptmodeltimer
v0.4.25no licenseupdated 2026-10-15gelwuyl/token-tax-weather/token-tax-weather
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · token-tax-weather
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /keepwarm ⎿ token-tax-weather: keepwarm on for 6h00m, a ping 50m after each idle stretch keeps the cache read, not re-written ☁ Cloudy 97.4k / 200k (49%) · ▄ · 1 call / 91k cache / 93% ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ token-tax-weather: on · ends 2:53pm · ping at 9:43am · 91k session, 86% saved · /cache-tax for the full card

Draws

Band
☁ Cloudy 97.4k / 200k (49%) · ▄ · 1 call / 91k cache / 93%
README

token-tax-weather

A forecast band above the prompt, a quiet state line beside the model picker.

Every long-running agent session lives under atmospheric pressure. Context accumulates turn by turn, the prompt cache cools in the silence between human thoughts, and autocompaction looms at the window's edge. token-tax-weather gives this invisible physics a visible, unobtrusive horizon right where you compose your next thought:

  • The AbovePrompt band charts the live weather of your context window: current atmospheric fill, remaining headroom before /autocompact, a 3-bar trajectory sparkline, directional delta trend, turn cache efficiency, and token generation speed.
  • The status line anchors persistent telemetry beside the model picker: whether /keepwarm is armed, absolute clock times for the next ping and window expiry, cumulative session tokens saved, and the model's rate discount — or, where no connected surface can paint the band, the context facts themselves.
  • A notice briefly supersedes the status line when a threshold is breached or an action demands attention: cold resumes, expiring caches, and unbudgeted writes.

Install

/plugin marketplace add gelwuyl/token-tax-weather
/plugin install token-tax-weather@token-tax-weather

With the claude CLI:

claude plugin marketplace add gelwuyl/token-tax-weather
claude plugin install token-tax-weather@token-tax-weather

The band needs desktop or terminal. Where no connected surface supports it, the status line carries the window facts itself — a substitution, not an extra readout beside the band.

Commands

CommandWhat it does
/keepwarmArms a six-hour warming window, pinging after 50 minutes of idle
/keepwarm 90m, /keepwarm 2h30m, /keepwarm 6hArms a window of that length
/keepwarm 6h every 20mStarts the search at a 20-minute idle interval; the window must precede every. The interval then converges as pings bracket the provider TTL
/keepwarm alwaysSix-hour window, for cache-tax compatibility; not unbounded, not remembered across sessions
/keepwarm offDisarms warming
/keepwarm statusReports what is armed
/cache-taxThe full card: cache state, context, window, autocompact threshold, token counts, rates, price comparison, warming break-even
/cache-tax-diagnosticRead-only report of whether the host exposes pricing; prints no settings values
  • There is no /keepwarm on. Run bare /keepwarm to arm it. A displayed on is an operational state label, not an executable command.

How /keepwarm works

Warming is an actual model request, not an HTTP header. It is a conversation kept alive across silence. Prompt caching is provider-side: the host keeps the processed token prefix in memory, bills a fraction of the input rate to read it, and evicts it after an unadvertised idle duration. Re-sending the prefix resets that timer. A ping does not petition a server to preserve state — it exercises the cache, which is the singular physical event that keeps it warm.

  • Arming sends nothing. It simply arms a quiet timer.
  • When the timer fires, the plugin invokes the engine's fork, replaying the session's exact prefix — model, system prompt, active tools, and conversation history — capped with a single prompt: ``text Reply with the single word: warm `` The call is tool-less, routed through your session's existing authenticated path, and the trailing ping word is never cached.
  • Survival is verified empirically, never assumed. The reply returns the engine's verified token counts:
  • read > 0 and write < 10% read: The prefix was served warm; the window remains safely armed.
  • read 0 or a write comparable to the read: The cache has evaporated; the window disarms immediately, logging the cache was gone to the status line and /cache-tax.

How the ping interval converges

every defines the starting frontier, not a permanent cadence. Each ping tests the provider's unadvertised TTL clock against a known idle duration, tightening a binary search bracket around the boundary:

Ping attemptBracket establishedNext scheduled ping
50m, coldTTL is strictly under 50m25m
25m, warmTTL is at least 25m38m
38m, warmTTL is at least 38m44m
44m, warmTTL is at least 44m47m
47m, coldTTL is strictly under 47m45m
45m, coldTTL is strictly under 45mSettles stably at 42m

The search halts once the bracket narrows to a two-minute margin, locking into the longest proven survival gap less that buffer. This avoids the wasteful polling of naive halving (which would have stuck at 25m, sending nearly 1.8× more requests). Cadence is clamped at one minute minimum, stops immediately if the route caches nothing at all, and persists in session storage so subsequent windows resume at the learned interval.

Four operational boundaries:

  • Provider-agnostic by design. Anthropic explicit breakpoints and automatic gateway prefix caching are both preserved identically through reuse, requiring no custom headers.
  • Warming cannot create caching upstream. If the harness or provider does not mark the prefix as cacheable, pings record zero reads and the window halts.
  • Gateway response caches are separate. Router-level whole-response caches (such as OpenRouter's) are orthogonal to prompt caching and unaffected by pings.
  • Warming spends model tokens. When cacheWrite is zero, a cold re-write costs nothing in dollars — so warming protects interactive latency, not financial spend.

The band

The composer is where intent becomes a prompt. The band sits directly above it, transforming the hidden physics of the engine into quiet peripheral awareness — so you sense the weight of the conversation and the proximity of compaction before you press Return.

<forecast>  <context> / <window> (<percent>%) · [sparkline] · [trend] · [<to go> to go (<to-go%>)] · [<n> calls / <tokens> cache / <hit>%] · [<speed> tok/s]

Slots with no data are omitted, never left blank; · separates slots and / separates fields within one. Token counts use k or M, to one decimal place, trailing .0 dropped.

The coloured slots lead. The forecast, the fill, and the sparkline share the forecast's hue, anchoring the visual weight on the left; the dim operational metrics follow in quiet alignment.

SlotFormsShown whenWhat it means
forecast☀ Clear · ☁ Cloudy · ☂ Showers · ☇ Storm · ↯ Compact soonAlwaysThe atmospheric barometer: yellow (<25%), cyan (25–50%), blue (50–75%), magenta (75–90%), and red (90%+). The forecast sets the dominant color for the entire leading group
fill<context> / <window> (<percent>%)AlwaysThe engine's empirical ground truth — the actual prompt footprint ingested by the model on the last turn, measured against the window ceiling. Both the fill percentage and headroom to go share this exact denominator
sparklineup to three bars from ▁▂▃▄▅▆▇█A completed reading exists, and 56+ columnsA three-bar seismic trajectory. Scaled against the window and painted in the forecast's hue, showing whether context is cresting or stabilizing across recent turns without demanding numeric reading
trend▲ +<tokens> · ▼ <tokens> · steadyTwo or more readings, and 72+ columnsDirectional velocity of context since the last turn. The glyph carries direction; color communicates consequence: green on reduction (▼), yellow on growth (▲), urgent red when growth enters Compact soon, and dim for quiet equilibrium (steady)
to go<tokens> to go (<to-go%>) · compact dueA context exists, and the engine reports an autocompact thresholdRemaining headroom before /autocompact triggers and shears history. Stays unobtrusively dim while headroom remains; flashes red in exact synchrony with the forecast ramp at 90%
turn cache<n> calls / <tokens> cache / <hit>%A turn has completedThe mechanical efficiency of the turn just gone: roundtrip model calls, prompt tokens served warm from cache, and cache hit percentage. Never silent: cold turns report 0 cache / 0% with honest precision
speed<speed> tok/sGeneration timing is recordedModel generation throughput averaged across all calls of the completed turn

Widest to narrowest:

↯  Compact soon  326.5k / 362k (90%)  ·  ▆▇█  ·  ▲ +12k  ·  compact due  ·  42 calls / 13.7M cache / 99%  ·  68 tok/s
☇  Storm  299.9k / 362k (83%)  ·  ▄▅▆  ·  ▲ +12k  ·  20.1k to go (5.6%)  ·  42 calls / 12.6M cache / 99%  ·  68 tok/s
☁  Cloudy  164.1k / 362k (46%)  ·  ▂▃▄  ·  ▲ +12k  ·  155.9k to go (43.1%)  ·  1 call / 164.1k cache / 99%
☀  Clear  60.2k / 362k (17%)  ·  259.8k to go (71.8%)  ·  1 call / 0 cache / 0%
☁  Cloudy  164.1k / 362k (46%)  ·  1 call / 0 cache / 0%
  • Every percentage in the band shares the window as its single denominator, preventing misleading mental conversions across varying bases.
  • Only the sparkline and trend drop under narrow viewports. Concrete metrics remain anchored for as long as terminal width allows.
  • The turn cache slot unifies three interdependent facts — model calls, cache volume, and hit rate. Dividing cache volume by calls reveals the effective context carried per step.
  • cache reports zero rather than fading into silence. A cold turn explicitly prints 0 cache / 0%, confirming the cache served nothing rather than leaving the operator to wonder if telemetry dropped.
  • The session token count lives on the status line, keeping the AbovePrompt band dedicated to the tactical dynamics of the current turn.
  • The fill is the engine's reported input side, not a synthetic sum of category estimates. It represents the exact input tokens the model processed (uncached, cache-read, and cache-written combined). /cache-tax prints both context and rows side by side so discrepancies in local category estimates remain transparent.
  • Headroom is reported solely as to go to compaction. Rather than confusing users with multiple conflicting free-space numbers, to go measures the true operational distance from current fill to the autocompact threshold.

The status line

The band is live atmospheric weather; the status line is grounded operational navigation. It sits beside the model picker, providing a single consolidated status readout that prioritizes urgent events over ongoing background state.

The lineDrawn whenCarries
a noticean event demands immediate attentionwhat happened, the cost impact, and what to do — an ephemeral high-priority alert that outranks all standard telemetry
the desktop and terminal formno notice, and a connected surface draws the bandwarming state, clock-time pings, session savings, rate discount, and command hints
the VS Code and mobile formno notice, and no connected surface draws the bandstate, ping, bare context count, turn cache, speed, and savings — self-contained fallback telemetry

Only one of the three can ever draw. On the desktop and terminal surfaces you only ever see the desktop and terminal form; the other is for a session attached to VS Code or a phone. The app clips this row and reveals the rest on hover, so the plugin writes the whole string and a long line costs nothing. It is plain text — the price carries no colour, so its form is the whole of what it can say.

When the line repaints

The band is redrawn by the app whenever it redraws the composer, so it is always current. The status line is not — it is a value the app holds until something sets it again.

Repaints atWhy then
session start, and again 3 seconds laterthe desktop surface attaches just after the session starts, so the first paint can be dropped
a resumed sessiona cold-resume notice has to be shown before any turn runs
a prompt is sentthe surface is certainly live by then, and a guard notice belongs to the prompt it warns about
a turn finishesthe context, the cache figure and the price have all changed
/keepwarm is run, and when a window arms or stopsthe state it reports is the thing that just changed

So the row names moments, not waits. A countdown written into a row that does not tick decays where it sits: 6h00m left, read forty minutes later, overstates what is left by forty minutes, and nothing on the row corrects it. A clock time says the same thing at every reading, which is why the row writes ends 7:00pm and ping at 1:50pm and stays true until the next paint. The /cache-tax card keeps its durations — it is a printout, read as it is written, and there the wait is the useful figure.

Switching to another session shows that session's own row, painted at its own last event. Because a notice is put on this row and taken off again at the end of its turn, it is a thing to read now rather than a durable state: visible for at least the turn it belongs to, and a cold-write notice for the turn after it as well.

A notice

One-off messages about an event, not the ongoing state; a newer one replaces the older. Each has three parts — what happened, the figure, and what to do.

NoticeFormRaised whenClears
resumecold resume · first message ≈<usd>a resumed or forked session's prompt cache is likely expiredat the end of the turn it belongs to
guardcold <age> · re-write ≈<usd> · sendinga prompt is sent after the estimated cache lifetime has elapsedat the end of the turn it belongs to
cold writecold write <tokens> · <usd> · /keepwarma turn records a large fresh cache writeat the end of the turn after it, since it is raised at the end of its own
cold resume · first message ≈$4.01
cold 2h00m · re-write ≈$4.01 · sending
cold write 200.5k · $4.01 · /keepwarm

A figure the plugin cannot price reads n/a, and the resume form then falls back to cold resume · the next message re-writes the context. A guard never blocks or drops a prompt. The rates behind each figure are in /cache-tax.

The desktop and terminal form, while the band is drawing

<state> · [ends <clock>] · [ping] · [<cost>] · [/keepwarm to arm the window] · /cache-tax for the full card
#SlotFormsShown whenWhat it means
1stateoff · on · stopped: <reason>Alwaysstopped names why a window gave up early, which is what tells a failure from a window that simply ran out its hours — that one reads off, as an unarmed window does
2windowends <clock>A warming window is armedWhen the window /keepwarm armed runs out — a budget this plugin chose, not a cache lifetime a provider promised
3pingping at <clock> · (held <gap>) · (went at <gap>) · ping after first turn · ping after next turnA warming window is armedThe gap is what the last ping proved about the provider's TTL, and it moved the interval the next ping uses. The two ping after forms stand in for the time while there is no warm reading to count from
4cost<tokens> session, <saving>% saved · n/aA context existsSession savings and rate discount. Shows total cache tokens saved across all turns since /clear, paired with the model's rate discount. Displays 0 session, 93% saved before any turn has hit cache.
5arm hint/keepwarm to arm the windowNo warming window is armedThe command that changes the state in slot 1
6card hint/cache-tax for the full cardAlwaysEverything this row has no width for
off · 41.6M session, 93% saved · /keepwarm to arm the window · /cache-tax for the full card
on · ends 7:00pm · ping at 1:50pm · 41.6M session, 93% saved · /cache-tax for the full card
on · ends 7:00pm · ping at 2:40pm (held 50m) · 41.6M session, 93% saved · /cache-tax for the full card
on · ends 7:00pm · ping at 2:15pm (went at 50m) · 41.6M session, 93% saved · /cache-tax for the full card
on · ends 7:00pm · ping after first turn · 93% saved · /cache-tax for the full card
stopped: ping not sent (nothing-to-fork) · 41.6M session, 93% saved · /keepwarm to arm the window · /cache-tax for the full card

The cost slot pairs session tokens with the rate discount. The session tokens count what the cache has saved across all completed turns since /clear (0 session before the first cached turn). The saving is what a carried token costs against an uncarried one. A surcharge or a zero keeps its signed money — +$0.03, +$0.00 — because a percentage could not say it. No rates at all is n/a.

The VS Code and mobile form, while no surface raises the band

The same facts, compactly, with the context as a bare token count — there is no room for the window beside it. It is the desktop and terminal form plus the window, minus the hints.

<state> · [ping] · <context> · [<n> calls / <tokens> cache / <hit>%] · [<speed> tok/s] · [<cost>]
#SlotFormsShown whenWhat it means
1stateoff · ends <clock> · stopped: <reason>AlwaysThe same facts as the other form's state slot, with no on: an armed window is already saying when it ends
2pingAs the desktop and terminal form'sA warming window is armed
3contextctx <tokens> · no context yetAlwaysA bare count, because this row has no width for the window beside it
4cache<n> calls / <tokens> cache / <hit>%A turn has completedThe band's turn cache slot, in the same words, because this row is the only surface showing it
5speed<speed> tok/sGeneration timing is recordedModel generation throughput
6costAs the desktop and terminal form'sA context exists
off · ctx 199.1k · 1 call / 190.4k cache / 99% · 41.6M session, 93% saved
ends 7:00pm · ping at 1:50pm · ctx 199.1k · 1 call / 190.4k cache / 99% · 41.6M session, 93% saved
ends 7:00pm · ping after next turn · ctx 199.1k · 1 call / 0 cache / 0% · 41.6M session, 93% saved
off · no context yet

The forecast, fill, sparkline, trend, to-go, session and command hints are all dropped here — this row has no width for them, and no band above it carries them either, which is why the window slots are here and not there.

Rates and price comparison

Providers quote rates per million tokens, but a rate is not a bill. /cache-tax translates raw rates into concrete dollars for the exact context currently in memory, comparing three distinct scenarios against the uncached baseline:

cost        for 66.7k tokens   no cache $0.03 = 100%
                               from cache $0.0020 = 7% of that
                               re-write $0.00 = 0% of that
  • no cache is the baseline: the entire context billed as fresh, uncached input.
  • from cache is the same context read from a warm prompt cache.
  • re-write is the context written to cache anew after eviction.
  • The share beside each is relative to the baseline, so efficiency is obvious without mental arithmetic. A real but rounding share prints <1% rather than 0% to keep "nearly nothing" distinct from "nothing".

The net financial effect is from cache minus no cache:

  • A saving is parenthesised, ($0.03): reading from cache costs less than the baseline. Parentheses are accounting's native mark for a credit, avoiding ambiguity with hyphens.
  • A surcharge carries a leading +, +$0.03: reading from cache costs more than uncached input.
  • Zero is +$0.00: input and cache-read costs are equal.
  • n/a: no rates are configured for the active model.

Rate configuration and discount math

Prices are user-supplied USD per million tokens, defined in token-tax-weather/hooks/register.ts:

export const RATES: Record<string, Rates> = {
  'claude-fable-5': { input: 0.43, cacheRead: 0.03, cacheWrite: 0, output: 0.87 },
  'claude-opus-5-5': { input: 0.0348, cacheRead: 0.005, cacheWrite: 0, output: 0.1392 },
}
  • Keys match the engine's exact model ID, never the UI picker's display label. Unconfigured models display n/a; rates are never borrowed across models.
  • The rate discount is invariant to context size. The status line displays 41.6M session, 93% saved (or 0 session, 93% saved before cache hits). The percentage is (input - cacheRead) ÷ input — because token count cancels out of the fraction, the discount percentage is constant across all context sizes, while the dollar value it represents grows with every turn.
  • The break-even reality. When a provider prices cacheWrite at zero, a cold re-write incurs no dollar surcharge. At those rates, paid warming cannot pay for itself in monetary savings alone; its true return is eliminating the time-to-first-token latency penalty of re-ingesting massive context windows.

Privacy and limits

  • Local token counts and the engine's free context breakdown. That is what the readout is built from.
  • Diagnostics print no settings values.
  • No automatic warming, and no provider probe. An explicitly armed /keepwarm window does send model requests.
  • Prompt-cache observations do not establish an OpenRouter response-cache hit. This plugin neither controls nor reports that separate cache's TTL or HIT/MISS.

Development

npx -y @anthropic-ai/claude-code@2.1.293 plugin test ./token-tax-weather
npx -y @anthropic-ai/claude-code@2.1.293 plugin validate ./token-tax-weather

Tests mount the real surface and inspect its drawn tree. The engine generates API declarations under .claude-plugin/types/ when it loads the plugin; they are gitignored. Type-check after those declarations exist.

Relation to cache-tax

This supersedes cache-tax 2.1.3 and registers the same /keepwarm and /cache-tax commands. Enable only one; a plugin that finds the names already taken skips them and reports the conflict.

Source 1 files
hooks/register.ts 1521 lines
1import type {
2  BoxProps,
3  CommandSpec,
4  ElementConstructor,
5  EngineInterface,
6  Register,
7  RenderElement,
8  RenderSurface,
9  SettingsReadArgs,
10  SettingsSource,
11  TextProps,
12} from 'claude-code'
13
14// token-tax-weather — supersedes the Original Mod (cache-tax 2.1.3).
15//
16// Ported from the Original Mod with six deliberate changes:
17//   1. the hard-coded first-party PRICES table is replaced by user-supplied rates
18//   2. uncached input is its own rate, not half the cache-write rate
19//   3. the guard warns only; no prompt is ever dropped
20//   4. warming is never armed automatically, only by an explicit command
21//   5. the status line is repainted as state changes — session start, every
22//      turn, every command — instead of being written once and left to go stale
23//   6. output never repeats the plugin name the host already prints
24
25const TTL_MS = 60 * 60 * 1000
26const PING_AFTER_MS = 50 * 60 * 1000
27const MIN_PING_MS = 60 * 1000
28const DEFAULT_WINDOW_MS = 6 * 60 * 60 * 1000
29const BIG_TOKENS = 50000
30const PING_PROMPT = 'Reply with the single word: warm'
31/**
32 * The safety margin subtracted from a gap a ping survived, and the width at
33 * which the search stops looking. One figure does both jobs because a bracket
34 * narrower than the margin cannot say anything the margin does not already
35 * cover: below it, the conservative answer and the precise one are the same
36 * interval.
37 */
38const TUNE_MARGIN_MS = 2 * 60 * 1000
39
40// Namespaced so the Custom Mod never inherits the Original Mod's window, ping
41// period, or `always` flag — inheriting `always` would arm paid warming on its
42// own at session start.
43const KEY_DEADLINE = 'token-tax-weather:deadline'
44const KEY_EVERY = 'token-tax-weather:every'
45const KEY_GUARD = 'token-tax-weather:guard'
46
47const rateKeys = ['input', 'cacheRead', 'cacheWrite', 'output'] as const
48type Rates = { input: number; cacheRead: number; cacheWrite: number; output: number }
49
50// USER-SUPPLIED rates in USD per million tokens, keyed by the exact model ID the
51// engine reports. Desktop does not hand its managed four rates to a plugin, so
52// every cost below is only as right as this table, and is always labeled
53// user-supplied. Zero is a valid rate — cacheWrite is zero here, which means a
54// cold re-write is billed at nothing and break-even reports not-applicable. A
55// model with no row shows an explicit unknown cost rather than borrowing
56// another model's rates.
57//
58// These are the operator's own figures, moved between models on request. On
59// 2026-10-10 the Fable row took over the numbers first given for Opus, and Opus
60// took the second set. Both are stated per million tokens; if an operator quotes
61// a provider's per-1K numbers instead, the whole table is 1000x out.
62//
63// Note on the Opus row: its cacheRead (0.005) is now below its input (0.0348),
64// so reading the prompt cache costs less than sending the same context uncached.
65// The cacheWrite is zero, so a cold re-write is billed at nothing and warming
66// still cannot pay for itself at these rates. The card reports what the
67// arithmetic says; it does not pretend the figures are typical.
68//
69// Add rows in this shape, then update the plugin:
70//
71//   'claude-opus-5-5': { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
72//
73export const RATES: Record<string, Rates> = {
74  'claude-fable-5': { input: 0.43, cacheRead: 0.03, cacheWrite: 0, output: 0.87 },
75  'claude-opus-5-5': { input: 0.0348, cacheRead: 0.005, cacheWrite: 0, output: 0.1392 },
76}
77
78const RATE_SOURCE = 'user-supplied rates'
79
80type PingRecord = { at: number; idle: number; read: number; write: number; usd: number | null; warm: boolean }
81type Miss = { at: number; tokens: number; usd: number | null }
82type GuardMode = 'warn'
83
84export type State = {
85  sid: string
86  deadline: number
87  every: number
88  /**
89   * The two bounds the pings have put on the provider's cache TTL, which nothing
90   * in the engine reports: `warmAt` is the longest idle gap a ping survived, a
91   * proven floor, and `coldAt` the shortest one that failed, a proven ceiling.
92   * Together they close on the TTL from both sides — walking down from a failure
93   * alone would settle for the first gap that happened to work, so a 45m TTL
94   * reached through a cold 50m would leave the window pinging at 25m forever.
95   * Zero and null before any ping has answered.
96   */
97  warmAt: number
98  coldAt: number | null
99  lastRequestAt: number
100  lastModel: string | null
101  ctx: number
102  /**
103   * What the breakdown's own rows add up to, free space, compaction buffer and
104   * deferred schemas aside. Kept only to be shown beside `ctx` on the card: the
105   * rows are the engine's estimates of what fills the window, and this band draws
106   * the engine's `context.tokens` instead, so the two disagreeing is the fact that
107   * explains a band that looks wrong next to the context popover.
108   */
109  rowsTokens: number
110  compacted: boolean
111  guard: GuardMode
112  coldWritePending: boolean
113  misses: Miss[]
114  pending: { cancel: () => void } | null
115  last: PingRecord | null
116  stopped: string | null
117  /** Cache-read tokens of the last completed main turn: what the cache actually served. */
118  lastRead: number
119  /**
120   * The last completed main turn's whole prompt, summed over its calls: the three
121   * input fields, which are disjoint slices of one prompt. `lastRead` against this
122   * is the turn's hit rate — how much of what was sent the cache carried — and it
123   * is a measurement, where the read rate against the input rate is only a price.
124   */
125  lastPrompt: number
126  /**
127   * Cache-read tokens summed over every main turn since the last /clear: the
128   * running total, where `lastRead` is only the turn just gone. A compaction does
129   * not start a new conversation, so it survives `session.compact` the same way
130   * the cold-write tally below does; only /clear resets it.
131   */
132  readSession: number
133  /** Completed main turns since the last /clear: what `readSession` was summed over. */
134  turns: number
135  /**
136   * Model calls the last completed main turn made, from the engine's own step
137   * index. A turn makes one model call per step, and the engine numbers a turn's
138   * steps from 0, so the highest index seen is one less than the count.
139   *
140   * This is the fact that makes `lastRead` legible: a turn's usage is its calls
141   * summed, so a long agentic turn reads the context once per call and the total
142   * runs to many times the context. `150.9k cache turn` beside a 157.9k context
143   * reads as a miscount until the call count that produced it is on the row too.
144   */
145  calls: number
146  /** Steps seen in the turn now running; moved into `calls` when that turn completes. */
147  steps: number
148  /** Output tokens generated across all steps of the last completed main turn. */
149  turnOut: number
150  /** Generation duration in milliseconds summed across the model calls of the last turn. */
151  turnDurationMs: number
152  /** Generation speed in tokens per second for the last completed turn, or null. */
153  speedToksPerSec: number | null
154  /** Live accumulator of step output tokens for the turn in flight. */
155  accumStepsOut: number
156  /** Live accumulator of step duration in milliseconds for the turn in flight. */
157  accumStepsDurationMs: number
158  /** True once this mod's command names are the session's, so the footer slot is ours to write. */
159  owns: boolean
160  /** The window the fill is measured against: the compaction window /autocompact sets, else the model's. */
161  window: number
162  /** The fill as a whole percentage of `window`. */
163  percent: number
164  /** Where that window came from (the engine's `ContextWindowSource`), or null when only the model's is known. */
165  windowSource: string | null
166  /**
167   * Tokens the window has left, from the breakdown's `free` row. The band does not
168   * draw it — it measures nearly the same thing as `compactAt` and so read as a
169   * near-duplicate — but `/cache-tax` reports it, because the card is where the
170   * complete set of figures belongs. Zero when the host reports no breakdown.
171   */
172  free: number
173  /**
174   * The token count auto-compaction fires at, as the engine reports it, or null
175   * when it is off or unreported. Kept so `/cache-tax` can show the engine's own
176   * threshold rather than a guess derived from the window.
177   */
178  compactAt: number | null
179  /** Recent readings of the context size, oldest first: the sparkline and the per-turn trend. */
180  history: number[]
181  /**
182   * The clock as of the last event that could change what the band says. A
183   * `ui.render` hook draws synchronously and `$.clock.now()` only answers a
184   * promise, so the countdown reads this rather than asking again; every event
185   * that repaints stamps it first.
186   */
187  now: number
188  /** The surface this session runs on: the band is raised on `desktop` and `terminal` only. */
189  surface: string
190  /**
191   * The one-off line pinned on the status line ahead of the readout, or null for
192   * none. It carries a cache-state notice — a cold resume, a cold send, a recorded
193   * cold write — rather than the continuously-updating facts, so it is read once
194   * and not scrolled back to. A second notice simply replaces the first: last
195   * writer wins, which is what the status line itself does.
196   */
197  notice: string | null
198}
199
200/** The configured rates for a model, or null when none are configured. Exact ID only. */
201export function ratesFor(model: string | null): Rates | null {
202  if (!model) return null
203  const row = RATES[model] ?? RATES[model.toLowerCase()]
204  if (!row) return null
205  const ok = rateKeys.every(k => typeof row[k] === 'number' && Number.isFinite(row[k]) && row[k] >= 0)
206  return ok ? row : null
207}
208
209export function parseDuration(text: string): number | null {
210  const m = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(text.trim())
211  if (!m || (m[1] === undefined && m[2] === undefined)) return null
212  return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60 * 1000
213}
214
215export function fmtDuration(ms: number): string {
216  const total = Math.max(0, Math.round(ms / 60000))
217  const h = Math.floor(total / 60)
218  const m = total % 60
219  if (h >= 48) return `${Math.floor(h / 24)}d ${h % 24}h`
220  return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
221}
222
223const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
224
225/**
226 * A clock time in the host's own zone — `7:00pm`, or `Tue 7:00pm` when the moment
227 * falls on a different day than `now` does.
228 *
229 * The status line is a value the app holds between paints, so anything in it that
230 * measures forward decays the moment it is set: `6h00m left`, read forty minutes
231 * later, is forty minutes wrong, and wrong in the direction that overstates what
232 * is left. An absolute time says the same thing at every reading. It is the one
233 * form that survives being held, which is why the row uses it and the `/cache-tax`
234 * card — a printout read as it is written — keeps its durations.
235 *
236 * Null when the host cannot format a clock, which leaves the caller its duration.
237 */
238export function fmtClock(ms: number, now: number): string | null {
239  try {
240    const at = new Date(ms)
241    const h = at.getHours()
242    const m = at.getMinutes()
243    if (!Number.isFinite(h) || !Number.isFinite(m)) return null
244    const clock = `${h % 12 === 0 ? 12 : h % 12}:${String(m).padStart(2, '0')}${h < 12 ? 'am' : 'pm'}`
245    const from = new Date(now)
246    const sameDay = at.getFullYear() === from.getFullYear()
247      && at.getMonth() === from.getMonth()
248      && at.getDate() === from.getDate()
249    return sameDay ? clock : `${DAYS[at.getDay()]} ${clock}`
250  } catch {
251    return null
252  }
253}
254
255function fmtUsd(usd: number | null): string {
256  if (usd == null) return 'n/a'
257  // Sub-cent figures are normal at these rates; two decimals would read as $0.00.
258  if (usd > 0 && usd < 0.01) return '$' + usd.toFixed(4)
259  return '$' + (usd >= 100 ? usd.toFixed(0) : usd.toFixed(2))
260}
261
262/**
263 * A signed difference. A surcharge carries a leading `+`; a saving is wrapped in
264 * parentheses — accounting's own mark for a credit, which reads as a saving
265 * without a minus sign that could be mistaken for a hyphen mid-line. Zero is
266 * `+$0.00`, a real answer rather than an unknown. `n/a` is the unknown: this mod
267 * has no rates for the model, so it computes no figure at all.
268 */
269export function fmtSignedUsd(usd: number | null): string {
270  if (usd == null) return 'n/a'
271  return usd < 0 ? `(${fmtUsd(-usd)})` : `+${fmtUsd(usd)}`
272}
273
274/**
275 * Rounding to whole thousands hid the difference the line exists to show: a 300k
276 * context served from a 299k cache and a 300k one served from 141k read the same.
277 * One decimal for the thousands and millions keeps the two figures apart, and the
278 * trailing `.0` is dropped so an exact thousand still reads as a round number.
279 */
280function fmtTok(n: number): string {
281  if (n >= 1e6) return trimZero((n / 1e6).toFixed(1)) + 'M'
282  if (n >= 1000) return trimZero((n / 1000).toFixed(1)) + 'k'
283  return String(n)
284}
285
286function trimZero(s: string): string {
287  return s.endsWith('.0') ? s.slice(0, -2) : s
288}
289
290/** ctx × the cache-write rate: what re-writing the context after expiry is billed. */
291function coldUsd(s: State): number | null {
292  const r = ratesFor(s.lastModel)
293  return r ? s.ctx * r.cacheWrite / 1e6 : null
294}
295
296/** ctx × the cache-read rate: what a turn whose context is served from cache costs. */
297function warmUsd(s: State): number | null {
298  const r = ratesFor(s.lastModel)
299  return r ? s.ctx * r.cacheRead / 1e6 : null
300}
301
302/** ctx × the uncached input rate: what the same context costs with no cache reuse at all. */
303function uncachedUsd(s: State): number | null {
304  const r = ratesFor(s.lastModel)
305  return r ? s.ctx * r.input / 1e6 : null
306}
307
308/** One hypothetical context read, not the turn's summed bill or the cache's current warmth. */
309function cacheEffectUsd(s: State): number | null {
310  const uncached = uncachedUsd(s)
311  const warm = warmUsd(s)
312  return uncached == null || warm == null ? null : warm - uncached
313}
314
315/**
316 * The share of the last turn's prompt tokens the cache served — a measurement of
317 * what happened, where the read rate against the input rate is only a price.
318 *
319 * A share that is real but not quite whole reads `99%` rather than `100%`, because
320 * rounding a hit rate up to whole would claim the cache carried a prompt it did
321 * not. It is the mirror of the `<1%` the cost share already uses, and it is why
322 * the ceiling here is 99 and not the nearest integer.
323 */
324export function hitPct(read: number, prompt: number): string {
325  if (prompt <= 0) return ''
326  const pct = (read / prompt) * 100
327  return `${pct >= 100 ? 100 : Math.min(99, Math.round(pct))}%`
328}
329
330/**
331 * The share a cached read saves against the same context sent uncached.
332 *
333 * Unlike the hit rate this is a *rate*, not a measurement, and it is worth being
334 * plain about why: both prices are `context × rate / 1e6`, so the context appears
335 * on both sides of the division and cancels. What is left is the two rates, the
336 * same figure for every context size and every turn with a given model — only the
337 * money it is worth moves with the context. Null where no rates are configured,
338 * and zero or less when a read costs as much as uncached input or more.
339 */
340export function savedPct(warm: number | null, uncached: number | null): number | null {
341  if (warm == null || uncached == null || uncached <= 0) return null
342  return Math.round((1 - warm / uncached) * 100)
343}
344
345/**
346 * A cost as a share of the uncached price, bare — the form the status line has
347 * room for. A non-zero share that rounds away is `<1%` rather than `0%`, which
348 * is the difference between a figure that is nothing and one that is merely
349 * small. Empty when either end is unknown, or when the baseline is zero and a
350 * share would be a division by it.
351 */
352export function fmtSharePct(usd: number | null, base: number | null): string {
353  if (usd == null || base == null || base <= 0) return ''
354  const pct = (usd / base) * 100
355  return pct <= 0 ? '0%' : pct < 1 ? '<1%' : `${Math.round(pct)}%`
356}
357
358/** The same share as a clause, for the card, which has room to say what of. */
359export function fmtShare(usd: number | null, base: number | null): string {
360  const pct = fmtSharePct(usd, base)
361  return pct ? ` = ${pct} of that` : ''
362}
363
364/**
365 * The status line's cost slot, in the two shares that read fastest: how much of
366 * the last turn's prompt the cache carried, and how much a carried token saves.
367 *
368 * It used to name the two prices, `$0.0047 of $0.07`, with the first as a share of
369 * the second. That share was the *cost* ratio, and it was the wrong figure to sit
370 * in a live row: both prices are `context × rate`, so the context cancels out of
371 * their ratio, and what remained was the model's two rates — always 7% for one
372 * model, always 14% for another, whatever the session was doing. A reading that
373 * cannot move is not a reading. Both replacements do move, and both read higher
374 * as cheaper, which the cost ratio did not.
375 *
376 * The prices themselves are not lost: `/cache-tax` prints all three, each against
377 * the uncached baseline, where there is room to say what a sign means.
378 */
379/** Formats generation speed in tokens per second, or empty string if not measured. */
380export function fmtSpeed(speed: number | null): string {
381  if (speed == null || speed <= 0 || !Number.isFinite(speed)) return ''
382  return `${speed >= 10 ? Math.round(speed) : speed.toFixed(1)} tok/s`
383}
384
385/** Formats the turn's cache telemetry: calls / tokens cache / hit%. */
386function turnCacheText(s: State): string {
387  const hit = hitPct(s.lastRead, s.lastPrompt)
388  return `${callCountText(s)} / ${fmtTok(s.lastRead)} cache / ${hit || '0%'}`
389}
390
391/**
392 * The status line's cost slot: total tokens saved this session (since /clear),
393 * and the rate discount for the model.
394 *
395 * Moving session tokens here from the band keeps the band focused on the turn
396 * that just completed (calls / tokens cache / hit% · speed), while the status
397 * line anchors the persistent session facts (state, timer, session tokens,
398 * and rate discount).
399 */
400export function costSlotText(sessionTokens: number, saved: number | null, effect: number | null): string {
401  // No rates for the model: nothing computable, so the unknown keeps its own form.
402  if (saved == null) return fmtSignedUsd(effect)
403  // A read that costs as much as uncached input, or more, is not a saving, and
404  // `0% saved` would have to mean both "no discount" and "a surcharge". The signed
405  // money carries that distinction instead, as it always has.
406  if (saved <= 0) return fmtSignedUsd(effect)
407  return `${fmtTok(sessionTokens)} session, ${saved}% saved`
408}
409
410function effectSlot(s: State): string {
411  return costSlotText(s.readSession, savedPct(warmUsd(s), uncachedUsd(s)), cacheEffectUsd(s))
412}
413
414/** Everything a fork bills: the cache read, any cache write, uncached input at its own rate, and the output. */
415function pingUsd(u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }, r: Rates): number {
416  return (u.cache_read_input_tokens * r.cacheRead + u.cache_creation_input_tokens * r.cacheWrite + u.input_tokens * r.input + u.output_tokens * r.output) / 1e6
417}
418
419/** The read-only upper bound: pings at the cache-read rate that cost as much as one cold write of the same context. */
420function breakEvenPings(s: State): number | null {
421  const r = ratesFor(s.lastModel)
422  if (!r || s.ctx <= 0 || r.cacheRead <= 0) return null
423  return Math.floor(r.cacheWrite / r.cacheRead)
424}
425
426function isCold(s: State, now: number): boolean {
427  return s.lastRequestAt > 0 && !s.compacted && now - s.lastRequestAt >= TTL_MS
428}
429
430// One line, because the status line is one line in a slot the app fixes the
431// width of. What fits is how long the cache has been gone and what sending
432// anyway costs; the rates behind that figure, and what a warm turn would have
433// cost instead, are in /cache-tax, which has room for them.
434function guardText(s: State, now: number): string {
435  return `cold ${fmtDuration(now - s.lastRequestAt - TTL_MS)} · re-write ≈${fmtUsd(coldUsd(s))}`
436}
437
438export type ResumeFields = {
439  source: string
440  model?: string
441  context_tokens?: number
442  seconds_since_last_response?: number
443  prompt_cache_likely_expired?: boolean
444  estimated_cache_write_usd?: number
445}
446
447/** /clear starts a new conversation in the same process; nothing priced before it still exists. */
448export function resetForClear(s: State) {
449  s.ctx = 0
450  s.rowsTokens = 0
451  s.lastRequestAt = 0
452  s.compacted = false
453  s.coldWritePending = false
454  s.misses = []
455  s.lastRead = 0
456  s.lastPrompt = 0
457  s.readSession = 0
458  s.turns = 0
459  s.calls = 0
460  s.steps = 0
461  s.turnOut = 0
462  s.turnDurationMs = 0
463  s.speedToksPerSec = null
464  s.accumStepsOut = 0
465  s.accumStepsDurationMs = 0
466  s.percent = 0
467  s.free = 0
468  s.compactAt = null
469  s.history = []
470  s.notice = null
471  disarm(s)
472}
473
474/** Applies a resumed session's fields to the state; returns the line to log, if any. */
475export function seedFromResume(s: State, e: ResumeFields, now: number): string | null {
476  if (e.source !== 'resume' && e.source !== 'fork') return null
477  if (typeof e.context_tokens === 'number' && e.context_tokens > 0) s.ctx = e.context_tokens
478  if (typeof e.seconds_since_last_response === 'number') s.lastRequestAt = now - e.seconds_since_last_response * 1000
479  if (typeof e.model === 'string') s.lastModel = e.model
480  s.compacted = false
481  if (e.prompt_cache_likely_expired !== true || s.ctx < BIG_TOKENS) return null
482  const usd = typeof e.estimated_cache_write_usd === 'number' ? fmtUsd(e.estimated_cache_write_usd) : fmtUsd(coldUsd(s))
483  // Same one-line budget as the guard. The advice that used to ride along here
484  // -- /clear and paste a summary if you only need the conclusions -- is in the
485  // /cache-tax card, which is where there is room to read it.
486  return usd === 'n/a'
487    ? 'cold resume · the next message re-writes the context'
488    : `cold resume · first message ≈${usd}`
489}
490
491/** The card's warming slot: off, a countdown, or why it stopped. */
492function warmingText(s: State, now: number): string {
493  if (s.stopped) return `stopped: ${s.stopped}`
494  if (!s.deadline) return 'off'
495  return `${fmtDuration(s.deadline - now)} left`
496}
497
498/**
499 * The same slot as the row writes it: when the armed window ends, as a clock
500 * time. Falls back to the countdown where the host cannot format one, and to
501 * nothing at all while no window is armed.
502 */
503function endsText(s: State, now: number): string | null {
504  if (!s.deadline) return null
505  const clock = fmtClock(s.deadline, now)
506  return clock ? `ends ${clock}` : `${fmtDuration(s.deadline - now)} left`
507}
508
509/**
510 * What the last ping proved about the provider's expiry clock, in the ping slot
511 * it came from: a warm ping after a gap means the clock outlasts that gap, a
512 * cold one means it does not. Either is worth saying, because either moved the
513 * interval the window will use next.
514 */
515function heldText(s: State): string {
516  if (!s.last) return ''
517  return s.last.warm ? ` (held ${fmtDuration(s.last.idle)})` : ` (went at ${fmtDuration(s.last.idle)})`
518}
519
520/**
521 * The interval to ping at next, from the bounds the pings have bracketed. The
522 * midpoint of a bracket is the fastest way to close it, and a bracket already
523 * down to the margin settles at the largest gap proven to work, less the margin.
524 *
525 * With no ceiling yet — the first ping came back warm — there is nothing to
526 * search between, so the configured interval stands: it is proven, and the user
527 * picked it as the long end.
528 */
529function retune(s: State): number {
530  const lo = s.warmAt
531  const hi = s.coldAt
532  if (hi == null) return Math.max(MIN_PING_MS, lo || s.every)
533  if (hi - lo <= TUNE_MARGIN_MS) return Math.max(MIN_PING_MS, lo - TUNE_MARGIN_MS)
534  return Math.max(MIN_PING_MS, Math.floor((lo + hi) / 2))
535}
536
537/** When the next ping can come, or null while nothing is armed. */
538function nextPingText(s: State, now: number): string | null {
539  if (!s.deadline) return null
540  if (!s.lastRequestAt) return 'ping after first turn'
541  if (isCold(s, now)) return 'ping after next turn'
542  const at = s.lastRequestAt + s.every
543  const clock = fmtClock(at, now)
544  return `${clock ? `ping at ${clock}` : `ping in ${fmtDuration(at - now)}`}${heldText(s)}`
545}
546
547// The under-composer line, in one fixed field order so the same fact always
548// appears in the same place — times first, then token counts, then money:
549//
550//   <warming> · [ping] · <context> · [cache] · [±]
551//
552// warming  off | ends <clock> | stopped: <why>
553// ping     present only while a window is armed
554// context  no context yet | ctx <tokens> — what the cache could be holding
555// cache    absent until a turn reports a cache read: how much it read this turn
556// final    absent until a context exists: what the cache does to the bill for
557//          this context, bare and signed. `-` is a saving — the read rate is
558//          below the input rate, so being warm lowers the bill by that much (the
559//          usual case); `+` is a surcharge — the read rate is above the input
560//          rate, so the cache costs more than it saves. `n/a` while this mod has
561//          no rates for the model in use, so a figure it cannot compute is never
562//          shown as zero. The sign is left to carry the meaning on its own; the
563//          wording that would explain it is what the card is for.
564//
565// The model itself is left out: the picker beside this line already names it, and
566// `/cache-tax` prints the exact ID the rates are keyed on. That model comes from
567// the last turn's own usage and never from a session lookup — at session start
568// the host may not yet have chosen one, and a footer must not be left waiting.
569function statusText(s: State, now: number): string {
570  const parts = [s.stopped ? `stopped: ${s.stopped}` : (endsText(s, now) ?? 'off')]
571  const ping = nextPingText(s, now)
572  if (ping) parts.push(ping)
573  parts.push(s.ctx > 0 ? `ctx ${fmtTok(s.ctx)}` : 'no context yet')
574  // The same reading the band carries: calls / tokens cache / hit%
575  if (s.calls > 0) parts.push(turnCacheText(s))
576  const speed = fmtSpeed(s.speedToksPerSec)
577  if (speed) parts.push(speed)
578  if (s.ctx > 0) parts.push(effectSlot(s))
579  return parts.join(' · ')
580}
581
582// Desktop clips long status strings and reveals their full text on hover.
583function hintsFor(s: State): string[] {
584  const hints: string[] = []
585  if (!s.deadline) hints.push('/keepwarm to arm the window')
586  hints.push('/cache-tax for the full card')
587  return hints
588}
589
590// $.ui.status accepts plain text, so the effect is distinguished by sign, not colour.
591// The state word drops the `keepwarm` prefix, as the other form's already does:
592// the row is one line in a fixed slot, and the command it names is on the same
593// line as a hint anyway.
594function hintText(s: State, now: number): string {
595  const parts = [s.stopped ? `stopped: ${s.stopped}` : s.deadline ? 'on' : 'off']
596  const ends = endsText(s, now)
597  if (ends) parts.push(ends)
598  const ping = nextPingText(s, now)
599  if (ping) parts.push(ping)
600  if (s.ctx > 0) parts.push(effectSlot(s))
601  return [...parts, ...hintsFor(s)].join(' · ')
602}
603
604function disarm(s: State) {
605  if (s.pending) s.pending.cancel()
606  s.pending = null
607}
608
609// --- The AbovePrompt band ----------------------------------------------------
610// Only one plugin can draw AbovePrompt: returning a tree stops the hook chain.
611
612/** Maximum readings the sparkline shows, oldest first. */
613const SPARK_BARS = 3
614/** Recent readings kept in state. */
615const HISTORY = 12
616const SPARK = '▁▂▃▄▅▆▇█'
617
618/**
619 * The forecast, by share of the window used. The colours are literal rather than
620 * theme keys on purpose: this is a ramp the person reads as a ramp, and it stays
621 * the same ramp whatever the theme does to `warning` or `error`.
622 */
623const FORECAST = [
624  { upTo: 25, icon: '☀', word: 'Clear', color: 'yellow' },
625  { upTo: 50, icon: '☁', word: 'Cloudy', color: 'cyan' },
626  { upTo: 75, icon: '☂', word: 'Showers', color: 'blue' },
627  { upTo: 90, icon: '☇', word: 'Storm', color: 'magenta' },
628  { upTo: Infinity, icon: '↯', word: 'Compact soon', color: 'red' },
629]
630
631function forecastFor(percent: number) {
632  return FORECAST.find(f => percent < f.upTo) ?? FORECAST[FORECAST.length - 1]!
633}
634
635/**
636 * One bar per reading, its height the share of the window it filled — not the
637 * share of the busiest reading shown, which is what token-weather scales by and
638 * which makes the same bar mean a different number of tokens in every window.
639 * Scaling to the window keeps a bar comparable with the percentage beside it.
640 */
641function sparkline(history: number[], window: number): string {
642  if (!window || !history.length) return ''
643  return history
644    .slice(-SPARK_BARS)
645    .map(t => {
646      const level = Math.floor((t / window) * (SPARK.length - 1))
647      return SPARK[Math.min(SPARK.length - 1, Math.max(0, level))]!
648    })
649    .join('')
650}
651
652/**
653 * How much the context moved on the last turn, or null while there is no turn to
654 * compare. The arrow carries the direction and the slot's position carries the
655 * "since the reading before it", so the words are left out: the band is a row of
656 * figures, and every other slot names its own unit rather than its tense.
657 */
658/**
659 * The model calls the last turn made, in the band's own words. This is the
660 * denominator the cache figure beside it has always lacked: `150.9k cache turn`
661 * against a 157.9k context looks like a miscount until the ~42 calls that read
662 * that context are on the row with it.
663 */
664function callCountText(s: State): string {
665  return `${s.calls} call${s.calls === 1 ? '' : 's'}`
666}
667
668function trendText(history: number[]): { text: string; delta: number } | null {
669  if (history.length < 2) return null
670  const delta = history[history.length - 1]! - history[history.length - 2]!
671  const text = delta === 0 ? 'steady' : `${delta > 0 ? '▲ +' : '▼ '}${fmtTok(Math.abs(delta))}`
672  return { text, delta }
673}
674
675/**
676 * The window the fill is measured against, and the fill itself. `rawMaxTokens` is
677 * what /autocompact actually fires against — the model's limit, or the smaller
678 * compaction window when a setting names one — so it is the honest denominator;
679 * `context.window` is only the model's and would understate the fill whenever
680 * autocompact has set something smaller, which is the case that matters.
681 *
682 * `breakdown: 'summary'` estimates locally and sends no request. `full` would
683 * send one count request per tool and per memory file, which the standing
684 * local-only constraint rules out.
685 */
686async function refreshWindow($: EngineInterface, s: State) {
687  try {
688    const usage = await $.session.usage({ breakdown: 'summary' })
689    const context = usage.context
690    const breakdown = context.breakdown
691    if (breakdown && breakdown.rawMaxTokens > 0) {
692      s.window = breakdown.rawMaxTokens
693      s.windowSource = breakdown.autocompactSource
694      const free = breakdown.categories.find(c => c.kind === 'free' || c.name === 'Free space')
695      s.free = free && free.tokens > 0 ? free.tokens : 0
696      s.compactAt = typeof breakdown.autoCompactThreshold === 'number' ? breakdown.autoCompactThreshold : null
697
698      // What the rows add up to, kept only for the card: the row total is an
699      // estimate, so it is never the fill this band draws.
700      const rows = breakdown.categories.filter(c =>
701        c.kind !== 'free' && c.kind !== 'buffer' && c.kind !== 'deferred' &&
702        !c.isDeferred && c.name !== 'Free space' && c.name !== 'Autocompact buffer')
703      s.rowsTokens = rows.length > 0 ? rows.reduce((sum, c) => sum + (c.tokens > 0 ? c.tokens : 0), 0) : 0
704      // The fill is the engine's own figure wherever it reports one. `context.tokens`
705      // is the last response's whole input — uncached, cache-read and cache-written
706      // together — so it is the prompt the model actually answered over, and it is
707      // the same number the engine's own context popover shows. The breakdown's rows
708      // are estimates meant to explain that figure, not to replace it: summing them
709      // drifts from it whenever a row is deferred, unlisted or unaccounted, which is
710      // exactly what put this band at odds with the popover.
711      const live = typeof context.tokens === 'number' && context.tokens > 0 ? context.tokens : null
712      if (live != null) {
713        s.ctx = live
714        // Both figures are read against the window this band reports, so the fill and
715        // the distance to autocompact below share one denominator.
716        s.percent = Math.round((live / s.window) * 100)
717      } else if (typeof breakdown.totalTokens === 'number' && breakdown.totalTokens > 0) {
718        s.ctx = breakdown.totalTokens
719        s.percent = Math.round(breakdown.percentage)
720      } else if (breakdown.percentage > 0) {
721        s.ctx = Math.round(s.window * (breakdown.percentage / 100))
722        s.percent = Math.round(breakdown.percentage)
723      }
724      return
725    }
726    if (context.window > 0) {
727      s.window = context.window
728      if (typeof context.tokens === 'number' && context.tokens > 0) {
729        s.ctx = context.tokens
730      }
731      s.percent = Math.round(context.percent ?? (s.ctx / context.window) * 100)
732      s.windowSource = null
733    }
734    // No breakdown means no free row and no threshold; a stale pair is worse than
735    // an absent one, so both are cleared rather than kept.
736    s.free = 0
737    s.compactAt = null
738  } catch {
739    // No session bound, or a host that answers no breakdown: keep the last reading.
740  }
741}
742
743/**
744 * Width is the band's own box, not the viewport; a docked pane reduces it.
745 * Only the sparkline and trend are dropped for width, never the token counts.
746 *
747 * The order is the window first and the history second: the forecast and the fill
748 * it measures, then the room still free and the distance to the point
749 * /autocompact fires, then the readings that say how the fill got here (the
750 * sparkline and the trend) and what the cache served along the way. The two
751 * window figures sit together because they answer one question between them —
752 * how much room is left — and the two history slots follow because they are
753 * derived from the readings rather than being measurements of this moment.
754 */
755function band(
756  Box: ElementConstructor<BoxProps>,
757  Text: ElementConstructor<TextProps>,
758  props: { bodyColumns: number },
759  s: State,
760) {
761  const columns = props.bodyColumns || 80
762  const f = forecastFor(s.percent)
763  // The table's constructors take children among the props and hand back an
764  // element with them beside `props`, which is the shape the engine draws.
765  const t = (textProps: TextProps, text: string) => Text({ ...textProps, children: text })
766  const dim = (text: string) => t({ dimColor: true }, text)
767  const parts: RenderElement[] = [
768    t({ color: f.color, bold: true }, `${f.icon}  ${f.word}`),
769    t({ color: f.color }, `  ${fmtTok(s.ctx)} / ${fmtTok(s.window)} (${s.percent}%)`),
770  ]
771  // The sparkline sits with the fill it continues: the same figure drawn, in the
772  // same colour, so the row leads with its two coloured slots before the dim ones.
773  const spark = columns >= 56 ? sparkline(s.history, s.window) : ''
774  if (spark) parts.push(dim('  ·  '), t({ color: f.color }, spark))
775  const trend = columns >= 72 ? trendText(s.history) : null
776  if (trend) {
777    const el = trend.delta > 0
778      ? t({ color: f.color === 'red' ? 'red' : 'yellow' }, trend.text)
779      : trend.delta < 0
780        ? t({ color: 'green' }, trend.text)
781        : dim(trend.text)
782    parts.push(dim('  ·  '), el)
783  }
784  // The distance to the point /autocompact actually fires. This is the window
785  // figure worth acting on: the free space the breakdown also reports measures
786  // nearly the same thing and reads as a near-duplicate beside it, so only this
787  // one is drawn. Absent until a context exists — with nothing in use the figure
788  // would only restate the threshold.
789  //
790  // It follows the history rather than the fill because it is the one slot whose
791  // meaning changes as it shrinks: roomy is a fact, nearly gone is a call to act.
792  // So it is dim while there is room and takes the forecast's own alarm colour
793  // once the window reaches the red step — the same moment the forecast turns,
794  // rather than a token count of its own, which would only suit one window size.
795  if (s.compactAt != null && s.ctx > 0) {
796    const toGo = s.compactAt - s.ctx
797    // The share is of the window, like the fill's, so both read against one
798    // denominator even though only the fill is a complement of it.
799    const share = s.window > 0 ? ` (${((toGo / s.window) * 100).toFixed(1)}%)` : ''
800    const text = toGo > 0 ? `${fmtTok(toGo)} to go${share}` : 'compact due'
801    parts.push(f.color === 'red' ? t({ color: 'red' }, `  ·  ${text}`) : dim(`  ·  ${text}`))
802  }
803  // The turn's cache telemetry: calls made / tokens served / percentage cached.
804  if (s.calls > 0) parts.push(dim(`  ·  ${turnCacheText(s)}`))
805  const speed = fmtSpeed(s.speedToksPerSec)
806  if (speed) parts.push(dim(`  ·  ${speed}`))
807  return Box({ flexDirection: 'row', paddingX: 1, children: parts })
808}
809
810// Status text is shared across connected surfaces. Use the fallback only when
811// none supports the band; a notice temporarily replaces either status form.
812//
813// Which surface this is cannot be read from the one captured at session start: a
814// desktop client can attach a moment after that event, when `e.surface` was still
815// null and the captured value became `''`, and the band it raises is up now. So
816// the decision is made from the live roster each time the line is painted.
817const BAND_SURFACES = new Set(['desktop', 'terminal'])
818
819/**
820 * The surfaces the session draws on right now, so the band's reach is read fresh
821 * rather than from the one frozen at session start: a client can attach after
822 * that, when `e.surface` was still null. Null means the ask failed; the engine's
823 * `surfaces()` is documented never to reject, but a host that answers nothing is
824 * told apart from an empty roster so a caller can fall back rather than mistake
825 * silence for "nothing draws".
826 */
827async function liveSurfaces($: EngineInterface): Promise<readonly RenderSurface[] | null> {
828  try {
829    return await $.session.surfaces()
830  } catch {
831    return null
832  }
833}
834
835// The one place that writes the status line, so a notice and the readout never
836// race each other for it. Painted only while this mod owns the session's command
837// names — the slot holds one entry per plugin. A live notice outranks everything
838// and shows on every surface, the band's included: it is a one-off thing to read
839// now, not the facts the band keeps current, so it is worth saying even where the
840// band is up.
841async function publish($: EngineInterface, s: State) {
842  s.now = await $.clock.now()
843  if (!s.owns) return
844  // A notice outranks the readout on the line, and every path below still has to
845  // reach the invalidate at the end: the band is a tree the engine caches, and a
846  // paint that returned early here would leave the band showing the turn before
847  // while the line announced the notice.
848  let text: string
849  if (s.notice) {
850    text = s.notice
851  } else {
852    // A client can attach after session.start, so ask the live roster on every paint.
853    const live = await liveSurfaces($)
854    const raised = live ? live.some(surface => BAND_SURFACES.has(surface)) : BAND_SURFACES.has(s.surface)
855    text = raised ? hintText(s, s.now) : statusText(s, s.now)
856  }
857  $.ui.status(text)
858  try {
859    $.ui.invalidate('ui.render')
860  } catch {}
861}
862
863// The window and its ping period belong to the session that armed them, so a
864// second session, or one resumed from another transcript, never inherits them
865// and cannot turn them off. The guard mode stays global.
866function deadlineKey(s: State): string {
867  return `${KEY_DEADLINE}:${s.sid}`
868}
869
870function everyKey(s: State): string {
871  return `${KEY_EVERY}:${s.sid}`
872}
873
874/** Clears this session's own dead window. Other sessions' keys are never touched. */
875async function prune($: EngineInterface, s: State, now: number) {
876  for (const key of [deadlineKey(s)]) {
877    const deadline = await $.store.get(key)
878    if (deadline === undefined) continue
879    if (typeof deadline === 'number' && deadline > now) continue
880    await $.store.delete(key)
881    await $.store.delete(everyKey(s))
882  }
883}
884
885async function stop($: EngineInterface, s: State, why: string | null) {
886  s.deadline = 0
887  s.every = PING_AFTER_MS
888  s.stopped = why
889  disarm(s)
890  await $.store.delete(deadlineKey(s))
891  await $.store.delete(everyKey(s))
892  await publish($, s)
893}
894
895async function arm($: EngineInterface, s: State) {
896  disarm(s)
897  if (!s.deadline) return
898  const now = await $.clock.now()
899  if (now >= s.deadline) return stop($, s, null)
900  // A cold window still needs expiry cleanup, but must not send a model request.
901  if (s.lastRequestAt && !s.compacted && !isCold(s, now)) {
902    const delay = Math.min(s.deadline - now, Math.max(1000, s.lastRequestAt + s.every - now))
903    s.pending = $.clock.after(delay, () => { void ping($, s) })
904  } else {
905    s.pending = $.clock.after(s.deadline - now, () => { void arm($, s) })
906  }
907  await publish($, s)
908}
909
910async function ping($: EngineInterface, s: State) {
911  s.pending = null
912  if (!s.deadline) return
913  const now = await $.clock.now()
914  if (now >= s.deadline) return arm($, s)
915  // A turn in the meantime re-armed the timer; this callback is stale.
916  if (now - s.lastRequestAt < s.every - 1000) return
917  if (isCold(s, now)) return arm($, s)
918  let reply
919  try {
920    reply = await $.model.fork({ prompt: PING_PROMPT })
921  } catch (err) {
922    return stop($, s, `ping failed: ${err instanceof Error ? err.message : String(err)}`)
923  }
924  // This build's fork never answers null: the union is an answer, or a reason.
925  if (!reply) return stop($, s, 'ping not sent')
926  if (!reply.isAnswered) return stop($, s, `ping not sent (${reply.reason})`)
927  const u = reply.usage
928  const r = ratesFor(s.lastModel)
929  // A warm ping reads the prefix and writes only its own message; a write of a tenth of the read or more means the prefix broke.
930  const warm = u.cache_read_input_tokens > 0 && u.cache_creation_input_tokens < 0.1 * u.cache_read_input_tokens
931  const usd = r ? pingUsd(u, r) : null
932  // How long the cache had been left alone before this ping. The outcome turns
933  // that gap into a fact about the provider's expiry clock, which the engine does
934  // not expose: a warm ping proves the clock outlasts the gap, a cold one proves
935  // it does not. Either way the bound comes from a request the window was going
936  // to send anyway, so learning it costs nothing extra.
937  const idle = now - s.lastRequestAt
938  s.last = { at: now, idle, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens, usd, warm }
939  if (warm) {
940    s.warmAt = Math.max(s.warmAt, idle)
941  } else if (u.cache_creation_input_tokens <= 0) {
942    // Not a cold cache — no cache. The reply neither read an entry nor wrote one,
943    // so this provider is not caching the prefix at all: there is no expiry to
944    // search for, and leaving the window armed would ping on a clock that no
945    // longer advances, once a second, for the rest of it.
946    return stop($, s, `ping read 0, wrote 0 (${fmtUsd(usd)}): the provider cached nothing, so there is no expiry to tune around`)
947  } else {
948    s.coldAt = s.coldAt == null ? idle : Math.min(s.coldAt, idle)
949    // A cache that goes cold inside the shortest interval the window allows is
950    // not a short TTL to search around; the search has run out of room.
951    if (s.coldAt <= MIN_PING_MS) {
952      return stop($, s, `ping read ${fmtTok(u.cache_read_input_tokens)}, wrote ${fmtTok(u.cache_creation_input_tokens)} (${fmtUsd(usd)}): the cache was gone after ${fmtDuration(idle)} idle, and ${fmtDuration(MIN_PING_MS)} is the shortest interval, so there is nothing here to keep warm`)
953    }
954  }
955  s.every = retune(s)
956  await $.store.set(everyKey(s), s.every)
957  // The fork re-sent the prefix, so a cold ping leaves the cache written afresh.
958  s.lastRequestAt = now
959  await arm($, s)
960}
961
962/** The reply to an arming command; on a cold cache it says when the first ping can come. */
963function armedText(s: State, now: number, windowMs: number): string {
964  if (isCold(s, now)) return `keepwarm on for ${fmtDuration(windowMs)}. The cache is cold now, so the first ping comes ${fmtDuration(s.every)} after the next turn`
965  return `keepwarm on for ${fmtDuration(windowMs)}, a ping ${fmtDuration(s.every)} after each idle stretch keeps the cache read, not re-written`
966}
967
968async function startWindow($: EngineInterface, s: State, windowMs: number, every: number) {
969  const now = await $.clock.now()
970  if (every !== PING_AFTER_MS) {
971    // An interval the user names replaces whatever the pings had bracketed: the
972    // command is the newer word on how often to ping.
973    s.warmAt = 0
974    s.coldAt = null
975    s.every = every
976  } else {
977    // The default defers to the bracket, so a window re-armed in the same session
978    // resumes at the interval the last one learned instead of starting the search
979    // over. The learned interval is written below, so it outlives the session too.
980    s.every = retune(s)
981  }
982  if (s.every === PING_AFTER_MS) await $.store.delete(everyKey(s))
983  else await $.store.set(everyKey(s), s.every)
984  s.deadline = now + windowMs
985  s.stopped = null
986  await $.store.set(deadlineKey(s), s.deadline)
987  await arm($, s)
988}
989
990/**
991 * Where the window the band measures against came from, said plainly. `settings`
992 * and `env` are a person's own `/autocompact` value; `model-default` is the
993 * model's own limit; `unknown-model` means the engine could not settle one and
994 * the percentage should be read as a guess, which is worth knowing when a
995 * gateway serves a model ID the engine does not recognise.
996 */
997function windowNote(s: State): string {
998  switch (s.windowSource) {
999    case 'settings': return ', set by /autocompact'
1000    case 'env': return ', set by the environment'
1001    case 'clientdata': return ', set by the client'
1002    case 'experiment': return ', set by an experiment'
1003    case 'model-default': return ", the model's own window"
1004    case 'auto': return ', settled automatically'
1005    case 'unknown-model': return ', the model is unknown to the engine, so this is a guess'
1006    default: return ', no compaction window reported, so the model window is used'
1007  }
1008}
1009
1010function card(s: State, now: number, surfaces: readonly RenderSurface[] | null): string {
1011  const lines: string[] = []
1012  const r = ratesFor(s.lastModel)
1013  lines.push(`${s.lastModel ?? 'model not seen yet'}`)
1014  if (s.compacted) lines.push('state       reset by compaction, waiting for the first turn')
1015  else if (!s.lastRequestAt) lines.push('state       no request yet this session')
1016  else if (isCold(s, now)) lines.push(`state       COLD, last request ${fmtDuration(now - s.lastRequestAt)} ago`)
1017  else lines.push(`state       warm, ${fmtDuration(s.lastRequestAt + TTL_MS - now)} left`)
1018  lines.push(`context     ${s.ctx.toLocaleString('en-US')} tokens, the most the cache can be holding`)
1019  lines.push(`window      ${s.window ? `${fmtTok(s.window)} (${s.percent}% used)` : 'not reported yet'}${windowNote(s)}`)
1020  // The two readings side by side, because the band draws the first and the engine's
1021  // context popover draws something the second resembles: the row total is the
1022  // breakdown's own estimate of what fills the window, and the band uses the engine's
1023  // reported figure instead. Printing both is what tells a wrong-looking fill from a
1024  // band that is right and a row estimate that is not.
1025  if (s.rowsTokens > 0 && s.window > 0) {
1026    lines.push(`rows        ${s.rowsTokens.toLocaleString('en-US')} tokens by the breakdown's own rows ` +
1027      `(${((s.rowsTokens / s.window) * 100).toFixed(1)}%) — an estimate, not the fill the band draws`)
1028  }
1029  // The band leaves this one out because it tracks `compact` too closely; the card
1030  // is where the complete set of figures belongs.
1031  if (s.free > 0 && s.window > 0) {
1032    lines.push(`free        ${s.free.toLocaleString('en-US')} tokens left in the window (${((s.free / s.window) * 100).toFixed(1)}%)`)
1033  }
1034  if (s.compactAt != null && s.window > 0) {
1035    // The engine's own threshold, so the fill can be read against the point where
1036    // /autocompact actually fires rather than against the window.
1037    const left = s.compactAt - s.ctx
1038    lines.push(`compact     auto-compaction at ${s.compactAt.toLocaleString('en-US')} tokens ` +
1039      `(${Math.round((s.compactAt / s.window) * 100)}% of the window), ${left > 0 ? `${fmtTok(left)} to go` : 'already past it'}`)
1040  }
1041  // Both surfaces, so the next session can see what the start value actually was
1042  // against what the session draws on now — the pair that decides the status line.
1043  const live = surfaces == null ? 'unavailable' : surfaces.length ? surfaces.join(', ') : '(none)'
1044  lines.push(`surfaces    captured ${s.surface || '(none)'} · live ${live}`)
1045  // What the cache read this turn, not a size it holds: a turn's usage is its
1046  // model calls summed, so a long agentic turn reads the context once per call
1047  // and the total can run to many times the context it was reading.
1048  const overCalls = s.calls > 0 ? ` over ${callCountText(s)}` : ''
1049  if (s.lastRead > 0) {
1050    const total = `${s.lastRead.toLocaleString('en-US')} tokens served from cache this turn${overCalls}`
1051    // The share of the turn's own prompt, which the status line carries bare: here
1052    // there is room to say what it is a share of.
1053    const hit = hitPct(s.lastRead, s.lastPrompt)
1054    const ofPrompt = hit ? ` — ${hit} of the turn's prompt` : ''
1055    // The multiple is worth naming only when the call count explains it: a read
1056    // many times the context takes many calls, and printing it beside a count of
1057    // one would be two figures on one line contradicting each other.
1058    const multiple = s.ctx > 0 && s.calls > 1 ? Math.round(s.lastRead / s.ctx) : 0
1059    lines.push(multiple >= 2
1060      ? `cache       ${total}${ofPrompt}, ≈${multiple} × the ${fmtTok(s.ctx)} context — one read per model call`
1061      : `cache       ${total}${ofPrompt}`)
1062  } else if (s.lastRequestAt) {
1063    lines.push(`cache       none served from cache${overCalls} — the last turn reported nothing`)
1064  }
1065  if (s.speedToksPerSec != null && s.speedToksPerSec > 0) {
1066    lines.push(`speed       ${fmtSpeed(s.speedToksPerSec)} generation throughput (${s.turnOut.toLocaleString('en-US')} tokens across ${s.turnDurationMs}ms)`)
1067  }
1068  // The running total and what it was summed over, so the figure on the band is
1069  // one command away from being checkable rather than taken on trust.
1070  if (s.turns > 0) {
1071    lines.push(`usage       ${s.readSession.toLocaleString('en-US')} tokens served from cache over ${s.turns} turn${s.turns === 1 ? '' : 's'} since /clear`)
1072  }
1073  if (r) {
1074    // The three figures for one read of the context in hand, each as a share of
1075    // the uncached price. Providers publish rates per million tokens, but a
1076    // person reads a bill for the context they actually have, so the comparison
1077    // is shown as costs and the rates stay in /cache-tax-diagnostic, which is
1078    // the command whose subject they are.
1079    const uncached = uncachedUsd(s)
1080    const warm = warmUsd(s)
1081    const cold = coldUsd(s)
1082    const head = `for ${fmtTok(s.ctx)} tokens`
1083    const pad = ' '.repeat(13 + head.length + 3)
1084    lines.push(`cost        ${head}   no cache ${fmtUsd(uncached)} = 100%`)
1085    lines.push(`${pad}from cache ${fmtUsd(warm)}${fmtShare(warm, uncached)}`)
1086    lines.push(`${pad}re-write ${fmtUsd(cold)}${fmtShare(cold, uncached)}`)
1087    const effect = cacheEffectUsd(s)
1088    lines.push(`cache effect  ${fmtSignedUsd(effect)} for this context at ${RATE_SOURCE}: "from cache" minus "no cache". A saving is parenthesised — the read rate is below the input rate, so being warm lowers the bill by that much. A surcharge takes a leading + — the read rate is above the input rate, so the cache costs more than it saves`)
1089  } else {
1090    lines.push(`cost        none configured for this model, so no cost can be shown (n/a)`)
1091  }
1092  // The line the shortened notices gave up. Said here, where there is room, and
1093  // only when it applies.
1094  if (isCold(s, now)) lines.push('cold note   the next message re-writes the context at the write rate. /keepwarm holds it; /clear and paste a summary if you only need the conclusions.')
1095  const armed = s.deadline ? `on, ${warmingText(s, now)}` : 'off (/keepwarm to arm it for 6h00m)'
1096  lines.push(`keepwarm    ${s.stopped ? `stopped, ${s.stopped}` : armed}`)
1097  if (s.last) {
1098    // The outcome is a fact about the provider's expiry clock, which nothing in
1099    // the engine reports: a warm ping proves the clock outlasts the idle gap it
1100    // followed, a cold one proves it does not.
1101    const bound = s.last.warm
1102      ? `warm after ${fmtDuration(s.last.idle)} idle, so the provider's TTL is at least that`
1103      : `the cache was gone after ${fmtDuration(s.last.idle)} idle, so the provider's TTL is under that`
1104    lines.push(`last ping   read ${fmtTok(s.last.read)} from cache, wrote ${fmtTok(s.last.write)}, ${fmtUsd(s.last.usd)} (${bound})`)
1105  }
1106  const pings = breakEvenPings(s)
1107  if (pings != null && pings > 0) lines.push(`break-even  up to ${pings} pings at the read rate cost one cold write, about ${fmtDuration(pings * s.every)} of idle at one ping per ${fmtDuration(s.every)}`)
1108  else if (r && r.cacheWrite <= 0) lines.push('break-even  warming cannot pay for itself at these rates: a cold re-write is billed at nothing, so every ping is a net cost')
1109  else if (r) lines.push('break-even  not applicable: a zero cache-read rate, or no context yet')
1110  lines.push(`guard       warn only, always. This mod never drops a prompt.`)
1111  const paid = s.misses.reduce((a, m) => a + (m.usd ?? 0), 0)
1112  lines.push(`session     ${s.misses.length} cold write${s.misses.length === 1 ? '' : 's'} paid, ${fmtUsd(paid)}`)
1113  return lines.join('\n')
1114}
1115
1116export function freshState(): State {
1117  return {
1118    sid: '', deadline: 0, every: PING_AFTER_MS, warmAt: 0, coldAt: null, lastRequestAt: 0, lastModel: null, ctx: 0, rowsTokens: 0, compacted: false,
1119    guard: 'warn', coldWritePending: false, misses: [], pending: null, last: null, stopped: null, lastRead: 0, lastPrompt: 0,
1120    readSession: 0, turns: 0, calls: 0, steps: 0,
1121    turnOut: 0, turnDurationMs: 0, speedToksPerSec: null, accumStepsOut: 0, accumStepsDurationMs: 0,
1122    owns: false,
1123    window: 0, percent: 0, windowSource: null, free: 0, compactAt: null,
1124    history: [], now: 0, surface: '', notice: null,
1125  }
1126}
1127
1128// --- Host pricing provenance -------------------------------------------------
1129// Desktop does not expose its managed four rates to a plugin. This section
1130// reports what the settings interface actually shows, so the absence of
1131// accepted pricing is visible rather than guessed at. It never becomes the
1132// source of a cost: costs come from the user-supplied RATES table above.
1133
1134type Pricing = { rates: Rates; multiplier: number }
1135type Snapshot = { available: boolean; present: boolean; exact: boolean; pricing?: Pricing }
1136type Diagnostic = {
1137  model: string
1138  state: 'accepted pricing available' | 'candidate/unconfirmed' | 'pricing unavailable'
1139  reason: string
1140  pricing?: Pricing
1141  sources: string[]
1142}
1143
1144function record(value: unknown): Record<string, unknown> | undefined {
1145  return value !== null && typeof value === 'object' && !Array.isArray(value)
1146    ? value as Record<string, unknown>
1147    : undefined
1148}
1149
1150function validRate(value: unknown): value is number {
1151  return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 10000
1152}
1153
1154function validMultiplier(value: unknown): value is number {
1155  return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 10
1156}
1157
1158// Select pricing fields immediately. Never retain, print, or persist settings.
1159async function snapshot($: EngineInterface, model: string, args?: SettingsReadArgs): Promise<Snapshot> {
1160  try {
1161    const { modelPricing } = await $.settings.read(args)
1162    const config = record(modelPricing)
1163    const overrides = record(config?.overrides)
1164    const exact = overrides !== undefined && Object.prototype.hasOwnProperty.call(overrides, model)
1165    const row = exact ? record(overrides?.[model]) : undefined
1166    const multiplier = config?.multiplier === undefined ? 1 : config.multiplier
1167    let pricing: Pricing | undefined
1168    if (row && rateKeys.every(key => validRate(row[key])) && validMultiplier(multiplier)) {
1169      pricing = {
1170        rates: { input: row.input as number, output: row.output as number,
1171          cacheRead: row.cacheRead as number, cacheWrite: row.cacheWrite as number },
1172        multiplier,
1173      }
1174    }
1175    return { available: true, present: modelPricing !== undefined, exact, pricing }
1176  } catch {
1177    // A host exception can contain settings or credentials; do not echo it.
1178    return { available: false, present: false, exact: false }
1179  }
1180}
1181
1182function samePricing(a: Pricing | undefined, b: Pricing): boolean {
1183  return a !== undefined && a.multiplier === b.multiplier &&
1184    rateKeys.every(key => a.rates[key] === b.rates[key])
1185}
1186
1187async function diagnose($: EngineInterface): Promise<Diagnostic> {
1188  let model: string
1189  try {
1190    model = await $.session.model()
1191    if (!model) throw new Error('no model')
1192  } catch {
1193    return { model: '(unavailable)', state: 'pricing unavailable',
1194      reason: 'Active model is not exposed by the host.', sources: [] }
1195  }
1196
1197  const policy = await snapshot($, model, { source: 'policy' })
1198  const ordinary: Array<{ source: SettingsSource; snapshot: Snapshot }> = []
1199  for (const source of ['user', 'project', 'local', 'flag'] as const) {
1200    ordinary.push({ source, snapshot: await snapshot($, model, { source }) })