SLOPSHOPPER

token-optimizer

The Token Optimizer status bar on its own, for its tests. It ships inside the token-optimizer plugin.

bandguardtoastpromptmodelprocess
★ 2,714v?PolyForm-Noncommercial-1.0.0updated 2026-10-21alexgreensh/token-optimizer/desktop/token-optimizer-desktop
A shopper browsing a rack in a slop shop
README

Token Optimizer Desktop

A status bar for the Claude desktop app. It draws above your prompt and shows session quality, context fill, cache countdown, and your 5-hour and weekly limits, with Clawd acting out what the session is doing.

Install

It ships inside the Token Optimizer plugin (hooks/hooks.json names this folder's hooks/register.tsx under modules), so there is nothing extra to install. This folder keeps its own manifest only so its tests run on their own with claude plugin test. npm run typecheck and npm test cover the pure modules (CI); npm run typecheck:engine checks hooks/ and tests/engine/ against Claude Code's plugin API declarations, which only the claude CLI writes, so it runs locally.

Needs Claude Code 2.1.287 or newer and Anthropic's mods feature. Anthropic can switch mods off remotely; when off, nothing breaks and the bar just does not appear. The terminal keeps its existing status line. VS Code is not supported.

What you get

  • One sentence about the most urgent thing, with at most one button.
  • Five marks with hover cards: quality grade, context fill, cache countdown, 5-hour limit, weekly limit.
  • The arrow beside Clawd unfolds one more line: branch, session time, tool calls, compactions (when any), when the last checkpoint was saved (any kind, or a relevant one from an earlier session), and the tokens Token Optimizer saved you in the last 30 days, the same total the dashboard shows.
  • Buttons: Clean up (compacts with Token Optimizer's guidance), Start fresh (second click saves a checkpoint, clears, and hands it to your first message), Keep warm (manual one-click cache refresh, only while the cache is warm, never automatic, uses a small amount of usage).
  • Full dashboard: a plain text link at the end of the unfolded line, in both band sizes (the folded band does not show it). Clicking it runs measure.py dashboard, the same command as the token-dashboard skill: it regenerates the dashboard page and opens it in your default browser (open on macOS, xdg-open on Linux, the file association on Windows). While it runs the band says "Opening the dashboard."; if it fails the band says "Could not open the dashboard." for a few seconds and nothing else happens. A second click while it runs is ignored. The link is a Button drawn with the plain style (its prop is on the engine's Button allowlist in Claude Code 2.1.287, 2.1.294 and 2.1.296, read from each build's strings; run on 2.1.294 to 2.1.296). The click runs measure.py dashboard --user: --user marks it as a person's click so the 20-second hook budget does not cut off a heavy rebuild (about 80 seconds cold on a real, heavy history), and the band waits up to 5 minutes. Only this link waits that long: Clean up and Start fresh still give up after 2 minutes.

The cache countdown is an estimate: 1 hour on Claude plans, 5 minutes on the API, measured from the session itself when possible.

Settings

TOKEN_OPTIMIZER_STATUS_BAR=0 hides the bar and TOKEN_OPTIMIZER_STATUS_BAR_ANIMATE=0 keeps Clawd still, set in the env block of ~/.claude/settings.json.

The – button beside the arrow shrinks the band to one line and + brings it back; the arrow still unfolds the details row under it, and the choice is remembered across sessions and restarts. TOKEN_OPTIMIZER_STATUS_BAR_SIZE=slim sets the starting size before a choice is stored, and the terminal status line uses the same variable to print one line.

The context mark measures against your own compact window when you set one: CLAUDE_CODE_AUTO_COMPACT_WINDOW, /autocompact, or the autoCompactWindow setting, within Claude Code's 100K-1M bounds and never above the model's window. A window given only with --autocompact for one launch is not visible to it.

Full docs

See the Token Optimizer README and the docs site page "Claude desktop app".

Source 14 files
hooks/register.tsx 1686 lines
1// The Token Optimizer band above the prompt in the desktop app.
2//
3// This is the plugin's one hooks module and the only file that touches `$`.
4// Every decision lives in ../src (pure, Node-tested) and ./data.ts (the data
5// gatherer over a port). The engine allows `$` only into functions declared
6// at the top of this file, so each `$` helper below is one, and closures made
7// inside hooks only ever hand `$` on to them.
8//
9// State the drawing reads lives in `$.state` atoms (types/index.d.ts) so a hot
10// reload keeps it; the pose reducer also runs from a module copy so streaming
11// chunks do not write on every piece.
12import { atom, read, update } from 'claude-code'
13import type { Elements, EngineInterface, Register } from 'claude-code'
14
15import type { TokenOptimizerDesktopSession } from '../types/index.d.ts'
16import {
17  BUSY_TIMEOUT_MS,
18  CAPTURE_TIMEOUT_MS,
19  DASHBOARD_ARGS,
20  DASHBOARD_FAILED,
21  DASHBOARD_TIMEOUT_MS,
22  HANDOFF_KEY,
23  HANDOFF_TTL_MS,
24  RESUME_TIMEOUT_MS,
25  WARM_PROMPT,
26  attachesHandoff,
27  busyNow,
28  busyTimeoutMs,
29  canOpenDashboard,
30  cleanUpOutcome,
31  dashboardFailed,
32  dashboardStatus,
33  handoffFate,
34  initialUi,
35  isArmed,
36  lifetimeFromUsage,
37  liveTokens,
38  noteNow,
39  prepareHandoff,
40  requestContextTokens,
41  stripCrossSessionPointer,
42  warmToast,
43  withBusy,
44  withNote,
45  type Busy,
46  type Handoff,
47  type HandoffPort,
48  type UiState,
49} from '../src/actions.ts'
50import { canKeepWarm, initialClock, reduceClock, view, type ClockEvent, type ClockState } from '../src/clock.ts'
51import { LIGHT, clawdSvg, type Gaze, type Palette } from '../src/clawd.ts'
52import type { Snapshot } from '../src/contracts.ts'
53import { ICONS, ICON_ALT, iconSvg, type IconName } from '../src/icons.ts'
54import { COMPACT_HEAVY, QUALITY_FLOOR, moodOf, sentence, type ActionId, type Run } from '../src/ladder.ts'
55import { cards, marks, row, type Card, type Mark, type MarkTone } from '../src/marks.ts'
56import { envSize, slimSide, storedSize, type BandSize } from '../src/size.ts'
57import { DEBOUNCE_MS, initialPose, reducePose, type PoseEvent, type PoseState } from '../src/pose.ts'
58import {
59  QUALITY_REFRESH_MS,
60  STATUS_AFTER_TURN_MS,
61  TICK_IDLE_MS,
62  TICK_WARNING_MS,
63  cleanId,
64  findTokenOptimizerRoot,
65  gather,
66  mergeStored,
67  readHome,
68  runMeasure,
69  type DataIo,
70  type GatherOptions,
71} from './data.ts'
72
73const sessionAtom = atom({ plugin: 'token-optimizer', key: 'session' } as const, null)
74const handoffAtom = atom({ plugin: 'token-optimizer', key: 'handoff' } as const, null)
75const clockAtom = atom({ plugin: 'token-optimizer', key: 'clock' } as const, null)
76const poseAtom = atom({ plugin: 'token-optimizer', key: 'pose' } as const, null)
77const engineCallAtom = atom({ plugin: 'token-optimizer', key: 'engineCall' } as const, null)
78const uiAtom = atom({ plugin: 'token-optimizer', key: 'ui' } as const, null)
79const frameAtom = atom({ plugin: 'token-optimizer', key: 'frame' } as const, 0)
80
81type Desktop = Elements['desktop']
82type Tones = { good: string; caution: string; bad: string; cold: string; ink: string; track: string; card: string; line: string }
83
84/** The design page's tone colours (light; each picture follows dark mode itself, see DARK_STYLE). */
85function tonesFor(p: Palette): Tones {
86  return { good: '#2f9e55', caution: '#c98a1b', bad: p.bad, cold: p.cold, ink: p.ink, track: '#d9d6cd', card: p.card, line: '#e2dfd6' }
87}
88
89// ---- module state: plain variables, rebuilt from the atoms after a reload ----
90
91let enabled = true
92let animate = true
93let active = false
94/** Whether the TOKEN_OPTIMIZER_STATUS_BAR switches have been read in this environment. */
95let switchesRead = false
96let timers: { cancel: () => void }[] = []
97let statusTimer: { cancel: () => void } | null = null
98let poseLive: PoseState | null = null
99let poseSig = ''
100let settleQueued = false
101/** The cache coldness last told to Clawd; null until the first tick tells him, so a cold pose kept across a reload never sticks. */
102let lastCold: boolean | null = null
103let frameText = ''
104/** The transcript Claude Code named for one session: never handed to another session's read. */
105let transcript: { sessionId: string; path: string } | null = null
106
107function noteTranscript(sessionId: unknown, path: unknown): void {
108  if (typeof path === 'string' && path && typeof sessionId === 'string' && sessionId) transcript = { sessionId: cleanId(sessionId), path }
109}
110
111function transcriptFor(sid: string): string | undefined {
112  return transcript !== null && sid !== '' && transcript.sessionId === sid ? transcript.path : undefined
113}
114let warmInFlight = false
115/**
116 * Which session the band is serving: bumped when one starts, is cleared or is
117 * swapped in. Work begun under one generation drops its result in the next.
118 */
119let sessionGen = 0
120/**
121 * A press is being claimed: a second press meanwhile is ignored (no double
122 * compaction). A claim older than the busy timeout is stale: a stuck press
123 * never holds the buttons past it.
124 */
125let claim: { at: number } | null = null
126/**
127 * The one engine call the buttons may have running: our `$.session.compact()`
128 * or our `$.command.run({ command: 'clear' })`. Set before the call's first
129 * await, cleared only when it settles, whatever the busy timeout says: a
130 * second compaction or clear never overlaps it. `engineCallAtom` records it
131 * too, so a reload mid-call still refuses (see runningCall).
132 */
133let engineCall: 'compact' | 'clear' | null = null
134/** When engineCall was claimed: a call that never settles stops blocking after HANDOFF_TTL_MS. */
135let engineCallAt = 0
136/** The live session a render last asked to re-read after finding another session's figures. */
137let resyncFor = ''
138/** Compactions that landed in this process, so Clean up can tell one happened during its /compact. */
139let compactionsLanded = 0
140
141/** The store key for the user's band size: the user's choice, so it survives sessions and restarts. */
142const SIZE_KEY = 'status-bar-size'
143/** The env default (TOKEN_OPTIMIZER_STATUS_BAR_SIZE), read once in readSwitches. */
144let sizeEnvDefault: BandSize = 'full'
145/** The stored size, once read or pressed: null while only the env default applies. */
146let sizeClicked: BandSize | null = null
147/** Whether $.store was consulted for the size successfully (a failed read retries next render). */
148let sizeRead = false
149
150const attempt = async <T,>(work: () => Promise<T>, fallback: T): Promise<T> => {
151  try {
152    return await work()
153  } catch {
154    return fallback
155  }
156}
157
158/** Session ids become file names; keep what Token Optimizer's sanitizer keeps (as data.ts does). */
159
160// ---- data ----
161
162/** The gatherer's port over `$` (data.ts never sees `$`). */
163function dataIo($: EngineInterface): DataIo {
164  return {
165    now: () => $.clock.now(),
166    sessionId: () => $.session.id(),
167    cwd: () => $.session.cwd(),
168    envHome: () => $.env.get('HOME'),
169    envUserProfile: () => $.env.get('USERPROFILE'),
170    envConfigDir: () => $.env.get('CLAUDE_CONFIG_DIR'),
171    envAutoCompactWindow: () => $.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW'),
172    usage: () => $.session.usage(),
173    list: path => $.fs.list(path),
174    stat: path => $.fs.stat(path),
175    read: async path => {
176      const text = await $.fs.read(path)
177      return typeof text === 'string' ? text : ''
178    },
179    run: (argv, init) => $.process.run(argv, init),
180    pluginRoot: () => $.plugin.root,
181    log: async text => {
182      await $.ui.log(text, { to: 'debug' })
183    },
184  }
185}
186
187/** Gather and store the session's figures, then let the cache clock learn from them. */
188async function refresh($: EngineInterface, options: GatherOptions = {}): Promise<void> {
189  let gen = sessionGen
190  const current = await attempt(() => read($, sessionAtom), null)
191  const liveSid = cleanId(options.sessionId ?? (await attempt(() => $.session.id(), '')))
192  const path = options.transcript ?? transcriptFor(liveSid)
193  const fresh = await gather(dataIo($), current, path ? { ...options, transcript: path } : options)
194  // Begun before a clear or a session change: its figures belong to the old session.
195  if (gen !== sessionGen) return
196  if (!options.reset && current !== null && fresh.sessionId !== '' && current.sessionId !== fresh.sessionId) {
197    // Another session (a new one, or a resume): nothing of the last one carries over.
198    sessionGen += 1
199    gen = sessionGen
200    toolsPending = 0
201    await feedClock($, { type: 'clear' })
202    await setUi($, () => initialUi())
203    lastCold = null
204    await feedPose($, { type: 'session-start' })
205  }
206  const latest = await attempt(() => read($, sessionAtom), null)
207  if (gen !== sessionGen) return
208  const merged = mergeStored(latest, fresh, options.reset, options.savings === true)
209  // Nothing shown changed (gatheredAt always does): no write, so no redraw.
210  if (latest !== null && sameShown(latest, merged)) return void (await syncClock($, fresh, gen))
211  await update($, sessionAtom, cur => gen === sessionGen ? mergeStored(cur, fresh, options.reset, options.savings === true) : cur)
212  if (gen !== sessionGen) return
213  await syncClock($, fresh, gen)
214}
215
216function sameShown(a: TokenOptimizerDesktopSession, b: TokenOptimizerDesktopSession): boolean {
217  return JSON.stringify({ ...a, gatheredAt: 0 }) === JSON.stringify({ ...b, gatheredAt: 0 })
218}
219
220/**
221 * Runs work off the current event (the status command can take seconds). Where no
222 * clock can schedule it, it runs now rather than not at all.
223 */
224async function later($: EngineInterface, work: () => Promise<void>): Promise<void> {
225  // Work for the session as it is now: a clear or session change before it runs drops it.
226  const gen = sessionGen
227  const guarded = async () => {
228    if (gen === sessionGen) await work()
229  }
230  try {
231    $.clock.after(0, () => void attempt(guarded, undefined))
232  } catch {
233    await attempt(guarded, undefined)
234  }
235}
236
237/** A prompt is taking the hand-off: a second prompt in the same moment does not. */
238let takingHandoff = false
239
240/** Tool calls the band counted since the last write: written alongside a redraw that happens anyway. */
241let toolsPending = 0
242
243async function flushTools($: EngineInterface): Promise<void> {
244  if (toolsPending === 0) return
245  const n = toolsPending
246  toolsPending = 0
247  await attempt(() => update($, sessionAtom, cur => (cur ? { ...cur, toolCallsSeen: (cur.toolCallsSeen ?? 0) + n } : cur)), undefined)
248}
249
250/** The status command's anchor and measured lifetime feed the clock when they are newer than what it holds. */
251async function syncClock($: EngineInterface, s: TokenOptimizerDesktopSession, gen?: number): Promise<void> {
252  if (gen !== undefined && gen !== sessionGen) return
253  await attempt(
254    () =>
255      update($, clockAtom, cur => {
256        if (gen !== undefined && gen !== sessionGen) return cur
257        let c: ClockState = cur ?? initialClock()
258        if (s.cacheLifetime && c.lifetime !== s.cacheLifetime) c = reduceClock(c, { type: 'lifetime-measured', lifetime: s.cacheLifetime })
259        if (s.lastRequestEpoch !== null) {
260          const at = s.lastRequestEpoch * 1000
261          if (c.anchor === null || at > c.anchor) {
262            c = reduceClock(c, { type: 'request-done', at, lifetime: s.cacheLifetime, contextTokens: s.contextTokens ?? c.contextTokens ?? 0 })
263          }
264        }
265        if (c.contextTokens === null && s.contextTokens !== null) c = { ...c, contextTokens: s.contextTokens }
266        return c
267      }),
268    undefined,
269  )
270}
271
272async function feedClock($: EngineInterface, event: ClockEvent, now?: number): Promise<void> {
273  await attempt(() => update($, clockAtom, cur => reduceClock(cur ?? initialClock(), event, now)), undefined)
274}
275
276/**
277 * One pose event. The reducer runs on the module copy; the atom is written
278 * only when something the drawing or a reload needs has changed.
279 */
280async function feedPose($: EngineInterface, event: PoseEvent): Promise<void> {
281  try {
282    const now = await $.clock.now()
283    if (!poseLive) poseLive = (await read($, poseAtom)) ?? initialPose(now)
284    poseLive = reducePose(poseLive, event, now)
285    const s = poseLive
286    const sig = JSON.stringify([s.pose, s.since, s.working, s.sub, s.agents, s.permissions, s.questions, s.compacting, s.cold, s.until])
287    if (sig !== poseSig) {
288      poseSig = sig
289      await update($, poseAtom, () => s)
290    }
291    // A sub-pose waiting out its debounce settles on a tick of its own.
292    if (s.rawSub !== s.sub && !settleQueued) {
293      settleQueued = true
294      $.clock.after(DEBOUNCE_MS, () => {
295        settleQueued = false
296        void feedPose($, { type: 'tick', now: 0 })
297      })
298    }
299  } catch {
300    // A pose that cannot be stored never breaks the event it rode on.
301  }
302}
303
304/** Permission prompts and questions have no closing event of their own: close them on the next sign of life. */
305async function closeAsks($: EngineInterface): Promise<void> {
306  // After a reload the module copy is empty until the first pose event: read the stored one.
307  if (!poseLive) poseLive = await attempt(() => read($, poseAtom), null)
308  for (let i = poseLive?.permissions ?? 0; i > 0; i--) await feedPose($, { type: 'permission-closed' })
309  for (let i = poseLive?.questions ?? 0; i > 0; i--) await feedPose($, { type: 'question-closed' })
310}
311
312function planDefault(s: TokenOptimizerDesktopSession | null): 3600 | 300 {
313  // Rate limits mean a Claude plan: an hour of cache; the API keeps five minutes.
314  // A limit seen once this session keeps it a plan, even if usage briefly stops reporting one.
315  return s && (s.fiveHour || s.week || s.sawLimits) ? 3600 : 300
316}
317
318/**
319 * Keeps Clawd's transients and naps moving and redraws when what the band
320 * shows changes: by the second near a deadline or during a hold, otherwise
321 * every 5 s, with at most one redraw a minute while nothing moves.
322 */
323/** Last tick that did its full work: when nothing moves by the second, every 5 s is enough. */
324let fullTickAt = 0
325const QUIET_TICK_MS = 5000
326/** Something on screen changes by the second (the last cache minutes, a note, a pending press). */
327let nearDeadline = false
328
329async function tick($: EngineInterface): Promise<void> {
330  try {
331    const now = await $.clock.now()
332    // By the second only while a countdown is near its end, a transient pose holds, or a
333    // press is pending; otherwise every 5 s (each tick is several engine calls).
334    // A hold still running at the last full tick keeps ticking by the second until it ends.
335    const urgent = poseLive !== null && Object.values(poseLive.until).some(t => t > fullTickAt)
336    if (!urgent && !settleQueued && now - fullTickAt < QUIET_TICK_MS && !nearDeadline) return
337    fullTickAt = now
338    await feedPose($, { type: 'tick', now })
339    const clock = (await read($, clockAtom)) ?? initialClock()
340    const session = await read($, sessionAtom)
341    const ui = (await read($, uiAtom)) ?? initialUi()
342    const v = view(clock, now, planDefault(session))
343    const cold = v.state === 'cold'
344    if (cold !== lastCold) {
345      lastCold = cold
346      await feedPose($, { type: 'cache-cold-changed', cold })
347    }
348    // Only a change the band shows redraws it, at most once a minute: the desktop restarts
349    // Clawd's picture on every redraw, so a per-second countdown made him blink each second.
350    // One minute clock: the cache countdown's when it runs, else the wall clock's (for "27m ago").
351    const minute = v.secondsLeft != null ? `c${Math.ceil(v.secondsLeft / 60)}` : `w${Math.floor(now / TICK_IDLE_MS)}`
352    const text = [v.state, minute, busyNow(ui, now), noteNow(ui, now), isArmed(ui, now)].join('|')
353    nearDeadline = v.state === 'warning' || v.state === 'warming' || busyNow(ui, now) !== null || noteNow(ui, now) !== null || isArmed(ui, now)
354    if (text !== frameText) await flushTools($)
355    if (text !== frameText) {
356      frameText = text
357      await update($, frameAtom, n => (n ?? 0) + 1)
358    }
359  } catch {
360    // The next tick tries again.
361  }
362}
363
364function startCadence($: EngineInterface): void {
365  for (const t of timers) t.cancel()
366  timers = []
367  try {
368    timers.push($.clock.every(TICK_WARNING_MS, () => void tick($)))
369    timers.push($.clock.every(QUALITY_REFRESH_MS, () => void attempt(() => refresh($), undefined)))
370  } catch {
371    // No timers: the band still redraws on events.
372  }
373}
374
375/** Everything a desktop session needs once: a pending hand-off from disk, figures, the cadence. */
376async function start($: EngineInterface): Promise<void> {
377  sessionGen += 1
378  // A warm-up marked running with no fork in flight here was cut off by a reload.
379  const clock = await attempt(() => read($, clockAtom), null)
380  if (clock?.warming && !warmInFlight) await feedClock($, { type: 'warm-failed' })
381  const sizing = attempt(() => readSize($), undefined)
382  const held = await heldHandoff($)
383  if (held) await handoffThatFits($, held)
384  await sizing
385  await feedPose($, { type: 'session-start' })
386  // The quick reads now, so the band fills at once; the status command (seconds, at worst)
387  // runs off the start event, so the session never waits on it.
388  await attempt(() => refresh($), undefined)
389  await later($, () => refresh($, { savings: true }))
390  startCadence($)
391}
392
393function isHandoff(v: unknown): v is Handoff {
394  if (!v || typeof v !== 'object') return false
395  const h = v as Record<string, unknown>
396  return typeof h.fromSessionId === 'string' && typeof h.cwd === 'string' && typeof h.text === 'string' && h.text !== '' && typeof h.checkpointPath === 'string' && typeof h.createdAt === 'number'
397}
398
399/**
400 * The pending hand-off. `$.store` is the truth (it survives restarts and is
401 * deleted when one session takes it); the atom only mirrors it for drawing. A
402 * store that cannot be read holds nothing: no stale mirror is ever attached.
403 */
404async function heldHandoff($: EngineInterface): Promise<Handoff | null> {
405  let stored: unknown
406  try {
407    stored = await $.store.get(HANDOFF_KEY)
408  } catch {
409    return null
410  }
411  const held = isHandoff(stored) ? stored : null
412  if (stored != null && !held) await attempt(() => $.store.delete(HANDOFF_KEY), undefined)
413  const mirror = await attempt(() => read($, handoffAtom), null)
414  if (JSON.stringify(mirror) !== JSON.stringify(held)) await attempt(() => update($, handoffAtom, () => held), undefined)
415  return held
416}
417
418/** When the live session began (`$.clock.now()` ms), or null when the engine cannot say. */
419async function sessionStartedAt($: EngineInterface): Promise<number | null> {
420  const usage = await attempt(() => $.session.usage(), null)
421  return typeof usage?.startedAt === 'number' && Number.isFinite(usage.startedAt) ? usage.startedAt : null
422}
423
424/**
425 * The held hand-off when it joins this session: another session than
426 * the one that saved it, in its project, started since the save, within 10
427 * minutes of it. An expired one in this project is dropped with a one-line
428 * note; another project's is left alone. `as` names the session when the
429 * caller knows its id better than the engine does yet (a clear's own start event).
430 */
431async function handoffThatFits($: EngineInterface, h: Handoff, as?: { sessionId: string; startedAt: number | null }): Promise<Handoff | null> {
432  const sessionId = as?.sessionId ?? cleanId(await attempt(() => $.session.id(), ''))
433  const cwd = await attempt(() => $.session.cwd(), '')
434  const now = await $.clock.now()
435  const startedAt = as ? as.startedAt : await sessionStartedAt($)
436  const fate = handoffFate(h, { sessionId, cwd, startedAt, now })
437  if (fate === 'attach') return h
438  if (fate === 'skip') return null
439  await dropHandoff($)
440  const line = `Start fresh's saved hand-off was discarded: ${fate.drop}.`
441  await setUi($, u => withNote(u, line, now))
442  toast($, line)
443  return null
444}
445
446/** The refusal for a press while our compaction or clear still runs. */
447function stillRunning(kind: 'compact' | 'clear'): string {
448  return kind === 'compact' ? 'Still finishing the last clean-up.' : 'Still clearing.'
449}
450
451/**
452 * Our compaction or clear still running: this module's own, or one recorded
453 * before a reload that is under 10 minutes old (an older record is cleared).
454 */
455async function runningCall($: EngineInterface): Promise<'compact' | 'clear' | null> {
456  if (engineCall) {
457    const at = await attempt(() => $.clock.now(), null)
458    if (at === null || at - engineCallAt < HANDOFF_TTL_MS) return engineCall
459    // Never settled: the record's own expiry below decides, as after a reload.
460    engineCall = null
461  }
462  const held = await attempt(() => read($, engineCallAtom), null)
463  if (engineCall) return engineCall
464  if (!held) return null
465  // A clock that cannot be read keeps the record: refuse rather than overlap.
466  const now = await attempt(() => $.clock.now(), null)
467  if (now === null || now - held.startedAt < HANDOFF_TTL_MS) return held.kind
468  await attempt(() => update($, engineCallAtom, cur => (cur && cur.startedAt === held.startedAt && cur.kind === held.kind ? null : cur)), undefined)
469  return null
470}
471
472/**
473 * Claims the one engine call (the caller checked runningCall with no await
474 * since) and records it for a reload. False when it cannot be recorded: the
475 * call is not made.
476 */
477async function claimCall($: EngineInterface, kind: 'compact' | 'clear'): Promise<{ kind: 'compact' | 'clear'; startedAt: number } | null> {
478  // Never over a call already in flight, whatever the caller checked before.
479  if (engineCall !== null) return null
480  engineCall = kind
481  try {
482    const mine = { kind, startedAt: await $.clock.now() }
483    engineCallAt = mine.startedAt
484    await update($, engineCallAtom, () => mine)
485    return mine
486  } catch {
487    engineCall = null
488    return null
489  }
490}
491
492/** The call settled: release it here and in the record (only our own record). */
493async function releaseCall($: EngineInterface, mine: { kind: 'compact' | 'clear'; startedAt: number }): Promise<void> {
494  engineCall = null
495  await attempt(() => update($, engineCallAtom, cur => (cur && cur.kind === mine.kind && cur.startedAt === mine.startedAt ? null : cur)), undefined)
496}
497
498// ---- buttons ----
499
500function toast($: EngineInterface, text: string): void {
501  try {
502    $.ui.toast(text)
503  } catch {
504    // A toast that cannot show is not worth failing a press over.
505  }
506}
507
508async function setUi($: EngineInterface, fn: (ui: UiState) => UiState): Promise<void> {
509  await attempt(() => update($, uiAtom, cur => fn(cur ?? initialUi())), undefined)
510}
511
512async function disarm($: EngineInterface): Promise<void> {
513  const ui = await attempt(() => read($, uiAtom), null)
514  if (ui?.freshArmedAt != null) await setUi($, u => ({ ...u, freshArmedAt: null }))
515}
516
517const BUSY_WORDS: Record<Exclude<Busy, null>, string> = {
518  clean: 'Clean up',
519  'fresh-capture': 'Start fresh',
520  'fresh-clear': 'Start fresh',
521  dashboard: 'Opening the dashboard',
522}
523
524/** A busy state ends by itself: a step label never outlives its work. */
525function armBusyTimeout($: EngineInterface, busy: Exclude<Busy, null>, since: number): void {
526  try {
527    $.clock.after(busyTimeoutMs(busy), () => void expireBusy($, busy, since))
528  } catch {
529    // busyNow() still treats it as over after the timeout.
530  }
531}
532
533async function expireBusy($: EngineInterface, busy: Exclude<Busy, null>, since: number): Promise<void> {
534  const ui = await attempt(() => read($, uiAtom), null)
535  if (!ui || ui.busy !== busy || ui.busySince !== since) return
536  const now = await $.clock.now()
537  // The clear waits for the turn to end and can still land: the hand-off stays
538  // for the conversation it creates, within 10 minutes of the save.
539  const line =
540    busy === 'fresh-clear' ? 'Start fresh clears when the current turn ends.' : busy === 'dashboard' ? DASHBOARD_FAILED : `${BUSY_WORDS[busy]} timed out.`
541  await setUi($, u => withNote(withBusy(u, null, now), line, now))
542  // The dashboard link fails by its note alone.
543  if (busy !== 'dashboard') toast($, line)
544}
545
546/** Deletes the held hand-off, store first; true only when the delete succeeded (the mirror follows it). */
547async function dropHandoff($: EngineInterface): Promise<boolean> {
548  try {
549    await $.store.delete(HANDOFF_KEY)
550  } catch {
551    return false
552  }
553  await attempt(() => update($, handoffAtom, () => null), undefined)
554  return true
555}
556
557async function isTurnRunning($: EngineInterface): Promise<boolean> {
558  const clock = await attempt(() => read($, clockAtom), null)
559  return Boolean(clock?.working || poseLive?.working)
560}
561
562/** Clean up: compaction with Token Optimizer's own PreCompact guidance, run outside the press. */
563async function cleanUp($: EngineInterface): Promise<void> {
564  const now = await $.clock.now()
565  const ui = (await attempt(() => read($, uiAtom), null)) ?? initialUi()
566  if (busyNow(ui, now) !== null) return
567  await disarm($)
568  const running = await runningCall($)
569  if (running) {
570    toast($, stillRunning(running))
571    return
572  }
573  if (await isTurnRunning($)) {
574    toast($, 'Clean up waits until the turn finishes.')
575    return
576  }
577  await setUi($, u => withBusy(u, 'clean', now))
578  armBusyTimeout($, 'clean', now)
579  $.clock.after(0, () => void attempt(() => runCompact($, now), undefined))
580}
581
582async function runCompact($: EngineInterface, since: number): Promise<void> {
583  // A turn that started since the press would be cut short.
584  if (await isTurnRunning($)) {
585    const ui = await attempt(() => read($, uiAtom), null)
586    if (!ui || ui.busy !== 'clean' || ui.busySince !== since) return
587    const now = await $.clock.now()
588    await setUi($, u => withBusy(u, null, now))
589    toast($, 'Clean up waits until the turn finishes.')
590    return
591  }
592  const running = await runningCall($)
593  if (running || engineCall) {
594    const ui = await attempt(() => read($, uiAtom), null)
595    if (!ui || ui.busy !== 'clean' || ui.busySince !== since) return
596    const now = await $.clock.now()
597    await setUi($, u => withBusy(u, null, now))
598    toast($, stillRunning(running ?? engineCall ?? 'compact'))
599    return
600  }
601  /** The note when no compaction can be confirmed; null after a confirmed one. */
602  let skip: string | null = null
603  const skipped = (reason: string) => `Clean up skipped: ${reason.replace(/\.$/, '')}.`
604  // Claimed with no await between the check and the claim; recorded before the call.
605  const mine = await claimCall($, 'compact')
606  if (!mine) {
607    skip = skipped('it could not be recorded')
608  } else {
609    try {
610      // The command, as if typed: $.session.compact() is refused in a headless
611      // session, and the desktop app runs its sessions headless.
612      // Success is decided from evidence, never from the reply's words (#207):
613      // Claude Code answers a refused /compact ("Not enough messages to compact.",
614      // a hook's veto) without throwing, and a reply may be empty or not English.
615      const landedBefore = compactionsLanded
616      const tokensBefore = liveTokens(await attempt(() => $.session.usage(), null))
617      const answer = await $.command.run({ command: 'compact' })
618      const tokensAfter = liveTokens(await attempt(() => $.session.usage(), null))
619      const outcome = cleanUpOutcome({
620        landed: compactionsLanded > landedBefore,
621        tokensBefore,
622        tokensAfter,
623        said: answer?.text ?? '',
624      })
625      if (!outcome.ok) skip = outcome.line
626    } catch (error) {
627      skip = skipped(error instanceof Error && error.message ? error.message.split('\n')[0] ?? 'it failed' : 'it failed')
628    } finally {
629      await releaseCall($, mine)
630    }
631  }
632  const ui = await attempt(() => read($, uiAtom), null)
633  // Timed out meanwhile, or another step took over: nothing to report here.
634  if (!ui || ui.busy !== 'clean' || ui.busySince !== since) return
635  const now = await $.clock.now()
636  if (skip !== null) {
637    const line = skip
638    await setUi($, u => withNote(withBusy(u, null, now), line, now))
639    toast($, line)
640  } else {
641    await setUi($, u => withNote(withBusy(u, null, now), 'Cleaned up.', now))
642  }
643  $.clock.after(0, () => void attempt(() => refresh($), undefined))
644}
645
646/** Keep warm: guarded at press time, one fork, never on a timer. */
647async function keepWarm($: EngineInterface): Promise<void> {
648  const now = await $.clock.now()
649  await disarm($)
650  const clock = (await attempt(() => read($, clockAtom), null)) ?? initialClock()
651  if (warmInFlight || clock.warming) {
652    toast($, 'A warm-up is already running.')
653    return
654  }
655  if (!canKeepWarm(clock, now)) {
656    toast($, clock.working || (await isTurnRunning($)) ? 'Keep warm waits until the turn finishes.' : 'The cache is too close to dropping to keep it warm.')
657    return
658  }
659  warmInFlight = true
660  const gen = sessionGen
661  await feedClock($, { type: 'warm-start' }, now)
662  $.clock.after(0, () => void attempt(() => runWarm($, clock.contextTokens, gen), undefined))
663}
664
665type ForkReply = Awaited<ReturnType<EngineInterface['model']['fork']>>
666
667/** The warm-up fork, or null once `ms` pass without an answer; a late answer is then ignored. */
668function forkWithin($: EngineInterface, ms: number): Promise<ForkReply | null> {
669  return new Promise<ForkReply | null>((resolve, reject) => {
670    let timer: { cancel: () => void } | null = null
671    try {
672      timer = $.clock.after(ms, () => resolve(null))
673    } catch {
674      // No timer: the fork alone decides.
675    }
676    $.model.fork({ prompt: WARM_PROMPT }).then(
677      reply => {
678        timer?.cancel()
679        resolve(reply)
680      },
681      error => {
682        timer?.cancel()
683        reject(error)
684      },
685    )
686  })
687}
688
689async function runWarm($: EngineInterface, known: number | null, gen: number): Promise<void> {
690  try {
691    const session = await attempt(() => read($, sessionAtom), null)
692    // A recorded 0 is no size at all: fall back to the session's own.
693    const contextTokens = known || session?.contextTokens || 0
694    const reply = await forkWithin($, BUSY_TIMEOUT_MS)
695    // Cleared meanwhile: this warm-up says nothing about the new session.
696    if (gen !== sessionGen) return
697    const at = await $.clock.now()
698    if (reply === null) {
699      await feedClock($, { type: 'warm-failed' })
700      toast($, warmToast({ ok: false, reason: 'the request failed' }))
701    } else if (reply.isAnswered) {
702      await feedClock($, { type: 'warm-done', at, cacheReadTokens: reply.usage.cache_read_input_tokens, contextTokens })
703      const after = await attempt(() => read($, clockAtom), null)
704      const line = warmToast({
705        ok: true,
706        lapsed: Boolean(after?.lapsed),
707        contextTokens,
708        cacheRead: reply.usage.cache_read_input_tokens,
709        lifetimeS: view(after ?? initialClock(), at, planDefault(session)).lifetime,
710      })
711      toast($, line)
712      // Also in the sentence for a few seconds, where the eye already is.
713      await setUi($, u => withNote(u, line, at))
714    } else {
715      await feedClock($, { type: 'warm-failed' })
716      toast($, warmToast({ ok: false, reason: reply.reason }))
717    }
718  } catch {
719    if (gen !== sessionGen) return
720    await feedClock($, { type: 'warm-failed' })
721    toast($, warmToast({ ok: false, reason: 'the request failed' }))
722  } finally {
723    warmInFlight = false
724  }
725}
726
727/**
728 * "Full dashboard": the dashboard command (it regenerates the page and opens it in the
729 * browser, whatever the OS opener is) through the runner Start fresh uses. A click while
730 * anything is busy is ignored; a failure is a note for NOTE_MS and nothing else.
731 */
732async function openDashboard($: EngineInterface): Promise<void> {
733  const now = await $.clock.now()
734  const ui = (await attempt(() => read($, uiAtom), null)) ?? initialUi()
735  if (!canOpenDashboard(ui, now)) return
736  await setUi($, u => withBusy(u, 'dashboard', now))
737  armBusyTimeout($, 'dashboard', now)
738  $.clock.after(0, () => void attempt(() => runDashboard($, now), undefined))
739}
740
741async function runDashboard($: EngineInterface, since: number): Promise<void> {
742  const io = dataIo($)
743  const root = await attempt(async () => findTokenOptimizerRoot(io, await readHome(io)), null)
744  const result = root ? await attempt(() => runMeasure(io, root, DASHBOARD_ARGS, { timeoutMs: DASHBOARD_TIMEOUT_MS }), null) : null
745  const ui = await attempt(() => read($, uiAtom), null)
746  // Timed out meanwhile, or another step took over: the person was told already.
747  if (!ui || ui.busy !== 'dashboard' || ui.busySince !== since) return
748  const now = await $.clock.now()
749  const failed = dashboardFailed(result)
750  await setUi($, u => (failed ? withNote(withBusy(u, null, now), DASHBOARD_FAILED, now) : withBusy(u, null, now)))
751}
752
753/** Start fresh: first press arms, a second within 5 s runs it. */
754async function startFresh($: EngineInterface): Promise<void> {
755  const now = await $.clock.now()
756  const ui = (await attempt(() => read($, uiAtom), null)) ?? initialUi()
757  if (busyNow(ui, now) !== null) return
758  if (!isArmed(ui, now)) {
759    await setUi($, u => ({ ...u, freshArmedAt: now }))
760    return
761  }
762  const running = await runningCall($)
763  if (running) {
764    await disarm($)
765    toast($, stillRunning(running))
766    return
767  }
768  if (await isTurnRunning($)) {
769    await disarm($)
770    toast($, 'Start fresh waits until the turn finishes.')
771    return
772  }
773  const sid = cleanId(await attempt(() => $.session.id(), ''))
774  if (!sid) {
775    await disarm($)
776    toast($, 'Start fresh stopped: no session to save. Nothing was cleared.')
777    return
778  }
779  const gen = sessionGen
780  await setUi($, u => withBusy(u, 'fresh-capture', now))
781  armBusyTimeout($, 'fresh-capture', now)
782  $.clock.after(0, () => void attempt(() => runFresh($, sid, now, gen), undefined))
783}
784
785/** Still the session Start fresh was pressed in: a typed /clear meanwhile means stand down. */
786async function stillSession($: EngineInterface, sid: string, gen: number): Promise<boolean> {
787  return gen === sessionGen && cleanId(await attempt(() => $.session.id(), '')) === sid
788}
789
790async function runFresh($: EngineInterface, sid: string, since: number, gen: number): Promise<void> {
791  const io = dataIo($)
792  const stop = async (reason: string): Promise<void> => {
793    const ui = await attempt(() => read($, uiAtom), null)
794    if (!ui || ui.busySince !== since) return
795    const now = await $.clock.now()
796    const line = `Start fresh stopped: ${reason}. Nothing was cleared.`
797    await setUi($, u => withNote(withBusy(u, null, now), line, now))
798    toast($, line)
799  }
800
801  const root = await findTokenOptimizerRoot(io, await readHome(io))
802  if (!root) return stop('Token Optimizer was not found')
803  const port: HandoffPort = {
804    run: (args, stdin) =>
805      runMeasure(io, root, args, {
806        timeoutMs: args[0] === 'compact-capture' ? CAPTURE_TIMEOUT_MS : RESUME_TIMEOUT_MS,
807        ...(stdin === undefined ? {} : { stdin }),
808      }),
809    read: path => io.read(path),
810  }
811  const cwd = await attempt(() => $.session.cwd(), '')
812  // `now` is a placeholder: the hand-off is stamped once its save lands (below).
813  const result = await prepareHandoff(port, { sessionId: sid, transcriptPath: transcriptFor(cleanId(sid)) ?? null, cwd, now: since })
814  const standDown = async (): Promise<void> => {
815    const now = await $.clock.now()
816    await setUi($, u => (u.busySince === since ? withBusy(u, null, now) : u))
817  }
818  // The session changed under it (a typed /clear, a resume): clear nothing, and say so.
819  const changed = async (): Promise<void> => {
820    await standDown()
821    toast($, 'Start fresh stopped: the session changed.')
822  }
823  if (!(await stillSession($, sid, gen))) return changed()
824  const ui = await attempt(() => read($, uiAtom), null)
825  // Timed out meanwhile: the person was told; clear nothing.
826  if (!ui || ui.busy !== 'fresh-capture' || ui.busySince !== since) return
827  if (!result.ok) return stop(result.reason)
828  // Our compaction or clear still running: never overlap it.
829  const running = await runningCall($)
830  if (running) return stop(running === 'compact' ? 'the last clean-up is still running' : 'the last clear is still running')
831  // A turn started during the capture: a queued clear would wipe it.
832  if (await isTurnRunning($)) {
833    await standDown()
834    toast($, 'Start fresh waits until the turn finishes.')
835    return
836  }
837
838  // Saved, then stamped from the clock right after the save lands: the
839  // 10-minute window and "started since the save" both count from there.
840  let handoff: Handoff
841  try {
842    // First kept with a stamp in the far future, so no session can count as "started
843    // since the save" until the real stamp below lands.
844    await $.store.set(HANDOFF_KEY, { ...result.handoff, createdAt: Number.MAX_SAFE_INTEGER, pendingSince: since })
845  } catch {
846    return stop('the hand-off could not be kept on disk')
847  }
848  try {
849    handoff = { ...result.handoff, createdAt: await $.clock.now() }
850    await $.store.set(HANDOFF_KEY, handoff)
851  } catch {
852    await dropHandoff($)
853    return stop('the hand-off could not be kept on disk')
854  }
855  try {
856    await update($, handoffAtom, () => handoff)
857  } catch {
858    // The new session would never see it.
859    await dropHandoff($)
860    return stop('the hand-off could not be kept on disk')
861  }
862  if (!(await stillSession($, sid, gen))) {
863    await dropHandoff($)
864    return changed()
865  }
866  const now = await $.clock.now()
867  await setUi($, u => withBusy(u, 'fresh-clear', now))
868  armBusyTimeout($, 'fresh-clear', now)
869  $.clock.after(0, () => void attempt(() => runClear($, now, handoff, sid, gen), undefined))
870}
871
872async function runClear($: EngineInterface, since: number, handoff: Handoff, sid: string, gen: number): Promise<void> {
873  const ours = (h: Handoff | null) => h !== null && h.fromSessionId === handoff.fromSessionId && h.createdAt === handoff.createdAt
874  const fail = async (line: string): Promise<void> => {
875    const held = await attempt(() => read($, handoffAtom), null)
876    if (ours(held)) await dropHandoff($)
877    const now = await $.clock.now()
878    await setUi($, u => withNote(u.busy === 'fresh-clear' && u.busySince === since ? withBusy(u, null, now) : u, line, now))
879    toast($, line)
880  }
881  // The session changed while the clear waited its turn: clear nothing.
882  if (gen !== sessionGen || cleanId(await attempt(() => $.session.id(), '')) !== sid) {
883    const held = await attempt(() => read($, handoffAtom), null)
884    if (ours(held)) await dropHandoff($)
885    const now = await $.clock.now()
886    await setUi($, u => (u.busy === 'fresh-clear' && u.busySince === since ? withBusy(u, null, now) : u))
887    toast($, 'Start fresh stopped: the session changed.')
888    return
889  }
890  const running = await runningCall($)
891  if (running || engineCall) return fail(`Start fresh stopped: ${(running ?? engineCall) === 'compact' ? 'the last clean-up is still running' : 'the last clear is still running'}. Nothing was cleared.`)
892  // Claimed with no await between the check and the claim; recorded before the call.
893  const mine = await claimCall($, 'clear')
894  if (!mine) return fail('Start fresh could not clear. Your conversation is unchanged.')
895  let cleared = false
896  try {
897    await $.command.run({ command: 'clear' })
898    cleared = true
899  } catch {
900    // Reported below, once the call has settled.
901  } finally {
902    await releaseCall($, mine)
903  }
904  if (!cleared) return fail('Start fresh could not clear. Your conversation is unchanged.')
905  // The hand-off now waits for the first prompt of a conversation started since the save.
906  const now = await $.clock.now()
907  await setUi($, u => (u.busy === 'fresh-clear' && u.busySince === since ? withBusy(u, null, now) : u))
908}
909
910/**
911 * The user's band size: a stored click first, else the env default. The store
912 * is read off the render path (a store read can be slow) and kept in module
913 * state; a press made meanwhile always wins (it set sizeClicked itself).
914 */
915function bandSize(): BandSize {
916  return sizeClicked ?? sizeEnvDefault
917}
918
919/** One store read for the size, fired off the render path; a found size redraws once when it differs. */
920async function readSize($: EngineInterface): Promise<void> {
921  if (sizeRead || sizeClicked !== null) return
922  try {
923    const stored = await $.store.get(SIZE_KEY)
924    sizeRead = true
925    const found = storedSize(stored)
926    if (sizeClicked === null) {
927      sizeClicked = found
928      // A stored size that differs from what was drawn earns one redraw.
929      if (found !== null && found !== sizeEnvDefault) await attempt(() => update($, frameAtom, n => (n ?? 0) + 1), undefined)
930    }
931  } catch {
932    // Store unreadable for now: the env default serves; a later readSize call retries.
933  }
934}
935
936/** The size button: flips the band and remembers the choice. A refused write just does not persist. */
937async function toggleSize($: EngineInterface): Promise<void> {
938  await disarm($)
939  const next: BandSize = bandSize() === 'slim' ? 'full' : 'slim'
940  sizeClicked = next
941  await attempt(() => $.store.set(SIZE_KEY, next), undefined)
942  await attempt(() => update($, frameAtom, n => (n ?? 0) + 1), undefined)
943}
944
945async function toggleDetails($: EngineInterface): Promise<void> {
946  await disarm($)
947  await flushTools($)
948  const current = await attempt(() => read($, sessionAtom), null)
949  if (!current) return
950  const opening = !current.sheetOpen
951  await update($, sessionAtom, cur => (cur ? { ...cur, sheetOpen: !cur.sheetOpen } : cur))
952  // Savings read when the row opens.
953  if (opening) $.clock.after(0, () => void attempt(() => refresh($, { savings: true }), undefined))
954}
955
956async function act($: EngineInterface, id: ActionId | 'dashboard'): Promise<void> {
957  // One press at a time: the claim is taken before the first await, so a second press
958  // arriving while this one reads the clock sees it (an unread time counts as now).
959  const prior = claim
960  if (prior !== null && prior.at === Number.POSITIVE_INFINITY) return
961  const mine = { at: Number.POSITIVE_INFINITY }
962  claim = mine
963  const now = await attempt(() => $.clock.now(), 0)
964  if (prior !== null && now - prior.at < BUSY_TIMEOUT_MS) {
965    if (claim === mine) claim = prior
966    return
967  }
968  mine.at = now
969  try {
970    if (id === 'clean' || id === 'clean-first') await cleanUp($)
971    else if (id === 'dashboard') await openDashboard($)
972    else if (id === 'fresh') await startFresh($)
973    else await keepWarm($)
974  } catch {
975    toast($, 'That did not work. Try again in a moment.')
976  } finally {
977    if (claim === mine) claim = null
978  }
979}
980
981// ---- drawing ----
982
983const ring = (p: number, color: string, track: string, cold: boolean): string => {
984  const c = 2 * Math.PI * 7
985  const bg = cold ? `stroke="${color}" stroke-dasharray="2.2 2.2"` : `class="t" stroke="${track}"`
986  return (
987    `<circle cx="10" cy="10" r="7" fill="none" stroke-width="3.2" ${bg}/>` +
988    (p > 0 ? `<circle cx="10" cy="10" r="7" fill="none" stroke-width="3.2" stroke="${color}" stroke-linecap="round" stroke-dasharray="${((c * p) / 100).toFixed(1)} ${c.toFixed(1)}" transform="rotate(-90 10 10)"/>` : '')
989  )
990}
991
992/**
993 * The desktop gives the band no light/dark signal (the config's theme is the
994 * terminal's), so the marks and icons follow the app's own appearance through their
995 * colour-scheme query; the drawn colours are the light ones, the fallback.
996 * Classes: k = ink stroke, kf = ink fill, t = track stroke, tf = track fill.
997 */
998const DARK_STYLE = '<style>@media (prefers-color-scheme: dark){.k{stroke:#f3f1ea}.kf{fill:#f3f1ea}.t{stroke:#4b4a46}.tf{fill:#4b4a46}}</style>'
999
1000function themed(svg: string, rootClass?: string): string {
1001  const open = svg.indexOf('>') + 1
1002  const head = rootClass ? svg.slice(0, open - 1).replace('<svg ', `<svg class="${rootClass}" `) + '>' : svg.slice(0, open)
1003  return head + DARK_STYLE + svg.slice(open)
1004}
1005
1006const esc = (v: string): string => v.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
1007
1008/** A mark's ring or grade badge, as the artifact draws it: the colour lives here, the text stays ink. */
1009function markSvg(mark: Mark, t: Tones): string {
1010  const color = toneColor(mark.tone, t)
1011  const right =
1012    mark.badge !== undefined
1013      ? `<rect x="1" y="1" width="18" height="18" rx="5"${mark.tone === 'none' ? ' class="tf"' : ''} fill="${mark.tone === 'none' ? t.track : color}"/>` +
1014        `<text x="10" y="14" text-anchor="middle" font-family="system-ui, sans-serif" font-size="11.5" font-weight="700" fill="${t.card}">${esc(mark.badge)}</text>`
1015      : ring(mark.ringPercent ?? 0, color, t.track, mark.tone === 'cold')
1016  return themed(`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" role="img" aria-label="${esc(mark.alt)}"><title>${esc(mark.alt)}</title>${right}</svg>`)
1017}
1018
1019function toneColor(tone: MarkTone, t: Tones): string {
1020  return tone === 'none' ? t.track : t[tone]
1021}
1022
1023function runsOf(D: Desktop, runs: Run[], t: Tones) {
1024  const { Text } = D
1025  return runs.map(r => (r.lose ? <Text bold color={t.bad}>{r.text}</Text> : r.strong ? <Text bold>{r.text}</Text> : r.text))
1026}
1027
1028function icon(D: Desktop, name: IconName, color: string, alt?: string) {
1029  const { Svg } = D
1030  const label = alt ?? ICON_ALT[name]
1031  const svg = iconSvg(name, color, { alt: label })
1032  return <Svg source={color === LIGHT.ink ? themed(svg, 'k') : svg} alt={label} width={16} height={16} />
1033}
1034
1035type Model = {
1036  snap: Snapshot
1037  tones: Tones
1038  sheetOpen: boolean
1039  savingsReason: string | null
1040  /** Keep warm can run now (the one guard): only then does the row offer it. */
1041  canWarm: boolean
1042  /** Clawd's pictures, bottom first: the previous pose stays beneath a new one while it fades in. */
1043  clawd: ClawdLayer[]
1044  /** While watching: one picture per look, each shown while the pointer is over its part of the band. */
1045  gazes: (ClawdLayer & { gaze: Gaze })[]
1046}
1047
1048type ClawdLayer = { key: string; source: string; alt: string }
1049
1050/** How long the previous pose stays beneath a new one: the fade plus the picture's own load. */
1051const UNDERLAY_MS = 900
1052let clawdTop: ClawdLayer | null = null
1053let clawdUnder: (ClawdLayer & { until: number }) | null = null
1054
1055/**
1056 * The desktop shows nothing while a changed picture loads, so a bare swap
1057 * blinks. Keep the old pose drawn, unchanged and under its own key, beneath
1058 * the new one until the new one has faded in, then drop it.
1059 */
1060function clawdLayers($: EngineInterface, layer: ClawdLayer, now: number): ClawdLayer[] {
1061  if (clawdTop !== null && clawdTop.key !== layer.key) {
1062    clawdUnder = { ...clawdTop, until: now + UNDERLAY_MS }
1063    $.clock.after(UNDERLAY_MS + 50, () => void attempt(() => update($, frameAtom, n => (n ?? 0) + 1), undefined))
1064  }
1065  clawdTop = layer
1066  if (clawdUnder !== null && (clawdUnder.until <= now || clawdUnder.key === layer.key)) clawdUnder = null
1067  return clawdUnder !== null ? [clawdUnder, layer] : [layer]
1068}
1069
1070/** Below this, "saved this session" is noise and stays off the row. */
1071const SESSION_SAVED_MIN = 1000
1072
1073type Handlers = { act: (id: ActionId) => void; dashboard: () => void; details: () => void; size: () => void }
1074
1075/** The five marks with their hover cards: one line, never wrapped, in both sizes. */
1076function markRow(D: Desktop, markList: Mark[], cardList: Card[], t: Tones, on: Handlers) {
1077  const { Box, Text, Svg } = D
1078  return (
1079    <Box flexDirection="row" flexWrap="nowrap" columnGap={3}>
1080      {markList.map((mark, i) => (
1081        <Box key={`mark-${mark.id}`} position="relative" flexDirection="row" alignItems="center" columnGap={1}>
1082          <Svg source={markSvg(mark, t)} alt={mark.alt} width={20} height={20} />
1083          <Text bold>{mark.value}</Text>
1084          {/* Always labelled: without the word, nobody knows which number is which. */}
1085          <Text>{mark.label}</Text>
1086          {(() => {
1087            // Matched by id, not position: a missing limit never shifts a card under the wrong mark.
1088            const card = cardList.find(c => c.id === mark.id)
1089            return card ? cardBox(D, card, i, t, on) : ''
1090          })()}
1091        </Box>
1092      ))}
1093    </Box>
1094  )
1095}
1096
1097function cardBox(D: Desktop, card: Card, index: number, t: Tones, on: Handlers) {
1098  const { Box, Text, Button } = D
1099  const side = index < 2 ? { left: 0 } : { right: 0 }
1100  return (
1101    <Box
1102      position="absolute"
1103      bottom={1}
1104      {...side}
1105      display="none"
1106      hover={{ display: 'flex' }}
1107      flexDirection="column"
1108      width={34}
1109      paddingX={1}
1110      borderStyle="round"
1111      borderColor={t.line}
1112      backgroundColor={t.card}
1113    >
1114      <Text bold>{card.title}</Text>
1115      <Text wrap="wrap">{runsOf(D, card.body, t)}</Text>
1116      {card.actions.length > 0 ? (
1117        <Box flexDirection="row" columnGap={1} marginTop={1}>
1118          {card.actions.map(a => (
1119            <Button key={`card-${card.id}-${a.id}`} label={a.label} onPress={() => on.act(a.id)} />
1120          ))}
1121        </Box>
1122      ) : (
1123        ''
1124      )}
1125    </Box>
1126  )
1127}
1128
1129/** The unfolded row, shared by both sizes: the facts, any card action the moment calls for, the savings. */
1130function detailRow(D: Desktop, m: Model, on: Handlers, size: BandSize) {
1131  const { Box, Text, Button } = D
1132  const { snap, tones: t } = m
1133  const say = sentence(snap)
1134  const cardList = cards(snap)
1135  const detail = row(snap)
1136  // A card action joins the row only when the moment calls for it (quality sagging, the cache
1137  // about to drop) and the sentence's own button is not already offering it.
1138  const q = snap.quality
1139  const sagging = q !== null && (q.score < QUALITY_FLOOR || q.compactions >= COMPACT_HEAVY)
1140  const rowActions = [
1141    ...(sagging ? cardList.find(c => c.id === 'quality')?.actions ?? [] : []),
1142    ...(m.canWarm && snap.cache.state === 'warning' ? [{ id: 'warm' as const, label: 'Keep warm' }] : []),
1143  ].filter(a => a.id !== say.action?.id && !(a.id === 'clean' && say.action?.id === 'clean-first'))
1144
1145  // Said plainly: a bare "47M past 30 days" reads like tokens spent, and a 30-bar chart
1146  // ruled by one big day said nothing. The total is the dashboard's own.
1147  const sessionSaved = (detail.savings.sessionTokens ?? 0) >= SESSION_SAVED_MIN
1148  // No figure yet: say why (or that it is being measured), never "Saved -- tokens".
1149  const savingsBlock =
1150    detail.savings.last30Tokens == null ? (
1151      <Box flexDirection="row" alignItems="center" columnGap={1}>
1152        {icon(D, 'saved', t.ink)}
1153        <Text>{detail.savings.state === 'loading' ? 'Measuring savings…' : (m.savingsReason ?? detail.savings.reason ?? 'Savings appear once Token Optimizer has measured some.')}</Text>
1154      </Box>
1155    ) : (
1156      <Box flexDirection="row" alignItems="center" columnGap={1}>
1157        {icon(D, 'saved', t.good)}
1158        <Text>
1159          Saved <Text bold>{detail.savings.last30Text}</Text> tokens in 30 days
1160          {sessionSaved ? (
1161            <Text>
1162              {' '}(<Text bold>{detail.savings.sessionText}</Text> this session)
1163            </Text>
1164          ) : (
1165            ''
1166          )}
1167        </Text>
1168      </Box>
1169    )
1170
1171  // The end of the row: a plain text link (a Button drawn without chrome, the only thing the
1172  // desktop lets be pressed), its label its accessible name. The slim band has no sentence
1173  // line to carry "Opening the dashboard.", so there the status stands beside the link.
1174  const status = size === 'slim' ? dashboardStatus(snap.busy, snap.note) : null
1175  const dashboardLink = (
1176    <Box flexDirection="row" alignItems="center" columnGap={1}>
1177      {status !== null ? (
1178        <Box key="dashboard-status">
1179          <Text>{status}</Text>
1180        </Box>
1181      ) : (
1182        ''
1183      )}
1184      <Button key="dashboard" plain label="Full dashboard" onPress={() => on.dashboard()} />
1185    </Box>
1186  )
1187
1188  return (
1189    <Box key="row" flexDirection="row" flexWrap="wrap" alignItems="center" justifyContent="space-between" columnGap={2} rowGap={1}>
1190      <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={2} rowGap={1}>
1191        {detail.facts.map(f => (
1192          <Box flexDirection="row" alignItems="center" columnGap={1}>
1193            {icon(D, f.icon, t.ink)}
1194            <Text>{runsOf(D, f.runs, t)}</Text>
1195          </Box>
1196        ))}
1197        {rowActions.length > 0 ? (
1198          <Box flexDirection="row" alignItems="center" columnGap={1}>
1199            {rowActions.map(a => (
1200              <Button key={`row-${a.id}`} label={a.label} onPress={() => on.act(a.id)} />
types/index.d.ts 159 lines
1// The status bar's state contract. Plain JSON only, and
2// self-contained: the engine ships this file to other plugins as is.
3//
4// `session` is one atom keyed by the session it describes. Readers compare its
5// sessionId to the live session and reset on a mismatch, so a /clear never
6// shows the previous session's figures. null means nothing read yet.
7//
8// `handoff` is Start fresh's pending hand-off. It deliberately lives outside
9// `session`: it is written in the old session and read in the new one, so a
10// session reset must not wipe it.
11
12export type TokenOptimizerDesktopLimit = { percentUsed: number; resetsAt: string | null }
13
14export type TokenOptimizerDesktopQuality = {
15  score: number
16  grade: string
17  drag: string | null
18  toolCalls: number | null
19  compactions: number
20  /** Epoch seconds. */
21  checkpointEpoch: number | null
22  /** Epoch seconds. */
23  sessionStartEpoch: number | null
24  /** Token Optimizer's own context fill, %. */
25  fillPct?: number | null
26}
27
28export type TokenOptimizerDesktopSavings = {
29  sessionTokens: number | null
30  last30Tokens: number | null
31  /** 30 entries, oldest first; today last. */
32  daily: number[]
33}
34
35export type TokenOptimizerDesktopSession = {
36  sessionId: string
37  /** `$.clock.now()` when these figures were gathered (ms). */
38  gatheredAt: number
39  quality: TokenOptimizerDesktopQuality | null
40  contextPercent: number | null
41  contextTokens: number | null
42  contextWindow: number | null
43  /** A smaller env ceiling invalidates full-window quality-cache fill. */
44  contextWindowReduced?: boolean
45  /** The model's own window when contextWindowReduced; null otherwise. */
46  contextModelWindow?: number | null
47  fiveHour: TokenOptimizerDesktopLimit | null
48  week: TokenOptimizerDesktopLimit | null
49  /** Current git branch; null outside a repository or on a detached HEAD. */
50  branch: string | null
51  /** Last known savings; kept while a refresh loads or times out. */
52  savings: TokenOptimizerDesktopSavings | null
53  savingsState: 'fresh' | 'stale' | 'loading' | 'unavailable'
54  /** One short reason when savings is null. */
55  savingsReason: string | null
56  /** Last main-thread request, epoch seconds (the cache clock's anchor). */
57  lastRequestEpoch: number | null
58  /** Last measured cache lifetime; null while unmeasured. */
59  cacheLifetime: '1h' | '5m' | null
60  /** The user's compact window from settings or /autocompact, as the status command resolved it. */
61  compactWindow?: number | null
62  /** When Token Optimizer last saved a checkpoint, epoch seconds. */
63  checkpointEpoch: number | null
64  /** The earlier session's checkpoint flagged as resumable for this one (epoch seconds). */
65  /** A rate limit was reported at least once this session: it runs on a Claude plan. */
66  sawLimits?: boolean
67  /** When the live session began (ms), from the engine. */
68  startedAtMs?: number | null
69  /** Main-thread tool calls and compactions the band watched itself: the row never waits on Token Optimizer's quality file. */
70  toolCallsSeen?: number
71  compactionsSeen?: number
72  /** Compactions counted in the transcript by the status command. */
73  compactions?: number | null
74  earlierCheckpoint?: { epoch: number; about: string | null } | null
75  /** The detail row under Clawd is unfolded. */
76  sheetOpen: boolean
77}
78
79export type TokenOptimizerDesktopState = TokenOptimizerDesktopSession | null
80
81/**
82 * Start fresh's hand-off, waiting for the first prompt of a session in the
83 * same project that started since it was saved, within 10 minutes.
84 */
85export type TokenOptimizerDesktopHandoff = {
86  fromSessionId: string
87  /** The project it was saved in; another project's session never touches it. */
88  cwd: string
89  checkpointPath: string
90  text: string
91  /** `$.clock.now()` when it was recorded (ms). */
92  createdAt: number
93  /** While the save is being stamped: the press time (createdAt is a far-future placeholder). */
94  pendingSince?: number
95} | null
96
97/** The cache clock's reducer state (src/clock.ts ClockState). */
98export type TokenOptimizerDesktopClock = {
99  anchor: number | null
100  lifetime: '1h' | '5m' | null
101  contextTokens: number | null
102  working: boolean
103  warming: boolean
104  lapsed: boolean
105}
106
107/** Clawd's pose reducer state (src/pose.ts PoseState). */
108export type TokenOptimizerDesktopPose = {
109  pose: 'wake' | 'idle' | 'think' | 'read' | 'type' | 'lift' | 'ask' | 'write' | 'compact' | 'done' | 'stop' | 'error' | 'cold' | 'sleep'
110  since: number
111  now: number
112  working: boolean
113  rawSub: 'think' | 'read' | 'type' | 'write' | 'lift' | null
114  rawSince: number
115  sub: 'think' | 'read' | 'type' | 'write' | 'lift' | null
116  agents: Readonly<Record<string, boolean>>
117  permissions: number
118  questions: number
119  compacting: boolean
120  cold: boolean
121  lastActivity: number
122  until: Readonly<Record<'wake' | 'done' | 'stop' | 'error', number>>
123}
124
125/** What a button is doing, the last outcome, and the Start fresh arm (src/actions.ts UiState). */
126export type TokenOptimizerDesktopUi = {
127  busy: 'clean' | 'fresh-capture' | 'fresh-clear' | 'dashboard' | null
128  busySince: number | null
129  note: string | null
130  noteUntil: number
131  freshArmedAt: number | null
132}
133
134/**
135 * The compaction or clear the buttons have running, recorded before the call
136 * and cleared when it settles, so a reload mid-call still refuses a second
137 * one. A record older than 10 minutes is treated as gone.
138 */
139export type TokenOptimizerDesktopEngineCall = {
140  kind: 'compact' | 'clear'
141  /** `$.clock.now()` when the call was recorded (ms). */
142  startedAt: number
143} | null
144
145declare module 'claude-code' {
146  interface PluginState {
147    'token-optimizer': {
148      session: TokenOptimizerDesktopState
149      handoff: TokenOptimizerDesktopHandoff
150      clock: TokenOptimizerDesktopClock | null
151      pose: TokenOptimizerDesktopPose | null
152      ui: TokenOptimizerDesktopUi | null
153      engineCall: TokenOptimizerDesktopEngineCall
154      /** Bumped by the clock tick when the visible clock changes. */
155      frame: number
156    }
157  }
158}
159
src/actions.ts 329 lines
1// The three buttons' pure parts. register.tsx owns
2// every `$` call; this file decides. Nothing here imports from 'claude-code'.
3import { tokens } from './format.ts'
4
5/** Start fresh waits this long for its second click. */
6export const FRESH_ARM_MS = 5_000
7/** A busy state ends by itself after this, so no step label outlives its work. */
8export const BUSY_TIMEOUT_MS = 120_000
9/** How long an outcome note replaces "All clear." */
10export const NOTE_MS = 8_000
11/** Keep warm's one-line fork prompt. */
12export const WARM_PROMPT = 'Reply with exactly: ok'
13/** The `$.store` key of a pending Start fresh hand-off (survives restarts). */
14export const HANDOFF_KEY = 'handoff'
15/** compact-capture reads a transcript; generous, still bounded. */
16export const CAPTURE_TIMEOUT_MS = 30_000
17/** The budget compact-capture is given (`--budget-seconds`), under CAPTURE_TIMEOUT_MS so it answers first. */
18export const CAPTURE_BUDGET_SECONDS = 25
19/** A saved hand-off joins a new session only this soon after it was saved; older ones are dropped. */
20export const HANDOFF_TTL_MS = 10 * 60_000
21/** resume-lean is a token-free read of checkpoints and the session log. */
22export const RESUME_TIMEOUT_MS = 20_000
23
24/**
25 * `measure.py dashboard` regenerates the page and opens it in the browser (whatever the OS
26 * opener is), so it can take a while on a long history. Bounded, and under the dashboard's
27 * busy timeout (see busyTimeoutMs) so the runner answers before the busy state gives up on its
28 * own. Measured cold on a real, heavy history: 80 s (a synthetic 800-session / 1.1 GB one took
29 * 38 s), so a slower disk needs room well past that.
30 */
31export const DASHBOARD_TIMEOUT_MS = 300_000
32/** How long past the runner's limit the dashboard's busy state waits before giving up on its own. */
33const DASHBOARD_BUSY_GRACE_MS = 30_000
34/**
35 * The arguments of that command. Never `--quiet`: quiet regenerates without opening anything.
36 * `--user` marks the run as a person's click: the runner cannot pass env and its stdin is not a tty,
37 * so without it measure.py reads the run as a hook and cuts a heavy rebuild off at its 20 s hook budget.
38 */
39export const DASHBOARD_ARGS = ['dashboard', '--user'] as const
40/** The band's note line while the dashboard opens. */
41export const DASHBOARD_OPENING = 'Opening the dashboard.'
42/** The note after it failed, shown for NOTE_MS. */
43export const DASHBOARD_FAILED = 'Could not open the dashboard.'
44
45export type Busy = 'clean' | 'fresh-capture' | 'fresh-clear' | 'dashboard' | null
46
47/** The band's own UI state: what a button is doing, the last outcome, the Start fresh arm. Plain JSON. */
48export type UiState = {
49  busy: Busy
50  /** When `busy` was set (ms); the timeout counts from here. */
51  busySince: number | null
52  note: string | null
53  /** The note shows until this time (ms). */
54  noteUntil: number
55  /** First Start fresh click (ms); null when disarmed. */
56  freshArmedAt: number | null
57}
58
59/** Start fresh's saved hand-off: who saved it, where, when (`$.clock.now()` ms), and the text it carries. */
60export type Handoff = {
61  fromSessionId: string
62  cwd: string
63  checkpointPath: string
64  text: string
65  createdAt: number
66  /** While the save is being stamped: createdAt is the far-future placeholder, this the press time. */
67  pendingSince?: number
68}
69
70/** A hand-off still being stamped this long after its press was cut off by a crash. */
71const PENDING_MAX_MS = 60_000
72
73export type HandoffFate = 'attach' | 'skip' | { drop: string }
74
75/**
76 * What the session `at.sessionId` in `at.cwd` does with a held hand-off.
77 * It joins a different session than the one that saved it, in the
78 * same project, that started at or after it was saved (`startedAt`, null when
79 * unknown), within 10 minutes of the save. No marker ties it to one clear, so
80 * a typed /clear, a reload or a lost start event cannot strand or steal it.
81 * Another project's hand-off is never this session's to touch; an
82 * expired one in this project is dropped (the reason ends a one-line note).
83 */
84export function handoffFate(h: Handoff, at: { sessionId: string; cwd: string; startedAt: number | null; now: number }): HandoffFate {
85  if (h.cwd !== at.cwd) return 'skip'
86  if (h.pendingSince !== undefined) {
87    // Being stamped right now; one a crash left half-saved is dropped after a minute.
88    return at.now - h.pendingSince > PENDING_MAX_MS ? { drop: 'its save never finished' } : 'skip'
89  }
90  if (at.now - h.createdAt > HANDOFF_TTL_MS) return { drop: 'it is more than 10 minutes old' }
91  if (at.sessionId === '' || at.sessionId === h.fromSessionId) return 'skip'
92  return at.startedAt !== null && at.startedAt >= h.createdAt ? 'attach' : 'skip'
93}
94
95export function initialUi(): UiState {
96  return { busy: null, busySince: null, note: null, noteUntil: 0, freshArmedAt: null }
97}
98
99export function isArmed(ui: UiState, now: number): boolean {
100  return ui.freshArmedAt !== null && now - ui.freshArmedAt < FRESH_ARM_MS
101}
102
103/**
104 * How long a busy state lasts before it ends by itself. The dashboard outlives the others: its
105 * runner is allowed DASHBOARD_TIMEOUT_MS, and the busy state must not give up before it answers.
106 */
107export function busyTimeoutMs(busy: Busy): number {
108  return busy === 'dashboard' ? DASHBOARD_TIMEOUT_MS + DASHBOARD_BUSY_GRACE_MS : BUSY_TIMEOUT_MS
109}
110
111/** The busy state as it stands at `now`: a stale one has timed out. */
112export function busyNow(ui: UiState, now: number): Busy {
113  if (ui.busy === null || ui.busySince === null) return null
114  return now - ui.busySince < busyTimeoutMs(ui.busy) ? ui.busy : null
115}
116
117/** The "Full dashboard" link is ignored while anything else is busy (a second click included). */
118export function canOpenDashboard(ui: UiState, now: number): boolean {
119  return busyNow(ui, now) === null
120}
121
122/** measure.py prints this and still exits 0 when the OS opener failed. */
123const BROWSER_FAILED = 'Could not auto-open browser'
124
125/** The dashboard run failed: it threw or timed out (`null`), exited non-zero, or could not open the browser. */
126export function dashboardFailed(result: { exitCode: number; stdout: string } | null): boolean {
127  return result === null || result.exitCode !== 0 || (result.stdout ?? '').includes(BROWSER_FAILED)
128}
129
130/** What the dashboard link's own status line says: while it opens, and after it failed; null otherwise. */
131export function dashboardStatus(busy: string | null, note: string | null): string | null {
132  if (busy === 'dashboard') return DASHBOARD_OPENING
133  return note === DASHBOARD_FAILED ? DASHBOARD_FAILED : null
134}
135
136export function withBusy(ui: UiState, busy: Busy, now: number): UiState {
137  return { ...ui, busy, busySince: busy === null ? null : now, freshArmedAt: null }
138}
139
140export function withNote(ui: UiState, note: string, now: number): UiState {
141  return { ...ui, note, noteUntil: now + NOTE_MS }
142}
143
144export function noteNow(ui: UiState, now: number): string | null {
145  return ui.note !== null && now < ui.noteUntil ? ui.note : null
146}
147
148/** Clean up's note when its /compact left no sign that a compaction happened, and gave no reason. */
149export const CLEAN_UNCONFIRMED = 'Clean up could not confirm a compaction.'
150
151/**
152 * What the band saw around Clean up's /compact. `landed`: its own
153 * `session.compact` hook watched a compaction stand during the call (the engine
154 * may leave a plugin's hooks out of a dispatch its own code raised, so a miss
155 * proves nothing). `tokensBefore`/`tokensAfter`: `$.session.usage().context.tokens`
156 * either side of the call, which the engine leaves absent "until the first
157 * response of the live window: a fresh session, or one just compacted"
158 * (SessionContextUsage). `said`: the command's reply, any language.
159 */
160export type CompactEvidence = {
161  landed: boolean
162  tokensBefore: number | null
163  tokensAfter: number | null
164  said: string
165}
166
167/**
168 * Clean up's outcome from evidence, never from the reply's wording (#207):
169 * success needs a compaction the band watched land, or the live window reset by
170 * it (tokens there before the call, gone after). Anything else is a skip: the
171 * reply names why when there is one ("Not enough messages to compact.", or a
172 * hook's veto, in whatever language), and an empty reply cannot confirm anything.
173 */
174export function cleanUpOutcome(ev: CompactEvidence): { ok: true } | { ok: false; line: string } {
175  const windowReset = ev.tokensBefore !== null && ev.tokensBefore > 0 && ev.tokensAfter === null
176  if (ev.landed || windowReset) return { ok: true }
177  const said = ev.said.trim().split('\n')[0]?.trim() ?? ''
178  if (said === '') return { ok: false, line: CLEAN_UNCONFIRMED }
179  return { ok: false, line: `Clean up skipped: ${said.replace(/\.$/, '')}.` }
180}
181
182/** The live window's tokens from a `$.session.usage()` reading, null when the engine has none. */
183export function liveTokens(usage: unknown): number | null {
184  if (!usage || typeof usage !== 'object') return null
185  const context = (usage as Json).context
186  if (!context || typeof context !== 'object') return null
187  const t = (context as Json).tokens
188  return typeof t === 'number' && Number.isFinite(t) ? t : null
189}
190
191/** The path compact-capture printed (`[Token Optimizer] Checkpoint saved: <path>`), or null. */
192export function checkpointPathFrom(stdout: string): string | null {
193  const match = /Checkpoint saved: (.+?)\s*$/m.exec(stdout)
194  return match?.[1] ? match[1] : null
195}
196
197/** compact_capture writes this note when it found no transcript to read. */
198export function isStubCheckpoint(contents: string): boolean {
199  if (!contents.includes('No transcript data available')) return false
200  // Empty means the phrase with almost nothing else; a real checkpoint that quotes it is not.
201  const rest = contents.replace('No transcript data available', '').replace(/^#.*$/gm, '').replace(/\s+/g, '')
202  return rest.length < STUB_MAX_CHARS
203}
204
205/** A checkpoint with less than this much besides its headings and the empty notice saved nothing. */
206const STUB_MAX_CHARS = 200
207
208const POINTER = /^.*Cross-session checkpoint.*$/
209
210/**
211 * Removes Token Optimizer's "Cross-session checkpoint" pointer lines from a
212 * SessionStart's context: after Start fresh the held hand-off replaces it.
213 * Every other line stays; an entry left empty is dropped.
214 */
215export function stripCrossSessionPointer(entries: readonly string[] | undefined): string[] | undefined {
216  if (!entries) return undefined
217  const out: string[] = []
218  for (const entry of entries) {
219    const kept = entry.split('\n').filter(line => !POINTER.test(line)).join('\n')
220    if (kept.trim() !== '') out.push(kept)
221  }
222  return out
223}
224
225type Json = Record<string, unknown>
226const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
227
228/**
229 * The lifetime one request's cache writes used, when its usage carries the
230 * 1h/5m split (transcript rows do; `TurnUsage` may not). Null when unknown.
231 */
232export function lifetimeFromUsage(usage: unknown): '1h' | '5m' | null {
233  if (!usage || typeof usage !== 'object') return null
234  const split = (usage as Json).cache_creation
235  if (!split || typeof split !== 'object') return null
236  if (num((split as Json).ephemeral_1h_input_tokens) > 0) return '1h'
237  if (num((split as Json).ephemeral_5m_input_tokens) > 0) return '5m'
238  return null
239}
240
241/** Prompt tokens one request carried: what the next request re-reads (per request, never the turn's sum). */
242export function requestContextTokens(usage: unknown): number {
243  if (!usage || typeof usage !== 'object') return 0
244  const u = usage as Json
245  return num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens)
246}
247
248export type WarmOutcome =
249  | { ok: true; lapsed: boolean; contextTokens: number; cacheRead?: number; lifetimeS?: number }
250  | { ok: false; reason: string }
251
252/** One line for the Keep warm outcome; a lapsed cache names what the warm-up cost. */
253export function warmToast(o: WarmOutcome): string {
254  if (!o.ok) return `Keep warm did not run: ${o.reason}.`
255  if (o.lapsed) return `The cache had already dropped, so the warm-up re-read ${tokens(o.contextTokens)} tokens at full price.`
256  // The receipt: what the warm-up read from the cache, and that the clock restarted.
257  const read = o.cacheRead && o.cacheRead > 0 ? `: re-read ${tokens(o.cacheRead)} tokens from the cache at a tenth of the price` : ''
258  const clock = o.lifetimeS ? ` The clock is back to ${Math.round(o.lifetimeS / 60)}m.` : ''
259  return `Cache kept warm${read}.${clock}`
260}
261
262const TYPED = new Set(['composer', 'sdk', 'bridge', 'unclassified'])
263
264/** The hand-off joins a prompt the person sent, never a notification, peer or automatic one. */
265export function attachesHandoff(originKind: string | undefined): boolean {
266  return originKind === undefined || TYPED.has(originKind)
267}
268
269/** What Start fresh needs from the host: measure.py by arguments (stdin optional), and a file read. */
270export type HandoffPort = {
271  run: (args: string[], stdin?: string) => Promise<{ exitCode: number; stdout: string }>
272  read: (path: string) => Promise<string>
273}
274
275export type HandoffResult = { ok: true; handoff: Handoff } | { ok: false; reason: string }
276
277/**
278 * Why Start fresh stopped when no launcher was a real Python 3 (#261): on
279 * Windows that is usually the Store's python shortcuts standing in for one.
280 */
281export const NO_PYTHON_REASON = 'no working Python 3 was found (the Microsoft Store python shortcuts are not one; install Python 3 from python.org)'
282
283/** The host's runner rejects with an error of this name when no Python 3 starts. */
284function isNoPython(error: unknown): boolean {
285  return error instanceof Error && error.name === 'PythonNotFoundError'
286}
287
288/**
289 * Start fresh up to the clear: save a checkpoint, check it is real,
290 * build the lean resume text. Any failure returns a one-line reason and
291 * nothing is cleared.
292 */
293export async function prepareHandoff(
294  port: HandoffPort,
295  input: { sessionId: string; transcriptPath: string | null; cwd: string; now: number },
296): Promise<HandoffResult> {
297  const fail = (reason: string): HandoffResult => ({ ok: false, reason })
298  const stdin = JSON.stringify(input.transcriptPath ? { session_id: input.sessionId, transcript_path: input.transcriptPath } : { session_id: input.sessionId })
299
300  let captured: { exitCode: number; stdout: string }
301  try {
302    captured = await port.run(['compact-capture', '--trigger', 'start-fresh', '--budget-seconds', String(CAPTURE_BUDGET_SECONDS)], stdin)
303  } catch (error) {
304    return fail(isNoPython(error) ? NO_PYTHON_REASON : 'the checkpoint could not be saved')
305  }
306  if (captured.exitCode !== 0) return fail('the checkpoint could not be saved')
307  const path = checkpointPathFrom(captured.stdout)
308  if (!path) return fail('the checkpoint could not be saved')
309
310  let contents: string
311  try {
312    contents = await port.read(path)
313  } catch {
314    return fail('the saved checkpoint could not be read')
315  }
316  if (isStubCheckpoint(contents)) return fail('the checkpoint came out empty')
317
318  let lean: { exitCode: number; stdout: string }
319  try {
320    lean = await port.run(['resume-lean', input.sessionId, '--print'])
321  } catch {
322    return fail('the hand-off text could not be built')
323  }
324  const text = lean.exitCode === 0 ? lean.stdout.trim() : ''
325  if (!text) return fail('the hand-off text came out empty')
326
327  return { ok: true, handoff: { fromSessionId: input.sessionId, cwd: input.cwd, checkpointPath: path, text, createdAt: input.now } }
328}
329
src/clock.ts 124 lines
1// The cache clock as a pure state machine. The anchor is the last
2// main-thread request; the deadline is anchor plus lifetime. Time is passed
3// in; `canKeepWarm` is the single guard every Keep warm caller uses.
4import type { CacheState, CacheView } from './contracts.ts'
5
6/** Keep warm is refused this close to expiry. Agent default (plan Assumptions). */
7export const KEEP_WARM_MARGIN_MS = 15_000
8/** Lifetime the warning and cold rules use until a measurement lands. */
9const UNMEASURED_RULE_SECONDS = 300
10/** A warm-up that read less than this share of the context found the cache lapsed. */
11const LAPSED_READ_SHARE = 0.5
12/** Below this many tokens read, a warm-up of unknown context size found the cache gone. */
13const LAPSED_FLOOR_TOKENS = 1024
14
15export type Lifetime = '1h' | '5m'
16
17export type ClockEvent =
18  | { type: 'request-done'; at: number; lifetime: Lifetime | null; contextTokens: number }
19  | { type: 'working-changed'; working: boolean }
20  | { type: 'warm-start' }
21  | { type: 'warm-done'; at: number; cacheReadTokens: number; contextTokens: number }
22  | { type: 'warm-failed' }
23  | { type: 'clear' }
24  | { type: 'lifetime-measured'; lifetime: Lifetime }
25  | { type: 'tick'; now: number }
26
27export type ClockState = {
28  /** Time of the last main-thread request (ms); null until one lands. */
29  anchor: number | null
30  /** Measured lifetime; null while unmeasured. */
31  lifetime: Lifetime | null
32  contextTokens: number | null
33  working: boolean
34  warming: boolean
35  /** A warm-up found the cache lapsed; cold until a real request lands. */
36  lapsed: boolean
37}
38
39export function initialClock(): ClockState {
40  return { anchor: null, lifetime: null, contextTokens: null, working: false, warming: false, lapsed: false }
41}
42
43const seconds = (l: Lifetime): number => (l === '1h' ? 3600 : 300)
44
45/**
46 * One step. `now` matters only for `warm-start`, which re-checks the guard at
47 * press time because a button handle can outlive the drawing that showed it.
48 */
49export function reduceClock(state: ClockState, event: ClockEvent, now?: number): ClockState {
50  switch (event.type) {
51    case 'request-done':
52      // An older request than the anchor says nothing about the cache now.
53      if (state.anchor !== null && event.at < state.anchor) return state
54      return {
55        ...state,
56        anchor: event.at,
57        lifetime: event.lifetime ?? state.lifetime,
58        contextTokens: event.contextTokens,
59        lapsed: false,
60      }
61    case 'working-changed':
62      return { ...state, working: event.working }
63    case 'warm-start':
64      // No press time given: refuse rather than guess.
65      return now !== undefined && canKeepWarm(state, now) ? { ...state, warming: true } : state
66    case 'warm-done':
67      // With no known context size, a warm-up that read (almost) nothing from the cache found it gone.
68      if (event.contextTokens > 0 ? event.cacheReadTokens < LAPSED_READ_SHARE * event.contextTokens : event.cacheReadTokens < LAPSED_FLOOR_TOKENS) {
69        return { ...state, warming: false, lapsed: true, contextTokens: event.contextTokens }
70      }
71      return {
72        ...state,
73        warming: false,
74        lapsed: false,
75        anchor: Math.max(state.anchor ?? event.at, event.at),
76        contextTokens: event.contextTokens,
77      }
78    case 'warm-failed':
79      return { ...state, warming: false }
80    case 'clear':
81      // A new session: re-measure before trusting a lifetime again.
82      return { ...initialClock(), working: state.working }
83    case 'lifetime-measured':
84      return { ...state, lifetime: event.lifetime }
85    case 'tick':
86      return state
87  }
88}
89
90/** The single Keep warm guard. */
91export function canKeepWarm(state: ClockState, now: number): boolean {
92  if (state.working || state.warming || state.lapsed) return false
93  if (state.anchor === null || state.lifetime === null) return false
94  const deadline = state.anchor + seconds(state.lifetime) * 1000
95  return now < deadline - KEEP_WARM_MARGIN_MS
96}
97
98/**
99 * The clock as the band shows it. While unmeasured, the countdown runs against
100 * the plan default (1h on Claude plans, 5m on the API) but warning and cold use
101 * five minutes, so a lapsed cache is never shown as warm.
102 */
103export function view(state: ClockState, now: number, planDefault: 3600 | 300): CacheView {
104  const measured = state.lifetime !== null
105  const lifetime = state.lifetime !== null ? seconds(state.lifetime) : planDefault
106  const base = { lifetime, measured, tokensAtStake: state.contextTokens }
107
108  if (state.working) return { ...base, state: 'refreshing', secondsLeft: lifetime }
109  if (state.anchor === null) return { ...base, state: 'unknown', secondsLeft: null, tokensAtStake: null }
110
111  const left = Math.max(0, Math.ceil((state.anchor + lifetime * 1000 - now) / 1000))
112  if (state.warming) return { ...base, state: 'warming', secondsLeft: left }
113  if (state.lapsed) return { ...base, state: 'cold', secondsLeft: 0 }
114
115  const rule = measured ? lifetime : UNMEASURED_RULE_SECONDS
116  const window = rule >= 3600 ? 300 : 60
117  const ruleDeadline = state.anchor + rule * 1000
118  let cache: CacheState
119  if (now >= ruleDeadline) cache = 'cold'
120  else if (now >= ruleDeadline - window * 1000) cache = 'warning'
121  else cache = 'warm'
122  return { ...base, state: cache, secondsLeft: cache === 'cold' ? 0 : left }
123}
124
src/clawd.ts 280 lines
1// Clawd, drawn on an 18 x 14.2 pixel grid, one SVG document per pose.
2//
3// The desktop draws an interactive Svg in a sandboxed frame where SMIL plays
4// but page CSS never reaches, so every loop is an <animate>/<animateTransform>
5// and every colour is inlined from the palette. With `animate` off the same
6// markup is emitted without any animation element: the pose's still frame.
7
8import type { Mood, Pose } from './contracts.ts'
9
10export type Palette = {
11  skin: string
12  eye: string
13  blush: string
14  ink: string
15  laptop: string
16  spark: string
17  card: string
18  bad: string
19  cold: string
20  ground: string
21}
22
23export const LIGHT: Palette = {
24  skin: '#d97757',
25  eye: '#2a1a12',
26  blush: '#f4a58a',
27  ink: '#1f1e1d',
28  laptop: '#3d3b37',
29  spark: '#e9a820',
30  card: '#ffffff',
31  bad: '#d6453d',
32  cold: '#4f8fd0',
33  ground: '#1f1e1d',
34}
35
36export const DARK: Palette = {
37  skin: '#e08a6c',
38  eye: '#1b100b',
39  blush: '#f7b9a2',
40  ink: '#f3f1ea',
41  laptop: '#d8d4c8',
42  spark: '#f5c451',
43  card: '#3a3a37',
44  bad: '#f0685f',
45  cold: '#7db4ee',
46  ground: '#f3f1ea',
47}
48
49/** Where Clawd looks while the pointer is on the band: over at it. */
50export type Gaze = 'right'
51
52/** Eye offsets per gaze, in the picture's own units (the face is 9 wide). */
53export const GAZE: Record<Gaze, [number, number]> = {
54  right: [1.5, 0],
55}
56
57export type ClawdOptions = {
58  animate: boolean
59  palette: Palette
60  /** A watching Clawd's steady look toward the pointer; no glance, no fade in. */
61  gaze?: Gaze
62  /** Fade in when drawn (a new pose); off for the gaze pictures stacked over him. */
63  fadeIn?: boolean
64}
65
66const ALT: Record<Pose, string> = {
67  wake: 'Clawd: waking up',
68  idle: 'Clawd: watching',
69  think: 'Clawd: thinking',
70  read: 'Clawd: reading',
71  type: 'Clawd: typing',
72  lift: 'Clawd: heavy lifting',
73  ask: 'Clawd: needs you',
74  write: 'Clawd: writing',
75  compact: 'Clawd: compacting',
76  done: 'Clawd: done',
77  stop: 'Clawd: stopped',
78  error: 'Clawd: dizzy',
79  cold: 'Clawd: cold',
80  sleep: 'Clawd: napping',
81}
82
83export function clawdAlt(pose: Pose): string {
84  return ALT[pose]
85}
86
87// The CSS design used ease-in-out; SMIL takes it as a spline per segment.
88const EASE = '0.42 0 0.58 1'
89
90type Loop = { dur: number; begin?: number; ease?: boolean; keyTimes?: string }
91
92function splines(values: string, ease: boolean): string {
93  if (!ease) return ''
94  const segments = values.split(';').length - 1
95  return ` calcMode="spline" keySplines="${Array(segments).fill(EASE).join(';')}"`
96}
97
98function timing(o: Loop, values: string): string {
99  const begin = o.begin ? ` begin="${o.begin}s"` : ''
100  const times = o.keyTimes ? ` keyTimes="${o.keyTimes}"` : ''
101  return ` dur="${o.dur}s" repeatCount="indefinite"${begin}${times}${splines(values, o.ease ?? true)}`
102}
103
104/** Builds SMIL loops, or nothing when the still frame is wanted. */
105function smil(animate: boolean) {
106  return {
107    attr(name: string, values: string, o: Loop): string {
108      return animate ? `<animate attributeName="${name}" values="${values}"${timing(o, values)}/>` : ''
109    },
110    move(type: 'translate' | 'rotate' | 'scale', values: string, o: Loop): string {
111      return animate ? `<animateTransform attributeName="transform" type="${type}" values="${values}"${timing(o, values)} additive="sum"/>` : ''
112    },
113  }
114}
115
116/** Wraps `inner` so a scale animation pivots on (cx, cy) instead of the origin. */
117function pivot(cx: number, cy: number, anim: string, inner: string): string {
118  if (!anim) return inner
119  return `<g transform="translate(${cx} ${cy})"><g>${anim}<g transform="translate(${-cx} ${-cy})">${inner}</g></g></g>`
120}
121
122function rect(x: number, y: number, w: number, h: number, fill: string, extra = ''): string {
123  return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${fill}"${extra}/>`
124}
125
126const BODY = 'M4 4H13V9H12.5V11H11.5V9H10.5V11H9.5V9H7.5V11H6.5V9H5.5V11H4.5V9H4Z'
127
128/** Seconds a new pose takes to fade in. */
129export const FADE_IN_S = 0.35
130
131export function clawdSvg(pose: Pose, mood: Mood, opts: ClawdOptions): string {
132  const p = opts.palette
133  const a = smil(opts.animate)
134  const stroke = (color: string, width: number) => ` fill="none" stroke="${color}" stroke-width="${width}" stroke-linecap="round" stroke-linejoin="round"`
135
136  // Eyes.
137  const eyeH = mood === 'calm' ? 1.6 : 2
138  const openEyes = pivot(8.5, 6.2, a.move('scale', '1 1;1 1;1 0.1;1 1', { dur: 5.2, keyTimes: '0;0.93;0.96;1', ease: false }),
139    rect(6, 5.2, 1, eyeH, p.eye) + rect(10, 5.2, 1, eyeH, p.eye) +
140    rect(6, 5.2, 0.4, 0.4, '#ffffff', ' opacity="0.9"') + rect(10, 5.2, 0.4, 0.4, '#ffffff', ' opacity="0.9"'))
141  const smile = (d: string) => `<path d="${d}"${stroke(p.eye, 0.55)}/>`
142  const eyesFor: Partial<Record<Pose, string>> = {
143    done: smile('M5.9 6.5L6.5 5.6L7.1 6.5') + smile('M9.9 6.5L10.5 5.6L11.1 6.5'),
144    lift: rect(5.8, 5.9, 1.4, 0.6, p.eye) + rect(9.8, 5.9, 1.4, 0.6, p.eye),
145    compact: smile('M5.8 5.6l1.2.6-1.2.6M11.2 5.6l-1.2.6 1.2.6'),
146    sleep: smile('M5.8 6.3h1.4M9.8 6.3h1.4'),
147    wake: rect(6, 5.9, 1, 0.8, p.eye) + rect(10, 5.9, 1, 0.8, p.eye),
148    error: smile('M6.5 6.1a.45.45 0 1 1 .45.45a.9.9 0 1 1-.9-.9M10.5 6.1a.45.45 0 1 1 .45.45a.9.9 0 1 1-.9-.9'),
149    stop: rect(5.8, 5, 1.3, 2.3, p.eye) + rect(9.8, 5, 1.3, 2.3, p.eye) +
150      rect(5.8, 5, 0.5, 0.5, '#ffffff', ' opacity="0.9"') + rect(9.8, 5, 0.5, 0.5, '#ffffff', ' opacity="0.9"'),
151  }
152  const look = pose === 'think' ? ' transform="translate(0.5 -0.45)"' : pose === 'write' ? ' transform="translate(0.2 0.5)"' : ''
153  // Watching with no pointer to follow: centred eyes that glance left, then right, about every 7 s.
154  const gazeAt = opts.gaze ? GAZE[opts.gaze] : null
155  const scan = gazeAt ? '' : pose === 'type'
156    ? a.move('translate', '-0.5 0.55;0.5 0.55;-0.5 0.55', { dur: 2.6 })
157    : pose === 'idle'
158      ? a.move('translate', '0 0;0 0;-0.6 0;-0.6 0;0.6 0;0.6 0;0 0;0 0', { dur: 7, keyTimes: '0;0.7;0.74;0.8;0.85;0.91;0.95;1' })
159      : ''
160  const eyes = `<g${gazeAt ? ` transform="translate(${gazeAt[0]} ${gazeAt[1]})"` : look}>${scan}${eyesFor[pose] ?? openEyes}</g>`
161
162  // Arms.
163  const arm = (side: 'l' | 'r', y: number, h = 1.2, anim = '', x?: number, w = 1.3) =>
164    `<rect x="${x ?? (side === 'l' ? 2.9 : 12.8)}" y="${y}" width="${w}" height="${h}" fill="${p.skin}">${anim}</rect>`
165  const key = (begin: number) => a.move('translate', '0 0;0 0.9;0 0', { dur: 0.26, begin, ease: false })
166  const reach = (side: 'l' | 'r') => pivot(side === 'l' ? 3.55 : 13.45, 7.2,
167    a.move('scale', '1 1;1 1;1 1.75;1 1.75;1 1', { dur: 1.7, keyTimes: '0;0.12;0.45;0.62;1' }), arm(side, 3.5, 3.7))
168  const sign = `<rect x="12.6" y="-1.5" width="3.9" height="2.9" rx="0.35" fill="${p.card}" stroke="${p.ink}" stroke-width="0.25"/>` +
169    `<path d="M13.95 -0.6q.6-.75 1.25 0q0 .55-.62.8v.35"${stroke(p.ink, 0.4)}/><circle cx="14.58" cy="1.05" r="0.17" fill="${p.ink}"/>`
170  const waveArm = `<g transform="translate(13.45 5.2)"><g>${a.move('rotate', '-8;8;-8', { dur: 1.8 })}<g transform="translate(-13.45 -5.2)">${arm('r', 1.8, 3.4)}${sign}</g></g></g>`
171  const armsFor: Partial<Record<Pose, string>> = {
172    think: arm('l', 6) + arm('r', 4.7),
173    type: arm('l', 7, 1.2, key(0)) + arm('r', 7, 1.2, key(0.13)),
174    done: arm('l', 4.3) + arm('r', 4.3),
175    lift: reach('l') + reach('r'),
176    write: arm('l', 7.6) + arm('r', 7.6),
177    read: arm('l', 6) + arm('r', 7.2),
178    stop: arm('l', 2.4, 2.8) + arm('r', 2.4, 2.8),
179    wake: arm('l', 1.6, 3.6) + arm('r', 1.6, 3.6),
180    compact: arm('l', 4.6) + arm('r', 4.6),
181    ask: arm('l', 6) + waveArm,
182  }
183  const arms = armsFor[pose] ?? arm('l', 6) + arm('r', 6)
184
185  // What Clawd holds.
186  const hold = pose === 'lift'
187    ? `<g>${a.move('translate', '0 0;0 0;0 -2.7;0 -2.7;0 0', { dur: 1.7, keyTimes: '0;0.12;0.45;0.62;1' })}` +
188      rect(0.6, 3.1, 15.8, 0.55, '#6b6861', ' rx="0.2"') +
189      rect(0.9, 2, 0.9, 2.75, p.ink, ' rx="0.25"') + rect(1.95, 2.45, 0.6, 1.85, p.ink, ' rx="0.2"') +
190      rect(15.2, 2, 0.9, 2.75, p.ink, ' rx="0.25"') + rect(14.45, 2.45, 0.6, 1.85, p.ink, ' rx="0.2"') + '</g>'
191    : ''
192
193  // The sweat drop shows when the session is in trouble or Clawd is straining.
194  const sweating = mood !== 'calm' || pose === 'lift'
195  const drop = sweating
196    ? `<path d="M13.4 2.7c.5.7.7 1 .7 1.3a.7.7 0 0 1-1.4 0c0-.3.2-.6.7-1.3z" fill="#5aa9e6">` +
197      `${a.move('translate', '0 0;0 2.4', { dur: 1.8, ease: false })}${a.attr('opacity', '0;1;0', { dur: 1.8, keyTimes: '0;0.2;1', ease: false })}</path>`
198    : ''
199
200  // The whole body's motion, pivoting on the feet.
201  const rigMotion: Partial<Record<Pose, string>> = {
202    idle: mood === 'panic'
203      ? a.move('translate', '0 0;-0.3 0;0.3 0;0 0', { dur: 0.28, ease: false })
204      : a.move('translate', '0 0;0 -0.4;0 0', { dur: 2.6 }),
205    think: a.move('rotate', '-1.4 8.5 11;1.4 8.5 11;-1.4 8.5 11', { dur: 3.6 }),
206    type: a.move('translate', '0 0;0 0.3;0 0', { dur: 0.22, ease: false }),
207    lift: pivotScale('1 0.95;1 0.95;1 1.03;1 1.03;1 0.95', 1.7, '0;0.12;0.45;0.62;1'),
208    done: a.move('translate', '0 0;0 -1.9;0 0;0 -0.7;0 0;0 0', { dur: 1.5, keyTimes: '0;0.22;0.44;0.58;0.72;1' }),
209    ask: a.move('translate', '0 0;0 -0.4;0 0', { dur: 1.2 }),
210    write: a.move('translate', '0 0;0 0.3;0 0', { dur: 0.3, ease: false }),
211    read: a.move('rotate', '-1.4 8.5 11;1.4 8.5 11;-1.4 8.5 11', { dur: 4 }),
212    compact: pivotScale('1 1;1.05 0.84;1 1', 1.3),
213    stop: a.move('translate', '0 0;0 -1.2;0 0;0 0', { dur: 1.6, keyTimes: '0;0.08;0.2;1' }),
214    error: a.move('rotate', '-3 8.5 11;3 8.5 11;-3 8.5 11', { dur: 1.2 }),
215    cold: a.move('translate', '0 0;-0.3 0;0.3 0;0 0', { dur: 0.18, ease: false }),
216    sleep: pivotScale('1 1;1 1.03;1 1', 3),
217    wake: pivotScale('1 1;1 1.07;1 1.07;1 1', 2.4, '0;0.35;0.55;1'),
218  }
219  function pivotScale(values: string, dur: number, keyTimes?: string): string {
220    // Scaling pivots on the feet: shift the origin down, scale, shift back.
221    return opts.animate
222      ? `<animateTransform attributeName="transform" type="translate" values="8.5 11" dur="${dur}s" repeatCount="indefinite" additive="sum"/>` +
223        a.move('scale', values, { dur, keyTimes }) +
224        `<animateTransform attributeName="transform" type="translate" values="-8.5 -11" dur="${dur}s" repeatCount="indefinite" additive="sum"/>`
225      : ''
226  }
227
228  // Props in front of the body.
229  const sparkle = (d: string, begin: number) =>
230    `<path d="${d}" fill="${p.spark}">${a.attr('opacity', '0.2;1;0.2', { dur: 1.1, begin })}</path>`
231  const sparks = sparkle('M1.6 1.4L2 2.5L3.1 2.9L2 3.3L1.6 4.4L1.2 3.3L0.1 2.9L1.2 2.5Z', 0) +
232    sparkle('M15.6 0L15.9 0.9L16.8 1.2L15.9 1.5L15.6 2.4L15.3 1.5L14.4 1.2L15.3 0.9Z', 0.35)
233  const dot = (cx: number, cy: number, r: number, begin: number) =>
234    `<circle cx="${cx}" cy="${cy}" r="${r}" fill="#6b6861">${a.attr('r', `${r * 0.55};${r};${r * 0.55}`, { dur: 1.5, begin })}${a.attr('opacity', '0.5;1;0.5', { dur: 1.5, begin })}</circle>`
235  const codeLine = (x: number, y: number, w: number, begin: number) =>
236    `<rect x="${x}" y="${y}" width="${w}" height="0.36" rx="0.18" fill="${p.ink}" opacity="${opts.animate ? 0 : 0.6}">` +
237    `${a.move('translate', '0 0;0 -3.4', { dur: 1.5, begin, ease: false })}${a.attr('opacity', '0;0.9;0', { dur: 1.5, begin, keyTimes: '0;0.25;1', ease: false })}</rect>`
238  const inkLine = (d: string, begin: number) =>
239    `<path d="${d}"${stroke(p.ink, 0.3)} stroke-dasharray="6" stroke-dashoffset="${opts.animate ? 6 : 0}">` +
240    `${a.attr('stroke-dashoffset', '6;0;0', { dur: 1.8, begin, keyTimes: '0;0.6;1', ease: false })}</path>`
241  const flake = (d: string, begin: number) =>
242    `<path d="${d}"${stroke(p.cold, 0.3)}>${a.move('translate', '0 -1;0 5', { dur: 2, begin, ease: false })}${a.attr('opacity', '0;1;0', { dur: 2, begin, keyTimes: '0;0.2;1', ease: false })}</path>`
243  const zz = (d: string, begin: number) =>
244    `<path d="${d}"${stroke(p.ink, 0.3)} opacity="${opts.animate ? 0 : 1}">${a.move('translate', '0 0;0.8 -2', { dur: 2.7, begin })}${a.attr('opacity', '0;1;0', { dur: 2.7, begin, keyTimes: '0;0.25;1' })}</path>`
245  const frontFor: Partial<Record<Pose, string>> = {
246    think: dot(14.4, 3.4, 0.38, 0) + dot(15.5, 2.2, 0.55, 0.2) + dot(16.9, 0.7, 0.8, 0.4),
247    type: rect(5.1, 7.5, 6.8, 3.5, p.laptop, ' rx="0.5"') + `<circle cx="8.5" cy="9.2" r="0.48" fill="${p.skin}"/>` +
248      rect(4.2, 10.75, 8.6, 0.6, p.laptop, ' rx="0.3"') + codeLine(14.6, 6, 1.7, 0) + codeLine(14.9, 7, 1.1, 0.5) + codeLine(14.4, 8, 1.4, 1),
249    done: sparks,
250    write: rect(4.4, 8.9, 8.2, 2.5, p.card, ` rx="0.3" stroke="${p.ink}" stroke-width="0.2"`) +
251      inkLine('M5.2 9.75h5.4', 0) + inkLine('M5.2 10.6h3.6', 0.9) +
252      `<g>${a.move('translate', '-4 0;0 0;-4 0', { dur: 1.8 })}<rect x="10.9" y="7.3" width="0.55" height="2.3" rx="0.2" fill="${p.spark}" transform="rotate(28 11.2 8.5)"/></g>`,
253    read: `<g>${a.move('translate', '-4 0;0.3 0;-4 0', { dur: 4.4 })}<circle cx="10.5" cy="6.1" r="1.75" fill="#ffffff" fill-opacity="0.35" stroke="${p.ink}" stroke-width="0.35"/>` +
254      `<path d="M11.8 7.4L13.5 9.1"${stroke(p.ink, 0.6)}/></g>`,
255    compact: `<g>${a.move('translate', '0 0;0 1.1;0 0', { dur: 1.3 })}<path d="M6 -1.2v2.1M5.25 0.25l.75.75.75-.75"${stroke(p.ink, 0.4)}/><path d="M11 -1.2v2.1M10.25 0.25l.75.75.75-.75"${stroke(p.ink, 0.4)}/></g>`,
256    stop: rect(8.15, -0.9, 0.75, 2.1, p.bad, ' rx="0.2"') + rect(8.15, 1.6, 0.75, 0.7, p.bad, ' rx="0.2"'),
257    error: `<g>${a.move('rotate', '0 8.5 2.6;360 8.5 2.6', { dur: 1.6, ease: false })}` +
258      ['M4.6 2.2', 'M12.4 3.1', 'M8.5 0.2'].map(m => `<path d="${m}l.25.6.6.25-.6.25-.25.6-.25-.6-.6-.25.6-.25Z" fill="${p.spark}"/>`).join('') + '</g>',
259    cold: flake('M2 1v1.4M1.3 1.7h1.4', 0) + flake('M15.4 0v1.4M14.7 0.7h1.4', 0.7) + flake('M12 -1v1.4M11.3 -0.3h1.4', 1.3),
260    sleep: zz('M13.6 2.6h1.1l-1.1 1.1h1.1', 0) + zz('M14.9 0.9h1.4l-1.4 1.4h1.4', 0.9) + zz('M16.4 -1h1.6l-1.6 1.6h1.6', 1.8),
261  }
262
263  const glow = pose === 'type'
264    ? `<rect x="4" y="6.4" width="9" height="1.1" fill="#ffffff" opacity="0.16">${a.attr('opacity', '0.08;0.22;0.08', { dur: 2.2 })}</rect>`
265    : ''
266  const frost = pose === 'cold' ? `<path d="M4 4H13V9H4Z" fill="${p.cold}" opacity="0.22"/>` : ''
267
268  const body = `<path d="${BODY}" fill="${p.skin}"/>` +
269    rect(4, 8.2, 9, 0.8, '#000000', ' opacity="0.13"') + rect(4.6, 4.4, 2.4, 0.45, '#ffffff', ' opacity="0.26"') +
270    rect(4.9, 7.25, 1.1, 0.5, p.blush, ' opacity="0.85"') + rect(11, 7.25, 1.1, 0.5, p.blush, ' opacity="0.85"')
271
272  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -1.6 18 14.2" role="img" aria-label="${ALT[pose]}">` +
273    `<title>${ALT[pose]}</title>` +
274    // A new pose fades in over the old one the band keeps beneath it, so a switch never cuts.
275    (opts.animate && opts.fadeIn !== false ? `<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="0s" dur="${FADE_IN_S}s" fill="freeze"/>` : '<g>') +
276    `<ellipse cx="8.5" cy="11.2" rx="5.2" ry="0.5" fill="${p.ground}" opacity="0.1"/>` +
277    `<g>${rigMotion[pose] ?? ''}${arms}${body}${glow}${frost}${eyes}${drop}${hold}</g>` +
278    (frontFor[pose] ?? '') + '</g></svg>'
279}
280
src/contracts.ts 97 lines
1// Shapes shared by the pure modules. Nothing here imports from 'claude-code':
2// register.tsx maps the engine's events and values onto these.
3
4/** Clawd's 14 moments, one pose each. */
5export type Pose =
6  | 'wake'
7  | 'idle'
8  | 'think'
9  | 'read'
10  | 'type'
11  | 'lift'
12  | 'ask'
13  | 'write'
14  | 'compact'
15  | 'done'
16  | 'stop'
17  | 'error'
18  | 'cold'
19  | 'sleep'
20
21/** How healthy the session looks; drives Clawd's eyes and sweat drop. */
22export type Mood = 'calm' | 'worried' | 'panic'
23
24/** Where the cache clock stands. */
25export type CacheState = 'unknown' | 'refreshing' | 'warm' | 'warning' | 'cold' | 'warming'
26
27/** The cache clock as the view model reads it. */
28export type CacheView = {
29  state: CacheState
30  /** Whole seconds until the cache lapses; null when unknown. */
31  secondsLeft: number | null
32  /** Lifetime in seconds the clock is counting against (3600 or 300). */
33  lifetime: number
34  /** True when the lifetime came from a measurement, not the plan default. */
35  measured: boolean
36  /** Tokens the next message would re-read at full price if the cache lapsed. */
37  tokensAtStake: number | null
38}
39
40/** A usage limit as `$.session.usage()` reports it. */
41export type Limit = { percentUsed: number; resetsAt: string | null }
42
43/** Token Optimizer's quality cache fields the band reads. */
44export type Quality = {
45  score: number
46  grade: string
47  drag: string | null
48  toolCalls: number | null
49  compactions: number
50  checkpointEpoch: number | null
51  sessionStartEpoch: number | null
52  /** Token Optimizer's own context fill, %; known right after a compact, before the next reply. */
53  fillPct?: number | null
54}
55
56/** What `measure.py status-bar` returns, reduced to what the band shows. */
57export type Savings = {
58  sessionTokens: number | null
59  last30Tokens: number | null
60  /** 30 entries, oldest first; today last. */
61  daily: number[]
62}
63
64/** Everything the view model needs for one frame. */
65export type Snapshot = {
66  now: number
67  working: boolean
68  quality: Quality | null
69  contextPercent: number | null
70  contextTokens: number | null
71  contextWindow: number | null
72  /** Set only when contextWindow is a smaller auto-compact ceiling: the model's own window. */
73  contextModelWindow?: number | null
74  fiveHour: Limit | null
75  week: Limit | null
76  cache: CacheView
77  branch: string | null
78  savings: Savings | null
79  savingsLoading: boolean
80  busy: 'clean' | 'fresh-capture' | 'fresh-clear' | 'dashboard' | 'warming' | null
81  /** One-line outcome shown in place of "All clear." for a few seconds. */
82  note: string | null
83  /** A Start fresh hand-off waits for the first prompt. */
84  handoffPending: boolean
85  /** Start fresh is armed and waiting for its second click. */
86  freshArmed: boolean
87  /** When the session began (ms), from the engine: the row's session time before Token Optimizer reports one. */
88  startedAtMs?: number | null
89  /** Tool calls and compactions the band watched itself. */
90  toolCallsSeen?: number
91  compactionsSeen?: number
92  /** When this session last saved a checkpoint, any trigger (epoch seconds). */
93  checkpointEpoch?: number | null
94  /** An earlier session's checkpoint on this work, when this session has none of its own (epoch seconds). */
95  earlierCheckpoint?: { epoch: number; about: string | null } | null
96}
97
src/icons.ts 51 lines
1// 16x16 stroke icons from the design page, plus a standalone SVG builder for
2// the drawing layer's Svg element. Pure.
3
4export const ICONS = {
5  branch: '<circle cx="4" cy="3.5" r="1.6"></circle><circle cx="4" cy="12.5" r="1.6"></circle><circle cx="12" cy="5" r="1.6"></circle><path d="M4 5.1v5.8M12 6.6c0 2.6-4 2.2-6.6 4.2"></path>',
6  clock: '<circle cx="8" cy="8" r="5.8"></circle><path d="M8 4.8V8l2.2 1.4"></path>',
7  tool: '<path d="M10.2 2.2a3.2 3.2 0 0 0-3 4.3L2.6 11a1.4 1.4 0 0 0 2 2l4.6-4.6a3.2 3.2 0 0 0 4.2-3.7l-1.9 1.9-1.6-.4-.4-1.6 1.9-1.9a3.2 3.2 0 0 0-1.2-.5z"></path>',
8  compact: '<path d="M3 2.5h10M3 13.5h10M8 4.3v2.8M6.4 5.7 8 7.2l1.6-1.5M8 11.7V8.9M6.4 10.3 8 8.8l1.6 1.5"></path>',
9  bookmark: '<path d="M4.5 2.5h7v11L8 10.8l-3.5 2.7z"></path>',
10  cold: '<path d="M8 2v12M2.8 5l10.4 6M13.2 5 2.8 11"></path>',
11  hourglass: '<path d="M4.5 2.5h7M4.5 13.5h7M5 2.5c0 3 3 3.6 3 5.5s-3 2.5-3 5.5M11 2.5c0 3-3 3.6-3 5.5s3 2.5 3 5.5"></path>',
12  gauge: '<path d="M2.8 11.5a5.8 5.8 0 1 1 10.4 0M8 9l2.6-3.2"></path>',
13  check: '<circle cx="8" cy="8" r="5.8"></circle><path d="M5.6 8.2 7.3 9.9l3.2-3.6"></path>',
14  slip: '<path d="M2.5 4.5 6.5 8.5l2.5-2.5 4.5 4.5M13.5 7v3.5H10"></path>',
15  ask: '<circle cx="8" cy="8" r="5.8"></circle><path d="M6.3 6.4a1.75 1.75 0 1 1 2.4 1.6c-.45.2-.7.55-.7 1v.35M8 11.3v.05"></path>',
16  saved: '<ellipse cx="8" cy="4.2" rx="4.8" ry="1.9"></ellipse><path d="M3.2 4.2v3.8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V4.2M3.2 8v3.8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V8"></path>',
17} as const
18
19export type IconName = keyof typeof ICONS
20
21/** Default alt text naming each icon, used when the caller passes none. */
22export const ICON_ALT: Record<IconName, string> = {
23  branch: 'Branch',
24  clock: 'Clock',
25  tool: 'Tool calls',
26  compact: 'Compaction',
27  bookmark: 'Checkpoint',
28  cold: 'Cold cache',
29  hourglass: 'Cache countdown',
30  gauge: 'Gauge',
31  check: 'All clear',
32  slip: 'Quality slipping',
33  ask: 'Question',
34  saved: 'Tokens saved',
35}
36
37function attr(value: string): string {
38  return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
39}
40
41/** A complete standalone SVG string for an icon stroked in `color`. */
42export function iconSvg(name: IconName, color: string, opts: { size?: number; alt?: string } = {}): string {
43  const size = opts.size ?? 16
44  const alt = opts.alt ?? ICON_ALT[name]
45  return (
46    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 16 16" fill="none" ` +
47    `stroke="${attr(color)}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="${attr(alt)}">` +
48    `<title>${attr(alt)}</title>${ICONS[name]}</svg>`
49  )
50}
51
src/ladder.ts 109 lines
1// The sentence ladder: the single most urgent thing to say, and
2// at most one button. Pure.
3import type { Limit, Mood, Snapshot } from './contracts.ts'
4import type { IconName } from './icons.ts'
5import { DASHBOARD_OPENING } from './actions.ts'
6import { clock, gradeOf, renewalPhrase, tokens, type FormatOptions } from './format.ts'
7
8export type Tone = 'good' | 'caution' | 'bad' | 'cold'
9
10/** A run of text. Text is full ink; only `lose` (bold red) carries colour. `strong` is bold ink. */
11export type Run = { text: string; lose?: true; strong?: true }
12
13export type ActionId = 'clean' | 'clean-first' | 'fresh' | 'warm'
14export type Action = { id: ActionId; label: string }
15
16export type Sentence = { icon: IconName; tone: Tone; runs: Run[]; action: Action | null }
17
18/** Quality below grade B (score under 70) is worth a sentence. */
19export const QUALITY_FLOOR = 70
20export const LIMIT_WARN = 90
21export const COMPACT_HEAVY = 3
22
23const say = (icon: IconName, tone: Tone, runs: Run[], action: Action | null = null): Sentence => ({ icon, tone, runs, action })
24const plain = (text: string): Run => ({ text })
25
26/** The tokens the next message would re-read, as the one bold red run. */
27export function loseRun(n: number): Run {
28  return { text: `${tokens(n)} tokens`, lose: true }
29}
30
31function renews(limit: Limit, now: number, opts: FormatOptions): string {
32  const when = renewalPhrase(limit.resetsAt, now, opts)
33  return when ? ` Renews ${when}.` : ''
34}
35
36function limitSentence(name: string, limit: Limit, now: number, opts: FormatOptions): Sentence {
37  const head = limit.percentUsed >= 100 ? `${name} limit reached.` : `${name} limit ${Math.round(limit.percentUsed)}% used.`
38  return say('gauge', 'bad', [plain(head + renews(limit, now, opts))])
39}
40
41export function sentence(s: Snapshot, opts: FormatOptions = {}): Sentence {
42  // What the band is doing right now leads, with no button.
43  if (s.busy === 'clean') return say('compact', 'good', [plain('Cleaning up.')])
44  if (s.busy === 'fresh-capture') return say('bookmark', 'good', [plain('Saving checkpoint.')])
45  if (s.busy === 'fresh-clear') return say('bookmark', 'good', [plain('Clearing.')])
46  if (s.busy === 'dashboard') return say('gauge', 'good', [plain(DASHBOARD_OPENING)])
47  if (s.busy === 'warming') return say('hourglass', 'good', [plain('Keeping the cache warm.')])
48  if (s.freshArmed) {
49    return say('bookmark', 'caution', [plain('Start fresh clears this conversation after saving a checkpoint.')], {
50      id: 'fresh',
51      label: 'Click again to clear',
52    })
53  }
54  if (s.handoffPending) return say('bookmark', 'good', [plain('Checkpoint ready, it joins your first message.')])
55
56  // The ladder, first match wins. Null limits (API users) skip their rules.
57  const five = s.fiveHour
58  const week = s.week
59  if (five && five.percentUsed >= 100) return limitSentence('5-hour', five, s.now, opts)
60  if (week && week.percentUsed >= 100) return limitSentence('Weekly', week, s.now, opts)
61  if (five && five.percentUsed >= LIMIT_WARN) return limitSentence('5-hour', five, s.now, opts)
62  if (week && week.percentUsed >= LIMIT_WARN) return limitSentence('Weekly', week, s.now, opts)
63
64  const q = s.quality
65  if (q && q.compactions >= COMPACT_HEAVY) {
66    return say('compact', 'bad', [plain(`Compacted ${q.compactions} times. Early detail is mostly gone.`)], {
67      id: 'fresh',
68      label: 'Start fresh',
69    })
70  }
71  if (q && q.score < QUALITY_FLOOR) {
72    return say('slip', 'bad', [plain(`Quality slipped to ${gradeOf(q.score)}.`)], { id: 'clean', label: 'Clean up' })
73  }
74
75  // Cache rules hold still while a turn runs: every request refreshes the cache.
76  if (!s.working) {
77    const c = s.cache
78    if (c.state === 'cold') {
79      const runs: Run[] =
80        c.tokensAtStake != null
81          ? [plain('Cache is cold. Next message re-reads '), loseRun(c.tokensAtStake), plain(' at full price.')]
82          : [plain('Cache is cold. Next message re-reads the whole context at full price.')]
83      runs.push(plain(' Cleaning up first makes later messages cheaper.'))
84      return say('cold', 'cold', runs, { id: 'clean-first', label: 'Clean up first' })
85    }
86    if (c.state === 'warning') {
87      const head = c.secondsLeft != null ? `Cache drops in ${clock(c.secondsLeft)}.` : 'Cache drops soon.'
88      const runs: Run[] =
89        c.tokensAtStake != null
90          ? [plain(`${head} Then the next message re-reads `), loseRun(c.tokensAtStake), plain('.')]
91          : [plain(`${head} Then the next message re-reads the whole context.`)]
92      // Keep warm only on a measured lifetime.
93      return say('hourglass', 'caution', runs, c.measured ? { id: 'warm', label: 'Keep warm' } : null)
94    }
95  }
96
97  return say('check', 'good', [plain(s.note ?? 'All clear.')])
98}
99
100/** How healthy the session looks, for Clawd's face. */
101export function moodOf(s: Snapshot): Mood {
102  const limits = [s.fiveHour, s.week].filter((l): l is Limit => l !== null)
103  const q = s.quality
104  if (limits.some((l) => l.percentUsed >= LIMIT_WARN) || (q && q.compactions >= COMPACT_HEAVY)) return 'panic'
105  if (q && q.score < QUALITY_FLOOR) return 'worried'
106  if (!s.working && (s.cache.state === 'cold' || s.cache.state === 'warning')) return 'worried'
107  return 'calm'
108}
109
src/marks.ts 284 lines
1// The five marks, their hover cards and the detail row as plain
2// data the drawing layer maps to elements. Pure.
3import type { CacheView, Limit, Snapshot } from './contracts.ts'
4import type { IconName } from './icons.ts'
5import { ago, clock, duration, minutes, gradeOf, relative, renewal, tokens, type FormatOptions } from './format.ts'
6import { KEEP_WARM_MARGIN_MS } from './clock.ts'
7import { LIMIT_WARN, QUALITY_FLOOR, loseRun, type Action, type Run, type Tone } from './ladder.ts'
8
9const KEEP_WARM_MARGIN_S = KEEP_WARM_MARGIN_MS / 1000
10
11export type MarkId = 'quality' | 'context' | 'cache' | 'fiveHour' | 'week'
12/** 'none' means no data: the drawing layer shows the mark uncoloured. */
13export type MarkTone = Tone | 'none'
14
15export type Mark = {
16  id: MarkId
17  icon: IconName
18  /** The figure on the bar, "--" when unavailable. */
19  value: string
20  label: string
21  tone: MarkTone
22  /** 0..100 for ring marks (context, cache, limits). */
23  ringPercent?: number
24  /** The grade letter on the quality mark. */
25  badge?: string
26  /** Alt text naming the state. */
27  alt: string
28}
29
30export type Card = { id: MarkId; title: string; body: Run[]; actions: Action[] }
31
32export type Fact = { icon: IconName; runs: Run[] }
33
34export type SavingsBlock = {
35  state: 'ready' | 'loading' | 'unavailable'
36  sessionTokens: number | null
37  last30Tokens: number | null
38  sessionText: string
39  last30Text: string
40  /** Raw daily figures, oldest first, today last; empty when unavailable. */
41  daily: number[]
42  /** Bar heights in percent of the tallest day, at least 8 so a quiet day still shows. */
43  bars: number[]
44  /** One short reason when unavailable. */
45  reason: string | null
46}
47
48export type Row = { facts: Fact[]; savings: SavingsBlock }
49
50const clamp = (p: number) => Math.max(0, Math.min(100, Math.round(p)))
51const plain = (text: string): Run => ({ text })
52const strong = (text: string): Run => ({ text, strong: true })
53
54export function qualityTone(score: number): Tone {
55  return score >= 80 ? 'good' : score >= QUALITY_FLOOR ? 'caution' : 'bad'
56}
57export function fillTone(p: number): Tone {
58  return p >= 80 ? 'bad' : p >= 60 ? 'caution' : 'good'
59}
60export function limitTone(p: number): Tone {
61  return p >= LIMIT_WARN ? 'bad' : p >= 75 ? 'caution' : 'good'
62}
63
64function estimateNote(c: CacheView): string {
65  return c.measured ? 'an estimate' : 'an estimate, lifetime not measured yet'
66}
67
68function cacheMark(c: CacheView): Mark {
69  const base = { id: 'cache' as const, label: 'cache' }
70  const est = estimateNote(c)
71  switch (c.state) {
72    case 'warm':
73    case 'warning': {
74      const left = c.secondsLeft ?? 0
75      const tone: Tone = c.state === 'warm' ? 'good' : 'caution'
76      const word = c.state === 'warm' ? 'warm' : 'about to drop'
77      return { ...base, icon: 'hourglass', value: minutes(left), tone, ringPercent: clamp((left / c.lifetime) * 100), alt: `Cache ${word}, ${minutes(left)} left, ${est}` }
78    }
79    case 'cold':
80      return { ...base, icon: 'cold', value: 'cold', tone: 'cold', ringPercent: 0, alt: `Cache cold, ${est}` }
81    case 'refreshing':
82      return { ...base, icon: 'hourglass', value: minutes(c.lifetime), tone: 'good', ringPercent: 100, alt: 'Cache refreshing while the turn runs' }
83    case 'warming':
84      return {
85        ...base,
86        icon: 'hourglass',
87        value: c.secondsLeft != null ? minutes(c.secondsLeft) : '--',
88        tone: 'good',
89        ringPercent: c.secondsLeft != null ? clamp((c.secondsLeft / c.lifetime) * 100) : 0,
90        alt: 'Cache warm-up running',
91      }
92    default:
93      return { ...base, icon: 'hourglass', value: '--', tone: 'none', ringPercent: 0, alt: 'Cache clock starts after the first reply' }
94  }
95}
96
97function limitMark(id: 'fiveHour' | 'week', limit: Limit, now: number, opts: FormatOptions): Mark {
98  const p = Math.round(limit.percentUsed)
99  const name = id === 'fiveHour' ? '5-hour' : 'Weekly'
100  const when = renewal(limit.resetsAt, now, opts)
101  return {
102    id,
103    icon: 'clock',
104    value: `${p}%`,
105    label: id === 'fiveHour' ? '5 hours' : 'week',
106    tone: limitTone(limit.percentUsed),
107    ringPercent: clamp(limit.percentUsed),
108    alt: `${name} limit ${p}% used` + (when ? `, renews ${when}` : ''),
109  }
110}
111
112/** The marks under the sentence, in order. Limit marks are omitted when the limit is null. */
113export function marks(s: Snapshot, opts: FormatOptions = {}): Mark[] {
114  const q = s.quality
115  const quality: Mark = q
116    ? {
117        id: 'quality',
118        icon: q.score < QUALITY_FLOOR ? 'slip' : 'check',
119        value: String(Math.round(q.score)),
120        badge: gradeOf(q.score),
121        label: 'quality',
122        tone: qualityTone(q.score),
123        alt: `Quality grade ${gradeOf(q.score)}, score ${Math.round(q.score)} of 100`,
124      }
125    : { id: 'quality', icon: 'check', value: '--', badge: '--', label: 'quality', tone: 'none', alt: 'Quality not measured yet' }
126
127  const p = s.contextPercent
128  const context: Mark =
129    p != null
130      ? { id: 'context', icon: 'gauge', value: `${Math.round(p)}%`, label: 'context', tone: fillTone(p), ringPercent: clamp(p), alt: `Context ${Math.round(p)}% full` }
131      : { id: 'context', icon: 'gauge', value: '--', label: 'context', tone: 'none', ringPercent: 0, alt: 'Context fill not reported yet' }
132
133  const out = [quality, context, cacheMark(s.cache)]
134  if (s.fiveHour) out.push(limitMark('fiveHour', s.fiveHour, s.now, opts))
135  if (s.week) out.push(limitMark('week', s.week, s.now, opts))
136  return out
137}
138
139function cacheCard(c: CacheView): Card {
140  const est = ` The clock is ${estimateNote(c)}.`
141  // Offered only while a press can still run: not in the last seconds before the cache drops.
142  const warm: Action[] = c.measured && (c.secondsLeft ?? 0) > KEEP_WARM_MARGIN_S ? [{ id: 'warm', label: 'Keep warm' }] : []
143  const stake = c.tokensAtStake
144  switch (c.state) {
145    case 'warm':
146      return {
147        id: 'cache',
148        title: `Warm for ${minutes(c.secondsLeft ?? 0)}`,
149        body: [plain(stake != null ? `Messages re-read ${tokens(stake)} tokens at a tenth of the price.` : 'Messages re-read the context at a tenth of the price.'), plain(est)],
150        actions: warm,
151      }
152    case 'warning':
153      return {
154        id: 'cache',
155        title: c.secondsLeft != null ? `Drops in ${minutes(c.secondsLeft)}` : 'Drops soon',
156        body: [
157          ...(stake != null ? [plain('Then the next message re-reads '), loseRun(stake), plain(' at full price.')] : [plain('Then the next message re-reads the whole context at full price.')]),
158          plain(est),
159        ],
160        actions: warm,
161      }
162    case 'cold':
163      return {
164        id: 'cache',
165        title: 'Cold',
166        body: [
167          ...(stake != null ? [plain('Next message re-reads '), loseRun(stake), plain(' at full price.')] : [plain('Next message re-reads the whole context at full price.')]),
168          plain(' Cleaning up first re-reads it once and makes later messages cheaper.'),
169        ],
170        actions: [{ id: 'clean-first', label: 'Clean up first' }],
171      }
172    case 'refreshing':
173      return { id: 'cache', title: 'Refreshing', body: [plain('Every request in this turn keeps the cache warm.')], actions: [] }
174    case 'warming':
175      return { id: 'cache', title: 'Keeping warm', body: [plain('A one-line warm-up is running.')], actions: [] }
176    default:
177      return { id: 'cache', title: 'Not started', body: [plain('The clock starts after the first reply.')], actions: [] }
178  }
179}
180
181function limitCard(id: 'fiveHour' | 'week', limit: Limit, now: number, opts: FormatOptions): Card {
182  const when = renewal(limit.resetsAt, now, opts)
183  const at = limit.resetsAt ? Date.parse(limit.resetsAt) : NaN
184  if (!when || !Number.isFinite(at)) {
185    const name = id === 'fiveHour' ? '5-hour' : 'Weekly'
186    return { id, title: `${name} limit ${Math.round(limit.percentUsed)}% used`, body: [plain('Renewal time not reported.')], actions: [] }
187  }
188  return { id, title: `Renews ${when}`, body: [plain(`That is ${relative(at, now)}.`)], actions: [] }
189}
190
191/** Hover card bodies, one per mark, same order and omissions as `marks`. */
192export function cards(s: Snapshot, opts: FormatOptions = {}): Card[] {
193  const q = s.quality
194  const qualityActions: Action[] = [
195    { id: 'clean', label: 'Clean up' },
196    { id: 'fresh', label: s.freshArmed ? 'Click again to clear' : 'Start fresh' },
197  ]
198  const quality: Card = q
199    ? {
200        id: 'quality',
201        title: `Quality ${gradeOf(q.score)} ${Math.round(q.score)}`,
202        body: [plain(q.drag ? `Biggest drag: ${q.drag}.` : 'Nothing is dragging quality down.')],
203        actions: qualityActions,
204      }
205    : { id: 'quality', title: 'Quality --', body: [plain('The score appears after the first tool call.')], actions: qualityActions }
206
207  // With a smaller auto-compact ceiling the ring measures distance to compaction, while
208  // quality follows the model window, so the card names both and makes no quality claim.
209  const model = s.contextModelWindow
210  const context: Card =
211    s.contextTokens != null && s.contextWindow != null
212      ? model != null && model > s.contextWindow
213        ? {
214            id: 'context',
215            title: `${tokens(s.contextTokens)} of ${tokens(s.contextWindow)} before auto-compact`,
216            body: [plain(`${Math.round((s.contextTokens / model) * 100)}% of the ${tokens(model)} model window.`)],
217            actions: [],
218          }
219        : { id: 'context', title: `${tokens(s.contextTokens)} of ${tokens(s.contextWindow)} tokens`, body: [plain('Quality holds best under half full.')], actions: [] }
220      : { id: 'context', title: 'Context --', body: [plain('The fill appears after the first reply.')], actions: [] }
221
222  const out = [quality, context, cacheCard(s.cache)]
223  if (s.fiveHour) out.push(limitCard('fiveHour', s.fiveHour, s.now, opts))
224  if (s.week) out.push(limitCard('week', s.week, s.now, opts))
225  return out
226}
227
228function savingsBlock(s: Snapshot): SavingsBlock {
229  const sv = s.savings
230  if (!sv) {
231    return {
232      state: s.savingsLoading ? 'loading' : 'unavailable',
233      sessionTokens: null,
234      last30Tokens: null,
235      sessionText: '--',
236      last30Text: '--',
237      daily: [],
238      bars: [],
239      reason: s.savingsLoading ? null : 'Savings appear once Token Optimizer has measured some.',
240    }
241  }
242  const top = Math.max(1, ...sv.daily)
243  return {
244    state: s.savingsLoading ? 'loading' : 'ready',
245    sessionTokens: sv.sessionTokens,
246    last30Tokens: sv.last30Tokens,
247    sessionText: sv.sessionTokens != null ? tokens(sv.sessionTokens) : '--',
248    last30Text: sv.last30Tokens != null ? tokens(sv.last30Tokens) : '--',
249    daily: sv.daily,
250    bars: sv.daily.map((v) => Math.max(8, Math.round((Math.max(0, v) / top) * 100))),
251    reason: null,
252  }
253}
254
255/**
256 * The detail row under Clawd: only what the bar does not show.
257 * `s.now` is epoch milliseconds; the quality cache's epochs are seconds.
258 */
259/** Longer branch names are cut so the unfolded row stays on one line. */
260const BRANCH_MAX = 20
261
262export function row(s: Snapshot, _opts: FormatOptions = {}): Row {
263  const q = s.quality
264  const facts: Fact[] = []
265  // One line in the band: every fact in its shortest plain form.
266  if (s.branch) facts.push({ icon: 'branch', runs: [strong(s.branch.length > BRANCH_MAX ? `${s.branch.slice(0, BRANCH_MAX - 1)}…` : s.branch)] })
267  // The band's own sightings fill in until Token Optimizer's quality file exists (a new session).
268  const startS = q?.sessionStartEpoch ?? (s.startedAtMs != null ? s.startedAtMs / 1000 : null)
269  if (startS != null) facts.push({ icon: 'clock', runs: [strong(duration(s.now / 1000 - startS))] })
270  const tools = Math.max(q?.toolCalls ?? 0, s.toolCallsSeen ?? 0)
271  if (q?.toolCalls != null || (s.toolCallsSeen ?? 0) > 0) facts.push({ icon: 'tool', runs: [strong(String(tools)), plain(tools === 1 ? ' tool' : ' tools')] })
272  const compacted = Math.max(q?.compactions ?? 0, s.compactionsSeen ?? 0)
273  if (compacted > 0) facts.push({ icon: 'compact', runs: [strong(`${compacted}×`), plain(' compacted')] })
274  facts.push({
275    icon: 'bookmark',
276    runs: (s.checkpointEpoch ?? q?.checkpointEpoch) != null
277      ? [plain('Checkpoint '), strong(ago((s.checkpointEpoch ?? q!.checkpointEpoch!) * 1000, s.now))]
278      : s.earlierCheckpoint
279        ? [plain('Earlier checkpoint '), strong(ago(s.earlierCheckpoint.epoch * 1000, s.now))]
280        : [plain('No checkpoint yet')],
281  })
282  return { facts, savings: savingsBlock(s) }
283}
284
src/size.ts 30 lines
1// The band's two sizes, and what the slim line's right end earns. Pure.
2import type { IconName } from './icons.ts'
3import type { Action, Run, Sentence, Tone } from './ladder.ts'
4
5export type BandSize = 'slim' | 'full'
6
7/** The env default: 'slim' slims, anything else (or unset) is the full band. */
8export function envSize(value: string | undefined): BandSize {
9  return (value ?? '').trim().toLowerCase() === 'slim' ? 'slim' : 'full'
10}
11
12/** A stored choice: only the two real sizes count; anything else is nothing stored. */
13export function storedSize(value: unknown): BandSize | null {
14  return value === 'slim' || value === 'full' ? value : null
15}
16
17/** The slim line's right end: the sentence's button, its text when it warns, or nothing. */
18export type SlimSide =
19  | { kind: 'action'; icon: IconName; tone: Tone; action: Action }
20  | { kind: 'warn'; icon: IconName; tone: Tone; runs: Run[] }
21  | { kind: 'none' }
22
23export function slimSide(say: Sentence): SlimSide {
24  // The sentence's own button first: it is the one thing worth a press.
25  if (say.action !== null) return { kind: 'action', icon: say.icon, tone: say.tone, action: say.action }
26  // No button but not calm: the sentence itself. Only a good tone is calm here.
27  if (say.tone !== 'good') return { kind: 'warn', icon: say.icon, tone: say.tone, runs: say.runs }
28  return { kind: 'none' }
29}
30
src/pose.ts 229 lines
1// Clawd's pose as a pure reducer. A base pose derived from what is
2// going on, plus short transient poses with holds. No I/O, no 'claude-code':
3// register.tsx maps engine events onto PoseEvent and passes the time in.
4import type { Pose } from './contracts.ts'
5
6/** Working sub-pose changes wait this long to settle, so read/type bursts do not strobe. */
7export const DEBOUNCE_MS = 900
8/** A working sub-pose stays on screen at least this long before the next one replaces it. */
9export const MIN_DWELL_MS = 1600
10/** Idle this long (no events) and Clawd naps. Agent default (plan Assumptions). */
11export const NAP_AFTER_MS = 10 * 60_000
12/** How long each transient pose holds. */
13export const HOLD_MS = { wake: 2000, done: 2500, stop: 2500, error: 4000 } as const
14
15type Transient = keyof typeof HOLD_MS
16type SubPose = 'think' | 'read' | 'type' | 'write' | 'lift'
17
18export type PoseEvent =
19  | { type: 'session-start' }
20  | { type: 'turn-start' }
21  | { type: 'working-changed'; working: boolean }
22  | { type: 'thinking' }
23  | { type: 'text' }
24  | { type: 'tool-call'; tool: string; agentId?: string }
25  | { type: 'tool-done'; agentId?: string }
26  | { type: 'agent-spawn'; agentId: string; background: boolean }
27  | { type: 'agent-done'; agentId: string }
28  | { type: 'permission-open' }
29  | { type: 'permission-closed' }
30  | { type: 'question-open' }
31  | { type: 'question-closed' }
32  | { type: 'compact-start' }
33  | { type: 'compact-end' }
34  | { type: 'turn-complete'; reason: 'answer' | 'aborted' | 'refusal' | 'error'; agentId?: string }
35  | { type: 'cache-cold-changed'; cold: boolean }
36  | { type: 'tick'; now: number }
37
38export type PoseState = {
39  /** The pose on screen. */
40  pose: Pose
41  /** When the pose on screen last changed (ms). */
42  since: number
43  /** Last time the reducer saw (ms). */
44  now: number
45  working: boolean
46  /** Latest main-thread working signal, before the debounce. */
47  rawSub: SubPose | null
48  /** When rawSub last changed. */
49  rawSince: number
50  /** The working sub-pose that has settled and may show. */
51  sub: SubPose | null
52  /** Running subagents by id; true = background (outlives the main turn). */
53  agents: Readonly<Record<string, boolean>>
54  permissions: number
55  questions: number
56  compacting: boolean
57  cold: boolean
58  /** Last non-tick, non-cache event (ms); napping counts from here. */
59  lastActivity: number
60  /** Transient hold deadlines (ms); 0 = not playing. */
61  until: Readonly<Record<Transient, number>>
62}
63
64const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'NotebookRead', 'LS'])
65const LIFT_TOOLS = new Set(['Task', 'Agent'])
66
67/** Which pose a main-thread tool call shows. Unknown tools type. */
68export function toolPose(tool: string): 'read' | 'type' | 'lift' {
69  if (READ_TOOLS.has(tool)) return 'read'
70  if (LIFT_TOOLS.has(tool)) return 'lift'
71  return 'type'
72}
73
74const NO_TRANSIENTS: Record<Transient, number> = { wake: 0, done: 0, stop: 0, error: 0 }
75
76export function initialPose(now: number): PoseState {
77  return {
78    pose: 'idle',
79    since: now,
80    now,
81    working: false,
82    rawSub: null,
83    rawSince: now,
84    sub: null,
85    agents: {},
86    permissions: 0,
87    questions: 0,
88    compacting: false,
89    cold: false,
90    lastActivity: now,
91    until: NO_TRANSIENTS,
92  }
93}
94
95/**
96 * One step. `now` defaults to the tick's own time, or the last time seen for
97 * other events; pass it explicitly when the caller knows when the event landed.
98 */
99export function reducePose(state: PoseState, event: PoseEvent, now?: number): PoseState {
100  const t = now ?? (event.type === 'tick' ? event.now : state.now)
101  let s: PoseState = { ...state, now: t }
102  if (event.type !== 'tick' && event.type !== 'cache-cold-changed') s.lastActivity = t
103
104  const setRaw = (sub: SubPose | null): void => {
105    if (s.rawSub === sub) return
106    s.rawSub = sub
107    s.rawSince = t
108  }
109  const play = (tr: Transient): void => {
110    // Dropped, not queued, while Clawd is asking for you.
111    if (needsYou(s)) return
112    s.until = { ...s.until, [tr]: t + HOLD_MS[tr] }
113  }
114  const dropAgent = (id: string): void => {
115    if (!(id in s.agents)) return
116    const rest = { ...s.agents }
117    delete rest[id]
118    s.agents = rest
119  }
120
121  switch (event.type) {
122    case 'session-start':
123      s = { ...initialPose(t), pose: s.pose, since: s.since, cold: s.cold }
124      play('wake')
125      break
126    case 'turn-start':
127      setRaw('think')
128      break
129    case 'working-changed':
130      s.working = event.working
131      if (event.working && s.rawSub === null) setRaw('think')
132      if (!event.working) {
133        setRaw(null)
134        s.sub = null
135      }
136      break
137    case 'thinking':
138      setRaw('think')
139      break
140    case 'text':
141      setRaw('write')
142      break
143    case 'tool-call':
144      // Subagent events only feed heavy lifting, through spawn/done.
145      if (event.agentId === undefined) setRaw(toolPose(event.tool))
146      break
147    case 'tool-done':
148      if (event.agentId === undefined && s.rawSub === 'lift') setRaw('think')
149      break
150    case 'agent-spawn':
151      s.agents = { ...s.agents, [event.agentId]: event.background }
152      break
153    case 'agent-done':
154      dropAgent(event.agentId)
155      break
156    case 'permission-open':
157      s.permissions += 1
158      break
159    case 'permission-closed':
160      s.permissions = Math.max(0, s.permissions - 1)
161      break
162    case 'question-open':
163      s.questions += 1
164      break
165    case 'question-closed':
166      s.questions = Math.max(0, s.questions - 1)
167      break
168    case 'compact-start':
169      s.compacting = true
170      break
171    case 'compact-end':
172      s.compacting = false
173      break
174    case 'turn-complete':
175      if (event.agentId !== undefined) {
176        dropAgent(event.agentId)
177        break
178      }
179      // Foreground agents end with the main turn; background ones keep lifting.
180      s.agents = Object.fromEntries(Object.entries(s.agents).filter(([, bg]) => bg))
181      setRaw(null)
182      s.sub = null
183      play(event.reason === 'error' ? 'error' : event.reason === 'aborted' ? 'stop' : 'done')
184      break
185    case 'cache-cold-changed':
186      s.cold = event.cold
187      break
188    case 'tick':
189      break
190  }
191
192  settle(s, t)
193  const pose = derive(s, t)
194  if (pose !== s.pose) {
195    s.pose = pose
196    s.since = t
197  }
198  return s
199}
200
201function needsYou(s: PoseState): boolean {
202  return s.permissions > 0 || s.questions > 0
203}
204
205/** Debounce: the first sub-pose of a turn shows at once; later changes wait to settle. */
206function settle(s: PoseState, t: number): void {
207  if (s.rawSub === s.sub) return
208  if (s.sub === null || (t - s.rawSince >= DEBOUNCE_MS && t - s.since >= MIN_DWELL_MS)) s.sub = s.rawSub
209}
210
211function playing(s: PoseState, tr: Transient, t: number): boolean {
212  return s.until[tr] > t
213}
214
215/** Precedence: needs-you > dizzy > stopped > compacting > heavy lifting > working > done > wake > cold > napping > watching. */
216function derive(s: PoseState, t: number): Pose {
217  if (needsYou(s)) return 'ask'
218  if (playing(s, 'error', t)) return 'error'
219  if (playing(s, 'stop', t)) return 'stop'
220  if (s.compacting) return 'compact'
221  if (Object.keys(s.agents).length > 0) return 'lift'
222  if (s.working) return s.sub ?? 'think'
223  if (playing(s, 'done', t)) return 'done'
224  if (playing(s, 'wake', t)) return 'wake'
225  if (s.cold) return 'cold'
226  if (t - s.lastActivity >= NAP_AFTER_MS) return 'sleep'
227  return 'idle'
228}
229
hooks/data.ts 582 lines
1// Data gathering and re-keying for the band.
2//
3// The engine refuses `$` passed across an import ("$ is followed only into a
4// function declared in this same file"), and a plugin has exactly one hooks
5// module. So this file never sees `$`: it works over `DataIo`, a port that
6// register.tsx builds from `$` in one top-level function (`dataIo($)`), each
7// member spelled `$.noun.method(...)` there. That keeps every noun call where
8// the engine's scan looks for it, and lets this logic run under plain Node.
9//
10// Every lookup is best effort: a figure that cannot be read is left null and
11// the rest still fill. Nothing here registers a hook; register.tsx wires the
12// events and the cadence below.
13import type { TokenOptimizerDesktopSession } from '../types/index.d.ts'
14import type { Limit, Quality } from '../src/contracts.ts'
15import {
16  parseQualityCache,
17  parseStatusBar,
18  parseUsage,
19  resolveTokenOptimizerRoot,
20  smallerCompactWindow,
21  type StatusBar,
22  type TokenOptimizerRoot,
23} from '../src/parse.ts'
24
25/** Redraw once a second, but only inside the cache warning window. */
26export const TICK_WARNING_MS = 1_000
27/** Redraw otherwise, beside the event-driven redraws. */
28export const TICK_IDLE_MS = 60_000
29/** Re-read the quality cache this often, and after each turn. */
30export const QUALITY_REFRESH_MS = 60_000
31/** Run the status command this long after a turn ends. */
32export const STATUS_AFTER_TURN_MS = 5_000
33/** The status command answers from its cache in well under a second warm. */
34export const STATUS_TIMEOUT_MS = 4_000
35/** `git branch --show-current` is local and instant; anything slower is skipped. */
36export const GIT_TIMEOUT_MS = 1_000
37
38/** Shown as the savings reason when no Token Optimizer install is found. */
39export const NOT_FOUND = 'Token Optimizer not found'
40/** No Python 3 launcher starts: Token Optimizer's scripts cannot run. */
41export const NO_PYTHON = 'Token Optimizer needs Python 3 to measure savings.'
42/** The installed Token Optimizer predates the status command this band reads. */
43export const OUTDATED = 'Update Token Optimizer to see savings.'
44
45/**
46 * Python launchers in the order tried on macOS and Linux. A launcher that
47 * cannot start (or Windows' Store stub, exit 9009) moves on to the next. The
48 * first that starts is remembered for the module's life.
49 */
50export const PYTHON_LAUNCHERS: readonly (readonly string[])[] = [['python3'], ['python'], ['py', '-3']]
51
52/**
53 * The order on a Windows install (#261). `py -3` is the python.org launcher in
54 * C:\\Windows and is never a Store alias, so it goes first; `python` and
55 * `python3` are often the WindowsApps "app execution alias" stubs, which are
56 * not an interpreter at all.
57 */
58export const WINDOWS_PYTHON_LAUNCHERS: readonly (readonly string[])[] = [['py', '-3'], ['python'], ['python3']]
59
60/**
61 * What a live Python 3 prints for the proof-of-life probe. The probe holds no
62 * spaces or double quotes, so it reaches Python intact through any Windows
63 * command-line quoting (and through `py`, which re-quotes for the child).
64 */
65export const PYTHON_PROOF = 'token-optimizer-python-ok'
66export const PYTHON_PROBE = `print(('','${PYTHON_PROOF}')[__import__('sys').version_info[0]>=3])`
67/** A cold interpreter start on Windows (Defender scanning it) can take seconds. */
68export const PYTHON_PROBE_TIMEOUT_MS = 8_000
69
70/** Windows' "app execution alias" stub for a missing python exits with this. */
71const WINDOWS_NOT_FOUND = 9009
72// Some Bun Windows runtimes expose only the low byte of the process exit code.
73const WINDOWS_NOT_FOUND_LOW_BYTE = WINDOWS_NOT_FOUND & 0xff
74
75/**
76 * The names Windows' App Installer claims as Store aliases (python.exe and
77 * python3.exe under WindowsApps). `py` is the real launcher in C:\\Windows
78 * and is never an alias, so its exit 49 is a real answer.
79 */
80function isStoreAliasName(launcher: readonly string[] | undefined): boolean {
81  return launcher?.[0] === 'python3' || launcher?.[0] === 'python'
82}
83
84/** A drive-letter or UNC scripts folder: the install is on Windows. */
85function isWindowsRoot(scriptsDir: string): boolean {
86  return /^[A-Za-z]:[\\/]/.test(scriptsDir) || scriptsDir.startsWith('\\\\')
87}
88
89let launcherIndex = 0
90let windowsLauncherIndex = 0
91/** The Windows launcher index whose proof-of-life probe passed, or -1. */
92let windowsProven = -1
93
94/** Forgets which launcher worked (tests, and nothing else). */
95export function resetLauncher(): void {
96  launcherIndex = 0
97  windowsLauncherIndex = 0
98  windowsProven = -1
99}
100
101/** No Python 3 interpreter could be found: every launcher was tried. */
102export class PythonNotFoundError extends Error {
103  constructor() {
104    super('python launcher not found')
105    this.name = 'PythonNotFoundError'
106  }
107}
108
109/**
110 * What the gatherer needs from the engine. register.tsx answers each member
111 * with the `$` call named beside it; any member may reject.
112 */
113export type DataIo = {
114  /** `$.clock.now()` (ms) */
115  now: () => Promise<number>
116  /** `$.session.id()` */
117  sessionId: () => Promise<string>
118  /** `$.session.cwd()` */
119  cwd: () => Promise<string>
120  /** `$.env.get('HOME')` (the validator wants a literal variable name) */
121  envHome: () => Promise<string | undefined>
122  /** `$.env.get('CLAUDE_CONFIG_DIR')`: a relocated Claude folder, as Token Optimizer honours it */
123  envConfigDir?: () => Promise<string | undefined>
124  /** `$.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW')`: the raw auto-compaction window override */
125  envAutoCompactWindow?: () => Promise<string | undefined>
126  /** `$.env.get('USERPROFILE')`, the Windows home */
127  envUserProfile: () => Promise<string | undefined>
128  /** `$.session.usage()` */
129  usage: () => Promise<unknown>
130  /** `$.fs.list(path)` */
131  list: (path: string) => Promise<readonly { name: string }[]>
132  /** `$.fs.stat(path)` */
133  stat: (path: string) => Promise<{ kind: string; mtimeMs: number }>
134  /** `$.fs.read(path)` */
135  read: (path: string) => Promise<string>
136  /** `$.plugin.root`: this plugin's own folder */
137  pluginRoot?: () => string
138  /** `$.process.run(argv, init)` */
139  run: (argv: string[], init: { cwd?: string; timeoutMs: number; stdin?: string }) => Promise<{ exitCode: number; stdout: string; stderr?: string }>
140  /** `$.ui.log(text, { to: 'debug' })`: a line in Claude Code's debug log */
141  log?: (text: string) => Promise<void>
142}
143
144async function attempt<T>(work: () => Promise<T>, fallback: T): Promise<T> {
145  try {
146    return await work()
147  } catch {
148    return fallback
149  }
150}
151
152/** Session ids become file names; keep only what Token Optimizer's own sanitizer keeps. */
153export function cleanId(id: string): string {
154  const clean = id.replace(/[^a-zA-Z0-9_-]/g, '')
155  // Token Optimizer files an id shorter than 6 under "unknown": read nothing for it either.
156  return clean.length >= 6 ? clean : ''
157}
158
159/** True when the stored atom belongs to another session (or to none) and must be reset. */
160export function shouldReset(stored: TokenOptimizerDesktopSession | null, liveSessionId: string): boolean {
161  return stored === null || stored.sessionId !== liveSessionId
162}
163
164/** The user's home, as the engine's process sees it. */
165export async function readHome(io: DataIo): Promise<string> {
166  return (await attempt(() => io.envHome(), undefined)) || (await attempt(() => io.envUserProfile(), undefined)) || ''
167}
168
169/** The Claude folder: CLAUDE_CONFIG_DIR when set (as Token Optimizer's claude_home()), else ~/.claude. */
170export async function claudeDir(io: DataIo, home: string): Promise<string> {
171  const set = io.envConfigDir ? await attempt(() => io.envConfigDir!(), undefined) : undefined
172  const dir = set ? set.trim().replace(/[\\/]+$/, '') : ''
173  // Absolute only, as Token Optimizer requires: a relative one would point the band elsewhere.
174  const absolute = dir.startsWith('/') || /^[A-Za-z]:[\\/]/.test(dir)
175  return absolute ? dir : home ? `${home}/.claude` : ''
176}
177
178/**
179 * The freshest `quality-cache-<sid>.json` across Token Optimizer's storage
180 * directories: each plugin install's data dir, then the legacy
181 * `~/.claude/token-optimizer`. Newest modification time wins.
182 */
183export async function readQuality(io: DataIo, home: string, sid: string): Promise<Quality | null> {
184  if (!home || !sid) {
185    return null
186  }
187
188  const claude = await claudeDir(io, home)
189  const dataRoot = `${claude}/plugins/data`
190  const entries = await attempt(() => io.list(dataRoot), [])
191  const dirs = entries
192    .filter(entry => entry.name.includes('token-optimizer'))
193    .map(entry => `${dataRoot}/${entry.name}/token-optimizer`)
194  dirs.push(`${claude}/token-optimizer`)
195
196  let freshest: { path: string; mtimeMs: number } | null = null
197
198  for (const dir of dirs) {
199    const path = `${dir}/quality-cache-${sid}.json`
200    const stat = await attempt(() => io.stat(path), null)
201
202    if (stat && stat.kind === 'file' && (!freshest || stat.mtimeMs > freshest.mtimeMs)) {
203      freshest = { path, mtimeMs: stat.mtimeMs }
204    }
205  }
206
207  if (!freshest) {
208    return null
209  }
210
211  const { path } = freshest
212  const raw = await attempt(() => io.read(path), null)
213  const nowMs = await attempt(() => io.now(), Date.now())
214
215  return raw === null ? null : parseQualityCache(raw, nowMs / 1000)
216}
217
218/**
219 * Token Optimizer's scripts: the installed-plugins registry first, then
220 * the skill install; the first whose measure.py exists. null when neither does.
221 */
222export async function findTokenOptimizerRoot(io: DataIo, home: string): Promise<TokenOptimizerRoot | null> {
223  const claude = await claudeDir(io, home)
224  const registry = claude ? await attempt(() => io.read(`${claude}/plugins/installed_plugins.json`), null) : null
225  // Shipped inside Token Optimizer, the plugin root is Token Optimizer itself; loaded on its
226  // own from a checkout (desktop/<this plugin>), the scripts two folders up are the matching version.
227  const root = io.pluginRoot ? await attempt(async () => io.pluginRoot!(), '') : ''
228  const sibling = [root.replace(/[\\/]+$/, ''), trimTwo(root)]
229    .filter(dir => dir !== '')
230    .map(dir => ({ scriptsDir: `${dir}/skills/token-optimizer/scripts`, runner: `${dir}/hooks/module_runner.py` }))
231
232  // Only scripts inside the Claude folder run (or beside this plugin in a checkout): a
233  // tampered or stale registry entry pointing elsewhere is skipped, never executed.
234  // Compared with one separator and one case of drive letter, so a Windows home
235  // (C:\\Users\\me) and a registry path (C:\\Users\\me\\.claude\\...) agree.
236  const norm = (p: string) => p.replace(/\\/g, '/').replace(/^([a-zA-Z]):/, (_m: string, d: string) => `${d.toLowerCase()}:`)
237  // Windows paths compare without case, as the filesystem does.
238  const fold = (p: string) => (/^[a-z]:\//.test(norm(claude)) ? norm(p).toLowerCase() : norm(p))
239  const base = fold(claude)
240  const inside = (p: string) => base !== '' && (fold(p) === base || fold(p).startsWith(`${base}/`))
241  const listed = resolveTokenOptimizerRoot(registry, claude).filter(r => inside(r.scriptsDir))
242  for (const root of [...sibling, ...listed]) {
243    if (!(await attempt(() => io.stat(`${root.scriptsDir}/measure.py`), null))) {
244      continue
245    }
246
247    const { runner } = root
248    const hasRunner = runner !== null && (await attempt(() => io.stat(runner), null)) !== null
249
250    return { scriptsDir: root.scriptsDir, runner: hasRunner ? runner : null }
251  }
252
253  return null
254}
255
256function newer(a: number | null, b: number | null): number | null {
257  return a === null ? b : b === null ? a : Math.max(a, b)
258}
259
260/** A path two folders up, or '' when it has fewer. */
261function trimTwo(path: string): string {
262  const parts = path.replace(/[\\/]+$/, '').split(/[\\/]/)
263  return parts.length > 2 ? parts.slice(0, -2).join('/') : ''
264}
265
266/** The argv for `measure.py <args>`, through module_runner when the install has it (bytecode reuse). */
267export function measureArgv(root: TokenOptimizerRoot, args: readonly string[], python: readonly string[] = PYTHON_LAUNCHERS[0] ?? ['python3']): string[] {
268  const launch = root.runner ? [...python, root.runner, root.scriptsDir, 'measure'] : [...python, `${root.scriptsDir}/measure.py`]
269
270  return [...launch, ...args]
271}
272
273/** The arguments of `measure.py status-bar` for one session. */
274function statusBarArgs(sid: string, transcript?: string): string[] {
275  return ['status-bar', '--session', sid, '--json', ...(transcript ? ['--transcript', transcript] : [])]
276}
277
278function isTimeout(error: unknown): boolean {
279  const name = error instanceof Error ? error.name : ''
280  return name === 'TimeoutError' || /timed? ?out|deadline/i.test(error instanceof Error ? error.message : String(error))
281}
282
283/** No Python launcher could start at all (every one was tried). */
284function noLauncher(error: unknown): boolean {
285  return /no python launcher|python launcher not found|ENOENT|not found/i.test(error instanceof Error ? error.message : String(error))
286}
287
288/**
289 * Windows only: does this launcher start a real Python 3? The answer is the
290 * probe's printed proof, never an exit code or a message, so a Store alias
291 * stub fails it in any language and however its exit code arrives, while a
292 * real Store-installed Python (also under WindowsApps) passes. Rejects on a
293 * spawn failure or a timeout, like any run.
294 */
295async function provesPython(io: DataIo, launcher: readonly string[]): Promise<boolean> {
296  const probe = await io.run([...launcher, '-I', '-c', PYTHON_PROBE], { timeoutMs: PYTHON_PROBE_TIMEOUT_MS })
297
298  return probe.exitCode === 0 && probe.stdout.split(/\r?\n/).some(line => line.trim() === PYTHON_PROOF)
299}
300
301/**
302 * Runs `measure.py <args>` with the first Python launcher that starts. On a
303 * Windows install each launcher must first pass a proof-of-life probe (once,
304 * then remembered), the same rule the hook launcher applies to WindowsApps
305 * candidates. A timeout is the command's own answer and is never retried, so
306 * a slow read costs one timeout, not three. Rejects as the last attempt did,
307 * or with PythonNotFoundError when no launcher was a Python 3.
308 */
309export async function runMeasure(
310  io: DataIo,
311  root: TokenOptimizerRoot,
312  args: readonly string[],
313  init: { timeoutMs: number; stdin?: string },
314): Promise<{ exitCode: number; stdout: string; stderr?: string }> {
315  const windowsRoot = isWindowsRoot(root.scriptsDir)
316  const launchers = windowsRoot ? WINDOWS_PYTHON_LAUNCHERS : PYTHON_LAUNCHERS
317  let lastError: unknown = new PythonNotFoundError()
318
319  for (let i = windowsRoot ? windowsLauncherIndex : launcherIndex; i < launchers.length; i++) {
320    const launcher = launchers[i]
321    try {
322      if (windowsRoot && windowsProven !== i) {
323        if (!(await provesPython(io, launcher ?? []))) {
324          lastError = new PythonNotFoundError()
325          continue
326        }
327        windowsProven = i
328      }
329
330      const result = await io.run(measureArgv(root, args, launcher), init)
331
332      // The Store alias (AppInstallerPythonRedirector) exits 9009, seen as 49
333      // where the runtime keeps the low byte, prints nothing to stdout, and
334      // writes its notice in the user's language, or straight to the console
335      // and so not to stderr at all. The text is therefore never consulted:
336      // on a Windows install, exit 49 with an empty stdout from the python3 or
337      // python name is the alias. measure.py never exits 49 of its own, so the
338      // one thing this can mistake is a script failure that also printed
339      // nothing, and that costs one more launcher attempt, not a wrong answer.
340      // The probe above already keeps the alias out on Windows; this stays as
341      // the second line of defence.
342      const storeAliasMissing = result.exitCode === WINDOWS_NOT_FOUND_LOW_BYTE
343        && windowsRoot
344        && isStoreAliasName(launcher)
345        && result.stdout.trim() === ''
346
347      if ((result.exitCode === WINDOWS_NOT_FOUND || storeAliasMissing) && i < launchers.length - 1) {
348        lastError = new PythonNotFoundError()
349        continue
350      }
351
352      if (windowsRoot) windowsLauncherIndex = i
353      else launcherIndex = i
354      return result
355    } catch (error) {
356      if (isTimeout(error)) {
357        throw error
358      }
359
360      lastError = error
361    }
362  }
363
364  throw noLauncher(lastError) ? new PythonNotFoundError() : lastError
365}
366
367/**
368 * `measure.py status-bar --json`; 'outdated' when the install has no
369 * such command (it prints usage, not JSON), null when it fails, times out or
370 * prints something else.
371 */
372export async function readStatusBar(
373  io: DataIo,
374  root: TokenOptimizerRoot,
375  sid: string,
376  transcript?: string,
377): Promise<StatusBar | 'outdated' | 'nopython' | null> {
378  const args = statusBarArgs(sid, transcript)
379  let result: { exitCode: number; stdout: string; stderr?: string } | 'nopython' | null = null
380  try {
381    result = await runMeasure(io, root, args, { timeoutMs: STATUS_TIMEOUT_MS })
382  } catch (error) {
383    result = noLauncher(error) ? 'nopython' : null
384  }
385
386  if (result === 'nopython') return 'nopython'
387  if (!result) return null
388  if (result.exitCode !== 0 && io.log) {
389    // Why the status read failed, where `claude --debug` shows it.
390    void attempt(() => io.log!(`token-optimizer status bar: status-bar exited ${result.exitCode}: ${(result.stderr ?? '').trim().slice(0, 300)}`), undefined)
391  }
392  // The JSON is the last line that is one (a stray line printed before it is not a reason to fail).
393  const json = result.stdout.split(/\r?\n/).map(l => l.trim()).filter(l => l.startsWith('{')).pop()
394  // An install without the command prints its usage instead of JSON (or exits 2).
395  // Usage text instead of JSON is an older install; empty output is just a failed read.
396  if (!json) return (result.exitCode === 0 || result.exitCode === 2) && result.stdout.trim() !== '' ? 'outdated' : null
397  return result.exitCode === 0 ? parseStatusBar(json) : null
398}
399
400/** The current git branch; null outside a repository, on a detached HEAD, or without git. */
401export async function readBranch(io: DataIo, cwd: string): Promise<string | null> {
402  const init = cwd ? { cwd, timeoutMs: GIT_TIMEOUT_MS } : { timeoutMs: GIT_TIMEOUT_MS }
403  const result = await attempt(() => io.run(['git', 'branch', '--show-current'], init), null)
404  const branch = result && result.exitCode === 0 ? result.stdout.trim() : ''
405
406  return branch === '' ? null : branch
407}
408
409export type GatherOptions = {
410  /** The live session id when the caller knows it better than `$.session.id()` (a classic SessionStart's `session_id`). */
411  sessionId?: string
412  /** Start over even when the id matches (a clear). */
413  reset?: boolean
414  /** Run the status command (start, 5 s after a turn, row opened). */
415  savings?: boolean
416  /** The session's transcript, so the status command need not look it up. */
417  transcript?: string
418}
419
420/**
421 * The per-session part of a Snapshot. Starts from `previous` only when it
422 * belongs to this session, so nothing carries over a clear. Savings and
423 * the clock facts come from the status command when asked for; when it is not
424 * asked, fails or times out, the last known values stay.
425 */
426/** Only the context figures of a parsed usage, with the reduced flag always present so a stale one is cleared. */
427function contextOf(u: ReturnType<typeof parseUsage>) {
428  return { contextPercent: u.contextPercent, contextTokens: u.contextTokens, contextWindow: u.contextWindow, contextWindowReduced: u.contextWindowReduced === true, contextModelWindow: u.contextModelWindow ?? null }
429}
430
431export async function gather(
432  io: DataIo,
433  previous: TokenOptimizerDesktopSession | null,
434  options: GatherOptions = {},
435): Promise<TokenOptimizerDesktopSession> {
436  const now = await attempt(() => io.now(), Date.now())
437  const sid = cleanId(options.sessionId ?? (await attempt(() => io.sessionId(), '')))
438  const base = options.reset || shouldReset(previous, sid) ? null : previous
439  const cwd = await attempt(() => io.cwd(), '')
440  const home = await readHome(io)
441  const autoCompactWindow = io.envAutoCompactWindow ? await attempt(() => io.envAutoCompactWindow!(), undefined) : undefined
442  const rawUsage = await attempt(() => io.usage(), null)
443  const reported = parseUsage(rawUsage, autoCompactWindow, base?.compactWindow)
444  // A limit does not vanish mid-session: a refresh that comes back without one (right
445  // after a compact, say) keeps the last known value; once that window has renewed, 0%.
446  const keep = (fresh: Limit | null, last: Limit | null | undefined): Limit | null => {
447    if (fresh) return fresh
448    // Kept only until its own renewal: after that the old figure is wrong, and an unreadable
449    // renewal time is no renewal time (either could otherwise stay on screen for good).
450    if (!last || last.resetsAt === null) return null
451    const renews = Date.parse(last.resetsAt)
452    return Number.isFinite(renews) && renews > now ? last : null
453  }
454  const usage = { ...reported, fiveHour: keep(reported.fiveHour, base?.fiveHour), week: keep(reported.week, base?.week) }
455  const sawLimits = Boolean(base?.sawLimits || reported.fiveHour || reported.week)
456  const branch = await readBranch(io, cwd)
457  const quality = await readQuality(io, home, sid)
458
459  let status: StatusBar | 'outdated' | 'nopython' | null = null
460  let notFound = false
461
462  if (options.savings && sid) {
463    const root = await findTokenOptimizerRoot(io, home)
464    notFound = root === null
465    status = root ? await readStatusBar(io, root, sid, options.transcript) : null
466  }
467
468  const kept = {
469    savings: base?.savings ?? null,
470    savingsState: base?.savingsState ?? ('unavailable' as const),
471    savingsReason: base?.savingsReason ?? null,
472    lastRequestEpoch: base?.lastRequestEpoch ?? null,
473    cacheLifetime: base?.cacheLifetime ?? null,
474    compactWindow: base?.compactWindow ?? null,
475    checkpointEpoch: base?.checkpointEpoch ?? null,
476    earlierCheckpoint: base?.earlierCheckpoint ?? null,
477    compactions: base?.compactions ?? null,
478  }
479  const seen = { toolCallsSeen: base?.toolCallsSeen ?? 0, compactionsSeen: base?.compactionsSeen ?? 0 }
480
481  const facts = notFound
482    ? { ...kept, savings: null, savingsState: 'unavailable' as const, savingsReason: NOT_FOUND, checkpointEpoch: null }
483    : status === 'outdated'
484      ? { ...kept, savings: null, savingsState: 'unavailable' as const, savingsReason: OUTDATED }
485    : status === 'nopython'
486      ? { ...kept, savings: null, savingsState: 'unavailable' as const, savingsReason: NO_PYTHON }
487    : status
488      ? {
489          // While savings load, the last known figures stay on show.
490          savings: status.savings ?? (status.savingsState === 'loading' ? kept.savings : null),
491          savingsState: status.savingsState,
492          savingsReason: status.savings ? null : status.savingsReason,
493          lastRequestEpoch: status.lastRequestEpoch ?? kept.lastRequestEpoch,
494          cacheLifetime: status.cacheLifetime ?? kept.cacheLifetime,
495          // An answer with no window means the user has none now: a kept one must not linger.
496          compactWindow: status.compactWindow,
497          checkpointEpoch: status.checkpointEpoch,
498          earlierCheckpoint: status.earlierCheckpoint,
499          compactions: status.compactions ?? kept.compactions,
500        }
501      : kept
502
503  // The higher count wins: the quality cache can lag a compaction that just landed.
504  // Never lower than the band already knew this session (it may have seen the compaction itself).
505  const known = Math.max(
506    'compactions' in facts && facts.compactions != null ? facts.compactions : 0,
507    base?.quality?.compactions ?? 0,
508  )
509  const counted = quality && known > quality.compactions ? { ...quality, compactions: known } : quality
510  // A status answer has already checked the checkpoint file is still on disk, so it wins
511  // over the quality cache, which keeps naming a save after retention removes it.
512  const answered = status !== null && typeof status === 'object'
513  const checkpointEpoch = notFound ? null : answered ? facts.checkpointEpoch : newer(quality?.checkpointEpoch ?? null, facts.checkpointEpoch)
514  const merged = counted && answered ? { ...counted, checkpointEpoch } : counted
515
516  // /autocompact and the autoCompactWindow setting reach the band through Token Optimizer's own
517  // resolver (the status command); when its answer differs from what the first parse assumed, the
518  // context figures are read again against it.
519  const windowNow = smallerCompactWindow(autoCompactWindow, facts.compactWindow)
520  const context = windowNow === smallerCompactWindow(autoCompactWindow, base?.compactWindow) ? usage : { ...usage, ...contextOf(parseUsage(rawUsage, autoCompactWindow, facts.compactWindow)) }
521
522  return {
523    sessionId: sid,
524    gatheredAt: now,
525    quality: merged,
526    ...context,
527    branch,
528    ...facts,
529    // Without a status answer, the newer of the two: the quality cache knows quality saves
530    // the moment they land, the status command also knows stop and compaction saves.
531    ...seen,
532    sawLimits,
533    checkpointEpoch,
534    sheetOpen: base?.sheetOpen ?? false,
535  }
536}
537
538/**
539 * What to store when `fresh` lands on top of `current` (read inside
540 * `update`): keeps a row toggle made while gathering, never across sessions
541 * or a forced reset.
542 */
543export function mergeStored(
544  current: TokenOptimizerDesktopSession | null,
545  fresh: TokenOptimizerDesktopSession,
546  reset = false,
547  savingsRead = true,
548): TokenOptimizerDesktopSession {
549  const sameSession = !reset && current !== null && current.sessionId === fresh.sessionId
550
551  // A refresh that began before a compaction landed must not write its count back down.
552  const counted = sameSession ? Math.max(current.quality?.compactions ?? 0, fresh.quality?.compactions ?? 0) : null
553  const quality = fresh.quality && counted !== null && counted > fresh.quality.compactions ? { ...fresh.quality, compactions: counted } : fresh.quality
554
555  // The band's own counts only grow; a refresh that read them earlier cannot undo a later one.
556  const seen = sameSession
557    ? {
558        toolCallsSeen: Math.max(current.toolCallsSeen ?? 0, fresh.toolCallsSeen ?? 0),
559        compactionsSeen: Math.max(current.compactionsSeen ?? 0, fresh.compactionsSeen ?? 0),
560      }
561    : {}
562
563  // A refresh that did not run the status command only carried its older copy of what that
564  // command reports: a slower savings refresh that landed meanwhile keeps its figures.
565  const statusFacts =
566    sameSession && !savingsRead
567      ? {
568          savings: current.savings,
569          savingsState: current.savingsState,
570          savingsReason: current.savingsReason,
571          earlierCheckpoint: current.earlierCheckpoint,
572          cacheLifetime: current.cacheLifetime ?? fresh.cacheLifetime,
573          lastRequestEpoch: newer(current.lastRequestEpoch, fresh.lastRequestEpoch),
574          checkpointEpoch: newer(current.checkpointEpoch, fresh.checkpointEpoch),
575          compactions:
576            current.compactions == null ? fresh.compactions : fresh.compactions == null ? current.compactions : Math.max(current.compactions, fresh.compactions),
577        }
578      : {}
579
580  return { ...fresh, ...statusFacts, ...seen, quality, sheetOpen: sameSession ? current.sheetOpen : fresh.sheetOpen }
581}
582