SLOPSHOPPER

session-band

Prompt cache status band (c / ctx / rwc / sc / plan limits) with hover help, cold-send guard, keep-warm, /board, /handoff that also picks up handoff files, and…

panebandspinnerguardcommandtoast
★ 1v?MITupdated 2026-10-25IT-BAER/claude-forge/mods/session-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-band
│ ┃ Sessions ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ STATE SESSION CONTEXT CACHE │ session-band │ │ ┃ COST AGENTS ⏺ Read(src/auth.ts) │ Keeping this cache warm until 12:53pm. A │ │ ┃ ○ idle app · fix the f… 97.4k 49 – ⎿ Read 6 lines │ ping reads the cache before it expires. │ │ ┃ └ warm until 12:53pm, 0 ping(s) ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ $0 ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ 1 session · $0.42 total · 0 waiting on you · ⎿ 3 pass, 1 fail │ ┃ cold restarts $0 · keep warm reads the cache │ ┃ before it expires · Esc closes ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /cache │ ⎿ session-band: Session Band: 97.4k tokens in context on opus-5-5, │ ⎿ session-band: No request yet this session, so the cache state is │ ⎿ session-band: Plan limits used: 5h 31%. │ ⎿ session-band: Session cost so far: $0.42. Cold restarts this ses │ ⎿ session-band: Cold-send guard: on for contexts over 150k tokens. │ ⎿ session-band: Settings: /cache ttl 5|60|auto, /cache guard on|of │ │ │ ctx 97.4k │ rwc $0.78 │ sc $0.42 │ 5h 31% h: handoff [ A ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
│ ctx 97.4k │ rwc $0.78 │ sc $0.42 │ 5h 31% h: handoff [ A ] ⟨Claude Code's own drawing⟩
Pane · Sessions
STATE SESSION CONTEXT CACHE COST AGENTS ○ idle app · fix the f… 97.4k 49 – $0.42 └ warm until 12:53pm, 0 ping(s) $0 1 session · $0.42 total · 0 waiting on you · cold restarts $0 · keep warm reads the cache before it expires · Esc closes
README

session-band

A compact prompt-cache status band for Claude Code, with a cold-send guard, keep-warm, a board of all local chats, and handoffs to a fresh chat.

This is a fork of Cache Keeper by Nate Herk (nateherkai/claude-code-mods), MIT licensed. The cache logic, board, guard and handoff flow are his work. See Changes from Cache Keeper for what this fork adds.

<img src="screenshots/band.png" alt="session-band above the prompt" width="686">

The band above the prompt: cache warm for 60 minutes, 342k tokens in context, a cold rewrite would cost about $2.73, the session cost $13 so far, and the 5-hour and weekly plan limits.

Why

Every request re-reads the whole chat. From the prompt cache that costs a tenth of the normal input price. Once the cache expires (5 minutes or 1 hour idle, depending on your plan), the next message writes the whole chat into the cache again at up to 2x the input price. On a large chat that one message can cost a few dollars.

Requirements

  • Claude Code 2.1.287 or later, in the terminal or the Desktop app's Code tab. The VS Code chat does not draw the band; the claude-status extension shows the same values in the VS Code status bar.
  • Mods turned on for your account. claude plugin test in any folder answers "no hooks module to load" when mods can load.
  • Do not install it next to Cache Keeper. Both register the same commands.
  • For autonomous mode: the session-handoff skill from this repository, installed in ~/.claude/skills/session-handoff. The marketplace does not install skills, so copy it by hand (see its README).

Install

/plugin marketplace add IT-BAER/claude-forge
/plugin install session-band@claude-forge

Start a new session afterwards.

The band

● c 60m │ ctx 342k │ rwc $2.73 │ sc $13 │ 5h 84% w 24%

PartMeaning
c 60mPrompt cache state and minutes until it expires. Yellow 5 minutes before expiry, red once cold. While keep-warm runs: ◆ c kept 7:12pm, the time it stops.
ctxTokens in context.
rwcRewrite cost: what writing the context into the cache again would cost if it expires.
scSession cost so far, at API list prices.
crCold restarts: how many sends rewrote an expired cache this session, and what they cost. Shown only after the first one.
5h, w, fw5-hour, weekly and per-model weekly (fw for Fable, the model's initial) plan limits used, each in its own colour. 5h: yellow at 80 %, red at 95 %. Weekly windows follow a daily budget: day n of 7 (counted from the reset) allows n/7 of the week, so day 1 allows 14.3 %. Red once today's budget is used, yellow at 80 % of it. The per-model windows come from the plan usage endpoint (/api/oauth/usage, asked at most every 5 minutes), because the mod API does not pass them.

Hover c, ctx, rwc, sc or cr for a one-line explanation above the band. Each starts with what the label stands for (rwc = rewrite cost: ...), and c names the state in full (kept, warm, cooling, cold). Hover the plan limits for what each window is and when it resets: 5h (5-hour window) resets 1:50pm (in 2h15m) · w (weekly, all models) resets Fri 9:00am (in 3d21h), budget today 57.1%. On a subscription the prices show up as usage against your limits, not as a bill.

Commands

  • /keepwarm [hours|off] keeps this chat's cache warm, 4 hours by default, with a small ping shortly before it would expire.
  • Cold-send guard: a message into a chat over 150k tokens after its cache expired asks first: Send anyway, Compact first, or Cancel.
  • /board shows every local chat in one pane: waiting on you first, then working, then the ones whose cache cools soonest.
  • /handoff (or the handoff button) runs the bundled session-handoff skill, then clears the chat and starts the fresh one from the handoff.
  • The A button at the right end of the band toggles autonomous mode: handoffs are cleared and continued without you.
  • /cache shows status and settings: ttl 5|60|auto, guard on|off, big 150k, alerts [on|off], toasts [on|off].
  • Alerts are off by default. They are the unasked toasts: a big cache about to go cold, and another chat waiting on you. /cache alerts toggles them.
  • Toasts are on by default. /cache toasts off mutes every toast of the band, errors included; the band and footer still show the state. /cache toasts toggles them.

Autonomous mode (A)

Autonomous mode lets one chat work through a long task in several fresh contexts while you are away. Each time Claude ends a turn with a handoff, the band clears the chat and starts the next one from that handoff, without a click from you.

It needs the session-handoff skill. That skill writes the handoff to a file under ~/.claude/handoffs/, so the work state survives the clear and the fresh chat gets a one-line resume prompt. Its consume step marks the file status: consumed, so the band never continues the same handoff twice.

Turn it on

Press A at the right end of the band. A toast confirms it. While A is on, the button is drawn as the primary button and the footer shows autonomous. Press A again to turn it off.

A lasts for the current Claude Code process only. It is not saved, so a restart or a new window starts with A off.

What changes while A is on

  • Each prompt carries one more hidden context block: nobody is at the keyboard, do not ask or wait for "proceed" or "go", decide with your own recommendation and continue. The continuation prompt after a clear ends with the same text. It is not a system prompt section, because the built-in cc-plugin-sec-default skips prompt.compose for installed mods; a turn that starts without a prompt (a task notification) does not get it.
  • Every AskUserQuestion is refused. The refusal tells Claude to pick its recommended option and continue.
  • After a handoff turn, the band does not ask "Clear and continue?". It does that by itself.

The loop

  1. Claude ends a turn and a handoff is ready. That is a handoff file written in this turn (by the session-handoff skill, or any file the band detects as a handoff), or the answer of a /handoff turn.
  2. The band waits until the chat is idle: 3 seconds after the turn end, no permission prompt or question waiting on you, no background agents running, no handoff still queued.
  3. The band runs /clear and sends the resume line as your message: Continue from session handoff: read <file>, consume it with session-handoff, do not re-explore.
  4. The fresh chat consumes the handoff and works. If it ends with a new handoff, the loop goes to step 1.

The band does not tell Claude to write handoffs. A new handoff comes from you (/handoff, the h button), from a hook of your own (for example at a context size), or from the handoff itself, when its remaining steps say to hand off again.

When A turns itself off

EventToast
A turn ends without a handoff and with no background work left. Claude found nothing left to do, or the turn broke off.Autonomous mode off: the turn ended without a handoff.
The turn's answer ends with an afk-shutdown end line ([afk-shutdown] DONE handoff=... or BLOCKED ...). The afk-shutdown watcher counts the session as finished, so continuing would start new work while the PC waits to shut down. The handoff waits for c.Autonomous mode off: the turn ended with the afk-shutdown end line, so this session is finished. The handoff waits for c.
/clear failed. The band stops instead of retrying.Autonomous mode off: clear and continue failed.
A third handoff is ready within 15 minutes, for example a chain of "check again later" handoffs. The band does not continue it; it waits for c.Autonomous mode off: 3 handoffs in 15 minutes, possible loop. The handoff waits for c.

Background work keeps A on when a turn ends without a handoff: a running subagent, or a background shell (started with run_in_background, or moved to the background by the Bash timeout). Claude Code wakes Claude when the task finishes, and that turn decides. The band forgets a shell when a turn starts with its task notification, or 2 hours after it started, because a notification Claude reads inside a busy turn is not visible to the band. Classic Stop hooks list background tasks too, but they do not reach a plugin you install where an organization manages Claude Code, so the band does not use them.

Before you leave a chat on A

  • Run the chat in auto mode, or with the permission rules it needs. Permission prompts still follow the permission mode, and the loop waits while one is open.
  • The A prompt tells Claude not to wait for approval. Where your CLAUDE.md asks for a confirmation first (push, delete, deploy), Claude now decides by itself. To block an action for sure, use a deny rule in the permission settings, not an instruction.

Changes from Cache Keeper

  • Short band labels (c, rwc, sc, w) so the band fits next to the prompt, session cost before the plan limits.
  • Hover help for the short labels. The help row opens above the band, so the hovered text does not move.
  • Handoff files: when Claude writes a session-handoff.md, a restart-packet.md (also with a suffix, like session-handoff-pve.md) or a file under handoffs/, the band shows handoff running while Claude still works, and offers to clear and continue from that file once the turn ends. A message you send mid-turn does not drop it. Any header format works; only a header marked status: consumed (or another non-active status) is skipped. If a handoff turn ends on a short answer (a Stop hook added a tail), the last handoff file written in the session is used instead. The fresh chat gets a short "read this file" prompt instead of the whole text.
  • Renamed to session-band. Data lives in ~/.claude/mods-data/session-band/.
  • Earlier versions of this fork were called cache-status. To switch, run /plugin uninstall cache-status@claude-forge, then install session-band@claude-forge and restart each chat. Nothing reads ~/.claude/mods-data/cache-status/ any more, so you can delete that folder once no chat runs the old mod.

Where the data lives

Everything stays on your machine, under ~/.claude/mods-data/. The mod makes no network calls of its own. Keep-warm pings are small model requests, sent only while /keepwarm is on.

License

MIT. See LICENSE. Original work copyright Nate Herk.

Source 4 files
hooks/register.mjs 1316 lines
1// Session Band (fork of Cache Keeper by Nate Herk): watches this session's prompt cache, keeps big caches warm on
2// request, refuses a cold send without asking first, and shows every local
3// session on one board (/board).
4//
5// Why: each request re-reads the whole context. From the cache that costs about
6// a tenth of normal input. Once the cache expires (1 hour idle on a subscription,
7// 5 minutes on the default API TTL), the next message writes the whole context
8// again at 1.25x to 2x input. A cache read also restarts the timer, so a tiny
9// ping before expiry costs a fraction of a rewrite.
10
11import { rewriteCost, requestCost, totalInput, cachedShare, priceFor } from './pricing.mjs'
12import { tokens, usd, minutes, clock, clip, basename, pad } from './fmt.mjs'
13import { makeMasker } from './privacy.mjs'
14
15const MIN = 60000
16const HEARTBEAT_EVERY = 30000
17const OUTSIDE_EVERY = 2000 // command files and handoff state for the VS Code extension
18const PANE = 'cache-board'
19
20// This session
21const S = {
22  id: '',
23  cwd: '',
24  label: '',
25  model: '',
26  lastActivity: 0, // last main-loop request or keep-warm ping that touched the cache
27  ctx: 0,
28  window: 0,
29  costUsd: 0,
30  ttlMin: 60,
31  ttlSource: 'default',
32  coldRestarts: [],
33  working: false,
34  turnId: '', // the main loop's running (or last) turn
35  waitingSince: 0,
36  waitingFor: '',
37  tool: '',
38  lastTurnEnd: 0,
39  keepWarm: false,
40  keepWarmUntil: 0,
41  pings: 0,
42  pingUsd: 0,
43  lastPingAt: 0,
44  warnedFor: 0,
45  agentsRunning: 0,
46  rateLimits: [],
47}
48
49const settings = { bigTokens: 150000, guard: true, ttlMin: 0, alerts: false, toasts: true, keepWarmHours: 4 }
50const names = { cache: 'cache', keepwarm: 'keepwarm', board: 'board', handoff: 'handoff' }
51
52let now = 0
53let home = ''
54let claudeDir = './.claude' // CLAUDE_CONFIG_DIR, else ~/.claude: one profile's data per account
55let lastHeartbeat = 0
56let rec = { on: false, strict: false }
57let mask = (s) => s
58let fleet = [] // heartbeats of every session, this one included
59const alerted = new Map() // sessionId -> state or warning key already announced
60let paneOpen = false
61let lastStepTotal = 0 // the previous main-loop request's input; a drop below 60 % is a compaction or /clear
62let modelLimits = [] // per-model weekly windows (Fable, ...) from the usage endpoint
63let usageAskedAt = -Infinity
64let handoffPending = false
65let lastLiveHandoff = '' // handoff state in the last live file
66let lastCommandAt = 0 // newest command file already taken
67let outsideBusy = false
68let endedId = '' // the chat session.end closed: never written as live again
69
70// The handoff flow. When /session-handoff runs (the band's button, /handoff, a
71// typed command, or Claude calling the skill), the answer of the turn it starts
72// is captured and saved to a file. "clear and continue" then runs /clear and
73// sends the handoff as the fresh chat's first prompt.
74const HANDOFF_SKILL = /(^|:)session-handoff$/
75const H = {
76  armed: false,
77  notTurn: '', // a turn already running when the handoff was queued: not the handoff's
78  askAfter: false, // /handoff asks "clear and continue?" once the handoff is in
79  text: '',
80  path: '',
81  file: '', // a handoff file Claude wrote with Write/Edit this turn (no button, no command)
82  lastFile: '', // the last handoff file written this session: the fallback when a handoff turn ends on a short answer
83  fromFile: false, // H.text came from that file: the fresh chat reads it by path
84  continuing: false,
85  resuming: false, // the last prompt was a resume line: its skill call consumes, not creates
86  announce: false, // a handoff file caught mid-turn: its toast waits for the turn end
87}
88// Clear and continue is offered only once Claude has stopped working
89const ready = () => !!H.text && !S.working
90const RESUME_LINE = /^\s*Continue from session handoff:/i
91
92// Autonomous mode (the band's A): each ready handoff is cleared and continued
93// without you, until a turn ends without one. Lasts for this process.
94let auto = false
95const AUTO_GRACE = 3000 // after the turn end: turn.complete is still taking the handoff file
96const AUTO_PROMPT = 'Autonomous mode is on: nobody is at the keyboard. Do not ask the user or wait for approval, "proceed" or "go". Where you would ask or offer a choice, decide with your own recommendation and continue.'
97const AUTO_ASK = 'Autonomous mode is on and nobody can answer. Pick your recommended option for each question and continue.'
98// Per-prompt context: the built-in cc-plugin-sec-default skips prompt.compose for installed mods
99const withAuto = (e) => (auto ? { ...e, context: [...(e.context ?? []), AUTO_PROMPT] } : e)
100// Every band toast; /cache toasts off mutes them all, errors included (the band still shows the state)
101function toast($, text, opts) {
102  if (settings.toasts) $.ui.toast(text, opts)
103}
104// Loop stop: the third ready handoff within 15 minutes turns A off instead of continuing
105const AUTO_LOOP = 3
106const AUTO_LOOP_MS = 15 * 60000
107let autoRuns = [] // when A cleared and continued, newest last
108// The afk-shutdown watcher counts a session finished by this last answer line; continuing would start new work
109const AFK_END = /\n?\s*\[afk-shutdown\] (?:DONE|BLOCKED) handoff=\S+[^\n]*\s*$/
110// Background shells: a turn that waits for one does not end the loop. An id goes when a turn starts
111// with its notification, or after AUTO_BG_MS (a notification read inside a busy turn goes unseen).
112const AUTO_BG_MS = 2 * 3600000
113const BG_STARTED = /(?:running in background with ID: |moved to the background \(ID: )(\w+)/
114const bgShells = new Map() // task id -> started at
115
116async function setAuto($, on, why) {
117  auto = on
118  autoRuns = []
119  if (why) toast($, why, { timeoutMs: 10000 })
120  $.ui.invalidate('ui.render')
121  await heartbeat($, true)
122}
123
124function waitsForWork() {
125  for (const [id, at] of bgShells) if (now - at >= AUTO_BG_MS) bgShells.delete(id)
126  return S.agentsRunning > 0 || bgShells.size > 0
127}
128
129async function autoStep($) {
130  if (!auto || !ready() || H.continuing || handoffPending || S.waitingSince || S.agentsRunning) return
131  if (now - S.lastTurnEnd < AUTO_GRACE) return
132  autoRuns = autoRuns.filter((t) => now - t < AUTO_LOOP_MS)
133  if (autoRuns.length >= AUTO_LOOP - 1) return setAuto($, false, `Autonomous mode off: ${AUTO_LOOP} handoffs in ${AUTO_LOOP_MS / 60000} minutes, possible loop. The handoff waits for c.`)
134  autoRuns.push(now)
135  await clearAndContinue($)
136  // /clear refused: stop instead of retrying every few seconds
137  if (H.text) await setAuto($, false, 'Autonomous mode off: clear and continue failed.')
138}
139
140// session-handoff.md, restart-packet.md, suffixed names (session-handoff-pve.md), or any .md under /handoffs/
141const HANDOFF_FILE = /[^"'\s]*(?:(?:session-handoff|restart-packet)[^"'\s/]*\.md|\/handoffs\/[^"'\s]*\.md)/
142
143// A shell path as an absolute one: Git Bash /d/x is D:/x, ~ is home, relative is under dir
144function shellPath(p, dir) {
145  p = p.replace(/\\/g, '/').replace(/^\/([a-z])\//i, (_, d) => d.toUpperCase() + ':/')
146  if (p.startsWith('~/')) return home.replace(/\\/g, '/') + p.slice(1)
147  if (/^[a-z]:\//i.test(p) || p.startsWith('/')) return p
148  return `${dir.replace(/\\/g, '/').replace(/\/$/, '')}/${p.replace(/^\.\//, '')}`
149}
150
151const SHELL_WRITE = />>?|\btee\b|\bsed\s+-i|\b(?:Set|Add)-Content\b|\bOut-File\b/i
152const SHELL_CD = /^\s*(?:cd|Set-Location)\s+['"]?([^'"\s]+)['"]?\s*$/i
153
154// The handoff file a Bash or PowerShell command writes: a path after >, tee, sed -i,
155// Set-Content, Add-Content or Out-File in one command step. shortcut: no quote-aware splitting.
156function shellHandoffWrite(command) {
157  let dir = S.cwd
158  for (const step of command.split(/&&|\|\|?|;|\n/)) {
159    const cd = SHELL_CD.exec(step)
160    if (cd) {
161      dir = shellPath(cd[1], dir)
162      continue
163    }
164    const w = SHELL_WRITE.exec(step)
165    const m = w && HANDOFF_FILE.exec(step.slice(w.index + w[0].length).replace(/\\/g, '/'))
166    if (m) return shellPath(m[0], dir)
167  }
168  return ''
169}
170
171// Notes a write to a handoff file; true when the write was one
172function noteHandoffFile(e) {
173  if (e.tool === 'Bash' || e.tool === 'PowerShell') {
174    const path = shellHandoffWrite(String((e.input && e.input.command) || e.command || ''))
175    if (path) H.file = H.lastFile = path
176    return !!path
177  }
178  if (e.tool !== 'Write' && e.tool !== 'Edit') return false
179  let raw = ''
180  try {
181    raw = JSON.stringify(e.input || e.args || e.params || e)
182  } catch {
183    return false
184  }
185  const m = HANDOFF_FILE.exec(raw.replace(/\\\\/g, '/'))
186  if (m) H.file = H.lastFile = m[0]
187  return !!m
188}
189
190// The handoff file an answer offers again after a later message made it out of date:
191// "Continue from session handoff: read <path>"
192const OFFERED = /Continue from session handoff:\s*read\s+`?([^`"'\s,]+\.md)/i
193function offeredHandoff(answer) {
194  const m = OFFERED.exec(String(answer || ''))
195  return m && HANDOFF_FILE.test(m[1].replace(/\\/g, '/')) ? shellPath(m[1], S.cwd) : ''
196}
197
198// A header status other than active (consumed) retires a handoff file.
199// Free-hand handoffs often lack the skill's <!-- handoff: --> header.
200function retired(text) {
201  const status = /status:\s*(\w+)/i.exec(text.split('\n', 3).join('\n'))
202  return !!status && status[1].toLowerCase() !== 'active'
203}
204
205async function fileRetired($, path) {
206  try {
207    return !(await $.fs.exists(path)) || retired(await $.fs.read(path))
208  } catch {
209    return false
210  }
211}
212
213// A handoff file becomes the ready handoff unless its header retires it.
214// early: right after the write, mid-turn; the turn end checks the file again.
215async function captureHandoffFile($, path = H.file, early = false) {
216  if (!early) H.file = ''
217  try {
218    if (!path || !(await $.fs.exists(path))) return false
219    const text = (await $.fs.read(path)).replace(/^/, '').trim()
220    if (text.length < 200 || retired(text)) return false
221    const known = H.fromFile && H.path === path && H.text === text
222    H.text = text
223    H.path = path
224    H.fromFile = true
225    if (!known) H.announce = true
226    if (early) {
227      $.ui.invalidate('ui.render')
228      return true
229    }
230    if (H.announce) toast($, `Handoff file written: ${path}. Press c on the band or type /${names.handoff} continue to clear and continue.`, { timeoutMs: 15000 })
231    H.announce = false
232    const askAfter = H.askAfter
233    H.armed = false
234    H.notTurn = ''
235    H.askAfter = false
236    // Off the hook: the turn is ending, and a dialog would hold it open
237    if (askAfter) $.clock.after(300, () => offerContinue($).catch(() => {}))
238    return true
239  } catch {
240    return false
241  }
242}
243
244function armHandoff(insideTurn) {
245  H.armed = true
246  H.notTurn = insideTurn ? '' : S.working ? S.turnId : ''
247}
248
249// The handoff without any preamble Claude put before its heading
250function handoffBody(answer) {
251  const text = String(answer || '').trim()
252  const i = text.indexOf('# Session Handoff')
253  return i > 0 ? text.slice(i) : text
254}
255
256function fileStamp(ms) {
257  const d = new Date(ms)
258  const two = (n) => String(n).padStart(2, '0')
259  return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}-${two(d.getHours())}${two(d.getMinutes())}`
260}
261
262async function saveHandoff($, text) {
263  const project = basename(S.cwd).replace(/[^A-Za-z0-9-]+/g, '-') || 'session'
264  const path = `${claudeDir}/mods-data/session-band/handoffs/${fileStamp(now)}-${project}-${S.id.slice(0, 8)}.md`.replace(/\\/g, '/')
265  await $.fs.write(path, text + '\n')
266  return path
267}
268
269async function captureHandoff($, e) {
270  H.armed = false
271  H.notTurn = ''
272  const askAfter = H.askAfter
273  H.askAfter = false
274  const body = e.reason === 'answer' ? handoffBody(e.answer) : ''
275  if (body.length < 200) {
276    // A Stop hook can end the turn on a short tail; the skill's file still holds the handoff
277    H.askAfter = askAfter
278    if (await captureHandoffFile($, H.lastFile)) return
279    H.askAfter = false
280    toast($, 'The handoff turn ended without a handoff, so nothing was saved.', { timeoutMs: 8000 })
281    return
282  }
283  H.text = body
284  try {
285    H.path = await saveHandoff($, body)
286  } catch {
287    H.path = ''
288  }
289  const saved = H.path ? `Handoff saved to ${H.path}.` : 'Handoff captured (the backup file could not be written).'
290  toast($, `${saved} Press c on the band or type /${names.handoff} continue to clear and continue.`, { timeoutMs: 15000 })
291  // Off the hook: the turn is ending, and a dialog would hold it open
292  if (askAfter) $.clock.after(300, () => offerContinue($).catch(() => {}))
293}
294
295async function offerContinue($) {
296  if (!H.text || auto) return
297  let answer = ''
298  try {
299    answer = await $.ui.ask('Handoff saved. Clear this chat and continue with it in a fresh context?', ['Clear and continue', 'Keep this chat'])
300  } catch {
301    return // dismissed: the band button and /handoff continue still work
302  }
303  if (answer === 'Clear and continue') await clearAndContinue($)
304}
305
306function continuationPrompt() {
307  if (H.fromFile) return `Continue from session handoff: read ${H.path}, consume it with session-handoff, do not re-explore.`
308  const where = H.path ? ` (saved at ${H.path})` : ''
309  return `Handoff from my previous session${where}:\n\n${H.text}`
310}
311
312async function clearAndContinue($) {
313  if (H.continuing) return
314  if (!H.text) {
315    toast($, `No handoff ready. Press h on the band or type /${names.handoff} first.`, { timeoutMs: 8000 })
316    return
317  }
318  if (S.working) {
319    toast($, 'Claude is still working. Clear and continue once this turn ends.', { timeoutMs: 8000 })
320    return
321  }
322  // our own submit skips our prompt.submit hook, so the A text rides in the prompt
323  const text = auto ? `${continuationPrompt()}\n\n${AUTO_PROMPT}` : continuationPrompt()
324  const path = H.path
325  H.continuing = true
326  $.ui.invalidate('ui.render')
327  try {
328    await $.command.run({ command: 'clear', args: '' })
329  } catch (err) {
330    H.continuing = false
331    $.ui.invalidate('ui.render')
332    toast($, 'Could not run /clear: ' + clip(String((err && err.message) || err), 100) + (path ? ` The handoff is saved at ${path}.` : ''), { timeoutMs: 10000 })
333    return
334  }
335  H.text = ''
336  H.path = ''
337  H.fromFile = false
338  // our own prompt.submit hook never sees this submission
339  H.resuming = true
340  try {
341    await $.prompt.submit({ text, asUser: true })
342  } catch {
343    // Not sent: leave it in the prompt box for one Enter
344    let filled = false
345    try {
346      filled = !!(await $.prompt.fill({ text })).isFilled
347    } catch {
348      filled = false
349    }
350    toast($, filled ? 'Cleared. The handoff is in the prompt box: press Enter to send it.' : `Cleared, but the handoff could not be sent.${path ? ` It's saved at ${path}.` : ''}`, { timeoutMs: 10000 })
351  } finally {
352    H.continuing = false
353    $.ui.invalidate('ui.render')
354  }
355}
356
357// Runs the /session-handoff skill as if you typed it. The engine queues it
358// until Claude finishes the current turn.
359async function runHandoff($) {
360  if (handoffPending) {
361    toast($, 'Session handoff is already queued.')
362    return
363  }
364  try {
365    const commands = await $.command.list()
366    const cmd = commands.find((c) => c.name === 'session-handoff') || commands.find((c) => HANDOFF_SKILL.test(c.name))
367    if (!cmd) {
368      H.askAfter = false
369      toast($, 'No /session-handoff skill in this session.', { timeoutMs: 8000 })
370      return
371    }
372    handoffPending = true
373    armHandoff(false)
374    $.ui.invalidate('ui.render')
375    toast($, S.working ? 'Session handoff queued: it runs when Claude finishes this turn.' : 'Running /session-handoff.')
376    await $.command.run({ command: cmd.name, args: '' })
377  } catch (err) {
378    H.armed = false
379    H.askAfter = false
380    toast($, 'Could not start /session-handoff: ' + clip(String((err && err.message) || err), 100), { timeoutMs: 8000 })
381  } finally {
382    handoffPending = false
383    $.ui.invalidate('ui.render')
384  }
385}
386
387function ttlMin() {
388  return settings.ttlMin || S.ttlMin
389}
390
391// Plan limit windows as the API reports them: five_hour, seven_day, spend_limit;
392// a per-model weekly window takes its model's initial ("fw" for Fable)
393const LIMIT_LABEL = { five_hour: '5h', seven_day: 'w', spend_limit: 'spend' }
394const limitLabel = (l) => LIMIT_LABEL[l.kind] || (l.model ? `${l.model[0].toLowerCase()}w` : l.kind)
395const LIMIT_NAME = { five_hour: '5-hour window', seven_day: 'weekly, all models', spend_limit: 'spend limit' }
396const limitName = (l) => LIMIT_NAME[l.kind] || (l.model ? `weekly, ${l.model} only` : '')
397
398function limitsText(limits, sep = ' · ') {
399  return limits.map((l) => `${limitLabel(l)} ${Math.round(l.percentUsed)}%`).join(sep)
400}
401
402// A weekly window's budget up to the end of today: day n of 7, counted from its reset, allows n/7 of it.
403// null for the 5-hour and spend windows, and for a weekly window without a reset time.
404const DAY = 24 * 60 * MIN
405function weekBudget(l, at) {
406  if ((l.kind !== 'seven_day' && !l.model) || !l.resetsAt) return null
407  const daysLeft = Math.min(6, Math.max(0, Math.floor((Date.parse(l.resetsAt) - at) / DAY)))
408  return ((7 - daysLeft) / 7) * 100
409}
410
411// Red at today's budget, yellow at 80 % of it; without a budget red at 95 %, yellow at 80 %
412function limitColor(l, at) {
413  const used = l.percentUsed || 0
414  const budget = weekBudget(l, at)
415  const [red, yellow] = budget === null ? [95, 80] : [budget, 0.8 * budget]
416  return used >= red ? 'red' : used >= yellow ? 'yellow' : null
417}
418
419// Each window's name and reset: "5h (5-hour window) resets 1:50pm (in 2h15m) · w (weekly, all models) resets Fri 9:00am (in 3d21h), budget today 57.1%"
420const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
421function resetsText(limits, at) {
422  return limits.map((l) => {
423    const name = limitName(l) ? `${limitLabel(l)} (${limitName(l)})` : limitLabel(l)
424    if (!l.resetsAt) return name
425    const t = Date.parse(l.resetsAt)
426    const left = t - at
427    const day = left >= DAY ? DAYS[new Date(t).getDay()] + ' ' : ''
428    const span = left <= 0 ? 'due' : left >= DAY ? `in ${Math.floor(left / DAY)}d${Math.floor((left % DAY) / (60 * MIN))}h` : `in ${minutes(left)}`
429    const budget = weekBudget(l, at)
430    return `${name} resets ${day}${clock(t)} (${span})${budget === null ? '' : `, budget today ${+budget.toFixed(1)}%`}`
431  }).join(' · ')
432}
433
434function allLimits() {
435  return [...S.rateLimits, ...modelLimits]
436}
437
438// The engine hands mods only five_hour, seven_day and spend_limit; per-model
439// weekly windows are rows of kind weekly_scoped in the usage endpoint's limits[].
440// Undocumented: a changed shape or failed request leaves the last rows.
441const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
442const USAGE_EVERY = 5 * MIN
443
444async function refreshModelLimits($) {
445  if (now - usageAskedAt < USAGE_EVERY) return
446  usageAskedAt = now
447  try {
448    const auth = await $.session.authorize()
449    if (!auth || auth.kind !== 'bearer') return
450    const r = await $.http.fetch(USAGE_URL, { auth: auth.handle, headers: { 'anthropic-beta': 'oauth-2025-04-20' } })
451    if (!r.ok) return
452    const rows = JSON.parse(r.text).limits
453    if (!Array.isArray(rows)) return
454    modelLimits = rows
455      .filter((l) => l && l.kind === 'weekly_scoped' && typeof l.percent === 'number' && typeof l.scope?.model?.display_name === 'string')
456      .map((l) => {
457        const model = l.scope.model.display_name
458        const t = Date.parse(l.resets_at)
459        return { kind: 'weekly_' + model.toLowerCase(), model, percentUsed: l.percent, ...(t ? { resetsAt: new Date(Math.round(t / MIN) * MIN).toISOString() } : {}) }
460      })
461    $.ui.invalidate('ui.render')
462    await heartbeat($, true)
463  } catch {
464    // endpoint unavailable: keep the last rows
465  }
466}
467
468function limitTone(color, extra) {
469  if (color === 'red') return { ...extra, color: 'red', bold: true }
470  if (color === 'yellow') return { ...extra, color: 'yellow' }
471  return { ...extra, dimColor: true }
472}
473
474function money(v) {
475  return rec.strict ? '$•••' : usd(v)
476}
477
478function msLeft(lastActivity, ttl) {
479  if (!lastActivity) return null
480  return ttl * MIN - (now - lastActivity)
481}
482
483function cacheState(hb) {
484  const left = msLeft(hb.lastActivity, hb.ttlMin)
485  if (left === null) return { kind: 'unknown', left: 0 }
486  if (hb.keepWarm) return { kind: 'kept', left }
487  if (left <= 0) return { kind: 'cold', left }
488  if (left <= 5 * MIN) return { kind: 'cooling', left }
489  return { kind: 'warm', left }
490}
491
492function myHeartbeat() {
493  const coldUsd = S.coldRestarts.reduce((a, c) => a + c.usd, 0)
494  let state = 'idle'
495  if (S.waitingSince && now - S.waitingSince > 5000) state = 'waiting'
496  else if (S.working) state = 'working'
497  return {
498    id: S.id,
499    label: S.label,
500    cwd: S.cwd,
501    model: S.model,
502    state,
503    waitingFor: S.waitingFor,
504    tool: S.tool,
505    ctx: S.ctx,
506    window: S.window,
507    ttlMin: ttlMin(),
508    lastActivity: S.lastActivity,
509    keepWarm: S.keepWarm,
510    keepWarmUntil: S.keepWarmUntil,
511    pings: S.pings,
512    pingUsd: S.pingUsd,
513    costUsd: S.costUsd,
514    coldCount: S.coldRestarts.length,
515    coldUsd,
516    agentsRunning: S.agentsRunning,
517    lastTurnEnd: S.lastTurnEnd,
518    updatedAt: now,
519  }
520}
521
522async function registerCommand($, name, description, argumentHint, immediate) {
523  const spec = immediate ? { name, description, argumentHint, immediate: true } : { name, description, argumentHint }
524  try {
525    await $.command.register(spec)
526    return name
527  } catch {
528    try {
529      await $.command.register({ ...spec, name: 'ck-' + name })
530      return 'ck-' + name
531    } catch {
532      return null
533    }
534  }
535}
536
537async function readRecording($) {
538  try {
539    const path = claudeDir + '/mods-data/recording.json'
540    if (!(await $.fs.exists(path))) {
541      rec = { on: false, strict: false }
542    } else {
543      const flag = JSON.parse(await $.fs.read(path))
544      rec = { on: !!flag.on, strict: !!flag.on && !!flag.strict }
545    }
546  } catch {
547    rec = { on: false, strict: false }
548  }
549  mask = rec.on ? makeMasker({ strict: rec.strict }) : (s) => s
550}
551
552async function heartbeat($, force) {
553  if (!S.id) return
554  if (!force && now - lastHeartbeat < 5000) return
555  lastHeartbeat = now
556  try {
557    const agents = await $.agent.list()
558    S.agentsRunning = agents.filter((a) => a.status === 'running').length
559  } catch {
560    // agent list unavailable: keep the last count
561  }
562  const hb = myHeartbeat()
563  await $.store.set('hb:' + S.id, hb)
564  await writeLive($, hb, false)
565}
566
567// One file per session for tools outside Claude Code (the VS Code status bar
568// extension): the heartbeat plus plan limits, rewrite price and surfaces.
569async function writeLive($, hb, ended) {
570  if (!home || !hb.id) return
571  try {
572    let surfaces = []
573    try {
574      surfaces = await $.session.surfaces()
575    } catch {
576      // surfaces unavailable: the reader falls back to matching the cwd
577    }
578    lastLiveHandoff = handoffState()
579    const live = { ...hb, surfaces, rateLimits: allLimits(), rewriteUsd: rewriteCost(S.ctx, S.model, ttlMin()), bigTokens: settings.bigTokens, masked: rec.strict, handoff: lastLiveHandoff, auto, ended }
580    await $.fs.write(outsidePath('live', hb.id), JSON.stringify(live))
581  } catch {
582    // a failed write only leaves the outside readers stale
583  }
584}
585
586// A chat this process enters (launch, --resume, /clear, /resume) starts with
587// nothing in memory: context, cost and limits come from the engine (local
588// estimate, no request); a reopened chat also brings its cache time and an
589// active handoff file it wrote earlier.
590async function restoreSession($) {
591  try {
592    const u = await $.session.usage({ breakdown: 'summary' })
593    const c = u.context || {}
594    S.ctx = c.tokens || (c.breakdown && c.breakdown.totalTokens) || S.ctx
595    if (c.window) S.window = c.window
596    if (u.cost) S.costUsd = u.cost.usd
597    if (Array.isArray(u.rateLimits) && u.rateLimits.length) S.rateLimits = u.rateLimits
598  } catch {
599    // usage unavailable: the first request fills it in
600  }
601  let messages = []
602  try {
603    messages = await $.session.messages()
604  } catch {
605    // no messages: nothing more to restore
606  }
607  if (messages.length) {
608    S.lastActivity = await lastResponseAt($)
609    for (const m of messages) for (const t of m.toolUses || []) noteHandoffFile(t)
610    H.file = ''
611    if (H.lastFile) await captureHandoffFile($, H.lastFile)
612  }
613  await heartbeat($, true)
614}
615
616// When the transcript's last model response was written. Not the file's mtime:
617// a resume appends rows. Claude Code names the folder after the launch cwd.
618async function lastResponseAt($) {
619  const path = `${claudeDir}/projects/${S.cwd.replace(/[^A-Za-z0-9]/g, '-')}/${S.id}.jsonl`.replace(/\\/g, '/')
620  let lines = []
621  try {
622    lines = (await $.fs.read(path)).split('\n')
623  } catch {
624    return 0 // no transcript there: the cache state stays unknown
625  }
626  for (let i = lines.length - 1; i >= 0; i--) {
627    if (!lines[i].includes('"assistant"')) continue
628    try {
629      const row = JSON.parse(lines[i])
630      if (row.type === 'assistant' && row.timestamp) return Date.parse(row.timestamp) || 0
631    } catch {
632      // a half-written last line
633    }
634  }
635  return 0
636}
637
638// /clear, /resume and /branch go on under a new id without a session.start, and
639// classic.SessionStart never reaches a mod: follow $.session.id() instead.
640async function followSessionId($) {
641  let id = ''
642  try {
643    id = await $.session.id()
644  } catch {
645    return
646  }
647  if (!id || id === S.id || id === endedId) return
648  S.id = id
649  S.label = basename(S.cwd)
650  S.lastActivity = 0
651  S.keepWarm = false
652  H.armed = false
653  H.file = H.lastFile = '' // the previous chat's handoff file is not this chat's
654  H.announce = false
655  await restoreSession($)
656}
657
658function outsidePath(dir, id) {
659  return `${claudeDir}/mods-data/session-band/${dir}/${id}.json`.replace(/\\/g, '/')
660}
661
662// What the band's handoff button shows, in the order the band picks it
663function handoffState() {
664  if (H.continuing) return 'clearing'
665  if (ready()) return 'ready'
666  if (handoffPending) return 'queued'
667  // a handoff file written mid-turn waits for the turn end
668  if (H.armed || (H.file && H.text && H.path === H.file)) return 'running'
669  return 'idle'
670}
671
672// The VS Code extension's handoff buttons: one command file per session, marked
673// done instead of deleted. Old commands are dropped so a reload never replays one.
674async function applyFileCommand($) {
675  const path = outsidePath('commands', S.id)
676  let c
677  try {
678    if (!(await $.fs.exists(path))) return
679    c = JSON.parse(await $.fs.read(path))
680  } catch {
681    return
682  }
683  if (!c || c.doneAt || !c.at || c.at <= lastCommandAt) return
684  lastCommandAt = c.at
685  await $.fs.write(path, JSON.stringify({ ...c, doneAt: now }))
686  if (now - c.at > 30000) return
687  // not awaited: a queued handoff waits for the turn to end
688  if (c.cmd === 'handoff') runHandoff($).catch(() => {})
689  else if (c.cmd === 'continue') clearAndContinue($).catch(() => {})
690}
691
692async function outsideStep($) {
693  if (!home || outsideBusy) return
694  outsideBusy = true
695  try {
696    now = await $.clock.now()
697    await followSessionId($)
698    if (!S.id) return
699    await applyFileCommand($)
700    // another chat consumed (or removed) the ready handoff's file
701    if (H.text && H.fromFile && !H.continuing && (await fileRetired($, H.path))) {
702      H.text = ''
703      H.path = ''
704      H.fromFile = false
705      $.ui.invalidate('ui.render')
706    }
707    await autoStep($)
708    if (handoffState() !== lastLiveHandoff) await heartbeat($, true)
709  } finally {
710    outsideBusy = false
711  }
712}
713
714async function readFleet($) {
715  const keys = (await $.store.keys()).filter((k) => k.startsWith('hb:'))
716  const list = []
717  for (const k of keys) {
718    const hb = await $.store.get(k)
719    if (!hb || typeof hb !== 'object') continue
720    if (hb.id === S.id) continue
721    // a session that stopped heartbeating an hour ago has ended or crashed
722    if (now - (hb.updatedAt || 0) > 60 * MIN) {
723      await $.store.delete(k)
724      continue
725    }
726    list.push({ ...hb, stale: now - (hb.updatedAt || 0) > 3 * MIN })
727  }
728  list.push({ ...myHeartbeat(), self: true })
729  fleet = list
730}
731
732// Commands another session's board sent this one, through the shared store
733async function applyRemoteCommands($) {
734  const c = await $.store.get('cmd:' + S.id)
735  if (!c) return
736  await $.store.delete('cmd:' + S.id)
737  if (c.keepWarm === true) startKeepWarm($, settings.keepWarmHours)
738  if (c.keepWarm === false) stopKeepWarm($, 'stopped from the board')
739}
740
741function startKeepWarm($, hours) {
742  S.keepWarm = true
743  S.keepWarmUntil = now + hours * 60 * MIN
744  toast($, `Keeping this cache warm until ${clock(S.keepWarmUntil)}. A ping reads the cache before it expires.`)
745}
746
747function stopKeepWarm($, why) {
748  if (!S.keepWarm) return
749  S.keepWarm = false
750  toast($, `Keep warm off (${why}). ${S.pings} ping(s), ${money(S.pingUsd)}.`, { timeoutMs: 8000 })
751}
752
753async function keepWarmStep($) {
754  if (!S.keepWarm) return
755  if (now >= S.keepWarmUntil) return stopKeepWarm($, 'time limit reached')
756  if (S.working || !S.lastActivity) return
757  const ttl = ttlMin()
758  const margin = ttl >= 60 ? 8 * MIN : 90000
759  if (now - S.lastActivity < ttl * MIN - margin) return
760  let reply = null
761  try {
762    reply = await $.model.fork({ prompt: 'session-band keep-alive ping. Reply with only: ok' })
763  } catch {
764    reply = null
765  }
766  if (!reply || !reply.usage) {
767    return stopKeepWarm($, 'the ping got no answer, so the cache may already be cold')
768  }
769  const u = reply.usage
770  S.pings += 1
771  S.lastPingAt = now
772  S.pingUsd += requestCost(u, S.model, ttl)
773  // A ping that writes instead of reading did not hit the cache: stop paying for it
774  if ((u.cache_creation_input_tokens || 0) > 0.1 * Math.max(1, u.cache_read_input_tokens || 0)) {
775    return stopKeepWarm($, `the ping wrote ${tokens(u.cache_creation_input_tokens)} tokens instead of reading the cache`)
776  }
777  S.lastActivity = now
778}
779
780function warnStep($) {
781  if (!settings.alerts) return
782  for (const hb of fleet) {
783    if (hb.stale || hb.keepWarm || (hb.ctx || 0) < settings.bigTokens) continue
784    const st = cacheState(hb)
785    if (st.kind !== 'cooling') continue
786    const key = 'cool:' + hb.lastActivity
787    if (alerted.get(hb.id) === key) continue
788    alerted.set(hb.id, key)
789    const cost = money(rewriteCost(hb.ctx, hb.model, hb.ttlMin))
790    const who = hb.self ? 'This session' : `"${mask(hb.label)}"`
791    const how = hb.self ? `type /${names.keepwarm} or press 1` : `open /${names.board} to keep it warm`
792    toast($, `${who}: ${tokens(hb.ctx)}-token cache goes cold in ${minutes(st.left)}. Rewriting it costs about ${cost}. ${how}.`, { timeoutMs: 15000 })
793  }
794  // Another session started waiting on a permission or a question
795  for (const hb of fleet) {
796    if (hb.self || hb.stale) continue
797    const prev = alerted.get('state:' + hb.id)
798    alerted.set('state:' + hb.id, hb.state)
799    if (hb.state === 'waiting' && prev && prev !== 'waiting') {
800      toast($, `"${mask(hb.label)}" is waiting on you${hb.waitingFor ? ': ' + hb.waitingFor : ''}`, { timeoutMs: 10000 })
801    }
802  }
803}
804
805async function tick($) {
806  now = await $.clock.now()
807  await readRecording($)
808  await applyRemoteCommands($)
809  await keepWarmStep($)
810  await heartbeat($, true)
811  await readFleet($)
812  warnStep($)
813  $.ui.invalidate('ui.render')
814}
815
816async function loadSettings($) {
817  const saved = await $.store.get('settings')
818  if (saved && typeof saved === 'object') Object.assign(settings, saved)
819}
820
821function statusText() {
822  const st = cacheState(myHeartbeat())
823  const ttl = ttlMin()
824  const lines = []
825  lines.push(`Session Band: ${tokens(S.ctx)} tokens in context on ${priceFor(S.model).id}, cache window ${ttl} min (${settings.ttlMin ? 'set by you' : S.ttlSource}).`)
826  if (st.kind === 'unknown') lines.push('No request yet this session, so the cache state is unknown.')
827  if (st.kind === 'warm' || st.kind === 'cooling') lines.push(`Cache is warm for about ${minutes(st.left)} more.`)
828  if (st.kind === 'cold') lines.push(`Cache went cold ${minutes(-st.left)} ago. The next message rewrites it for about ${money(rewriteCost(S.ctx, S.model, ttl))}.`)
829  if (S.keepWarm) lines.push(`Keep warm is on until ${clock(S.keepWarmUntil)}: ${S.pings} ping(s), ${money(S.pingUsd)} so far.`)
830  if (allLimits().length) lines.push(`Plan limits used: ${limitsText(allLimits())}.`)
831  lines.push(`Session cost so far: ${money(S.costUsd)}. Cold restarts this session: ${S.coldRestarts.length} (${money(S.coldRestarts.reduce((a, c) => a + c.usd, 0))}).`)
832  lines.push(`Cold-send guard: ${settings.guard ? 'on' : 'off'} for contexts over ${tokens(settings.bigTokens)} tokens. Alerts: ${settings.alerts ? 'on' : 'off'}. Toasts: ${settings.toasts ? 'on' : 'off'}.`)
833  lines.push(`Settings: /${names.cache} ttl 5|60|auto, /${names.cache} guard on|off, /${names.cache} big 150k, /${names.cache} alerts [on|off], /${names.cache} toasts [on|off] (no value toggles). Board: /${names.board}.`)
834  return lines.join('\n')
835}
836
837function parseTokens(text) {
838  const m = String(text || '').trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*([km]?)$/)
839  if (!m) return null
840  return Math.round(Number(m[1]) * (m[2] === 'm' ? 1e6 : m[2] === 'k' ? 1e3 : 1))
841}
842
843export function register(on) {
844  on('session.start', async ($, e, next) => {
845    now = await $.clock.now()
846    home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || ''
847    claudeDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home || '.'}/.claude`
848    S.id = await $.session.id()
849    S.cwd = await $.session.cwd()
850    S.label = basename(S.cwd)
851    S.model = await $.session.model()
852    await loadSettings($)
853    await readRecording($)
854    names.cache = (await registerCommand($, 'cache', 'Session Band status and settings', '[ttl 5|60|auto] [guard on|off] [big 150k] [alerts [on|off]] [toasts [on|off]]')) || names.cache
855    names.keepwarm = (await registerCommand($, 'keepwarm', 'Keep this session\'s prompt cache warm (default 4 hours), or /keepwarm off', '[hours|off]', true)) || names.keepwarm
856    names.board = (await registerCommand($, 'board', 'Every local Claude Code session: state, context, cache, cost', '', true)) || names.board
857    names.handoff = (await registerCommand($, 'handoff', 'Session handoff, then clear this chat and continue with it (/handoff continue)', '[continue]')) || names.handoff
858    $.clock.every(HEARTBEAT_EVERY, () => tick($).catch(() => {}))
859    $.clock.every(OUTSIDE_EVERY, () => outsideStep($).catch(() => {}))
860    // Run the mods below first: the startup command list misses commands they register late.
861    const result = await next(e)
862    await restoreSession($)
863    refreshModelLimits($).catch(() => {})
864    return result
865  })
866
867  // A /clear or /resume ends the chat but not the process: no heartbeat may
868  // write this id again, and followSessionId picks up the next one.
869  on('session.end', async ($, e, next) => {
870    if (S.id) {
871      await $.store.delete('hb:' + S.id)
872      await writeLive($, myHeartbeat(), true)
873      endedId = S.id
874      S.id = ''
875    }
876    return next(e)
877  })
878
879  // The first prompt names the session on the board
880  on('prompt.submit', async ($, e, next) => {
881    now = await $.clock.now()
882    await followSessionId($) // a prompt right after /clear: the new chat before its first request
883    H.resuming = RESUME_LINE.test(String(e.text || ''))
884    if (S.label === basename(S.cwd) && e.origin && e.origin.kind === 'composer' && e.text) {
885      S.label = basename(S.cwd) + ' · ' + clip(e.text, 40)
886    }
887    // A new message in this chat makes a waiting handoff out of date (its file stays);
888    // a message sent mid-turn does not, because the turn end takes the file again
889    if (H.text && !H.continuing && !S.working && e.origin && e.origin.kind === 'composer' && !String(e.text || '').trim().startsWith('/')) {
890      H.text = ''
891      H.path = ''
892      H.fromFile = false
893      $.ui.invalidate('ui.render')
894    }
895    const ttl = ttlMin()
896    const left = msLeft(S.lastActivity, ttl)
897    const isCold = left !== null && left <= 0
898    const fromUser = e.origin && (e.origin.kind === 'composer' || e.origin.kind === 'bridge')
899    if (!settings.guard || !fromUser || !isCold || S.ctx < settings.bigTokens || e.turnId) return next(withAuto(e))
900    const cost = money(rewriteCost(S.ctx, S.model, ttl))
901    let answer = 'Send anyway'
902    try {
903      answer = await $.ui.ask(
904        `Cache went cold ${minutes(-left)} ago. Sending now rewrites ${tokens(S.ctx)} tokens of context (about ${cost}). What should happen?`,
905        ['Send anyway', 'Compact first, then send', 'Cancel'],
906      )
907    } catch {
908      // nobody to ask (a -p run, or the dialog was dismissed): send as typed
909      return next(withAuto(e))
910    }
911    if (answer === 'Compact first, then send') {
912      try {
913        await $.session.compact()
914      } catch {
915        // compaction refused or failed: send anyway
916      }
917      return next(withAuto(e))
918    }
919    if (answer === 'Send anyway') return next(withAuto(e))
920    toast($, 'Not sent. A fresh session with a short handoff avoids the rewrite entirely.', { timeoutMs: 8000 })
921    return { drop: 'Cancelled by session-band before a cold cache rewrite' }
922  })
923
924  on('turn.start', async ($, e, next) => {
925    now = await $.clock.now()
926    S.working = true
927    if (e.turnId) S.turnId = e.turnId
928    if (!e.agentId) for (const m of String(e.text || '').matchAll(/<task-id>(\w+)<\/task-id>/g)) bgShells.delete(m[1])
929    await heartbeat($, true)
930    return next(e)
931  })
932
933  // Each main-loop request: did it read the cache, or rewrite it?
934  on('turn.step', async function* ($, e, next) {
935    const startedAt = await $.clock.now()
936    const result = yield* next(e)
937    if (e.agentId || !result || !result.usage) return result
938    now = await $.clock.now()
939    const u = result.usage
940    const total = totalInput(u)
941    const written = u.cache_creation_input_tokens || 0
942    const gap = S.lastActivity ? startedAt - S.lastActivity : 0
943    S.model = u.model || S.model
944    const afterCompact = total < 0.6 * lastStepTotal
945    lastStepTotal = total
946    if (afterCompact) {
947      // the first request after a compaction or /clear writes the new, shorter context: expected
948    } else if (S.lastActivity && total > 30000 && written / total > 0.5) {
949      // A rewrite after 5-60 idle minutes means this session runs on the 5-minute TTL
950      if (!settings.ttlMin && gap > 5.5 * MIN && gap < S.ttlMin * MIN) {
951        S.ttlMin = 5
952        S.ttlSource = 'measured'
953      }
954      S.coldRestarts.push({ at: now, tokens: written, usd: rewriteCost(written, S.model, ttlMin()), gapMin: Math.round(gap / MIN) })
955    } else if (S.lastActivity && total > 30000 && gap > 5.5 * MIN && cachedShare(u) > 0.8) {
956      // A hit after more than 5 idle minutes proves the 1-hour TTL
957      if (!settings.ttlMin) {
958        S.ttlMin = 60
959        S.ttlSource = 'measured'
960      }
961    }
962    S.ctx = total
963    S.lastActivity = now
964    return result
965  })
966
967  on('turn.complete', async ($, e, next) => {
968    const r = await next(e)
969    if (e.agentId) return r
970    now = await $.clock.now()
971    S.working = false
972    S.waitingSince = 0
973    S.tool = ''
974    S.lastTurnEnd = now
975    try {
976      const usage = await $.session.usage()
977      if (usage.context && usage.context.tokens) S.ctx = usage.context.tokens
978      if (usage.context && usage.context.window) S.window = usage.context.window
979      if (usage.cost) S.costUsd = usage.cost.usd
980      if (Array.isArray(usage.rateLimits) && usage.rateLimits.length) S.rateLimits = usage.rateLimits
981    } catch {
982      // usage unavailable: keep the per-request figures
983    }
984    const wrote = H.file
985    if (wrote && (await captureHandoffFile($))) {
986      // the file is the handoff; the turn's answer is only its summary
987    } else if (wrote && (await fileRetired($, wrote))) {
988      // the turn consumed a handoff: its answer is not a new one
989      H.armed = false
990      H.notTurn = ''
991      H.askAfter = false
992    } else if (H.armed && e.turnId !== H.notTurn) await captureHandoff($, e)
993    else if (!H.text && !H.resuming && e.reason === 'answer' && offeredHandoff(e.answer)) await captureHandoffFile($, offeredHandoff(e.answer))
994    await heartbeat($, true)
995    // No handoff from this turn and no background work to wait for: nothing left to do (or the turn broke off)
996    if (auto && !H.text && !H.armed && !handoffPending && !waitsForWork()) await setAuto($, false, 'Autonomous mode off: the turn ended without a handoff.')
997    if (auto && e.reason === 'answer' && AFK_END.test(String(e.answer || ''))) await setAuto($, false, 'Autonomous mode off: the turn ended with the afk-shutdown end line, so this session is finished. The handoff waits for c.')
998    // clear right after the grace instead of on the next 2 s tick
999    if (auto && H.text) $.clock.after(AUTO_GRACE, () => outsideStep($).catch(() => {}))
1000    refreshModelLimits($).catch(() => {})
1001    $.ui.invalidate('ui.render')
1002    return r
1003  })
1004
1005  on('session.measure', async ($, e, next) => {
1006    if (e.context && e.context.tokens) S.ctx = e.context.tokens
1007    if (e.context && e.context.window) S.window = e.context.window
1008    if (e.cost) S.costUsd = e.cost.usd
1009    if (Array.isArray(e.rateLimits) && e.rateLimits.length) S.rateLimits = e.rateLimits
1010    return next(e)
1011  })
1012
1013  // Waiting on the person: a permission prompt or a question
1014  on('tool.check', async ($, e, next) => {
1015    const d = await next(e)
1016    if (d && d.decision === 'ask' && !S.waitingSince) {
1017      now = await $.clock.now()
1018      S.waitingSince = now
1019      S.waitingFor = 'permission for ' + e.tool
1020    }
1021    return d
1022  })
1023
1024  on('tool.call', async ($, e, next) => {
1025    if (auto && e.tool === 'AskUserQuestion') return { deny: AUTO_ASK }
1026    if (!e.agentId) S.tool = e.tool
1027    // Claude calling the handoff skill itself: this turn's answer is the handoff
1028    if (!e.agentId && e.tool === 'Skill' && HANDOFF_SKILL.test(String(e.skill || '')) && !H.resuming) armHandoff(true)
1029    if (e.tool === 'AskUserQuestion') {
1030      now = await $.clock.now()
1031      S.waitingSince = now
1032      S.waitingFor = 'a question'
1033    }
1034    try {
1035      const r = await next(e)
1036      const bg = !e.agentId && r && ((r.result && r.result.backgroundTaskId) || (BG_STARTED.exec(String(r.text || '')) || [])[1])
1037      if (bg) bgShells.set(bg, await $.clock.now())
1038      // a denied or failed write left the file as it was
1039      if (!e.agentId && r && !r.deny && !r.isError && noteHandoffFile(e)) await captureHandoffFile($, H.file, true)
1040      return r
1041    } finally {
1042      if (S.waitingSince) {
1043        S.waitingSince = 0
1044        S.waitingFor = ''
1045      }
1046    }
1047  })
1048
1049  // /session-handoff from anywhere (typed, the band, /handoff): watch for its answer
1050  on('command.run', async ($, e, next) => {
1051    if (HANDOFF_SKILL.test(String(e.command || ''))) armHandoff(false)
1052    return next(e)
1053  })
1054
1055  // /handoff runs the handoff and then asks to clear and continue (the band's
1056  // buttons draw only in the terminal); /handoff continue does the second half.
1057  // Both run off the hook: a command started inside a hook the session is
1058  // waiting on is refused.
1059  on('command.run', { command: ['handoff', 'ck-handoff'] }, async ($, e) => {
1060    now = await $.clock.now()
1061    const arg = String(e.args || '').trim().toLowerCase()
1062    if (arg === 'continue' || arg === 'go') {
1063      if (!H.text) return { text: `No handoff ready yet. Type /${names.handoff} to make one.` }
1064      $.clock.after(50, () => clearAndContinue($).catch(() => {}))
1065      return { text: 'Clearing this chat and continuing with the handoff.' }
1066    }
1067    H.askAfter = true
1068    $.clock.after(50, () => runHandoff($).catch(() => {}))
1069    return { text: 'Running the session handoff. When it finishes, you can clear this chat and continue with it.' }
1070  })
1071
1072  on('command.run', { command: ['cache', 'ck-cache'] }, async ($, e) => {
1073    now = await $.clock.now()
1074    const [key, value] = String(e.args || '').trim().toLowerCase().split(/\s+/)
1075    if (key === 'ttl') {
1076      settings.ttlMin = value === '5' ? 5 : value === '60' ? 60 : 0
1077    } else if (key === 'guard' || key === 'alerts' || key === 'toasts') {
1078      // no value toggles
1079      settings[key] = value === undefined ? !settings[key] : value !== 'off'
1080    } else if (key === 'big') {
1081      const n = parseTokens(value)
1082      if (n) settings.bigTokens = n
1083    }
1084    if (key) {
1085      await $.store.set('settings', settings)
1086      $.ui.invalidate('ui.render')
1087    }
1088    return { text: statusText() }
1089  })
1090
1091  on('command.run', { command: ['keepwarm', 'ck-keepwarm'] }, async ($, e) => {
1092    now = await $.clock.now()
1093    const arg = String(e.args || '').trim().toLowerCase()
1094    if (arg === 'off' || (arg === '' && S.keepWarm)) {
1095      stopKeepWarm($, 'turned off')
1096    } else {
1097      const hours = Number(arg) > 0 ? Math.min(24, Number(arg)) : settings.keepWarmHours
1098      startKeepWarm($, hours)
1099    }
1100    await heartbeat($, true)
1101    $.ui.invalidate('ui.render')
1102    return {}
1103  })
1104
1105  on('command.run', { command: ['board', 'ck-board'] }, async ($, e) => {
1106    now = await $.clock.now()
1107    await heartbeat($, true)
1108    await readFleet($)
1109    const surface = await $.session.surface()
1110    if (!surface) return { text: boardText() }
1111    paneOpen = true
1112    await $.ui.open({ id: PANE, title: 'Sessions', focus: true, closeOnEscape: true })
1113    return {}
1114  })
1115
1116  on('ui.close', async ($, e, next) => {
1117    if (e.id === PANE) paneOpen = false
1118    return next(e)
1119  })
1120
1121  // The band above the prompt: this session's cache at a glance
1122  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1123    const below = await next(e)
1124    if (e.props && e.props.hasSurvey) return below
1125    if (!S.lastActivity && !S.keepWarm) return below
1126    const { Box, Text, Button } = $.ui.resolve(e)
1127    const hb = myHeartbeat()
1128    const st = cacheState(hb)
1129    const ttl = ttlMin()
1130    const big = S.ctx >= settings.bigTokens
1131    const parts = []
1132    const tip = (scope) => ({ scope, underline: true })
1133    if (st.kind === 'kept') parts.push(Text({ color: 'cyan', hover: tip('ck-c'), children: [`◆ c kept ${clock(S.keepWarmUntil)}`] }))
1134    else if (st.kind === 'warm') parts.push(Text({ color: 'green', hover: tip('ck-c'), children: [`● c ${minutes(st.left)}`] }))
1135    else if (st.kind === 'cooling') parts.push(Text({ color: 'yellow', bold: true, hover: tip('ck-c'), children: [`◐ c ${minutes(st.left)}`] }))
1136    else if (st.kind === 'cold') parts.push(Text(big ? { color: 'red', bold: true, hover: tip('ck-c'), children: [`○ c cold ${minutes(-st.left)}`] } : { dimColor: true, hover: tip('ck-c'), children: [`○ c cold ${minutes(-st.left)}`] }))
1137    parts.push(Text({ dimColor: true, hover: tip('ck-ctx'), children: [` │ ctx ${tokens(S.ctx)}`] }))
1138    if (st.kind === 'cold' && big) parts.push(Text({ color: 'red', hover: tip('ck-rewrite'), children: [` │ next send rewrites it ≈ ${money(rewriteCost(S.ctx, S.model, ttl))}`] }))
1139    else parts.push(Text({ dimColor: true, hover: tip('ck-rewrite'), children: [` │ rwc ${money(rewriteCost(S.ctx, S.model, ttl))}`] }))
1140    parts.push(Text({ dimColor: true, hover: tip('ck-sc'), children: [` │ sc ${money(S.costUsd)}`] }))
1141    const cold = S.coldRestarts.length
1142    const coldUsd = money(S.coldRestarts.reduce((a, c) => a + c.usd, 0))
1143    if (cold) parts.push(Text({ dimColor: true, hover: tip('ck-cr'), children: [` │ cr ${cold} ${coldUsd}`] }))
1144    const limits = allLimits()
1145    limits.forEach((l, i) => parts.push(Text(limitTone(limitColor(l, now), { hover: tip('ck-limits'), children: [`${i ? ' ' : ' │ '}${limitLabel(l)} ${Math.round(l.percentUsed)}%`] }))))
1146    // Whole segments wrap to a second row; a squeezed segment would split its label from its value
1147    const row = [Box({ flexDirection: 'row', flexWrap: 'wrap', children: parts })]
1148    if (st.kind === 'cooling' && big) {
1149      row.push(Button({ key: 'keepwarm', label: 'keep warm', hotkey: '1', plain: true, onPress: async () => { now = await $.clock.now(); startKeepWarm($, settings.keepWarmHours); await heartbeat($, true); $.ui.invalidate('ui.render') } }))
1150    } else if (st.kind === 'kept') {
1151      row.push(Button({ key: 'keepwarm', label: 'stop warm', hotkey: '1', plain: true, onPress: async () => { now = await $.clock.now(); stopKeepWarm($, 'turned off'); await heartbeat($, true); $.ui.invalidate('ui.render') } }))
1152    }
1153    const left = Box({ flexDirection: 'row', columnGap: 2, children: row })
1154    // Right edge: one click runs /session-handoff (h while the band has the focus;
1155    // a letter never fires from the prompt box, unlike a digit). Once a handoff
1156    // is in, c clears this chat and sends it as the fresh chat's first prompt.
1157    const hs = handoffState()
1158    const busy = hs === 'queued' || hs === 'running'
1159    const handoff = Button({ key: 'handoff', label: busy ? 'handoff ' + hs : 'handoff', hotkey: 'h', plain: true, dimColor: busy, onPress: () => runHandoff($) })
1160    // A: a framed button, primary while on; not plain, because a plain Button draws the same with any variant
1161    const autoButton = Button({ key: 'auto', label: 'A', variant: auto ? 'primary' : 'secondary', dimColor: !auto, hover: { scope: 'ck-auto', underline: true }, onPress: async () => { now = await $.clock.now(); await setAuto($, !auto, auto ? 'Autonomous mode off.' : 'Autonomous mode on: each ready handoff is cleared and continued without you.') } })
1162    const rightParts = [handoff, autoButton]
1163    if (ready() || H.continuing) {
1164      rightParts.unshift(Button({ key: 'continue', label: H.continuing ? 'clearing' : 'clear and continue', hotkey: 'c', plain: true, onPress: () => clearAndContinue($) }))
1165    }
1166    const right = Box({ flexDirection: 'row', columnGap: 2, children: rightParts })
1167    const mine = Box({ flexDirection: 'row', justifyContent: 'space-between', width: '100%', columnGap: 2, children: [left, right] })
1168    // Hover help rows sit above the band row, so revealing one leaves the hovered text in place.
1169    const help = (scope, text) => Box({ display: 'none', hover: { scope, display: 'flex' }, children: [Text({ dimColor: true, italic: true, children: [text] })] })
1170    const cacheHelp = { kept: `kept warm until ${clock(S.keepWarmUntil)}, ${S.pings} ping${S.pings === 1 ? '' : 's'} so far (${money(S.pingUsd)})`, warm: `warm, expires in ${minutes(st.left)}`, cooling: `cooling, expires in ${minutes(st.left)}`, cold: `cold for ${minutes(-st.left)}` }
1171    const tips = [
1172      help('ck-c', `c = prompt cache: ${cacheHelp[st.kind] || 'state unknown'}${ttl ? ` (${ttl}m TTL)` : ''}; once cold, the next send writes the whole context again`),
1173      help('ck-ctx', `ctx = context: ${tokens(S.ctx)} tokens in this session's context window${S.window ? ` of ${tokens(S.window)}` : ''}`),
1174      help('ck-rewrite', `rwc = rewrite cost: estimated cost to write ${tokens(S.ctx)} of context into the cache again if it expires (cache write price${ttl ? `, ${ttl}m TTL` : ''})`),
1175      help('ck-sc', 'sc = session cost: what this session has cost so far, at API list prices'),
1176      help('ck-auto', `A = autonomous mode: ${auto ? 'on' : 'off'}. While on, each ready handoff is cleared and continued by itself, and Claude answers its own questions. A turn that ends without a handoff, or with the afk-shutdown end line, turns it off.`),
1177    ]
1178    if (cold) tips.push(help('ck-cr', `cr = cold restarts: ${cold} send${cold === 1 ? '' : 's'} rewrote the expired cache this session, ${coldUsd} in total`))
1179    const resets = resetsText(limits, now)
1180    if (resets) tips.push(help('ck-limits', 'plan limits: ' + resets))
1181    return Box({ flexDirection: 'column', children: below ? [...tips, mine, below] : [...tips, mine] })
1182  })
1183
1184  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
1185    if (e.requestId !== PANE) return next(e)
1186    return drawBoard($, e)
1187  })
1188
1189  // The footer draws in the terminal and the Desktop app; it carries a short
1190  // label, only when there's something to act on.
1191  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
1192    const label = footerLabel()
1193    if (!label) return next(e)
1194    const modes = Array.isArray(e.props && e.props.modes) ? e.props.modes : []
1195    return next({ ...e, props: { ...e.props, modes: [...modes, label] } })
1196  })
1197}
1198
1199function footerLabel() {
1200  const parts = []
hooks/pricing.mjs 96 lines
1// Shared source. Copied into each mod's hooks/ folder by _dev/sync-shared.mjs.
2// Edit it here, then run: node mods/_dev/sync-shared.mjs
3
4// Dollars per million tokens, from the Claude API pricing table (cached 2026-09-25).
5// Cache writes cost 1.25x input on the 5-minute TTL and 2x input on the 1-hour TTL.
6const TABLE = [
7  ['fable-5-1', { input: 10, output: 50, read: 0.25 }],
8  ['mythos-5-1', { input: 10, output: 50, read: 0.25 }],
9  ['fable-5', { input: 10, output: 50, read: 1.0 }],
10  ['opus-5-5', { input: 4, output: 20, read: 0.2 }],
11  ['opus-5', { input: 5, output: 25, read: 0.5 }],
12  ['opus-4-8', { input: 5, output: 25, read: 0.5 }],
13  ['opus-4-7', { input: 5, output: 25, read: 0.5 }],
14  ['opus-4-6', { input: 5, output: 25, read: 0.5 }],
15  ['sonnet-5-5', { input: 2, output: 10, read: 0.2 }],
16  ['sonnet-5', { input: 2, output: 10, read: 0.2 }],
17  ['sonnet-4-6', { input: 3, output: 15, read: 0.3 }],
18  ['haiku-4-5', { input: 1, output: 5, read: 0.1 }],
19]
20
21const FAMILY = {
22  fable: 'fable-5-1',
23  mythos: 'mythos-5-1',
24  opus: 'opus-5-5',
25  sonnet: 'sonnet-5-5',
26  haiku: 'haiku-4-5',
27}
28
29export function normalizeModel(model) {
30  return String(model || '')
31    .toLowerCase()
32    .replace(/^claude-/, '')
33    .replace(/\[.*?\]/g, '')
34    .replace(/-\d{8}$/, '')
35    .trim()
36}
37
38export function priceFor(model) {
39  const id = normalizeModel(model)
40  for (const [key, price] of TABLE) {
41    if (id === key || id.startsWith(key + '-') || id.startsWith(key)) {
42      // 'opus-5' must not swallow 'opus-5-5': the table lists longer ids first
43      return { id: key, ...price }
44    }
45  }
46  for (const [family, key] of Object.entries(FAMILY)) {
47    if (id.includes(family)) {
48      const found = TABLE.find(([k]) => k === key)
49      return { id: key, ...found[1] }
50    }
51  }
52  return { id: 'opus-5-5', input: 4, output: 20, read: 0.2 }
53}
54
55export function writeRate(model, ttlMinutes) {
56  const p = priceFor(model)
57  return p.input * (ttlMinutes >= 60 ? 2 : 1.25)
58}
59
60// usage: { input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens }
61export function requestCost(usage, model, ttlMinutes = 60) {
62  if (!usage) return 0
63  const p = priceFor(model || usage.model)
64  const w = writeRate(model || usage.model, ttlMinutes)
65  return (
66    ((usage.input_tokens || 0) * p.input +
67      (usage.cache_read_input_tokens || 0) * p.read +
68      (usage.cache_creation_input_tokens || 0) * w +
69      (usage.output_tokens || 0) * p.output) /
70    1e6
71  )
72}
73
74export function rewriteCost(tokens, model, ttlMinutes = 60) {
75  return ((tokens || 0) * writeRate(model, ttlMinutes)) / 1e6
76}
77
78export function readCost(tokens, model) {
79  return ((tokens || 0) * priceFor(model).read) / 1e6
80}
81
82export function totalInput(usage) {
83  if (!usage) return 0
84  return (
85    (usage.input_tokens || 0) +
86    (usage.cache_read_input_tokens || 0) +
87    (usage.cache_creation_input_tokens || 0)
88  )
89}
90
91// Share of a request's input served from the cache, 0 to 1.
92export function cachedShare(usage) {
93  const total = totalInput(usage)
94  return total > 0 ? (usage.cache_read_input_tokens || 0) / total : 0
95}
96
hooks/fmt.mjs 70 lines
1// Shared source. Copied into each mod's hooks/ folder by _dev/sync-shared.mjs.
2
3export function tokens(n) {
4  const v = Number(n) || 0
5  if (v >= 1e6) return (v / 1e6).toFixed(v >= 1e7 ? 0 : 1) + 'M'
6  if (v >= 1e3) return (v / 1e3).toFixed(v >= 1e5 ? 0 : 1) + 'k'
7  return String(Math.round(v))
8}
9
10export function usd(n) {
11  const v = Number(n) || 0
12  if (v === 0) return '$0'
13  if (v < 0.01) return '<$0.01'
14  if (v < 10) return '$' + v.toFixed(2)
15  return '$' + v.toFixed(0)
16}
17
18export function duration(ms) {
19  const s = Math.max(0, Math.round((Number(ms) || 0) / 1000))
20  if (s < 60) return s + 's'
21  const m = Math.floor(s / 60)
22  if (m < 60) return m + 'm' + String(s % 60).padStart(2, '0') + 's'
23  const h = Math.floor(m / 60)
24  return h + 'h' + String(m % 60).padStart(2, '0') + 'm'
25}
26
27export function minutes(ms) {
28  const m = Math.round((Number(ms) || 0) / 60000)
29  if (m <= 60) return m + 'm'
30  return Math.floor(m / 60) + 'h' + String(m % 60).padStart(2, '0') + 'm'
31}
32
33export function clock(ts) {
34  const d = new Date(ts)
35  let h = d.getHours()
36  const ampm = h >= 12 ? 'pm' : 'am'
37  h = h % 12 || 12
38  return h + ':' + String(d.getMinutes()).padStart(2, '0') + ampm
39}
40
41const SPARKS = '▁▂▃▄▅▆▇█'
42
43export function sparkline(values, width = 12) {
44  const vals = values.slice(-width)
45  if (vals.length === 0) return ''
46  const max = Math.max(...vals, 1)
47  return vals.map((v) => SPARKS[Math.min(7, Math.floor((v / max) * 7.999))]).join('')
48}
49
50export function bar(fraction, width = 20, full = '█', empty = '░') {
51  const f = Math.max(0, Math.min(1, Number(fraction) || 0))
52  const n = Math.round(f * width)
53  return full.repeat(n) + empty.repeat(width - n)
54}
55
56export function clip(text, max) {
57  const s = String(text ?? '').replace(/\s+/g, ' ').trim()
58  return s.length > max ? s.slice(0, Math.max(0, max - 1)) + '…' : s
59}
60
61export function pad(text, width) {
62  const s = String(text ?? '')
63  return s.length >= width ? s.slice(0, width) : s + ' '.repeat(width - s.length)
64}
65
66export function basename(path) {
67  const parts = String(path || '').split(/[\\/]+/).filter(Boolean)
68  return parts[parts.length - 1] || String(path || '')
69}
70
hooks/privacy.mjs 337 lines
1// Masks secrets, personal details, and business figures for screen recording.
2// Pure functions: no mods API calls here. The same file ships in each mod that
3// draws text, since a mod may import only its own files.
4
5const DOTS = '••••••••'
6const HIDE = '•••'
7const HIDDEN_OUTPUT = '••• hidden while recording'
8
9const SECRET_PATTERNS = [
10  /sk-ant-[A-Za-z0-9_-]{16,}/g,
11  /\bsk-(?:proj-|live-|test-|svcacct-)?[A-Za-z0-9_-]{20,}/g,
12  /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
13  /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
14  /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
15  /\bAIza[0-9A-Za-z_-]{30,}/g,
16  /\bAKIA[0-9A-Z]{16}\b/g,
17  /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
18  /\b(?:hf|r8|pk_live|sk_live|rk_live|whsec|pat|key)_[A-Za-z0-9]{20,}/g,
19  /\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*/gi,
20]
21
22// NAME=value or "name": "value" where the name looks like a credential
23const ASSIGNMENT =
24  /\b([A-Za-z0-9_.-]*(?:API[_-]?KEY|SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE[_-]?KEY|ACCESS[_-]?KEY|CLIENT[_-]?SECRET|AUTH)[A-Za-z0-9_.-]*)(["']?\s*[=:]\s*["']?)([^\s"'`,;}{]{6,})/gi
25
26const EMAIL_SRC = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}'
27const EMAIL = new RegExp(`\\b${EMAIL_SRC}\\b`, 'g')
28
29// People: "Jane Doe <jane@x.com>", "displayName": "Jane Doe", and From:/Attendees: lines
30const NAME_WORD = "[A-Z][\\p{L}'’.-]*"
31const DISPLAY_NAME = new RegExp(`(["']?)(${NAME_WORD}(?:[ \\t]+${NAME_WORD}){0,3})\\1([ \\t]*<[ \\t]*${EMAIL_SRC}[ \\t]*>)`, 'gu')
32const PERSON_KEY =
33  /("(?:displayName|display_name|fullName|full_name|firstName|first_name|lastName|last_name|givenName|given_name|familyName|family_name|real_name|realName|senderName|sender_name|authorName|author_name|username|user_name)"\s*:\s*")([^"]{1,80})(")/g
34const PERSON_LINE = /^([ \t>*-]*(?:From|To|Cc|Bcc|Reply-To|Attendees?|Organizer|Invitees?|Guests?|Assignees?|Sender|Owner)[ \t]*:[ \t]*)(\S.*)$/gm
35
36// Personal details
37const PHONE = /(?<![\w.])(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}(?![\w.])/g
38const PHONE_INTL = /(?<![\w.])\+\d{1,3}[\s.-]?\(?\d{1,4}\)?(?:[\s.-]?\d{2,4}){2,4}(?![\w.])/g
39const SSN = /(?<![\w-])\d{3}-\d{2}-\d{4}(?![\w-])/g
40const EIN = /(?<![\w-])\d{2}-\d{7}(?![\w-])/g
41const CARD = /(?<![\w-])(?:4\d{3}|5[1-5]\d{2}|2[2-7]\d{2}|3[47]\d{2}|6(?:011|5\d{2}))(?:[ -]?\d{2,4}){3,4}(?![\w-])/g
42const IBAN = /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){3,7}(?: ?[A-Z0-9]{1,3})?\b/g
43const ACCOUNT = /\b((?:routing|account|acct|a\/c|aba|swift|bic|iban|passport|driver'?s license)(?:\s*(?:number|no\.?|num|#))?\s*[:#]?\s*)(\d[\d -]{3,}\d)/gi
44const CARD_ENDING = /\b((?:ending(?:\s+in)?|last\s+(?:4|four)(?:\s+digits)?)\s*[:#]?\s*)(\d{4})\b/gi
45const STREET = /\b\d{1,6}\s+(?:[NSEW]\.?\s+)?(?:[A-Z][\p{L}'.-]*\s+){1,3}(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Drive|Dr|Lane|Ln|Way|Court|Ct|Place|Pl|Parkway|Pkwy|Highway|Hwy|Circle|Cir|Terrace|Ter|Trail|Trl|Square|Sq)\b\.?(?:,?\s+(?:Apt|Apartment|Suite|Ste|Unit|#)\.?\s*[\w-]+)?/gu
46const PO_BOX = /\bP\.?\s?O\.?\s+Box\s+\d+/gi
47const STATE_ZIP = /(,\s*(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY]))\s+\d{5}(?:-\d{4})?\b/g
48const BIRTH = /\b((?:DOB|D\.O\.B\.|date of birth|birth\s?date|birthday|born(?: on)?)\s*[:-]?\s*)([A-Za-z0-9 ,/.-]{4,20}\d)/gi
49const IPV4 = /(?<![\w.])((?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3})(?![\w.])/g
50
51// Money in any common currency
52const MONEY = /(?:US|CA|AU)?[$€£¥]\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:[kKmMbB]|bn|million|thousand|billion)\b)?/g
53const MONEY_WORD = /(?<![\w.])(?:(?:USD|EUR|GBP|CAD|AUD)\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:[kKmMbB]|bn|million|thousand|billion)\b)?|\d[\d,]*(?:\.\d+)?(?:\s?(?:[kKmMbB]|bn|million|thousand|billion))?\s?(?:USD|EUR|GBP|CAD|AUD|dollars|bucks)\b)/gi
54
55// Figures near business words: "MRR is 84k", "40% margin", "profit share 20%"
56const FIN_WORD =
57  /\b(?:revenues?|mrr|arr|gmv|profits?|profit share|margins?|ebitda|income|earnings|payroll|salar(?:y|ies)|wages?|compensation|comp|bonus(?:es)?|equity|stakes?|ownership|valuation|runway|burn(?: rate)?|cash(?:flow)?|balances?|budgets?|spend(?:ing)?|pric(?:e|es|ing)|fees?|invoices?|payouts?|distributions?|dividends?|tax(?:es)?|sales|ltv|cac|aov|sponsor(?:s|ships?)?|cpm|rpm|retainers?|commissions?|royalt(?:y|ies)|refunds?|expenses?|debts?|loans?|funding|investments?|deals?|net|gross|paid|pays?|owed?|costs?)\b/gi
58const FIGURE = /(?<![\w.])\d[\d,]*(?:\.\d+)?(?:\s?(?:%|percent\b|[kKmMbB]\b|bn\b|million\b|thousand\b|billion\b|x\b))?/g
59const BIG_FIGURE = /(?<![\w.])(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?\s?(?:%|percent\b|[kKmMbB]\b|bn\b|million\b|thousand\b|billion\b))/g
60
61// Single names that are also ordinary words, and names that stay visible (the channel's own)
62const COMMON_WORDS = new Set(
63  'Will Mark Grant Bill Rich Art Hope Faith Joy May June April August Summer Rose Page Chase Hunter Max Ray Dawn Sky Brook Lane Dean Gene Guy Frank Sterling Major Price Young King Long Little Wood Hill Stone Field Ford Hall Bell Rice Banks Case Cook Fox Gray Green Brown White Black Day Lee West North South Love Church Park Street Bishop Mason Miller Baker Carter Cole Wells Hart Moon Star Van Von De Del La Le Da Di St Mr Mrs Ms Dr Jr Sr Claude Code Team Support Admin Info Hello The And Ai Slack Gmail Google Calendar Meeting Sync Notes Update Review Weekly Daily Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '),
64)
65const ROLE_LOCAL_PARTS = /^(?:info|hello|hi|team|support|help|admin|noreply|no-reply|donotreply|contact|sales|billing|accounts?|notifications?|news|newsletter|marketing|office|mail|security|privacy|legal|press|jobs|careers|hr|ops|dev|bot|alerts?|updates?|calendar|invites?)$/i
66
67// Files that stay closed while recording. Add your own folders and file names
68// in ~/.claude/mods-data/recording-mode/config.json ("privatePaths"); /rec config makes one.
69const PRIVATE_PATHS = [
70  /(^|[\\/\s"'`])\.env(\.[A-Za-z0-9_-]+)?(?=$|[\s"'`;|&)])/i,
71  /\.credentials\.json/i,
72  /[\\/]\.claude\.json\b/i,
73  /\.claude[\\/]projects[\\/][^\\/\s"'`]+[\\/]memory/i,
74  /(^|[\\/\s"'`])\.(?:ssh|aws|gnupg)(?=$|[\\/])/i,
75  /\bid_(?:rsa|ed25519|ecdsa)\b/i,
76  /(^|[\\/\s"'`])\.(?:netrc|npmrc|pypirc)\b/i,
77  /\.(?:pem|p12|pfx)\b/i,
78  /taxes?[-_ ]?20\d\d/i,
79  /[\\/_-](?:payroll|invoices?|contracts?|financials?|finances?|budgets?|forecasts?|cap[-_ ]?table|term[-_ ]?sheets?|offer[-_ ]?letters?|business[-_ ]?plans?)(?=$|[\\/._\s"'`;|&)-])/i,
80  /(^|[\s"'`])(?:payroll|invoices?|contracts?|financials?|finances?|budgets?|forecasts?|business[-_ ]?plans?)(?=[\\/.])/i,
81]
82
83// Tools whose results are business data: drawn as hidden while recording
84const BUSINESS_TOOL =
85  /(?:^|__|_)(?:clickup|slack|gmail|outlook|notion|asana|linear|jira|clay|qbo|quickbooks|xero|fireflies|hubspot|salesforce|stripe|calendar|gcal|google_drive|drive|sheets)|search_threads|get_thread|get_message|list_drafts|get_draft|read_file_content|download_file_content|search_files|list_recent_files|get_file_metadata|profit_loss|cash_flow|balance_sheet|payroll|session_transcripts|export_transcript/i
86const BUSINESS_COMMAND = /\bgws(?:\.cmd|\.exe)?\b|fireflies|quickbooks/i
87// Finance tools stay closed while recording
88const FINANCE_TOOL = /__(?:qbo_|quickbooks|profit_loss|cash_flow|balance_sheet|benchmarking_quickbooks|money_onboarding|company_info)/i
89
90function escapeRegExp(s) {
91  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
92}
93
94// Values from .env files: long enough to be secret, and not plain words or numbers.
95export function secretValuesFromEnv(text) {
96  const values = []
97  for (const line of String(text || '').split(/\r?\n/)) {
98    const m = line.match(/^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*)\s*$/)
99    if (!m) continue
100    let v = m[1].trim()
101    if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1)
102    if (v.length < 8) continue
103    if (/^(true|false|null|none|yes|no)$/i.test(v)) continue
104    if (/^\d+(\.\d+)?$/.test(v)) continue
105    if (/your[-_ ]?(key|token|secret)|here$|^<.*>$|^xxx/i.test(v)) continue
106    values.push(v)
107  }
108  return [...new Set(values)].sort((a, b) => b.length - a.length)
109}
110
111// The forms of one person's name that get masked: the full name, its slug, and each part that isn't an ordinary word
112function nameForms(full, keep) {
113  const clean = String(full || '').replace(/\s+/g, ' ').trim()
114  if (!clean || clean.length > 60 || keep.has(clean)) return []
115  const forms = new Set()
116  const parts = clean.split(/[ -]/).filter((p) => /^[A-Z][\p{L}'’.]*$/u.test(p) && p.length >= 2)
117  if (parts.length >= 2) {
118    forms.add(clean)
119    forms.add(clean.toLowerCase())
120    forms.add(clean.toLowerCase().replace(/ /g, '-'))
121    forms.add(clean.toLowerCase().replace(/ /g, '_'))
122  }
123  for (const p of parts) if (!COMMON_WORDS.has(p) && !keep.has(p)) forms.add(p)
124  return [...forms]
125}
126
127function namesFromEmail(email) {
128  const local = email.split('@')[0]
129  if (ROLE_LOCAL_PARTS.test(local)) return null
130  const parts = local.split(/[._+-]/).filter((p) => /^[a-z]{2,}$/i.test(p))
131  if (parts.length < 2 || parts.length > 4) return null
132  return parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join(' ')
133}
134
135// Masks numbers in the same clause as a business word
136function maskFigures(text, strict) {
137  if (strict) text = text.replace(BIG_FIGURE, HIDE)
138  const ranges = []
139  for (const m of text.matchAll(FIN_WORD)) {
140    const s = m.index
141    const e = s + m[0].length
142    let a = Math.max(0, s - 30)
143    let b = Math.min(text.length, e + 45)
144    const before = text.slice(a, s)
145    const stop = Math.max(before.lastIndexOf('\n'), before.lastIndexOf(';'), before.search(/[.!?]\s[^.!?]*$/))
146    if (stop >= 0) a += stop + 1
147    const after = text.slice(e, b)
148    const end = after.search(/\n|;|[.!?](?:\s|$)/)
149    if (end >= 0) b = e + end
150    ranges.push([a, b])
151  }
152  if (!ranges.length) return text
153  return text.replace(FIGURE, (fig, offset) => {
154    if (/^(?:19|20)\d\d$/.test(fig)) return fig // a year
155    return ranges.some(([a, b]) => offset >= a && offset < b) ? HIDE : fig
156  })
157}
158
159function luhn(digits) {
160  let sum = 0
161  for (let i = 0; i < digits.length; i++) {
162    let d = Number(digits[digits.length - 1 - i])
163    if (i % 2 === 1) {
164      d *= 2
165      if (d > 9) d -= 9
166    }
167    sum += d
168  }
169  return sum % 10 === 0
170}
171
172function publicIp(ip) {
173  const [a, b] = ip.split('.').map(Number)
174  if (a === 10 || a === 127 || a === 0 || ip === '255.255.255.255') return false
175  if (a === 192 && b === 168) return false
176  if (a === 172 && b >= 16 && b <= 31) return false
177  if (a === 169 && b === 254) return false
178  return true
179}
180
181// Your own name and its parts stay visible
182function keepSet(keepNames) {
183  const keep = new Set()
184  for (const n of keepNames || []) {
185    const clean = String(n || '').replace(/\s+/g, ' ').trim()
186    if (!clean) continue
187    keep.add(clean)
188    keep.add(clean.toLowerCase())
189    keep.add(clean.toLowerCase().replace(/ /g, '-'))
190    for (const part of clean.split(/[ -]/)) if (part) keep.add(part)
191  }
192  return keep
193}
194
195// strict: also every large figure (1,250 / 18% / 40k) wherever it appears
196// names: people to mask; keepNames: names that stay visible (yours)
197export function makeMasker({ strict = false, values = [], names = [], keepNames = [] } = {}) {
198  const KEEP_NAMES = keepSet(keepNames)
199  const valueRe = values.length
200    ? new RegExp(values.map(escapeRegExp).join('|'), 'g')
201    : null
202  // Names: the roster passed in plus any learned from emails and contact fields. Memory only.
203  const people = new Set()
204  let nameRe = null
205  let dirty = false
206  const learn = (full) => {
207    if (people.size > 2000) return
208    for (const f of nameForms(full, KEEP_NAMES)) {
209      if (!people.has(f)) {
210        people.add(f)
211        dirty = true
212      }
213    }
214  }
215  for (const n of names) learn(n)
216  const nameRegex = () => {
217    if (dirty) {
218      const list = [...people].sort((a, b) => b.length - a.length).map(escapeRegExp)
219      nameRe = list.length ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${list.join('|')})(?:['’]s)?(?![\\p{L}\\p{N}_])`, 'gu') : null
220      dirty = false
221    }
222    return nameRe
223  }
224
225  return function mask(text) {
226    if (typeof text !== 'string' || text.length === 0) return text
227    let out = text
228    if (valueRe) out = out.replace(valueRe, DOTS)
229    for (const re of SECRET_PATTERNS) out = out.replace(re, DOTS)
230    out = out.replace(ASSIGNMENT, (_, name, sep) => name + sep + DOTS)
231
232    // people, learned before the emails that name them are masked
233    for (const m of out.matchAll(EMAIL)) {
234      const n = namesFromEmail(m[0])
235      if (n) learn(n)
236    }
237    out = out.replace(DISPLAY_NAME, (_, q, name, addr) => {
238      learn(name)
239      return KEEP_NAMES.has(name) ? q + name + q + addr : HIDE + addr
240    })
241    out = out.replace(PERSON_KEY, (_, head, value, tail) => {
242      learn(value)
243      return head + (KEEP_NAMES.has(value) ? value : HIDE) + tail
244    })
245    out = out.replace(PERSON_LINE, (line, label, value) => (KEEP_NAMES.has(value.trim()) ? line : label + HIDE))
246    out = out.replace(EMAIL, '•••@•••')
247    const re = nameRegex()
248    if (re) out = out.replace(re, HIDE)
249
250    // personal details
251    out = out.replace(CARD, (m) => {
252      const digits = m.replace(/\D/g, '')
253      return digits.length >= 13 && digits.length <= 19 && luhn(digits) ? '•••• •••• •••• ••••' : m
254    })
255    out = out.replace(SSN, '•••-••-••••')
256    out = out.replace(EIN, '••-•••••••')
257    out = out.replace(IBAN, HIDE)
258    out = out.replace(ACCOUNT, (_, head) => head + HIDE)
259    out = out.replace(CARD_ENDING, (_, head) => head + '••••')
260    out = out.replace(BIRTH, (_, head) => head + HIDE)
261    out = out.replace(STREET, HIDE)
262    out = out.replace(PO_BOX, HIDE)
263    out = out.replace(STATE_ZIP, (_, head) => head + ' •••••')
264    out = out.replace(PHONE, '•••-•••-••••')
265    out = out.replace(PHONE_INTL, '+•• •••')
266    out = out.replace(IPV4, (ip) => (publicIp(ip) ? '•••.•••.•••.•••' : ip))
267
268    // business figures
269    out = out.replace(MONEY, '$•••')
270    out = out.replace(MONEY_WORD, HIDE)
271    out = maskFigures(out, strict)
272    return out
273  }
274}
275
276// Masks every string inside plain data, keeping the shape.
277export function deepMask(value, mask, depth = 0) {
278  if (depth > 12) return value
279  if (typeof value === 'string') return mask(value)
280  if (Array.isArray(value)) return value.map((v) => deepMask(v, mask, depth + 1))
281  if (value && typeof value === 'object') {
282    const proto = Object.getPrototypeOf(value)
283    if (proto !== Object.prototype && proto !== null) return value
284    const out = {}
285    for (const [k, v] of Object.entries(value)) out[k] = deepMask(v, mask, depth + 1)
286    return out
287  }
288  return value
289}
290
291// Hides the readable text inside a business tool's result, keeping short tags (type: 'text') so the row still draws.
292export function hideText(s) {
293  if (typeof s !== 'string' || s.length === 0) return s
294  return s.length > 24 || /\s/.test(s) ? HIDDEN_OUTPUT : s
295}
296
297// extra: your own folder or file names from the config file, matched anywhere in a path, any case
298export function privatePathHit(text, extra = []) {
299  const s = String(text || '')
300  for (const re of PRIVATE_PATHS) {
301    const m = s.match(re)
302    if (m) return m[0].trim().replace(/^["'`\\/_-]/, '')
303  }
304  const flat = s.replace(/\\/g, '/').toLowerCase()
305  for (const item of extra) {
306    const needle = String(item || '').replace(/\\/g, '/').toLowerCase().trim()
307    if (needle && flat.includes(needle)) return String(item)
308  }
309  return null
310}
311
312// The strings in a tool call's arguments that could name a file or carry a command.
313export function toolCallTargets(e) {
314  const keys = ['file_path', 'path', 'pattern', 'glob', 'command', 'notebook_path', 'url']
315  const out = []
316  for (const k of keys) if (typeof e?.[k] === 'string') out.push(e[k])
317  return out
318}
319
320// Whether a tool's result is business data (mail, chat, tasks, files, calendar, finance)
321// extra: more tool or command names (any part of the name) whose results draw as hidden
322export function businessSource(tool, input, extra = []) {
323  const name = String(tool || '')
324  if (BUSINESS_TOOL.test(name)) return true
325  const cmd = input && typeof input.command === 'string' ? input.command : ''
326  const hay = (name + ' ' + cmd).toLowerCase()
327  if (extra.some((x) => x && hay.includes(String(x).toLowerCase()))) return true
328  const command = input && typeof input.command === 'string' ? input.command : ''
329  return command ? BUSINESS_COMMAND.test(command) : false
330}
331
332// extra: more tool names (any part of the name) that stay closed while recording
333export function financeTool(tool, extra = []) {
334  const name = String(tool || '')
335  return FINANCE_TOOL.test(name) || extra.some((x) => x && name.toLowerCase().includes(String(x).toLowerCase()))
336}
337