SLOPSHOPPER

Token Weather Usage

One line above the prompt: context tokens with their weather, a bar per recent prompt, your 5-hour and 7-day limits against the time elapsed, the prompt cache…

bandtimer
★ 21v3.17.15Apache-2.0updated 2026-10-22augiefra/claude-mods/plugins/token-weather-usage
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · token-weather-usage
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ☁ 97.4k │ 5h ━━──── 31% │ cache — │ ≈ $0.42 ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
☁ 97.4k │ 5h ━━──── 31% │ cache — │ ≈ $0.42 ⟨Claude Code's own drawing⟩
README

Token Weather Usage

One band above the Claude Code prompt: the context in tokens, your 5-hour and 7-day limits against the clock, whether the prompt cache is still warm, what the session and the last prompt cost, and which agents are running.

One session, step by step

All clear

Agents at work

Cache about to lapse

Slow down

  • Context: tokens in the context with a weather icon (hover the pill for the weather and the share of the window), one bar per recent prompt, the last prompt's change.
  • 5h / 7d: the share of your account's limits already used, in green, yellow or red by pace. The gap with the time elapsed is hatched: grey while you have margin, in the bar's color when you use faster than time passes. Then the time left; in the app, hover the 5-hour pill for the reset time (machine's time zone). When the week's pace would use up the 7-day limit before its reset, a warning follows the bar, ⚠ out Sun night (in the app ⚠ Sun night, in place of the time left), amber, red within a day: the share used since the week started over the time elapsed, the same projection as Claude's usage page. Its hover card gives the time and, beside it, the last day's pace, to see whether you are speeding up or slowing down. An estimate, shown after the week's first day and from 15% used, hidden when the terminal line is too narrow.
  • Cache: the time before the prompt cache lapses (1 hour on a subscription, 5 minutes on an API key, inferred), behind a bolt in the app. The share of the last message read from the cache shows only under 90%. Yellow under 10 minutes, with what is at stake ("$2.32 at stake"); "missed" with its cause and what it cost above a hit ("+$2.10"); red "expired" with the cost of writing the context again ("289k to rewrite ≈ $2.32"), and the way out from 100k tokens: /compact, or a new thread from 300k (on the line in the terminal, in the hover card in the app). In the app, hover the cache pill for the expiry time, the share read, what the context costs a message from the cache against writing it again, and what the cache saved in this thread. The dollars come from Anthropic's list prices (dated 2026-10-08); on a subscription they are API-price equivalents, hence the "≈". A model missing from the price table shows tokens only. After a compaction the band updates at once: the context drops, and the cache reads "compacted" until the next message writes a new one.
  • Cost: the session cost as /cost totals it (whole dollars from $100; in the app the pill shows whole dollars, the hover card the cents), and what the last prompt added, in dollars and in points of the 5-hour limit (in the pill's hover card in the app). On a subscription, an API-price equivalent, not a bill.
  • Agents: how many subagents the thread ran ("2 running · 7" while some run). In the app the pill stays; hover it for the cost split by model and effort, the agents running with the name of each one's latest tool (never its arguments), the last batch (how long, how much ran in parallel, tool calls, cost) and what delegating saved.

In the terminal:

☂ 634k ▃▄▂█▆ ▲ +6.3k │ 5h ━━━━╍─ 74% · 24 min │ 7d ━━━━── 65% · 2d20h │ cache 52 min │ ≈ $41.07 (+$0.58 · +1.5% 5h) │ 2 agents

Labels in English, French or Russian: auto follows LC_ALL, LC_MESSAGES or LANG, otherwise pick en, fr or ru in the Language option (/config).

Privacy

No personal data collected, sent or retained, no network requests. The mod reads the usage figures Claude Code provides (context, limits, session cost, each request's cache token counts), the list of the session's subagents and the names of the tools their responses ask for (never the arguments; shown in the agents card and kept in memory only), the locale variables and the prompt-cache switches; it reads no file and hooks no tool call. It keeps in the plugin's local storage the latest limits reading, the 7-day share used every half hour over the last two days, and, per session, recent context readings, the last request's cache figures, what the cache saved in the session, the last prompt's cost and each subagent's model, effort, token counts and description (deleted after 8 idle days).

What its hooks do. Every hook only reads and passes the event on unchanged (return next(e)): the mod never changes, delays or refuses anything. session.start and session.end start and stop its timers; turn.step reads each model response's token counts and the names of the tools it asks for; turn.complete reads the session's usage after each turn; session.measure reads new limits and cost readings; session.compact notes a compaction; ui.render draws the band above the prompt.

Credits and license

Weather, context and turns chart after Anthropic's Token Weather example (claude-code-playground, Apache-2.0). Limit gauges written after HolyGrail's usage-meter (HolyGrail/claude-mods), and the cache block after Daniel San's prompt-cache-control (davila7/claude-code-templates, MIT), without copying their code. The agents card's tool lines and last batch adapt code from Anji Xu's agentpane (xuanji86/claude-agentpane, MIT). Apache-2.0 license: see LICENSE and NOTICE.

Source 1 files
hooks/token-weather-usage.mjs 1704 lines
1// Token Weather Usage: one line above the prompt.
2//   Terminal, blocks split by a thin rule:
3//   ☁ 440k ▃▄▂▇▆ ▲ +8.4k │ 5h ━━╍╍── 37% · 2h22 │ 7d ━━━╍── 60% · 2d23h │ cache 52 min │ ≈ $4.32 (+$0.84 · +2% 5h) │ 2 agents
4//   Desktop app: the same blocks as tinted, outlined pills; the cost pill keeps the total (the last
5//   prompt in its card) and the agents pill stays, its card splitting the cost by model and effort.
6//
7// Weather, context and recent turns: adapted from the Token Weather example,
8//   Copyright 2026 Anthropic PBC, SPDX-License-Identifier: Apache-2.0 (claude-code-playground).
9// 5-hour and 7-day limits: written for this mod after HolyGrail's usage-meter
10//   (https://github.com/HolyGrail/claude-mods/tree/main/plugins/usage-meter), without copying its code.
11// Prompt cache: written for this mod after Daniel San's prompt-cache-control
12//   (https://github.com/davila7/claude-code-templates, MIT), without copying its code.
13// Agents card, its tool lines and last batch: adapted from Anji Xu's agentpane
14//   (https://github.com/xuanji86/claude-agentpane, MIT): latestBatch, batchReceipt, toolParts.
15//
16// The engine reads on(...) and $.noun.method(...) from the source: they stay spelled out,
17// and the functions that take $ live at the top level.
18
19// ---------- Language ----------
20
21// Labels in English, French or Russian. "auto" follows LC_ALL, LC_MESSAGES or LANG, then the runtime's
22// locale; English unless one of them starts with "fr" or "ru". The desktop app often sets none of
23// them, so the language option (/config) is the sure way to pick.
24const TEXT = {
25  en: {
26    weather: { clear: "Clear", cloudy: "Cloudy", showers: "Showers", storm: "Storm", compact: "Compact soon" },
27    percent: (n) => `${n}%`,
28    labels: { five_hour: "5h", seven_day: "7d", spend_limit: "$" },
29    day: "d",
30    hour: "h",
31    minute: "min",
32    second: "s",
33    contextAlt: (word, percent, window) => `${word} · ${percent} of ${window}`,
34    turnsAlt: (n) => `Tokens added by the last ${n} prompts`,
35    gaugeAlt: (label, value) => `${label}: ${value} used`,
36    cache: "cache",
37    expired: "expired",
38    compacted: "compacted",
39    missed: "missed",
40    causes: { model: "model changed", lapsed: "lapsed", prefix: "start changed" },
41    underMinute: "< 1 min",
42    cost: (usd) => (usd >= 100 ? `≈ $${Math.round(usd)}` : `≈ $${usd.toFixed(2)}`),
43    costWhole: (usd) => (usd < 0.5 ? "< $1" : `≈ $${Math.round(usd)}`),
44    resetsAt: (time) => `Resets at ${time}`,
45    weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
46    dayParts: ["night", "morning", "afternoon", "evening"],
47    dayPartsShort: ["night", "am", "pm", "eve"],
48    dayPart: (day, part) => `${day} ${part}`,
49    night: (day) => `${day} night`,
50    date: (day, d, m) => `${day} ${d}/${m}`,
51    runOut: (when) => `⚠ out ${when}`,
52    runOutShort: (when) => `⚠ ${when}`,
53    runOutTip: (gained, over, when, time, reset) => `At this week's pace (+${gained} in ${over}), the 7-day limit runs out ${when} around ${time}, before the reset on ${reset}.`,
54    recentOut: (gained, over, when, time) => `At the last ${over}'s pace (+${gained}): ${when} around ${time}.`,
55    recentLasts: (gained, over) => `At the last ${over}'s pace (+${gained}), it would last until the reset.`,
56    lastPrompt: (usd) => `+$${usd.toFixed(2)}`,
57    lastPrompt5h: (points) => `+${decimal(points)}% 5h`,
58    toRewrite: (tokens) => `${tokens} to rewrite`,
59    newThread: "new thread",
60    // $2.32, $182 from 100 dollars, < $0.01 under a cent.
61    money: (usd) => (usd < 0.01 ? "< $0.01" : `$${amount(usd)}`),
62    atStake: (what) => `${what} at stake`,
63    // The cache's tooltip in the app, one line per item.
64    tips: {
65      warm: (time, oneHour, observed) => `Cache warm until ${time} (${oneHour ? "1-hour" : "5-minute"} lifetime, ${observed ? "observed" : "assumed"}).`,
66      lastRead: (share, tokens) => `Last message: ${share} read from the cache (${tokens}).`,
67      costs: (read, rewrite) => `Reading the context: ${read} a message. If it expires: ${rewrite} to write it again.`,
68      saved: (usd) => `This thread: ${usd} saved by the cache.`,
69      soon: (time, tokens, costs) =>
70        `The cache expires at ${time}. Send your next message before then, or it writes ${tokens} tokens again${costs ? ` (${costs.rewrite} instead of ${costs.read})` : ""}.`,
71      expired: (tokens, cost) => `The next message writes the whole context (${tokens}) again at full price${cost ? `, ${cost}` : ""}.`,
72      compact: "/compact before going on: the context written again will be smaller.",
73      newThread: "A new thread avoids this rewrite; a compaction would read it all again.",
74      missed: (share, cause, tokens, surcharge) =>
75        `This message read only ${share} from the cache (${cause}): it wrote ${tokens} tokens again${surcharge ? `, ${surcharge} more than a message served by the cache` : ""}.`,
76      compacted: "Compacted: the next message writes a new, smaller cache.",
77    },
78    agents: (n) => (n === 1 ? "1 agent" : `${n} agents`),
79    agentsRunning: (running, n) => `${running} running · ${n}`,
80    // The cost pill's card in the app.
81    costTips: {
82      total: (usd) => `Thread cost ${usd}`,
83      plan: "At API prices: a subscription is not billed per token, this counts toward its limits.",
84      api: "At API list prices.",
85      last: (what) => `Last prompt: ${what}`,
86    },
87    // The agents pill's card: who spent what, by model and effort.
88    team: {
89      title: (n, running) => `Agents in this thread: ${n}${running ? ` (${running} running)` : ""}`,
90      line: (label, usd, share) => `${label}: ${usd}${share ? ` · ${share}` : ""}`,
91      main: (model) => `${model} · main thread`,
92      group: (model, n) => `${model} · ${n === 1 ? "1 agent" : `${n} agents`}`,
93      detail: (efforts, tokens) => `  ${efforts ? `effort ${efforts} · ` : ""}${tokens} tokens`,
94      efforts: { low: "low", medium: "medium", high: "high", xhigh: "extra high", max: "max" },
95      none: "No subagent in this thread yet.",
96      running: (model, description, time) => `Running: ${model} · “${description}” · ${time}`,
97      saved: (usd, model) => `Delegating: ${usd} saved compared with ${model}.`,
98      doing: (tool, n) => `  ↳ ${tool} · ${n === 1 ? "1 call" : `${n} calls`}`,
99      batch: (n, wall, usd) => `Last batch: ${n} agents in ${wall}${usd ? ` · ${usd}` : ""}`,
100      batchHow: (together, calls) => [together ? `${together.toFixed(1)}× in parallel` : "", calls ? `${calls} ${calls === 1 ? "tool call" : "tool calls"}` : ""].filter(Boolean).join(" · "),
101    },
102    icons: { five_hour: "5-hour limit", seven_day: "7-day limit", spend_limit: "Spend limit", reset: "Resets in", cache: "Prompt cache", cost: "Session cost", lastPrompt: "Last prompt", agents: "Agents" },
103  },
104  fr: {
105    weather: { clear: "Clair", cloudy: "Nuageux", showers: "Averses", storm: "Orage", compact: "Compacter bientôt" },
106    percent: (n) => `${n} %`,
107    labels: { five_hour: "5h", seven_day: "7j", spend_limit: "$" },
108    day: "j",
109    hour: "h",
110    minute: "min",
111    second: "s",
112    contextAlt: (word, percent, window) => `${word} · ${percent} de ${window}`,
113    turnsAlt: (n) => `Tokens ajoutés par les ${n} derniers prompts`,
114    gaugeAlt: (label, value) => `${label} : ${value} consommés`,
115    cache: "cache",
116    expired: "expiré",
117    compacted: "compacté",
118    missed: "raté",
119    causes: { model: "modèle changé", lapsed: "délai dépassé", prefix: "début modifié" },
120    underMinute: "< 1 min",
121    cost: (usd) => (usd >= 100 ? `≈ ${Math.round(usd)} $` : `≈ ${usd.toFixed(2).replace(".", ",")} $`),
122    costWhole: (usd) => (usd < 0.5 ? "< 1 $" : `≈ ${Math.round(usd)} $`),
123    resetsAt: (time) => `Remise à zéro à ${time}`,
124    weekdays: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
125    dayParts: ["nuit", "matin", "après-midi", "soir"],
126    dayPartsShort: ["nuit", "matin", "ap.-m.", "soir"],
127    dayPart: (day, part) => `${day} ${part}`,
128    night: (day, next) => `nuit de ${day} à ${next}`,
129    date: (day, d, m) => `${day} ${d}/${m}`,
130    runOut: (when) => `⚠ à court ${when}`,
131    runOutShort: (when) => `⚠ ${when}`,
132    runOutTip: (gained, over, when, time, reset) => `Au rythme de la semaine (+${gained} en ${over}), la limite 7 jours sera atteinte ${when} vers ${time}, avant la remise à zéro du ${reset}.`,
133    recentOut: (gained, over, when, time) => `Au rythme des dernières ${over} (+${gained}) : ${when} vers ${time}.`,
134    recentLasts: (gained, over) => `Au rythme des dernières ${over} (+${gained}), elle tiendrait jusqu’à la remise à zéro.`,
135    lastPrompt: (usd) => `+${usd.toFixed(2).replace(".", ",")} $`,
136    lastPrompt5h: (points) => `+${decimal(points).replace(".", ",")} % 5h`,
137    toRewrite: (tokens) => `${tokens} à réécrire`,
138    newThread: "nouveau fil",
139    money: (usd) => (usd < 0.01 ? "< 0,01 $" : `${amount(usd).replace(".", ",")} $`),
140    atStake: (what) => `${what} en jeu`,
141    tips: {
142      warm: (time, oneHour, observed) => `Cache chaud jusqu'à ${time} (durée ${oneHour ? "1 h" : "5 min"} ${observed ? "constatée" : "supposée"}).`,
143      lastRead: (share, tokens) => `Dernier message : ${share} lu depuis le cache (${tokens}).`,
144      costs: (read, rewrite) => `Relire le contexte : ${read} par message. S'il expire : ${rewrite} pour le réécrire.`,
145      saved: (usd) => `Ce fil : ${usd} économisés grâce au cache.`,
146      soon: (time, tokens, costs) =>
147        `Le cache expire à ${time}. Envoie ton prochain message avant, sinon il réécrira ${tokens} tokens${costs ? ` (${costs.rewrite} au lieu de ${costs.read})` : ""}.`,
148      expired: (tokens, cost) => `Le prochain message réécrira tout le contexte (${tokens}) au prix fort${cost ? `, ${cost}` : ""}.`,
149      compact: "/compact avant de reprendre : le contexte réécrit sera plus petit.",
150      newThread: "Un nouveau fil évite cette réécriture ; une compaction relirait tout.",
151      missed: (share, cause, tokens, surcharge) =>
152        `Ce message n'a lu que ${share} depuis le cache (${cause}) : il a réécrit ${tokens} tokens${surcharge ? `, ${surcharge} de plus qu'un message servi par le cache` : ""}.`,
153      compacted: "Compacté : le prochain message écrira un cache neuf, plus petit.",
154    },
155    agents: (n) => (n === 1 ? "1 agent" : `${n} agents`),
156    agentsRunning: (running, n) => `${running} en cours · ${n}`,
157    costTips: {
158      total: (usd) => `Coût du fil ${usd}`,
159      plan: "Au prix de l'API : un abonnement n'est pas facturé au token, cela compte dans ses limites.",
160      api: "Au prix catalogue de l'API.",
161      last: (what) => `Dernier message : ${what}`,
162    },
163    team: {
164      title: (n, running) => `Agents du fil : ${n}${running ? ` (${running} en cours)` : ""}`,
165      line: (label, usd, share) => `${label} : ${usd}${share ? ` · ${share}` : ""}`,
166      main: (model) => `${model} · fil principal`,
167      group: (model, n) => `${model} · ${n === 1 ? "1 agent" : `${n} agents`}`,
168      detail: (efforts, tokens) => `  ${efforts ? `effort ${efforts} · ` : ""}${tokens} tokens`,
169      efforts: { low: "bas", medium: "moyen", high: "élevé", xhigh: "très élevé", max: "max" },
170      none: "Aucun sous-agent dans ce fil.",
171      running: (model, description, time) => `En cours : ${model} · « ${description} » · ${time}`,
172      saved: (usd, model) => `Délégation : ${usd} économisés par rapport à ${model}.`,
173      doing: (tool, n) => `  ↳ ${tool} · ${n === 1 ? "1 appel" : `${n} appels`}`,
174      batch: (n, wall, usd) => `Dernier lot : ${n} agents en ${wall}${usd ? ` · ${usd}` : ""}`,
175      batchHow: (together, calls) => [together ? `${together.toFixed(1).replace(".", ",")}× en parallèle` : "", calls ? `${calls} ${calls === 1 ? "appel d'outil" : "appels d'outils"}` : ""].filter(Boolean).join(" · "),
176    },
177    icons: { five_hour: "Limite 5 h", seven_day: "Limite 7 jours", spend_limit: "Plafond de dépense", reset: "Remise à zéro dans", cache: "Cache de prompt", cost: "Coût du fil", lastPrompt: "Dernier prompt", agents: "Agents" },
178  },
179  ru: {
180    weather: { clear: "Ясно", cloudy: "Облачно", showers: "Ливни", storm: "Гроза", compact: "Скоро сжатие" },
181    percent: (n) => `${n}%`,
182    labels: { five_hour: "5ч", seven_day: "7д", spend_limit: "$" },
183    day: "д",
184    hour: "ч",
185    minute: "мин",
186    second: "с",
187    contextAlt: (word, percent, window) => `${word} · ${percent} из ${window}`,
188    turnsAlt: (n) => `Токены, добавленные последними промптами: ${n}`,
189    gaugeAlt: (label, value) => `${label}: израсходовано ${value}`,
190    cache: "кэш",
191    expired: "истёк",
192    compacted: "сжат",
193    missed: "промах",
194    causes: { model: "смена модели", lapsed: "истёк срок", prefix: "изменилось начало" },
195    underMinute: "< 1 мин",
196    cost: (usd) => (usd >= 100 ? `≈ ${Math.round(usd)} $` : `≈ ${usd.toFixed(2).replace(".", ",")} $`),
197    costWhole: (usd) => (usd < 0.5 ? "< 1 $" : `≈ ${Math.round(usd)} $`),
198    resetsAt: (time) => `Сброс в ${time}`,
199    weekdays: ["вс", "пн", "вт", "ср", "чт", "пт", "сб"],
200    dayParts: ["ночью", "утром", "днём", "вечером"],
201    dayPartsShort: ["ночью", "утром", "днём", "вечером"],
202    dayPart: (day, part) => `${day} ${part}`,
203    night: (day, next) => `в ночь на ${next}`,
204    date: (day, d, m) => `${day} ${d}.${m}`,
205    runOut: (when) => `⚠ кончится ${when}`,
206    runOutShort: (when) => `⚠ ${when}`,
207    runOutTip: (gained, over, when, time, reset) => `При темпе этой недели (+${gained} за ${over}) недельный лимит закончится ${when} около ${time}, до сброса ${reset}.`,
208    recentOut: (gained, over, when, time) => `При темпе последних ${over} (+${gained}): ${when} около ${time}.`,
209    recentLasts: (gained, over) => `При темпе последних ${over} (+${gained}) лимита хватит до сброса.`,
210    lastPrompt: (usd) => `+${usd.toFixed(2).replace(".", ",")} $`,
211    lastPrompt5h: (points) => `+${decimal(points).replace(".", ",")}% 5ч`,
212    toRewrite: (tokens) => `${tokens} к перезаписи`,
213    newThread: "новый тред",
214    money: (usd) => (usd < 0.01 ? "< 0,01 $" : `${amount(usd).replace(".", ",")} $`),
215    atStake: (what) => `под угрозой ${what}`,
216    tips: {
217      warm: (time, oneHour, observed) => `Кэш тёплый до ${time} (срок жизни ${oneHour ? "1 час" : "5 минут"}, ${observed ? "замерен" : "предполагается"}).`,
218      lastRead: (share, tokens) => `Последнее сообщение: ${share} прочитано из кэша (${tokens}).`,
219      costs: (read, rewrite) => `Чтение контекста: ${read} за сообщение. Если кэш истечёт: ${rewrite} на повторную запись.`,
220      saved: (usd) => `Этот тред: кэш сэкономил ${usd}.`,
221      soon: (time, tokens, costs) =>
222        `Кэш истекает в ${time}. Отправь следующее сообщение до этого, иначе ${tokens} токенов запишутся заново${costs ? ` (${costs.rewrite} вместо ${costs.read})` : ""}.`,
223      expired: (tokens, cost) => `Следующее сообщение заново запишет весь контекст (${tokens}) по полной цене${cost ? `, ${cost}` : ""}.`,
224      compact: "Сделай /compact перед продолжением: перезаписываемый контекст будет меньше.",
225      newThread: "Новый тред избавит от перезаписи; сжатие прочитает всё заново.",
226      missed: (share, cause, tokens, surcharge) =>
227        `Это сообщение прочитало из кэша только ${share} (${cause}): ${tokens} токенов записаны заново${surcharge ? `, на ${surcharge} дороже, чем сообщение из кэша` : ""}.`,
228      compacted: "Сжато: следующее сообщение запишет новый, меньший кэш.",
229    },
230    agents: (n) => `${n} ${plural(n, "агент", "агента", "агентов")}`,
231    agentsRunning: (running, n) => `${running} в работе · ${n}`,
232    costTips: {
233      total: (usd) => `Стоимость треда ${usd}`,
234      plan: "По ценам API: подписка не тарифицируется по токенам, это идёт в зачёт её лимитов.",
235      api: "По прайсовым ценам API.",
236      last: (what) => `Последний промпт: ${what}`,
237    },
238    team: {
239      title: (n, running) => `Агенты в треде: ${n}${running ? ` (в работе: ${running})` : ""}`,
240      line: (label, usd, share) => `${label}: ${usd}${share ? ` · ${share}` : ""}`,
241      main: (model) => `${model} · основной тред`,
242      group: (model, n) => `${model} · ${n} ${plural(n, "агент", "агента", "агентов")}`,
243      detail: (efforts, tokens) => `  ${efforts ? `усилие ${efforts} · ` : ""}${tokens} токенов`,
244      efforts: { low: "низкое", medium: "среднее", high: "высокое", xhigh: "очень высокое", max: "макс." },
245      none: "В этом треде пока нет субагентов.",
246      running: (model, description, time) => `В работе: ${model} · «${description}» · ${time}`,
247      saved: (usd, model) => `Делегирование: сэкономлено ${usd} по сравнению с ${model}.`,
248      doing: (tool, n) => `  ↳ ${tool} · ${n} ${plural(n, "вызов", "вызова", "вызовов")}`,
249      batch: (n, wall, usd) => `Последняя группа: ${n} ${plural(n, "агент", "агента", "агентов")} за ${wall}${usd ? ` · ${usd}` : ""}`,
250      batchHow: (together, calls) =>
251        [together ? `${together.toFixed(1).replace(".", ",")}× параллельно` : "", calls ? `${calls} ${plural(calls, "вызов", "вызова", "вызовов")} ${plural(calls, "инструмента", "инструментов", "инструментов")}` : ""].filter(Boolean).join(" · "),
252    },
253    icons: { five_hour: "Лимит на 5 часов", seven_day: "Лимит на 7 дней", spend_limit: "Лимит расходов", reset: "Сброс через", cache: "Кэш промпта", cost: "Стоимость сессии", lastPrompt: "Последний промпт", agents: "Агенты" },
254  },
255};
256let T = TEXT.en;
257
258// Russian plural: 1 агент, 2 агента, 5 агентов.
259function plural(n, one, few, many) {
260  const m10 = n % 10;
261  const m100 = n % 100;
262  if (m10 === 1 && m100 !== 11) return one;
263  if (m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14)) return few;
264  return many;
265}
266
267// 2.32, or 182 from 100 dollars (cents dropped).
268function amount(usd) {
269  return Math.round(usd * 100) >= 10_000 ? String(Math.round(usd)) : usd.toFixed(2);
270}
271
272// "≈ $2.32"; under a cent, "< $0.01" alone.
273function approx(usd) {
274  return usd < 0.01 ? T.money(usd) : `≈ ${T.money(usd)}`;
275}
276
277// ---------- Context weather (Token Weather) ----------
278
279const HISTORY = 12;
280const BARS = "▁▂▃▄▅▆▇█";
281const FORECAST = [
282  // Single-column symbols, no emoji: they line up in every font.
283  { upTo: 25, id: "clear", icon: "☀", color: "yellow" },
284  { upTo: 50, id: "cloudy", icon: "☁", color: "cyan" },
285  { upTo: 75, id: "showers", icon: "☂", color: "blue" },
286  { upTo: 90, id: "storm", icon: "☇", color: "magenta" },
287  { upTo: Infinity, id: "compact", icon: "↯", color: "red" },
288];
289
290// Turn bars: tokens added by each recent prompt; the current prompt takes the weather's tint
291// (colors readable on light and dark backgrounds), earlier ones stay grey.
292const TURN_BARS = 5;
293const SPARK = { height: 14, bar: 5.5, gap: 2 };
294const PAST_BAR = "rgba(127,127,127,0.45)";
295const SPARK_COLORS = { yellow: "#e0b000", cyan: "#1ba1c4", blue: "#2f68c0", magenta: "#b04fc0", red: "#d64545" };
296
297// Weather icons drawn in the app (the terminal keeps FORECAST's Unicode symbols): filled,
298// 15 px, each in its own tint. "Compact soon" redraws the ↯ zigzag with a thick stroke.
299const WEATHER_ICON_SIZE = 15;
300const WEATHER_ICONS = {
301  clear: (c) =>
302    `<circle cx="12" cy="12" r="4.5" fill="${c}"/><path fill="none" stroke="${c}" stroke-width="2" stroke-linecap="round" d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>`,
303  cloudy: (c) =>
304    `<path fill="${c}" stroke="${c}" stroke-width="1.5" stroke-linejoin="round" d="M7 18.5a3.75 3.75 0 0 1-.4-7.48A5.6 5.6 0 0 1 17.2 9.6a4.45 4.45 0 0 1 .3 8.9z"/>`,
305  showers: (c) =>
306    `<path fill="${c}" stroke="${c}" stroke-width="1.5" stroke-linejoin="round" d="M7 14.5a3.25 3.25 0 0 1-.35-6.48A5 5 0 0 1 16.2 6.8a3.85 3.85 0 0 1 .3 7.7z"/><path fill="none" stroke="${c}" stroke-width="2" stroke-linecap="round" d="M8.5 17.5l-1 2.5M12.5 17.5l-1 2.5M16.5 17.5l-1 2.5"/>`,
307  storm: (c) => `<path fill="${c}" stroke="${c}" stroke-width="1.5" stroke-linejoin="round" d="M13.5 2 5 13.5h6.5L10.5 22 19 10.5h-6.5z"/>`,
308  compact: (c) =>
309    `<path fill="none" stroke="${c}" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round" d="M14 2 7 12h8l-5 9M14.5 18.8 10 21l-.5-5"/>`,
310};
311const WEATHER_ICON_COLORS = { clear: "#e0b000", cloudy: "#8ea3b8", showers: "#2f68c0", storm: "#b04fc0", compact: "#d64545" };
312
313// Hover cards: the app shows no SVG <title> tooltip, so each pill carries a card of its own,
314// hidden until the pointer is over the pill, drawn above the band, in the app theme's own
315// background and outline colors (tested in the app against a fixed dark card: this one reads better).
316const CARD = { back: "background", line: "subtle" };
317function hoverCard(Box, Text, tip) {
318  const lines = String(tip).split("\n");
319  // No key: a keyed Box would scope its own hover, and a hidden one is never hovered.
320  return Box({
321    position: "absolute",
322    bottom: 1,
323    left: 0,
324    display: "none",
325    hover: { display: "flex" },
326    flexDirection: "column",
327    paddingX: 1,
328    paddingY: 0,
329    borderStyle: "round",
330    borderColor: CARD.line,
331    backgroundColor: CARD.back,
332    // An indented line is a detail of the one above it: dim.
333    children: lines.map((line, i) => Text(line.startsWith("  ") ? { key: "t" + i, dimColor: true, children: line } : { key: "t" + i, children: line })),
334  });
335}
336
337// The weather word goes to the pill's hover card: the pill keeps the tokens alone.
338function weatherSvg(id) {
339  const draw = WEATHER_ICONS[id];
340  if (!draw) return null;
341  return `<svg xmlns="http://www.w3.org/2000/svg" width="${WEATHER_ICON_SIZE}" height="${WEATHER_ICON_SIZE}" viewBox="0 0 24 24">${draw(WEATHER_ICON_COLORS[id])}</svg>`;
342}
343
344// Context readings: { tokens, window, percent }, oldest first.
345let readings = [];
346// Each session's readings are kept in $.store, so the bars come back after a restart.
347const TURNS_PREFIX = "turns:";
348const TURNS_KEEP_MS = 8 * 24 * 3_600_000;
349let turnsKey = null;
350
351// ---------- Account limits ----------
352
353const MINUTE = 60_000;
354const HOUR = 60 * MINUTE;
355const DAY = 24 * HOUR;
356// Length of each window; without one (spend cap), no elapsed-time marker.
357const SPANS = { five_hour: 5 * HOUR, seven_day: 7 * DAY };
358// Display order; an unknown window goes last.
359const ORDER = ["five_hour", "seven_day", "spend_limit"];
360// Pace = share used minus share of time elapsed, in points.
361// Above 0: using faster than time; beyond 15, or at 90% used: alert.
362const PACE_ALERT = 15;
363const USED_ALERT = 90;
364// Limits belong to the account: the latest reading, across sessions, lives in $.store.
365const SHARED_KEY = "limits";
366
367// Latest known reading: { at (ms), list: SessionRateLimit[] }.
368let limits = { at: 0, list: [] };
369
370// 7-day pace: readings of the week's share used, one per half hour over two days, kept in $.store
371// across sessions ({ at, used, resetsAt }, oldest first). The pace is read over the last day, or
372// over the whole week while fewer than six hours are known; shown only after a day of the week
373// and 15% used, when the limit would run out before the reset.
374const WEEK_KEY = "week";
375const WEEK_GAP = 30 * MINUTE;
376const WEEK_KEEP = 2 * DAY;
377const PACE_SPAN = DAY;
378const PACE_MIN_SPAN = 6 * HOUR;
379const OUT_MIN_ELAPSED = DAY;
380const OUT_MIN_USED = 15;
381const OUT_ALERT = DAY;
382let week = [];
383let ticker = null;
384
385// ---------- Prompt cache ----------
386
387// The cache keeps the start of the conversation for 5 minutes, or 1 hour; each request that
388// reads it starts the time again, counted from the request's start. Once it lapses, the next
389// message writes the whole context again. Mods get the token counts, not the lifetime: it is
390// inferred (Claude Code's rules, then what the traffic shows).
391const TTL = { "5m": 5 * MINUTE, "1h": HOUR };
392// Yellow under 10 minutes left.
393const CACHE_SOON = 10 * MINUTE;
394// From this context size, an expired cache suggests /compact before going on.
395const COMPACT_AT = 100_000;
396// From this one, a new thread instead: after a pause the next message writes the whole context
397// again at full price; a new thread avoids that rewrite, a compaction would read it all again.
398const LARGE_CONTEXT = 300_000;
399// A request that read less than half its prompt from the cache, and wrote more than this, missed.
400const MISS_SHARE = 50;
401const MISS_WRITE = 1_000;
402// From this share read from the cache, the pill shows the time left alone.
403const GOOD_HIT = 90;
404// Last main-loop request: { at, model, read, write, fresh, cause }.
405let cache = null;
406// True from a compaction of the main conversation until its next request: the cache that
407// request writes is a new one, neither expired nor missed.
408let compacted = false;
409// Lifetime seen in the traffic ("5m" | "1h"), which beats the rules.
410let seenTtl = null;
411// What the cache saved this session, in dollars: each request's tokens read from the cache,
412// at the input price minus the cache-read price.
413let savedUsd = 0;
414
415// Anthropic first-party list prices, USD per million tokens, as of 2026-10-08: input and cache
416// read. Cache writes follow from input: 1.25× for the 5-minute lifetime, 2× for 1 hour; output
417// is 5× input for every model here (OUTPUT).
418// "over" holds the prices of prompts above "at" tokens, for a model priced by prompt size.
419// Update this table, and its date, when the prices change. A model missing here shows tokens only.
420const PRICES = {
421  "claude-fable-5-1": { input: 10, read: 0.25 },
422  "claude-mythos-5-1": { input: 10, read: 0.25 },
423  "claude-fable-5": { input: 10, read: 1 },
424  "claude-opus-5-5": { input: 4, read: 0.2 },
425  "claude-opus-5": { input: 5, read: 0.5 },
426  "claude-opus-4-8": { input: 5, read: 0.5 },
427  "claude-opus-4-7": { input: 5, read: 0.5 },
428  "claude-opus-4-6": { input: 5, read: 0.5 },
429  "claude-sonnet-5-5": { input: 2, read: 0.1 },
430  "claude-sonnet-5": { input: 2, read: 0.2 },
431  "claude-sonnet-4-6": { input: 3, read: 0.3 },
432  "claude-haiku-5-5": { input: 0.1, read: 0.01, over: { at: 100_000, input: 0.5, read: 0.05 } },
433  "claude-haiku-4-5": { input: 1, read: 0.1 },
434};
435const OUTPUT = 5;
436// Environment switches read at session start.
437let cacheEnv = {};
438let cacheTicker = null;
439let cacheKey = "";
440
441// Session cost in dollars, as /cost totals it; null where the host keeps no ledger.
442let cost = null;
443// What the last prompt added to it (its subagents included), and the total it started from.
444let lastPrompt = null;
445let promptBase = null;
446// The same in points of the 5-hour limit (an account figure: other sessions running at the
447// same time count in it), and the reading it started from.
448let lastPrompt5h = null;
449let promptBase5h = null;
450let promptReset5h = null;
451
452// Subagents running now: { id, description, type }.
453let agents = [];
454let agentsKey = "";
455// Every subagent this thread ran, by id: { model, effort, usd, priced, input, read, write, output,
456// at, description, type }. Its requests are counted at list prices as they come back.
457let team = {};
458// Each agent's latest tool call and its calls so far ({ text, calls }), and when each agent ran
459// ({ from, to, seen, busy, ran, parentId }): the agents card's running lines and last batch. Kept in
460// memory only. After agentpane (xuanji86/claude-agentpane, MIT).
461let activity = {};
462// Agents whose last response asked for tools still running.
463let waiting = {};
464let runs = {};
465// The runs that ended before their agent ran again (a teammate woken, an agent resumed), each in its
466// own batch: { id, from, to, ran, parentId, calls, usd, priced }.
467let past = [];
468let activityDirty = false;
469// A start more than 30 s after everything before it had ended opens a new batch.
470const BATCH_GAP = 30_000;
471// An agent the list no longer names counts as ended after a minute without a request or a tool call.
472const IDLE = 60_000;
473// One stuck inside a call (a stalled try) counts as ended after ten minutes without a trace.
474const STALLED = 10 * MINUTE;
475
476// ---------- Layout ----------
477
478const SEP = "│";
479const TEXT_CELLS = 6;
480// 68 px: the band fits one line in the app with room to spare.
481const GAUGE = { width: 68, height: 9 };
482const TONES = {
483  calm: { svg: "#3fa66b", text: "green" },
484  // The theme's "yellow" is bright yellow in the app, unreadable on the yellow pill: a deep amber.
485  fast: { svg: "#d9962b", text: "#a8690a" },
486  alert: { svg: "#d64545", text: "red" },
487};
488const TRACK = "rgba(127,127,127,0.2)";
489// Hatching of the gap when using slower than time: grey stripes on the gauge's track.
490const HATCH = { back: "rgba(127,127,127,0.16)", line: "rgba(127,127,127,0.6)" };
491// Desktop pills: a light tint and a slightly stronger outline per block.
492const TINTS = {
493  context: ["rgba(47,104,192,0.10)", "rgba(47,104,192,0.28)"],
494  five_hour: ["rgba(63,166,107,0.13)", "rgba(63,166,107,0.32)"],
495  seven_day: ["rgba(140,100,210,0.13)", "rgba(140,100,210,0.32)"],
496  spend_limit: ["rgba(184,140,40,0.13)", "rgba(184,140,40,0.34)"],
497  calm: ["rgba(27,161,196,0.11)", "rgba(27,161,196,0.30)"],
498  fast: ["rgba(217,150,43,0.14)", "rgba(217,150,43,0.36)"],
499  alert: ["rgba(214,69,69,0.12)", "rgba(214,69,69,0.36)"],
500  cost: ["rgba(184,140,40,0.13)", "rgba(184,140,40,0.34)"],
501  agents: ["rgba(196,80,127,0.11)", "rgba(196,80,127,0.32)"],
502};
503// Small outlined icons in the app, each in its pill's color (the alt text is required: a
504// drawing without one is dropped). The clock before a reset time takes the pill's color too.
505const ICON_SIZE = 16;
506const SMALL_ICON = 14;
507const ICONS = {
508  // Gauge and speech bubble are drawn around y=11.5: half a unit down centres them like the others.
509  gauge: (c) =>
510    `<g transform="translate(0 0.5)"><path d="M3.6 18.5a9.5 9.5 0 1 1 16.8 0" fill="none" stroke="${c}" stroke-width="2.2" stroke-linecap="round"/><path d="M12 14.5l4.3-4.6" fill="none" stroke="${c}" stroke-width="2.2" stroke-linecap="round"/><circle cx="12" cy="14.5" r="1.7" fill="${c}"/></g>`,
511  calendar: (c) =>
512    `<rect x="3" y="4.5" width="18" height="17" rx="3" fill="none" stroke="${c}" stroke-width="2"/><path d="M3 9.5h18M8 2.5v4M16 2.5v4" fill="none" stroke="${c}" stroke-width="2" stroke-linecap="round"/><text x="12" y="19.2" font-size="8.5" font-weight="700" font-family="-apple-system,Helvetica,Arial,sans-serif" text-anchor="middle" fill="${c}">7</text>`,
513  // A clock turning back: the time left before the window starts over.
514  clock: (c) =>
515    `<path d="M4.2 13A8 8 0 1 0 6.6 6.2" fill="none" stroke="${c}" stroke-width="2.1" stroke-linecap="round"/><path d="M3.4 3.6v4.2h4.2" fill="none" stroke="${c}" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 8v4.6l3 1.8" fill="none" stroke="${c}" stroke-width="2.1" stroke-linecap="round"/>`,
516  bolt: (c) => `<path d="M13.2 2 4 13.6h7.2L10.4 22l9.2-11.6h-7.2z" fill="${c}" fill-opacity="0.18" stroke="${c}" stroke-width="2" stroke-linejoin="round"/>`,
517  coin: (c) =>
518    `<circle cx="12" cy="12" r="9.5" fill="${c}" fill-opacity="0.16" stroke="${c}" stroke-width="2"/><path d="M15 8.8c-.5-1-1.6-1.6-3-1.6-1.7 0-3 .9-3 2.2s1.3 1.8 3 2.1 3 .9 3 2.2-1.3 2.3-3 2.3c-1.4 0-2.5-.6-3.1-1.6M12 5.6v1.6M12 16.8v1.6" fill="none" stroke="${c}" stroke-width="1.9" stroke-linecap="round"/>`,
519  // A speech bubble: what the last prompt cost.
520  prompt: (c) =>
521    `<g transform="translate(0 0.5)"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.5 4v-4H6.5A2.5 2.5 0 0 1 4 13.5z" fill="${c}" fill-opacity="0.14" stroke="${c}" stroke-width="2" stroke-linejoin="round"/><path d="M8.5 8.5h7M8.5 11.5h4.5" fill="none" stroke="${c}" stroke-width="2" stroke-linecap="round"/></g>`,
522  // A small robot: subagents at work.
523  agents: (c) =>
524    `<rect x="4" y="7.5" width="16" height="12.5" rx="3.5" fill="${c}" fill-opacity="0.14" stroke="${c}" stroke-width="2"/><path d="M12 7.5V4M2 12.5v3M22 12.5v3" fill="none" stroke="${c}" stroke-width="2" stroke-linecap="round"/><circle cx="12" cy="3.2" r="1.3" fill="${c}"/><circle cx="9" cy="13" r="1.5" fill="${c}"/><circle cx="15" cy="13" r="1.5" fill="${c}"/><path d="M9.5 16.8h5" fill="none" stroke="${c}" stroke-width="1.8" stroke-linecap="round"/>`,
525};
526// Icon color per block: deeper than the pill's tint, readable on light and dark backgrounds.
527const ICON_COLORS = { five_hour: "#3a9a62", seven_day: "#8a5fd0", spend_limit: "#b8892a", calm: "#1b9cbe", fast: "#d9962b", alert: "#d64545", cost: "#b8892a", agents: "#c4507f" };
528const LIMIT_ICONS = { five_hour: "gauge", seven_day: "calendar", spend_limit: "coin" };
529// Columns the terminal may cover at the end of the band.
530const RESERVED_COLUMNS = 2;
531
532export function register(on, options) {
533  const language = options?.language;
534
535  on("session.start", async ($, e, next) => {
536    ticker?.cancel();
537    cacheTicker?.cancel();
538    T = TEXT[await languageOf($, language)];
539    readings = [];
540    limits = { at: 0, list: [] };
541    cache = null;
542    compacted = false;
543    seenTtl = null;
544    savedUsd = 0;
545    team = {};
546    activity = {};
547    waiting = {};
548    runs = {};
549    past = [];
550    lastPrompt = null;
551    lastPrompt5h = null;
552    cacheKey = "";
553    cacheEnv = await cacheEnvOf($);
554    turnsKey = TURNS_PREFIX + (await $.session.id());
555    await restoreTurns($);
556    const usage = await $.session.usage();
557    pushReading(usage.context);
558    cost = usage.cost?.usd ?? null;
559    promptBase = cost;
560    promptBase5h = fiveHourOf(usage.rateLimits);
561    promptReset5h = fiveHourReset(usage.rateLimits);
562    agents = [];
563    agentsKey = "";
564    await refreshAgents($);
565    nameTeam();
566    // On start or reload the local reading may be stale (an idle session): the shared reading
567    // wins, and the local one is published only when none exists yet.
568    await adoptShared($);
569    if (limits.list.length === 0 && usage.rateLimits.length > 0) await shareLimits($, usage.rateLimits);
570    // Every minute: elapsed time moves on, and another session may have measured something newer.
571    ticker = $.clock.every(MINUTE, async () => {
572      await adoptShared($);
573      $.ui.invalidate("ui.render");
574    });
575    // The cache countdown: a redraw only when its text changes.
576    // and the agents running, which start and end between turns.
577    cacheTicker = $.clock.every(10_000, async () => {
578      const key = cacheText(cacheState(await $.clock.now()));
579      const changed = await refreshAgents($);
580      if (key !== cacheKey || changed || activityDirty) {
581        cacheKey = key;
582        activityDirty = false;
583        $.ui.invalidate("ui.render");
584      }
585    });
586    $.ui.invalidate("ui.render");
587    return next(e);
588  });
589
590  on("session.end", async ($, e, next) => {
591    // A real end (exit, or process stopped); /clear, /resume and disconnect keep the tickers.
592    if (e.reason === "prompt_input_exit" || e.reason === "other") {
593      ticker?.cancel();
594      cacheTicker?.cancel();
595    }
596    return next(e);
597  });
598
599  // Each main-loop request: how much of its prompt the cache served (subagents have their own).
600  // A subagent's request goes to its line in the agents card: model, effort, tokens, cost.
601  on("turn.step", async function* ($, e, next) {
602    if (e.agentId) {
603      const id = e.agentId;
604      const at = await $.clock.now();
605      // The tools the last response asked for have run: the agent is back at the model.
606      if (waiting[id]) {
607        waiting[id] = false;
608        touch(id, at, -1);
609      }
610      touch(id, at, 1);
611      let result;
612      try {
613        result = yield* next(e);
614      } finally {
615        try {
616          touch(id, await $.clock.now(), -1);
617        } catch {}
618      }
619      if (result?.usage) recordAgentStep(id, at, result.usage, e.model, e.effort);
620      // The tools the response asks for, by name only: the card never shows their arguments.
621      // Read from the response, the mod never stands in a tool call's way.
622      try {
623        const uses = result?.toolUses ?? [];
624        if (runs[id] && uses.length) {
625          const a = (activity[id] ??= { text: "", calls: 0 });
626          a.text = toolText(uses[uses.length - 1].name);
627          a.calls += uses.length;
628          activityDirty = true;
629          // Still at work while they run, however long.
630          if (result.stopReason === "tool_use") {
631            waiting[id] = true;
632            touch(id, await $.clock.now(), 1);
633          }
634        }
635      } catch {}
636      return result;
637    }
638    const at = await $.clock.now();
639    const result = yield* next(e);
640    if (result?.usage) {
641      recordRequest(at, result.usage, e.model);
642      // The request may have started an agent.
643      await refreshAgents($);
644      $.ui.invalidate("ui.render");
645    }
646    return result;
647  });
648
649  // One context reading after each main turn (not subagents' turns).
650  on("turn.complete", async ($, e, next) => {
651    const result = await next(e);
652    // A subagent's turn: it may have just finished.
653    if (e.agentId) {
654      if (waiting[e.agentId]) {
655        waiting[e.agentId] = false;
656        touch(e.agentId, await $.clock.now(), -1);
657      }
658      await refreshAgents($);
659      nameTeam();
660      await saveTurns($);
661      $.ui.invalidate("ui.render");
662      return result;
663    }
664    try {
665      const usage = await $.session.usage();
666      pushReading(usage.context);
667      if (usage.cost) {
668        cost = usage.cost.usd;
669        if (promptBase !== null && cost >= promptBase) lastPrompt = cost - promptBase;
670        promptBase = cost;
671      }
672      // A window that reset in between gives no share, even when its first reading is not lower.
673      const now5h = fiveHourOf(usage.rateLimits);
674      if (now5h !== null) {
675        const reset = fiveHourReset(usage.rateLimits);
676        const same = promptReset5h === null || reset === null || Math.abs(reset - promptReset5h) < MINUTE;
677        lastPrompt5h = promptBase5h !== null && same && now5h >= promptBase5h ? Math.round((now5h - promptBase5h) * 10) / 10 : null;
678        promptBase5h = now5h;
679        promptReset5h = reset;
680      }
681      await saveTurns($);
682      $.ui.invalidate("ui.render");
683    } catch {
684      // No reading this turn: the line keeps the previous one.
685    }
686    return result;
687  });
688
689  // A compaction of the main conversation: the context drops now, not at the end of the next
690  // prompt. Its size comes from the compaction's result (or, missing, the live figures); the
691  // next request writes a new cache, which is neither expired nor a miss.
692  on("session.compact", async ($, e, next) => {
693    const result = await next(e);
694    if (e.agentId || e.trigger === "precompute" || !result || typeof result.skip === "string") return result;
695    try {
696      const last = readings[readings.length - 1];
697      if (Number.isFinite(result.tokensAfter) && result.tokensAfter > 0 && last?.window > 0) {
698        pushReading({ tokens: result.tokensAfter, window: last.window });
699      } else {
700        pushReading((await $.session.usage()).context);
701      }
702      compacted = true;
703      await saveTurns($);
704      $.ui.invalidate("ui.render");
705    } catch {
706      // No reading: the line catches up at the end of the next prompt.
707    }
708    return result;
709  });
710
711  on("session.measure", async ($, e, next) => {
712    if (e.changed.includes("rateLimits") && e.rateLimits.length > 0) await shareLimits($, e.rateLimits);
713    if (e.cost) cost = e.cost.usd;
714    $.ui.invalidate("ui.render");
715    return next(e);
716  });
717
718  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
719    const props = e.props ?? e;
720    if (props.hasSurvey || (readings.length === 0 && limits.list.length === 0)) return next(e);
721    const elements = $.ui.resolve(e);
722    const now = await $.clock.now();
723    const line = drawLine(elements, e.surface, props.bodyColumns ?? 80, now);
724    // Mods placed after us draw below our line; an empty drawing adds no blank line.
725    const below = await next(e);
726    return isBlank(below) ? line : elements.Box({ flexDirection: "column", children: [line, below] });
727  });
728}
729
730// "en", "fr" or "ru": the language option when it names one, otherwise the environment's locale.
731async function languageOf($, choice) {
732  if (choice === "en" || choice === "fr" || choice === "ru") return choice;
733  let locale = "";
734  try {
735    locale = (await $.env.get("LC_ALL")) || (await $.env.get("LC_MESSAGES")) || (await $.env.get("LANG")) || "";
736  } catch {
737    locale = "";
738  }
739  if (!locale || locale === "C" || locale === "POSIX") {
740    try {
741      locale = Intl.DateTimeFormat().resolvedOptions().locale;
742    } catch {
743      locale = "";
744    }
745  }
746  return /^fr/i.test(locale) ? "fr" : /^ru/i.test(locale) ? "ru" : "en";
747}
748
749// ---------- Turns: readings kept per session ----------
750
751// Restores this session's readings and cache, and deletes sessions idle for more than 8 days.
752async function restoreTurns($) {
753  const now = await $.clock.now();
754  try {
755    for (const key of await $.store.keys()) {
756      if (!key.startsWith(TURNS_PREFIX)) continue;
757      const saved = await $.store.get(key);
758      if (key === turnsKey && saved && Array.isArray(saved.readings)) {
759        readings = saved.readings.filter((r) => r && r.window > 0).slice(-HISTORY);
760        if (saved.cache && Number.isFinite(saved.cache.at)) cache = saved.cache;
761        compacted = saved.compacted === true;
762        if (saved.seenTtl === "5m" || saved.seenTtl === "1h") seenTtl = saved.seenTtl;
763        if (Number.isFinite(saved.saved) && saved.saved >= 0) savedUsd = saved.saved;
764        if (Number.isFinite(saved.lastPrompt)) lastPrompt = saved.lastPrompt;
765        if (Number.isFinite(saved.lastPrompt5h)) lastPrompt5h = saved.lastPrompt5h;
766        if (saved.team && typeof saved.team === "object") team = saved.team;
767      } else if (!saved || !(now - saved.at < TURNS_KEEP_MS)) await $.store.delete(key);
768    }
769  } catch {
770    // Unreadable store: the line starts from scratch.
771  }
772}
773
774async function saveTurns($) {
775  if (!turnsKey) return;
776  try {
777    await $.store.set(turnsKey, { at: await $.clock.now(), readings, cache, compacted, seenTtl, saved: savedUsd, lastPrompt, lastPrompt5h, team });
778  } catch {
779    // Not saved this turn: the bars come back on the next one.
780  }
781}
782
783// ---------- Limits: shared reading ----------
784
785// Keeps this session's reading and publishes it if it is the most recent known.
786async function shareLimits($, list) {
787  const at = await $.clock.now();
788  limits = { at, list: sortLimits(list) };
789  let stored = null;
790  try {
791    stored = await $.store.get(SHARED_KEY);
792  } catch {
793    stored = null;
794  }
795  if (!stored || !(stored.at > at)) await $.store.set(SHARED_KEY, limits);
796  await recordWeek($, at, list);
797}
798
799// Adds a 7-day reading at most every half hour; a new week starts over.
800async function recordWeek($, at, list) {
801  const w = list.find((l) => l.kind === "seven_day");
802  if (!w || !w.resetsAt || !Number.isFinite(w.percentUsed)) return;
803  await loadWeek($);
804  week = week.filter((s) => s.resetsAt === w.resetsAt && s.at <= at && at - s.at <= WEEK_KEEP);
805  const last = week[week.length - 1];
806  if (last && at - last.at < WEEK_GAP) return;
807  week.push({ at, used: w.percentUsed, resetsAt: w.resetsAt });
808  try {
809    await $.store.set(WEEK_KEY, week);
810  } catch {
811    // Unwritable store: the pace waits for a later reading.
812  }
813}
814
815async function loadWeek($) {
816  try {
817    const saved = await $.store.get(WEEK_KEY);
818    if (Array.isArray(saved)) week = saved;
819  } catch {
820    // Unreadable store: keep this session's readings.
821  }
822}
823
824// Takes another session's reading when it is newer than ours.
825async function adoptShared($) {
826  try {
827    const stored = await $.store.get(SHARED_KEY);
828    if (stored && Array.isArray(stored.list) && stored.at > limits.at) limits = { at: stored.at, list: sortLimits(stored.list) };
829  } catch {
830    // Unreadable store: keep the local reading.
831  }
832  await loadWeek($);
833}
834
835function sortLimits(list) {
836  const rank = (kind) => (ORDER.includes(kind) ? ORDER.indexOf(kind) : ORDER.length);
837  return [...list].sort((a, b) => rank(a.kind) - rank(b.kind));
838}
839
840// ---------- Limits: reading one window ----------
841
842// What the line shows of a window: share used, time elapsed, tone, grey detail.
843function gaugeOf(limit, now) {
844  const used = Math.max(0, limit.percentUsed);
845  const resetMs = limit.resetsAt ? Date.parse(limit.resetsAt) : NaN;
846  const span = SPANS[limit.kind];
847  const left = Number.isFinite(resetMs) ? Math.max(0, resetMs - now) : null;
848  const elapsed = span && left !== null ? bound(((span - left) / span) * 100) : null;
849  const pace = elapsed === null ? 0 : used - elapsed;
850  const tone = used >= USED_ALERT || pace > PACE_ALERT ? "alert" : pace > 0 ? "fast" : "calm";
851  // The time left; the 5-hour reset time goes to the clock's tooltip.
852  const when = left !== null ? duration(left) : "";
853  const resetAt = left !== null && limit.kind === "five_hour" ? clockTime(resetMs) : "";
854  return { kind: limit.kind, label: T.labels[limit.kind] ?? limit.kind, used, elapsed, tone, value: T.percent(Math.round(used)), when, resetAt, out: runOutOf(limit, used, now) };
855}
856
857// When the 7-day limit runs out at the recent pace, if before the reset: { at, left, gained, over, resetMs }.
858function runOutOf(limit, used, now) {
859  if (limit.kind !== "seven_day") return null;
860  const resetMs = Date.parse(limit.resetsAt ?? "");
861  if (!Number.isFinite(resetMs)) return null;
862  const start = resetMs - SPANS.seven_day;
863  if (now - start < OUT_MIN_ELAPSED || used < OUT_MIN_USED || used >= 100) return null;
864  // The week's pace decides, as Claude's own usage page does.
865  const rate = used / (now - start);
866  if (!(rate > 0)) return null;
867  const at = now + (100 - used) / rate;
868  if (at >= resetMs) return null;
869  return { at, left: at - now, gained: used, over: now - start, resetMs, recent: recentPace(limit, used, now, resetMs) };
870}
871
872// The pace since the reading closest to a day ago (at least six hours old), shown beside the week's.
873function recentPace(limit, used, now, resetMs) {
874  let base = null;
875  for (const s of week) {
876    if (s.resetsAt !== limit.resetsAt || now - s.at < PACE_MIN_SPAN) continue;
877    if (!base || Math.abs(now - s.at - PACE_SPAN) < Math.abs(now - base.at - PACE_SPAN)) base = s;
878  }
879  if (!base || !(used > base.used)) return null;
880  const at = now + (100 - used) * (now - base.at) / (used - base.used);
881  return { at: at < resetMs ? at : null, gained: used - base.used, over: now - base.at };
882}
883
884// "Fri evening": the hours after midnight belong to the day before ("Fri night").
885function dayPartOf(ms, short = false) {
886  const d = new Date(ms);
887  const h = d.getHours();
888  const part = h < 6 ? 0 : h < 12 ? 1 : h < 18 ? 2 : 3;
889  if (h < 6) return T.night(T.weekdays[(d.getDay() + 6) % 7], T.weekdays[d.getDay()]);
890  return T.dayPart(T.weekdays[d.getDay()], (short ? T.dayPartsShort : T.dayParts)[part]);
891}
892
893function recentLine(r) {
894  if (!r) return "";
895  const gained = T.percent(Math.round(r.gained));
896  return r.at ? T.recentOut(gained, duration(r.over), dayPartOf(r.at), clockTime(r.at)) : T.recentLasts(gained, duration(r.over));
897}
898
899function dateOf(ms) {
900  const d = new Date(ms);
901  return T.date(T.weekdays[d.getDay()], String(d.getDate()).padStart(2, "0"), String(d.getMonth() + 1).padStart(2, "0"));
902}
903
904// 3h02, 42 min, 2d23h (2j23h in French, 2д23ч in Russian).
905function duration(ms) {
906  const minutes = Math.round(ms / MINUTE);
907  if (minutes < 60) return `${minutes} ${T.minute}`;
908  const days = Math.floor(minutes / 1440);
909  const hours = Math.floor((minutes % 1440) / 60);
910  if (days > 0) return `${days}${T.day}${String(hours).padStart(2, "0")}${T.hour}`;
911  return `${hours}${T.hour}${String(minutes % 60).padStart(2, "0")}`;
912}
913
914// 24-hour time in the machine's time zone; UTC when the runtime has no time zone data.
915function clockTime(ms) {
916  try {
917    return new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(ms);
918  } catch {
919    const d = new Date(ms);
920    return `${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")} UTC`;
921  }
922}
923
924// The 5-hour window's share used, or null without one.
925function fiveHourOf(list) {
926  const w = (list ?? []).find((l) => l.kind === "five_hour");
927  return w && Number.isFinite(w.percentUsed) ? w.percentUsed : null;
928}
929
930// When the 5-hour window resets, in ms; null unknown.
931function fiveHourReset(list) {
932  const ms = Date.parse((list ?? []).find((l) => l.kind === "five_hour")?.resetsAt ?? "");
933  return Number.isFinite(ms) ? ms : null;
934}
935
936// 6.5, 12, 0.4: one decimal under 10.
937function decimal(x) {
938  return x >= 10 ? String(Math.round(x)) : String(Math.round(x * 10) / 10);
939}
940
941function bound(percent) {
942  return Math.min(100, Math.max(0, percent));
943}
944
945// ---------- Prompt cache: requests and lifetime ----------
946
947// Names stay literal: the engine lists the variables a module reads.
948async function cacheEnvOf($) {
949  const read = async (get) => {
950    try {
951      return (await get()) || "";
952    } catch {
953      return "";
954    }
955  };
956  return {
957    off: isOn(await read(() => $.env.get("DISABLE_PROMPT_CACHING"))),
958    force5m: isOn(await read(() => $.env.get("FORCE_PROMPT_CACHING_5M"))),
959    ttl: await read(() => $.env.get("CLAUDE_CODE_PROMPT_CACHE_TTL")),
960    enable1h: isOn(await read(() => $.env.get("ENABLE_PROMPT_CACHING_1H"))),
961  };
962}
963
964function isOn(value) {
965  return /^(1|true|yes|on)$/i.test(String(value).trim());
966}
967
968function promptOf(r) {
969  return (r.read ?? 0) + (r.write ?? 0) + (r.fresh ?? 0);
970}
971
972function hitOf(r) {
973  const total = promptOf(r);
974  return total > 0 ? Math.round(((r.read ?? 0) / total) * 100) : 0;
975}
976
977// Notes a main-loop request, names the cause when it missed the cache, learns the lifetime, and
978// adds what the tokens read from the cache saved. The model comes from the usage, else the request.
979function recordRequest(at, usage, model) {
980  const cur = {
981    at,
982    model: usage.model || model || "",
983    read: usage.cache_read_input_tokens ?? 0,
984    write: usage.cache_creation_input_tokens ?? 0,
985    fresh: usage.input_tokens ?? 0,
986    cause: null,
987  };
988  const prev = cache;
989  const afterCompact = compacted;
990  compacted = false;
991  // After a compaction the request writes a new cache: read nothing, yet nothing missed.
992  if (afterCompact) cur.rebuilt = true;
993  if (prev && !afterCompact) {
994    const gap = at - prev.at;
995    const missed = hitOf(cur) < MISS_SHARE && cur.write > MISS_WRITE;
996    // A hit more than 5 minutes after the previous request proves the 1-hour lifetime;
997    // a miss within the hour, same model, prompt not shrunk, says 5 minutes.
998    if (!missed && cur.read > 0 && gap > TTL["5m"]) seenTtl = "1h";
999    else if (missed && gap > TTL["5m"] && gap < TTL["1h"] && cur.model === prev.model && promptOf(cur) >= promptOf(prev)) seenTtl = "5m";
1000    if (missed) cur.cause = cur.model !== prev.model ? "model" : gap >= ttlMs() ? "lapsed" : "prefix";
1001  }
1002  const price = priceOf(cur.model, promptOf(cur));
1003  if (price) savedUsd += (cur.read * (price.input - price.read)) / 1e6;
1004  cache = cur;
1005}
1006
1007// A model id as the price table names it: lowercase, without a "[1m]"-style suffix, a Vertex
1008// "@date", a Bedrock "-v1:0", a trailing date or a provider prefix ("anthropic.", "us.anthropic.",
1009// ".../"). "us.anthropic.claude-sonnet-5-5-20260101-v1:0" → "claude-sonnet-5-5".
1010export function modelId(model) {
1011  let id = String(model ?? "").trim().toLowerCase();
1012  id = id.replace(/\[[^\]]*\]$/, "").replace(/@[^@/]*$/, "").replace(/-v\d+(?::\d+)?$/, "").replace(/-20\d{6}$/, "");
1013  return id.slice(Math.max(id.lastIndexOf("."), id.lastIndexOf("/")) + 1);
1014}
1015
1016// List prices of a model id, for a prompt of that many tokens; null when the table lacks it.
1017function priceOf(model, tokens = 0) {
1018  const id = modelId(model);
1019  if (!Object.prototype.hasOwnProperty.call(PRICES, id)) return null;
1020  const price = PRICES[id];
1021  return price.over && tokens > price.over.at ? price.over : price;
1022}
1023
1024// Price of a cache write, per million tokens, for the lifetime in use.
1025function writePrice(price, ttl) {
1026  return (ttl === TTL["1h"] ? 2 : 1.25) * price.input;
1027}
1028
1029// Claude Code's rules for the main conversation, after what the traffic showed.
1030function ttlMs() {
1031  if (seenTtl) return TTL[seenTtl];
1032  if (cacheEnv.force5m) return TTL["5m"];
1033  if (cacheEnv.ttl === "5m" || cacheEnv.ttl === "1h") return TTL[cacheEnv.ttl];
1034  if (cacheEnv.enable1h) return TTL["1h"];
1035  // A Claude subscription within its plan usage gets 1 hour; usage credits or an API key, 5 minutes.
1036  const plan = limits.list.filter((l) => l.kind === "five_hour" || l.kind === "seven_day");
1037  return plan.length > 0 && plan.every((l) => l.percentUsed < 100) ? TTL["1h"] : TTL["5m"];
1038}
1039
1040// What the cache block shows: { tone, value, detail, urgent, stake, advice, tip }; null when
1041// caching is off. detail follows the value (in yellow when urgent), stake comes after it, dim;
1042// advice is for the terminal only (the app puts it in tip, the bolt's tooltip).
1043function cacheState(now) {
1044  if (cacheEnv.off) return null;
1045  if (compacted) return { tone: "none", value: T.compacted, detail: "", tip: T.tips.compacted };
1046  if (!cache) return { tone: "none", value: "—", detail: "" };
1047  const left = cache.at + ttlMs() - now;
1048  const tokens = readings.length > 0 ? readings[readings.length - 1].tokens : promptOf(cache);
1049  const ttl = ttlMs();
1050  // In dollars, at list prices, for the context the next message reads: from the cache, and
1051  // written again once it lapsed. Null for a model missing from PRICES: tokens only.
1052  const price = priceOf(cache.model, tokens);
1053  const costs = price ? { read: (tokens * price.read) / 1e6, rewrite: (tokens * writePrice(price, ttl)) / 1e6 } : null;
1054  // Expired: say what the next message writes again, and the way out: from 300k a new thread
1055  // (it avoids rewriting the whole context at full price), from 100k /compact. In the app the
1056  // way out goes to the tooltip; the terminal, without one, keeps it on the line.
1057  if (left <= 0) {
1058    const rewrite = T.toRewrite(short(tokens));
1059    const detail = tokens < COMPACT_AT ? "" : costs ? `${rewrite} ${approx(costs.rewrite)}` : rewrite;
1060    const advice = tokens >= LARGE_CONTEXT ? T.newThread : tokens >= COMPACT_AT ? "/compact" : "";
1061    const tip = [T.tips.expired(short(tokens), costs && approx(costs.rewrite))];
1062    if (tokens >= LARGE_CONTEXT) tip.push(T.tips.newThread);
1063    else if (tokens >= COMPACT_AT) tip.push(T.tips.compact);
1064    return { tone: "alert", value: T.expired, detail, advice, tip: tip.join("\n") };
1065  }
1066  const share = hitOf(cache);
1067  // A miss: what writing the cache again cost above a message served by it.
1068  if (cache.cause) {
1069    const cause = T.causes[cache.cause];
1070    const surcharge = price ? ((cache.write ?? 0) * (writePrice(price, ttl) - price.read)) / 1e6 : null;
1071    const extra = surcharge !== null && surcharge >= 0.01 ? ` · +${T.money(surcharge)}` : "";
1072    const tip = T.tips.missed(T.percent(share), cause, short(cache.write ?? 0), surcharge !== null && approx(surcharge));
1073    return { tone: "fast", value: T.percent(share), detail: `${T.missed} · ${cause}${extra}`, tip };
1074  }
1075  const time = left < MINUTE ? T.underMinute : duration(left);
1076  const soon = left < CACHE_SOON;
1077  const expiry = clockTime(cache.at + ttl);
1078  // A cache that served the message (90% or more), or one just rebuilt after a compaction,
1079  // shows its time alone; below, the share first.
1080  const shown = share >= GOOD_HIT || cache.rebuilt ? { value: time, detail: "" } : { value: T.percent(share), detail: time };
1081  // Under 10 minutes: what letting it lapse would cost.
1082  if (soon) {
1083    const stake = T.atStake(costs ? T.money(costs.rewrite) : short(tokens));
1084    const tip = [T.tips.soon(expiry, short(tokens), costs && { read: approx(costs.read), rewrite: approx(costs.rewrite) })];
1085    return { tone: "fast", ...shown, urgent: true, stake, tip: tip.join("\n") };
1086  }
1087  const tip = [T.tips.warm(expiry, ttl === TTL["1h"], seenTtl !== null), T.tips.lastRead(T.percent(share), short(cache.read ?? 0))];
1088  if (costs) {
1089    tip.push(T.tips.costs(approx(costs.read), approx(costs.rewrite)));
1090    if (savedUsd >= 0.01) tip.push(T.tips.saved(approx(savedUsd)));
1091  }
1092  return { tone: "calm", ...shown, urgent: false, tip: tip.join("\n") };
1093}
1094
1095// ---------- Agents ----------
1096
1097// Every agent $.agent.list() returned last: it names the team's entries.
1098let listed = [];
1099
1100// Reads the subagents running now; true when the list changed.
1101async function refreshAgents($) {
1102  let list = [];
1103  try {
1104    list = await $.agent.list();
1105  } catch {
1106    return false;
1107  }
1108  listed = (list ?? []).filter((a) => a && a.id);
1109  const at = await $.clock.now();
1110  for (const a of listed) {
1111    const r = (runs[a.id] ??= { from: at, to: null, busy: 0, ran: false, parentId: a.parentId ?? null, ...baseOf(a.id) });
1112    r.status = a.status;
1113    // Running, waiting on its own agents or not yet started: open. Ended and open again (a teammate
1114    // woken, a finished agent resumed under its id), or first seen idle and now running: a new run.
1115    if (a.status === "running" || a.status === "waiting" || a.status === "pending") {
1116      if (r.to !== null || (!r.ran && a.status === "running")) begin(a.id, r, at);
1117    } else if (r.to === null && !(r.busy > 0 && at - (r.seen ?? at) <= STALLED)) {
1118      // Idle between turns, or ended (not while one of its requests or tool calls runs):
1119      // Its last request's end, when one was seen, rather than this reading's time.
1120      r.to = r.seen !== undefined && r.seen >= r.from ? Math.min(at, r.seen) : at;
1121      activityDirty = true;
1122    }
1123  }
1124  // The agents the list dropped: ended at their last trace once idle for a minute,
1125  // not while a request or a tool call runs (but for a stalled one).
1126  for (const [id, r] of Object.entries(runs)) {
1127    if (r.to !== null || r.seen === undefined || listed.some((a) => a.id === id)) continue;
1128    if ((r.busy > 0 ? at - r.seen > STALLED : at - r.seen > IDLE)) {
1129      r.to = r.seen;
1130      activityDirty = true;
1131    }
1132  }
1133  const running = listed.filter((a) => a.status === "running").map((a) => ({ id: a.id, type: a.type ?? "", description: a.description ?? "" }));
1134  const key = running.map((a) => a.id).join(",");
1135  if (key === agentsKey) return false;
1136  agentsKey = key;
1137  agents = running;
1138  return true;
1139}
1140
1141// One subagent request: its tokens, and their cost at list prices (Haiku 5.5's by the request's
1142// prompt size). Subagents write the 5-minute cache (assumed). A model missing from PRICES counts
1143// tokens only.
1144function recordAgentStep(id, at, usage, model, effort) {
1145  const a = (team[id] ??= { model: "", effort: null, usd: 0, priced: true, input: 0, read: 0, write: 0, output: 0, at, description: "", type: "" });
1146  const u = { input: usage.input_tokens ?? 0, read: usage.cache_read_input_tokens ?? 0, write: usage.cache_creation_input_tokens ?? 0, output: usage.output_tokens ?? 0 };
1147  a.model = usage.model || model || a.model;
1148  if (effort !== undefined && effort !== null) a.effort = effort;
1149  for (const k of ["input", "read", "write", "output"]) a[k] += u[k];
1150  const price = priceOf(a.model, u.input + u.read + u.write);
1151  if (price) a.usd += requestCost(price, u, TTL["5m"]);
1152  else a.priced = false;
1153}
1154
1155// What one request cost: its fresh input, cache reads, cache writes and output.
1156function requestCost(price, u, ttl) {
1157  return (u.input * price.input + u.read * price.read + u.write * writePrice(price, ttl) + u.output * OUTPUT * price.input) / 1e6;
1158}
1159
1160// The description and type of each agent the list still holds.
1161function nameTeam() {
1162  for (const a of listed) {
1163    const t = team[a.id];
1164    if (!t) continue;
1165    if (a.description) t.description = a.description;
1166    if (a.type) t.type = a.type;
1167  }
1168}
1169
1170// "claude-haiku-5-5" → "Haiku 5.5"; an id it cannot read stays as it is.
1171function modelName(model) {
1172  const m = /^claude-([a-z]+)-(\d+(?:-\d+)*)$/.exec(modelId(model));
1173  return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2].replace(/-/g, ".")}` : String(model ?? "");
1174}
1175
1176// A share of the thread's cost, "> 99%" and "< 1%" at the ends.
1177function shareOf(usd, total) {
1178  if (!(total > 0)) return "";
1179  const pct = (usd / total) * 100;
1180  return T.percent(pct < 1 ? "< 1" : pct > 99 ? "> 99" : Math.round(pct));
1181}
1182
1183// Agents in this thread: those counted and those running that have not answered yet.
1184function teamSize() {
1185  const ids = new Set(Object.keys(team));
1186  for (const a of agents) ids.add(a.id);
1187  return ids.size;
1188}
1189
1190// The agents pill's card: the main thread's share, then each model's agents with their efforts
1191// and tokens, the agents still running, and what delegating saved against the main thread's model.
1192function teamTip(now) {
1193  const list = Object.values(team);
1194  const lines = [T.team.title(teamSize(), agents.length)];
1195  // What is known of each agent's cost, even one with an unpriced request: never the main thread's.
1196  const agentsUsd = list.reduce((sum, a) => sum + a.usd, 0);
1197  const mainModel = cache?.model ?? "";
1198  // The main thread: the session's cost less its agents' (its own requests are not all seen here).
1199  if (cost !== null) {
1200    const mainUsd = Math.max(0, cost - agentsUsd);