SLOPSHOPPER

g-line

Live status under Claude Code's prompt, and receipts on the turns themselves: context jumps, cache rebuilds and tool failures marked on the turn's own closing…

panespinnerguardcommandtoastprompt
v0.19.2MITupdated 2026-10-26lifeofgurpreet/g-line
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · g-line
│ ┃ g-line ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ l: Layout two lines r: Receipt adaptive p: │ g-line │ │ ┃ Opus 5.5 ⏺ Read(src/auth.ts) │ glanceline is now g-line: use /g-line. │ │ ┃ context ▰▰▱▱▱ 49% (103k left) ⎿ Read 6 lines │ /glanceline works until the next release. │ │ ┃ 5h ▰▰▱▱▱ 31% ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ $0.42 at API prices ⎿ Added 2 lines, removed 1 line │ ┃ 30m session ⏺ Bash(bun test) │ ┃ Tools (9 calls, 1 failed) ⎿ 3 pass, 1 fail │ ┃ 4 Bash (1 failed) │ ┃ 2 Write ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 1 Read │ ┃ 1 Grep ✻ Worked for 42s · done 4:20 PM │ ┃ 1 Edit │ ┃ Times are this machine's (UTC+0); "tz" in › /g-line │ ┃ config.json sets yours. │ ┃ Pace projects your average rate since each │ ┃ window opened. Totals count only sessions │ ┃ g-line ran in. Layout: │ ┃ model,context,five_hour,seven_day,spend,cach │ ┃ e. │ ┃ [ Share card ] │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ⟨Claude Code's own drawing⟩ Opus 5.5

Draws

Pane · g-line
l: Layout two lines r: Receipt adaptive p: Pulse off s: A Opus 5.5 context ▰▰▱▱▱ 49% (103k left) 5h ▰▰▱▱▱ 31% $0.42 at API prices 30m session Tools (9 calls, 1 failed) 4 Bash (1 failed) 2 Write 1 Read 1 Grep 1 Edit Times are this machine's (UTC+0); "tz" in config.json sets yours. Pace projects your average rate since each window opened. Totals count only sessions g-line ran in. Layout: model,context,five_hour,seven_day,spend,cache. [ Share card ]
Prompt hint
⟨Claude Code's own drawing⟩ Opus 5.5
README

g-line

Live status. Receipts on the turns.

g-line is a Claude Code mod. It writes context jumps, cache rebuilds and tool failures on the turns where they happened, and keeps the model, its effort, the prompt cache and your usage windows in two short lines under the prompt.

In Claude Code 2.1.293 or later, type at the prompt:

/plugin install g-line --marketplace lifeofgurpreet/g-line

Answer y to add the marketplace and pick a scope (user is the usual choice). The mod starts at once, with no restart. /plugin uninstall g-line removes it.

A real Claude Code session with g-line: an ordinary turn closes with "API $0.22 · cache read 49%"; while it runs, the spinner shows its burn; over five idle minutes the cache countdown on the second line runs down, a heads-up warns before it goes cold, and it goes cold; the next turn closes with "cache cold · rebuilt 42k · API $0.31"

What you get

  • A receipt on every turn. The line that closes a turn (Worked for 20s · done 11:01 AM) gains what the turn cost at API prices and how much of its input the prompt cache served: API $0.22 · cache read 49%. A turn that did something unusual leads with it, in colour: +86k context, cache cold · rebuilt 42k, 3 failed Bash calls, compacted 182k → 31k, API $1.42 · 4x recent. Scroll back and you can see which turn changed things.
  • The running turn on the spinner. 3 tools · +4.1k ctx · 5h 74% while it works, and ⚠ 3× Edit failures on core.ts when calls keep failing.
  • Two lines under the prompt. Context and usage at the end of Claude Code's own hint line (ctx 13% · 5h 1% · wk 79%!), and one coloured row with the model, the cache countdown and what happens next (Opus 5.5 high · cache ~59m · wk full in ~1d 4h, back Fri 16:00). Nothing goes above the prompt.
  • Heads-ups. A native notification five minutes before a one-hour prompt cache goes cold, with the context at stake (Claude cache goes cold in 5m (148k of context at risk)), and another when a usage window you came close to resets.
  • The cache after a restart. A resumed conversation (--resume, --continue, a terminal restored after a reboot) shows its cache before its first turn: cache warm ~41m (180k) or cache cold, next turn rebuilds 486k.
  • A dashboard. /g-line dashboard opens a local page with your usage windows, the sessions on this machine, and two weeks of turns, cost and cache rebuilds.

Optional, and off until you turn them on: guard rules for a low usage window, keep-warm for idle prompt caches, and Pulse headlines.

A schema comparison closes with "Baked for 43s · done 1:22 PM · cache cold · rebuilt 42k · API $0.31"; under the prompt, the hint line ends with "ctx 4% · 5h 1% · wk 80%!" and the coloured line reads "Opus 5.5 high · cache warm ~4m · 5h resets in 2h 47m · wk out ~Thu 19:00, resets Fri 16:00"

What you see

The receipt

ReceiptWhen
API $0.22 · cache read 49%An ordinary turn: its cost at API prices and the share of its input the cache served
+86k contextThe turn grew the context by at least 8k tokens, or by 2% of the window when that is more
cache cold · rebuilt 42kThe turn's first request came after the cache's lifetime and rewrote it
cache write 84kA request wrote at least 20k tokens to the cache, well beyond what the context grew
3 failed Bash callsTwo or more tool calls failed in the turn (named when they were all one tool)
compacted 182k → 31kThe context was compacted during the turn
API $1.42 · 4x recentAt least three times the median of your recent turns, and at least 20 cents more
answered by Sonnet 5.5A model other than the one asked for answered (Claude Code fell back)

A receipt records what happened. It says a cold cache was rebuilt and leaves the cause to you. When a background agent ran alongside the turn, the session's cost growth isn't the turn's alone, so the dollar figure is left out. A narrow terminal drops the supporting facts first.

The two lines under the prompt

Line 1 is the end of Claude Code's hint line, drawn dim:

SegmentExampleMeaning
contextctx 13%How full the context window is, from the last response
5h, week5h 1%, wk 79%!Your usage windows. ! means on pace to run out before the reset
spendspend 83%Behind a Claude gateway that sets a spend limit

Line 2 is g-line's own row, in colour:

SegmentExampleMeaning
modelOpus 5.5 highThe model and the effort of the last request (fast when fast mode is on)
cachecache ~59m, cache coldHow long the prompt cache stays warm: green, then amber in its last minutes. ~ because it's an estimate from when the last request ran and the cache's lifetime. After a compaction it shows the summary the next turn will write instead
timingwk full in ~1d 4h, back Fri 16:00How long until a window on pace to run out fills (a projection, so rounded) and when it comes back; otherwise when it resets
agents, compactionagents 2 running, compacts in ~3 turnsWhile subagents work; when a compaction is near
others2 others · 1 waitingOther g-line sessions on this machine, and how many are waiting on you for a permission answer. roster: false turns it off
guardguard: effort medium, kept warm 2× · $0.08Only with your guard rules: what they're doing now

When the terminal narrows, line 2 shortens first (Opus 5.5 to Opus, the effort kept), and what line 1 can't fit moves down rather than disappearing. A healthy window's reset time goes first; a warning keeps its projection the longest.

Line 1 and line 2 at 100 columns At 80 columns

Prefer one line? Set lines to 1: everything goes on the hint line, and Claude Code's standing hint (shift+tab to cycle) shortens to ⇧⇥ to make room. Already using another status line? Set lines to receipts: g-line then adds only the receipts, the spinner and the heads-ups.

The spinner

Sautéing… · 3 tools · +4.1k ctx · 5h 74% while a turn runs, and ⚠ 3× Edit failures on core.ts first once calls keep failing.

The spinner mid-turn: Sprouting… · 2 tools · +1.2k ctx · 5h 1%

The pane, settings and dashboard

/g-line opens a pane with every figure spelled out: limits with bars and reset times on your own clock (5-hour 62% used, resets 14:12 (in 2h 47m)), warnings, agents, the last turns' receipts, what fills the context, tools used and failed, the other sessions on this machine, and today's and this week's totals. Its top row flips common settings with one key (l layout, r receipt, p Pulse); s opens all settings, n the news reader and b the dashboard.

The /g-line pane

/g-line settings lists every setting with its value and where the value comes from (default, config.json, /config or your choice). Press a key and the setting changes at once, in every open session.

/g-line settings: rows grouped under Show, Heads-ups and Extras, such as "l: Layout two lines default" and "p: Pulse on • your choice"

/g-line dashboard writes a local page and opens it in your browser: usage windows, this machine's sessions, and two weeks of history. It loads nothing from the network. See the dashboard.

/g-line card shows a share card of the session, without your repository, branch, paths or account. /g-line off hides everything g-line draws until /g-line on.

Optional features

  • Guard. Rules you write for a low usage window: lower the effort, start new subagents on a cheaper model, or hold new prompts, by window, account, group and office hours, or by pace through the week. With no rules, g-line changes nothing. Everything it does is shown on line 2, in a toast and on the turn's closing line, and /g-line guard simulate tries your rules without spending anything.
  • Keep-warm. Re-reads an idle conversation's prompt cache before its hour runs out, so the next prompt doesn't pay to rebuild it. Each re-read is shown with its cost.
  • Pulse. AI news headlines on a dim row under the prompt, from one static file fetched at most every 45 minutes, with a reader at /g-line news.

Configure

/g-line settings changes every on/off and layout choice. To set them for every session or machine, write ~/.config/g-line/config.json; running sessions pick up an edit within 15 seconds. If you switch accounts with a tool of your own, account_command lets g-line see the switch and share usage readings between sessions. All settings are in Configuration.

{
  "lines": 2,
  "git": true,
  "notify": { "cache": true, "reset": true, "long_turn": true },
  "today_budget": 50
}

Why a mod

A statusLine command is a separate program: Claude Code runs it and prints its output in a status area under the prompt. A mod runs inside Claude Code and can draw on Claude Code's own lines. That is what lets g-line:

  • write a receipt on each turn's own closing line, where it stays in scrollback beside the turn;
  • show the burn and failures on the spinner while the turn runs;
  • put the gauges at the end of the existing hint line, so the footer grows by one row;
  • read each request's cache reads and writes, every tool call and its result, subagents and compactions from the engine as they happen, rather than from the transcript file;
  • offer a /g-line command that runs without a Claude turn, a pane with buttons, and native notifications.

How it compares

From each project's README on 2026-10-14. "Not documented" means not in its docs, not that it can't be done.

g-lineclaude-hudccstatuslineclaude-powerlineccusage
What it isClaude Code modPlugin that sets up a statusLine commandstatusLine commandstatusLine commandUsage-report CLI with a statusline command
Where it drawsThe hint line, one row under it, the spinner, each turn's closing lineIts status lines (two by default)Its status lines, configurableIts status lines, powerline styleIts status line, and separate reports
Receipt on each turn's own lineYesNot documentedNot documentedNot documentedNot documented
Model and effortYesYes (effort optional)Yes (widget)YesWhen Claude Code supplies it
Prompt-cache countdownYes, an estimateOptionalYes (widget)OptionalNot documented
Limits with paceProjected run-out timeUsage windows, pace coloursUsage and reset widgetsUsage with an even-spend pace markerBlock cost, time and burn rate
HistoryReceipts in scrollback; today, this week and a 14-day dashboardOptional cost ledgerSession and compaction widgetsToday and month budgetsDaily, monthly and session reports
Where activity comes fromEngine eventsStatus data; optional lines read the transcriptStatus data, transcript and usage API, by widgetStatus data and local transcripts, by featureLocal usage records
Pick it toSee which turn changed things, beside the workGet a configurable session overviewGet extensive widget customisationGet a styled layout with budgetsGet retrospective usage analysis

Privacy and what it runs

  • Reads: the figures Claude Code hands every mod (usage, turns, tool calls and whether they succeeded, subagents, compactions). It doesn't read the transcript file.
  • Keeps: per session per day, numbers only (cost at API prices, turns, tool calls, cold rebuilds, keep-warm re-reads, agents) in Claude Code's plugin store, deleted after 35 days; your choices made with /g-line; when you last opened the news reader; with Pulse on, the last feed and which headlines it showed today; and, with roster on (the default), each running session's heartbeat (state, context, cache, model, and the account_command line only if you set one), cleared when the session ends.
  • Runs: git status only with git: true or while the pane is open; your account_command and usage_command only if you set them; uname -s once per session, to know whether a browser can open; open (or xdg-open) when you ask to open a link or the dashboard.
  • Sends: nothing, unless Pulse is on (one GET of a static file) or you turn on claude_reads (the snapshot goes into your conversation). With keep-warm in your guard, Claude Code sends your conversation again, through its own client, to re-read the cache.
  • Changes: nothing, unless you write guard rules: then a lower effort, a cheaper model for new subagents, a held prompt, or with resume one prompt after a limit's reset, each as your rule says and each shown.
  • Writes: a one-line timestamp at ~/.cache/glanceline/live/<session id> so an older status line command can step aside; with export_state, a JSON file for other bars; and ~/.cache/g-line/dashboard.html when you ask for the dashboard.

Claude Code already notifies you when it waits for a permission answer or for your input, so g-line adds no "Claude is waiting" notifications of its own.

Upgrading from glanceline

glanceline is now g-line, at lifeofgurpreet/g-line (the old address redirects). Claude Code treats the new name as a new plugin, so an installed glanceline updates to a small stub that tells you, once per session, to switch:

/plugin uninstall glanceline
/plugin install g-line --marketplace lifeofgurpreet/g-line

Your ~/.config/glanceline/config.json keeps working. If you used the old Python status line (glanceline install), run glanceline uninstall once to put your previous statusLine back.

Contributing

Issues and pull requests are welcome; see CONTRIBUTING.md. AGENTS.md has the rules g-line stands on, a map of the code, and recipes for adding a figure or a receipt event.

claude --plugin-dir .        # a session with your working copy; saving reloads it
claude plugin validate .     # what the engine reads, the hooks and calls, what it would refuse
claude plugin test .         # the tests

The terminal screenshots are real captures (tmux capture-pane -e), drawn by scripts/ansi2png.py. The dashboard image is the real page generator run on sample data.

License

MIT

Source 12 files
hooks/register.tsx 2889 lines
1// g-line, the mod: live status under the prompt, receipts on the turns.
2//
3// The live figures ride on lines Claude Code already draws: the hint line
4// under the prompt (context, 5-hour and weekly limits with pace, cache, git),
5// the footer's mode labels (agents at work, when the context will compact),
6// the working spinner (what the turn has cost so far) and the line that
7// closes each turn (`Baked for 1m 4s · $0.38 · 94% cached · 7 tools`).
8// Heads-ups arrive as toasts and native notifications; everything else is in
9// the `/g-line` pane and its share card.
10//
11// Every figure is Claude Code's own (`$.session.usage()`, `session.measure`,
12// `turn.complete`, `$.agent.list()`, `session.compact`, `tool.call`) or what
13// the mod watched happen. No transcript is parsed, nothing is estimated that
14// the engine reports, and nothing leaves the machine.
15
16import { atom, read, update } from 'claude-code'
17import type { EngineInterface, Register } from 'claude-code'
18
19import type { AgentRow, Receipt, Snap, Totals } from '../types'
20import { SEP, alerts, clock, layoutKeys, modelName, pct, segments, str, tokens, utcLabel, width, zoneOffset } from './core'
21import type { Limit } from './roster'
22import { LIMITS_PREFIX, ROSTER_PREFIX, mergeLimits, parseUsage, othersSegment, rosterOf, rosterRow, staleRosterKeys } from './roster'
23import type { RosterEntry, RosterState } from './roster'
24import type { Options, Payload, Preset, Segment, Tone } from './core'
25import {
26  EMPTY_TOTALS, RECEIPT_PRESETS, agentsSegment, cacheHit, cardLines, coach, compactionText, contextView, costRatio,
27  dayOf, fitParts, forecast, forecastSegment, isActive, isEnded, ledger, loopWarning, money, receiptSpec,
28  receiptText, spark, spinnerParts, staleKeys, target, todaySegment, turnLength, turnLineWidth, unusedServers,
29} from './extras'
30import type { ReceiptSpec } from './extras'
31import { MOD_KEYS, accountSegment, inline, joined, modesWidth, shownHint, tailRoom, withText } from './inline'
32import { deck, nextRoom } from './deck'
33import { dashboardHtml } from './dashboard'
34import { STATUS_DESCRIPTION, STATUS_SCHEMA, STATUS_TOOL, statusJson } from './glance'
35import {
36  PULSE_AFTER_MS, PULSE_BEATS, PULSE_EVERY_MS, PULSE_TTL_MS, PULSE_URL, ageOf, clean, countOf, itemNow, keptShown, linksDrawn, mergedShown,
37  muted, opensHere, pageOf, parseFeed, pickNext, pulseRow, safeUrl, tickerText, withShow, xLead,
38} from './pulse'
39import type { PulseFeed, PulseItem, Shown } from './pulse'
40import { gitSegmentOf } from './core'
41import {
42  AGENT_TYPE_MODELS, accountIdentity, accountKey, agentModel, cappedEffort, changeText, drainText, effortKeepsCache, bridgeDue, endText, epochOf, evaluate, groupOf, guardForms, liftsAt, inForceText, leaseFree, namesAccounts, readBack, ruleText, simulated, stopText,
43  resumeAt, warmDue, warmForms, whyLines,
44} from './guard'
45import type { Effort, Facts, Simulation, Verdict, WindowName } from './guard'
46import {
47  DEFAULTS, GROUPS, SETTINGS, changed, merge, nextValue, originOf, parseCommand, patchOf, said, withPatch, withoutSetting,
48} from './settings'
49import type { Config, Layer, Setting } from './settings'
50
51const snap = atom({ plugin: 'g-line', key: 'snap' } as const, {})
52const tick = atom({ plugin: 'g-line', key: 'tick' } as const, 0)
53const seen = atom({ plugin: 'g-line', key: 'seen' } as const, [])
54const hidden = atom({ plugin: 'g-line', key: 'hidden' } as const, false)
55const receipts = atom({ plugin: 'g-line', key: 'receipts' } as const, {})
56const turnNow = atom({ plugin: 'g-line', key: 'turn' } as const, null)
57const agents = atom({ plugin: 'g-line', key: 'agents' } as const, [])
58const totals = atom({ plugin: 'g-line', key: 'totals' } as const, EMPTY_TOTALS)
59const outlook = atom({ plugin: 'g-line', key: 'forecast' } as const, null)
60const contextAtom = atom({ plugin: 'g-line', key: 'context' } as const, null)
61const ledgerAtom = atom({ plugin: 'g-line', key: 'ledger' } as const, null)
62const view = atom({ plugin: 'g-line', key: 'view' } as const, 'details')
63const pulseAtom = atom({ plugin: 'g-line', key: 'pulse' } as const, null)
64const pulseNow = atom({ plugin: 'g-line', key: 'pulseNow' } as const, null)
65const newsAt = atom({ plugin: 'g-line', key: 'newsAt' } as const, 0)
66
67const PANE = 'g-line'
68const INSTALL = '/plugin install g-line --marketplace lifeofgurpreet/g-line'
69/** The command's name, and the 0.4 name it still answers to for one release. */
70const COMMAND = 'g-line'
71const OLD_COMMAND = 'glanceline'
72const TICK_MS = 15_000
73/**
74 * A status line command steps aside while this session's file is under a
75 * minute old. The path keeps the 0.4 name: other tools read it.
76 */
77const LIVE_DIR = '.cache/glanceline/live'
78const STATE_DIR = '.cache/g-line/state'
79
80const COLORS: Record<Tone, string | undefined> = {
81  ok: 'success', warn: 'warning', bad: 'error', accent: 'claude', dim: undefined,
82}
83
84// ----------------------------------------------------------------- config
85
86async function readJson($: EngineInterface, path: string): Promise<unknown> {
87  try {
88    return JSON.parse(String(await $.fs.read(path)))
89  } catch {
90    return undefined
91  }
92}
93
94/** The files config is read from, lowest first, each with the name `/g-line settings` gives it. */
95async function configFiles($: EngineInterface): Promise<{ name: string; path: string }[]> {
96  const files = [{ name: 'plugin', path: `${$.plugin.root}/config.json` }]
97  const xdg = await $.env.get('XDG_CONFIG_HOME')
98  const home = await $.env.get('HOME')
99  const base = xdg || (home ? `${home}/.config` : undefined)
100  // The 0.4 name's file, then the new one: settings carry over across the rename.
101  if (base) {
102    files.push({ name: 'glanceline/config.json', path: `${base}/glanceline/config.json` })
103    files.push({ name: 'config.json', path: `${base}/g-line/config.json` })
104  }
105  return files
106}
107
108/** What /config sets; its rows left at their defaults say nothing. */
109function chosenOf(options: Record<string, unknown>): Record<string, unknown> {
110  const chosen: Record<string, unknown> = {}
111  if (options.lines !== undefined && options.lines !== '2') chosen.lines = options.lines
112  if (options.preset !== undefined && options.preset !== 'default') chosen.preset = options.preset
113  if (options.icons !== undefined && options.icons !== 'none') chosen.icons = options.icons
114  if (options.toasts === false) chosen.toasts = false
115  if (options.notifications === false) chosen.notify = false
116  if (options.receipt !== undefined && options.receipt !== 'adaptive') chosen.receipt = options.receipt
117  return chosen
118}
119
120/** The layer of choices made with /g-line, in the pane or by command. */
121const CHOSEN = 'your choice'
122
123/** Defaults, then the plugin's own config.json, the user's files, /config, then choices made with /g-line: the most recent. */
124async function loadConfig($: EngineInterface, options: Record<string, unknown>): Promise<{ config: Config; layers: Layer[] }> {
125  const found: Layer[] = []
126  for (const file of await configFiles($)) found.push({ name: file.name, raw: await readJson($, file.path) })
127  found.push({ name: '/config', raw: chosenOf(options) })
128  try {
129    found.push({ name: CHOSEN, raw: (await $.store.get(SETTINGS_KEY)) ?? {} })
130  } catch {
131    // no store: the files and /config decide
132  }
133  return { config: found.reduce((c, layer) => merge(c, layer.raw), DEFAULTS), layers: found }
134}
135
136const SETTINGS_KEY = 'settings'
137
138/**
139 * What changes when config is read again: the files' times and the saved
140 * choices (another session's pane writes them). Checked on the beat, so an
141 * edit to ~/.config/g-line/config.json reaches running sessions within 30 s.
142 */
143async function configStamp($: EngineInterface): Promise<string> {
144  const parts: string[] = []
145  for (const file of await configFiles($)) {
146    try {
147      parts.push(String((await $.fs.stat(file.path)).mtimeMs))
148    } catch {
149      parts.push('-')
150    }
151  }
152  try {
153    parts.push(JSON.stringify((await $.store.get(SETTINGS_KEY)) ?? null))
154  } catch {
155    parts.push('-')
156  }
157  return parts.join('|')
158}
159
160/** Reads every layer again and applies what changed. */
161async function reloadConfig($: EngineInterface): Promise<void> {
162  const before = config
163  ;({ config, layers } = await loadConfig($, startOptions))
164  stamp = await configStamp($)
165  await applied($, before)
166}
167
168/** Makes a change of settings take effect in this session, without a restart. */
169async function applied($: EngineInterface, before: Config): Promise<void> {
170  if (config.cacheTtl !== before.cacheTtl) ttl = await explicitTtl($, config)
171  if (config.exportState !== before.exportState) await setupLive($)
172  if (config.claudeReads && !statusRegistered) await registerStatus($)
173  if (config.pulse && !before.pulse) {
174    await refreshPulse($, true)
175    await readTerminal($)
176  }
177  await update($, tick, n => n + 1)
178}
179
180/** Saves the choice for later sessions and applies it now. */
181async function choose($: EngineInterface, patch: Record<string, unknown>): Promise<void> {
182  const held = layers.find(layer => layer.name === CHOSEN)?.raw
183  let saved = (held && typeof held === 'object' ? held : {}) as Record<string, unknown>
184  try {
185    saved = ((await $.store.get(SETTINGS_KEY)) ?? {}) as Record<string, unknown>
186  } catch {
187    // the choice holds for this session
188  }
189  await keep($, withPatch(saved, patch))
190}
191
192/** Replaces the saved choices: they now decide, over the files and /config. */
193async function keep($: EngineInterface, saved: Record<string, unknown>): Promise<void> {
194  try {
195    await $.store.set(SETTINGS_KEY, saved)
196  } catch {
197    // the choice holds for this session
198  }
199  const before = config
200  layers = [...layers.filter(layer => layer.name !== CHOSEN), { name: CHOSEN, raw: saved }]
201  config = layers.reduce((c, layer) => merge(c, layer.raw), DEFAULTS)
202  stamp = await configStamp($)
203  await applied($, before)
204}
205
206/** The toast after a setting changes: its new value, and when it takes effect if not at once. */
207function changedText(setting: Setting): string {
208  const value = said(setting, config)
209  const note = setting.key === 'claude_reads'
210    ? (config.claudeReads ? ' Claude can call g-line\'s status tool from your next message.' : ' The status tool now answers that it is off, and is gone in new sessions.')
211    : setting.key === 'pulse' && config.pulse ? ' Headlines from g-line\'s feed on long turns and in /g-line; one static file, fetched every 45 minutes.'
212      : setting.key === 'pulse' ? ' No fetches.' : ''
213  return `${setting.label}: ${value}.${note}`
214}
215
216// ------------------------------------------------------------------ cache
217
218/** A model id without its context-size tag or date: `claude-opus-5-5[1m]` and `claude-opus-5-5` are one model. */
219function plainModel(id: string): string {
220  return modelName(id).replace(' (1M)', '')
221}
222
223function truthy(value: string | undefined): boolean {
224  return value !== undefined && value !== '' && value !== '0' && value.toLowerCase() !== 'false'
225}
226
227/**
228 * The TTL Claude Code writes for the main conversation, by its documented
229 * rule: FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the
230 * promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H; unset, one hour on a
231 * subscription within its limits and five minutes otherwise. A hit or miss
232 * the mod observed after an idle gap overrides the rule.
233 */
234async function explicitTtl($: EngineInterface, config: Config): Promise<'5m' | '1h' | undefined> {
235  if (config.cacheTtl !== 'auto') return config.cacheTtl
236  if (truthy(await $.env.get('FORCE_PROMPT_CACHING_5M'))) return '5m'
237  const env = await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL')
238  if (env === '5m' || env === '1h') return env
239  try {
240    const setting = (await $.settings.read()).promptCacheTtl
241    if (setting === '5m' || setting === '1h') return setting
242  } catch {
243    // settings unreadable: fall through to the automatic rule
244  }
245  if (truthy(await $.env.get('ENABLE_PROMPT_CACHING_1H'))) return '1h'
246  return undefined
247}
248
249/**
250 * Claude Code's idle compaction: on unless `"idleCompaction": false`, for an
251 * hour-long cache holding at least `CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS`
252 * (200k unset). It summarises the conversation shortly before the cache expires.
253 */
254type IdleCompaction = { minTokens: number }
255
256async function idleCompactionOf($: EngineInterface): Promise<IdleCompaction | undefined> {
257  try {
258    if ((await $.settings.read()).idleCompaction === false) return undefined
259  } catch {
260    // settings unreadable: Claude Code's default, on
261  }
262  // Claude Code turns idle compaction on per account, out of sight: it counts
263  // here only once a session on this machine was seen compacting while idle.
264  try {
265    const seen = Number(await $.store.get(IDLE_SEEN_KEY))
266    if (!(seen > 0) || (await nowMs($)) - seen > IDLE_SEEN_MS) return undefined
267  } catch {
268    return undefined
269  }
270  const min = Number(await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS'))
271  return { minTokens: Number.isFinite(min) && min > 0 ? Math.max(100_000, min) : 200_000 }
272}
273
274/**
275 * Where hooks.json's SessionStart command leaves Claude Code's own figures for
276 * a resumed conversation (`--resume`, `--continue`, a terminal brought back
277 * after a restart): how long ago its last response came, what the next request
278 * sends, and whether Claude Code reckons the cache expired. Such a process has
279 * made no request, so there's nothing of its own to time the cache from. A
280 * command hook runs beneath every hooks module, so a managed plugin seated
281 * ahead can't send the event on past it. One file per session, read once.
282 */
283const RESUME_DIR = '.cache/g-line/resume'
284/** Beats left to look for the file: the command may finish after `session.start`. */
285let resumeLooks = 8
286
287async function readResumed($: EngineInterface): Promise<void> {
288  if (resumeLooks <= 0) return
289  resumeLooks -= 1
290  try {
291    const home = await $.env.get('HOME')
292    if (!home || !sessionId) return
293    const path = `${home}/${RESUME_DIR}/${sessionId}.json`
294    let figures: Record<string, unknown>
295    try {
296      figures = JSON.parse(String(await $.fs.read(path))) as Record<string, unknown>
297    } catch {
298      return
299    }
300    resumeLooks = 0
301    await $.process.run(['rm', '-f', path], { timeoutMs: 2000 }).catch(() => undefined)
302    const now = await nowSeconds($)
303    const { at, since, context, expired } = figures
304    if (typeof at !== 'number' || typeof since !== 'number' || typeof context !== 'number') return
305    // Written for this start, not left over from an earlier one.
306    if (since < 0 || context <= 0 || Math.abs(now - at) > 600) return
307    // Claude Code's own verdict settles the lifetime where the age alone can't.
308    const learned = expired === true && since < 3600 ? '5m' : expired === false && since > 300 ? '1h' : undefined
309    const cache: NonNullable<Snap['cache']> = { lastAt: Math.floor(at - since), cached: true, prefix: context, restored: true }
310    if (learned) cache.learned = learned
311    // A request this process made since knows better.
312    await update($, snap, s => (s.cache && !s.cache.restored ? s : { ...s, cache }))
313  } catch {
314    // the line waits for the first request, as before
315  }
316}
317
318/** When a session on this machine last compacted while idle (ms), and how long that counts. */
319const IDLE_SEEN_KEY = 'idle-compaction-seen'
320const IDLE_SEEN_MS = 14 * 86_400_000
321
322/** An idle compaction seen: from now on Claude Code's idle compaction counts on this machine. */
323async function idleCompactionSeen($: EngineInterface): Promise<void> {
324  try {
325    await $.store.set(IDLE_SEEN_KEY, await nowMs($))
326  } catch {
327    // this session's own view
328  }
329  idle = await idleCompactionOf($)
330}
331
332function automaticTtl(s: Snap): '5m' | '1h' {
333  const limits = s.rateLimits ?? []
334  const subscription = limits.some(l => l.kind === 'five_hour' || l.kind === 'seven_day')
335  const within = limits.every(l => l.percentUsed < 100)
336  return subscription && within ? '1h' : '5m'
337}
338
339// ---------------------------------------------------------------- payload
340
341/** The statusLine-shaped view of what the mod knows, for the core. */
342export function payload(s: Snap, nowSeconds: number, ttl: '5m' | '1h' | undefined, idle?: IdleCompaction): Payload {
343  const p: Payload = {}
344  if (s.model) p.model = { display_name: modelName(s.model) }
345  if (s.effort) p.effort = { level: s.effort, ...(s.effortSet ? { set: s.effortSet } : {}) }
346  if (s.context && s.context.percent !== undefined) {
347    p.context_window = { used_percentage: s.context.percent, context_window_size: s.context.window,
348      total_input_tokens: s.context.tokens }
349  }
350  const limits: NonNullable<Payload['rate_limits']> = {}
351  for (const limit of s.rateLimits ?? []) {
352    if (limit.kind === 'five_hour' || limit.kind === 'seven_day' || limit.kind === 'spend_limit') {
353      limits[limit.kind] = { used_percentage: limit.percentUsed, resets_at: limit.resetsAt }
354    }
355  }
356  if (Object.keys(limits).length) p.rate_limits = limits
357  if (s.costUsd !== undefined || s.startedAt !== undefined) {
358    p.cost = { total_cost_usd: s.costUsd,
359      total_duration_ms: s.startedAt !== undefined ? nowSeconds * 1000 - s.startedAt : undefined }
360  }
361  if (s.cache?.cached) {
362    const effective = s.cache.learned ?? ttl ?? automaticTtl(s)
363    const expires = s.cache.lastAt + (effective === '1h' ? 3600 : 300)
364    const compacted = s.cache.compactedTo !== undefined
365    const moved = s.cache.accountChanged === true
366    p.prompt_cache = { caching_observed: true, ttl: effective, warm: !compacted && !moved && expires > nowSeconds, expires_at: expires,
367      recache_tokens_if_cold: compacted ? s.cache.compactedTo || undefined : s.cache.prefix }
368    if (compacted) p.prompt_cache.compacted = true
369    else if (moved) p.prompt_cache.account_changed = true
370    else if (idle && effective === '1h' && s.cache.prefix >= idle.minTokens) p.prompt_cache.idle_compacts = true
371  }
372  if (s.git) p.git = s.git
373  return p
374}
375
376// ------------------------------------------------------------------ mod
377
378let config: Config = DEFAULTS
379/** Where config came from, lowest first: `/g-line settings` names the layer each value is from. */
380let layers: Layer[] = []
381/** The config files' times and the saved choices when last read. */
382let stamp = ''
383let startOptions: Record<string, unknown> = {}
384let statusRegistered = false
385let ttl: '5m' | '1h' | undefined
386let idle: IdleCompaction | undefined
387let beats = 0
388let liveFile: string | undefined
389let stateFile: string | undefined
390let sessionId: string | undefined
391/** The receipt of the main-loop turn that just ended, until its closing line is appended. */
392let pending: Promise<Receipt> | undefined
393/** The hint line's last text: `1 shell` and the like say background work is running. */
394let lastHint = ''
395/** Whether this turn's first request rebuilt a cold cache. */
396let coldThisTurn = false
397/** Whether the last account reading failed or ran out of time. */
398let accountMissed = false
399/** When the account was last read (ms): after a turn it's read again if older than two minutes. */
400let accountAt = 0
401/** A reading is due within two minutes of a turn, so the account its cache was written under gets confirmed. */
402let accountSoon = false
403/** The messages the next request is built from, counted once the last request's session went idle. */
404let idleCount: { lastAt: number; messages: number } | undefined
405/** Pulse's 8-second beats so far; the row moves on every `PULSE_BEATS[speed]` of them. */
406let pulseBeats = 0
407/** Consecutive failures per agent, tool and target. */
408const streaks = new Map<string, number>()
409
410const UNREADABLE = JSON.stringify({ schema: 1, state: 'unavailable' })
411const STATUS_OFF = JSON.stringify({ schema: 1, state: 'disabled', note: 'The person turned this tool off (/g-line set claude_reads on turns it back on).' })
412const BACKGROUND = /\b\d+ (?:shells?|monitors?|tasks?|agents?|workflows?|background)\b/i
413/** Columns a receipt leaves for Claude Code's own words on a closing line that reports background work. */
414const BACKGROUND_ROOM = 64
415/** The settings the details view offers at once; the rest are a key away. */
416const QUICK = SETTINGS.filter(setting => ['lines', 'receipt', 'pulse'].includes(setting.key))
417
418async function nowMs($: EngineInterface): Promise<number> {
419  return $.clock.now()
420}
421
422async function nowSeconds($: EngineInterface): Promise<number> {
423  return (await $.clock.now()) / 1000
424}
425
426/** Minutes east of UTC at `ms` where the person is: their `tz`, else the machine's zone. */
427const offsetAt = (ms: number) => zoneOffset(config.tz, ms) ?? -new Date(ms).getTimezoneOffset()
428
429/** The last usage readings sessions on this machine shared for an account. */
430let shared: { account: string; limits: unknown } | undefined
431
432/** What the person's `usage_command` last printed, for the account it was read under. */
433let fed: { account: string; limits: Limit[] } | undefined
434/** When `usage_command` last ran (ms); it runs about every two minutes. */
435let usageAt = 0
436/**
437 * When this session last got an API response (seconds): the engine's usage
438 * figures come from the latest one, so this is when they were observed. Until
439 * the first, the engine's figures carry no time and any timed reading wins.
440 */
441let lastResponseAt: number | undefined
442
443/** This session's reading with what other sessions on the same account last shared, and `usage_command` printed. */
444function withShared(account: string | null | undefined, own: Snap['rateLimits'], now: number): Snap['rateLimits'] {
445  if (!config.accountCommand || !account) return own
446  const key = accountKey(account)
447  let out = own
448  if (shared && shared.account === key) out = mergeLimits(out, shared.limits, now)
449  if (config.usageCommand && fed && fed.account === key) out = mergeLimits(out, fed.limits, now)
450  return out
451}
452
453/**
454 * Runs the person's `usage_command` about every two minutes, only with an
455 * `account_command` and a known account: it can say what another machine spent.
456 * Output that isn't the JSON, or a failure, leaves the readings alone; a good
457 * one merges like a shared reading, so it raises a figure and never lowers it.
458 */
459async function refreshUsage($: EngineInterface): Promise<void> {
460  const command = config.usageCommand
461  if (!command || !config.accountCommand) return
462  const now = await nowMs($)
463  if (now - usageAt < 120_000) return
464  usageAt = now
465  try {
466    const account = (await read($, snap)).account
467    if (!account) {
468      usageAt = 0
469      return
470    }
471    const run = await $.process.run(command, { timeoutMs: 5000 })
472    if (run.exitCode !== 0) return
473    const limits = parseUsage(run.stdout, Math.floor(now / 1000))
474    if (!limits) return
475    const key = accountKey(account)
476    const at = (await nowMs($)) / 1000
477    fed = { account: key, limits: mergeLimits(fed?.account === key ? fed.limits : [], limits, at) }
478    const s = await read($, snap)
479    const merged = mergeLimits(s.rateLimits, limits, at)
480    if (JSON.stringify(merged) !== JSON.stringify(s.rateLimits ?? [])) {
481      await update($, snap, x => ({ ...x, rateLimits: merged, peaks: peaksOf(x, merged) }))
482    }
483  } catch {
484    // the command failed or ran out of time: the readings stand
485  }
486}
487
488/**
489 * Shares this session's usage readings with the other sessions on this machine
490 * on the same account, and takes theirs: an idle terminal reads what a busy one
491 * on the same account just spent. Only with an account reading, so two
492 * accounts never mix.
493 */
494async function shareLimits($: EngineInterface): Promise<void> {
495  const s = await read($, snap)
496  if (!config.accountCommand || !s.account) return
497  try {
498    const key = accountKey(s.account)
499    const value = await $.store.get(`${LIMITS_PREFIX}${key}`)
500    const theirs = value && typeof value === 'object' ? (value as { limits?: unknown }).limits : undefined
501    shared = { account: key, limits: theirs }
502    const merged = mergeLimits(s.rateLimits, theirs, (await nowMs($)) / 1000)
503    if (JSON.stringify(merged) !== JSON.stringify(s.rateLimits ?? [])) {
504      await update($, snap, x => ({ ...x, rateLimits: merged, peaks: peaksOf(x, merged) }))
505    }
506    if (merged.length) await $.store.set(`${LIMITS_PREFIX}${key}`, { at: await nowMs($), limits: merged })
507  } catch {
508    // the store is busy: this session's own reading stands
509  }
510}
511
512function limitsOf(list: readonly { kind: string; percentUsed: number; resetsAt?: string }[], at?: number): Snap['rateLimits'] {
513  return list.map(l => ({ kind: l.kind, percentUsed: l.percentUsed,
514    resetsAt: l.resetsAt ? Math.floor(Date.parse(l.resetsAt) / 1000) : undefined, ...(at !== undefined ? { at } : {}) }))
515}
516
517/** The highest percent each window has reached, so a reset can say what it freed. */
518function peaksOf(s: Snap, limits: Snap['rateLimits']): Snap['peaks'] {
519  const peaks = { ...(s.peaks ?? {}) }
520  for (const l of limits ?? []) {
521    if ((l.kind === 'five_hour' || l.kind === 'seven_day') && l.resetsAt) {
522      const key = `${l.kind}:${l.resetsAt}`
523      peaks[key] = Math.max(peaks[key] ?? 0, l.percentUsed)
524    }
525  }
526  return peaks
527}
528
529/**
530 * The cache once the engine's context count falls below half the last
531 * request's prefix with no request since: a compaction replaced the
532 * conversation, whether or not a `session.compact` reached the mod.
533 */
534function shrunk(cache: Snap['cache'], context: number | undefined): Snap['cache'] {
535  if (!cache || context === undefined || context <= 0 || cache.compactedTo) return cache
536  return context < cache.prefix / 2 ? { ...cache, compactedTo: context } : cache
537}
538
539/** Marks the cached conversation replaced by a compaction, `after` tokens when known. */
540async function markCompacted($: EngineInterface, after?: number): Promise<void> {
541  await update($, snap, s => (s.cache
542    ? { ...s, cache: { ...s.cache, compactedTo: after ?? s.cache.compactedTo ?? 0 } }
543    : s))
544}
545
546/**
547 * Idle compaction reports itself through `session.compact` and the
548 * `compaction` door, and a managed plugin seated ahead of this one can send
549 * both on past it; Claude Code's context count then waits for the next
550 * request. What stays readable is the conversation the next request is built
551 * from: counted once the session is idle, it falls below half when a
552 * compaction replaces it with a summary.
553 */
554async function watchIdle($: EngineInterface): Promise<void> {
555  const cache = (await read($, snap))?.cache
556  if (!cache?.cached || cache.compactedTo !== undefined) return
557  if ((await nowSeconds($)) - cache.lastAt < 60) return
558  const messages = (await $.session.messages({ as: 'api' })).length
559  if (idleCount?.lastAt !== cache.lastAt) idleCount = { lastAt: cache.lastAt, messages }
560  else if (messages < idleCount.messages / 2) {
561    await markCompacted($)
562    await idleCompactionSeen($)
563  }
564}
565
566async function measure($: EngineInterface): Promise<void> {
567  const usage = await $.session.usage()
568  const limits = withShared((await read($, snap)).account, limitsOf(usage.rateLimits, lastResponseAt), await nowSeconds($))
569  await update($, snap, s => ({
570    ...s,
571    startedAt: usage.startedAt,
572    context: { tokens: usage.context.tokens, window: usage.context.window, percent: usage.context.percent },
573    rateLimits: limits,
574    costUsd: usage.cost?.usd,
575    peaks: peaksOf(s, limits),
576    cache: shrunk(s.cache, usage.context.tokens),
577  }))
578}
579
580async function refreshGit($: EngineInterface, force = false): Promise<void> {
581  if (!force && !layoutHas('git')) return
582  try {
583    const run = await $.process.run(
584      ['git', '--no-optional-locks', 'status', '--porcelain=v1', '--branch', '--untracked-files=no'],
585      { timeoutMs: 2000 })
586    if (run.exitCode !== 0) {
587      await update($, snap, s => ({ ...s, git: null }))
588      return
589    }
590    const [head = '', ...rest] = run.stdout.split('\n')
591    const name = head.replace(/^## /, '').replace(/^No commits yet on /, '').split('...')[0]?.split(' ')[0]
592    const branch = name === 'HEAD' ? 'detached' : str(name, 40)
593    await update($, snap, s => ({ ...s, git: { branch, dirty: rest.some(line => line.trim()) } }))
594  } catch {
595    // no git, or too slow: keep the last reading
596  }
597}
598
599/**
600 * The account line, read again every ten minutes. A command that answers says
601 * what is now known, an empty line included; one that fails or runs past its
602 * time on a loaded box says nothing, so the last reading stays and the next
603 * try comes a minute later.
604 */
605async function refreshAccount($: EngineInterface): Promise<void> {
606  const command = config.accountCommand
607  if (!command) return
608  try {
609    const run = await $.process.run(command, { timeoutMs: 5000 })
610    accountMissed = run.exitCode !== 0
611    if (accountMissed) return
612    const confirmedAt = accountAt
613    accountAt = await nowMs($)
614    const line = str(run.stdout.split('\n')[0], 120)
615    const before = (await read($, snap)).account
616    // Another account: caches are kept per organization, so the cache this
617    // session counted on isn't the new account's. Count it cold, but only a
618    // cache written before the old account's last confirmed reading: one
619    // written since may already be the new account's (the switch came while
620    // idle and the turn after it ran on the new one before this reading).
621    const moved = !!before && !!line && accountIdentity(before) !== accountIdentity(line)
622    const cold = (c: Snap['cache']) => moved && !!c?.cached && c.lastAt * 1000 <= confirmedAt
623    await update($, snap, s => ({ ...s, account: line ?? null,
624      cache: cold(s.cache) && s.cache ? { ...s.cache, accountChanged: true } : s.cache }))
625    if (cold((await read($, snap)).cache)) {
626      await toast($, 'The account changed: prompt caches are kept per organization, so the next turn starts a new cache.', 10_000)
627    }
628  } catch {
629    accountMissed = true
630  }
631}
632
633function optionsAt(seconds: number): Options {
634  return { now: seconds, preset: config.preset, segments: config.segments, icons: config.icons,
635    utcOffsetMinutes: offsetAt(seconds * 1000) }
636}
637
638/** A heads-up that reaches you in another app, or a toast when no channel takes it. */
639async function heads($: EngineInterface, text: string, title: string, notify: boolean): Promise<void> {
640  if (await read($, hidden)) return
641  if (notify) {
642    try {
643      if ((await $.ui.notify(text, { title })).isSent) return
644    } catch {
645      // a hook refused it, or the write failed: fall back to the toast
646    }
647  }
648  await toast($, text, 12_000)
649}
650
651/** A terminal toast, unless toasts are off or `/g-line off` hid the mod. */
652async function toast($: EngineInterface, text: string, timeoutMs: number): Promise<void> {
653  if (config.toasts && !(await read($, hidden))) $.ui.toast(text, { timeoutMs })
654}
655
656/** Puts a command in the prompt box for Tab to take, unless the mod is hidden. */
657async function suggest($: EngineInterface, text: string): Promise<void> {
658  if (!(await read($, hidden))) await $.prompt.suggest({ text }).catch(() => undefined)
659}
660
661/** Marks an id as handled; true the first time. */
662async function once($: EngineInterface, id: string): Promise<boolean> {
663  if ((await read($, seen)).includes(id)) return false
664  await update($, seen, list => (list.includes(id) ? list : [...list, id].slice(-100)))
665  return true
666}
667
668/** True the first time any session asks about `key`; the store keeps it across sessions. */
669async function firstAcrossSessions($: EngineInterface, key: string): Promise<boolean> {
670  try {
671    if ((await $.store.get(key)) !== undefined) return false
672    await $.store.set(key, Math.floor(await nowSeconds($)))
673    return true
674  } catch {
675    return true
676  }
677}
678
679async function nudge($: EngineInterface): Promise<void> {
680  const seconds = await nowSeconds($)
681  const s = await read($, snap)
682  const p = payload(s, seconds, ttl, idle)
683  for (const alert of alerts(p, optionsAt(seconds))) {
684    if (!(await once($, alert.id))) continue
685    if (alert.id.startsWith('cache:')) {
686      await heads($, alert.text, 'Prompt cache', config.notify.cache)
687      continue
688    }
689    // The coach speaks once per 5-hour window across every session, so a new
690    // session in a hot window doesn't offer the same command again.
691    const advice = config.coach && alert.id.startsWith('five_hour:') && (await firstAcrossSessions($, `coach:${alert.id}`))
692      ? coach('five_hour', p.rate_limits?.five_hour, seconds, s.effort, offsetAt(seconds * 1000)) : undefined
693    await toast($, advice ? advice.text : alert.text, 15_000)
694    if (advice) await suggest($, advice.suggest)
695  }
696  // A window that reset while you were near or at its limit.
697  for (const [key, peak] of Object.entries(s.peaks ?? {})) {
698    const [kind, at] = key.split(':')
699    const resetAt = Number(at)
700    if (!Number.isFinite(resetAt) || resetAt > seconds || seconds - resetAt > 6 * 3600) continue
701    if (peak < config.resetThreshold || !(await once($, `reset:${key}`))) continue
702    const name = kind === 'five_hour' ? '5-hour' : 'weekly'
703    await heads($, `Your ${name} usage window has reset. You'd reached ${pct(peak)} of it.`, 'Usage window reset', config.notify.reset)
704  }
705}
706
707/**
708 * Tells any status line command configured in this session (an older
709 * glanceline, a team's own) that the mod draws these figures, so they never
710 * show twice: such a command reads the file named after its session id and
711 * steps aside while it is under a minute old. Nothing else is in it.
712 */
713async function markLive($: EngineInterface): Promise<void> {
714  if (!liveFile) return
715  try {
716    await $.fs.write(liveFile, `${Math.floor(await nowSeconds($))}\n`)
717  } catch {
718    // unwritable home: such a command keeps drawing, which is only redundant
719  }
720}
721
722async function setupLive($: EngineInterface): Promise<void> {
723  try {
724    const home = await $.env.get('HOME')
725    const id = await $.session.id()
726    if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) return
727    sessionId = id
728    if (!home) return
729    liveFile = `${home}/${LIVE_DIR}/${id}`
730    stateFile = config.exportState ? `${home}/${STATE_DIR}/${id}.json` : undefined
731    await markLive($)
732    // Forget sessions that ended more than a day ago.
733    await $.process.run(['find', `${home}/${LIVE_DIR}`, '-type', 'f', '-mmin', '+1440', '-delete'], { timeoutMs: 2000 })
734    if (stateFile) await $.process.run(['find', `${home}/${STATE_DIR}`, '-type', 'f', '-mmin', '+1440', '-delete'], { timeoutMs: 2000 })
735  } catch {
736    // best effort
737  }
738}
739
740/** The figures as JSON for tmux, sketchybar and other bars, when `export_state` is on. */
741async function exportState($: EngineInterface): Promise<void> {
742  if (!stateFile) return
743  try {
744    const seconds = await nowSeconds($)
745    const s = await read($, snap)
746    const p = payload(s, seconds, ttl, idle)
747    const active = (await read($, agents)).filter(row => isActive(row.status)).length
748    const body = {
749      updatedAt: Math.floor(seconds), line: joined(inline(p, optionsAt(seconds))),
750      model: p.model?.display_name, context: p.context_window?.used_percentage,
751      fiveHour: p.rate_limits?.five_hour?.used_percentage, sevenDay: p.rate_limits?.seven_day?.used_percentage,
752      cache: p.prompt_cache ? { warm: p.prompt_cache.warm, expiresAt: p.prompt_cache.expires_at } : undefined,
753      agents: active, cost: s.costUsd,
754    }
755    await $.fs.write(stateFile, `${JSON.stringify(body)}\n`)
756  } catch {
757    // best effort
758  }
759}
760
761// ----------------------------------------------------------------- agents
762
763/** Reads the engine's agent list and says when a background agent ends. */
764async function refreshAgents($: EngineInterface): Promise<void> {
765  let list
766  try {
767    list = await $.agent.list()
768  } catch {
769    return
770  }
771  const at = await nowMs($)
772  const before = await read($, agents)
773  const ended: AgentRow[] = []
774  const rows = before.map(row => {
775    const live = list.find(one => one.id === row.id)
776    const status = live?.status ?? (isActive(row.status) ? 'ended' : row.status)
777    const next = { ...row, status, endedAt: row.endedAt ?? (isEnded(status) ? at : undefined) }
778    if (isActive(row.status) && isEnded(status)) ended.push(next)
779    return next
780  })
781  for (const one of list) {
782    if (rows.some(row => row.id === one.id)) continue
783    rows.push({ id: one.id, description: one.description, type: one.type, status: one.status,
784      background: true, teammate: one.teammateId !== undefined, startedAt: at,
785      endedAt: isEnded(one.status) ? at : undefined })
786  }
787  await update($, agents, () => rows.slice(-50))
788  for (const row of ended) {
789    if (!row.background) continue
790    const what = `"${row.description.slice(0, 60)}"`
791    if (row.status === 'failed' || row.status === 'killed') {
792      await heads($, `Background agent ${what} ${row.status === 'failed' ? 'failed' : 'was stopped'}.`, 'Agent', config.notify.agents)
793    } else if (config.notify.agents) {
794      await heads($, `Background agent ${what} finished.`, 'Agent', true)
795    }
796  }
797}
798
799// ----------------------------------------------------------------- turns
800
801/** The receipt of a main-loop turn, from the engine's ledger and the turn's usage. */
802async function receiptOf($: EngineInterface, e: { durationMs: number; usage?: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number } }): Promise<Receipt> {
803  const live = await read($, turnNow)
804  let cost: number | undefined
805  let context: number | undefined
806  try {
807    const usage = await $.session.usage()
808    if (usage.cost && live?.costAt !== undefined) cost = Math.max(0, usage.cost.usd - live.costAt)
809    if (usage.context.tokens !== undefined && live?.contextAt !== undefined) context = usage.context.tokens - live.contextAt
810  } catch {
811    // no ledger: the receipt shows what the turn's usage says
812  }
813  const rows = await read($, agents)
814  const active = rows.some(row => isActive(row.status))
815  const overlap = (live?.overlap ?? false) || rows.some(row => row.background && isActive(row.status))
816  const earlier = Object.values(await read($, receipts)).sort((x, y) => x.endAt - y.endAt).slice(-20)
817    .filter(one => one.cost !== undefined && one.cost > 0 && !one.overlap).map(one => one.cost as number)
818  let window: number | undefined
819  try {
820    window = (await read($, snap)).context?.window
821  } catch {
822    window = undefined
823  }
824  return {
825    cost, context, cacheHit: e.usage ? cacheHit(e.usage) : undefined,
826    tools: live?.tools ?? 0, agents: live?.agents ?? 0, output: e.usage?.output_tokens,
827    endAt: await nowMs($), durationMs: e.durationMs, background: active || BACKGROUND.test(lastHint),
828    cacheWrite: live?.cacheWrite, warmBefore: live?.warmBefore, failures: live?.failures,
829    failedTool: live?.failedTool ?? undefined, overlap, cold: live?.cold, compacted: live?.compacted, window,
830    ratio: costRatio(cost, overlap, earlier),
831    guardEffort: live?.guardEffort, guardAgents: live?.guardAgents, guardEnded: live?.guardEnded, servedBy: live?.servedBy, accountChanged: live?.accountChanged,
832  }
833}
834
835/** After a main-loop turn: totals, the forecast, the context view and the day's ledger. */
836async function afterTurn($: EngineInterface, r: Receipt, aborted: boolean): Promise<void> {
837  let context: number | undefined
838  let percent: number | undefined
839  let breakdown
840  try {
841    const usage = await $.session.usage({ breakdown: 'summary' })
842    context = usage.context.tokens
843    percent = usage.context.percent
844    breakdown = usage.context.breakdown
845    await update($, snap, s => ({ ...s, context: { tokens: usage.context.tokens, window: usage.context.window,
846      percent: usage.context.percent }, costUsd: usage.cost?.usd ?? s.costUsd }))
847  } catch {
848    // keep the last figures
849  }
850  const cold = r.cold === true
851  const t = await update($, totals, x => ({
852    ...x, turns: x.turns + 1, colds: x.colds + (cold ? 1 : 0),
853    peakContext: Math.max(x.peakContext, percent ?? 0),
854    growth: r.context !== undefined && r.context >= 0 ? [...x.growth, r.context].slice(-8) : x.growth,
855  }))
856  const at = await nowMs($)
857  if (breakdown) await update($, contextAtom, () => contextView(breakdown, at))
858  const f = forecast(context, breakdown?.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined, t.growth) ?? null
859  await update($, outlook, () => f)
860  if (f && f.turns <= 2 && (await once($, `compact:${t.compactions.length}`))) {
861    await toast($, `Context compacts ${f.turns <= 1 ? 'soon' : `in ~${f.turns} turns`}. To choose what's kept, run /compact with a note now${config.coach ? ' (Tab starts one)' : ''}.`, 15_000)
862    if (config.coach) await suggest($, '/compact keep ')
863  }
864  if (!aborted && r.durationMs >= config.longTurnSeconds * 1000 && config.notify.longTurn) {
865    const cost = r.cost !== undefined && r.cost > 0 ? ` · ${money(r.cost)}` : ''
866    await heads($, `Turn finished after ${turnLength(r.durationMs)}${cost}.`, 'Claude Code', true)
867  }
868  await addToDay($, r, cold, at)
869}
870
871/** Adds the turn to this session's entry for the day, then sums every session's. */
872async function addToDay($: EngineInterface, r: Receipt, cold: boolean, at: number): Promise<void> {
873  if (!sessionId) return
874  const today = dayOf(at, offsetAt(at))
875  const key = `d:${today}:${sessionId}`
876  try {
877    const old = ((await $.store.get(key)) ?? {}) as Record<string, number>
878    await $.store.set(key, {
879      ...old, cost: (old.cost ?? 0) + (r.cost ?? 0), turns: (old.turns ?? 0) + 1, tools: (old.tools ?? 0) + r.tools,
880      colds: (old.colds ?? 0) + (cold ? 1 : 0), agents: (old.agents ?? 0) + r.agents,
881    })
882    await refreshLedger($, at)
883  } catch {
884    // the store is full or unwritable: the line and pane go on without it
885  }
886}
887
888/** A keep-warm re-read in today's entry: one more, and its cost when the engine counted one. */
889async function addWarmToDay($: EngineInterface, cost: number | undefined, at: number): Promise<void> {
890  if (!sessionId) return
891  const key = `d:${dayOf(at, offsetAt(at))}:${sessionId}`
892  try {
893    const old = ((await $.store.get(key)) ?? {}) as Record<string, number>
894    await $.store.set(key, { ...old, cost: (old.cost ?? 0) + (cost ?? 0), warms: (old.warms ?? 0) + 1, warmCost: (old.warmCost ?? 0) + (cost ?? 0) })
895    await refreshLedger($, at)
896  } catch {
897    // the store is full or unwritable
898  }
899}
900
901async function refreshLedger($: EngineInterface, at: number): Promise<void> {
902  const today = dayOf(at, offsetAt(at))
903  const keys = (await $.store.keys()).filter(key => key.startsWith('d:'))
904  const recent = keys.filter(key => !staleKeys([key], today, 7).length)
905  const entries = await Promise.all(recent.map(async key => ({ key, value: await $.store.get(key) })))
906  const l = ledger(entries, today)
907  await update($, ledgerAtom, () => l)
908  if (config.budget && l.today.cost >= config.budget && (await once($, `budget:${today}`))) {
909    await heads($, `Today's usage across sessions reached ${money(l.today.cost)} at API prices, past your ${money(config.budget)} budget.`, 'Daily budget', false)
910  }
911}
912
913async function pruneLedger($: EngineInterface): Promise<void> {
914  try {
915    const at = await nowMs($)
916    const keys = await $.store.keys()
917    for (const key of staleKeys(keys, dayOf(at, offsetAt(at)))) await $.store.delete(key)
918    // Keep-warm's hourly counts (`warm:<account>:<hour>`) matter for their hour only.
919    for (const key of keys.filter(k => k.startsWith('warm:'))) {
920      const hour = Number(key.split(':').pop())
921      if (!Number.isFinite(hour) || hour < Math.floor(at / 3_600_000) - 1) await $.store.delete(key)
922    }
923    // `coach:five_hour:<resets at>` marks outlive their window by a day at most.
924    for (const key of keys.filter(k => k.startsWith('coach:'))) {
925      const resets = Number(key.split(':').pop())
926      if (!Number.isFinite(resets) || resets * 1000 < at - 86_400_000) await $.store.delete(key)
927    }
928    await refreshLedger($, at)
929  } catch {
930    // best effort
931  }
932}
933
934/** Reads what the engine knows now: the session's id, model, usage, git and agents. */
935async function resync($: EngineInterface): Promise<void> {
936  await setupLive($)
937  try {
938    const id = await $.session.model()
939    await update($, snap, s => ({ ...s, model: s.model ?? id }))
940  } catch {
941    // the first request names the model
942  }
943  await Promise.all([measure($).catch(() => undefined), refreshGit($), refreshAccount($), refreshAgents($), pruneLedger($)])
944}
945
946async function heartbeat($: EngineInterface): Promise<void> {
947  beats += 1
948  await markLive($)
949  await update($, tick, () => beats)
950  await nudge($)
951  if (beats % 2 === 0) await refreshGit($)
952  if (beats % 40 === 0 || (accountMissed && beats % 4 === 0)) await refreshAccount($)
953  if (beats % 20 === 0) void refreshPulse($)
954  if (beats % 8 === 0) await watchIdle($).catch(() => undefined)
955  if (resumeLooks > 0) await readResumed($)
956  if ((await configStamp($)) !== stamp) await reloadConfig($)
957  if ((await read($, agents)).some(row => isActive(row.status))) await refreshAgents($)
958  // An account rule needs a fresh reading: an account manager may have switched accounts.
959  else if (beats % 8 === 0 && config.guard.rules.some(namesAccounts)) await refreshAccount($)
960  await refreshUsage($)
961  await shareLimits($)
962  await guardNow($).catch(() => undefined)
963  await drainNudge($).catch(() => undefined)
964  await queueTick($).catch(() => undefined)
965  await keepWarm($).catch(() => undefined)
966  await heartbeatRoster($)
967  await exportState($)
968}
969
970// ------------------------------------------------------------- the line
971
972function layoutHas(key: string): boolean {
973  if (key === 'git' && config.lines === 2) return config.git
974  return layoutKeys({ now: 0, preset: config.preset, segments: config.segments }).flat().includes(key)
975}
976
977type Extras = Partial<Record<string, Segment | undefined>>
978
979async function extrasNow($: EngineInterface): Promise<Extras> {
980  const l = await read($, ledgerAtom)
981  return {
982    agents: agentsSegment(await read($, agents)),
983    compact: forecastSegment(await read($, outlook)),
984    today: todaySegment(l?.today, config.budget),
985    guard: await guardSegment($),
986    resume: await resumeSegment($),
987    others: config.roster ? othersSegment(others) : undefined,
988  }
989}
990
991/** The labels g-line adds to the footer's mode labels: what the layout doesn't place on the hint. */
992function footerLabels(extras: Extras): string[] {
993  if (config.lines === 2) return []
994  // What the guard is doing always shows: it acts on your behalf.
995  const guard = [extras.guard?.forms[1], extras.resume?.forms[0]].filter((label): label is string => Boolean(label))
996  if (!config.footerLabels) return guard
997  return [...(['agents', 'compact', 'others'] as const)
998    .filter(key => !layoutHas(key))
999    .map(key => extras[key]?.forms[0])
1000    .filter((label): label is string => Boolean(label)), ...guard]
1001}
1002
1003// ---------------------------------------------------------------- the pane
1004
1005type Row = { key: string; text: string; tone?: Tone; bold?: boolean }
1006
1007function ago(ms: number): string {
1008  const s = Math.floor(ms / 1000)
1009  if (s < 60) return `${s}s`
1010  if (s < 3600) return `${Math.floor(s / 60)}m`
1011  return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
1012}
1013
1014const bar = (value: number, cells = 10) => {
1015  const filled = Math.max(0, Math.min(cells, Math.round(value * cells)))
1016  return '█'.repeat(filled) + '░'.repeat(cells - filled)
1017}
1018
1019async function detailRows($: EngineInterface, seconds: number, columns?: number): Promise<Row[]> {
1020  const s = await read($, snap)
1021  const p = payload(s, seconds, ttl, idle)
1022  const opts = { ...optionsAt(seconds), preset: 'full' as const, segments: undefined }
1023  const rows: Row[] = segments(p, opts).flat().map(row => ({ key: row.key, text: row.forms[0] ?? '', tone: row.tone }))
1024  for (const l of s.rateLimits ?? []) {
1025    if (!['five_hour', 'seven_day', 'spend_limit'].includes(l.kind)) rows.push({ key: `limit-${l.kind}`, text: `${l.kind.replace(/_/g, ' ')} ${pct(l.percentUsed)}` })
1026  }
1027  for (const alert of alerts(p, opts)) rows.push({ key: alert.id, text: alert.text, tone: 'warn' })
1028
1029  const t = await read($, totals)
1030  const f = await read($, outlook)
1031  const now = seconds * 1000
1032
1033  const list = await read($, agents)
1034  if (list.length) {
1035    rows.push({ key: 'h-agents', text: 'Agents', bold: true })
1036    for (const row of list.slice(-8)) {
1037      const age = ago((row.endedAt ?? now) - row.startedAt)
1038      const kind = row.teammate ? 'teammate' : row.type
1039      const model = row.model ? ` · ${modelName(row.model)}` : ''
1040      rows.push({ key: `a-${row.id}`, text: `${row.status.padEnd(9)} ${row.description.slice(0, 48)} (${kind}${model}, ${age})`,
1041        tone: row.status === 'failed' || row.status === 'killed' ? 'bad' : isActive(row.status) ? 'ok' : 'dim' })
1042    }
1043  }
1044
1045  const recent = Object.values(await read($, receipts)).sort((x, y) => x.endAt - y.endAt).slice(-5)
1046  if (recent.length) {
1047    rows.push({ key: 'h-turns', text: 'Last turns', bold: true })
1048    for (const r of recent) {
1049      rows.push({ key: `t-${r.endAt}`, tone: 'dim',
1050        text: `${turnLength(r.durationMs).padStart(8)}${receiptText(r, RECEIPT_PRESETS.full ?? [], columns === undefined ? undefined : columns - 8)}` })
1051    }
1052  }
1053
1054  const c = await read($, contextAtom)
1055  if (c) {
1056    rows.push({ key: 'h-context', text: `What fills the context (local estimate, ${tokens(c.total)} of ${tokens(c.max)})`, bold: true })
1057    for (const row of c.rows.slice(0, 7)) {
1058      rows.push({ key: `c-${row.name}`, text: `${bar(row.tokens / Math.max(1, c.total))} ${tokens(row.tokens).padStart(5)}  ${row.name}` })
1059    }
1060    if (c.memoryFiles) rows.push({ key: 'c-mem', tone: 'dim', text: `${c.memoryFiles} memory ${c.memoryFiles === 1 ? 'file' : 'files'}, ${tokens(c.memoryTokens)}` })
1061    if (c.skills) rows.push({ key: 'c-skills', tone: 'dim', text: `${c.skills.count} skills listed, ${tokens(c.skills.tokens)}` })
1062    for (const u of unusedServers(c, t.byTool).slice(0, 4)) {
1063      rows.push({ key: `c-mcp-${u.server}`, tone: 'warn', text: `MCP ${u.server}: ${tokens(u.tokens)} of tool definitions, none called this session` })
1064    }
1065    if (f) rows.push({ key: 'c-forecast', tone: f.turns <= 2 ? 'warn' : undefined, text: `${pct(f.percent)} of the auto-compact threshold; at this rate it compacts in ~${f.turns} turns` })
1066  }
1067  for (const k of t.compactions.slice(-3)) rows.push({ key: `k-${k.at}`, tone: 'dim', text: compactionText(k) })
1068
1069  const tools = Object.entries(t.byTool).sort((x, y) => y[1].calls - x[1].calls).slice(0, 6)
1070  if (tools.length) {
1071    rows.push({ key: 'h-tools', text: `Tools (${t.tools} calls, ${t.failures} failed)`, bold: true })
1072    for (const [name, v] of tools) {
1073      rows.push({ key: `tool-${name}`, tone: v.failures ? 'warn' : 'dim', text: `${String(v.calls).padStart(4)}  ${name}${v.failures ? `  (${v.failures} failed)` : ''}` })
1074    }
1075  }
1076
1077  const l = await read($, ledgerAtom)
1078  if (l && l.week.some(d => d.turns)) {
1079    rows.push({ key: 'h-day', text: 'Today and this week, every session on this machine', bold: true })
1080    rows.push({ key: 'd-today', text: `today ${money(l.today.cost)} at API prices · ${l.today.turns} turns · ${l.today.sessions} ${l.today.sessions === 1 ? 'session' : 'sessions'}${l.today.colds ? ` · ${l.today.colds} cold-cache rebuilds` : ''}${l.today.warms ? ` · kept warm ${l.today.warms}×${l.today.warmCost ? ` (${money(l.today.warmCost)})` : ''}` : ''}` })
1081    const week = l.week.reduce((sum, d) => sum + d.cost, 0)
1082    rows.push({ key: 'd-week', text: `7 days ${spark(l.week.map(d => d.cost))} ${money(week)}` })
1083  }
1084  // The windows' resets on your own clock.
1085  const resets = (s.rateLimits ?? []).filter(l => (l.kind === 'five_hour' || l.kind === 'seven_day') && l.resetsAt && l.resetsAt > seconds)
1086  if (resets.length) {
1087    rows.push({ key: 'h-windows', text: 'Usage windows (your local time)', bold: true })
1088    for (const l of resets) {
1089      const at = l.resetsAt ?? 0
1090      rows.push({ key: `w-${l.kind}`, text: `${l.kind === 'five_hour' ? '5-hour' : 'weekly'} ${pct(l.percentUsed)} used, resets ${clock(at, seconds, offsetAt(seconds * 1000))} (in ${ago((at - seconds) * 1000)})` })
1091    }
1092  }
1093  if (resumePlan) {
1094    rows.push({ key: 'w-resume', tone: 'accent', text: `"${config.guard.resume?.text ?? 'continue'}" goes at ${clock(Math.floor(resumePlan.at / 1000), seconds, offsetAt(seconds * 1000))}, after the reset (/g-line guard cancel)` })
1095  }
1096  if (config.roster && others.length) {
1097    rows.push({ key: 'h-roster', text: 'Sessions on this machine', bold: true })
1098    const mine = rosterState && sessionId ? [{ id: sessionId, at: now, state: rosterState.state, since: rosterState.since,
1099      ...(s.context?.percent !== undefined ? { ctx: s.context.percent } : {}), ...(s.model ? { model: modelName(s.model) } : {}) }] : []
1100    for (const entry of [...mine, ...others].slice(0, 10)) {
1101      rows.push({ key: `r-${entry.id}`, tone: entry.state === 'waiting' ? 'warn' : entry.id === sessionId ? undefined : 'dim', text: rosterRow(entry, now, entry.id === sessionId) })
1102    }
1103  }
1104  if (config.guard.rules.length || config.guard.keepWarm) {
1105    rows.push({ key: 'h-guard', text: `Guard (your rules${config.guard.on ? '' : ', off'}; /g-line guard once|pause|off)`, bold: true })
1106    const mine = groupOf(config.guard.groups, s.account)
1107    for (const g of config.guard.groups ?? []) {
1108      rows.push({ key: `gg-${g.name}`, tone: mine?.name === g.name ? 'accent' : 'dim', text: `${mine?.name === g.name ? 'this one ' : '         '}group ${g.name}: ${g.words.join(', ')} (kept for ${g.keepFor})` })
1109    }
1110    if (config.guard.groups?.length && mine?.name === 'other') rows.push({ key: 'gg-other', tone: 'accent', text: 'this one group other: this account is in none of your groups' })
1111    for (const rule of config.guard.rules) {
1112      const on = verdict.active[rule.id] !== undefined
1113      rows.push({ key: `g-${rule.id}`, tone: on ? (rule.stop ? 'bad' : 'warn') : 'dim', text: `${on ? 'in force ' : '         '}${ruleText(rule)}` })
1114    }
1115    const k = config.guard.keepWarm
1116    if (k) rows.push({ key: 'g-warm', tone: 'dim', text: `keep-warm: after ${Math.round(k.after / 60)}m idle, up to ${k.max} times, ${tokens(k.minContext)}+ context${warmOff ? ' (off for this session)' : `, ${warmed} so far`}` })
1117    if (config.guard.rules.length) {
1118      for (const [i, line] of (await whyNow($)).entries()) rows.push({ key: `g-why-${i}`, tone: line.startsWith('Held:') ? 'bad' : 'dim', text: line })
1119    }
1120    for (const error of config.guard.errors) rows.push({ key: `g-err-${error}`, tone: 'warn', text: `not read: ${error}` })
1121  }
1122  rows.push({ key: 'tz', tone: 'dim', text: `Times are ${config.tz ? `in ${config.tz} (${utcLabel(offsetAt(seconds * 1000))})` : `this machine's (${utcLabel(offsetAt(seconds * 1000))})`}; "tz" in config.json sets yours.` })
1123  rows.push({ key: 'note', tone: 'dim', text: `Pace projects your average rate since each window opened. Totals count only sessions g-line ran in. Layout: ${layoutKeys(optionsAt(seconds)).map(x => x.join(',')).join(' | ')}.` })
1124  return rows
1125}
1126
1127async function cardText($: EngineInterface, seconds: number): Promise<string[]> {
1128  const s = await read($, snap)
1129  const t = await read($, totals)
1130  const p = payload(s, seconds, ttl, idle)
1131  return cardLines({
1132    model: p.model?.display_name,
1133    elapsedSeconds: s.startedAt !== undefined ? seconds - s.startedAt / 1000 : undefined,
1134    totals: t, cost: s.costUsd,
1135    // Weighted by tokens over the whole session, not an average of turns.
1136    cacheHit: t.inputTokens ? ((t.cacheRead ?? 0) / t.inputTokens) * 100 : undefined,
1137    fiveHour: p.rate_limits?.five_hour?.used_percentage,
1138    agentsNow: (await read($, agents)).filter(row => isActive(row.status)).length,
1139    today: (await read($, ledgerAtom))?.today,
1140  })
1141}
1142
1143async function openPane($: EngineInterface, mode: 'details' | 'card' | 'settings' | 'news'): Promise<Record<string, never>> {
1144  await update($, view, () => mode)
1145  await Promise.all([pruneLedger($), refreshGit($, true)])
1146  try {
1147    const usage = await $.session.usage({ breakdown: 'summary' })
1148    const b = usage.context.breakdown
1149    if (b) {
1150      const at = await nowMs($)
1151      await update($, contextAtom, () => contextView(b, at))
1152    }
1153  } catch {
1154    // the pane shows the rest
1155  }
1156  void refreshPulse($)
1157  const title = mode === 'card' ? 'g-line card' : mode === 'settings' ? 'g-line settings' : mode === 'news' ? 'Pulse' : 'g-line'
1158  // The reader and the settings answer keys: they take the keyboard, asked for by the command.
1159  const opened = await $.ui.open({ id: PANE, title, ...(mode === 'news' || mode === 'settings' ? { focus: true as const, rows: 40 } : {}) })
1160  if (!opened.isPlaced) $.ui.toast('g-line: widen the terminal to see the pane.', { timeoutMs: 5000 })
1161  // Nothing goes back into the conversation: a command's text is read by Claude.
1162  return {}
1163}
1164
1165// ------------------------------------------------------------------ pulse
1166
1167/** Fetches g-line's static headline feed when it is on and the copy is old, then puts a headline up if none shows. Never on the drawing path. */
1168async function refreshPulse($: EngineInterface, force = false): Promise<void> {
1169  await fetchPulse($, force)
1170  await turnPulse($, true).catch(() => undefined)
1171}
1172
1173async function fetchPulse($: EngineInterface, force: boolean): Promise<void> {
1174  if (!config.pulse) return
1175  try {
1176    const at = await nowMs($)
1177    const held = await read($, pulseAtom)
1178    if (!force && held && at - held.fetchedAt < PULSE_TTL_MS) return
1179    const stored = (await $.store.get('pulse')) as { fetchedAt?: number; raw?: string } | undefined
1180    if (!force && stored?.raw && stored.fetchedAt && at - stored.fetchedAt < PULSE_TTL_MS) {
1181      const feed = parseFeed(stored.raw, stored.fetchedAt)
1182      if (feed) await update($, pulseAtom, () => feed)
1183      return
1184    }
1185    // One GET of a static file, nothing sent; given up after five seconds.
1186    const response = await Promise.race([$.http.fetch(PULSE_URL), $.clock.sleep(5000).then(() => undefined)])
1187    const feed = response && response.ok && response.text.length <= 262_144 ? parseFeed(response.text, at) : undefined
1188    if (feed) {
1189      await $.store.set('pulse', { fetchedAt: at, raw: response?.text })
1190      await update($, pulseAtom, () => feed)
1191    } else if (!held && stored?.raw && stored.fetchedAt) {
1192      // Offline: the last copy fetched, rather than nothing.
1193      const old = parseFeed(stored.raw, stored.fetchedAt)
1194      if (old) await update($, pulseAtom, () => old)
1195    }
1196  } catch {
1197    // offline or refused: the spinner and pane go on without headlines
1198  }
1199}
1200
hooks/core.ts 495 lines
1// glanceline core: turns Claude Code's own session figures into short,
2// width-aware segments, and spots what is about to go wrong.
3//
4// Pure functions only (no `$`, no clock, no I/O), so the tests call them
5// directly against the golden file. The input is shaped like Claude Code's
6// session figures; the mod builds it from `$.session.usage()` and the turns
7// it watches.
8
9export type Tone = 'ok' | 'warn' | 'bad' | 'dim' | 'accent'
10
11export type Payload = {
12  model?: { id?: string; display_name?: string }
13  /** `set`: what the person chose, when the guard ran the request at `level` instead. */
14  effort?: { level?: string; set?: string }
15  fast_mode?: boolean
16  context_window?: {
17    used_percentage?: number | null
18    context_window_size?: number
19    total_input_tokens?: number
20  }
21  rate_limits?: {
22    five_hour?: Window
23    seven_day?: Window
24    spend_limit?: Window & { used_usd?: number; limit_usd?: number; period?: string }
25  }
26  prompt_cache?: {
27    warm?: boolean
28    caching_observed?: boolean
29    ttl?: string
30    expires_at?: number | null
31    recache_tokens_if_cold?: number | null
32    /** A compaction replaced the cached conversation; the next request writes `recache_tokens_if_cold`. */
33    compacted?: boolean
34    /** Claude Code's idle compaction will summarise the conversation before this cache expires. */
35    idle_compacts?: boolean
36    /** The account changed since the cache was written: caches don't carry across organizations. */
37    account_changed?: boolean
38  }
39  cost?: {
40    total_cost_usd?: number
41    total_duration_ms?: number
42    total_lines_added?: number
43    total_lines_removed?: number
44  }
45  pr?: { number?: number; review_state?: string; kind?: string }
46  vim?: { mode?: string }
47  git?: { branch?: string; dirty?: boolean } | null
48}
49
50export type Window = { used_percentage?: number; resets_at?: number }
51
52/**
53 * A part of a line: its forms widest first. `spare` counts trailing forms kept
54 * back: they're used only before something at least as important would be
55 * dropped (the cache keeps its size until then).
56 */
57export type Segment = { key: string; priority: number; forms: string[]; tone?: Tone; spare?: number }
58export type Placed = { key: string; text: string; tone?: Tone }
59export type Preset = 'minimal' | 'default' | 'full'
60
61export type Options = {
62  /** Unix seconds. */
63  now: number
64  preset?: Preset
65  /** Custom layout: segment keys, `|` starts a new line. Overrides preset. */
66  segments?: string
67  icons?: 'none' | 'nerd'
68  /** Minutes east of UTC for clock times; the caller's local offset. */
69  utcOffsetMinutes?: number
70}
71
72export type Alert = { id: string; text: string; tone: Tone }
73
74export const SEP = ' · '
75
76/** Added to a segment's priority while it warns, so it outlasts the model name when space runs out. */
77export const URGENT = 50
78
79export const PRESETS: Record<Preset, string> = {
80  minimal: 'model,context,five_hour,cache',
81  default: 'model,context,five_hour,seven_day,spend,cache',
82  full: 'model,context,five_hour,seven_day,spend,cache|git,pr,cost,time,lines,vim',
83}
84
85const NERD: Record<string, string> = {
86  model: '\u{f06a9} ', context: '\u{f035b} ', five_hour: '\u{f0150} ', seven_day: '\u{f00f0} ',
87  spend: '\u{f01c1} ', cache: '\u{f0e57} ', git: '\u{e725} ', pr: '\u{e726} ', cost: '\u{f01c1} ',
88  time: '\u{f051f} ', lines: '\u{f0c7e} ',
89}
90
91// ------------------------------------------------------------ formatting
92
93/** A finite number (booleans and NaN are not), else undefined. */
94export function num(value: unknown): number | undefined {
95  return typeof value === 'number' && Number.isFinite(value) ? value : undefined
96}
97
98/** A short printable string, else undefined. Control characters never pass. */
99export function str(value: unknown, limit = 48): string | undefined {
100  if (typeof value !== 'string') return undefined
101  const clean = value.trim()
102  if (!clean || /[\u0000-\u001f\u007f-\u009f]/.test(clean)) return undefined
103  return clean.slice(0, limit)
104}
105
106/** 4d 10h · 2h 5m · 7m · <1m. Floored: a countdown never overstates. */
107export function duration(seconds: number, compact = false): string {
108  const s = Math.floor(seconds)
109  if (s < 60) return '<1m'
110  const days = Math.floor(s / 86400)
111  const hours = Math.floor((s % 86400) / 3600)
112  const minutes = Math.floor((s % 3600) / 60)
113  const gap = compact ? '' : ' '
114  if (days) return hours ? `${days}d${gap}${hours}h` : `${days}d`
115  if (hours) return minutes ? `${hours}h${gap}${minutes}m` : `${hours}h`
116  return `${minutes}m`
117}
118
119export function tokens(count: number): string {
120  const n = Math.floor(count)
121  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
122  if (n >= 1000) return `${Math.round(n / 1000)}k`
123  return String(n)
124}
125
126export function pct(value: number): string {
127  return `${Math.round(value)}%`
128}
129
130const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
131
132/** Minutes east of UTC in IANA zone `tz` at `ms`; undefined for no zone or one this runtime doesn't know. */
133export function zoneOffset(tz: string | undefined, ms: number): number | undefined {
134  if (!tz) return undefined
135  try {
136    const parts = new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric',
137      hour: 'numeric', minute: 'numeric' }).formatToParts(new Date(ms))
138    const n = (type: string) => Number(parts.find(p => p.type === type)?.value)
139    const local = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour') % 24, n('minute'))
140    const minute = Math.floor(ms / 60_000) * 60_000
141    return Math.round((local - minute) / 60_000)
142  } catch {
143    return undefined
144  }
145}
146
147/** `UTC+11`, `UTC+5:45`, `UTC-3`: an offset in minutes, for saying which zone times are in. */
148export function utcLabel(offsetMinutes: number): string {
149  const sign = offsetMinutes < 0 ? '-' : '+'
150  const a = Math.abs(offsetMinutes)
151  return `UTC${sign}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, '0')}` : ''}`
152}
153
154/** 16:40 when within a day of `now`, else Thu 16:40, in the caller's zone. */
155export function clock(at: number, now: number, offsetMinutes = 0): string {
156  const local = new Date((Math.floor(at) + offsetMinutes * 60) * 1000)
157  const hh = String(local.getUTCHours()).padStart(2, '0')
158  const mm = String(local.getUTCMinutes()).padStart(2, '0')
159  return at - now < 20 * 3600 ? `${hh}:${mm}` : `${DAYS[local.getUTCDay()]} ${hh}:${mm}`
160}
161
162export function bar(percent: number, cells = 5): string {
163  const filled = Math.max(0, Math.min(cells, Math.round((percent / 100) * cells)))
164  return '▰'.repeat(filled) + '▱'.repeat(cells - filled)
165}
166
167function pressure(percent: number): Tone | undefined {
168  if (percent >= 95) return 'bad'
169  if (percent >= 80) return 'warn'
170  return undefined
171}
172
173// ------------------------------------------------------------------ pace
174
175/**
176 * A projection rounded to the precision it deserves: to the hour when it is
177 * more than six hours off, to the quarter hour beyond ninety minutes.
178 */
179export function roundEta(eta: number, now: number): number {
180  const ahead = eta - now
181  const step = ahead > 6 * 3600 ? 3600 : ahead > 90 * 60 ? 900 : 60
182  return Math.round(eta / step) * step
183}
184
185export type Pace = { kind: 'full' } | { kind: 'hot'; eta: number } | { kind: 'ok' }
186
187const WINDOW_SECONDS: Record<string, number> = { five_hour: 5 * 3600, seven_day: 7 * 86400 }
188const MIN_ELAPSED: Record<string, number> = { five_hour: 15 * 60, seven_day: 12 * 3600 }
189
190/**
191 * Where the average rate since the window opened lands: past 100% before the
192 * reset (`hot`, with the moment it would), or not (`ok`). Undefined until the
193 * window has run long enough for the rate to mean something.
194 */
195export function pace(kind: string, window: Window | undefined, now: number): Pace | undefined {
196  const used = num(window?.used_percentage)
197  const resets = num(window?.resets_at)
198  const length = WINDOW_SECONDS[kind]
199  if (used === undefined || resets === undefined || length === undefined || resets <= now) return undefined
200  if (used >= 100) return { kind: 'full' }
201  const elapsed = now - (resets - length)
202  if (elapsed < (MIN_ELAPSED[kind] ?? 0) || used < 1) return undefined
203  const eta = now + ((100 - used) * elapsed) / used
204  return eta < resets - 60 ? { kind: 'hot', eta } : { kind: 'ok' }
205}
206
207// -------------------------------------------------------------- segments
208
209function modelSegment(p: Payload): Segment | undefined {
210  const name = str(p.model?.display_name) ?? str(p.model?.id)
211  if (!name) return undefined
212  const level = str(p.effort?.level, 12)
213  const set = str(p.effort?.set, 12)
214  const fast = p.fast_mode === true
215  if (level && set && set !== level) {
216    const family = name.split(' ')[0] ?? name
217    return { key: 'model', priority: 82, tone: 'warn',
218      forms: [`${name} (${set}→${level} effort by guard${fast ? ', fast' : ''})`, `${name} ${set}→${level}`, `${family} ${set}→${level}`, `${family} ${level}`] }
219  }
220  const detail = [level ? `${level} effort` : '', fast ? 'fast' : ''].filter(Boolean).join(', ')
221  const family = name.split(' ')[0] ?? name
222  // The effort stays in every form: it is what you change most often.
223  const forms = detail ? [`${name} (${detail})`, level ? `${name} ${level}` : name, level ? `${family} ${level}` : family] : [name]
224  return { key: 'model', priority: 82, forms, tone: 'accent' }
225}
226
227function contextSegment(p: Payload, full: boolean): Segment | undefined {
228  const w = p.context_window
229  const used = num(w?.used_percentage)
230  if (used === undefined || used < 0) return undefined
231  const size = num(w?.context_window_size)
232  const inside = num(w?.total_input_tokens)
233  const left = size !== undefined && inside !== undefined && size > inside ? size - inside : undefined
234  const forms = [`ctx ${pct(used)}`]
235  if (left !== undefined) forms.unshift(`ctx ${pct(used)} (${tokens(left)} left)`)
236  if (full) forms.unshift(`context ${bar(used)} ${pct(used)}` + (left !== undefined ? ` (${tokens(left)} left)` : ''))
237  return { key: 'context', priority: 90, forms, tone: pressure(used) }
238}
239
240function windowSegment(p: Payload, kind: 'five_hour' | 'seven_day', o: Options, full: boolean): Segment | undefined {
241  const window = p.rate_limits?.[kind]
242  const used = num(window?.used_percentage)
243  if (used === undefined || used < 0) return undefined
244  const [name, short, priority] = kind === 'five_hour' ? ['5h', '5h', 85] : ['week', 'wk', 70]
245  const resets = num(window?.resets_at)
246  const left = resets !== undefined && resets > o.now ? resets - o.now : undefined
247  const state = pace(kind, window, o.now)
248  const head = full ? `${name} ${bar(used)} ${pct(used)}` : `${name} ${pct(used)}`
249  if (state?.kind === 'full') {
250    const after = left !== undefined ? ` (resets in ${duration(left)})` : ''
251    return { key: kind, priority, tone: 'bad',
252      forms: [`${name} limit reached${after}`, `${short} full` + (left !== undefined ? ` (${duration(left, true)})` : ''), `${short} full`] }
253  }
254  if (state?.kind === 'hot') {
255    // `!` and `~` carry the meaning where the line is drawn dim: a warning, and
256    // a projection rather than an appointment. The fill is a duration and the
257    // reset a clock time, so the two can't be read as the same kind of figure.
258    const fills = Math.max(60, roundEta(state.eta, o.now) - o.now)
259    const back = resets !== undefined ? ` (back ${clock(resets, o.now, o.utcOffsetMinutes)})` : ''
260    const soon = state.eta - o.now < 30 * 60
261    return { key: kind, priority, tone: soon ? 'bad' : 'warn',
262      forms: [`${head} ! full in ~${duration(fills)}${back}`, `${short} ${pct(used)} ! full in ~${duration(fills, true)}`, `${short} ${pct(used)}!`] }
263  }
264  if (left === undefined) return { key: kind, priority, tone: pressure(used), forms: [head, `${short} ${pct(used)}`] }
265  return { key: kind, priority, tone: pressure(used),
266    forms: [`${head} (resets in ${duration(left)})`, `${short} ${pct(used)} (${duration(left, true)})`, `${short} ${pct(used)}`] }
267}
268
269function spendSegment(p: Payload): Segment | undefined {
270  const spend = p.rate_limits?.spend_limit
271  const used = num(spend?.used_percentage)
272  if (used === undefined || used < 0) return undefined
273  const forms = [`spend ${pct(used)}`]
274  const usd = num(spend?.used_usd)
275  const cap = num(spend?.limit_usd)
276  if (usd !== undefined && cap) {
277    const period = ['daily', 'weekly', 'monthly'].includes(spend?.period ?? '') ? ` ${spend?.period}` : ''
278    forms.unshift(`spend $${Math.round(usd)} of $${Math.round(cap)}${period}`)
279  }
280  return { key: 'spend', priority: 75, forms, tone: pressure(used) }
281}
282
283function cacheSegment(p: Payload, now: number): Segment | undefined {
284  const cache = p.prompt_cache
285  if (!cache || cache.caching_observed !== true) return undefined
286  const expires = num(cache.expires_at)
287  if (cache.compacted === true) {
288    const size = num(cache.recache_tokens_if_cold)
289    return { key: 'cache', priority: 80,
290      forms: size && size > 0 ? [`cache reset by compaction (next turn writes ${tokens(size)})`, 'cache compacted'] : ['cache compacted'] }
291  }
292  if (cache.warm === true && expires !== undefined && expires > now) {
293    const left = expires - now
294    const soon = left <= (cache.ttl === '1h' ? 300 : 60)
295    return { key: 'cache', priority: 80, tone: soon ? 'warn' : 'ok',
296      forms: left < 60 ? ['cache warm (<1m left)', 'cache <1m'] : [`cache warm (~${duration(left)} left)`, `cache ~${duration(left, true)}`] }
297  }
298  const recache = num(cache.recache_tokens_if_cold)
299  const why = cache.account_changed === true ? ', account changed' : ''
300  const forms = recache && recache > 0 ? [`cache cold (next turn rebuilds ${tokens(recache)}${why})`, 'cache cold'] : ['cache cold']
301  return { key: 'cache', priority: 80, tone: 'warn', forms }
302}
303
304function costSegment(p: Payload): Segment | undefined {
305  const usd = num(p.cost?.total_cost_usd)
306  if (usd === undefined || usd <= 0) return undefined
307  return { key: 'cost', priority: 50, tone: 'dim', forms: [`$${usd.toFixed(2)} at API prices`, `$${usd.toFixed(2)}`] }
308}
309
310function timeSegment(p: Payload): Segment | undefined {
311  const ms = num(p.cost?.total_duration_ms)
312  if (ms === undefined || ms < 60_000) return undefined
313  return { key: 'time', priority: 45, tone: 'dim', forms: [`${duration(ms / 1000)} session`, duration(ms / 1000, true)] }
314}
315
316function linesSegment(p: Payload): Segment | undefined {
317  const added = num(p.cost?.total_lines_added) ?? 0
318  const removed = num(p.cost?.total_lines_removed) ?? 0
319  if (added <= 0 && removed <= 0) return undefined
320  return { key: 'lines', priority: 40, tone: 'dim', forms: [`+${added} −${removed} lines`, `+${added} −${removed}`] }
321}
322
323function gitSegment(p: Payload): Segment | undefined {
324  return gitSegmentOf(p.git)
325}
326
327/** The branch, `*` when tracked files have changes. */
328export function gitSegmentOf(git: Payload['git'] | undefined): Segment | undefined {
329  const branch = str(git?.branch, 40)
330  if (!branch) return undefined
331  const mark = git?.dirty ? '*' : ''
332  return { key: 'git', priority: 60, forms: [`${branch}${mark}`, `${branch.slice(0, 16)}${mark}`] }
333}
334
335function prSegment(p: Payload): Segment | undefined {
336  const n = num(p.pr?.number)
337  if (n === undefined) return undefined
338  const label = p.pr?.kind === 'mr' ? `MR !${n}` : `PR #${n}`
339  const state = str(p.pr?.review_state, 20)?.replace(/_/g, ' ')
340  return { key: 'pr', priority: 55, forms: state ? [`${label} ${state}`, label] : [label] }
341}
342
343function vimSegment(p: Payload): Segment | undefined {
344  const mode = str(p.vim?.mode, 12)
345  return mode ? { key: 'vim', priority: 30, tone: 'dim', forms: [mode] } : undefined
346}
347
348/** The layout's segment keys, one list per line. */
349export function layoutKeys(o: Options): string[][] {
350  const spec = o.segments && /^[a-z_,| ]+$/.test(o.segments) ? o.segments : PRESETS[o.preset ?? 'default'] ?? PRESETS.default
351  return spec.split('|').map(line => line.split(',').map(key => key.trim()).filter(Boolean)).filter(line => line.length)
352}
353
354/** Segments for each line, in order, with anything unknown left out. */
355export function segments(p: Payload, o: Options): Segment[][] {
356  const full = (o.preset ?? 'default') === 'full' && !o.segments
357  const build: Record<string, () => Segment | undefined> = {
358    model: () => modelSegment(p),
359    context: () => contextSegment(p, full),
360    five_hour: () => windowSegment(p, 'five_hour', o, full),
361    seven_day: () => windowSegment(p, 'seven_day', o, full),
362    spend: () => spendSegment(p),
363    cache: () => cacheSegment(p, o.now),
364    cost: () => costSegment(p),
365    time: () => timeSegment(p),
366    lines: () => linesSegment(p),
367    git: () => gitSegment(p),
368    pr: () => prSegment(p),
369    vim: () => vimSegment(p),
370  }
371  const icons = o.icons === 'nerd'
372  return layoutKeys(o).map(keys => keys.flatMap(key => {
373    const segment = build[key]?.()
374    if (!segment) return []
375    // What is pressing outranks what is merely useful, so it survives a narrow terminal.
376    if (segment.tone === 'warn' || segment.tone === 'bad') segment.priority += URGENT
377    if (icons && NERD[key]) segment.forms = segment.forms.map(form => NERD[key] + form)
378    return [segment]
379  })).filter(line => line.length)
380}
381
382// ---------------------------------------------------------------- layout
383
384/** Display columns. Everything glanceline prints is one column per code point. */
385export function width(text: string): number {
386  return [...text].length
387}
388
389export function truncate(text: string, room: number): string {
390  if (room <= 0) return ''
391  const chars = [...text]
392  return chars.length <= room ? text : chars.slice(0, Math.max(room - 1, 0)).join('') + '…'
393}
394
395/**
396 * One form per segment so the line fits `room` columns. Calm segments narrow
397 * together, one tier at a time, so the line keeps one voice; a segment that
398 * warns keeps its words longer: it narrows to its middle form only once the
399 * calm ones are at their shortest, and to its shortest only after every calm
400 * segment that doesn't fit has gone, lowest priority first. The last one left
401 * is cut.
402 */
403export function fit(items: Segment[], room?: number): Placed[] {
404  if (room === undefined) return items.map(item => ({ key: item.key, text: item.forms[0] ?? '', tone: item.tone }))
405  const live = [...items]
406  const loud = (item: Segment) => item.tone === 'warn' || item.tone === 'bad'
407  const deepest = Math.max(1, ...live.map(item => item.forms.length))
408  let calmTier = 0
409  let loudTier = 0
410  let spent = false
411  const reach = (item: Segment) => item.forms.length - 1 - (spent ? 0 : Math.max(0, item.spare ?? 0))
412  const forms = () => live.map(item => item.forms[Math.max(0, Math.min(loud(item) ? loudTier : calmTier, reach(item)))] ?? '')
413  const dropLowest = () => {
414    let lowest = 0
415    live.forEach((item, index) => { if (item.priority < (live[lowest]?.priority ?? 0)) lowest = index })
416    // Spare forms go before a warning, or anything at least as important as their segment, does.
417    const guarded = live.filter(item => (item.spare ?? 0) > 0)
418    const going = live[lowest]
419    if (!spent && going && guarded.length && (loud(going) || guarded.some(item => item.priority <= going.priority))) {
420      spent = true
421      calmTier = Math.max(calmTier, deepest - 1)
422      return
423    }
424    live.splice(lowest, 1)
425  }
426  while (width(forms().join(SEP)) > room) {
427    if (calmTier < deepest - 1) calmTier += 1
428    else if (loudTier < Math.max(1, deepest - 2)) loudTier += 1
429    else if (live.length > 1 && live.some(item => !loud(item))) dropLowest()
430    else if (loudTier < deepest - 1) loudTier += 1
431    else if (live.length > 1) dropLowest()
432    else break
433  }
434  return live.map((item, index) => ({ key: item.key, text: truncate(forms()[index] ?? '', room), tone: item.tone }))
435}
436
437/** One extra line (a plug-in's): the widest of its forms that fits. */
438export function fitExtra(forms: string[], room?: number): string {
439  const clean = forms.filter(Boolean)
440  if (!clean.length) return ''
441  const chosen = clean.find(form => room === undefined || width(form) <= room) ?? clean[clean.length - 1] ?? ''
442  return room === undefined ? chosen : truncate(chosen, room)
443}
444
445/** Every line, fitted. */
446export function render(p: Payload, o: Options & { columns?: number }): Placed[][] {
447  return segments(p, o).map(line => fit(line, o.columns))
448}
449
450export function plain(lines: Placed[][]): string[] {
451  return lines.map(line => line.map(part => part.text).join(SEP))
452}
453
454// ---------------------------------------------------------------- alerts
455
456/** What deserves a heads-up now: each with an id that is stable per event. */
457export function alerts(p: Payload, o: Options): Alert[] {
458  const found: Alert[] = []
459  const cache = p.prompt_cache
460  const expires = num(cache?.expires_at)
461  if (cache?.caching_observed === true && cache.warm === true && expires !== undefined) {
462    const left = expires - o.now
463    if (left > 0 && left <= (cache.ttl === '1h' ? 300 : 60)) {
464      const recache = num(cache.recache_tokens_if_cold)
465      const stake = recache && recache > 0 ? ` (${tokens(recache)} of context at risk)` : ''
466      const after = cache.idle_compacts === true
467        ? 'if not, Claude Code compacts the conversation to a summary first.'
468        : 'after, the next turn rebuilds it.'
469      found.push({ id: `cache:${Math.floor(expires)}`, tone: 'warn',
470        text: `Claude cache goes cold in ${duration(left)}${stake}. Reply before then to keep it cached; ${after}` })
471    }
472  }
473  for (const [kind, name] of [['five_hour', '5-hour'], ['seven_day', 'weekly']] as const) {
474    const window = p.rate_limits?.[kind]
475    const state = pace(kind, window, o.now)
476    const resets = num(window?.resets_at)
477    if (state?.kind === 'hot' && resets !== undefined) {
478      found.push({ id: `${kind}:${Math.floor(resets)}`, tone: 'warn',
479        text: `At this pace you'll hit your ${name} limit around ${clock(roundEta(state.eta, o.now), o.now, o.utcOffsetMinutes)}. It resets ${clock(resets, o.now, o.utcOffsetMinutes)}.` })
480    }
481  }
482  return found
483}
484
485// ------------------------------------------------------------ model names
486
487/** claude-opus-5-5[1m] -> Opus 5.5; anything unrecognised is returned as is. */
488export function modelName(id: string): string {
489  const match = /^(?:[a-z]+\.)?(?:anthropic\.)?claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?:-v\d+(?::\d+)?)?(\[1m\])?$/.exec(id)
490  if (!match) return id
491  const [, family = '', major, minor, wide] = match
492  const name = family.charAt(0).toUpperCase() + family.slice(1)
493  return `${name} ${major}${minor ? '.' + minor : ''}${wide ? ' (1M)' : ''}`
494}
495
hooks/roster.ts 165 lines
1// The sessions on this machine: each g-line session writes a heartbeat to
2// Claude Code's plugin store (shared by every session on the machine, and
3// nowhere else), and reads the others'. Line 2 says how many others there are
4// and how many wait on you; the pane lists them.
5//
6// Pure: the mod hands in the store's entries, these decide what they say.
7
8import type { Segment } from './core'
9
10export type RosterState = 'working' | 'waiting' | 'idle'
11
12export type RosterEntry = {
13  id: string
14  /** When the session last wrote (ms). */
15  at: number
16  state: RosterState
17  /** Since when it has been in that state (ms). */
18  since: number
19  /** Context used, percent. */
20  ctx?: number
21  /** When its prompt cache is estimated to lapse (seconds), while warm. */
22  cacheUntil?: number
23  model?: string
24  /** The `account_command` reading, only where the person configured one. */
25  account?: string
26}
27
28/** A session that hasn't written for this long is gone (it ended, or its machine slept). */
29export const ROSTER_STALE_MS = 60_000
30
31/** The store keys of the roster: `s:<session id>`. */
32export const ROSTER_PREFIX = 's:'
33
34/** The entries the store holds that are fresh and well formed, the newest first. */
35export function rosterOf(entries: readonly { key: string; value: unknown }[], nowMs: number): RosterEntry[] {
36  const out: RosterEntry[] = []
37  for (const { key, value } of entries) {
38    if (!key.startsWith(ROSTER_PREFIX) || !value || typeof value !== 'object') continue
39    const v = value as Record<string, unknown>
40    if (typeof v.at !== 'number' || nowMs - v.at > ROSTER_STALE_MS) continue
41    const state = v.state === 'working' || v.state === 'waiting' || v.state === 'idle' ? v.state : undefined
42    if (!state) continue
43    out.push({
44      id: key.slice(ROSTER_PREFIX.length), at: v.at, state, since: typeof v.since === 'number' ? v.since : v.at,
45      ...(typeof v.ctx === 'number' ? { ctx: v.ctx } : {}),
46      ...(typeof v.cacheUntil === 'number' ? { cacheUntil: v.cacheUntil } : {}),
47      ...(typeof v.model === 'string' ? { model: v.model.slice(0, 40) } : {}),
48      ...(typeof v.account === 'string' ? { account: v.account.slice(0, 120) } : {}),
49    })
50  }
51  return out.sort((a, b) => b.at - a.at)
52}
53
54/** Keys of entries a day or more old: left behind by sessions that never said goodbye. */
55export function staleRosterKeys(entries: readonly { key: string; value: unknown }[], nowMs: number): string[] {
56  return entries.filter(({ key, value }) => key.startsWith(ROSTER_PREFIX)
57    && !(value && typeof value === 'object' && typeof (value as { at?: unknown }).at === 'number'
58      && nowMs - (value as { at: number }).at < 86_400_000)).map(({ key }) => key)
59}
60
61/** Line 2's `2 others · 1 waiting`: only when there are others; the waiting count is amber. */
62export function othersSegment(others: readonly RosterEntry[]): Segment | undefined {
63  if (!others.length) return undefined
64  const waiting = others.filter(o => o.state === 'waiting').length
65  const n = `${others.length} ${others.length === 1 ? 'other' : 'others'}`
66  if (waiting) return { key: 'others', priority: 38, tone: 'warn', forms: [`${n} · ${waiting} waiting`, `${waiting} waiting`] }
67  return { key: 'others', priority: 30, forms: [n] }
68}
69
70const ago = (ms: number) => {
71  const m = Math.floor(ms / 60_000)
72  return m < 1 ? '<1m' : m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
73}
74
75/** One pane row per session: what it's doing and for how long, its context, its cache, its model and account. */
76export function rosterRow(e: RosterEntry, nowMs: number, mine: boolean): string {
77  const what = e.state === 'waiting' ? `waiting on you ${ago(nowMs - e.since)}` : `${e.state} ${ago(nowMs - e.since)}`
78  const cache = e.cacheUntil !== undefined
79    ? e.cacheUntil * 1000 > nowMs ? `cache ~${ago(e.cacheUntil * 1000 - nowMs)}` : 'cache cold' : ''
80  return [mine ? `${what} (this one)` : what, e.ctx !== undefined ? `ctx ${Math.round(e.ctx)}%` : '', cache, e.model ?? '', e.account ?? '']
81    .filter(Boolean).join(' · ')
82}
83
84/** The store key under which sessions on this machine share one account's usage readings. */
85export const LIMITS_PREFIX = 'g-line-limits:'
86
87/** `at`: when the reading was observed (epoch seconds). Readings shared before 0.19.1 have none. */
88export type Limit = { kind: string; percentUsed: number; resetsAt?: number; at?: number }
89
90/**
91 * Whether reading `a` should replace `b` in the same window: the newer
92 * observation, a timed reading over an untimed one, and the higher percent
93 * when neither says when. Use only grows until the reset, so the newest
94 * reading is normally the highest; when it isn't (a stale figure, a reading
95 * that was wrong, a reset the provider gave early), the newest is still right.
96 */
97function replaces(a: Limit, b: Limit): boolean {
98  if (a.at !== undefined && b.at !== undefined) return a.at > b.at || (a.at === b.at && a.percentUsed > b.percentUsed)
99  if (a.at !== undefined) return true
100  if (b.at !== undefined) return false
101  return a.percentUsed > b.percentUsed
102}
103
104/**
105 * One account's usage windows from this session's reading and the one sessions
106 * on this machine share: in the same window the newest observation (see
107 * `replaces`), across windows the later one. A shared window already past its
108 * reset is left out. Order-free, so sessions converge whoever writes last.
109 */
110export function mergeLimits(own: readonly Limit[] | undefined, shared: unknown, nowSeconds: number): Limit[] {
111  const out = new Map<string, Limit>()
112  for (const l of own ?? []) out.set(l.kind, l)
113  const list = Array.isArray(shared) ? shared : []
114  for (const raw of list) {
115    if (!raw || typeof raw !== 'object') continue
116    const s = raw as Partial<Limit>
117    if (typeof s.kind !== 'string' || typeof s.percentUsed !== 'number' || !Number.isFinite(s.percentUsed)) continue
118    if (typeof s.resetsAt !== 'number' || s.resetsAt <= nowSeconds) continue
119    const mine = out.get(s.kind)
120    const at = typeof s.at === 'number' && Number.isFinite(s.at) ? { at: s.at } : {}
121    const theirs: Limit = { kind: s.kind, percentUsed: s.percentUsed, resetsAt: s.resetsAt, ...at }
122    if (!mine || mine.resetsAt === undefined) {
123      if (!mine) out.set(s.kind, theirs)
124      continue
125    }
126    // Resets read a fraction apart from one request to the next: within a minute is the same window.
127    if (Math.abs(mine.resetsAt - s.resetsAt) <= 60) {
128      if (replaces(theirs, mine)) out.set(s.kind, { ...mine, percentUsed: s.percentUsed, ...at })
129    } else if (s.resetsAt > mine.resetsAt || mine.resetsAt <= nowSeconds) {
130      out.set(s.kind, theirs)
131    }
132  }
133  return [...out.values()]
134}
135
136/**
137 * The readings a `usage_command` printed: the first line as JSON,
138 * `{"five_hour":{"used_percentage":N,"resets_at":"ISO"},"seven_day":{...}}`.
139 * A window's optional `observed_at` (ISO) says when it was read; without one
140 * it counts as read at `nowSeconds`. Anything else is no reading (undefined),
141 * so what's known stays.
142 */
143export function parseUsage(stdout: string, nowSeconds?: number): Limit[] | undefined {
144  try {
145    const parsed: unknown = JSON.parse(stdout.split('\n')[0] ?? '')
146    if (!parsed || typeof parsed !== 'object') return undefined
147    const out: Limit[] = []
148    for (const kind of ['five_hour', 'seven_day']) {
149      const w = (parsed as Record<string, unknown>)[kind]
150      if (!w || typeof w !== 'object') continue
151      const { used_percentage: pct, resets_at: at, observed_at: seen } =
152        w as { used_percentage?: unknown; resets_at?: unknown; observed_at?: unknown }
153      const resetsAt = typeof at === 'string' ? Date.parse(at) / 1000 : NaN
154      if (typeof pct !== 'number' || !Number.isFinite(pct) || !Number.isFinite(resetsAt)) continue
155      const observed = typeof seen === 'string' ? Date.parse(seen) / 1000 : NaN
156      const when = Number.isFinite(observed) ? Math.floor(observed) : nowSeconds
157      out.push({ kind, percentUsed: Math.min(100, Math.max(0, pct)), resetsAt: Math.floor(resetsAt),
158        ...(when !== undefined ? { at: when } : {}) })
159    }
160    return out.length ? out : undefined
161  } catch {
162    return undefined
163  }
164}
165
hooks/extras.ts 455 lines
1// What only the mod can show: a receipt for each turn, the agents running,
2// when the context will compact, what fills it, repeated tool failures, the
3// day's totals across sessions, a share card and a pace coach. Pure, like
4// core.ts: the mod hands in what the engine reported, these turn it into
5// words, and the tests call them directly.
6
7import { SEP, clock, duration, modelName, pace, pct, tokens, width } from './core'
8import type { Segment, Tone, Window } from './core'
9import type { AgentRow, ContextView, Day, Forecast, Ledger, Receipt, Totals } from '../types'
10
11export const EMPTY_TOTALS: Totals = {
12  turns: 0, tools: 0, failures: 0, agents: 0, colds: 0, peakContext: 0, byTool: {}, compactions: [], growth: [],
13  cacheRead: 0, inputTokens: 0,
14}
15
16export function emptyDay(day: string): Day {
17  return { day, cost: 0, turns: 0, tools: 0, sessions: 0, colds: 0, agents: 0 }
18}
19
20const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
21
22// --------------------------------------------------------------- receipts
23
24/** The fields a receipt can show, in the order they are written. */
25export const RECEIPT_FIELDS = ['cost', 'cache', 'context', 'tools', 'agents', 'output'] as const
26export type ReceiptField = (typeof RECEIPT_FIELDS)[number]
27/** `adaptive` picks what the turn did that was out of the ordinary; a field list prints the same fields every time. */
28export type ReceiptSpec = 'adaptive' | ReceiptField[]
29export const RECEIPT_PRESETS: Record<string, ReceiptField[]> = {
30  short: ['cost', 'cache', 'tools'],
31  full: ['cost', 'cache', 'context', 'tools', 'agents', 'output'],
32  off: [],
33}
34
35/** `adaptive`, `short`, `full`, `off`, or a comma list of fields. */
36export function receiptFields(spec: unknown): ReceiptSpec {
37  if (typeof spec !== 'string') return 'adaptive'
38  const name = spec.trim()
39  if (name === 'adaptive') return 'adaptive'
40  const preset = RECEIPT_PRESETS[name]
41  if (preset) return preset
42  const picked = name.split(',').map(s => s.trim()).filter((s): s is ReceiptField => (RECEIPT_FIELDS as readonly string[]).includes(s))
43  return picked.length ? picked : 'adaptive'
44}
45
46/** The share of a request's input the prompt cache served, 0 to 100. */
47export function cacheHit(u: { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }): number | undefined {
48  const total = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
49  return total > 0 ? (u.cache_read_input_tokens / total) * 100 : undefined
50}
51
52export function money(usd: number): string {
53  if (usd < 0.005) return '<$0.01'
54  return usd < 100 ? `$${usd.toFixed(2)}` : `$${Math.round(usd)}`
55}
56
57/** One piece of a receipt: its words, and how loud it is (`accent` and up stand out). */
58export type Part = { text: string; tone?: Tone }
59
60/** The turn's cost at API prices, or nothing when background work makes it someone else's too. */
61function costPart(r: Receipt): Part | undefined {
62  return r.cost !== undefined && r.cost > 0 && !r.overlap ? { text: `API ${money(r.cost)}` } : undefined
63}
64
65function cachePart(r: Receipt): Part | undefined {
66  return r.cacheHit !== undefined ? { text: `cache read ${Math.floor(r.cacheHit)}%` } : undefined
67}
68
69/** The receipt's parts for a fixed field list, in field order; zero and unknown figures are left out. */
70export function receiptParts(r: Receipt, fields: readonly ReceiptField[]): Part[] {
71  const parts: Part[] = []
72  for (const field of fields) {
73    const part = field === 'cost' ? costPart(r)
74      : field === 'cache' ? cachePart(r)
75        : field === 'context' && r.context !== undefined && r.context !== 0
76          ? { text: r.context > 0 ? `+${tokens(r.context)} context` : `−${tokens(-r.context)} context` }
77          : field === 'tools' && r.tools > 0 ? { text: plural(r.tools, 'tool') }
78            : field === 'agents' && r.agents > 0 ? { text: plural(r.agents, 'agent') }
79              : field === 'output' && r.output ? { text: `${tokens(r.output)} out` } : undefined
80    if (part) parts.push(part)
81  }
82  return parts
83}
84
85/** A context jump worth a mention: 8k tokens, or 2% of the window when that is more. */
86export function bigJump(r: Receipt): boolean {
87  if (r.context === undefined || r.compacted) return false
88  return r.context >= Math.max(8000, 0.02 * (r.window ?? 0))
89}
90
91/** How much more than the recent median a turn has to cost, and by how many dollars, to be called out. */
92export const OUTLIER = { ratio: 3, dollars: 0.2, history: 5 }
93
94/**
95 * The turn's cost over the median of earlier attributable turns: undefined
96 * until there are `OUTLIER.history` of them, or when the turn's own cost is
97 * not attributable. Fixed when the turn closes, so an old receipt never
98 * changes its mind.
99 */
100export function costRatio(cost: number | undefined, overlap: boolean, earlier: readonly number[]): number | undefined {
101  if (cost === undefined || cost <= 0 || overlap || earlier.length < OUTLIER.history) return undefined
102  const sorted = [...earlier].sort((a, b) => a - b)
103  const middle = sorted.length / 2
104  const median = sorted.length % 2 ? sorted[Math.floor(middle)] ?? 0 : ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2
105  if (median <= 0 || cost - median < OUTLIER.dollars) return undefined
106  const ratio = cost / median
107  return ratio >= OUTLIER.ratio ? ratio : undefined
108}
109
110/**
111 * What about a turn is worth reading, at most two facts, most telling first:
112 * failed calls, a compaction, a cold cache the turn rebuilt, a big context
113 * jump, a large cache write that the context's growth doesn't explain.
114 * Observations, never diagnoses.
115 */
116export function receiptEvents(r: Receipt): Part[] {
117  const events: Part[] = []
118  // The model that answered wasn't the one asked for: Claude Code fell back.
119  if (r.servedBy) events.push({ tone: 'bad', text: `answered by ${modelName(r.servedBy)}` })
120  // What the guard changed on this turn, by the person's own rules.
121  const ended = r.guardEnded?.pace
122    ? `ended the turn, ahead of pace: ${Math.round(r.guardEnded.pace.used)}% of the ${r.guardEnded.window === '5h' ? '5h' : 'week'} used, ${Math.round(r.guardEnded.pace.allowed)}% allowed`
123    : r.guardEnded ? `ended the turn, ${Math.max(0, Math.round(r.guardEnded.left))}% ${r.guardEnded.window} left` : ''
124  const guard = [ended,
125    r.guardEffort ? `effort ${r.guardEffort.to}` : '', r.guardAgents ? `${plural(r.guardAgents, 'agent')} on a cheaper model` : '']
126    .filter(Boolean)
127  if (guard.length) events.push({ tone: 'warn', text: `guard: ${guard.join(', ')}` })
128  if (r.failures !== undefined && r.failures >= 2) {
129    events.push({ tone: 'bad', text: r.failedTool ? `${r.failures} failed ${r.failedTool} calls` : `${r.failures} failed calls` })
130  }
131  if (r.compacted) {
132    const { before, after } = r.compacted
133    events.push({ tone: 'accent', text: before && after !== undefined ? `compacted ${tokens(before)} → ${tokens(after)}` : 'compacted' })
134  }
135  const write = r.cacheWrite ?? 0
136  // The turn's first request came after the cache's lifetime and rewrote most of it.
137  const cold = r.cold === true && write >= 10_000
138  if (cold) events.push({ tone: 'warn', text: `cache cold${r.accountChanged ? ' after account change' : ''} · rebuilt ${tokens(write)}` })
139  if (bigJump(r)) events.push({ tone: 'accent', text: `+${tokens(r.context ?? 0)} context` })
140  if (!cold && r.warmBefore && write >= 20_000 && write >= Math.max(0, r.context ?? 0) + 10_000) {
141    events.push({ tone: 'warn', text: `cache write ${tokens(write)}` })
142  }
143  return events.slice(0, 2)
144}
145
146/** The first of the turn's unusual facts, if any. */
147export function receiptEvent(r: Receipt): Part | undefined {
148  return receiptEvents(r)[0]
149}
150
151/**
152 * The adaptive receipt: an ordinary turn says what it cost and how much the
153 * cache served; an unusual one leads with what was unusual (at most two
154 * facts), then the cost. A cost several times the recent median says so
155 * after the cost.
156 */
157export function adaptiveParts(r: Receipt): Part[] {
158  const events = receiptEvents(r)
159  const cost = costPart(r)
160  const outlier = cost && r.ratio !== undefined ? { tone: 'accent' as Tone, text: `${Math.round(r.ratio)}x recent` } : undefined
161  if (events.length) return [...events, cost, outlier].filter((p): p is Part => p !== undefined)
162  if (outlier && cost) return [cost, outlier]
163  return [cost, cachePart(r)].filter((p): p is Part => p !== undefined)
164}
165
166export function receiptSpec(r: Receipt, spec: ReceiptSpec): Part[] {
167  return spec === 'adaptive' ? adaptiveParts(r) : receiptParts(r, spec)
168}
169
170/** The parts that fit `room` (with their ` · ` leads), the last dropped first, so the lead fact stays. */
171export function fitParts(parts: readonly Part[], room?: number): Part[] {
172  const kept = [...parts]
173  while (kept.length) {
174    if (room === undefined || width(SEP + kept.map(p => p.text).join(SEP)) <= room) return kept
175    kept.pop()
176  }
177  return []
178}
179
180/** ` · API $0.38 · cache read 94%`, the last parts dropped to fit `room`. */
181export function receiptText(r: Receipt, spec: ReceiptSpec, room?: number): string {
182  const parts = fitParts(receiptSpec(r, spec), room)
183  return parts.length ? SEP + parts.map(p => p.text).join(SEP) : ''
184}
185
186/** The spinner's words for the running turn: cost so far, tools, agents, and failures once there are two. */
187/**
188 * The spinner's words for the running turn: the burn so far (tools, agents,
189 * context added, the 5-hour window), and a warning once calls keep failing,
190 * naming the tool and what it failed on when they were all the same.
191 */
192export function spinnerParts(live: { tools: number; agents: number; failures?: number; failedTool?: string | null;
193  failedTarget?: string | null; contextGrowth?: number }, fiveHour?: number): string[] {
194  const parts: string[] = []
195  if (live.failures && live.failures >= 2) {
196    const on = live.failedTool && live.failedTarget && live.failedTarget !== live.failedTool ? ` on ${live.failedTarget}` : ''
197    parts.push(live.failedTool ? `⚠ ${live.failures}× ${live.failedTool} failures${on}` : `⚠ ${live.failures} failed calls`)
198  }
199  if (live.tools) parts.push(plural(live.tools, 'tool'))
200  if (live.agents) parts.push(plural(live.agents, 'agent'))
201  if (live.contextGrowth !== undefined && live.contextGrowth >= 1000) parts.push(`+${tokensOne(live.contextGrowth)} ctx`)
202  if (fiveHour !== undefined) parts.push(`5h ${pct(fiveHour)}`)
203  return parts
204}
205
206/** `4.1k` under ten thousand, `42k` above: a growth figure that moves visibly while a turn runs. */
207export function tokensOne(count: number): string {
208  return count >= 1000 && count < 10_000 ? `${(count / 1000).toFixed(1)}k` : tokens(count)
209}
210
211/** A turn's length as Claude Code writes it on that line: `11s`, `1m 4s`, `1h 2m 3s`. */
212export function turnLength(ms: number): string {
213  const s = Math.floor(ms / 1000)
214  const h = Math.floor(s / 3600)
215  const m = Math.floor((s % 3600) / 60)
216  const rest = s % 60
217  if (h) return `${h}h ${m}m ${rest}s`
218  if (m) return `${m}m ${rest}s`
219  return `${rest}s`
220}
221
222/** Columns Claude Code's own `✻ Baked for 3s · done 3:45 PM` takes, the glyph's two included. */
223export function turnLineWidth(word: string, durationMs: number, doneAt?: string): number {
224  return 2 + width(`${word} for ${turnLength(durationMs)}${doneAt ? ` · done ${doneAt}` : ''}`)
225}
226
227// ----------------------------------------------------------------- agents
228
229const ACTIVE = new Set(['pending', 'running', 'waiting'])
230const ENDED = new Set(['completed', 'failed', 'killed'])
231
232export const isActive = (status: string) => ACTIVE.has(status)
233export const isEnded = (status: string) => ENDED.has(status)
234
235/** `agents 3 (2 running, 1 waiting)`, only while some are at work. */
236export function agentsSegment(rows: readonly AgentRow[]): Segment | undefined {
237  const active = rows.filter(row => isActive(row.status))
238  if (!active.length) return undefined
239  const running = active.filter(row => row.status !== 'waiting').length
240  const waiting = active.length - running
241  const detail = waiting && running ? ` (${running} running, ${waiting} waiting)` : waiting ? ' waiting' : ' running'
242  return { key: 'agents', priority: 68, forms: [`agents ${active.length}${detail}`, `agents ${active.length}`, `ag ${active.length}`] }
243}
244
245// ------------------------------------------------------------- compaction
246
247/**
248 * When auto-compaction will run: the room left before its threshold over the
249 * average context growth of the last turns. Undefined below 60% of the
250 * threshold, with too little history, or when it is more than 30 turns off.
251 */
252export function forecast(contextTokens: number | undefined, threshold: number | undefined, growth: readonly number[]): Forecast | undefined {
253  if (!contextTokens || !threshold || threshold <= 0) return undefined
254  const percent = (contextTokens / threshold) * 100
255  const recent = growth.slice(-5)
256  if (percent < 60 || recent.length < 2) return undefined
257  const average = recent.reduce((sum, n) => sum + Math.max(0, n), 0) / recent.length
258  if (average <= 0) return undefined
259  const turns = Math.max(1, Math.ceil((threshold - contextTokens) / average))
260  return turns > 30 ? undefined : { turns, percent, threshold }
261}
262
263export function forecastSegment(f?: Forecast | null): Segment | undefined {
264  if (!f) return undefined
265  const tone: Tone | undefined = f.turns <= 2 ? 'warn' : undefined
266  // One turn out is said as "soon": the average of recent growth is rough.
267  if (f.turns <= 1) return { key: 'compact', priority: 72, tone, forms: ['compacts soon', 'compact soon', 'cmp soon'] }
268  return { key: 'compact', priority: 72, tone,
269    forms: [`compacts in ~${f.turns} turns`, `compact ~${f.turns} turns`, `cmp ~${f.turns}`] }
270}
271
272export function compactionText(c: { trigger: string; before?: number; after?: number }): string {
273  const how = c.trigger === 'auto' ? 'automatically' : c.trigger === 'manual' ? 'by /compact' : `by ${c.trigger}`
274  if (c.before && c.after !== undefined) return `Context compacted ${how}: ${tokens(c.before)} → ${tokens(c.after)} tokens.`
275  return `Context compacted ${how}.`
276}
277
278// ----------------------------------------------------------- context view
279
280type Breakdown = {
281  categories: readonly { name: string; tokens: number; kind: string }[]
282  totalTokens: number
283  rawMaxTokens: number
284  autoCompactThreshold?: number
285  isAutoCompactEnabled: boolean
286  mcpTools: readonly { serverName: string; tokens: number; isLoaded: boolean }[]
287  memoryFiles: readonly { tokens: number }[]
288  skills?: { includedSkills: number; tokens: number }
289}
290
291/** The breakdown, cut to what the pane shows: no file paths, no tool names. */
292export function contextView(b: Breakdown, at: number): ContextView {
293  const servers = new Map<string, { tokens: number; tools: number }>()
294  for (const tool of b.mcpTools) {
295    if (!tool.isLoaded) continue
296    const s = servers.get(tool.serverName) ?? { tokens: 0, tools: 0 }
297    servers.set(tool.serverName, { tokens: s.tokens + tool.tokens, tools: s.tools + 1 })
298  }
299  return {
300    at, total: b.totalTokens, max: b.rawMaxTokens,
301    threshold: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
302    rows: b.categories.filter(c => c.kind === 'used' && c.tokens > 0).map(c => ({ name: c.name, tokens: c.tokens, kind: c.kind }))
303      .sort((x, y) => y.tokens - x.tokens),
304    mcp: [...servers].map(([server, s]) => ({ server, ...s })).sort((x, y) => y.tokens - x.tokens),
305    memoryFiles: b.memoryFiles.length,
306    memoryTokens: b.memoryFiles.reduce((sum, f) => sum + f.tokens, 0),
307    skills: b.skills ? { count: b.skills.includedSkills, tokens: b.skills.tokens } : undefined,
308  }
309}
310
311/** The MCP servers whose tool definitions ride in the context but none of whose tools ran. */
312export function unusedServers(view: ContextView, byTool: Totals['byTool']): { server: string; tokens: number }[] {
313  const used = new Set(Object.keys(byTool).filter(t => t.startsWith('mcp__')).map(t => t.split('__')[1]))
314  return view.mcp.filter(s => !used.has(s.server)).map(s => ({ server: s.server, tokens: s.tokens }))
315}
316
317// ------------------------------------------------------------ tool vitals
318
319/** What a call worked on, short: a file's name, a command's first words. */
320export function target(tool: string, input: Record<string, unknown>): string {
321  const pick = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : undefined)
322  const path = pick('file_path') ?? pick('notebook_path') ?? pick('path')
323  if (path) return path.split('/').filter(Boolean).pop() ?? path
324  const command = pick('command')
325  if (command) return command.trim().split(/\s+/).slice(0, 3).join(' ').slice(0, 40)
326  const other = pick('pattern') ?? pick('url') ?? pick('query') ?? pick('skill')
327  return other ? other.slice(0, 40) : tool
328}
329
330/** The toast after the same call has failed `streak` times in a row. */
331export function loopWarning(tool: string, what: string, streak: number): string {
332  const on = what && what !== tool ? ` on ${what}` : ''
333  return `⚠ ${streak}× ${tool} failures in a row${on}. Worth a look before it burns more of your limit.`
334}
335
336// ----------------------------------------------------------------- ledger
337
338/** `2026-10-13` in the caller's zone. */
339export function dayOf(ms: number, offsetMinutes = 0): string {
340  return new Date(ms + offsetMinutes * 60_000).toISOString().slice(0, 10)
341}
342
343const KEY = /^d:(\d{4}-\d{2}-\d{2}):/
344
345/** Store keys from before `keepDays` days ago. */
346export function staleKeys(keys: readonly string[], today: string, keepDays = 35): string[] {
347  const cutoff = new Date(Date.parse(`${today}T00:00:00Z`) - keepDays * 86_400_000).toISOString().slice(0, 10)
348  return keys.filter(key => { const m = KEY.exec(key); return m !== null && (m[1] ?? '') < cutoff })
349}
350
351/** Today and the last seven days, each summed over the sessions' entries. */
352export function ledger(entries: readonly { key: string; value: unknown }[], today: string): Ledger {
353  const days: string[] = []
354  for (let i = 6; i >= 0; i--) days.push(new Date(Date.parse(`${today}T00:00:00Z`) - i * 86_400_000).toISOString().slice(0, 10))
355  const sums = new Map(days.map(day => [day, emptyDay(day)]))
356  for (const { key, value } of entries) {
357    const day = KEY.exec(key)?.[1]
358    const sum = day ? sums.get(day) : undefined
359    if (!sum || !value || typeof value !== 'object') continue
360    const v = value as Record<string, unknown>
361    const n = (k: string) => (typeof v[k] === 'number' && Number.isFinite(v[k]) ? (v[k] as number) : 0)
362    sum.cost += n('cost'); sum.turns += n('turns'); sum.tools += n('tools'); sum.colds += n('colds'); sum.agents += n('agents')
363    if (n('warms')) {
364      sum.warms = (sum.warms ?? 0) + n('warms')
365      sum.warmCost = (sum.warmCost ?? 0) + n('warmCost')
366    }
367    sum.sessions += 1
368  }
369  const week = days.map(day => sums.get(day) ?? emptyDay(day))
370  return { today: week[week.length - 1] ?? emptyDay(today), week }
371}
372
373/** `today $41` (`of $50` with a budget), for the line. */
374export function todaySegment(day: Day | undefined, budget?: number): Segment | undefined {
375  if (!day || day.cost <= 0) return undefined
376  const spent = money(day.cost)
377  if (budget && budget > 0) {
378    const share = (day.cost / budget) * 100
379    const tone: Tone | undefined = share >= 100 ? 'bad' : share >= 80 ? 'warn' : undefined
380    return { key: 'today', priority: 58, tone, forms: [`today ${spent} of ${money(budget)}`, `today ${spent}`] }
381  }
382  return { key: 'today', priority: 58, tone: 'dim', forms: [`today ${spent}`] }
383}
384
385const BLOCKS = '▁▂▃▄▅▆▇█'
386
387/** One block per value, scaled to the largest. */
388export function spark(values: readonly number[]): string {
389  const top = Math.max(0, ...values)
390  return values.map(v => (top <= 0 || v <= 0 ? ' ' : BLOCKS[Math.min(7, Math.round((v / top) * 7))])).join('')
391}
392
393// ------------------------------------------------------------------ coach
394
395const LOWER: Record<string, string> = { max: 'xhigh', xhigh: 'high', high: 'medium' }
396
397/**
398 * Advice for a usage window on pace to run out: how much slower the rest of
399 * the window would have to go to last until it resets, and the one command
400 * that usually gets there (a lower effort, else a lighter model), offered
401 * for Tab to take. It changes nothing itself.
402 */
403export function coach(kind: 'five_hour' | 'seven_day', window: Window | undefined, now: number,
404  effort?: string, offsetMinutes = 0): { text: string; suggest: string } | undefined {
405  const state = pace(kind, window, now)
406  const used = window?.used_percentage
407  const resets = window?.resets_at
408  if (state?.kind !== 'hot' || used === undefined || resets === undefined) return undefined
409  const length = kind === 'five_hour' ? 5 * 3600 : 7 * 86400
410  const rate = used / (now - (resets - length))
411  const affordable = (100 - used) / (resets - now)
412  const cut = Math.round((1 - affordable / rate) * 100)
413  if (cut <= 0) return undefined
414  const lower = effort ? LOWER[effort] : undefined
415  const suggest = lower ? `/effort ${lower}` : '/model'
416  const name = kind === 'five_hour' ? '5-hour' : 'Weekly'
417  const at = (t: number) => clock(t, now, offsetMinutes)
418  // Short enough for a toast's three lines.
419  return {
420    suggest,
421    text: `${name} limit: out at ${at(state.eta)} at this pace, resets ${at(resets)}. To last, use ~${cut}% less per hour: Tab takes ${suggest}.`,
422  }
423}
424
425// ------------------------------------------------------------------- card
426
427export type CardInput = {
428  model?: string
429  elapsedSeconds?: number
430  totals: Totals
431  cost?: number
432  cacheHit?: number
433  fiveHour?: number
434  agentsNow: number
435  today?: Day
436}
437
438/** The share card's lines. No repository, branch, path or account. */
439export function cardLines(c: CardInput): string[] {
440  const t = c.totals
441  const head = [c.model, c.elapsedSeconds !== undefined ? duration(c.elapsedSeconds) : undefined, plural(t.turns, 'turn')]
442    .filter(Boolean).join(SEP)
443  const work = [plural(t.tools, 'tool call'), t.agents ? plural(t.agents, 'agent') : undefined,
444    t.failures ? plural(t.failures, 'failed call') : undefined].filter(Boolean).join(SEP)
445  const cache = [c.cacheHit !== undefined ? `cache read ${pct(c.cacheHit)}` : undefined,
446    plural(t.compactions.length, 'compaction'), plural(t.colds, 'cold-cache rebuild')].filter(Boolean).join(SEP)
447  const lines = ['g-line · session card', head, work, cache]
448  const money_ = [c.cost !== undefined ? `${money(c.cost)} at API prices` : undefined,
449    t.peakContext ? `peak context ${pct(t.peakContext)}` : undefined,
450    c.fiveHour !== undefined ? `5h window ${pct(c.fiveHour)}` : undefined].filter(Boolean).join(SEP)
451  if (money_) lines.push(money_)
452  if (c.today && c.today.sessions > 0) lines.push(`today: ${money(c.today.cost)} over ${plural(c.today.sessions, 'session')} on this machine`)
453  return lines
454}
455
hooks/inline.ts 101 lines
1// The one line glanceline adds under the prompt: every segment of the layout,
2// then an optional account, fitted to the room left at the end of Claude
3// Code's own hint line. Pure, like core.ts, so tests can call it directly.
4
5import { SEP, fit, layoutKeys, segments, width } from './core'
6import type { Options, Payload, Placed, Segment } from './core'
7
8/**
9 * Columns the engine's permission-mode label takes before the hint when a
10 * mode is on (`⏵⏵ bypass permissions on `, the widest), the hint then reading
11 * `(shift+tab to cycle)`.
12 */
13export const MODE_LABEL = 26
14
15/**
16 * Columns of the label a quieter mode draws before the hint (`⏸ manual mode
17 * on · `). The hint the mod is handed leaves it out, and it stays while you
18 * type, so these columns are always kept free.
19 */
20export const QUIET_MODE_LABEL = 19
21
22/** The hint line's two-column indent, and the three columns the engine keeps free at its right end. */
23const EDGES = 5
24
25/**
26 * The line an `account_command` printed, as one short segment:
27 * `account you@example.com (via my-accounts)` reads `you@example.com`.
28 */
29export function accountSegment(line?: string | null): Segment | undefined {
30  const text = line?.trim()
31  if (!text) return undefined
32  const short = text.replace(/^account\s+/i, '').replace(/\s*\([^()]*\)$/, '').trim()
33  return { key: 'account', priority: 65, tone: 'dim', forms: [short || text] }
34}
35
36/**
37 * Columns left for glanceline after the engine's hint (which it joins to the
38 * tail with ` · `), or undefined when the surface has not measured.
39 */
40export function tailRoom(columns: number | undefined, hint: string, shown = hint): number | undefined {
41  if (columns === undefined) return undefined
42  const mode = /shift\+tab/i.test(hint) ? MODE_LABEL : QUIET_MODE_LABEL
43  return columns - EDGES - mode - width(shown) - SEP.length
44}
45
46/**
47 * Claude Code's two standing hints, shortened. Any other hint (`esc to
48 * interrupt`, a background shell's pill, a key to press twice) is left whole.
49 */
50export const SHORT_HINTS: Record<string, string> = { '(shift+tab to cycle)': '⇧⇥', '? for shortcuts': '?' }
51
52/**
53 * The hint line's props with glanceline's text added: after a shortened
54 * standing hint (a rewritten hint replaces the engine's tail, so only when
55 * there is none), else as the tail the engine draws after its own hint.
56 */
57export function withText<P extends { hint: string; tail?: string }>(props: P, text: string, short: boolean): P {
58  if (!text) return props
59  const brief = short && !props.tail ? SHORT_HINTS[props.hint] : undefined
60  if (brief !== undefined) return { ...props, hint: `${brief} · ${text}` }
61  return { ...props, tail: props.tail ? `${props.tail} · ${text}` : text }
62}
63
64/** The hint as it will show: shortened where `withText` would shorten it. */
65export function shownHint(hint: string, short: boolean): string {
66  return (short && SHORT_HINTS[hint]) || hint
67}
68
69/** Keys only the mod can fill, placed where a custom `segments` layout names them. */
70export const MOD_KEYS = ['agents', 'compact', 'today'] as const
71
72/**
73 * Every segment on one line, the account last, fitted to `room`: segments
74 * narrow together and the least important go first. Mod-only segments
75 * (`extras`) stand where the layout names them. Empty under four columns,
76 * where the engine would leave the tail out anyway.
77 */
78export function inline(p: Payload, o: Options, account?: string | null, room?: number,
79  extras: Partial<Record<string, Segment | undefined>> = {}, trailing: Segment[] = []): Placed[] {
80  const core = new Map(segments(p, o).flat().map(segment => [segment.key, segment]))
81  const items: Segment[] = []
82  for (const key of layoutKeys(o).flat()) {
83    const segment = core.get(key) ?? extras[key]
84    if (segment) items.push(segment)
85  }
86  items.push(...trailing)
87  const extra = accountSegment(account)
88  if (extra) items.push(extra)
89  if (!items.length || (room !== undefined && room < 4)) return []
90  return fit(items, room)
91}
92
93/** Columns to keep free for the footer's mode labels at the right of the hint row, with a clear gap before them. */
94export function modesWidth(labels: readonly string[]): number {
95  return labels.length ? width(labels.join(' & ')) + 4 : 0
96}
97
98export function joined(parts: Placed[]): string {
99  return parts.map(part => part.text).join(SEP)
100}
101
hooks/deck.ts 188 lines
1// The two lines under the prompt. Line 1 rides at the end of Claude Code's own
2// hint line and says how full things are: context, and how much of each usage
3// window is gone. Line 2 sits directly under it, in colour: the model and its
4// effort, then what happens next: when the prompt cache goes cold, when each
5// window resets or runs out, what is running, what compacts.
6//
7// Pure, like core.ts: the mod hands in what it knows, the tests call it.
8
9import { SEP, clock, duration, fit, num, pace, pct, roundEta, str, tokens } from './core'
10import type { Options, Payload, Placed, Segment, Tone } from './core'
11
12/** Added to a segment's priority while it warns, as core's segments do. */
13const URGENT = 50
14
15function urgent(segment: Segment): Segment {
16  return segment.tone === 'warn' || segment.tone === 'bad' ? { ...segment, priority: segment.priority + URGENT } : segment
17}
18
19function pressure(percent: number): Tone | undefined {
20  if (percent >= 95) return 'bad'
21  if (percent >= 80) return 'warn'
22  return undefined
23}
24
25const WINDOW_NAME = { five_hour: '5h', seven_day: 'wk' } as const
26
27// ------------------------------------------------------------------ line 1
28
29/** `Opus 5.5 xhigh`, or `Opus 5.5 xhigh→medium` where the guard ran it lower: the effort stays even in the narrowest form. */
30export function modelNext(p: Payload): Segment | undefined {
31  const name = str(p.model?.display_name) ?? str(p.model?.id)
32  if (!name) return undefined
33  const level = str(p.effort?.level, 12)
34  const set = str(p.effort?.set, 12)
35  const fast = p.fast_mode === true ? ' fast' : ''
36  const family = name.split(' ')[0] ?? name
37  if (level && set && set !== level) {
38    return { key: 'model', priority: 95, tone: 'warn',
39      forms: [`${name} ${set}→${level} by guard${fast}`, `${name} ${set}→${level}${fast}`, `${family} ${set}→${level}`, `${family} ${level}`] }
40  }
41  const forms = level
42    ? [`${name} ${level}${fast}`, `${family} ${level}${fast}`, `${family} ${level}`]
43    : [`${name}${fast}`, family]
44  return { key: 'model', priority: 95, tone: 'accent', forms }
45}
46
47export function contextNow(p: Payload): Segment | undefined {
48  const w = p.context_window
49  const used = num(w?.used_percentage)
50  if (used === undefined || used < 0) return undefined
51  // The window's headroom isn't the room before auto-compact, so the line
52  // shows the percentage alone; the `/g-line` pane says the rest.
53  return { key: 'context', priority: 90, tone: pressure(used), forms: [`ctx ${pct(used)}`] }
54}
55
56/** `5h 64%`, with `!` once the window is on pace to run out (the line is drawn dim). */
57export function windowNow(p: Payload, kind: 'five_hour' | 'seven_day', now: number): Segment | undefined {
58  const window = p.rate_limits?.[kind]
59  const used = num(window?.used_percentage)
60  if (used === undefined || used < 0) return undefined
61  const state = pace(kind, window, now)
62  const name = WINDOW_NAME[kind]
63  const priority = kind === 'five_hour' ? 85 : 70
64  if (state?.kind === 'full') return { key: kind, priority, tone: 'bad', forms: [`${name} full`] }
65  if (state?.kind === 'hot') return { key: kind, priority, tone: 'warn', forms: [`${name} ${pct(used)}!`] }
66  return { key: kind, priority, tone: pressure(used), forms: [`${name} ${pct(used)}`] }
67}
68
69export function spendNow(p: Payload): Segment | undefined {
70  const used = num(p.rate_limits?.spend_limit?.used_percentage)
71  if (used === undefined || used < 0) return undefined
72  return { key: 'spend', priority: 75, tone: pressure(used), forms: [`spend ${pct(used)}`] }
73}
74
75/** Line 1's segments, in order. */
76export function lineNow(p: Payload, o: Options): Segment[] {
77  return [contextNow(p), windowNow(p, 'five_hour', o.now), windowNow(p, 'seven_day', o.now), spendNow(p)]
78    .filter((s): s is Segment => s !== undefined).map(urgent)
79}
80
81// ------------------------------------------------------------------ line 2
82
83/**
84 * `cache warm ~58m (57k)`, green while warm, amber in its last minutes, then `cache cold`;
85 * after a compaction, the summary the next turn writes instead.
86 */
87export function cacheNext(p: Payload, now: number): Segment | undefined {
88  const cache = p.prompt_cache
89  if (!cache || cache.caching_observed !== true) return undefined
90  const expires = num(cache.expires_at)
91  if (cache.compacted === true) {
92    const size = num(cache.recache_tokens_if_cold)
93    return { key: 'cache', priority: 90,
94      forms: size && size > 0 ? [`compacted, next turn caches ${tokens(size)}`, 'cache compacted'] : ['cache compacted'] }
95  }
96  if (cache.warm === true && expires !== undefined && expires > now) {
97    const left = expires - now
98    const soon = left <= (cache.ttl === '1h' ? 300 : 60)
99    // `~`: the mod knows when the last request ran and the cache's lifetime,
100    // not the provider's own expiry.
101    const about = left < 60 ? '<1m' : `~${duration(left, true)}`
102    const warm = `cache warm ${left < 60 ? '<1m' : `~${duration(left)}`}`
103    // Each request restarts the clock, so a busy session always reads ~59m:
104    // the size is what a lapse would cost.
105    const size = num(cache.recache_tokens_if_cold)
106    return { key: 'cache', priority: 90, tone: soon ? 'warn' : 'ok',
107      ...(size && size > 0 ? { spare: 1 } : {}),
108      forms: size && size > 0 ? [`${warm} (${tokens(size)})`, `cache ${about} (${tokens(size)})`, `cache ${about} ${tokens(size)}`, `cache ${about}`] : [warm, `cache ${about}`] }
109  }
110  const recache = num(cache.recache_tokens_if_cold)
111  if (cache.account_changed === true) {
112    return { key: 'cache', priority: 90, tone: 'warn',
113      ...(recache && recache > 0 ? { spare: 1 } : {}),
114      forms: recache && recache > 0
115        ? [`cache cold (account changed), next turn rebuilds ${tokens(recache)}`, `cache cold (account changed) ${tokens(recache)}`, `cache cold ${tokens(recache)}`, 'cache cold']
116        : ['cache cold (account changed)', 'cache cold'] }
117  }
118  // The size stays as long as there's room for it, like the warm cache's: it's what the next turn pays.
119  return { key: 'cache', priority: 90, tone: 'warn',
120    ...(recache && recache > 0 ? { spare: 1 } : {}),
121    forms: recache && recache > 0 ? [`cache cold, next turn rebuilds ${tokens(recache)}`, `cache cold, rebuilds ${tokens(recache)}`, `cache cold ${tokens(recache)}`, 'cache cold'] : ['cache cold'] }
122}
123
124/** When a window resets, or (on pace to run out) roughly when it runs out. */
125export function windowNext(p: Payload, kind: 'five_hour' | 'seven_day', o: Options): Segment | undefined {
126  const window = p.rate_limits?.[kind]
127  const used = num(window?.used_percentage)
128  const resets = num(window?.resets_at)
129  if (used === undefined || used < 0 || resets === undefined || resets <= o.now) return undefined
130  const name = WINDOW_NAME[kind]
131  const state = pace(kind, window, o.now)
132  const at = (t: number) => clock(t, o.now, o.utcOffsetMinutes)
133  const left = resets - o.now
134  // A healthy window's reset is the first thing to go when room is short.
135  const priority = kind === 'five_hour' ? 40 : 35
136  if (state?.kind === 'full') {
137    return { key: `${kind}_next`, priority, tone: 'bad', forms: [`${name} back in ${duration(left)}`, `${name} back ${duration(left, true)}`] }
138  }
139  if (state?.kind === 'hot') {
140    const tone: Tone = state.eta - o.now < 30 * 60 ? 'bad' : 'warn'
141    // How long until it fills, not a clock time: "out ~00:35" at 00:20 read as
142    // 35 minutes left, beside a reset two hours away. `back` is the full
143    // window's own word for the reset.
144    const fills = Math.max(60, roundEta(state.eta, o.now) - o.now)
145    return { key: `${kind}_next`, priority, tone,
146      forms: [`${name} full in ~${duration(fills)}, back ${at(resets)}`, `${name} full in ~${duration(fills, true)}`] }
147  }
148  return { key: `${kind}_next`, priority, forms: [`${name} resets in ${duration(left)}`, `${name} resets ${duration(left, true)}`] }
149}
150
151export function spendNext(p: Payload): Segment | undefined {
152  const spend = p.rate_limits?.spend_limit
153  const usd = num(spend?.used_usd)
154  const cap = num(spend?.limit_usd)
155  if (usd === undefined || !cap) return undefined
156  const period = ['daily', 'weekly', 'monthly'].includes(spend?.period ?? '') ? ` ${spend?.period}` : ''
157  return { key: 'spend_next', priority: 75, forms: [`$${Math.round(usd)} of $${Math.round(cap)}${period}`, `$${Math.round(usd)}/$${Math.round(cap)}`] }
158}
159
160/** Line 2's segments: the model and effort, the cache, the windows' timing, then what the mod adds (agents, compaction, today, branch, account). */
161export function lineNext(p: Payload, o: Options, extras: Segment[] = []): Segment[] {
162  return [modelNext(p), cacheNext(p, o.now), windowNext(p, 'five_hour', o), windowNext(p, 'seven_day', o), spendNext(p), ...extras]
163    .filter((s): s is Segment => s !== undefined).map(urgent)
164}
165
166// ---------------------------------------------------------------- the deck
167
168/** Columns line 2 has: it starts at the row's two-column indent, and the engine keeps three columns free at its end. */
169export function nextRoom(columns: number | undefined): number | undefined {
170  return columns === undefined ? undefined : columns - 5
171}
172
173export type Deck = { now: Placed[]; next: Placed[] }
174
175/**
176 * Both lines, each fitted to its own room. What line 1 has no room for moves
177 * down to line 2 instead of vanishing; line 2 drops its least important
178 * segments only when both lines are full.
179 */
180export function deck(p: Payload, o: Options, rooms: { now?: number; next?: number }, extras: Segment[] = []): Deck {
181  const now = lineNow(p, o)
182  const placed = rooms.now !== undefined && rooms.now < 4 ? [] : fit(now, rooms.now)
183  const kept = new Set(placed.map(part => part.key))
184  const moved = now.filter(segment => !kept.has(segment.key))
185  const next = [...lineNext(p, o, extras), ...moved]
186  return { now: placed, next: rooms.next !== undefined && rooms.next < 4 ? [] : fit(next, rooms.next) }
187}
188
hooks/dashboard.ts 249 lines
1// `/g-line dashboard`: one self-contained HTML page, a snapshot of what g-line
2// holds at the moment it is asked. No script, nothing loaded from anywhere,
3// nothing that updates itself. Pure, like extras.ts and deck.ts: the mod
4// gathers the snapshot, writes the file and opens it; this turns the figures
5// into words and markup, and the tests call it directly.
6//
7// Rule 4 (private by default): the page never takes a path, a repository name,
8// a branch or an email from the snapshot. The account line shows only when the
9// snapshot says the person set `account_command`.
10
11import { clock, duration, modelName, pace, pct, tokens, utcLabel } from './core'
12import type { Payload } from './core'
13import { cacheNext, windowNext } from './deck'
14import { dayOf, emptyDay, money } from './extras'
15import { rosterRow } from './roster'
16import type { RosterEntry } from './roster'
17import type { Day } from '../types'
18
19export type DashboardGuard = {
20  /** Each rule as `ruleText` writes it, and whether it is in force now. */
21  rules: { text: string; inForce: boolean }[]
22  /** `whyLines`: what is in force now. */
23  why: string[]
24  on: boolean
25  /** The readings are simulated (`/g-line guard simulate`). */
26  simulated: boolean
27  /** Keep-warm as the pane words it, when configured. */
28  keepWarm?: string
29  errors: string[]
30}
31
32export type DashboardSnapshot = {
33  /** Unix seconds when the snapshot was made. */
34  nowSeconds: number
35  /** Minutes east of UTC where the person is (their `tz`, else the machine's). */
36  utcOffsetMinutes: number
37  /** The IANA zone the person set under `tz`, if any. */
38  tz?: string
39  /** g-line's version, when it could be read. */
40  version?: string | null
41  /** The statusLine-shaped view the line is drawn from: windows, cache, model, context. */
42  payload: Payload
43  /** Sessions on this machine, this one included. */
44  sessions: { entry: RosterEntry; mine: boolean }[]
45  /** True only when the person set `account_command`. */
46  showAccount: boolean
47  /** The store's `d:<day>:<session>` entries. */
48  ledger: { key: string; value: unknown }[]
49  guard: DashboardGuard
50}
51
52/** Escapes a string for HTML text and attribute values. */
53export function esc(value: unknown): string {
54  return String(value ?? '')
55    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
56    .replace(/"/g, '&quot;').replace(/'/g, '&#39;')
57}
58
59const KEY = /^d:(\d{4}-\d{2}-\d{2}):/
60
61/** The last `count` days ending today, oldest first, each summed over the sessions' entries. */
62export function historyDays(entries: readonly { key: string; value: unknown }[], today: string, count = 14): Day[] {
63  const days: string[] = []
64  for (let i = count - 1; i >= 0; i--) days.push(new Date(Date.parse(`${today}T00:00:00Z`) - i * 86_400_000).toISOString().slice(0, 10))
65  const sums = new Map(days.map(day => [day, emptyDay(day)]))
66  for (const { key, value } of entries) {
67    const day = KEY.exec(key)?.[1]
68    const sum = day ? sums.get(day) : undefined
69    if (!sum || !value || typeof value !== 'object') continue
70    const v = value as Record<string, unknown>
71    const n = (k: string) => (typeof v[k] === 'number' && Number.isFinite(v[k]) ? (v[k] as number) : 0)
72    sum.cost += n('cost'); sum.turns += n('turns'); sum.tools += n('tools'); sum.colds += n('colds'); sum.agents += n('agents')
73    if (n('warms')) {
74      sum.warms = (sum.warms ?? 0) + n('warms')
75      sum.warmCost = (sum.warmCost ?? 0) + n('warmCost')
76    }
77    sum.sessions += 1
78  }
79  return days.map(day => sums.get(day) ?? emptyDay(day))
80}
81
82const WINDOWS = [['five_hour', '5-hour'], ['seven_day', 'weekly']] as const
83
84function windowsSection(s: DashboardSnapshot): string {
85  const now = s.nowSeconds
86  const rows: string[] = []
87  for (const [kind, name] of WINDOWS) {
88    const w = s.payload.rate_limits?.[kind]
89    const used = w?.used_percentage
90    if (typeof used !== 'number' || !Number.isFinite(used) || used < 0) continue
91    const resets = typeof w?.resets_at === 'number' && w.resets_at > now ? w.resets_at : undefined
92    const when = resets !== undefined ? `, resets ${clock(resets, now, s.utcOffsetMinutes)} (in ${duration(resets - now)})` : ''
93    const state = pace(kind, w, now)
94    const next = windowNext(s.payload, kind, { now, utcOffsetMinutes: s.utcOffsetMinutes })
95    const paceText = state?.kind === 'full' ? 'The window is full.'
96      : state?.kind === 'hot' ? `On pace to run out: ${next?.forms[0] ?? ''}.`
97      : state?.kind === 'ok' ? 'On pace to last until the reset.' : 'Too early in the window to project a pace.'
98    const tone = state?.kind === 'full' ? 'bad' : state?.kind === 'hot' || used >= 80 ? 'warn' : ''
99    rows.push(`<div class="card ${tone}"><div class="big">${esc(pct(used))}</div><div><p class="strong">${esc(`${name} ${pct(used)} used${when}`)}</p>`
100      + `<div class="meter"><span style="width:${Math.max(0, Math.min(100, used)).toFixed(0)}%"></span></div>`
101      + `<p class="muted">${esc(paceText)}</p></div></div>`)
102  }
103  if (!rows.length) return '<p class="muted">No usage readings yet (an API key, a cloud provider, or no request so far).</p>'
104  const zone = `Times are ${s.tz ? `in ${s.tz} (${utcLabel(s.utcOffsetMinutes)})` : `this machine's (${utcLabel(s.utcOffsetMinutes)})`}.`
105  return `<div class="cards">${rows.join('')}</div><p class="muted">${esc(zone)}</p>`
106}
107
108function sessionsSection(s: DashboardSnapshot): string {
109  if (!s.sessions.length) return '<p class="muted">No sessions reported on this machine yet.</p>'
110  const now = s.nowSeconds * 1000
111  const items = s.sessions.slice(0, 20).map(({ entry, mine }) => {
112    const shown = s.showAccount ? entry : { ...entry, account: undefined }
113    const tone = entry.state === 'waiting' ? 'warn' : entry.state === 'working' ? 'ok' : ''
114    return `<li class="${tone}">${esc(rosterRow(shown, now, mine))}</li>`
115  })
116  return `<ul class="rows">${items.join('')}</ul>`
117}
118
119function bars(days: readonly Day[]): string {
120  const top = Math.max(0, ...days.map(d => d.cost))
121  const w = 28
122  const h = 90
123  const cells = days.map((d, i) => {
124    const barH = top > 0 ? Math.max(d.cost > 0 ? 2 : 0, Math.round((d.cost / top) * (h - 16))) : 0
125    const x = i * w + 4
126    return `<g><title>${esc(`${d.day}: ${money(d.cost)}`)}</title>`
127      + `<rect class="bar" x="${x}" y="${h - barH}" width="${w - 8}" height="${barH}" rx="2"/>`
128      + `<text class="tick" x="${x + (w - 8) / 2}" y="${h + 12}" text-anchor="middle">${esc(d.day.slice(8))}</text></g>`
129  })
130  return `<svg class="chart" viewBox="0 0 ${days.length * w} ${h + 18}" role="img" aria-label="${esc(`Cost per day at API prices, last ${days.length} days, highest ${money(top)}`)}">${cells.join('')}</svg>`
131}
132
133function historySection(s: DashboardSnapshot): string {
134  const today = dayOf(s.nowSeconds * 1000, s.utcOffsetMinutes)
135  const days = historyDays(s.ledger, today, 14)
136  if (!days.some(d => d.turns || d.cost)) {
137    return '<p class="muted">No history yet: g-line counts turns from the sessions it runs in, and none has finished a turn in the last 14 days.</p>'
138  }
139  const cell = (n: number | undefined, text: string) => `<td class="num">${n ? esc(text) : '-'}</td>`
140  const rows = [...days].reverse().map(d => `<tr><td>${esc(d.day)}</td>${cell(d.turns, String(d.turns))}${cell(d.cost, money(d.cost))}`
141    + `${cell(d.colds, String(d.colds))}${cell(d.warms, String(d.warms ?? 0))}${cell(d.warmCost, money(d.warmCost ?? 0))}`
142    + `${cell(d.tools, String(d.tools))}${cell(d.agents, String(d.agents))}</tr>`)
143  const week = days.slice(-7)
144  const sum = (f: (d: Day) => number) => week.reduce((t, d) => t + f(d), 0)
145  const totals = `This week (last 7 days): ${sum(d => d.turns)} turns, ${money(sum(d => d.cost))} at API prices, ${sum(d => d.colds)} cold cache rebuilds, `
146    + `${sum(d => d.warms ?? 0)} keep-warm re-reads (${money(sum(d => d.warmCost ?? 0))}), ${sum(d => d.tools)} tool calls, ${sum(d => d.agents)} agents.`
147  return `<p class="strong">${esc(totals)}</p>${bars(days)}<p class="muted">Cost per day at API prices, oldest on the left. Only sessions g-line ran in are counted.</p>`
148    + `<div class="scroll"><table><thead><tr><th>Day</th><th class="num">Turns</th><th class="num">Cost</th><th class="num">Cold rebuilds</th>`
149    + `<th class="num">Keep-warm re-reads</th><th class="num">Re-read cost</th><th class="num">Tool calls</th><th class="num">Agents</th></tr></thead>`
150    + `<tbody>${rows.join('')}</tbody></table></div>`
151}
152
153function cacheSection(s: DashboardSnapshot): string {
154  const seg = cacheNext(s.payload, s.nowSeconds)
155  const model = s.payload.model?.display_name
156  const ctx = s.payload.context_window?.used_percentage
157  const facts = [model ? `Model ${modelName(model)}` : '', typeof ctx === 'number' ? `context ${pct(ctx)} used` : ''].filter(Boolean).join(', ')
158  if (!seg) return `<p class="muted">No prompt cache observed in this session yet.</p>${facts ? `<p class="muted">${esc(facts)}.</p>` : ''}`
159  const text = seg.forms[0] ?? ''
160  return `<p class="strong ${seg.tone === 'warn' ? 'warn-text' : ''}">${esc(text)}</p>`
161    + `<p class="muted">An estimate (the ~): from when the last request ran and the cache's lifetime, not the provider's own expiry.${facts ? ` ${esc(facts)}.` : ''}</p>`
162}
163
164function guardSection(g: DashboardGuard): string {
165  if (!g.rules.length && !g.keepWarm) return '<p class="muted">No guard rules.</p>'
166  const parts: string[] = []
167  if (g.simulated) parts.push('<p class="warn-text strong">Simulated readings: these are not the real figures.</p>')
168  if (!g.on) parts.push('<p class="muted">The guard is off.</p>')
169  if (g.rules.length) {
170    parts.push(`<ul class="rows">${g.rules.map(r => `<li class="${r.inForce ? 'warn' : ''}">${esc(r.inForce ? 'In force: ' : 'Not in force: ')}${esc(r.text)}</li>`).join('')}</ul>`)
171    parts.push(`<h3>What is in force now</h3><ul class="plain">${g.why.map(line => `<li>${esc(line)}</li>`).join('')}</ul>`)
172  }
173  if (g.keepWarm) parts.push(`<p class="muted">${esc(g.keepWarm)}</p>`)
174  for (const error of g.errors) parts.push(`<p class="warn-text">${esc(`Not read: ${error}`)}</p>`)
175  return parts.join('')
176}
177
178const CSS = `
179:root{--bg:#faf8f5;--fg:#1f1d1a;--muted:#6b665e;--card:#fff;--line:#e4dfd7;--accent:#c4602d;--ok:#2f7d4a;--warn:#a86a00;--bad:#b3261e;color-scheme:light dark}
180@media (prefers-color-scheme: dark){:root{--bg:#161513;--fg:#ece8e1;--muted:#a09a90;--card:#201e1b;--line:#37342f;--accent:#e08a5c;--ok:#6fcf8e;--warn:#e3b04b;--bad:#ff8a80}}
181*{box-sizing:border-box}
182body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
183main{max-width:860px;margin:0 auto;padding:24px 16px 48px}
184h1{font-size:1.5rem;margin:0 0 4px}
185h2{font-size:1.1rem;margin:32px 0 8px;padding-top:16px;border-top:1px solid var(--line)}
186h3{font-size:.95rem;margin:16px 0 4px}
187p{margin:6px 0}
188.muted{color:var(--muted);font-size:.9rem}
189.strong{font-weight:600}
190.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
191.card{display:flex;gap:12px;align-items:center;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px}
192.card .big{font-size:1.8rem;font-weight:700;min-width:3.4ch;color:var(--ok)}
193.card.warn .big{color:var(--warn)}.card.bad .big{color:var(--bad)}
194.card>div:last-child{flex:1;min-width:0}
195.meter{height:8px;background:var(--line);border-radius:4px;overflow:hidden;margin:6px 0}
196.meter span{display:block;height:100%;background:var(--ok)}.card.warn .meter span{background:var(--warn)}.card.bad .meter span{background:var(--bad)}
197.rows{list-style:none;margin:0;padding:0}
198.rows li{background:var(--card);border:1px solid var(--line);border-left-width:4px;border-radius:8px;padding:8px 12px;margin:6px 0;overflow-wrap:anywhere}
199.rows li.ok{border-left-color:var(--ok)}.rows li.warn{border-left-color:var(--warn)}
200.plain{margin:4px 0;padding-left:20px}
201.warn-text{color:var(--warn)}
202.chart{width:100%;max-width:700px;height:auto;display:block;margin:12px 0 4px}
203.bar{fill:var(--accent)}
204.tick{fill:var(--muted);font-size:9px}
205.scroll{overflow-x:auto}
206table{border-collapse:collapse;width:100%;font-size:.9rem;font-variant-numeric:tabular-nums}
207th,td{padding:6px 8px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap}
208th.num,td.num{text-align:right}
209footer{margin-top:40px;padding-top:16px;border-top:1px solid var(--line)}
210`
211
212/** The whole page. Pure: the same snapshot gives the same text. */
213export function dashboardHtml(s: DashboardSnapshot): string {
214  const at = new Date((s.nowSeconds + s.utcOffsetMinutes * 60) * 1000).toISOString()
215  const made = `${at.slice(0, 10)} ${at.slice(11, 16)} (${utcLabel(s.utcOffsetMinutes)})`
216  const version = s.version ? `g-line ${s.version}` : 'g-line (version unknown)'
217  return `<!doctype html>
218<html lang="en">
219<head>
220<meta charset="utf-8">
221<meta name="viewport" content="width=device-width, initial-scale=1">
222<meta name="color-scheme" content="light dark">
223<title>g-line dashboard</title>
224<style>${CSS}</style>
225</head>
226<body>
227<main>
228<h1>g-line dashboard</h1>
229<p class="muted">What g-line held when you asked. It does not update by itself.</p>
230<h2>Usage windows</h2>
231${windowsSection(s)}
232<h2>Sessions on this machine</h2>
233${sessionsSection(s)}
234<h2>History, last 14 days</h2>
235${historySection(s)}
236<h2>This session's cache</h2>
237${cacheSection(s)}
238<h2>Guard</h2>
239${guardSection(s.guard)}
240<footer class="muted">
241<p>${esc(`Generated ${made} by ${version}.`)}</p>
242<p>A snapshot: run /g-line dashboard again to refresh.</p>
243</footer>
244</main>
245</body>
246</html>
247`
248}
249
hooks/glance.ts 93 lines
1// What Claude reads when it calls g-line's `status` tool, which is off unless
2// turned on (`claude_reads: true`): a small JSON snapshot of the session's
3// reported context, the account's usage windows and the estimated prompt-cache
4// expiry. Observations only, with their scope and basis; never advice.
5//
6// Pure, like core.ts; the mod hands in the figures, the tests call it.
7
8import { num, pace, roundEta } from './core'
9import type { Payload } from './core'
10
11export const STATUS_TOOL = 'status'
12
13export const STATUS_DESCRIPTION = [
14  "Read this Claude Code session's reported context use and automatic-compaction headroom, the account's usage windows,",
15  'and the estimated prompt-cache expiry, as g-line observed them.',
16  'Use when the user asks about these figures or explicitly requests a capacity check.',
17  'This tool observes state; it changes no settings. Estimates may be stale and are not task budgets.',
18  'Do not poll, send keep-alive prompts, reduce requested work, or change model, effort or compaction settings',
19  'based on this result without the user\'s authorization.',
20].join(' ')
21
22export const STATUS_SCHEMA = {
23  type: 'object',
24  properties: { section: { type: 'string', enum: ['all', 'context', 'limits', 'cache'], description: 'Which part to read; all by default.' } },
25}
26
27export type StatusInput = {
28  p: Payload
29  /** Unix seconds now, and when the figures were last observed. */
30  now: number
31  observedAt?: number
32  /** Tokens at which auto-compact runs, when it is on; undefined when off or unknown. */
33  compactAt?: number
34  compactOn?: boolean
35  section?: string
36  disabled?: boolean
37}
38
39const iso = (seconds: number | undefined) => (seconds === undefined ? null : new Date(Math.floor(seconds) * 1000).toISOString())
40
41function window(p: Payload, kind: 'five_hour' | 'seven_day', now: number) {
42  const w = p.rate_limits?.[kind]
43  const used = num(w?.used_percentage)
44  if (used === undefined) return null
45  const state = pace(kind, w, now)
46  return {
47    used_percent: Math.round(used),
48    resets_at: iso(num(w?.resets_at)),
49    projected_limit_at: state?.kind === 'hot' ? iso(roundEta(state.eta, now)) : state?.kind === 'full' ? 'reached' : null,
50  }
51}
52
53/** The snapshot as a JSON string. Unknown stays null; nothing is guessed. */
54export function statusJson(s: StatusInput): string {
55  if (s.disabled) return JSON.stringify({ schema: 1, state: 'disabled', note: 'g-line is turned off in this session (/g-line on turns it back on).' })
56  const section = ['context', 'limits', 'cache'].includes(s.section ?? '') ? s.section : 'all'
57  const out: Record<string, unknown> = { schema: 1, captured_at: iso(s.now), observed_at: iso(s.observedAt) }
58  if (section === 'all' || section === 'context') {
59    const w = s.p.context_window
60    const used = num(w?.total_input_tokens)
61    out.context = {
62      scope: 'main_session',
63      used_tokens: used ?? null,
64      window_tokens: num(w?.context_window_size) ?? null,
65      used_percent: num(w?.used_percentage) === undefined ? null : Math.round(num(w?.used_percentage) ?? 0),
66      auto_compact: s.compactOn === false
67        ? { enabled: false }
68        : { enabled: s.compactAt !== undefined ? true : null, threshold_tokens: s.compactAt ?? null,
69            headroom_tokens: s.compactAt !== undefined && used !== undefined ? Math.max(0, s.compactAt - used) : null,
70            basis: 'engine_local_estimate' },
71    }
72  }
73  if (section === 'all' || section === 'limits') {
74    out.limits = {
75      scope: 'account',
76      five_hour: window(s.p, 'five_hour', s.now),
77      seven_day: window(s.p, 'seven_day', s.now),
78      projection_basis: 'rounded_linear_since_window_start',
79    }
80  }
81  if (section === 'all' || section === 'cache') {
82    const c = s.p.prompt_cache
83    const expires = num(c?.expires_at)
84    out.cache = c?.caching_observed
85      ? { scope: 'main_session_last_request',
86          state: c.compacted ? 'compacted' : c.warm && expires !== undefined && expires > s.now ? 'estimated_warm' : 'estimated_cold',
87          estimated_expires_at: iso(expires), lifetime: c.ttl ?? null, rebuild_tokens_if_cold: num(c.recache_tokens_if_cold) ?? null,
88          basis: 'configured_ttl_and_observed_request', ...(c.account_changed ? { account_changed: true } : {}) }
89      : null
90  }
91  return JSON.stringify(out)
92}
93
hooks/pulse.ts 316 lines
1// Pulse: a few AI-dev headlines from g-line's own static feed, for the time a
2// long turn keeps you waiting. Off unless turned on (`/g-line pulse`). When
3// on, the mod fetches one static JSON file now and then; it sends nothing
4// about you, and it never fetches while drawing.
5//
6// Pure: parsing and cleaning the feed. Feed text is untrusted, so every
7// string is stripped of escapes and control characters and cut to length
8// before it can reach the terminal.
9
10import type { PulseFeed, PulseItem } from '../types'
11
12export type { PulseFeed, PulseItem }
13
14export const PULSE_URL = 'https://raw.githubusercontent.com/lifeofgurpreet/g-line/pulse/pulse.json'
15/** How long a fetched feed is used before the next fetch. */
16export const PULSE_TTL_MS = 45 * 60_000
17/** How long a turn runs before the spinner starts showing headlines. */
18export const PULSE_AFTER_MS = 15_000
19/** How long each headline stays on the spinner and on Pulse's row. */
20export const PULSE_EVERY_MS = 8_000
21
22/** Pulse's 8-second beats per headline at each speed; paused never moves on. */
23export const PULSE_BEATS = { normal: 1, slow: 5, paused: 0 } as const
24
25/** Whether `mute` names the item's source: a case-insensitive match within it. */
26export function muted(item: PulseItem, mute: readonly string[]): boolean {
27  const source = item.source.toLowerCase()
28  return mute.some(word => source.includes(word.toLowerCase()))
29}
30/** The longest text the reader shows for one item. */
31export const TEXT_MAX = 600
32/** How many items the reader shows at once. */
33export const READER_PAGE = 5
34
35// CSI and OSC escape sequences, then any C0/C1 control, then bidi and zero-width controls.
36const ESCAPES = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-_]/g
37const CONTROLS = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/g
38// Variation selectors are dropped, so a symbol draws in its one-column text form.
39const SELECTORS = /[\ufe00-\ufe0f]/g
40// Feed text, unlike the mod's own, can hold emoji and East Asian wide characters (two columns) and combining marks (none).
41const WIDE = /\p{Emoji_Presentation}|[\u1100-\u115f\u2e80-\u303e\u3041-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{20000}-\u{3fffd}]/u
42const ZERO = /[\p{Mn}\p{Me}]/u
43
44const cell = (ch: string) => ZERO.test(ch) ? 0 : WIDE.test(ch) ? 2 : 1
45
46/** Display columns of feed text. */
47export function cells(text: string): number {
48  let n = 0
49  for (const ch of text) n += cell(ch)
50  return n
51}
52
53/** Text safe to draw: no escapes or control characters, one line, at most `max` columns. */
54export function clean(value: unknown, max: number): string {
55  if (typeof value !== 'string') return ''
56  const text = value.replace(ESCAPES, '').replace(CONTROLS, ' ').replace(SELECTORS, '').replace(/\s+/g, ' ').trim()
57  if (cells(text) <= max) return text
58  let kept = ''
59  let used = 0
60  for (const ch of text) {
61    used += cell(ch)
62    if (used > max - 1) break
63    kept += ch
64  }
65  return `${kept.trimEnd()}…`
66}
67
68/**
69 * Only plain https links, short enough to be a link and not a payload. A
70 * publisher's gift link carries a token and can run past 400 characters;
71 * Claude Code takes links up to 2048.
72 */
73export function safeUrl(value: unknown): string | undefined {
74  if (typeof value !== 'string' || value.length > 1000) return undefined
75  try {
76    const url = new URL(value)
77    if (url.protocol !== 'https:' || url.username || url.password) return undefined
78    return url.href
79  } catch {
80    return undefined
81  }
82}
83
84const count = (value: unknown): number | undefined =>
85  (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined)
86
87/** The feed's items, cleaned; anything malformed is left out. At most `limit`. */
88export function parseFeed(raw: string, fetchedAt: number, limit = 40): PulseFeed | undefined {
89  let data: unknown
90  try {
91    data = JSON.parse(raw)
92  } catch {
93    return undefined
94  }
95  if (!data || typeof data !== 'object') return undefined
96  const d = data as Record<string, unknown>
97  if (d.schema !== 1 || !Array.isArray(d.items)) return undefined
98  const items: PulseItem[] = []
99  for (const entry of d.items) {
100    if (!entry || typeof entry !== 'object') continue
101    const e = entry as Record<string, unknown>
102    const title = clean(e.title, 100)
103    const url = safeUrl(e.url)
104    const source = clean(e.source, 28)
105    if (!title || !url || !source) continue
106    const text = clean(e.text, TEXT_MAX)
107    const likes = count(e.likes)
108    const points = count(e.points)
109    const author = clean(e.author_name, 40)
110    const story = clean(e.story, 200)
111    const via = clean(e.via, 28)
112    const discussion = safeUrl(e.discussion)
113    items.push({ title, url, source, at: clean(e.published_at, 32) || undefined,
114      ...(text && text !== title ? { text } : {}), ...(likes !== undefined ? { likes } : {}), ...(author ? { author } : {}),
115      ...(story ? { story } : {}), ...(via ? { via } : {}), ...(points !== undefined ? { points } : {}),
116      ...(discussion ? { discussion } : {}) })
117    if (items.length >= limit) break
118  }
119  return { fetchedAt, generatedAt: clean(d.generated_at, 32) || undefined, items }
120}
121
122/** An X post leads with its author and age: `𝕏 @claudeai · 40m`, `· 3h`, `· 2d`. Other items: nothing. */
123export function xLead(item: PulseItem, nowMs?: number): string {
124  if (!item.source.startsWith('𝕏 @')) return ''
125  const at = item.at ? Date.parse(item.at) : Number.NaN
126  if (nowMs === undefined || !Number.isFinite(at)) return item.source
127  const minutes = Math.max(1, Math.floor((nowMs - at) / 60_000))
128  const age = minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / 1440)}d`
129  return `${item.source} · ${age}`
130}
131
132/** The spinner's headline for `item` `elapsedMs` into a turn, cut to `room` columns, or nothing yet. */
133export function tickerText(item: PulseItem | undefined, elapsedMs: number, room: number, nowMs?: number): string {
134  if (!item || elapsedMs < PULSE_AFTER_MS || room < 24) return ''
135  // A headline cut to a stub says nothing: drop the source before the title, and skip it if still too narrow.
136  const lead = xLead(item, nowMs)
137  if (lead && room - cells(lead) - 2 >= 24) return `${lead}: ${clean(item.title, room - cells(lead) - 2)}`
138  if (lead) return clean(item.title, room)
139  const tail = ` (${item.source})`
140  if (room - cells(tail) >= 24) return `${clean(item.title, room - cells(tail))}${tail}`
141  return clean(item.title, room)
142}
143
144// ------------------------------------------------------------- the cycle
145//
146// The rules, as the README states them: the row moves every 8 s (slow: 40 s);
147// headlines never shown come first, in the feed's order; a shown headline
148// rests 30 minutes before it can come back, and shows at most 3 times a day;
149// with every headline resting the row holds still; the same headline never
150// shows twice in a row, a feed refresh included. Every session on the
151// machine shares the count, so two sessions don't repeat each other.
152
153/** How long a shown headline rests before it can come back. */
154export const PULSE_REST_MS = 30 * 60_000
155/** How many times a day a headline shows. */
156export const PULSE_MAX_SHOWS = 3
157/** How long a headline's count is kept. */
158export const PULSE_FORGET_MS = 24 * 3_600_000
159
160/** Per link: how many times it was shown, and when last (ms). */
161export type Shown = Record<string, { n: number; at: number }>
162
163/** The counts younger than a day; anything malformed is dropped. */
164export function keptShown(raw: unknown, nowMs: number): Shown {
165  const out: Shown = {}
166  if (!raw || typeof raw !== 'object') return out
167  for (const [url, value] of Object.entries(raw as Record<string, unknown>)) {
168    const r = value as { n?: unknown; at?: unknown } | null
169    if (r && typeof r.n === 'number' && typeof r.at === 'number' && nowMs - r.at < PULSE_FORGET_MS) out[url] = { n: r.n, at: r.at }
170  }
171  return out
172}
173
174/** Two counts merged: the larger count and the later time of each link (another session may have shown it too). */
175export function mergedShown(a: Shown, b: Shown): Shown {
176  const out: Shown = { ...a }
177  for (const [url, s] of Object.entries(b)) {
178    const was = out[url]
179    out[url] = was ? { n: Math.max(was.n, s.n), at: Math.max(was.at, s.at) } : s
180  }
181  return out
182}
183
184/**
185 * The headline to move to after `current`, or nothing to hold still: one
186 * never shown first, in the feed's order; else the one shown longest ago
187 * that has rested and has shows left. Never `current` itself.
188 */
189export function pickNext(items: readonly PulseItem[], shown: Shown, current: string | null | undefined, nowMs: number): PulseItem | undefined {
190  const others = items.filter(item => item.url !== current)
191  const fresh = others.find(item => !shown[item.url])
192  if (fresh) return fresh
193  return others
194    .filter(item => {
195      const s = shown[item.url]
196      return s !== undefined && s.n < PULSE_MAX_SHOWS && nowMs - s.at >= PULSE_REST_MS
197    })
198    .sort((a, b) => (shown[a.url]?.at ?? 0) - (shown[b.url]?.at ?? 0))[0]
199}
200
201/**
202 * The headline shown now: `current` while the feed still has it; else the
203 * next by the rules; else, every one resting, the one shown longest ago.
204 */
205export function itemNow(items: readonly PulseItem[], shown: Shown, current: string | null | undefined, nowMs: number): PulseItem | undefined {
206  const held = items.find(item => item.url === current)
207  if (held) return held
208  return pickNext(items, shown, current, nowMs)
209    ?? [...items].sort((a, b) => (shown[a.url]?.at ?? 0) - (shown[b.url]?.at ?? 0))[0]
210}
211
212/** `shown` with one more show of `url` at `nowMs`. */
213export function withShow(shown: Shown, url: string, nowMs: number): Shown {
214  return { ...shown, [url]: { n: (shown[url]?.n ?? 0) + 1, at: nowMs } }
215}
216
217// ------------------------------------------------------------- the links
218
219/** The variables Claude Code decides links by. */
220export type TermEnv = Partial<Record<'FORCE_HYPERLINK' | 'NETLIFY' | 'CI' | 'TEAMCITY_VERSION' | 'WT_SESSION' | 'TERM_PROGRAM'
221  | 'TERM_PROGRAM_VERSION' | 'VTE_VERSION' | 'TERM' | 'TERMINAL_EMULATOR' | 'TMUX' | 'LC_TERMINAL', string>>
222
223function version(text: string | undefined): { major: number; minor: number } {
224  if (text && /^\d{3,4}$/.test(text)) {
225    const m = /(\d{1,2})(\d{2})/.exec(text)
226    return { major: 0, minor: Number(m?.[1]) }
227  }
228  const [major = Number.NaN, minor = Number.NaN] = (text ?? '').split('.').map(part => Number.parseInt(part, 10))
229  return { major, minor }
230}
231
232const LINK_TERMINALS = ['ghostty', 'Hyper', 'kitty', 'alacritty', 'iTerm.app', 'iTerm2', 'WarpTerminal']
233
234/**
235 * Whether Claude Code draws a `Link` as an OSC 8 link, by its own rule
236 * (2.1.304): FORCE_HYPERLINK first, then the terminals it recognises. Where
237 * it doesn't, it prints the link's whole address after the text, so Pulse's
238 * row draws its headline as plain text there. A terminal Claude Code doesn't
239 * recognise (herdr, Zellij, a session reached over SSH) gets links with
240 * `FORCE_HYPERLINK=1` set where Claude Code starts.
241 */
242export function linksDrawn(env: TermEnv): boolean {
243  const force = env.FORCE_HYPERLINK
244  if (force) return !(force.length > 0 && Number.parseInt(force, 10) === 0)
245  const program = env.TERM_PROGRAM
246  if (env.NETLIFY || env.WT_SESSION !== undefined) return true
247  const ci = !!env.CI || !!env.TEAMCITY_VERSION
248  if (!ci && program === 'WezTerm' && version(env.TERM_PROGRAM_VERSION).major >= 20200620) return true
249  if (!ci && program === 'vscode') {
250    const v = version(env.TERM_PROGRAM_VERSION)
251    if (v.major > 1 || (v.major === 1 && v.minor >= 72)) return true
252  }
253  if (!ci && env.VTE_VERSION && env.VTE_VERSION !== '0.50.0') {
254    const v = version(env.VTE_VERSION)
255    if (v.major > 0 || v.minor >= 50) return true
256  }
257  if (!ci && env.TERM === 'alacritty') return true
258  if (program && LINK_TERMINALS.includes(program)) return true
259  if (env.TERMINAL_EMULATOR === 'JetBrains-JediTerm') return true
260  if (program === 'tmux') {
261    const v = version(env.TERM_PROGRAM_VERSION)
262    if (v.major > 3 || (v.major === 3 && v.minor >= 4)) return true
263  }
264  if (env.LC_TERMINAL && LINK_TERMINALS.includes(env.LC_TERMINAL)) return true
265  return env.TERM?.includes('kitty') === true
266}
267
268/**
269 * Whether a browser can open for the person on this machine: never over
270 * SSH, and on Linux only with a display. A multiplexer's server started
271 * detached (herdr, tmux) carries no SSH variables, so there the display decides.
272 */
273export function opensHere(o: { os: string; ssh: boolean; display: boolean }): boolean {
274  if (o.ssh) return false
275  return o.os === 'Darwin' || o.display
276}
277
278/** An item's age: `40m`, `3h`, `2d`; nothing when the feed gave no time. */
279export function ageOf(item: PulseItem, nowMs: number): string {
280  const at = item.at ? Date.parse(item.at) : Number.NaN
281  if (!Number.isFinite(at)) return ''
282  const minutes = Math.max(1, Math.floor((nowMs - at) / 60_000))
283  return minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / 1440)}d`
284}
285
286/** `1.2k` likes and the like: a count a glance can take in. */
287export function countOf(n: number): string {
288  if (n < 1000) return String(n)
289  if (n < 10_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
290  return n < 1_000_000 ? `${Math.round(n / 1000)}k` : `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
291}
292
293/**
294 * Pulse's row under the prompt: who, how long ago, the headline, and a dim
295 * pointer to the reader when there is room. Each part is plain text: the
296 * headline is drawn as a link by the caller. Nothing when too narrow.
297 */
298export function pulseRow(item: PulseItem | undefined, room: number, nowMs: number):
299  { lead: string; title: string; tail: string } | undefined {
300  if (!item || room < 30) return undefined
301  const age = ageOf(item, nowMs)
302  const lead = `${item.source}${age ? ` · ${age}` : ''}`
303  const tailText = ' · /g-line news'
304  const tail = room - cells(lead) - 2 - cells(tailText) >= 40 ? tailText : ''
305  const titleRoom = room - cells(lead) - 2 - cells(tail)
306  if (titleRoom < 24) return { lead: '', title: clean(item.title, room), tail: '' }
307  return { lead, title: clean(item.title, titleRoom), tail }
308}
309
310/** The items the reader shows around the selected one: `[start, end)`, at most `size`. */
311export function pageOf(count: number, selected: number, size = READER_PAGE): [number, number] {
312  if (count <= size) return [0, count]
313  const start = Math.min(Math.max(0, selected - Math.floor(size / 2)), count - size)
314  return [start, start + size]
315}
316
hooks/guard.ts 1107 lines
1// The guard: rules the person writes in config.json that act when a usage
2// window runs low. Off by default: with no rules it does nothing at all.
3//
4// A rule names how much of a window is left (`left`: percent) and one thing to
5// do then: run the main conversation at a lower effort, run new subagents on a
6// cheaper model, or stop new prompts. It can be limited to some accounts (the
7// `account_command` reading) and to hours of the week in a time zone. Keep-warm
8// re-reads an idle conversation's prompt cache before it lapses.
9//
10// Pure: the mod hands in the figures, these decide. Missing figures decide
11// nothing: no reading, no account, an unknown time zone, and the rule waits.
12
13/** How far above its threshold a window must climb before an active rule lets go: readings are coarse. */
14export const CLEAR_MARGIN = 2
15
16export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
17export type Effort = (typeof EFFORTS)[number]
18
19export type WindowName = '5h' | 'week'
20
21export type Hours = { from: number; to: number; days: number[] }
22
23export type Rule = {
24  id: string
25  /** Percent of the window left at or below which the rule applies. */
26  left: number
27  window: WindowName
28  effort?: Effort
29  /** A model alias or id for new subagents (`sonnet`, `haiku`). */
30  agents?: string
31  stop?: boolean
32  /** A stop that also ends a running main-loop turn at its next step, once the rule starts mid-turn. */
33  endTurn?: boolean
34  /** The rule waits while the window resets within this many seconds. */
35  unlessResetWithin?: number
36  /** Lower-case parts of the account reading, any of which picks the account. */
37  accounts?: string[]
38  /** Lower-case parts of the account reading, any of which leaves the account out. */
39  exceptAccounts?: string[]
40  /** Names of account groups (`guard.groups`, or `other` for an account in none) the rule applies to. */
41  groups?: string[]
42  hours?: Hours
43  tz?: string
44  /** A paced weekly allowance in place of a cliff: the rule's steps come with how far ahead of pace the week is. */
45  pace?: Pace
46  /** The rule as written, for toasts. */
47  text: string
48}
49
50/**
51 * A paced weekly allowance. The week runs from seven days before the engine's reported
52 * weekly reset to the reset. `reserve` percent of it is kept back; `burst` points are
53 * free from the first minute; the rest opens up as the week goes by, office hours
54 * counting `officeWeight` times an ordinary hour. Ahead of that allowance by `tiers[0]`
55 * points (the used figure plus `buffer`), the conversation's effort is capped; by
56 * `tiers[1]`, new subagents run on a cheaper model; by `tiers[2]`, new prompts stop.
57 */
58export type Pace = {
59  reserve: number; burst: number; office?: Hours; officeWeight: number; tz?: string
60  buffer: number; tiers: [number, number, number]; effort: Effort
61  /** The model new subagents move to at the second step; none with `"agents": false` (the step changes nothing). */
62  agents?: string
63  /** The window paced: the week (the default) or the 5-hour window. */
64  window?: WindowName
65}
66
67const FIVE_HOURS_MS = 5 * 3_600_000
68const spanOf = (p: Pace) => (p.window === '5h' ? FIVE_HOURS_MS : WEEK_MS)
69/** The paced window in words. */
70const paceName = (w: WindowName | undefined) => (w === '5h' ? '5-hour window' : 'week')
71
72export type KeepWarm = {
73  /** `last`: only the session the person last typed in, per account; `all`: every idle session. */
74  sessions: 'last' | 'all'
75  /** Seconds idle before a re-read. */
76  after: number
77  /** Re-reads per idle stretch. */
78  max: number
79  /** Smallest cached conversation worth keeping, in tokens. */
80  minContext: number
81  /** No re-read once the 5-hour window has less than this percent left. */
82  minLeft: number
83  /** Re-reads per hour across every session on the machine. */
84  perHour: number
85}
86
87/** After a turn stops on a usage limit: one prompt after the reset, plus up to `jitter` seconds. */
88export type Resume = { text: string; jitter: number }
89
90/**
91 * A named bucket of accounts (`guard.groups`): an account belongs to the first
92 * group, in the order written, whose words its account line contains, and to
93 * `other` when it's in none. Rules name groups to apply to them all at once.
94 */
95export type Group = { name: string; words: string[]; keepFor: string }
96
97/** The group of accounts in no group the person wrote. */
98export const OTHER_GROUP = 'other'
99
100export type GuardConfig = {
101  on: boolean; rules: Rule[]; groups?: Group[]; keepWarm?: KeepWarm; resume?: Resume
102  /** Hold a typed prompt the guard refuses and send it when the guard lets it through. */
103  queue?: boolean
104  /** Near the weekly reset, say once that what's left is there to use: within `within` seconds, with `left` percent or more left. */
105  drain?: { within: number; left: number }
106  errors: string[]
107}
108
109export const NO_GUARD: GuardConfig = { on: true, rules: [], errors: [] }
110
111export const KEEP_WARM_DEFAULTS: KeepWarm = { sessions: 'last', after: 45 * 60, max: 2, minContext: 50_000, minLeft: 20, perHour: 6 }
112
113/** `45m`, `1h`, `90s`, `1h30m`, `3d`, or a number of minutes, in seconds. */
114export function seconds(value: unknown): number | undefined {
115  if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value * 60
116  if (typeof value !== 'string') return undefined
117  const text = value.trim().toLowerCase()
118  if (!/^(\d+(\.\d+)?\s*[dhms]\s*)+$/.test(text)) return undefined
119  let total = 0
120  for (const [, n, unit] of text.matchAll(/(\d+(?:\.\d+)?)\s*([dhms])/g)) total += Number(n) * (unit === 'd' ? 86_400 : unit === 'h' ? 3600 : unit === 'm' ? 60 : 1)
121  return Number.isFinite(total) ? total : undefined
122}
123
124/** `50k`, `1.2m`, `50000`, in tokens. */
125export function tokenCount(value: unknown): number | undefined {
126  if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value
127  if (typeof value !== 'string') return undefined
128  const m = /^(\d+(?:\.\d+)?)\s*([km]?)$/i.exec(value.trim())
129  if (!m) return undefined
130  const n = Number(m[1]) * (m[2]?.toLowerCase() === 'k' ? 1000 : m[2]?.toLowerCase() === 'm' ? 1_000_000 : 1)
131  return Number.isFinite(n) ? n : undefined
132}
133
134const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
135
136/** `09:00-17:00 mon-fri`, `22:00-06:00`, `9-17 sat,sun`: minutes of the day and the days (0 = Sunday). */
137export function parseHours(value: unknown): Hours | undefined {
138  if (typeof value !== 'string') return undefined
139  const m = /^\s*(\d{1,2})(?::(\d{2}))?\s*-\s*(\d{1,2})(?::(\d{2}))?\s*(.*)$/.exec(value.toLowerCase())
140  if (!m) return undefined
141  const from = Number(m[1]) * 60 + Number(m[2] ?? 0)
142  const to = Number(m[3]) * 60 + Number(m[4] ?? 0)
143  const minutesOk = (m[2] === undefined || Number(m[2]) < 60) && (m[4] === undefined || Number(m[4]) < 60)
144  if (!minutesOk || from > 24 * 60 || to > 24 * 60 || from === to) return undefined
145  const rest = (m[5] ?? '').trim()
146  if (!rest || rest === 'daily' || rest === 'every day') return { from, to, days: [0, 1, 2, 3, 4, 5, 6] }
147  const days = new Set<number>()
148  for (const part of rest.split(/[\s,]+/).filter(Boolean)) {
149    const range = /^([a-z]{3})[a-z]*(?:-([a-z]{3})[a-z]*)?$/.exec(part)
150    const a = range ? DAYS.indexOf(range[1] ?? '') : -1
151    const b = range?.[2] ? DAYS.indexOf(range[2]) : a
152    if (a < 0 || b < 0) return undefined
153    for (let d = a; ; d = (d + 1) % 7) {
154      days.add(d)
155      if (d === b) break
156    }
157  }
158  return { from, to, days: [...days].sort() }
159}
160
161/** The weekday (0 = Sunday) and minute of the day at `nowMs` in `tz` (the machine's zone when absent); nothing for an unknown zone. */
162export function localTime(nowMs: number, tz?: string, offsetMinutes?: number): { day: number; minute: number } | undefined {
163  if (!tz) {
164    const at = new Date(nowMs + (offsetMinutes ?? 0) * 60_000)
165    return { day: at.getUTCDay(), minute: at.getUTCHours() * 60 + at.getUTCMinutes() }
166  }
167  try {
168    const parts = new Intl.DateTimeFormat('en-US', { timeZone: tz, weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
169      .formatToParts(new Date(nowMs))
170    const get = (type: string) => parts.find(p => p.type === type)?.value ?? ''
171    const day = DAYS.indexOf(get('weekday').toLowerCase().slice(0, 3))
172    const minute = (Number(get('hour')) % 24) * 60 + Number(get('minute'))
173    return day < 0 || !Number.isFinite(minute) ? undefined : { day, minute }
174  } catch {
175    return undefined
176  }
177}
178
179/** Whether `at` falls in `hours`. A range past midnight counts from its starting day. */
180export function inHours(hours: Hours, at: { day: number; minute: number }): boolean {
181  if (hours.from < hours.to) return hours.days.includes(at.day) && at.minute >= hours.from && at.minute < hours.to
182  if (at.minute >= hours.from) return hours.days.includes(at.day)
183  return at.minute < hours.to && hours.days.includes((at.day + 6) % 7)
184}
185
186const word = (v: unknown) => (typeof v === 'string' ? v.trim().toLowerCase() : '')
187
188/** The `guard` block of config.json. Anything malformed is left out and said in `errors`. */
189export function parseGuard(raw: unknown): GuardConfig {
190  if (raw === false) return { ...NO_GUARD, on: false }
191  if (!raw || typeof raw !== 'object') return NO_GUARD
192  const r = raw as Record<string, unknown>
193  const errors: string[] = []
194  const rules: Rule[] = []
195  const groups = parseGroups(r.groups, errors)
196  const list = Array.isArray(r.rules) ? r.rules : []
197  list.forEach((entry, index) => {
198    const text = JSON.stringify(entry)
199    if (!entry || typeof entry !== 'object') {
200      errors.push(`rule ${index + 1} is not an object`)
201      return
202    }
203    const e = entry as Record<string, unknown>
204    const n = index + 1
205    // A rule with anything malformed is left out whole: a half-read rule would apply more widely than written.
206    const bad = (why: string) => {
207      errors.push(`rule ${n}: ${why}`)
208    }
209    const paced = e.pace !== undefined
210    const left = paced ? 0 : typeof e.left === 'number' ? e.left : Number.NaN
211    if (!paced && !(left > 0 && left <= 100)) return bad('"left" must be a percent from 1 to 100')
212    if (e.window !== undefined && !['5h', 'week'].includes(word(e.window))) return bad('"window" is "5h" or "week"')
213    if (paced && (e.left !== undefined || e.effort !== undefined || e.agents !== undefined || e.stop !== undefined)) {
214      return bad('a "pace" rule sets its own steps: leave out "left", "effort", "agents" and "stop"')
215    }
216    // A pace rule paces the week unless it names the 5-hour window.
217    const window: WindowName = paced ? (word(e.window) === '5h' ? '5h' : 'week') : word(e.window) === 'week' ? 'week' : '5h'
218    const rule: Rule = { id: `r${index}`, left, window, text }
219    if (paced) {
220      const pace = parsePace(e.pace, typeof e.tz === 'string' ? e.tz.trim() : undefined, n, errors)
221      if (!pace) return
222      rule.pace = window === '5h' ? { ...pace, window } : pace
223      rule.stop = true
224    }
225    if (e.effort !== undefined) {
226      if ((EFFORTS as readonly string[]).includes(word(e.effort))) rule.effort = word(e.effort) as Effort
227      else return bad(`"effort" is one of ${EFFORTS.join(', ')}`)
228    }
229    if (e.agents !== undefined) {
230      if (typeof e.agents === 'string' && /^[a-z0-9._[\]-]{2,80}$/i.test(e.agents.trim())) rule.agents = e.agents.trim()
231      else return bad('"agents" names a model, such as "sonnet"')
232    }
233    if (e.stop === true) rule.stop = true
234    if (e.end_turn !== undefined && typeof e.end_turn !== 'boolean') return bad('"end_turn" is true or false')
235    if (e.end_turn === true) {
236      if (rule.stop) rule.endTurn = true
237      else return bad('"end_turn" goes with "stop": true')
238    }
239    if (!rule.effort && !rule.agents && !rule.stop) return bad('it does nothing: give it "effort", "agents" or "stop": true')
240    if (e.unless_reset_within !== undefined) {
241      const s = seconds(e.unless_reset_within)
242      if (s === undefined) return bad('"unless_reset_within" is a time such as "1h"')
243      rule.unlessResetWithin = s
244    }
245    if (e.accounts !== undefined) {
246      const accounts = (Array.isArray(e.accounts) ? e.accounts : [e.accounts]).map(word).filter(Boolean)
247      if (!accounts.length) return bad('"accounts" lists parts of the account line, such as "team@"')
248      rule.accounts = accounts
249    }
250    if (e.except_accounts !== undefined) {
251      const except = (Array.isArray(e.except_accounts) ? e.except_accounts : [e.except_accounts]).map(word).filter(Boolean)
252      if (!except.length) return bad('"except_accounts" lists parts of the account line, such as "me@"')
253      rule.exceptAccounts = except
254    }
255    if (e.groups !== undefined || e.group !== undefined) {
256      const named = (Array.isArray(e.groups) ? e.groups : [e.groups ?? e.group]).map(word).filter(Boolean)
257      const unknown = named.filter(g => g !== OTHER_GROUP && !groups.some(x => x.name === g))
258      if (!named.length) return bad('"groups" names groups from "guard.groups", such as "team"')
259      if (unknown.length) return bad(`no group named ${unknown.map(g => `"${g}"`).join(', ')} in "guard.groups"`)
260      rule.groups = named
261    }
262    if (e.hours !== undefined) {
263      const hours = parseHours(e.hours)
264      if (!hours) return bad('"hours" is like "09:00-17:00 mon-fri"')
265      rule.hours = hours
266    }
267    if (e.tz !== undefined) {
268      if (typeof e.tz !== 'string' || !e.tz.trim() || !localTime(0, e.tz.trim())) return bad(`unknown time zone "${String(e.tz)}"`)
269      rule.tz = e.tz.trim()
270    }
271    rules.push(rule)
272  })
273  let keepWarm: KeepWarm | undefined
274  if (r.keep_warm === true) keepWarm = KEEP_WARM_DEFAULTS
275  else if (r.keep_warm && typeof r.keep_warm === 'object') {
276    const k = r.keep_warm as Record<string, unknown>
277    const after = seconds(k.after)
278    const max = typeof k.max === 'number' && k.max >= 0 ? Math.floor(k.max) : undefined
279    const minContext = tokenCount(k.min_context)
280    const minLeft = typeof k.min_left === 'number' && k.min_left >= 0 ? k.min_left : undefined
281    const perHour = typeof k.per_hour === 'number' && k.per_hour >= 0 ? Math.floor(k.per_hour) : undefined
282    keepWarm = {
283      sessions: k.sessions === 'all' ? 'all' : 'last',
284      // Under ten minutes would ping a busy session; past 55 the cache may already be gone.
285      after: after !== undefined ? Math.min(55 * 60, Math.max(10 * 60, after)) : KEEP_WARM_DEFAULTS.after,
286      max: Math.min(6, max ?? KEEP_WARM_DEFAULTS.max),
287      minContext: minContext ?? KEEP_WARM_DEFAULTS.minContext,
288      minLeft: minLeft ?? KEEP_WARM_DEFAULTS.minLeft,
289      perHour: perHour ?? KEEP_WARM_DEFAULTS.perHour,
290    }
291  }
292  let resume: Resume | undefined
293  if (r.resume === true) resume = { text: 'continue', jitter: 300 }
294  else if (r.resume && typeof r.resume === 'object') {
295    const o = r.resume as Record<string, unknown>
296    const text = typeof o.text === 'string' && o.text.trim() ? o.text.trim().slice(0, 500) : 'continue'
297    resume = { text, jitter: Math.min(1800, seconds(o.jitter) ?? 300) }
298  }
299  let drain: GuardConfig['drain']
300  if (r.drain === true) drain = { within: 48 * 3600, left: 20 }
301  else if (r.drain && typeof r.drain === 'object') {
302    const o = r.drain as Record<string, unknown>
303    const within = o.within === undefined ? 48 * 3600 : seconds(o.within)
304    const left = o.left === undefined ? 20 : typeof o.left === 'number' && o.left > 0 && o.left <= 100 ? o.left : undefined
305    if (within === undefined || within <= 0 || within > 7 * 86_400) errors.push('"drain": "within" is a time up to a week, such as "48h"')
306    else if (left === undefined) errors.push('"drain": "left" is a percent from 1 to 100')
307    else drain = { within, left }
308  } else if (r.drain !== undefined && r.drain !== false) errors.push('"drain" is true, or { "within": "48h", "left": 20 }')
309  return { on: r.on !== false, rules, ...(groups.length ? { groups } : {}), ...(keepWarm ? { keepWarm } : {}), ...(resume ? { resume } : {}),
310    ...(r.queue === true ? { queue: true } : {}), ...(drain ? { drain } : {}), errors }
311}
312
313/** `guard.groups`: `{ "team": ["team@", "ops@"], "people": { "accounts": ["sam@"], "for": "its owner" } }`. */
314function parseGroups(raw: unknown, errors: string[]): Group[] {
315  if (raw === undefined) return []
316  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
317    errors.push('"groups" maps a group name to the parts of account lines in it, such as { "team": ["team@"] }')
318    return []
319  }
320  const groups: Group[] = []
321  for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
322    const name = word(key)
323    if (!/^[a-z0-9][a-z0-9._-]{0,30}$/.test(name) || name === OTHER_GROUP) {
324      errors.push(`group "${key}": a name of letters, digits, dots or dashes, and not "${OTHER_GROUP}" (that's every account in no group)`)
325      continue
326    }
327    const o = Array.isArray(value) || typeof value === 'string' ? { accounts: value } : (value as Record<string, unknown> | null) ?? {}
328    const list = (Array.isArray(o.accounts) ? o.accounts : [o.accounts]).map(word).filter(Boolean)
329    if (!list.length) {
330      errors.push(`group "${key}" lists no accounts`)
331      continue
332    }
333    const keepFor = typeof o.for === 'string' && o.for.trim() ? o.for.trim().slice(0, 60) : `the ${name} group`
334    groups.push({ name, words: list, keepFor })
335  }
336  return groups
337}
338
339/** The group an account line belongs to; undefined with no reading. */
340export function groupOf(groups: readonly Group[] | undefined, account: string | null | undefined): Group | undefined {
341  const line = account?.toLowerCase()
342  if (!line) return undefined
343  return (groups ?? []).find(g => g.words.some(part => line.includes(part))) ?? { name: OTHER_GROUP, words: [], keepFor: 'others' }
344}
345
346// ------------------------------------------------------------------- pace
347
348const WEEK_MS = 7 * 86_400_000
349const DAY_MS = 86_400_000
350const PACE_KEYS = ['reserve', 'burst', 'office', 'office_weight', 'tz', 'buffer', 'tiers', 'effort', 'agents']
351
352/** `pace` in a rule: `{ "reserve": 10, "burst": 8, "office": "09:00-18:00 mon-fri", "office_weight": 4, "tz": "Asia/Kuala_Lumpur" }`. */
353function parsePace(raw: unknown, ruleTz: string | undefined, n: number, errors: string[]): Pace | undefined {
354  const fail = (why: string) => {
355    errors.push(`rule ${n}: "pace" ${why}`)
356    return undefined
357  }
358  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return fail('is an object, such as { "reserve": 10, "burst": 8 }')
359  const o = raw as Record<string, unknown>
360  const unknown = Object.keys(o).filter(k => !PACE_KEYS.includes(k))
361  if (unknown.length) return fail(`doesn't know ${unknown.map(k => `"${k}"`).join(', ')} (it takes ${PACE_KEYS.join(', ')})`)
362  const num = (key: string, fallback: number, lo: number, hi: number): number | undefined => {
363    const v = o[key]
364    if (v === undefined) return fallback
365    return typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi ? v : undefined
366  }
367  const reserve = num('reserve', 10, 0, 50)
368  if (reserve === undefined) return fail('"reserve" is a percent from 0 to 50 of the week kept back')
369  const burst = num('burst', 8, 0, 100 - reserve)
370  if (burst === undefined) return fail(`"burst" is points of the week free from the start, from 0 to ${100 - reserve} (100 less the reserve)`)
371  const buffer = num('buffer', 2, 0, 20)
372  if (buffer === undefined) return fail('"buffer" is a few points of slack for a coarse reading, from 0 to 20')
373  let office: Hours | undefined
374  if (o.office !== undefined) {
375    office = parseHours(o.office)
376    if (!office) return fail('"office" is like "09:00-18:00 mon-fri"')
377  }
378  const officeWeight = num('office_weight', office ? 4 : 1, 0.1, 20)
379  if (officeWeight === undefined) return fail('"office_weight" is how many times an office hour counts, from 0.1 to 20')
380  let tiers: [number, number, number] = [0, 3, 6]
381  if (o.tiers !== undefined) {
382    const t = o.tiers
383    const ok = Array.isArray(t) && t.length === 3 && t.every(x => typeof x === 'number' && Number.isFinite(x) && x >= -20 && x <= 50)
384      && (t as number[])[0]! < (t as number[])[1]! && (t as number[])[1]! < (t as number[])[2]!
385    if (!ok) return fail('"tiers" is three rising points ahead of pace, such as [0, 3, 6]: effort, cheaper agents, stop')
386    tiers = [...(t as [number, number, number])]
387  }
388  const effort = o.effort === undefined ? 'medium' : word(o.effort)
389  if (!(EFFORTS as readonly string[]).includes(effort)) return fail(`"effort" is one of ${EFFORTS.join(', ')}`)
390  // `false`: models are never changed, and the second step only marks the way to the stop.
391  const agents = o.agents === false ? undefined : o.agents === undefined ? 'sonnet' : typeof o.agents === 'string' ? o.agents.trim() : ''
392  if (agents !== undefined && (!/^[a-z0-9._[\]-]{2,80}$/i.test(agents) || !rank(agents))) return fail('"agents" names a model family, such as "sonnet" or "haiku", or is false')
393  const tz = o.tz === undefined ? ruleTz || undefined : typeof o.tz === 'string' ? o.tz.trim() : ''
394  if (tz !== undefined && (!tz || !localTime(0, tz))) return fail(`has an unknown time zone "${String(o.tz)}"`)
395  return { reserve, burst, ...(office ? { office } : {}), officeWeight, ...(tz ? { tz } : {}), buffer, tiers, effort: effort as Effort, ...(agents ? { agents } : {}) }
396}
397
398const zoneFormats = new Map<string, Intl.DateTimeFormat>()
399
400/** The zone's offset from UTC at `ms`, in ms: the named zone's (daylight saving included), else the machine's fixed `fallbackMinutes`. */
401function zoneOffsetMs(tz: string | undefined, ms: number, fallbackMinutes: number): number | undefined {
402  if (!tz) return fallbackMinutes * 60_000
403  try {
404    let f = zoneFormats.get(tz)
405    if (!f) {
406      f = new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' })
407      zoneFormats.set(tz, f)
408    }
409    const parts = f.formatToParts(new Date(ms))
410    const get = (type: string) => Number(parts.find(p => p.type === type)?.value)
411    const asUtc = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour') % 24, get('minute'), get('second'))
412    return Number.isFinite(asUtc) ? asUtc - Math.floor(ms / 1000) * 1000 : undefined
413  } catch {
414    return undefined
415  }
416}
417
418/** The week of a pace rule: its office spans inside it, in UTC ms. */
419export type PaceCalendar = { startMs: number; endMs: number; spans: [number, number][]; officeMs: number; weight: number }
420
421/** The week ending at `resetMs`, with its office hours (in the rule's zone, daylight saving included) laid out once. */
422export function paceCalendar(p: Pace, resetMs: number, offsetMinutes = 0): PaceCalendar | undefined {
423  const startMs = resetMs - spanOf(p)
424  const spans: [number, number][] = []
425  if (p.office) {
426    const off = (ms: number) => zoneOffsetMs(p.tz, ms, offsetMinutes)
427    const at = off(startMs)
428    if (at === undefined) return undefined
429    const first = new Date(startMs + at)
430    const [y, m, d] = [first.getUTCFullYear(), first.getUTCMonth(), first.getUTCDate()]
431    // A wall-clock minute of a calendar day (`dayMs` is that day's midnight read as UTC) as an instant.
432    const instant = (dayMs: number, minute: number) => {
433      const guess = dayMs + minute * 60_000
434      const a = off(guess) ?? 0
435      return guess - (off(guess - a) ?? a)
436    }
437    for (let i = -1; i <= 8; i++) {
438      const dayMs = Date.UTC(y, m, d + i)
439      if (!p.office.days.includes(new Date(dayMs).getUTCDay())) continue
440      const from = instant(dayMs, p.office.from)
441      const to = instant(p.office.from < p.office.to ? dayMs : dayMs + DAY_MS, p.office.to)
442      const lo = Math.max(from, startMs)
443      const hi = Math.min(to, resetMs)
444      if (hi > lo) spans.push([lo, hi])
445    }
446  }
447  return { startMs, endMs: resetMs, spans, officeMs: spans.reduce((sum, [a, b]) => sum + (b - a), 0), weight: p.officeWeight }
448}
449
450/** The weighted share of the week gone by `nowMs`, 0 to 1: an office hour counts `weight` times an ordinary one. */
451export function paceFraction(cal: PaceCalendar, nowMs: number): number {
452  const t = Math.min(cal.endMs, Math.max(cal.startMs, nowMs))
453  const extra = cal.weight - 1
454  const office = cal.spans.reduce((sum, [a, b]) => sum + Math.max(0, Math.min(b, t) - a), 0)
455  return ((t - cal.startMs) + extra * office) / ((cal.endMs - cal.startMs) + extra * cal.officeMs)
456}
457
458/** What a week of the rule may have used by `nowMs`, in percent: `burst`, rising to `100 - reserve` by the reset. */
459export function paceAllowance(p: Pace, cal: PaceCalendar, nowMs: number): number {
460  const room = 100 - p.reserve
461  return Math.min(room, p.burst + (room - p.burst) * paceFraction(cal, nowMs))
462}
463
464/** Where a pace rule stands: the week used, what's allowed by now, how far ahead, and the step that means. */
465export type PaceNow = {
466  used: number; allowed: number; ahead: number
467  /** 0 on pace; 1 effort capped; 2 also cheaper new agents; 3 also stop. */
468  tier: 0 | 1 | 2 | 3
469  /** Stopped because the week's reserve itself is near, not only because of the pace. */
470  hard: boolean
471  reserve: number
472  office: boolean
473  /** The window paced. */
474  window?: WindowName
475  /** About when this step lets go on its own (ms), for a step in force. */
476  liftsAt?: number
477}
478
479/** What a pace rule remembers, so a step lets go only after CLEAR_MARGIN points, and only in the window and for the account it began in. */
480export type PaceMemory = { tier: number; hard: boolean; reset: number | null; account: string }
481
482const calendars = new WeakMap<Pace, { key: string; cal: PaceCalendar | undefined }>()
483
484function calendarOf(p: Pace, resetMs: number, offsetMinutes: number): PaceCalendar | undefined {
485  const key = `${resetMs}|${p.tz ? '' : offsetMinutes}`
486  const kept = calendars.get(p)
487  if (kept?.key === key) return kept.cal
488  const cal = paceCalendar(p, resetMs, offsetMinutes)
489  calendars.set(p, { key, cal })
490  return cal
491}
492
493/** The pace rule's standing against the weekly window now; nothing when the reading or the zone can't say. */
494export function paceRead(p: Pace, w: { left: number; resetsAt: number }, nowMs: number, offsetMinutes = 0, was?: { tier: number; hard: boolean }): PaceNow | undefined {
495  if (!Number.isFinite(w.left) || !Number.isFinite(w.resetsAt)) return undefined
496  const resetMs = w.resetsAt * 1000
497  if (resetMs <= nowMs || resetMs - nowMs > spanOf(p) + 3_600_000) return undefined
498  const cal = calendarOf(p, resetMs, offsetMinutes)
499  if (!cal) return undefined
500  const used = Math.min(100, Math.max(0, 100 - w.left))
501  const allowed = paceAllowance(p, cal, nowMs)
502  const ahead = used + p.buffer - allowed
503  let tier = 0
504  for (let i = 0; i < 3; i++) if (ahead >= (p.tiers[i] ?? Infinity) - ((was?.tier ?? 0) >= i + 1 ? CLEAR_MARGIN : 0)) tier = i + 1
505  const hard = w.left <= p.reserve + p.buffer + (was?.hard ? CLEAR_MARGIN : 0)
506  if (hard) tier = 3
507  const now: PaceNow = { used, allowed, ahead, tier: tier as PaceNow['tier'], hard, reserve: p.reserve,
508    office: cal.spans.some(([a, b]) => nowMs >= a && nowMs < b), ...(p.window === '5h' ? { window: p.window } : {}) }
509  if (tier > 0) {
510    if (hard) now.liftsAt = resetMs
511    else {
512      // The allowance only rises: the first moment it climbs far enough for this step to let go.
513      const target = used + p.buffer - ((p.tiers[tier - 1] ?? 0) - CLEAR_MARGIN)
514      let lo = nowMs
515      let hi = resetMs
516      for (let i = 0; i < 40 && hi - lo > 1000; i++) {
517        const mid = (lo + hi) / 2
518        if (paceAllowance(p, cal, mid) >= target) hi = mid
519        else lo = mid
520      }
521      now.liftsAt = Math.ceil(hi)
522    }
523  }
524  return now
525}
526
527/** The standing in words: `ahead of pace: 62% of the week used, 48% allowed by now`. */
528export function paceWords(n: PaceNow): string {
529  return n.hard
530    ? `${pct(100 - n.used)} of the ${paceName(n.window)} is left, inside the ${n.reserve}% g-line keeps back`
531    : `ahead of pace: ${pct(n.used)} of the ${paceName(n.window)} used, ${pct(n.allowed)} allowed by now`
532}
533
534/** What the guard reads. `left` is percent of the window left; `resetsAt` in seconds. */
535export type Facts = {
536  nowMs: number
537  windows: Partial<Record<WindowName, { left: number; resetsAt?: number }>>
538  /** The `account_command` reading; undefined when unknown. */
539  account?: string | null
540  /** The machine's offset from UTC, for rules with no `tz`. */
541  offsetMinutes?: number
542}
543
544/** Rules in force, by id, each with the window's reset it began in (a new window starts over). */
545export type Active = Record<string, number | null>
546
547export type Verdict = {
548  active: Active
549  rules: Rule[]
550  /** Where each pace rule in force stands, by rule id. */
551  pace?: Record<string, PaceNow>
552  /** What each pace rule in force remembers (hand it back to `evaluate`). */
553  memory?: Record<string, PaceMemory>
554  effort?: Effort
555  agents?: string
556  stop?: Held
557  /** The strictest stop in force that also ends a running turn. */
558  end?: Held
559}
560
561/** A stop in force: its rule, the window and what's left, and the account's group when the rule names groups. */
562export type Held = { rule: Rule; window: WindowName; left: number; resetsAt?: number; group?: Group; pace?: PaceNow }
563
564/**
565 * The rules in force now. A rule starts when its window's percent left falls to
566 * its threshold and every condition it names holds; once in force it lets go only
567 * when the window climbs CLEAR_MARGIN points past the threshold, the window
568 * resets, or a condition stops holding (the account changed, the hours ended).
569 */
570export function evaluate(guard: GuardConfig, facts: Facts, before: Active = {}, memory: Record<string, PaceMemory> = {}): Verdict {
571  const active: Active = {}
572  const rules: Rule[] = []
573  const paces: Record<string, PaceNow> = {}
574  const kept: Record<string, PaceMemory> = {}
575  if (!guard.on) return { active, rules }
576  for (const rule of guard.rules) {
577    const w = facts.windows[rule.window]
578    if (!w || !Number.isFinite(w.left)) continue
579    // A reading from before the window's reset says nothing about the new window.
580    if (w.resetsAt !== undefined && w.resetsAt * 1000 <= facts.nowMs) continue
581    const resets = w.resetsAt ?? null
582    let pace: PaceNow | undefined
583    if (rule.pace) {
584      // The week is anchored on the engine's reset: with none, there is no week to pace.
585      if (w.resetsAt === undefined) continue
586      // A step's memory belongs to the account and the window it began in; any other starts afresh.
587      const mem = memory[rule.id]
588      const same = mem && mem.reset === resets && mem.account === accountKey(facts.account)
589      pace = paceRead(rule.pace, { left: w.left, resetsAt: w.resetsAt }, facts.nowMs, facts.offsetMinutes, same ? mem : undefined)
590      if (!pace || pace.tier === 0) continue
591    } else {
592      const was = Object.prototype.hasOwnProperty.call(before, rule.id) && before[rule.id] === resets
593      if (w.left > rule.left + (was ? CLEAR_MARGIN : 0)) continue
594    }
595    if (rule.unlessResetWithin !== undefined) {
596      if (w.resetsAt === undefined || w.resetsAt * 1000 - facts.nowMs <= rule.unlessResetWithin * 1000) continue
597    }
598    if (!inScope(guard, rule, facts)) continue
599    active[rule.id] = resets
600    rules.push(rule)
601    if (pace) {
602      paces[rule.id] = pace
603      kept[rule.id] = { tier: pace.tier, hard: pace.hard, reset: resets, account: accountKey(facts.account) }
604    }
605  }
606  const verdict: Verdict = { active, rules, ...(Object.keys(paces).length ? { pace: paces, memory: kept } : {}) }
607  const group = groupOf(guard.groups, facts.account)
608  for (const rule of rules) {
609    const pace = paces[rule.id]
610    // A pace rule's steps come one at a time with how far ahead of pace the week is.
611    const effort = pace ? (pace.tier >= 1 ? rule.pace?.effort : undefined) : rule.effort
612    const agents = pace ? (pace.tier >= 2 ? rule.pace?.agents : undefined) : rule.agents
613    const stops = pace ? pace.tier >= 3 : rule.stop
614    if (effort && (!verdict.effort || EFFORTS.indexOf(effort) < EFFORTS.indexOf(verdict.effort))) verdict.effort = effort
615    // A model the guard can't rank must not mask a cheaper one it can.
616    if (agents && (!verdict.agents || (rank(agents) > 0 && (rank(verdict.agents) === 0 || rank(agents) < rank(verdict.agents))))) verdict.agents = agents
617    const w = facts.windows[rule.window]
618    const held = w ? { rule, window: rule.window, left: w.left, resetsAt: w.resetsAt, ...(rule.groups && group ? { group } : {}), ...(pace ? { pace } : {}) } : undefined
619    if (stops && held && binds(rule, held.left, verdict.stop)) verdict.stop = held
620    if (stops && rule.endTurn && held && binds(rule, held.left, verdict.end)) verdict.end = held
621  }
622  return verdict
623}
624
625/** Whether the account, group and hours a rule names hold now. */
626export function inScope(guard: GuardConfig, rule: Rule, facts: Facts): boolean {
627  if (rule.accounts) {
628    const account = facts.account?.toLowerCase()
629    if (!account || !rule.accounts.some(part => account.includes(part))) return false
630  }
631  if (rule.exceptAccounts) {
632    const account = facts.account?.toLowerCase()
633    if (!account || rule.exceptAccounts.some(part => account.includes(part))) return false
634  }
635  if (rule.groups) {
636    const g = groupOf(guard.groups, facts.account)
637    if (!g || !rule.groups.includes(g.name)) return false
638  }
639  if (rule.hours) {
640    const at = localTime(facts.nowMs, rule.tz, facts.offsetMinutes)
641    if (!at || !inHours(rule.hours, at)) return false
642  }
643  return true
644}
645
646/**
647 * Whether a stop rule gives the reason over the one chosen so far: the window
648 * with less left; on the same reading, a team-seat rule, then the higher
649 * threshold (the rule that started first), so the reason doesn't change from
650 * one prompt to the next as stricter rules join it.
651 */
652function binds(rule: Rule, left: number, chosen: Verdict['stop']): boolean {
653  if (!chosen) return true
654  if (left !== chosen.left) return left < chosen.left
655  const team = namesAccounts(rule)
656  if (team !== namesAccounts(chosen.rule)) return team
657  return rule.left > chosen.rule.left
658}
659
660/** Whether a rule depends on the account reading. */
661export const namesAccounts = (rule: Rule) => Boolean(rule.accounts || rule.exceptAccounts || rule.groups)
662
663/** A model family's price rank: haiku 1, sonnet 2, opus 3, fable or mythos 4; 0 unknown. */
664export function rank(model: string | undefined): number {
665  const m = (model ?? '').toLowerCase()
666  if (m.includes('haiku')) return 1
667  if (m.includes('sonnet')) return 2
668  if (m.includes('opus')) return 3
669  if (m.includes('fable') || m.includes('mythos')) return 4
670  return 0
671}
672
673/** The lower of the request's effort and the guard's; nothing to change when it is already as low, or not a named level. */
674export function cappedEffort(current: unknown, cap: Effort | undefined): Effort | undefined {
675  if (!cap || typeof current !== 'string') return undefined
676  const at = EFFORTS.indexOf(current as Effort)
677  return at > EFFORTS.indexOf(cap) ? cap : undefined
678}
679
680/**
681 * Whether a lower effort keeps the prompt cache: on Opus 5.5, Sonnet 5.5,
682 * Haiku 5.5 and Fable 5.1 through the Claude API (an API key or a subscription),
683 * as Claude Code's prompt-caching page says. Elsewhere a change of effort reads
684 * the whole conversation again, so the guard waits for the cache to lapse.
685 */
686export function effortKeepsCache(model: string | undefined, env: { bedrock?: boolean; vertex?: boolean; foundry?: boolean; noBetas?: boolean }): boolean {
687  if (env.bedrock || env.vertex || env.foundry || env.noBetas) return false
688  return /opus-5-5|sonnet-5-5|haiku-5-5|fable-5-1|mythos-5-1/.test((model ?? '').toLowerCase())
689}
690
691/**
692 * The model a new subagent runs on under the guard, or nothing to leave it.
693 * Only ever cheaper: an agent that names, or is known to run on, a model at or
694 * below the guard's keeps it. One whose model isn't known (an agent type whose
695 * own definition picks it) is left alone, since it may already be cheaper. A
696 * fork inherits the parent and can't change.
697 */
698export function agentModel(target: string | undefined, spawn: { model?: string; fork: boolean; known?: string }): string | undefined {
699  if (!target || spawn.fork) return undefined
700  const want = rank(target)
701  if (!want) return undefined
702  const now = rank(spawn.model ?? spawn.known)
703  return now > want ? target : undefined
704}
705
706/**
707 * What Claude Code's own agent types run on when the Agent call names no
708 * model: the parent's (`inherit`) or a model of their own. Types not listed
709 * are learned from what they ran on, and left alone until then.
710 */
711export const AGENT_TYPE_MODELS: Record<string, string> = {
712  'general-purpose': 'inherit', Plan: 'inherit', Explore: 'haiku', 'claude-code-guide': 'haiku', 'statusline-setup': 'sonnet',
713}
714
715const pct = (n: number) => `${Math.max(0, Math.round(n))}%`
716const NAMES: Record<WindowName, string> = { '5h': '5-hour', week: 'weekly' }
717
718/** When a window resets, in the caller's zone: `08:20, in 1h 5m`, or `Tue 13:00, in 3d 4h`. */
719function resetWords(resetsAt: number | undefined, nowMs: number, offsetMinutes: number): string {
720  if (resetsAt === undefined) return ''
721  const left = Math.max(0, Math.round(resetsAt - nowMs / 1000))
722  const d = Math.floor(left / 86_400)
723  const h = Math.floor((left % 86_400) / 3600)
724  const m = Math.floor((left % 3600) / 60)
725  const at = new Date(resetsAt * 1000 + offsetMinutes * 60_000)
726  const hm = `${String(at.getUTCHours()).padStart(2, '0')}:${String(at.getUTCMinutes()).padStart(2, '0')}`
727  const day = left >= 20 * 3600 ? `${(DAYS[at.getUTCDay()] ?? '').replace(/^./, c => c.toUpperCase())} ` : ''
728  const span = d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m`
729  return `${day}${hm}, in ${span}`
730}
731
732/** A rule's hours in words: `Mon-Fri 04:00-17:00 Kuala Lumpur time`. */
733export function hoursWords(rule: Rule): string {
734  if (!rule.hours) return ''
735  const days = [...rule.hours.days].sort((a, b) => a - b)
736  const name = (d: number) => (DAYS[d] ?? '').replace(/^./, c => c.toUpperCase())
737  const run = days.length > 2 && days.every((d, i) => i === 0 || d === (days[i - 1] ?? 0) + 1)
738  const span = days.length === 7 ? 'Every day' : run ? `${name(days[0] ?? 0)}-${name(days[days.length - 1] ?? 0)}` : days.map(name).join(', ')
739  const zone = rule.tz ? ` ${(rule.tz.split('/').pop() ?? rule.tz).replace(/_/g, ' ')} time` : ''
740  return `${span} ${hhmm(rule.hours.from)}-${hhmm(rule.hours.to)}${zone}`
741}
742
743/** The reason a stop is in force, in a sentence or two, without the way past. */
744function reasonText(stop: NonNullable<Verdict['stop']>, simulated: boolean, account?: string | null): string {
745  const window = `${NAMES[stop.window]} window`
746  const sim = simulated ? ' (simulated)' : ''
747  if (stop.pace) {
748    const said = `${paceWords(stop.pace)}${sim}`
749    if (!namesAccounts(stop.rule)) return `${said}.`
750    const who = account ? accountIdentity(account) : 'this account'
751    return `${who} is ${said}, so it lasts for ${stop.group?.keepFor ?? 'the team'}.`
752  }
753  if (namesAccounts(stop.rule)) {
754    const who = account ? accountIdentity(account) : 'this account'
755    return `${who} has ${pct(stop.left)} of its ${window} left${sim}; g-line keeps the last ${stop.rule.left}% for ${stop.group?.keepFor ?? 'the team'}.`
756  }
757  return `${pct(stop.left)} of the ${window} left${sim}, at or under your ${stop.rule.left}% stop.`
758}
759
760/** Why a prompt was held, when the window resets, and the way past: Enter again for a prompt the person typed. */
761export function stopText(stop: NonNullable<Verdict['stop']>, nowMs: number, offsetMinutes: number, simulated = false,
762  o: { account?: string | null; typed?: boolean; queued?: { at?: string; cache?: 'warm' | 'bridge' | 'cold' } } = {}): string {
763  // When it lets go on its own: a pace step's lift or the end of the rule's hours, else the reset.
764  const lift = liftsAt(stop, nowMs, offsetMinutes)
765  const when = resetWords(lift !== undefined ? Math.ceil(lift / 1000) : stop.resetsAt, nowMs, offsetMinutes)
766  const cache = o.queued?.cache === 'bridge' ? ', cache kept warm' : o.queued?.cache === 'cold' ? '; the cache will be cold by then' : ''
767  const past = o.typed === false
768    ? ''
769    : o.queued
770      ? ` Queued${o.queued.at ? ` for about ${o.queued.at}` : ''}${cache}; Enter again sends it now.`
771      : ' Enter again sends it anyway.'
772  return `g-line held this: ${reasonText(stop, simulated, o.account)}${when ? ` Lifts ${lift !== undefined && stop.pace ? 'about ' : 'at '}${when}.` : ''}${past}`
773}
774
775/**
776 * About when a stop lets go on its own (ms): the window's reset, or sooner the
777 * end of the rule's hours. Undefined when neither is known.
778 */
779export function liftsAt(held: Held, nowMs: number, offsetMinutes?: number): number | undefined {
780  const reset = held.pace?.liftsAt ?? (held.resetsAt !== undefined ? held.resetsAt * 1000 : undefined)
781  const hours = held.rule.hours
782  if (!hours) return reset
783  const at = localTime(nowMs, held.rule.tz, offsetMinutes)
784  if (!at) return reset
785  const end = nowMs + (((hours.to - at.minute) % 1440 + 1440) % 1440) * 60_000
786  return reset === undefined ? end : Math.min(reset, end)
787}
788
789/** What a queue bridge reads: times in seconds, the window's percent left. */
790export type BridgeFacts = { now: number; expiresAt?: number; sendAt?: number; left?: number; bridges: number; prefix: number }
791
792/**
793 * Whether a queued prompt's cache needs one re-read now to still be warm when the
794 * prompt goes: it expires before the send, within four minutes, the window has
795 * room for a read, the cache is worth it, and at most two bridges per prompt.
796 */
797export function bridgeDue(f: BridgeFacts): boolean {
798  if (f.expiresAt === undefined || f.sendAt === undefined || f.expiresAt >= f.sendAt) return false
799  if (f.now < f.expiresAt - 240 || f.now > f.expiresAt - 20) return false
800  return (f.left ?? 0) > 1 && f.bridges < 2 && f.prefix >= 20_000
801}
802
803/** Why a running turn was ended, when the window resets, and how to carry on. */
804export function endText(end: NonNullable<Verdict['end']>, nowMs: number, offsetMinutes: number, simulated = false, account?: string | null): string {
805  const reset = resetWords(end.resetsAt, nowMs, offsetMinutes)
806  return `g-line ended this turn before its next request: ${reasonText(end, simulated, account)}${reset ? ` It resets at ${reset}.` : ''}`
807    + ' To carry on anyway, type "continue" and press Enter twice.'
808}
809
810const hhmm = (minute: number) => `${String(Math.floor(minute / 60)).padStart(2, '0')}:${String(minute % 60).padStart(2, '0')}`
811
812/** A rule in words: `at 10% of 5h left, on accounts "team@", 09:00-17:00 Mon-Fri (Asia/Kuala_Lumpur): stop`. */
813export function ruleText(rule: Rule): string {
814  const when = [rule.pace ? (rule.pace.window === '5h' ? 'paced 5h window' : 'paced week') : `at ${rule.left}% of ${rule.window} left`]
815  if (rule.unlessResetWithin !== undefined) {
816    const u = rule.unlessResetWithin
817    when.push(`unless it resets within ${u >= 86_400 && u % 86_400 === 0 ? `${u / 86_400}d` : u >= 3600 && u % 3600 === 0 ? `${u / 3600}h` : `${Math.round(u / 60)}m`}`)
818  }
819  if (rule.accounts) when.push(`on accounts ${rule.accounts.map(a => `"${a}"`).join(', ')}`)
820  if (rule.exceptAccounts) when.push(`on accounts except ${rule.exceptAccounts.map(a => `"${a}"`).join(', ')}`)
821  if (rule.groups) when.push(`on ${rule.groups.length === 1 ? 'group' : 'groups'} ${rule.groups.join(', ')}`)
822  if (rule.hours) {
823    const days = rule.hours.days.length === 7 ? 'daily' : rule.hours.days.map(d => (DAYS[d] ?? '').replace(/^./, c => c.toUpperCase())).join(',')
824    when.push(`${hhmm(rule.hours.from)}-${hhmm(rule.hours.to)} ${days}${rule.tz ? ` (${rule.tz})` : ''}`)
825  }
826  if (rule.pace) {
827    const p = rule.pace
828    const office = p.office ? `, office ${hoursWords({ ...rule, hours: p.office, tz: p.tz })} counts ${p.officeWeight}x` : p.tz ? `, ${p.tz}` : ''
829    when.push(`keeps ${p.reserve}% back, ${p.burst}% free at the start${office}`)
830    const steps = [`effort ${p.effort}`, p.agents ? `agents on ${p.agents}` : '', rule.endTurn ? 'stop new prompts and end a running turn' : 'stop new prompts']
831    return `${when.join(', ')}: ${steps.map((x, i) => (x ? `${x} at ${p.tiers[i]} points ahead` : '')).filter(Boolean).join(', ')}`
832  }
833  const what = [rule.effort ? `effort ${rule.effort}` : '', rule.agents ? `agents on ${rule.agents}` : '', rule.stop ? (rule.endTurn ? 'stop new prompts and end a running turn' : 'stop new prompts') : ''].filter(Boolean)
834  return `${when.join(', ')}: ${what.join(', ')}`
835}
836
837/** What's in force, in a few words: `stop (4% of 5h left), effort low, agents on haiku`. */
838export function inForceText(v: Verdict): string {
839  return [v.stop ? (v.stop.pace ? `stop (${paceWords(v.stop.pace)})` : `stop (${pct(v.stop.left)} of ${v.stop.window} left)`) : '', v.effort ? `effort ${v.effort}` : '', v.agents ? `agents on ${v.agents}` : '']
840    .filter(Boolean).join(', ')
841}
842
843/** What a pace rule's steps are, by tier 1 to 3. */
844const paceSteps = (rule: Rule, from: number, to: number): string[] => {
845  const p = rule.pace
846  if (!p) return []
847  const steps = [`the conversation runs at effort ${p.effort}`, p.agents ? `new subagents run on ${p.agents}` : '', 'new prompts stop']
848  return steps.slice(from, to).filter(Boolean)
849}
850
851/** What changed between two verdicts, in words for a toast; nothing when nothing did. */
852export function changeText(before: Verdict | undefined, after: Verdict): string | undefined {
853  const was = new Set(before?.rules.map(r => r.id) ?? [])
854  const started = after.rules.filter(r => !was.has(r.id))
855  const parts: string[] = []
856  // A pace rule climbing a step says where the week stands and what now applies.
857  for (const rule of after.rules) {
858    const at = after.pace?.[rule.id]
859    if (!at) continue
860    const from = before?.pace?.[rule.id]?.tier ?? 0
861    if (at.tier > from) parts.push(`${paceWords(at)}: ${paceSteps(rule, from, at.tier).join(', ')}`)
862  }
863  if (after.stop && started.includes(after.stop.rule) && !after.stop.pace) parts.push(`new prompts stop (${pct(after.stop.left)} of the ${NAMES[after.stop.window]} window left)`)
864  if (after.effort && started.some(r => r.effort)) parts.push(`the conversation runs at effort ${after.effort}`)
865  if (after.agents && started.some(r => r.agents)) parts.push(`new subagents run on ${after.agents}`)
866  if (before?.effort && after.effort && before.effort !== after.effort) parts.push(`the conversation now runs at effort ${after.effort}`)
867  if (before?.agents && after.agents && before.agents !== after.agents) parts.push(`new subagents now run on ${after.agents}`)
868  if (before?.stop && !after.stop) parts.push('prompts go through again')
869  if (before?.effort && !after.effort) parts.push('effort is yours again')
870  if (before?.agents && !after.agents) parts.push('subagents pick their own model again')
871  if (!parts.length) return undefined
872  return `g-line guard: ${parts.join('; ')}.`
873}
874
875/** Line 2's guard segment words, widest first: what's in force, or that it's paused. */
876export function guardForms(verdict: Verdict, pausedFor?: number, until?: string, queued = false): { forms: string[]; tone: 'bad' | 'warn' | 'dim' } | undefined {
877  if (pausedFor !== undefined && pausedFor > 0 && verdict.rules.length) {
878    const m = Math.ceil(pausedFor / 60)
879    return { forms: [`guard paused ${m}m`, 'guard paused'], tone: 'dim' }
880  }
881  if (verdict.stop?.pace) {
882    // A pace step's lift is reckoned from the allowance's growth: about, not exact.
883    const till = until ? ` till ~${until}` : ''
884    const forms = [`guard: over pace, ${pct(verdict.stop.pace.used)} of the ${verdict.stop.pace.window === '5h' ? '5h' : 'week'} used${till}`, `over pace${till}`, 'over pace']
885    return { forms: queued ? forms.map((f, i) => (i < forms.length - 1 ? `${f}, 1 queued` : f)) : forms, tone: 'bad' }
886  }
887  if (verdict.stop) {
888    const till = until ? ` till ${until}` : ''
889    const reserve = `${verdict.stop.group?.name ?? 'team'} reserve`
890    const forms = namesAccounts(verdict.stop.rule)
891      ? [`guard: ${reserve}, ${pct(verdict.stop.left)} ${verdict.stop.window} left${till}`, `${reserve}${till}`, reserve]
892      : [`guard: held, ${pct(verdict.stop.left)} ${verdict.stop.window} left${till}`, `guard: held${till}`, 'guard: held']
893    return { forms: queued ? forms.map((f, i) => (i < forms.length - 1 ? `${f}, 1 queued` : f)) : forms, tone: 'bad' }
894  }
895  const doing = [verdict.effort ? `effort ${verdict.effort}` : '', verdict.agents ? `agents ${verdict.agents}` : ''].filter(Boolean)
896  if (!doing.length) return undefined
897  const paced = verdict.pace && verdict.rules.every(r => r.pace)
898  return { forms: paced ? [`guard: over pace, ${doing.join(', ')}`, 'over pace'] : [`guard: ${doing.join(', ')}`, 'guard on'], tone: 'warn' }
899}
900
901/** What keep-warm reads. Times in seconds. */
902export type WarmFacts = {
903  now: number
904  /** When the main conversation's last request started. */
905  lastAt: number
906  ttl: '5m' | '1h'
907  /** Tokens the cache holds: the next request's prefix. */
908  prefix: number
909  compacted: boolean
910  /** Claude Code's idle compaction will summarise this conversation before the cache expires. */
911  compactionCovers: boolean
912  /** Re-reads already made since the last real request. */
913  done: number
914  /** Re-reads every session on the machine made this hour. */
915  thisHour: number
916  fiveHourLeft?: number
917  /** A guard stop rule is in force. */
918  stopped: boolean
919  /** Seconds until that stop lets go on its own, when known. */
920  liftsIn?: number
921  /** A turn is running. */
922  busy: boolean
923  /** Seconds added to `after`, so sessions idle since the same moment don't all re-read at once. */
924  jitter: number
925  /** The account changed since the cache was written: it belongs to the other account. */
926  accountChanged?: boolean
927  /** The model changed (`/model`) since the last request: its cache is the old model's. */
928  modelChanged?: boolean
929  /** Another session on this account was typed in more recently (`sessions: last`). */
930  notLastTouched?: boolean
931  /** Another session on this account holds the re-read for now. */
932  leased?: boolean
933}
934
935/** Idle seconds after which an hour-long cache may already be gone. */
936const WARM_LAPSE = 3600 - 120
937
938/** Why keep-warm re-reads now, or why it won't: the first reason that holds. */
939export function warmDue(k: KeepWarm | undefined, f: WarmFacts): { due: boolean; why: string } {
940  if (!k) return { due: false, why: 'off' }
941  if (f.busy) return { due: false, why: 'a turn is running' }
942  if (f.ttl !== '1h') return { due: false, why: 'the cache lives 5 minutes (over the plan limit, on credits, or by setting)' }
943  if (f.compacted) return { due: false, why: 'the conversation was compacted' }
944  if (f.accountChanged) return { due: false, why: 'the account changed' }
945  if (f.modelChanged) return { due: false, why: 'the model changed' }
946  if (f.compactionCovers) return { due: false, why: 'Claude Code compacts this conversation when idle' }
947  if (f.prefix < k.minContext) return { due: false, why: 'too small to be worth keeping' }
948  // A hold mustn't cost the cache: bridge it when the re-reads left can reach its lift.
949  if (f.stopped && (f.liftsIn === undefined || f.liftsIn > (k.max - f.done) * WARM_LAPSE)) return { due: false, why: 'held for longer than keep-warm can bridge' }
950  if (f.fiveHourLeft === undefined || !Number.isFinite(f.fiveHourLeft) || f.fiveHourLeft < k.minLeft) return { due: false, why: 'the 5-hour window is low' }
951  if (f.done >= k.max) return { due: false, why: 'kept warm as many times as allowed' }
952  if (f.thisHour >= k.perHour) return { due: false, why: 'the hourly limit on this account is reached' }
953  if (k.sessions === 'last' && f.notLastTouched) return { due: false, why: 'you typed in another session on this account last' }
954  if (f.leased) return { due: false, why: 'another session on this account is re-reading' }
955  const idle = f.now - f.lastAt
956  // Two minutes before the hour is up the cache may already be gone: a re-read then would rebuild it.
957  // `after` plus the spread stops a minute short of that, so a late `after` still gets its chance.
958  if (idle < Math.min(k.after + f.jitter, WARM_LAPSE - 60)) return { due: false, why: 'not idle long enough' }
959  if (idle > WARM_LAPSE) return { due: false, why: 'the cache has lapsed' }
960  return { due: true, why: 'idle' }
961}
962
963/**
964 * Whether a re-read found the cache: it read most of the conversation and
965 * wrote little. A read of nothing, or writes of 10% or more of what it read,
966 * mean the cache it meant to keep wasn't there, so keep-warm stands down.
967 */
968export function readBack(prefix: number, usage: { cache_read_input_tokens: number; cache_creation_input_tokens: number } | undefined): boolean {
969  if (!usage || usage.cache_read_input_tokens <= 0) return false
970  return usage.cache_read_input_tokens >= prefix * 0.5 && usage.cache_creation_input_tokens < usage.cache_read_input_tokens * 0.1
971}
972
973/**
974 * The account an `account_command` line names, without a leading `account`
975 * and a trailing `(…)` note (a plan, a quota, `via my-accounts`) that can change
976 * while the account stays the same: `account you@example.com (82% left)`
977 * reads `you@example.com`.
978 */
979export function accountIdentity(line: string | null | undefined): string {
980  const text = (line ?? '').trim()
981  return text.replace(/^account\s+/i, '').replace(/\s*\([^()]*\)$/, '').trim() || text
982}
983
984/** The store's name for an account's share of keep-warm and resume: its reading, or the machine's when there is none. */
985export function accountKey(account: string | null | undefined): string {
986  const a = accountIdentity(account).toLowerCase().replace(/[^a-z0-9@._+-]+/g, '_').slice(0, 80)
987  return a || 'machine'
988}
989
990/** A lease on `key` for `holder` until `until` (ms): free, expired, or already the holder's. */
991export function leaseFree(lease: unknown, holder: string, nowMs: number): boolean {
992  if (!lease || typeof lease !== 'object') return true
993  const l = lease as { holder?: unknown; until?: unknown }
994  return l.holder === holder || typeof l.until !== 'number' || !Number.isFinite(l.until) || l.until <= nowMs
995}
996
997/** `kept warm 2× · $0.18` for line 2 while re-reads hold the cache; the cost only when known. */
998export function warmForms(count: number, cost?: number): string[] {
999  if (count <= 0) return []
1000  const money = cost !== undefined && cost > 0 ? ` · ${cost < 0.005 ? '<$0.01' : `$${cost.toFixed(2)}`}` : ''
1001  return money ? [`kept warm ${count}×${money}`, `kept warm ${count}×`] : [`kept warm ${count}×`]
1002}
1003
1004export type Simulation = { window: WindowName; used: number; until: number }
1005
1006/** `/g-line guard simulate 5h 96`: the window's reading replaced for the guard alone, reset two hours out when unknown. */
1007export function simulated(facts: Facts, sim: Simulation | undefined): Facts {
1008  if (!sim || sim.until <= facts.nowMs) return facts
1009  const real = facts.windows[sim.window]
1010  const resetsAt = real?.resetsAt && real.resetsAt * 1000 > facts.nowMs ? real.resetsAt : Math.floor(facts.nowMs / 1000) + 2 * 3600
1011  return { ...facts, windows: { ...facts.windows, [sim.window]: { left: 100 - sim.used, resetsAt } } }
1012}
1013
1014/**
1015 * When a stopped turn can go on: the reset of every window that reads full
1016 * (100% used), the latest of them, plus `jitterSeconds` so sessions on one
1017 * account don't all start at once. Nothing when no window reads full, or a
1018 * full one has no reset time.
1019 */
1020export function resumeAt(limits: readonly { kind: string; percentUsed: number; resetsAt?: number }[], nowMs: number, jitterSeconds: number):
1021  { at: number; window: WindowName } | undefined {
1022  const full = limits.filter(l => (l.kind === 'five_hour' || l.kind === 'seven_day') && l.percentUsed >= 100)
1023  if (!full.length || full.some(l => l.resetsAt === undefined || !Number.isFinite(l.resetsAt) || l.resetsAt * 1000 <= nowMs)) return undefined
1024  const last = full.reduce((a, b) => ((b.resetsAt ?? 0) > (a.resetsAt ?? 0) ? b : a))
1025  return { at: (last.resetsAt ?? 0) * 1000 + Math.max(0, Math.round(Number.isFinite(jitterSeconds) ? jitterSeconds : 0)) * 1000, window: last.kind === 'five_hour' ? '5h' : 'week' }
1026}
1027
1028/**
1029 * What a held decision or a pass is bound to: the account and the window (and its reset)
1030 * it was made for. An account switch, or a window that has reset since, makes it a
1031 * different epoch, and whatever was bound to the old one (a pass for one prompt, a prompt
1032 * sent again, a queued prompt) no longer carries over.
1033 */
1034export function epochOf(account: string | null | undefined, held?: { window: WindowName; resetsAt?: number }): string {
1035  return `${accountKey(account)}|${held ? `${held.window}:${held.resetsAt ?? ''}` : '-'}`
1036}
1037
1038/** `/g-line guard why`: the figures, each rule's state, the account's group, the pace allowance now and when the hold lifts. */
1039export function whyLines(guard: GuardConfig, facts: Facts, verdict: Verdict, o: { pausedFor?: number; simulated?: boolean } = {}): string[] {
1040  const out: string[] = []
1041  const offset = facts.offsetMinutes ?? 0
1042  if (!guard.rules.length) return ['No guard rules: write them under "guard" in config.json.']
1043  if (!guard.on) out.push('The guard is off (/g-line guard on).')
1044  if (o.simulated) out.push('These are simulated readings.')
1045  if (o.pausedFor && o.pausedFor > 0) out.push(`Paused for ${Math.ceil(o.pausedFor / 60)} more minutes.`)
1046  for (const name of ['week', '5h'] as const) {
1047    const w = facts.windows[name]
1048    const reset = w?.resetsAt !== undefined ? ` Resets ${resetWords(w.resetsAt, facts.nowMs, offset)}.` : ''
1049    out.push(w && Number.isFinite(w.left) ? `${NAMES[name].replace(/^./, c => c.toUpperCase())} window: ${pct(100 - w.left)} used, ${pct(w.left)} left.${reset}` : `${NAMES[name].replace(/^./, c => c.toUpperCase())} window: no reading yet.`)
1050  }
1051  if (guard.groups?.length) {
1052    const g = groupOf(guard.groups, facts.account)
1053    out.push(g ? `This account is in group ${g.name}.` : 'No account reading yet, so no group.')
1054  }
1055  for (const rule of guard.rules) {
1056    const w = facts.windows[rule.window]
1057    const label = ruleText(rule)
1058    if (!w || !Number.isFinite(w.left)) {
1059      out.push(`${label}: no ${NAMES[rule.window]} reading yet, so it waits.`)
1060      continue
1061    }
1062    const on = verdict.active[rule.id] !== undefined
1063    const scope = inScope(guard, rule, facts)
1064    if (rule.pace) {
1065      const now = verdict.pace?.[rule.id] ?? (w.resetsAt !== undefined ? paceRead(rule.pace, { left: w.left, resetsAt: w.resetsAt }, facts.nowMs, facts.offsetMinutes) : undefined)
1066      if (!now) {
1067        out.push(`${label}: the engine gave no reset time for the ${paceName(rule.pace.window)}, so there's nothing to pace.`)
1068        continue
1069      }
1070      const figures = `${pct(now.used)} of the ${paceName(now.window)} used, ${pct(now.allowed)} allowed by now${now.office ? ' (office hours)' : ''}`
1071      const state = on ? `step ${now.tier} of 3 in force${now.hard ? ' (inside the reserve)' : ''}` : now.tier > 0 && !scope ? 'waits (not this account or hours)' : 'on pace'
1072      out.push(`${label}: ${figures}; ${state}.`)
1073    } else {
1074      out.push(`${label}: ${pct(w.left)} left; ${on ? 'in force' : scope ? 'not reached' : 'waits (not this account or hours)'}.`)
1075    }
1076  }
1077  if (verdict.stop) {
1078    const lift = liftsAt(verdict.stop, facts.nowMs, facts.offsetMinutes)
1079    out.push(`Held: new prompts stop. ${lift !== undefined ? `The hold lifts about ${resetWords(Math.floor(lift / 1000), facts.nowMs, offset)}.` : 'No lift time is known.'}`)
1080  } else if (verdict.effort || verdict.agents) {
1081    const steps = Object.values(verdict.pace ?? {}).map(n => n.liftsAt).filter((x): x is number => x !== undefined)
1082    const next = steps.length ? Math.min(...steps) : undefined
1083    out.push(`In force: ${inForceText(verdict)}.${next !== undefined ? ` The next step eases about ${resetWords(Math.floor(next / 1000), facts.nowMs, offset)}.` : ''}`)
1084  } else out.push('Nothing is held now.')
1085  return out
1086}
1087
1088/**
1089 * Near the weekly reset, what's left of the week is there to use: the words for it, once
1090 * the week resets within `drain.within` with `drain.left` percent or more left, else
1091 * nothing. Says what the guard still keeps back for this account, if anything.
1092 */
1093export function drainText(guard: GuardConfig, facts: Facts, account?: string | null): string | undefined {
1094  const d = guard.drain
1095  const w = facts.windows.week
1096  if (!d || !guard.on || !w || w.resetsAt === undefined) return undefined
1097  const until = w.resetsAt * 1000 - facts.nowMs
1098  if (until <= 0 || until > d.within * 1000 || w.left < d.left) return undefined
1099  // What a week stop rule in force for this account, now or later this week, keeps back.
1100  const keeps = guard.rules.filter(r => r.window === 'week' && r.stop && !r.pace && inScope(guard, r, facts)
1101    && (r.unlessResetWithin === undefined || until > r.unlessResetWithin * 1000)).map(r => r.left)
1102  const keep = keeps.length ? Math.max(...keeps) : 0
1103  const who = account ? `${accountIdentity(account)} has` : 'This account has'
1104  const reset = resetWords(w.resetsAt, facts.nowMs, facts.offsetMinutes ?? 0)
1105  return `${who} ${pct(w.left)} of its week left, and it resets at ${reset}. It's yours to use${keep ? `: g-line keeps only the last ${pct(keep)}` : ''}.`
1106}
1107
hooks/settings.ts 388 lines
1// Settings: one table every surface reads. The defaults, merging a layer
2// (a config file, /config, a choice made in the pane), the pane's toggles,
3// `/g-line set` and `/g-line settings` all come from SETTINGS below, so a
4// setting added here has a toggle, a command name and an origin at once.
5//
6// Pure: no `$`. The layers are read in register.tsx, lowest first:
7// defaults, the plugin's config.json, ~/.config/glanceline/config.json (0.4),
8// ~/.config/g-line/config.json, /config, then the pane. The highest layer
9// that names a setting is where its value comes from.
10
11import { num, zoneOffset } from './core'
12import type { Preset } from './core'
13import { receiptFields } from './extras'
14import type { ReceiptSpec } from './extras'
15import { NO_GUARD, parseGuard, seconds } from './guard'
16import type { GuardConfig } from './guard'
17
18export type Notify = { cache: boolean; reset: boolean; longTurn: boolean; agents: boolean }
19
20export type PulseSpeed = 'normal' | 'slow' | 'paused'
21
22export type Config = {
23  /** 2: line 1 at the end of the hint line, line 2 under it; 1: the hint line only; 0: receipts, spinner and heads-ups, no footer. */
24  lines: 0 | 1 | 2
25  /** Headlines from g-line's feed on long turns' spinner and in the pane; fetches one static file. */
26  pulse: boolean
27  /** How often Pulse moves to the next headline. */
28  pulseSpeed: PulseSpeed
29  /** Sources Pulse skips, matched case-insensitively within an item's source: `𝕏` skips every post on X. */
30  pulseMute: string[]
31  /** Shorten Claude Code's standing hints: `(shift+tab to cycle)` to `⇧⇥`, `? for shortcuts` to `?`. */
32  shortHints: boolean
33  /** The branch on line 2 (two lines; one line names `git` in `segments`). */
34  git: boolean
35  preset: Preset
36  segments?: string
37  icons: 'none' | 'nerd'
38  toasts: boolean
39  cacheTtl: 'auto' | '5m' | '1h'
40  accountCommand?: string[]
41  /** A command that prints the account's usage as JSON (another machine's spending); only with `accountCommand`. */
42  usageCommand?: string[]
43  notify: Notify
44  longTurnSeconds: number
45  resetThreshold: number
46  receipt: ReceiptSpec
47  spinner: boolean
48  footerLabels: boolean
49  coach: boolean
50  /** Give Claude the `status` tool to read these figures when asked (off by default). */
51  claudeReads: boolean
52  toolStreak: number
53  budget?: number
54  exportState: boolean
55  /** The guard's rules and keep-warm (config.json `guard`); none by default, so it does nothing. */
56  guard: GuardConfig
57  /** The other g-line sessions on this machine: `2 others · 1 waiting` on line 2, and the list in the pane. */
58  roster: boolean
59  /** The person's IANA time zone for every time g-line shows; the machine's own when unset (`auto`). */
60  tz?: string
61}
62
63export const DEFAULTS: Config = {
64  lines: 2, pulse: false, pulseSpeed: 'normal', pulseMute: [], shortHints: true, git: false, preset: 'default', icons: 'none', toasts: true, cacheTtl: 'auto',
65  notify: { cache: true, reset: true, longTurn: false, agents: false },
66  longTurnSeconds: 60, resetThreshold: 80, receipt: 'adaptive', spinner: true, footerLabels: true,
67  coach: false, claudeReads: false, toolStreak: 3, exportState: false, guard: NO_GUARD, roster: true,
68}
69
70/** One layer over `base`: config.json's snake_case keys; anything malformed is ignored. */
71export function merge(base: Config, raw: unknown): Config {
72  if (!raw || typeof raw !== 'object') return base
73  const r = raw as Record<string, unknown>
74  const next = { ...base, notify: { ...base.notify } }
75  if ([0, 1, 2, '0', '1', '2'].includes(r.lines as number)) next.lines = Number(r.lines) as 0 | 1 | 2
76  if (r.lines === 'receipts') next.lines = 0
77  if (typeof r.pulse === 'boolean') next.pulse = r.pulse
78  if (r.pulse_speed === 'normal' || r.pulse_speed === 'slow' || r.pulse_speed === 'paused') next.pulseSpeed = r.pulse_speed
79  if (Array.isArray(r.pulse_mute)) {
80    next.pulseMute = r.pulse_mute.filter((word): word is string => typeof word === 'string' && word.trim() !== '')
81      .map(word => word.trim()).slice(0, 100)
82  }
83  if (typeof r.git === 'boolean') next.git = r.git
84  if (typeof r.short_hints === 'boolean') next.shortHints = r.short_hints
85  if (r.preset === 'minimal' || r.preset === 'default' || r.preset === 'full') next.preset = r.preset
86  // A custom layout is one line's: naming segments picks the one-line layout.
87  if (typeof r.segments === 'string' && r.segments.trim()) {
88    next.segments = r.segments
89    if (r.lines === undefined) next.lines = 1
90  }
91  if (r.icons === 'none' || r.icons === 'nerd') next.icons = r.icons
92  if (typeof r.toasts === 'boolean') next.toasts = r.toasts
93  if (r.cache_ttl === '5m' || r.cache_ttl === '1h' || r.cache_ttl === 'auto') next.cacheTtl = r.cache_ttl
94  const command = r.account_command
95  if (Array.isArray(command) && command.length && command.every(word => typeof word === 'string')) {
96    next.accountCommand = command as string[]
97  }
98  const usage = r.usage_command
99  if (Array.isArray(usage) && usage.length && usage.every(word => typeof word === 'string')) {
100    next.usageCommand = usage as string[]
101  }
102  if (typeof r.notify === 'boolean') next.notify = { cache: r.notify, reset: r.notify, longTurn: r.notify && base.notify.longTurn, agents: r.notify && base.notify.agents }
103  else if (r.notify && typeof r.notify === 'object') {
104    const n = r.notify as Record<string, unknown>
105    if (typeof n.cache === 'boolean') next.notify.cache = n.cache
106    if (typeof n.reset === 'boolean') next.notify.reset = n.reset
107    if (typeof n.long_turn === 'boolean') next.notify.longTurn = n.long_turn
108    if (typeof n.agents === 'boolean') next.notify.agents = n.agents
109  }
110  const seconds = num(r.long_turn_seconds)
111  if (seconds !== undefined && seconds >= 5) next.longTurnSeconds = seconds
112  const threshold = num(r.reset_threshold)
113  if (threshold !== undefined && threshold >= 0 && threshold <= 100) next.resetThreshold = threshold
114  if (r.receipt !== undefined) next.receipt = r.receipt === false ? [] : receiptFields(r.receipt)
115  if (typeof r.spinner === 'boolean') next.spinner = r.spinner
116  if (typeof r.footer_labels === 'boolean') next.footerLabels = r.footer_labels
117  if (typeof r.coach === 'boolean') next.coach = r.coach
118  if (typeof r.claude_reads === 'boolean') next.claudeReads = r.claude_reads
119  const streak = num(r.tool_streak)
120  if (streak !== undefined && streak >= 0) next.toolStreak = Math.floor(streak)
121  const budget = num(r.today_budget)
122  if (budget !== undefined && budget > 0) next.budget = budget
123  if (typeof r.export_state === 'boolean') next.exportState = r.export_state
124  if (typeof r.roster === 'boolean') next.roster = r.roster
125  if (r.tz === 'auto' || r.tz === null) delete next.tz
126  else if (typeof r.tz === 'string' && r.tz.trim() && zoneOffset(r.tz.trim(), 0) !== undefined) next.tz = r.tz.trim()
127  // `true`/`false` (from `/g-line guard on|off`) switches the rules the files wrote; an object replaces them.
128  if (typeof r.guard === 'boolean') next.guard = { ...base.guard, on: r.guard }
129  else if (r.guard && typeof r.guard === 'object') next.guard = parseGuard(r.guard)
130  return next
131}
132
133// ------------------------------------------------------------- the table
134
135export type Group = 'Show' | 'Heads-ups' | 'Extras'
136
137type Common = {
138  /** The config.json key; `notify.cache` is `{ "notify": { "cache": … } }`. */
139  key: string
140  /** Other names `/g-line set` takes. */
141  aliases: readonly string[]
142  label: string
143  group: Group
144  /** The pane's key for it: unique among the settings view's buttons. */
145  hotkey: string
146  help: string
147}
148
149/** On or off. */
150export type Toggle = Common & { kind: 'toggle'; get: (c: Config) => boolean }
151
152/** One of a few named values, cycled in the pane. */
153export type Choice = Common & { kind: 'choice'; options: readonly string[]; get: (c: Config) => string; words?: Readonly<Record<string, string>> }
154
155export type Setting = Toggle | Choice
156
157const receiptName = (c: Config): string => {
158  if (c.receipt === 'adaptive') return 'adaptive'
159  if (!c.receipt.length) return 'off'
160  const short = receiptFields('short')
161  const full = receiptFields('full')
162  const same = (a: ReceiptSpec, b: ReceiptSpec) => Array.isArray(a) && Array.isArray(b) && a.join() === b.join()
163  return same(c.receipt, short) ? 'short' : same(c.receipt, full) ? 'full' : 'custom'
164}
165
166const toggle = (key: string, label: string, group: Group, hotkey: string, get: (c: Config) => boolean, help: string,
167  aliases: readonly string[] = []): Toggle => ({ kind: 'toggle', key, label, group, hotkey, get, help, aliases })
168
169export const SETTINGS: readonly Setting[] = [
170  { kind: 'choice', key: 'lines', aliases: ['layout'], label: 'Layout', group: 'Show', hotkey: 'l',
171    options: ['2', '1', 'receipts'], get: c => (c.lines === 0 ? 'receipts' : String(c.lines)),
172    words: { 2: 'two lines', 1: 'one line', receipts: 'receipts only' },
173    help: '2: the hint line plus one row under it; 1: the hint line only; receipts: no footer' },
174  { kind: 'choice', key: 'receipt', aliases: ['receipts'], label: 'Receipt', group: 'Show', hotkey: 'r',
175    options: ['adaptive', 'short', 'full', 'off'], get: receiptName,
176    help: 'what each turn\'s closing line adds' },
177  toggle('spinner', 'Spinner extras', 'Show', 's', c => c.spinner, 'the running turn\'s cost and tools on the spinner'),
178  toggle('footer_labels', 'Footer labels', 'Show', 'f', c => c.footerLabels, 'agents and compaction in the footer (one-line layout)', ['footer']),
179  toggle('short_hints', 'Short hints', 'Show', 'h', c => c.shortHints, '`(shift+tab to cycle)` drawn as `⇧⇥`', ['hints']),
180  toggle('git', 'Git branch', 'Show', 'g', c => c.git, 'the branch on line 2', ['branch', 'git_branch']),
181  toggle('roster', 'Other sessions', 'Show', 'b', c => c.roster, 'other g-line sessions on this machine on line 2, and which wait on you', ['others', 'sessions']),
182  toggle('toasts', 'Toasts', 'Heads-ups', 't', c => c.toasts, 'heads-ups as toasts in the terminal'),
183  toggle('notify.cache', 'Cold cache', 'Heads-ups', 'k', c => c.notify.cache, 'a notification before the prompt cache goes cold', ['cache', 'cold_cache']),
184  toggle('notify.reset', 'Window reset', 'Heads-ups', 'w', c => c.notify.reset, 'a notification when a usage window resets', ['reset', 'window_reset']),
185  toggle('notify.long_turn', 'Long turn', 'Heads-ups', 'u', c => c.notify.longTurn, 'a notification when a long turn ends', ['long_turn']),
186  toggle('notify.agents', 'Agents', 'Heads-ups', 'a', c => c.notify.agents, 'a notification when a background agent ends', ['agents']),
187  toggle('pulse', 'Pulse', 'Extras', 'p', c => c.pulse, 'AI dev headlines and posts on X; fetches one static file every 45 minutes'),
188  { kind: 'choice', key: 'pulse_speed', aliases: ['speed', 'rotation'], label: 'Pulse speed', group: 'Extras', hotkey: 'v',
189    options: ['normal', 'slow', 'paused'], get: c => c.pulseSpeed,
190    words: { normal: 'every 8 s', slow: 'every 40 s', paused: 'paused' },
191    help: 'how often Pulse moves to the next headline; paused keeps one until you page in /g-line news' },
192  toggle('coach', 'Coach', 'Extras', 'o', c => c.coach, 'offers /effort or /compact for Tab to take; never changes anything'),
193  toggle('claude_reads', 'Claude reads', 'Extras', 'x', c => c.claudeReads, 'gives Claude a read-only `status` tool for these figures', ['status', 'status_tool']),
194  toggle('export_state', 'Export state', 'Extras', 'e', c => c.exportState, 'writes the figures as JSON for tmux and other bars', ['export']),
195]
196
197export const GROUPS: readonly Group[] = ['Show', 'Heads-ups', 'Extras']
198
199const normal = (name: string) => name.trim().toLowerCase().replace(/[-\s]+/g, '_')
200
201/** The setting a name means: its key, an alias, or its label. */
202export function findSetting(name: string): Setting | undefined {
203  const n = normal(name)
204  return SETTINGS.find(s => normal(s.key) === n || s.aliases.includes(n) || normal(s.label) === n)
205}
206
207/** The value in words, for the pane and toasts: `on`, `two lines`. */
208export function said(setting: Setting, c: Config): string {
209  const value = shown(setting, c)
210  return setting.kind === 'choice' ? setting.words?.[value] ?? value : value
211}
212
213/** The value as config.json spells it: `on`/`off` or the choice's name. */
214export function shown(setting: Setting, c: Config): string {
215  return setting.kind === 'toggle' ? (setting.get(c) ? 'on' : 'off') : setting.get(c)
216}
217
218/** What a layer gets to say `setting` is `value`: `{ pulse: true }`, `{ notify: { cache: false } }`. */
219export function patchOf(setting: Setting, value: boolean | string): Record<string, unknown> {
220  if (setting.key.startsWith('notify.')) return { notify: { [setting.key.slice('notify.'.length)]: value } }
221  if (setting.key === 'lines') return { lines: value === '2' || value === '1' ? Number(value) : value }
222  return { [setting.key]: value }
223}
224
225/** A saved layer with a patch laid over it; `notify` is merged field by field. */
226export function withPatch(saved: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {
227  const next = { ...saved, ...patch }
228  if (patch.notify && typeof patch.notify === 'object') {
229    const was = saved.notify
230    const before = typeof was === 'boolean'
231      ? { cache: was, reset: was, ...(was ? {} : { long_turn: false, agents: false }) }
232      : was && typeof was === 'object' ? was as Record<string, unknown> : {}
233    next.notify = { ...before, ...(patch.notify as Record<string, unknown>) }
234  }
235  return next
236}
237
238/** A saved layer without `setting`: what the layers beneath it then decide. */
239export function withoutSetting(saved: Record<string, unknown>, setting: Setting): Record<string, unknown> {
240  const next = { ...saved }
241  if (setting.key.startsWith('notify.')) {
242    const sub = setting.key.slice('notify.'.length)
243    const was = saved.notify
244    if (typeof was === 'boolean') next.notify = (withPatch({ notify: was }, { notify: {} })).notify
245    if (next.notify && typeof next.notify === 'object') {
246      const rest = { ...(next.notify as Record<string, unknown>) }
247      delete rest[sub]
248      if (Object.keys(rest).length) next.notify = rest
249      else delete next.notify
250    }
251    return next
252  }
253  delete next[setting.key]
254  return next
255}
256
257/** Whether a layer names `setting`. */
258export function names(raw: unknown, setting: Setting): boolean {
259  if (!raw || typeof raw !== 'object') return false
260  const r = raw as Record<string, unknown>
261  if (setting.key.startsWith('notify.')) {
262    if (typeof r.notify === 'boolean') return true
263    return !!r.notify && typeof r.notify === 'object' && typeof (r.notify as Record<string, unknown>)[setting.key.slice(7)] === 'boolean'
264  }
265  if (setting.key === 'lines') return r.lines !== undefined || (typeof r.segments === 'string' && !!r.segments.trim())
266  return r[setting.key] !== undefined
267}
268
269export type Layer = { name: string; raw: unknown }
270
271/** Where a setting's value comes from: the highest layer that names it, else `default`. */
272export function originOf(setting: Setting, layers: readonly Layer[]): string {
273  for (let i = layers.length - 1; i >= 0; i--) {
274    const layer = layers[i]
275    if (layer && names(layer.raw, setting)) return layer.name
276  }
277  return 'default'
278}
279
280/** Whether the value differs from what a fresh install shows. */
281export function changed(setting: Setting, c: Config): boolean {
282  return shown(setting, c) !== shown(setting, DEFAULTS)
283}
284
285/** The next value a press in the pane moves to. */
286export function nextValue(setting: Setting, c: Config): boolean | string {
287  if (setting.kind === 'toggle') return !setting.get(c)
288  const at = setting.options.indexOf(setting.get(c))
289  return setting.options[(at + 1) % setting.options.length] ?? setting.options[0] ?? ''
290}
291
292// --------------------------------------------------------------- command
293
294export type Command =
295  | { kind: 'pane' }
296  | { kind: 'card' }
297  | { kind: 'settings' }
298  | { kind: 'news' }
299  | { kind: 'open' }
300  | { kind: 'show' }
301  | { kind: 'hide' }
302  | { kind: 'set'; setting: Setting; value: boolean | string | 'toggle' }
303  | { kind: 'all'; value: boolean }
304  | { kind: 'reset'; setting?: Setting }
305  | { kind: 'guard'; action: 'status' | 'once' | 'resume' | 'on' | 'off' | 'cancel' | 'why' | 'on here' | 'off here' }
306  | { kind: 'guard'; action: 'pause'; seconds: number }
307  | { kind: 'guard'; action: 'simulate'; window: '5h' | 'week'; used: number }
308  | { kind: 'guard'; action: 'simulate'; window?: undefined; used?: undefined }
309  | { kind: 'error'; text: string }
310
311const ON = ['on', 'true', 'yes', '1', 'enable', 'enabled']
312const OFF = ['off', 'false', 'no', '0', 'disable', 'disabled']
313
314const unknownName = (name: string) => ({
315  kind: 'error' as const,
316  text: `g-line has no setting "${name}". /g-line settings lists them: ${SETTINGS.map(s => s.key).join(', ')}.`,
317})
318
319/** What `/g-line <args>` asks for. */
320export function parseCommand(args: string): Command {
321  const words = args.trim().split(/\s+/).filter(Boolean).map(w => w.toLowerCase())
322  const [verb = '', ...rest] = words
323  if (verb === '' || verb === 'details') return { kind: 'pane' }
324  if (verb === 'card') return { kind: 'card' }
325  if (verb === 'settings' || verb === 'config' || verb === 'list') return { kind: 'settings' }
326  if ((verb === 'news' || verb === 'read' || verb === 'reader') && !rest.length) return { kind: 'news' }
327  if (verb === 'open' && !rest.length) return { kind: 'open' }
328  if (verb === 'on' && !rest.length) return { kind: 'show' }
329  if (verb === 'guard') return guardCommand(rest)
330  if (verb === 'off' && !rest.length) return { kind: 'hide' }
331  if (verb === 'reset') {
332    if (!rest.length) return { kind: 'reset' }
333    const setting = findSetting(rest.join('_'))
334    return setting ? { kind: 'reset', setting } : unknownName(rest.join(' '))
335  }
336  // `/g-line set pulse on`, `/g-line toggle pulse`, and the bare `/g-line pulse [on|off]` of 0.5.
337  const named = verb === 'set' || verb === 'toggle' ? rest : words
338  if (!named.length) return { kind: 'error', text: 'Name a setting: /g-line set pulse on. /g-line settings lists them.' }
339  const last = named[named.length - 1] ?? ''
340  const hasValue = named.length > 1 && verb !== 'toggle'
341  const name = hasValue ? named.slice(0, -1).join('_') : named.join('_')
342  const raw = hasValue ? last : 'toggle'
343  if (name === 'all' || name === 'everything') {
344    if (ON.includes(raw)) return { kind: 'all', value: true }
345    if (OFF.includes(raw)) return { kind: 'all', value: false }
346    return { kind: 'error', text: '/g-line set all on, or /g-line set all off.' }
347  }
348  const setting = findSetting(name)
349  if (!setting) return unknownName(name.replace(/_/g, ' '))
350  if (raw === 'toggle') return { kind: 'set', setting, value: 'toggle' }
351  if (setting.kind === 'toggle') {
352    if (ON.includes(raw)) return { kind: 'set', setting, value: true }
353    if (OFF.includes(raw)) return { kind: 'set', setting, value: false }
354    return { kind: 'error', text: `${setting.key} is on or off.` }
355  }
356  const choice = raw === 'two' ? '2' : raw === 'one' ? '1' : raw
357  if (setting.options.includes(choice)) return { kind: 'set', setting, value: choice }
358  return { kind: 'error', text: `${setting.key} is one of ${setting.options.join(', ')}.` }
359}
360
361/** `/g-line guard [status|why|once|pause [30m]|resume|on|off|off here|on here]`. */
362function guardCommand(rest: string[]): Command {
363  const [action = 'status', ...more] = rest
364  if (action === 'pause') {
365    const s = more.length ? seconds(more.join('')) : 3600
366    if (s === undefined || s <= 0 || s > 24 * 3600) return { kind: 'error', text: '/g-line guard pause takes a time up to a day, such as 30m or 2h; an hour if none.' }
367    return { kind: 'guard', action: 'pause', seconds: s }
368  }
369  if (action === 'simulate' || action === 'sim') {
370    if (more.length === 1 && (more[0] === 'off' || more[0] === 'stop')) return { kind: 'guard', action: 'simulate' }
371    const [win = '', pct = ''] = more
372    const window = win === '5h' || win === 'five' ? '5h' : win === 'week' || win === 'wk' || win === '7d' ? 'week' : undefined
373    const used = Number(pct.replace(/%$/, ''))
374    if (!window || more.length !== 2 || !Number.isFinite(used) || used < 0 || used > 100) {
375      return { kind: 'error', text: '/g-line guard simulate 5h 96 (or week 90): the guard acts as if that much of the window were used, for 15 minutes. /g-line guard simulate off ends it.' }
376    }
377    return { kind: 'guard', action: 'simulate', window, used }
378  }
379  // `off here`: this session alone, so the person's own session is free while agents on the machine stay guarded.
380  if ((action === 'off' || action === 'on') && more.length === 1 && (more[0] === 'here' || more[0] === 'me')) {
381    return { kind: 'guard', action: action === 'off' ? 'off here' : 'on here' }
382  }
383  if (more.length === 0 && (action === 'status' || action === 'once' || action === 'resume' || action === 'on' || action === 'off' || action === 'cancel' || action === 'why')) {
384    return { kind: 'guard', action }
385  }
386  return { kind: 'error', text: '/g-line guard, then why, once, off here, on here, pause [30m], resume, simulate 5h 96, cancel, on or off.' }
387}
388
types/index.d.ts 223 lines
1/** What the mod has seen of the session, kept by the host across reloads. */
2export type Snap = {
3  /** Model id the last main-loop request named. */
4  model?: string
5  effort?: string
6  /** The effort the person set, when the guard ran the last main-loop request lower. */
7  effortSet?: string
8  context?: { tokens?: number; window?: number; percent?: number }
9  rateLimits?: { kind: string; percentUsed: number; resetsAt?: number; at?: number }[]
10  costUsd?: number
11  /** Milliseconds since the epoch. */
12  startedAt?: number
13  cache?: {
14    /** Unix seconds the last main-loop request started. */
15    lastAt: number
16    /** Whether that response reported cache tokens. */
17    cached: boolean
18    /** Tokens the next request rewrites if the cache is cold. */
19    prefix: number
20    /** TTL learned from a hit or miss after an idle gap. */
21    learned?: '5m' | '1h'
22    /**
23     * Tokens the conversation was compacted to since that request: the cached
24     * prefix is gone, and the next request writes the summary whatever the time.
25     * 0 when a compaction was seen but not its size.
26     */
27    compactedTo?: number
28    /**
29     * The `account_command` reading changed since this cache was written. Caches
30     * are kept per organization, so the next request starts a new one.
31     */
32    accountChanged?: boolean
33    /**
34     * Read from Claude Code's figures for a resumed conversation (its last
35     * response's age and size), not from a request this process made. Keep-warm
36     * waits for a real request: before one there's nothing to send again.
37     */
38    restored?: boolean
39  }
40  git?: { branch?: string; dirty?: boolean } | null
41  account?: string | null
42  /** Highest percent seen per usage window, keyed `<kind>:<resets at>`. */
43  peaks?: Record<string, number>
44}
45
46/** One finished main-loop turn, drawn at the end of its "Baked for 3s" line. */
47export type Receipt = {
48  /** Dollars the session's cost ledger grew by during the turn (API prices). */
49  cost?: number
50  /** Share of the turn's input read from the prompt cache, 0 to 100. */
51  cacheHit?: number
52  /** Context tokens the turn added (negative after a compaction). */
53  context?: number
54  tools: number
55  agents: number
56  /** Output tokens the main loop produced. */
57  output?: number
58  /** Milliseconds since the epoch the turn ended. */
59  endAt: number
60  durationMs: number
61  /** Background work was still running when the turn ended. */
62  background: boolean
63  /** The largest prompt-cache write of one main-loop request in the turn. */
64  cacheWrite?: number
65  /** Whether the session had a cache before the turn, so a first write is no news. */
66  warmBefore?: boolean
67  /** Failed tool calls in the main loop; `tool` names the tool when they were all one. */
68  failures?: number
69  failedTool?: string
70  /** A background agent overlapped the turn, so the session's cost growth is not the turn's alone. */
71  overlap?: boolean
72  /** The turn's first request rebuilt a prompt cache that had gone cold. */
73  cold?: boolean
74  /** A compaction ran during the turn, with its size before and after. */
75  compacted?: { before?: number; after?: number }
76  /** The context window size, for what counts as a big jump. */
77  window?: number
78  /** The turn's cost over the median of the recent attributable turns, fixed when it closed. */
79  ratio?: number
80  /** The guard lowered the main conversation's effort for this turn. */
81  guardEffort?: { from: string; to: string }
82  /** Subagents the guard started on a cheaper model during the turn. */
83  guardAgents?: number
84  /** The guard ended the turn before its next request: how much of which window was left, and the week's pace when a pace rule ended it. */
85  guardEnded?: { left: number; window: string; pace?: { used: number; allowed: number } }
86  /** The account changed since the cache this turn found was written. */
87  accountChanged?: boolean
88  /** The model that answered, when it wasn't the one the request asked for (a fallback). */
89  servedBy?: string
90}
91
92/** The turn running now, for the spinner. */
93export type TurnLive = {
94  id: string
95  startAt: number
96  costAt?: number
97  contextAt?: number
98  tools: number
99  agents: number
100  failures?: number
101  /** The tool that failed, while every failure was the same tool; null once they differ. */
102  failedTool?: string | null
103  /** What the failing calls worked on (a file's name, a command's first words), while it was the same. */
104  failedTarget?: string | null
105  /** Context tokens the turn has added so far, from its latest request. */
106  contextGrowth?: number
107  cacheWrite?: number
108  warmBefore?: boolean
109  cold?: boolean
110  overlap?: boolean
111  compacted?: { before?: number; after?: number }
112  guardEffort?: { from: string; to: string }
113  guardAgents?: number
114  guardEnded?: { left: number; window: string; pace?: { used: number; allowed: number } }
115  servedBy?: string
116  accountChanged?: boolean
117}
118
119export type AgentRow = {
120  id: string
121  description: string
122  type: string
123  model?: string
124  status: string
125  background: boolean
126  teammate: boolean
127  /** Milliseconds since the epoch. */
128  startedAt: number
129  endedAt?: number
130}
131
132export type Compaction = { at: number; trigger: string; before?: number; after?: number }
133
134export type Forecast = { turns: number; percent: number; threshold: number }
135
136/** What the session has done, for the pane and the card. */
137export type Totals = {
138  turns: number
139  tools: number
140  failures: number
141  agents: number
142  /** Turns whose first request rebuilt a cold prompt cache. */
143  colds: number
144  peakContext: number
145  /** Per tool: calls and failures. */
146  byTool: Record<string, { calls: number; failures: number }>
147  compactions: Compaction[]
148  /** Context growth of the last main-loop turns, for the forecast. */
149  growth: number[]
150  /** Main-loop input tokens read from the cache, and all main-loop input tokens, for a weighted hit rate. */
151  cacheRead?: number
152  inputTokens?: number
153}
154
155/** The context window by category, as /context counts it locally. */
156export type ContextView = {
157  at: number
158  total: number
159  max: number
160  threshold?: number
161  rows: { name: string; tokens: number; kind: string }[]
162  mcp: { server: string; tokens: number; tools: number }[]
163  memoryFiles: number
164  memoryTokens: number
165  skills?: { count: number; tokens: number }
166}
167
168/** One day's figures, summed over every session the mod ran in on this machine. */
169export type Day = {
170  day: string; cost: number; turns: number; tools: number; sessions: number; colds: number; agents: number
171  /** Keep-warm's re-reads, and what they cost at API prices (included in `cost`) when the engine counted it. */
172  warms?: number; warmCost?: number
173}
174
175export type Ledger = { today: Day; week: Day[] }
176
177/** One headline from g-line's Pulse feed, cleaned. */
178export type PulseItem = {
179  title: string
180  url: string
181  source: string
182  at?: string
183  /** The whole post or summary, for the reader; the title when the feed has none. */
184  text?: string
185  likes?: number
186  /** The author's display name on X (`Claude`), beside the handle in `source`. */
187  author?: string
188  /** The story a post on X is about, or what it quotes. */
189  story?: string
190  /** Who found a publisher's item (`Techmeme`), when `source` is the publisher. */
191  via?: string
192  /** Hacker News points, and its comments page. */
193  points?: number
194  discussion?: string
195}
196
197/** The feed as last fetched. */
198export type PulseFeed = { fetchedAt: number; generatedAt?: string; items: PulseItem[] }
199
200declare module 'claude-code' {
201  interface PluginState {
202    'g-line': {
203      snap: Snap
204      tick: number
205      seen: string[]
206      hidden: boolean
207      receipts: Record<string, Receipt>
208      turn: TurnLive | null
209      agents: AgentRow[]
210      totals: Totals
211      forecast: Forecast | null
212      context: ContextView | null
213      ledger: Ledger | null
214      view: 'details' | 'card' | 'settings' | 'news'
215      pulse: PulseFeed | null
216      /** The link of the headline Pulse shows now: the cycle's rules move it on. */
217      pulseNow: string | null
218      /** The reader's selected item. */
219      newsAt: number
220    }
221  }
222}
223