SLOPSHOPPER

claude-carbon

Track the carbon footprint of your Claude Code sessions, in the terminal and the Claude desktop app

panebandspinnerguardcommandtoast
★ 227v1.18.2MITupdated 2026-10-26gwittebolle/claude-carbon
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · claude-carbon
│ ┃ carbon ✕ › fix the failing auth test and ad╭────────────────────────────────╮ │ ┃ This session: waiting for the │ claude-carbon │ │ ┃ ▄▄ ▀▀▀▀▀ ▄▄ 1 answer · 0 subagent ⏺ Read(src/auth.ts) │ CO₂ now shows for each answer. │ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀ Context 49 % ⎿ Read 6 lines ╰────────────────────────────────╯ │ ┃ ▀▀▀▀▀ The history of your sessions ⏺ Update(src/auth.ts) │ ┃ the full install (see the REA ⎿ 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 │ │ › /carbon-panel │ │ This session: waiting for the first answer ▄▄ ▀▀▀▀▀ ▄▄ 1 answer · 0 subagent ▀▀▀▀▀▀▀▀▀▀▀▀▀ Context 49 % ▀▀▀▀▀ The history of your sessions comes with the full install (see the README). ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
This session: waiting for the first answer ▄▄ ▀▀▀▀▀ ▄▄ 1 answer · 0 subagent ▀▀▀▀▀▀▀▀▀▀▀▀▀ Context 49 % ▀▀▀▀▀ The history of your sessions comes with the full install (see the README). ⟨Claude Code's own drawing⟩
Pane · carbon
This session: waiting for the first answer ▄▄ ▀▀▀▀▀ ▄▄ 1 answer · 0 subagent ▀▀▀▀▀▀▀▀▀▀▀▀▀ Context 49 % ▀▀▀▀▀ The history of your sessions comes with the f (see the README).
README

GitHub stars License: MIT GitHub release npm CI

claude-carbon is an open source Claude Code plugin that tracks the carbon footprint of your sessions: a live CO2 estimate computed locally from your token usage, in the terminal status line and in the Code tab of the Claude desktop app, next to the session's API-equivalent cost. In the desktop app, /carbon-panel opens a pane with a pixel molecule coloured by this session's CO2 against the median of your past sessions, your usage over the period you pick, its warming stripes, and a button for your yearly card.

What claude-carbon does

  • /carbon-panel: a pane in the Claude desktop app with your CO2 molecule, your usage and the warming stripes of your sessions (in a terminal, the session in the band above the prompt). See the mod
  • Adds a live CO2 estimate to the Claude Code status line, and the session's CO2 under the prompt in the Claude desktop app, each next to the session's API-equivalent cost
  • Persists each session to a local SQLite database, so history survives the 30-day transcript purge
  • Backfills historical data from existing ~/.claude transcripts
  • Slash commands: /carbon-report (text), /carbon-card (PNG), /carbon-pr (footprint of a pull request)
  • A README badge with your all-time total, and a public methodology with every factor sourced

About the $ figure. It is an API equivalent: what your session would cost at Anthropic's pay-as-you-go API list prices. On a Pro or Max subscription you do not pay it; it shows the value of what you used, next to its CO2. See How it works.

Install

Two ways, same result. Pick the one that fits you:

Already installed? See Updating.

Option 1: from the Claude desktop app (no terminal)

Illustration of the Claude desktop app with the claude-carbon pane open: a blue pixel molecule, "This session: 8.2 gCO₂ · 0.04× your median", the last 30 days as tiles and warming stripes, a "Get my 2026 card" button, and "This session: 8.2 gCO₂" under the prompt

  1. Open the Code tab of the Claude desktop app and start a session, in any folder. In the mode selector under the prompt box, pick Manual if it shows Auto: auto mode blocks any command that downloads a script and runs it, and Claude would hand you the command instead of running it. Switch back once the install is done.
  2. Paste the message for your system. It works in any language. Claude runs the installer for you and asks before running the command: accept.

macOS or Linux:

   Install claude-carbon for me by running this command:
   curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | bash

Windows:

   Install claude-carbon for me by running this command in PowerShell:
   irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex
  1. Quit the desktop app completely, open it again, and start a new session in the Code tab. Under the prompt you now see This session: 3.6 gCO₂ · $0.12 (Cette session : 3,6 gCO₂ · 0,12 $ in French). /carbon-report and /carbon-card work from there too.

The $ is an API-equivalent cost, not what your subscription bills.

If the install stops

  • macOS opens a window about "command line developer tools". That is git, which the installer needs and a Mac without developer tools does not have yet. Click Install, wait until it finishes (a few minutes), then tell Claude: "Run the claude-carbon install again."
  • "jq is not installed" or "sqlite3 is not installed". Tell Claude: "Install what is missing, then run the claude-carbon install again." Every Mac has sqlite3, and macOS 15 and later also have jq; on an older Mac the installer fetches the official jq itself, checked against its published checksum. On Windows the installer installs both with winget itself, and prints the winget commands only when that fails.
  • Windows says Git Bash is missing. Install Git for Windows (Claude Code needs it on Windows anyway), quit the app completely and reopen it, then ask Claude again in a new session. Claude Code looks for Git Bash when a session starts, so a session open during the Git install still runs without it.

The chat and Cowork tabs are not covered: their sessions run on Anthropic's servers, so nothing reaches your machine to count.

Option 2: from a terminal (developers)

Live CO2 in the Claude Code status line

1. Install (or update):

macOS, Linux, WSL:

curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | bash

Windows (PowerShell), which needs Git for Windows and two packages first - see Windows:

irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex

Or, on any platform with Node.js:

npx claude-carbon

Same command to install and to update to the latest version (all three run the same installer).

Installed from Anthropic's community marketplace and the plugin fails to load? The co2-tracker@claude-community entry is pinned to a release from August 2026 that current Claude Code rejects ("Duplicate hooks file detected"). Run /plugin uninstall co2-tracker@claude-community, then install with one of the commands above.

2. Restart Claude Code. Your CO2 appears in the status line:

claude-carbon ⌥ main | 🟢 Opus 5 ▓▓▓░░░░░░░ 35% | $0.50 · 65gCO₂ | Use 24% ↻13:00

Segments, left to right: project + git branch, model + context window %, API-equivalent session cost + CO2, 5h block usage % + reset time. A 🔥 prefix appears when the sustained burn rate would overshoot 100% of the limit by the end of the 5h block (after a 15 min grace window, only once usage reaches 15%).

Where the CO2 shows up. The status line is a feature of the Claude Code terminal UI. It is displayed only when you run claude in a terminal, including the integrated terminal of VS Code or JetBrains. The IDE extensions' chat panel has no status line at all, so nothing is displayed there even though the hooks still run and your sessions are recorded: /carbon-report covers them. If you use the VS Code panel and want the live CO2, open a terminal in VS Code (` Ctrl+ `) and run claude` from there. The web app (claude.ai/code) runs neither the status line nor the hooks, so nothing is displayed or recorded there. The desktop app does not display the status line either; the plugin's mod draws the CO2 in its Code tab.

5h quota source. The percentage comes directly from Anthropic's /api/oauth/usage endpoint (the same data Claude Code displays in /usage). No heuristic, no token-limit file to seed. Two sources in order:

  1. stdin (preferred): if Claude Code injects rate_limits.five_hour.used_percentage in the statusline JSON, that value is used straight away.
  2. OAuth API fallback: GET https://api.anthropic.com/api/oauth/usage with the bearer token from macOS Keychain, CLAUDE_CODE_OAUTH_TOKEN, or ~/.claude/.credentials.json. Cached 60s in ~/.claude/claude-carbon/oauth-usage.json.

Accurate on every plan, including Max 20x.

3. Use the slash commands:

  • /carbon-report - text report with totals, a car equivalent, this year's share of a 2 t per-person budget, top sessions
  • /carbon-card - generate shareable PNG report cards (drawn with the Chrome or Edge already on your machine, see Dependencies; without one the card opens in your browser)
  • /carbon-update - update to the latest version, whichever way you installed (see Updating)

Example report

<img src="docs/example-card.png" alt="claude-carbon summary card: 1190.3 kg of estimated CO2 from January to September 2026, a bar per month, then 25.3B tokens processed, 94% of them cache reads, a car equivalent, the API-price cost and a yearly projection" width="540">

Generate yours with /carbon-card in Claude Code. The summary and detailed PNGs land in ~/Downloads/claude-carbon/ (the Windows Downloads folder follows the system setting, so a OneDrive-redirected one is honoured) and the folder opens in your file manager, with the card selected on macOS. CLAUDE_CARBON_EXPORT_DIR picks another folder; CLAUDE_CARBON_NO_OPEN=1 skips the opening.

Without Playwright or Chromium there is no PNG and the command still finishes: the summary card is saved as an HTML page in the same folder and opens in your browser, scaled to fit the window, and a screenshot of it does the job. The token count on the card is every token Claude processed, cache reads included, as ccusage counts them; the grey line under it gives the share of cache reads. The card's footer says where to find the tool, claude-carbon sur GitHub / claude-carbon on GitHub, with the address below it.

From the 1st to the 10th of each month the status line ends with 📊 September: 84.2kgCO₂ · /carbon-card: the total of the month just closed, the bar the card draws for it, in the same format as the session figure. It is read from carbon.db once a day while the nudge shows, and kept in ~/.claude/claude-carbon/last-month-total. A month with fewer than 7 days of sessions gets no nudge, so a fresh install is not pushed to share a near-empty card. Generating a card clears it for the month; it goes quiet on its own after the 10th. CLAUDE_CARBON_CARD_NUDGE_UNTIL_DAY moves the cut-off, CLAUDE_CARBON_NO_CARD_NUDGE=1 removes the nudge. Nothing is posted anywhere: sharing stays a human decision.

# Since a specific date
bash ~/code/claude-carbon/scripts/generate-report.sh --since 2026-03-01

# All time
bash ~/code/claude-carbon/scripts/generate-report.sh --all

# A closed period (--until is an exclusive upper bound: this one stops at June 30th)
bash ~/code/claude-carbon/scripts/generate-report.sh --since 2026-01-01 --until 2026-07-01
curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | CLAUDE_CARBON_DIR=~/my-path/claude-carbon bash

The env var has to sit on the bash side of the pipe, not the curl side, or the installer never sees it.

If you run a second Claude Code environment out of its own config directory, e.g.

alias claude-work="CLAUDE_CONFIG_DIR=~/.claude-work claude"

install claude-carbon into that same directory by passing CLAUDE_CONFIG_DIR to the installer:

curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | CLAUDE_CONFIG_DIR=~/.claude-work bash

The status line, the hooks, the database and the /carbon-* commands all live under that config dir, so each environment tracks its own sessions independently. When CLAUDE_CONFIG_DIR is unset everything falls back to ~/.claude as before.

git clone https://github.com/gwittebolle/claude-carbon.git ~/code/claude-carbon
bash ~/code/claude-carbon/scripts/setup.sh
bash ~/code/claude-carbon/scripts/configure-settings.sh

The second script merges the block below into ~/.claude/settings.json (additively: an existing status line or third-party hooks are left alone) and symlinks the /carbon-* commands. To wire it by hand instead, skip it and add:

{
  "statusLine": {
    "type": "command",
    "command": "~/code/claude-carbon/scripts/statusline.sh"
  },
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/code/claude-carbon/scripts/persist-session.sh"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/code/claude-carbon/scripts/persist-on-exit.sh"
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/code/claude-carbon/scripts/safety-rescan.sh"
          }
        ]
      }
    ],
    "SubagentStop": [
      {
        "matcher": ".+",
        "hooks": [
          {
            "type": "command",
            "command": "~/code/claude-carbon/scripts/agent-stop.sh"
          }
        ]
      }
    ]
  }
}

The Stop hook records the session after each turn, and SessionEnd records it once more as it closes, so a last turn interrupted before Stop fired is still counted. The SessionStart one re-scans for sessions both missed (crash, kill) and drives the daily update check the status line reads; without it you are never told a new version exists. SubagentStop records the branch an agent worked on, for /carbon-pr.

Restart Claude Code.

For teams

claude-carbon measures one developer's sessions, locally. If the question comes from your CTO, a client RFP or a CSR committee, the same methodology exists as a hosted layer:

  • Free calculator and per-model factor sheets - the exact versioned factors of this repo, browsable.
  • AI usage report - a self-serve, shareable report of your organisation's real Claude usage (cost, CO2e, water, energy), generated in minutes from an Anthropic admin key. The key is never stored; the methodology annex is citation-ready.
  • TokenClimate - hosted team dashboards. Both sides share this repo's golden vectors, verified weekly in CI.

The only places the OSS points there are a one-line footer in /carbon-report and a small credit on the /carbon-card PNGs. No status-line promo, no email capture: nothing leaves your machine.

PR dev footprint (/carbon-pr)

The number reviewers rarely see is what the PR cost to develop: your local Claude Code sessions while building the branch. /carbon-pr (or scripts/generate-pr-report.sh) sums the recorded sessions of the current branch and posts one sticky comment on its open PR, through your own gh auth. Run it after your push; running it again updates the same comment in place.

**Claude Code carbon report** · developing this PR
124 g CO2e · $3.00 · 180k tokens · 1.5M cache reads · 2 sessions

How the sessions are attributed: the Stop hook stores each session's git branch (read from the transcript), and the report selects project + branch. Sessions recorded before this column existed carry no branch; scripts/backfill.sh repairs them while their transcripts are still on disk (about 30 days). A session whose last folder is a subdirectory of the repo is stored under the subdirectory's name and stays out of the sum. A session that ends on another branch than it started is attributed to where it finished.

How its agents are attributed: an agent counts with its session, unless it worked on a branch of its own. A session on main that sends agents to build a PR in a worktree puts their share on the PR's branch, and the comment then says how many sessions recorded elsewhere it includes. A SubagentStop hook (agent-stop.sh) reads the branch as each agent ends, while its worktree still exists:

  • an agent that ran in a worktree of its own (Claude Code's isolated and workflow agents) counts on the branch that worktree has then, unless Claude Code named it (worktree-agent-*, worktree-wf_*) or it is detached;
  • an agent that ran in the session's folder counts on the worktree its tool calls name in at least half of those that give a place (a command, a file path), and no other as often: absolute paths, ~/, ../ from the repository's folder when the worktree sits beside it, ./ when it sits inside. Never the repository's main folder, nor the session's own. This one is a deduction from the agent's commands.

The hook stores that agent's tokens, CO2 and cost, per model, in an agent_usage table, with the repository and the worktree's folder; the session's own row does not change. The report takes those agents out of their session's branch and adds them to theirs, as long as the session's row holds all its agents (agents_collected = 2: the Stop hook or the rescan read every agent transcript), was written after the agent ended (in a later second) and was recorded with the current method (not a v1 row). An agent that worked in another repository than its session's is not recorded, and one recorded before its repository was moved stays with its session. Forks are left out (they replay their parent's messages), and so is the work a session does itself in a worktree. Only agents that end with this version installed are attributed: nothing is rebuilt for past sessions.

The hook needs Claude Code 2.1.69 or later, the first to give SubagentStop the agent's type (its id and transcript came in 2.0.42); with an older one it records nothing. Claude Code's own agents (prompt suggestions, /btw) are left out. In a session run without --agent their type is empty: the hook's matcher skips them from 2.1.275, the script itself before that. With --agent they carry that agent's name and pass the matcher; the script skips them because their transcript is not one the session's row reads.

The hook runs synchronously, before the agent's result reaches the session: on a Mac, about 0.1 to 0.3 s for most agents, up to about 1 to 2 s for one whose transcript passes 100 MB, since it reads that transcript whole. Claude Code writes transcripts asynchronously: when the agent's final message is not in it yet, the hook reads it again every 0.2 s, for 1 s at most, then counts what is there. A database kept busy for more than about 10 s (a long read elsewhere) loses the record, and the agent counts with its session.

Turning it off is the default: nothing is posted unless you run it. --dry-run previews the comment, --pr <number> targets a specific PR of the repository (one opened from a fork is refused: run the command from the fork's clone instead), and deleting the comment on GitHub is the full cleanup. Once agents of the repository are on record, the report counts, from whichever folder it runs, the sessions of the repository's main folder, of the worktree the branch is checked out in and of the worktrees its agents worked in, even removed since. A branch checked out nowhere whose name sessions of other folders also carry is refused: nothing is posted rather than a figure that may lack them.

How it works

claude-carbon data flow: Claude Code transcripts and status line JSON to a local SQLite database and a CO2 estimate

Three data paths, two levels of accuracy:

ScriptTriggerData sourceSubagentsCache readsAccuracy
backfill.shManual / setupJSONL filesIncludedCounted (8% energy)Best estimate
persist-session.shStop + SessionEnd hooksJSONL filesIncludedCounted (8% energy)Best estimate
statusline.shEvery turn (live)carbon.db rowIncludedCounted (8% energy)One turn late

backfill and persist-session parse the raw JSONL transcripts (main session, subagent files and the transcripts of the agents a workflow starts), applying per-model emission factors. They deduplicate assistant messages by (message.id, requestId), so resumed and compacted sessions are not double-counted (this matches ccusage; without it the token sum inflates roughly 3x). Each session stores its raw token breakdown (input, cache write, cache read, output), which feeds the SQLite database used by reports.

An agent's transcript stops changing once the agent is done, so its totals are kept in ~/.claude/claude-carbon/usage-cache/ (one small file per session, removed by the daily re-scan 45 days after it was last written) and read again only when the file's size, modification or change time, or inode changes (the file a symlink points to). An agent with a line that does not parse yet, cut by a write in progress, is never kept. The main transcript is always read in full. CLAUDE_CARBON_NO_USAGE_CACHE=1 reads everything every time and writes no cache.

Cost is the theoretical API list value (pay-as-you-go), not your subscription price: input, output, cache write, and cache read (0.1x input) at current Anthropic rates, set in data/prices.json. Cache writes are billed per TTL tier, 1.25x input for the 5-minute tier and 2x for the 1-hour one; each session's split is read from its transcript rather than assumed (Claude Code writes at the 1-hour tier). On deduplicated data it matches ccusage.

statusline reads this session's row from carbon.db at each turn, so the CO2 it shows is the session total on the same basis as the reports, one turn behind at most. Before that row exists (first turn, or no database yet) it falls back to an estimate from context_window.total_input_tokens, which is the size of the current context rather than a running total: subagents are invisible to it and every compaction sends it back down. Either way the status line displays, it never feeds the reports.

Surviving the 30-day transcript purge

Claude Code deletes JSONL transcripts after about 30 days, so the SQLite database is the durable record. The Stop and SessionEnd hooks capture each session before its transcript ages out, and a once-a-day background re-scan (SessionStart hook, safety-rescan.sh) catches any session they missed while its transcript still exists, including one whose transcript kept growing after its row was written. Because each row stores raw token counts, recompute.sh regenerates cost and CO2 from `data/factors.

Source 10 files
hooks/mod/register.tsx 1654 lines
1// The claude-carbon mod: the CO2 of each Claude Code answer, at the moment the answer ends.
2//
3// Terminal: at the right end of the turn duration line ("✻ Worked for 4s · done 10:32 PM
4// ... 1,1 gCO₂"). Desktop app, where that line is not drawn: a line under the answer, for
5// unusual answers only. The session total, CO2 and API-price cost, is pinned under the
6// prompt, unless a status line already shows it on this surface (the claude-carbon
7// one, or showSessionTotal off).
8//
9// /carbon-panel opens a pane: the mascot, a pixel CO2 molecule coloured by this session against
10// the median of past sessions, which walks while Claude works, and the warming stripes
11// of past sessions, by session, week or month. The history comes from the file the Stop
12// hook writes next to carbon.db (lib/sessions.ts); the mod never opens the database.
13//
14// One request at a time through turn.step, the formulas, factors and prices of the bash
15// plugin (lib/co2.ts, lib/cost.ts). Writes no database, starts no process, calls no
16// network, never changes what Claude does.
17
18import { atom, read, update } from "claude-code";
19import type { EngineInterface, Register, RenderInputOf } from "claude-code";
20
21import type {
22  AnswerCo2Entry,
23  PaneBlocks,
24  PaneView,
25  SessionTotal,
26} from "../../types";
27import {
28  co2Grams,
29  family,
30  DEFAULT_FACTORS,
31  isExcluded,
32  parseFactors,
33} from "./lib/co2.ts";
34import type { Factors, Family } from "./lib/co2.ts";
35import { costUsd, parsePrices } from "./lib/cost.ts";
36import { DETAIL_SVG_HEIGHT, periodDetail, splitBarSvg, swatchSvg } from "./lib/detail.ts";
37import type { Prices } from "./lib/cost.ts";
38import {
39  answerLine,
40  builtByLabel,
41  REPO_URL,
42  repoLabel,
43  updateText,
44  forTeamLabel,
45  AUTHOR_URL,
46  datePlaceholder,
47  dateInvalid,
48  dayInputValue,
49  teamUrl,
50  apiValueNote,
51  blockTitle,
52  sessionStatsText,
53  changeValue,
54  formatGrams,
55  moneyValue,
56  tileLabel,
57  blockLabel,
58  detailAlt,
59  detailBarLabel,
60  detailCoverage,
61  detailLine,
62  METHODOLOGY_URL,
63  methodologyLabel,
64  detailHover,
65  detailTotalLine,
66  detailWaitText,
67  kindLabel,
68  buildAnswerCo2,
69  cardButtonLabel,
70  cardDraftBusy,
71  cardFillFailed,
72  cardReadyText,
73  changePercent,
74  colorNote,
75  commandDescription,
76  compareText,
77  costText,
78  currentLine,
79  dateLabel,
80  detectLang,
81  emptyRangeText,
82  carValue,
83  carTag,
84  fromLabel,
85  hasLangVariable,
86  isCarbonStatusLine,
87  languageSetting,
88  contextText,
89  moreAgentsText,
90  subagentsAlt,
91  subagentTitle,
92  mascotAlt,
93  scaleAlt,
94  noHistoryText,
95  otherProjectsLine,
96  paneHint,
97  paneTitle,
98  paneUnplaced,
99  projectBarLine,
100  pushHistory,
101  quotaText,
102  rangeLabel,
103  sessionLine,
104  updateHint,
105  cardHint,
106  showLabel,
107  stripesAlt,
108  stripesCaption,
109  stripesWaitText,
110  stripeTitle,
111  toLabel,
112  waitingText,
113  welcomeText,
114} from "./lib/format.ts";
115import type { Lang } from "./lib/format.ts";
116import { lineEntry } from "./lib/lines.ts";
117import {
118  CELL_COLUMNS,
119  CELL_ROWS,
120  classOf,
121  colorOf,
122  miniFaceFrame,
123  moodOf,
124  isStill,
125  faceAt,
126  REACT_MS,
127  SLEEP_AFTER_MS,
128  type Mood,
129  mascotCells,
130  mascotSvg,
131  scaleSvg,
132  SCALE_WIDTH,
133  SCALE_HEIGHT,
134  NEUTRAL,
135  IDLE_STEP_MS,
136  stepMs,
137  subagentsSvg,
138  STRIPES_SVG_HEIGHT,
139  stripesSvg,
140} from "./lib/mascot.ts";
141import type { Stripe } from "./lib/mascot.ts";
142import {
143  barMedian,
144  bars,
145  CURRENT_VERSION,
146  DEFAULT_VIEW,
147  folderName,
148  panelSite,
149  historyPath,
150  newestRelease,
151  updateFlagPaths,
152  statePath,
153  cardNudge,
154  CARD_STAMP_FILE,
155  CARD_NUDGE_UNTIL_DAY,
156  isView,
157  dayKey,
158  parseDay,
159  parseHistory,
160  pastSessions,
161  periodTotal,
162  previousTotal,
163  RANGES,
164  MIN_STRIPES,
165  colourMedian,
166  sessionMedian,
167  windowOf,
168} from "./lib/sessions.ts";
169import type { SessionRow } from "./lib/sessions.ts";
170import { carEquivalence, equivalenceSet } from "./lib/equiv.ts";
171import type { CarEquivalence } from "./lib/equiv.ts";
172
173// One entry per main-loop turn, oldest first, uncounted turns included (co2 null) so
174// a duration line never borrows another turn's figure (lib/lines.ts).
175const answers = atom(
176  { plugin: "claude-carbon", key: "answers" } as const,
177  [] as AnswerCo2Entry[],
178);
179const session = atom(
180  { plugin: "claude-carbon", key: "session" } as const,
181  { grams: 0, usd: 0, turns: 0, tokens: { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 } } as SessionTotal,
182);
183
184const working = atom(
185  { plugin: "claude-carbon", key: "working" } as const,
186  false,
187);
188// In a terminal, /carbon-panel shows the molecule in the band above the prompt: a docked
189// pane would take a whole column for four lines.
190const band = atom(
191  { plugin: "claude-carbon", key: "band" } as const,
192  false,
193);
194const paneView = atom(
195  { plugin: "claude-carbon", key: "view" } as const,
196  DEFAULT_VIEW as PaneView,
197);
198// What the pane shows under the stripes, besides the total: the person's choice
199const DEFAULT_BLOCKS: PaneBlocks = {
200  compare: true,
201  cost: true,
202  equivalence: true,
203  projects: false,
204  detail: false,
205};
206const BLOCKS = ["compare", "cost", "equivalence", "projects", "detail"] as const;
207const paneBlocks = atom(
208  { plugin: "claude-carbon", key: "blocks" } as const,
209  DEFAULT_BLOCKS,
210);
211
212const PANE_ID = "carbon";
213const COMMAND = "carbon-panel";
214// The pane's last range and step, and the blocks shown, kept for the next session
215const VIEW_KEY = "pane.view";
216const BLOCKS_KEY = "pane.blocks";
217// The one-time "/carbon-panel" hint, for someone welcomed before the pane existed
218const HINT_KEY = "pane.hinted";
219
220// The middle of the palette, for a walk with no colour to set its pace
221const NEUTRAL_CLASS = 3;
222// The pane's settings control: a gear (U+2699, text presentation)
223const GEAR = "\u2699";
224// The most stripes drawn, the most recent kept: in the desktop app few enough to stay
225// readable in a side pane (and far under the Svg's 131072 characters), in a terminal
226// what the line holds, up to a Raster's 512 columns.
227const DESKTOP_MAX_STRIPES = 180;
228// The subagent molecules shown under the big one before "+N"
229const MAX_AGENT_MOLECULES = 8;
230// How long the pane says that /carbon-card waits in the prompt
231const CARD_NOTE_MS = 10_000;
232
233// v2: the values of v1 counted background subagents in the answer that started them.
234// The v1 key is left as it is and never read again.
235const HISTORY_KEY = "history.v2";
236const KEEP_ANSWERS = 100;
237
238type History = {
239  values: number[];
240  welcomed: boolean;
241};
242
243// The answer being written: from the main loop's turn.start to its turn.complete.
244type OpenTurn = {
245  turnId: string;
246  grams: number;
247  subagentGrams: number;
248  // Subagents started in the foreground during this turn, and those that made a request
249  spawned: Set<string>;
250  stepped: Set<string>;
251};
252
253function openTurn(turnId: string): OpenTurn {
254  return {
255    turnId,
256    grams: 0,
257    subagentGrams: 0,
258    spawned: new Set(),
259    stepped: new Set(),
260  };
261}
262
263// $.store is shared by every session on the machine and has no conditional write: two
264// sessions ending a turn at once can lose one value of the history. The median tolerates it.
265async function loadHistory($: EngineInterface): Promise<History> {
266  const raw = (await $.store.get(HISTORY_KEY)) as Partial<History> | undefined;
267  const values = Array.isArray(raw?.values)
268    ? raw.values.filter((v): v is number => typeof v === "number" && v > 0)
269    : [];
270  return { values, welcomed: raw?.welcomed === true };
271}
272
273// No terminal draws this session: the duration line never shows here.
274function isRemoteOnly(surfaces: readonly string[]): boolean {
275  return surfaces.length > 0 && !surfaces.includes("terminal");
276}
277
278// /clear and /resume go on in another conversation: its total and per-answer figures start over.
279async function resetSessionState($: EngineInterface) {
280  await $.state.set(
281    { plugin: "claude-carbon", key: "session" },
282    { grams: 0, usd: 0, turns: 0, tokens: { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 } },
283  );
284  await $.state.set({ plugin: "claude-carbon", key: "answers" }, []);
285  $.ui.status(undefined);
286  pane.subagents = 0;
287  pane.agents = new Map();
288  pane.sessionFamily = null;
289  // The pane follows the new conversation: its id is read again at the next drawing, and
290  // the history with it, where the conversation before is now a past session
291  pane.sessionId = null;
292  pane.rows = undefined;
293  pane.mood = null;
294  pane.lastActive = 0;
295  pane.reactUntil = 0;
296}
297
298// The pane. Where the history file is, this session's id (its own row in the file holds
299// a partial total), and the history as last read: undefined until read, null when there
300// is no file to read (no database: an install without the bash hooks). The walk in the
301// terminal: the timer that steps it; the picture follows the clock, so a redraw for
302// another reason (a new request's total) keeps the step.
303const pane: {
304  historyFile: string | null;
305  // The daily release check's flags (a marketplace install's, a clone's), the running
306  // plugin's version, and the newer release the foot names (null when there is none)
307  updateFiles: string[];
308  ownVersion: string | null;
309  newer: string | null;
310  sessionId: string | null;
311  rows: SessionRow[] | null | undefined;
312  walkTimer: { cancel: () => void } | null;
313  // Bumped by every start and stop of the walk: a step begun under an older one stops,
314  // so two chains never run at once and a stopped walk never draws again.
315  walkRun: number;
316  // This session's project, its folder's name, as the hooks will record it
317  project: string;
318  // Until when the pane confirms that /carbon-card waits in the prompt (ms)
319  cardReadyUntil: number;
320  // The row of block switches is open
321  customizing: boolean;
322  // The tile whose note is open, by its (i)
323  openNote: string | null;
324  // The running session as the pane tells it: subagents started, the family of the last
325  // model that answered
326  subagents: number;
327  // Each subagent started this session, in order, and the CO2 of its requests
328  agents: Map<string, number>;
329  sessionFamily: Family | null;
330  // The molecule's mood, since when (its faces loop from there), the last turn's start
331  // or end, and until when it reacts to the last answer (ms)
332  mood: Mood | null;
333  moodSince: number;
334  // The band's site, as its last drawing named it: where the walk blits
335  bandRequestId: string | null;
336  lastActive: number;
337  reactUntil: number;
338} = {
339  historyFile: null,
340  updateFiles: [],
341  ownVersion: null,
342  newer: null,
343  sessionId: null,
344  rows: undefined,
345  walkTimer: null,
346  walkRun: 0,
347  project: "",
348  cardReadyUntil: 0,
349  customizing: false,
350  openNote: null,
351  subagents: 0,
352  agents: new Map<string, number>(),
353  sessionFamily: null,
354  mood: null,
355  moodSince: 0,
356  bandRequestId: null,
357  lastActive: 0,
358  reactUntil: 0,
359};
360
361// The newest release the flags name above this copy's version, null when none does
362async function newerReleaseOf($: EngineInterface): Promise<string | null> {
363  const flags: string[] = [];
364  for (const file of pane.updateFiles) {
365    try {
366      const text = await $.fs.read(file);
367      if (typeof text === "string") flags.push(text);
368    } catch {
369      // No flag yet, or none for this kind of install
370    }
371  }
372  return newestRelease(flags, pane.ownVersion, await $.clock.now());
373}
374
375// The month just closed, for the entry's card hint: its total is read from the history
376// once a day, as the status line reads it; the stamp at every answer, so that a card made
377// in the meantime clears the hint.
378const cardHintState: {
379  stampFile: string | null;
380  untilDay: number;
381  day: string;
382  rows: ReturnType<typeof parseHistory>;
383} = { stampFile: null, untilDay: CARD_NUDGE_UNTIL_DAY, day: "", rows: [] };
384
385async function cardHintOf($: EngineInterface, lang: Lang): Promise<string | null> {
386  if (cardHintState.stampFile === null || pane.historyFile === null) return null;
387  const now = await $.clock.now();
388  if (new Date(now).getDate() > cardHintState.untilDay) return null;
389  const today = new Date(now).toDateString();
390  if (cardHintState.day !== today) {
391    // Kept for the day once read: a file not there yet, or not readable now, is retried
392    try {
393      const text = await $.fs.read(pane.historyFile);
394      if (typeof text !== "string") return null;
395      cardHintState.rows = parseHistory(text);
396      cardHintState.day = today;
397    } catch {
398      return null;
399    }
400  }
401  let stamp: string | null = null;
402  try {
403    const text = await $.fs.read(cardHintState.stampFile);
404    stamp = typeof text === "string" ? text : null;
405  } catch {
406    stamp = null;
407  }
408  const nudge = cardNudge(cardHintState.rows, now, stamp, cardHintState.untilDay);
409  return nudge === null ? null : cardHint(nudge.month, nudge.grams, lang);
410}
411
412async function loadPaneHistory($: EngineInterface) {
413  pane.newer = await newerReleaseOf($);
414  if (pane.historyFile === null) {
415    pane.rows = null;
416    return;
417  }
418  try {
419    const text = await $.fs.read(pane.historyFile);
420    pane.rows = typeof text === "string" ? parseHistory(text) : null;
421  } catch {
422    pane.rows = null;
423  }
424}
425
426async function isPaneOpen($: EngineInterface): Promise<boolean> {
427  try {
428    return (await $.ui.panes()).some((open) => open.id === PANE_ID);
429  } catch {
430    return false;
431  }
432}
433
434// The molecule's class (this session against the median of past sessions, null without
435// enough of them) and mood. A new mood starts its faces from the first.
436async function moleculeNow(
437  $: EngineInterface,
438  now: number,
439): Promise<{ cls: number | null; mood: Mood; isWorking: boolean }> {
440  const total = await read($, session);
441  const isWorking = await read($, working);
442  const m = colourMedian(pastSessions(pane.rows ?? [], pane.sessionId));
443  // Grey, as drawn, until this session counts something
444  const cls = !(total.grams > 0) ? null : classOf(total.grams, m);
445  if (pane.lastActive === 0) pane.lastActive = now;
446  const mood = moodOf({
447    working: isWorking,
448    cls,
449    hasAnswer: total.turns > 0,
450    idleMs: now - pane.lastActive,
451    reacting: now < pane.reactUntil,
452  });
453  if (mood !== pane.mood) {
454    pane.mood = mood;
455    pane.moodSince = now;
456  }
457  return { cls, mood, isWorking };
458}
459
460// The terminal's molecule at `now`: its hop, at the pace of its colour while a turn runs
461// and a slow breath at rest, and its face; with how long that picture holds.
462function terminalMolecule(
463  now: number,
464  mood: Mood,
465  cls: number | null,
466  isWorking: boolean,
467): { frame: string[]; holdMs: number } {
468  const pace = isWorking ? stepMs(cls ?? NEUTRAL_CLASS) : IDLE_STEP_MS;
469  const hop = isStill(mood) || Math.floor(now / pace) % 2 === 0 ? 0 : 1;
470  const { face, holdMs } = faceAt(mood, now - pane.moodSince);
471  return {
472    frame: miniFaceFrame(hop, face),
473    holdMs: Math.min(pace - (now % pace), holdMs),
474  };
475}
476
477// The terminal's whole drawing: this session beside its small molecule, a few rows. In
478// the band above the prompt, or in a pane the desktop app opened on a session the
479// terminal shows too.
480async function terminalSession(
481  $: EngineInterface,
482  e: RenderInputOf<"AbovePrompt", "terminal"> | RenderInputOf<"Pane", "terminal">,
483  lang: Lang,
484) {
485  if (pane.rows === undefined) await loadPaneHistory($);
486  if (pane.sessionId === null) pane.sessionId = await $.session.id().catch(() => null);
487  const total = await read($, session);
488  const now = await $.clock.now();
489  const past = pastSessions(pane.rows ?? [], pane.sessionId);
490  const sm = sessionMedian(past);
491  const cm = colourMedian(past);
492  const { cls, mood, isWorking } = await moleculeNow($, now);
493  const color = colorOf(cls);
494  // A dot per subagent in its molecule's colour, eight then "+N"
495  const agents = [...pane.agents.values()];
496  const dots = agents
497    .slice(0, MAX_AGENT_MOLECULES)
498    .map((grams) => (!(grams > 0) ? NEUTRAL : colorOf(classOf(grams, cm))));
499  const more = agents.length - dots.length;
500  // The context window's fill and the session's API-price value, as the status line
501  // has them
502  const contextUsed = await $.session
503    .usage()
504    .then((u) => u.context.percent ?? null)
505    .catch(() => null);
506  const meta = [
507    ...(contextUsed !== null ? [contextText(contextUsed, lang)] : []),
508    ...(total.usd !== undefined && total.usd > 0 ? [costText(total.usd, lang)] : []),
509  ].join(" · ");
510  const ui = $.ui.resolve(e);
511  const { Box, Text } = ui;
512  return (
513    <Box flexDirection="row">
514      <ui.Raster
515        key="mascot"
516        columns={CELL_COLUMNS}
517        rows={CELL_ROWS}
518        cells={mascotCells(terminalMolecule(now, mood, cls, isWorking).frame, color)}
519      />
520      <Box flexDirection="column" marginLeft={2} flexShrink={1}>
521        <Text bold>
522          {total.grams > 0 ? currentLine(total.grams, sm, lang) : waitingText(lang)}
523        </Text>
524        {total.turns > 0 && (
525          <Text dimColor>
526            {sessionStatsText(total.turns, pane.subagents, pane.sessionFamily, lang)}
527          </Text>
528        )}
529        {dots.length > 0 && (
530          <Box flexDirection="row" columnGap={1}>
531            {dots.map((dot, i) => (
532              <Text key={`agent-${i}`} color={dot}>
533                ●
534              </Text>
535            ))}
536            {more > 0 && <Text dimColor>{moreAgentsText(more)}</Text>}
537          </Box>
538        )}
539        {meta !== "" && <Text dimColor>{meta}</Text>}
540        {/* No history file, or a reference until there is a median of one's own */}
541        {pane.rows === null ? (
542          <Text dimColor>{noHistoryText(lang)}</Text>
543        ) : (
544          sm === null && <Text dimColor>{colorNote(past.length, lang)}</Text>
545        )}
546      </Box>
547    </Box>
548  );
549}
550
551// The kept choice over the defaults: a block added since it was kept takes its default.
552// Null when nothing usable was kept.
553function keptBlocksOf(value: unknown): PaneBlocks | null {
554  if (typeof value !== "object" || value === null) return null;
555  const v = value as Partial<Record<string, unknown>>;
556  const out: PaneBlocks = { ...DEFAULT_BLOCKS };
557  let isAny = false;
558  for (const block of BLOCKS) {
559    const kept = v[block];
560    if (typeof kept === "boolean") {
561      out[block] = kept;
562      isAny = true;
563    }
564  }
565  return isAny ? out : null;
566}
567
568function stopWalk() {
569  pane.walkTimer?.cancel();
570  pane.walkTimer = null;
571  pane.walkRun += 1;
572}
573
574// One step of the terminal's molecule while the pane is open: a blit of the next frame,
575// no redraw, then the next step, at the pace of the current colour while a turn runs and
576// a slow breath at rest. A blit the surface refuses (the pane in a hidden tab) is left be.
577// Each await may see the walk stopped or restarted: the step then ends without drawing.
578async function walkStep($: EngineInterface, run: number) {
579  const isCurrent = () => run === pane.walkRun;
580  try {
581    const surfaces = await $.session.surfaces();
582    const isBand = await read($, band);
583    const isPane = await isPaneOpen($);
584    const goOn = surfaces.includes("terminal") && (isBand || isPane);
585    const isWorking = await read($, working);
586    if (!isCurrent()) return;
587    if (!goOn) {
588      stopWalk();
589      return;
590    }
591    const now = await $.clock.now();
592    const { cls, mood } = await moleculeNow($, now);
593    if (!isCurrent()) return;
594    const shown = terminalMolecule(now, mood, cls, isWorking);
595    const cells = mascotCells(shown.frame, colorOf(cls));
596    const sites = [
597      ...(isPane ? [PANE_ID] : []),
598      ...(isBand && pane.bandRequestId !== null ? [pane.bandRequestId] : []),
599    ];
600    for (const requestId of sites)
601      await $.ui
602        .blit({ requestId, key: "mascot", cells, columns: CELL_COLUMNS, rows: CELL_ROWS })
603        .catch(() => undefined);
604    if (!isCurrent()) return;
605    pane.walkTimer = $.clock.after(Math.max(40, shown.holdMs), () => {
606      void walkStep($, run);
607    });
608  } catch {
609    if (isCurrent()) stopWalk();
610  }
611}
612
613function ensureWalk($: EngineInterface) {
614  if (pane.walkTimer !== null) return;
615  pane.walkRun += 1;
616  const run = pane.walkRun;
617  pane.walkTimer = $.clock.after(IDLE_STEP_MS, () => {
618    void walkStep($, run);
619  });
620}
621
622export const register: Register = (on, options) => {
623  const showPerTurn = options.showPerTurn !== false;
624  // Off where a status line already shows the total (ccstatusline with the
625  // claude-carbon segment): read like the claude-carbon status line, so the
626  // desktop app, which draws no status line, keeps it.
627  const showSessionTotal = options.showSessionTotal !== false;
628  let factors: Factors = DEFAULT_FACTORS;
629  // The car equivalence of the pane, from the same file and set as the reports
630  let factorsJson: unknown = null;
631  let car: CarEquivalence | null = null;
632  // Null when data/prices.json cannot be read: the entry then shows the CO2 alone.
633  let prices: Prices | null = null;
634  let lang: Lang = "fr";
635  let hasCarbonStatusLine = false;
636  let current: OpenTurn | null = null;
637  // Background subagents: their requests count in the session total only, since they
638  // can go on after the answer that started them has ended. Kept across /clear: an
639  // agent started before it may still be running.
640  const background = new Set<string>();
641  // The turn each foreground subagent was started in. Its requests count in that
642  // answer only, even when it outlives it.
643  const owner = new Map<string, string>();
644  // The history as this session last read or wrote it: an answer's figure is ready
645  // before the engine draws its line, with no store read in between.
646  let known: History | null = null;
647  // When each duration line was first drawn, by requestId: only a line first drawn
648  // as a turn ends takes that turn's figure, never one drawn again later. Kept here,
649  // since a drawing never writes $.state.
650  const firstDrawn = new Map<string, number>();
651  const turnOf = new Map<string, string>();
652  const taken = new Set<string>();
653
654  on("session.start", async ($, e, next) => {
655    try {
656      const text = await $.fs.read(`${$.plugin.root}/data/factors.json`);
657      factorsJson = typeof text === "string" ? JSON.parse(text) : null;
658      factors =
659        factorsJson !== null ? parseFactors(factorsJson) : DEFAULT_FACTORS;
660    } catch {
661      factors = DEFAULT_FACTORS;
662    }
663    try {
664      const text = await $.fs.read(`${$.plugin.root}/data/prices.json`);
665      prices = typeof text === "string" ? parsePrices(JSON.parse(text)) : null;
666    } catch {
667      prices = null;
668    }
669    try {
670      const text = await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`);
671      const version: unknown =
672        typeof text === "string" ? JSON.parse(text)?.version : undefined;
673      pane.ownVersion = typeof version === "string" ? version : null;
674    } catch {
675      pane.ownVersion = null;
676    }
677
678    let settings: Record<string, unknown> = {};
679    try {
680      settings = await $.settings.read();
681    } catch {
682      settings = {};
683    }
684    const statusLine = settings.statusLine as { command?: unknown } | undefined;
685    hasCarbonStatusLine = isCarbonStatusLine(statusLine?.command);
686
687    // Same variables, order and sentinels as the reports. The desktop app and a
688    // Windows session usually set none: then the language setting, then French.
689    const envValues = [
690      await $.env.get("CLAUDE_CARBON_LOCALE"),
691      await $.env.get("LC_ALL"),
692      await $.env.get("LC_MESSAGES"),
693      await $.env.get("LANG"),
694    ];
695    lang = detectLang(
696      envValues,
697      hasLangVariable(envValues)
698        ? undefined
699        : languageSetting(settings.language),
700    );
701    car = carEquivalence(factorsJson, equivalenceSet(envValues, lang));
702
703    // Once per machine. A session nothing draws yet is welcomed at its first
704    // answer instead.
705    const history = await loadHistory($);
706    known = history;
707    if (!history.welcomed && e.isInteractive) {
708      const surfaces = await $.session.surfaces();
709      if (surfaces.length > 0) {
710        $.ui.toast(welcomeText(lang), { timeoutMs: 10000 });
711        known = { ...history, welcomed: true };
712        await $.store.set(HISTORY_KEY, known);
713      }
714    }
715
716    // The pane: where its history is, this session's id, the last range and step.
717    try {
718      pane.historyFile = historyPath({
719        db: await $.env.get("CLAUDE_CARBON_DB"),
720        configDir: await $.env.get("CLAUDE_CONFIG_DIR"),
721        home: await $.env.get("HOME"),
722        userProfile: await $.env.get("USERPROFILE"),
723      });
724      const stateEnv = {
725        configDir: await $.env.get("CLAUDE_CONFIG_DIR"),
726        home: await $.env.get("HOME"),
727        userProfile: await $.env.get("USERPROFILE"),
728      };
729      // The same opt-outs and the same last day as the status line's hints
730      const isSet = (v: string | undefined) => v !== undefined && v !== "";
731      pane.updateFiles = isSet(await $.env.get("CLAUDE_CARBON_NO_UPDATE_NOTIFIER"))
732        ? []
733        : updateFlagPaths(stateEnv);
734      cardHintState.stampFile = isSet(await $.env.get("CLAUDE_CARBON_NO_CARD_NUDGE"))
735        ? null
736        : statePath(stateEnv, CARD_STAMP_FILE);
737      // Unset or empty, the 10th; a value that is not a day, as the status line reads it,
738      // never shows the hint
739      const untilText = await $.env.get("CLAUDE_CARBON_CARD_NUDGE_UNTIL_DAY");
740      const untilDay = Number(untilText);
741      cardHintState.untilDay = !isSet(untilText)
742        ? CARD_NUDGE_UNTIL_DAY
743        : Number.isInteger(untilDay) && untilDay > 0
744          ? untilDay
745          : 0;
746      cardHintState.day = "";
747      pane.sessionId = await $.session.id().catch(() => null);
748      pane.project = folderName(e.cwd ?? "");
749      pane.subagents = 0;
750      pane.agents = new Map();
751      pane.sessionFamily = null;
752      pane.rows = undefined;
753      pane.mood = null;
754      pane.lastActive = 0;
755      pane.reactUntil = 0;
756      stopWalk();
757      pane.bandRequestId = null;
758      await $.state.set({ plugin: "claude-carbon", key: "working" }, false);
759      await $.state.set({ plugin: "claude-carbon", key: "band" }, false);
760      const kept = await $.store.get(VIEW_KEY);
761      if (isView(kept)) {
762        await $.state.set({ plugin: "claude-carbon", key: "view" }, kept);
763      }
764      const keptBlocks = keptBlocksOf(await $.store.get(BLOCKS_KEY));
765      if (keptBlocks !== null) {
766        await $.state.set({ plugin: "claude-carbon", key: "blocks" }, keptBlocks);
767      }
768    } catch {
769      // The pane opens on what could be read.
770    }
771
772    // Last: a taken name throws, and nothing above depends on it. Someone welcomed
773    // before the pane existed then hears of /carbon-panel once, if it is ours; a welcome
774    // shown in this very session waits for the next one: one toast at a time.
775    try {
776      await $.command.register({
777        name: COMMAND,
778        description: commandDescription(lang),
779        immediate: true,
780      });
781      if (history.welcomed && e.isInteractive) {
782        const hinted = (await $.store.get(HINT_KEY)) === true;
783        const surfaces = await $.session.surfaces();
784        if (!hinted && surfaces.length > 0) {
785          $.ui.toast(paneHint(lang), { timeoutMs: 10000 });
786          await $.store.set(HINT_KEY, true);
787        }
788      }
789    } catch {
790      // /carbon-panel is someone else's here: the rest of the mod works without it.
791    }
792
793    return next(e);
794  });
795
796  on("agent.spawn", async ($, e, next) => {
797    const started = await next(e);
798    const id = started.agentId;
799    if (id !== undefined) {
800      pane.subagents += 1;
801      pane.agents.set(id, 0);
802      const parent = e.parentAgentId;
803      // A subagent of a background subagent is in the background too, and one of a
804      // foreground subagent belongs to its parent's answer.
805      if (e.background || (parent !== undefined && background.has(parent))) {
806        background.add(id);
807      } else {
808        const turnId =
809          (parent !== undefined ? owner.get(parent) : undefined) ??
810          current?.turnId;
811        if (turnId !== undefined) owner.set(id, turnId);
812        if (current !== null && turnId === current.turnId) {
813          current.spawned.add(id);
814        }
815      }
816    }
817    return started;
818  }).catch(($, e, next) => next(e));
819
820  // A foreground subagent sent to the background (ctrl+b) ends its Agent call with
821  // this status: from then on it counts like one started there.
822  // @ts-ignore TS2589 under TypeScript 5.6, which gives up on this matcher's types
823  on("tool.call", { tool: "Agent" }, async ($, e, next) => {
824    const called = await next(e);
825    const record = called.result as
826      { status?: unknown; agentId?: unknown } | undefined;
827    if (
828      record?.status === "async_launched" &&
829      typeof record.agentId === "string"
830    ) {
831      background.add(record.agentId);
832      current?.spawned.delete(record.agentId);
833    }
834    return called;
835  }).catch(($, e, next) => next(e));
836
837  on("turn.start", async ($, e, next) => {
838    // The main loop alone raises turn.start; a subagent's run does not.
839    current = openTurn(e.turnId);
840    try {
841      pane.lastActive = await $.clock.now();
842      await $.state.set({ plugin: "claude-carbon", key: "working" }, true);
843      if ((await read($, band)) || (await isPaneOpen($))) ensureWalk($);
844    } catch {
845      // The molecule stands still; the turn goes on.
846    }
847    return next(e);
848  });
849
850  on("turn.step", async function* ($, e, next) {
851    const result = yield* next(e);
852    try {
853      const usage = result.usage;
854      if (usage !== null) {
855        const model = usage.model !== "" ? usage.model : e.model;
856        if (!isExcluded(model, factors.excludeModels)) {
857          const grams = co2Grams(usage, model, factors);
858          pane.sessionFamily = family(model);
859          if (e.agentId !== undefined && pane.agents.has(e.agentId))
860            pane.agents.set(e.agentId, (pane.agents.get(e.agentId) ?? 0) + grams);
861          const usd = prices !== null ? costUsd(usage, model, prices) : null;
862          await update($, session, ({ usd: spent, tokens: seen, ...total }) => ({
863            ...total,
864            grams: total.grams + grams,
865            // Counted from the first request of the session on; a total kept without
866            // them stays without them until it starts over
867            ...(seen !== undefined
868              ? {
869                  tokens: {
870                    input: seen.input + usage.input_tokens,
871                    cacheWrite: seen.cacheWrite + usage.cache_creation_input_tokens,
872                    cacheRead: seen.cacheRead + usage.cache_read_input_tokens,
873                    output: seen.output + usage.output_tokens,
874                  },
875                }
876              : {}),
877            // A request with no price, or a total kept from code that counted no cost,
878            // leaves the cost out until the total starts over.
879            ...(usd !== null && spent !== undefined ? { usd: spent + usd } : {}),
880          }));
881          const agent = e.agentId;
882          // Outside an open answer, from a background subagent or from a subagent of
883          // an earlier answer: session total only. An agent no spawn named (the
884          // engine's own work, a compaction) counts in the open answer.
885          if (
886            current !== null &&
887            (agent === undefined ||
888              (!background.has(agent) &&
889                (owner.get(agent) ?? current.turnId) === current.turnId))
890          ) {
891            current.grams += grams;
892            // Work the engine runs on its own (a compaction) is in the answer's
893            // total but is not named as a subagent.
894            if (agent !== undefined && current.spawned.has(agent)) {
895              current.subagentGrams += grams;
896              current.stepped.add(agent);
897            }
898          }
899        }
900      }
901    } catch {
902      // A failed measure never touches the response.
903    }
904    return result;
905  });
906
907  on("turn.complete", async ($, e, next) => {
908    if (e.agentId !== undefined) return next(e);
909    // Before anything that may return early: a module reloaded during the turn has no
910    // open answer, and the molecule must still slow down (its next step reads `working`).
911    // The Stop hook writes the history again after this answer, other sessions running at
912    // the same time included: the pane's next drawing reads it again (and finds it, when
913    // an update installed in this very session had none yet).
914    pane.rows = undefined;
915    try {
916      await $.state.set({ plugin: "claude-carbon", key: "working" }, false);
917    } catch {
918      // The next session start sets it again.
919    }
920    // The molecule reacts to the answer, then falls asleep if nothing follows. On the
921    // desktop nothing else redraws it at those two moments.
922    try {
923      const now = await $.clock.now();
924      pane.lastActive = now;
925      pane.reactUntil = now + REACT_MS;
926      if (await isPaneOpen($)) {
927        $.clock.after(REACT_MS, () => $.ui.invalidate("ui.render"));
928        $.clock.after(SLEEP_AFTER_MS, () => $.ui.invalidate("ui.render"));
929      }
930    } catch {
931      // It keeps its face until the next drawing.
932    }
933    // Only the turn that opened the answer closes it.
934    const done = current;
935    if (done === null || e.turnId !== done.turnId) return next(e);
936    current = null;
937    const isCounted = done.grams > 0;
938    let co2: AnswerCo2Entry["co2"] = null;
939    try {
940      // Written before the engine draws the turn's duration line, which takes the
941      // entry written within a second of its first draw.
942      if (known === null) known = await loadHistory($);
943      co2 = isCounted
944        ? buildAnswerCo2(
945            {
946              grams: done.grams,
947              subagentGrams: done.subagentGrams,
948              subagents: done.stepped.size,
949            },
950            known.values,
951            lang,
952          )
953        : null;
954      const at = await $.clock.now();
955      await update($, answers, (all) =>
956        [
957          ...all,
958          { turnId: done.turnId, durationMs: e.durationMs, at, co2 },
959        ].slice(-KEEP_ANSWERS),
960      );
961    } catch {
962      // The line stays as the engine draws it.
963    }
964    const result = await next(e);
965    try {
966      const history = await loadHistory($);
967      const surfaces = await $.session.surfaces();
968      const remoteOnly = isRemoteOnly(surfaces);
969      const isWelcome = !history.welcomed && surfaces.length > 0;
970      if (isWelcome) {
971        $.ui.toast(welcomeText(lang), { timeoutMs: 10000 });
972      }
973      known = history;
974      if (isCounted || isWelcome) {
975        known = {
976          ...history,
977          ...(isCounted
978            ? { values: pushHistory(history.values, done.grams) }
979            : {}),
980          welcomed: history.welcomed || isWelcome,
981        };
982        await $.store.set(HISTORY_KEY, known);
983      }
984      await update($, session, (total) => ({
985        ...total,
986        turns: total.turns + 1,
987      }));
988      const { value: total } = await $.state.get({
989        plugin: "claude-carbon",
990        key: "session",
991      });
992      // A status line only shows in a terminal.
993      if (
994        ((showSessionTotal && !hasCarbonStatusLine) || remoteOnly) &&
995        total !== undefined &&
996        total.grams > 0
997      ) {
998        // The 5-hour quota the status line also shows, from the engine's own reading
999        const quota = await $.session
1000          .usage()
1001          .then((u) => quotaText(u.rateLimits, lang))
1002          .catch(() => null);
1003        // Then the status line's two hints: a newer release, and the month's card
1004        const newer = await newerReleaseOf($).catch(() => null);
1005        const card = await cardHintOf($, lang).catch(() => null);
1006        $.ui.status(
1007          sessionLine(
1008            total.grams,
1009            lang,
1010            total.usd ?? null,
1011            quota,
1012            newer === null ? null : updateHint(newer),
1013            card,
1014          ),
1015        );
1016      }
1017      // The figure becomes a line under the answer, for unusual answers only.
1018      if (co2 !== null && co2.isUnusual && showPerTurn && remoteOnly) {
1019        return { ...result, text: answerLine(co2) };
1020      }
1021    } catch {
1022      // A failure here leaves the answer as it was.
1023    }
1024    return result;
1025  });
1026
1027  on("session.end", async ($, e, next) => {
1028    // /clear and /resume (and /branch, reported as resume) go on in another conversation.
1029    if (e.reason === "clear" || e.reason === "resume") {
1030      current = null;
1031      await resetSessionState($);
1032    }
1033    return next(e);
1034  });
1035
1036  // /carbon-panel opens the pane, or closes it when it is open. Opened without the keyboard:
1037  // the pane has nothing to type into, and Escape must still interrupt a turn. The
1038  // command is also a skill of the plugin (skills/carbon-panel), so the desktop app lists
1039  // it: its plugin spelling is caught here too, and its text never reaches the model.
1040  on("command.run", { command: [COMMAND, `claude-carbon:${COMMAND}`] }, async ($, e) => {
1041    try {
1042      // Typed in a terminal, the molecule shows in the band above the prompt, on and off:
1043      // a pane would dock as a whole column in fullscreen rendering, for four lines.
1044      // Sent from the desktop app or a phone, it opens the side pane there.
1045      const surfaces = await $.session.surfaces();
1046      if (panelSite(surfaces, e.origin?.kind ?? "") === "band") {
1047        const isOn = !(await read($, band));
1048        if (isOn) {
1049          pane.rows = undefined;
1050          await loadPaneHistory($);
1051        } else {
1052          stopWalk();
1053        }
1054        await $.state.set({ plugin: "claude-carbon", key: "band" }, isOn);
1055        if (isOn) ensureWalk($);
1056        return {};
1057      }
1058      if (await isPaneOpen($)) {
1059        stopWalk();
1060        await $.ui.close({ id: PANE_ID });
1061        return {};
1062      }
1063      pane.rows = undefined;
1064      await loadPaneHistory($);
1065      // The desktop app's side pane
1066      const opened = await $.ui.open({
1067        id: PANE_ID,
1068        title: paneTitle(lang),
1069        closeOnEscape: true,
1070      });
1071      if (!opened.isPlaced) {
1072        $.ui.toast(paneUnplaced(lang), { timeoutMs: 8000 });
1073      } else {
1074        ensureWalk($);
1075      }
1076    } catch {
1077      // Nothing opened: the command ends quietly.
1078    }
1079    return {};
1080  }).catch(() => ({}));
1081
1082  on("ui.close", ($, e, next) => {
1083    if (e.id === PANE_ID) stopWalk();
1084    return next(e);
1085  }).catch(($, e, next) => next(e));
1086
1087  // The band above a terminal's prompt, while /carbon-panel has it on: the session beside
1088  // its molecule, over whatever else the band holds. A survey has the band to itself.
1089  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
1090    try {
1091      if (e.surface !== "terminal" || e.props.hasSurvey || !(await read($, band)))
1092        return next(e);
1093      pane.bandRequestId = e.requestId;
1094      const ours = await terminalSession($, e, lang);
1095      const below = await next(e);
1096      if (below === null || below === undefined) return ours;
1097      const { Box } = $.ui.resolve(e);
1098      return (
1099        <Box flexDirection="column">
1100          {ours}
1101          {below}
1102        </Box>
1103      );
1104    } catch {
1105      return next(e);
1106    }
1107  });
1108
1109  on("ui.render", { component: "Pane", requestId: PANE_ID }, async ($, e, next) => {
1110    try {
1111      if (e.surface === "terminal") return await terminalSession($, e, lang);
1112      if (pane.rows === undefined) await loadPaneHistory($);
1113      if (pane.sessionId === null)
1114        pane.sessionId = await $.session.id().catch(() => null);
1115      const total = await read($, session);
1116      const isWorking = await read($, working);
1117      const view = await read($, paneView);
1118      const now = await $.clock.now();
1119      const past = pastSessions(pane.rows ?? [], pane.sessionId);
1120      const sm = sessionMedian(past);
1121      const cm = colourMedian(past);
1122      // Grey until this session has counted something
1123      const cls = !(total.grams > 0) ? null : classOf(total.grams, cm);
1124      const color = colorOf(cls);
1125      const { mood } = await moleculeNow($, now);
1126      // The running session joins the stripes with its live total, as the newest, at
1127      // the start its own row in the file gives.
1128      const own = (pane.rows ?? []).find((r) => r.id === pane.sessionId);
1129      const isLive = total.grams > 0;
1130      const rows = isLive
1131        ? [
1132            ...past,
1133            {
1134              id: pane.sessionId ?? "current",
1135              at: own?.at ?? now,
1136              grams: total.grams,
1137              version: CURRENT_VERSION,
1138              project: own?.project ?? pane.project,
1139              usd: total.usd ?? null,
1140              model: own?.model ?? "",
1141              // The running session's tokens counted live, or as the file last saw them
1142              tokens: total.tokens ?? own?.tokens ?? null,
1143            },
1144          ]
1145        : past;
1146      // The window the view covers, and one stripe per day, week or month across all of
1147      // it: the stripes always match the period picked.
1148      const w = windowOf(view, rows, now);
1149      const list = pane.rows === null ? [] : bars(rows, w);
1150      // The stripes measure the periods against each other, the one still filling (today,
1151      // this week, this month) left out of the median.
1152      const bm = barMedian(list.slice(0, -1));
1153      // A window longer than the room (years by month) keeps its most recent periods
1154      const shown = list.slice(-DESKTOP_MAX_STRIPES);
1155      const stripes: Stripe[] = shown.map((b) => ({
1156        color: b.grams > 0 ? (bm === null ? NEUTRAL : colorOf(classOf(b.grams, bm))) : null,
1157        title: stripeTitle(b.start, w.step, b.grams, b.sessions, lang),
1158        start: b.start,
1159      }));
1160      const blocks = await read($, paneBlocks);
1161      const setView = (chosen: PaneView) => {
1162        void (async () => {
1163          await $.state.set({ plugin: "claude-carbon", key: "view" }, chosen);
1164          await $.store.set(VIEW_KEY, chosen);
1165        })().catch(() => undefined);
1166      };
1167
1168      const ui = $.ui.resolve(e);
1169      const { Box, Text, Button } = ui;
1170      // The molecule, and under it the colour scale with this session's place on it
1171      const mascot = (
1172        <Box flexDirection="column" alignItems="center">
1173          <ui.Svg
1174            source={mascotSvg({
1175              color,
1176              walking: isWorking,
1177              step: stepMs(cls ?? NEUTRAL_CLASS),
1178              title: mascotAlt(lang),
1179              mood,
1180            })}
1181            alt={mascotAlt(lang)}
1182            width={112}
1183            height={90}
1184            isInteractive
1185          />
1186          <ui.Svg
1187            source={scaleSvg(cls)}
1188            alt={scaleAlt(cls, lang)}
1189            width={SCALE_WIDTH}
1190            height={SCALE_HEIGHT}
1191          />
1192        </Box>
1193      );
1194      // The chosen button in the app's main style, the others dim
1195      const choice = (isChosen: boolean) =>
1196        isChosen ? { variant: "primary" as const } : { dimColor: true };
1197      const sessionText = total.grams > 0 ? currentLine(total.grams, sm, lang) : waitingText(lang);
1198      const hasStripes = pane.rows !== null && stripes.length > 0;
1199      // Periods with sessions in them: below three, the stripes say they are coming
1200      const filledStripes = shown.filter((b) => b.sessions > 0).length;
hooks/mod/lib/co2.ts 109 lines
1// CO2 of one model request, with the same formula, factors and model resolution as the
2// bash plugin (METHODOLOGY.md, scripts/portable-lib.sh: cc_family, cc_params,
3// cc_is_excluded_model). Checked against tests/methodology-vectors*.json by
4// tests/run-mod-tests.mjs. Pure: no Claude Code API, so Node runs it directly.
5
6export type Family = "fable" | "opus" | "sonnet" | "haiku";
7
8export type FamilyFactors = { input: number; output: number };
9
10export type Factors = {
11  models: Record<Family, FamilyFactors>;
12  cacheReadFactor: number;
13  excludeModels: string[];
14};
15
16export type TokenUsage = {
17  input_tokens: number;
18  cache_creation_input_tokens: number;
19  cache_read_input_tokens: number;
20  output_tokens: number;
21};
22
23// The jq fallbacks in CC_JQ_MODEL_DEFS, used when factors.json lacks a value.
24export const DEFAULT_FACTORS: Factors = {
25  models: {
26    fable: { input: 156, output: 3304 },
27    opus: { input: 78, output: 1652 },
28    sonnet: { input: 39, output: 826 },
29    haiku: { input: 10, output: 207 },
30  },
31  cacheReadFactor: 0.08,
32  excludeModels: [],
33};
34
35const FAMILIES: Family[] = ["fable", "opus", "sonnet", "haiku"];
36
37export function family(model: string): Family {
38  const m = model.toLowerCase();
39  if (m.includes("haiku")) return "haiku";
40  if (m.includes("opus")) return "opus";
41  if (/fable|mythos/.test(m)) return "fable";
42  return "sonnet";
43}
44
45function numberOr(value: unknown, fallback: number): number {
46  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
47}
48
49// Reads data/factors.json as parsed JSON, falling back per value like `//` in jq.
50export function parseFactors(json: unknown): Factors {
51  const root = (
52    typeof json === "object" && json !== null ? json : {}
53  ) as Record<string, unknown>;
54  const models = (
55    typeof root.models === "object" && root.models !== null ? root.models : {}
56  ) as Record<string, Record<string, unknown> | undefined>;
57  const resolved = {} as Record<Family, FamilyFactors>;
58  for (const name of FAMILIES) {
59    const entry = models[name] ?? {};
60    resolved[name] = {
61      input: numberOr(entry.input, DEFAULT_FACTORS.models[name].input),
62      output: numberOr(entry.output, DEFAULT_FACTORS.models[name].output),
63    };
64  }
65  const exclude = Array.isArray(root.exclude_models)
66    ? root.exclude_models.filter(
67        (p): p is string => typeof p === "string" && p !== "",
68      )
69    : [];
70  return {
71    models: resolved,
72    cacheReadFactor: numberOr(
73      root.cache_read_factor,
74      DEFAULT_FACTORS.cacheReadFactor,
75    ),
76    excludeModels: exclude,
77  };
78}
79
80// Not an Anthropic Claude model (a local model behind ANTHROPIC_BASE_URL, the
81// "<synthetic>" marker), or matching one of the user's exclude_models patterns.
82export function isExcluded(model: string, patterns: string[]): boolean {
83  if (!/claude/i.test(model)) return true;
84  return patterns.some((pattern) => {
85    try {
86      return new RegExp(pattern, "i").test(model);
87    } catch {
88      return false;
89    }
90  });
91}
92
93// input_tokens is the uncached input; cache writes are a full prefill at the input
94// factor; cache reads at cache_read_factor of it.
95export function co2Grams(
96  usage: TokenUsage,
97  model: string,
98  factors: Factors,
99): number {
100  const f = factors.models[family(model)];
101  const input = usage.input_tokens + usage.cache_creation_input_tokens;
102  return (
103    (input * f.input +
104      usage.cache_read_input_tokens * (f.input * factors.cacheReadFactor) +
105      usage.output_tokens * f.output) /
106    1e6
107  );
108}
109
hooks/mod/lib/cost.ts 174 lines
1// API-price cost of one model request, with the same formula, prices and model resolution
2// as the bash plugin's cost_usd (METHODOLOGY.md, scripts/portable-lib.sh: cc_override,
3// cc_params, CC_AWK_PRICE). Checked against the expected_cost_usd of
4// tests/methodology-vectors*.json by tests/run-mod-tests.mjs. Pure: no Claude Code API,
5// so Node runs it directly.
6
7import { family } from "./co2.ts";
8import type { Family, TokenUsage } from "./co2.ts";
9
10export type FamilyPrices = { input: number; output: number };
11
12// What a model_overrides entry may set; anything left out falls back to the family
13// price and the global multipliers.
14export type PriceOverride = {
15  input?: number;
16  output?: number;
17  cacheWriteMultiplier?: number;
18  cacheWriteMultiplier1h?: number;
19  cacheReadMultiplier?: number;
20};
21
22export type Prices = {
23  models: Record<Family, FamilyPrices>;
24  overrides: Array<[string, PriceOverride]>;
25  cacheWriteMultiplier: number;
26  cacheWriteMultiplier1h: number;
27  cacheReadMultiplier: number;
28};
29
30// One model's prices once resolved, in USD per million tokens.
31export type ModelPrices = {
32  input: number;
33  output: number;
34  cacheWriteMultiplier: number;
35  cacheWriteMultiplier1h: number;
36  cacheReadMultiplier: number;
37};
38
39// The jq fallbacks in CC_JQ_MODEL_DEFS, used when prices.json lacks a value.
40export const DEFAULT_PRICES: Prices = {
41  models: {
42    fable: { input: 10, output: 50 },
43    opus: { input: 4, output: 20 },
44    sonnet: { input: 2, output: 10 },
45    haiku: { input: 0.1, output: 0.5 },
46  },
47  overrides: [],
48  cacheWriteMultiplier: 1.25,
49  cacheWriteMultiplier1h: 2.0,
50  cacheReadMultiplier: 0.1,
51};
52
53const FAMILIES: Family[] = ["fable", "opus", "sonnet", "haiku"];
54
55function isObject(value: unknown): value is Record<string, unknown> {
56  return typeof value === "object" && value !== null && !Array.isArray(value);
57}
58
59function numberOr(value: unknown, fallback: number): number {
60  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
61}
62
63function numberOrUndefined(value: unknown): number | undefined {
64  return typeof value === "number" && Number.isFinite(value)
65    ? value
66    : undefined;
67}
68
69// Reads data/prices.json as parsed JSON, falling back per value like `//` in jq. Null
70// when it is not a JSON object: there is no price to show then.
71export function parsePrices(json: unknown): Prices | null {
72  if (!isObject(json)) return null;
73  const models = isObject(json.models) ? json.models : {};
74  const resolved = {} as Record<Family, FamilyPrices>;
75  for (const name of FAMILIES) {
76    const entry = isObject(models[name]) ? models[name] : {};
77    resolved[name] = {
78      input: numberOr(entry.input, DEFAULT_PRICES.models[name].input),
79      output: numberOr(entry.output, DEFAULT_PRICES.models[name].output),
80    };
81  }
82  const overrides: Array<[string, PriceOverride]> = [];
83  if (isObject(json.model_overrides)) {
84    for (const [key, value] of Object.entries(json.model_overrides)) {
85      if (key.startsWith("_") || !isObject(value)) continue;
86      overrides.push([
87        key.toLowerCase(),
88        {
89          input: numberOrUndefined(value.input),
90          output: numberOrUndefined(value.output),
91          cacheWriteMultiplier: numberOrUndefined(value.cache_write_multiplier),
92          cacheWriteMultiplier1h: numberOrUndefined(
93            value.cache_write_multiplier_1h,
94          ),
95          cacheReadMultiplier: numberOrUndefined(value.cache_read_multiplier),
96        },
97      ]);
98    }
99  }
100  return {
101    models: resolved,
102    overrides,
103    cacheWriteMultiplier: numberOr(
104      json.cache_write_multiplier,
105      DEFAULT_PRICES.cacheWriteMultiplier,
106    ),
107    cacheWriteMultiplier1h: numberOr(
108      json.cache_write_multiplier_1h,
109      DEFAULT_PRICES.cacheWriteMultiplier1h,
110    ),
111    cacheReadMultiplier: numberOr(
112      json.cache_read_multiplier,
113      DEFAULT_PRICES.cacheReadMultiplier,
114    ),
115  };
116}
117
118// A key matches the id exactly, or as a prefix followed by nothing but a dated snapshot
119// suffix "-YYYYMMDD"; a trailing context marker such as "[1m]" is ignored; the longest
120// matching key wins.
121export function priceOverride(
122  model: string,
123  overrides: Array<[string, PriceOverride]>,
124): PriceOverride {
125  const m = model.toLowerCase().replace(/\[[^\]]*\]$/, "");
126  let best: [string, PriceOverride] | undefined;
127  for (const entry of overrides) {
128    const [key] = entry;
129    const isMatch =
130      m === key ||
131      (m.startsWith(`${key}-`) && /^[0-9]{8}$/.test(m.slice(key.length + 1)));
132    if (isMatch && (best === undefined || key.length > best[0].length)) {
133      best = entry;
134    }
135  }
136  return best?.[1] ?? {};
137}
138
139export function modelPrices(model: string, prices: Prices): ModelPrices {
140  const base = prices.models[family(model)];
141  const o = priceOverride(model, prices.overrides);
142  return {
143    input: o.input ?? base.input,
144    output: o.output ?? base.output,
145    cacheWriteMultiplier: o.cacheWriteMultiplier ?? prices.cacheWriteMultiplier,
146    cacheWriteMultiplier1h:
147      o.cacheWriteMultiplier1h ?? prices.cacheWriteMultiplier1h,
148    cacheReadMultiplier: o.cacheReadMultiplier ?? prices.cacheReadMultiplier,
149  };
150}
151
152// cacheWrite1h is the part of the cache writes at the 1-hour tier, clamped to the
153// total write; the rest is priced at the 5-minute tier. turn.step does not split the
154// writes by tier: left out, they are all at the 1-hour tier, the one Claude Code writes
155// at (data/prices.json, _cache_write_multipliers).
156export function costUsd(
157  usage: TokenUsage,
158  model: string,
159  prices: Prices,
160  cacheWrite1h: number = usage.cache_creation_input_tokens,
161): number {
162  const p = modelPrices(model, prices);
163  const write = usage.cache_creation_input_tokens;
164  const write1h = Math.min(Math.max(cacheWrite1h, 0), write);
165  return (
166    (usage.input_tokens * p.input +
167      write1h * (p.input * p.cacheWriteMultiplier1h) +
168      (write - write1h) * (p.input * p.cacheWriteMultiplier) +
169      usage.cache_read_input_tokens * (p.input * p.cacheReadMultiplier) +
170      usage.output_tokens * p.output) /
171    1e6
172  );
173}
174
hooks/mod/lib/detail.ts 191 lines
1// The pane's "Détail" block: a period's tokens, energy and CO2 by kind of token, with two
2// stacked bars (the share of the tokens, the share of the CO2). Pure.
3//
4// The CO2 of each session is the one the hooks stored; it is split over the four kinds
5// with the weights the factors give them (input and cache writes 1, cache reads
6// cache_read_factor, output output/input of the session's family), so the parts add up
7// to what was stored. A session stored with older factors (a frozen month, or a row
8// written before cache reads were recorded) is left out: its stored CO2 no longer matches
9// its tokens under today's factors (2.3 to 6.4 times them in May and June 2026), so
10// today's weights would misplace it. A session that mixed models sits between 0.5 and
11// 2 times the CO2 of its dominant model and splits the same way, as every family weighs
12// its kinds alike: it is kept.
13// The factors start from energy per token (PUE included) and convert it to CO2 with the
14// grid intensity (0.287 kgCO2e/kWh, AWS us-east location-based, data/factors.json
15// _methodology). The stored CO2 is divided back by that intensity to show the energy.
16import { family } from "./co2.ts";
17import { HOVER_LABEL_HEIGHT, hoverLabelSvg } from "./mascot.ts";
18import type { Factors } from "./co2.ts";
19import type { SessionRow, TokenSplit, Window } from "./sessions.ts";
20
21export const KINDS = ["input", "cacheWrite", "cacheRead", "output"] as const;
22export type Kind = (typeof KINDS)[number];
23
24export const GRID_G_PER_WH = 0.287;
25// How far a stored CO2 may sit from its tokens under today's factors and still be split
26const MIN_RATIO = 0.4;
27const MAX_RATIO = 2.5;
28
29export type DetailPart = {
30  kind: Kind;
31  tokens: number;
32  grams: number;
33  wh: number;
34  tokenShare: number;
35  gramShare: number;
36};
37
38export type Detail = {
39  parts: DetailPart[];
40  tokens: number;
41  grams: number;
42  wh: number;
43  // Sessions of the period that carry their tokens, out of all of them
44  sessions: number;
45  sessionsInPeriod: number;
46};
47
48export function weightsOf(model: string, factors: Factors): TokenSplit {
49  const f = factors.models[family(model)];
50  return {
51    input: 1,
52    cacheWrite: 1,
53    cacheRead: factors.cacheReadFactor,
54    output: f.input > 0 ? f.output / f.input : 0,
55  };
56}
57
58// The period's detail, or null when none of its sessions carries its tokens yet
59export function periodDetail(
60  rows: readonly SessionRow[],
61  w: Window,
62  factors: Factors,
63): Detail | null {
64  const inPeriod = rows.filter((r) => r.at >= w.start && r.at <= w.end);
65  const tokens: TokenSplit = { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 };
66  const grams: TokenSplit = { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 };
67  let sessions = 0;
68  for (const r of inPeriod) {
69    if (r.tokens === null) continue;
70    const wt = weightsOf(r.model, factors);
71    const weighted = KINDS.map((k) => r.tokens![k] * wt[k]);
72    const sum = weighted.reduce((s, v) => s + v, 0);
73    // The CO2 these tokens make with today's factors, in grams
74    const expected = (sum * factors.models[family(r.model)].input) / 1e6;
75    if (!(expected > 0)) continue;
76    const ratio = r.grams / expected;
77    if (ratio < MIN_RATIO || ratio > MAX_RATIO) continue;
78    sessions += 1;
79    KINDS.forEach((k, i) => {
80      tokens[k] += r.tokens![k];
81      grams[k] += (r.grams * (weighted[i] ?? 0)) / sum;
82    });
83  }
84  if (sessions === 0) return null;
85  const totalTokens = KINDS.reduce((s, k) => s + tokens[k], 0);
86  const totalGrams = KINDS.reduce((s, k) => s + grams[k], 0);
87  return {
88    parts: KINDS.map((kind) => ({
89      kind,
90      tokens: tokens[kind],
91      grams: grams[kind],
92      wh: grams[kind] / GRID_G_PER_WH,
93      tokenShare: totalTokens > 0 ? tokens[kind] / totalTokens : 0,
94      gramShare: totalGrams > 0 ? grams[kind] / totalGrams : 0,
95    })),
96    tokens: totalTokens,
97    grams: totalGrams,
98    wh: totalGrams / GRID_G_PER_WH,
99    sessions,
100    sessionsInPeriod: inPeriod.length,
101  };
102}
103
104// One colour per kind, in the bars' order, from the author's palette: Amethyst for
105// uncached input, sand and Pierre for the cache written and re-read, Tangerine for the
106// output, which weighs far more than its share of the tokens. A light and a dark step;
107// neighbours stay apart for colour-blind readers on both surfaces, and every part is
108// also named with its figures in the text under the bars.
109export const DETAIL_COLORS = ["#1b0b45", "#c4b8aa", "#7a6e63", "#f55c0f"] as const;
110export const DETAIL_COLORS_DARK = ["#8b7fd6", "#6b6158", "#a89c8e", "#f55c0f"] as const;
111const BAR_HEIGHT = 12;
112// The bar, then a band under it where the hovered part's label shows, a pixel to spare
113const LABEL_TOP = BAR_HEIGHT + 4;
114export const DETAIL_SVG_HEIGHT = LABEL_TOP + HOVER_LABEL_HEIGHT + 1;
115const GAP = 2;
116
117function colorCss(): string {
118  const rule = (colors: readonly string[]) =>
119    colors.map((c, i) => `.k${i}{fill:${c}}`).join("");
120  return `${rule(DETAIL_COLORS)}@media (prefers-color-scheme: dark){${rule(DETAIL_COLORS_DARK)}}`;
121}
122
123// A bar split by `shares` (in the kinds' order) across `width` CSS pixels, 2 px apart.
124// As on the stripes: all the parts first, then their labels, hidden, in a layer above;
125// hovering part i lights it up and shows label i at once in a dark box under the bar,
126// readable on a light or a dark pane. A CSS :hover and the sibling selector, no script,
127// no <title> (the app's own tooltip would show a second label late). Parts under half a
128// pixel are left out; their figures stay in the text under the bars. `name` prefixes
129// the ids and the hover classes, so two bars (and the stripes) never answer each other's
130// hover should the app put the drawings in one document; the colour classes are the
131// swatches' own, with the same rules.
132export function splitBarSvg(
133  shares: readonly number[],
134  labels: readonly string[],
135  width: number,
136  name = "bar",
137): string {
138  const drawn = shares
139    .map((s, i) => ({ s, i }))
140    .filter(({ s }) => s * width >= 0.5);
141  const room = width - GAP * Math.max(0, drawn.length - 1);
142  const total = drawn.reduce((t, d) => t + d.s, 0) || 1;
143  // A part under a pixel is drawn at one; the others share what is left, so the last
144  // part still ends at the bar's right edge
145  const thin = drawn.filter(({ s }) => (room * s) / total < 1);
146  const thick = total - thin.reduce((t, d) => t + d.s, 0) || 1;
147  const left = Math.max(0, room - thin.length);
148  let x = 0;
149  const parts = drawn.map(({ s, i }) => {
150    const wd = (room * s) / total < 1 ? 1 : (left * s) / thick;
151    const part = { i, x, wd };
152    x += wd + GAP;
153    return part;
154  });
155  const rects = parts
156    .map(
157      ({ i, x: px, wd }) =>
158        `<rect id="${name}-p${i}" class="${name}-b k${i}" x="${px.toFixed(2)}" y="0" width="${wd.toFixed(2)}" height="${BAR_HEIGHT}" rx="2"/>`,
159    )
160    .join("");
161  const boxes = parts
162    .map(({ i, x: px, wd }) =>
163      hoverLabelSvg({
164        id: `${name}-t${i}`,
165        cls: `${name}-t`,
166        text: labels[i] ?? "",
167        centre: px + wd / 2,
168        y: LABEL_TOP,
169        width,
170      }),
171    )
172    .join("");
173  const show = parts.map(({ i }) => `#${name}-p${i}:hover~#${name}-t${i}`).join(",");
174  const style =
175    `<style>${colorCss()}.${name}-t{opacity:0;pointer-events:none}.${name}-b:hover{opacity:.75}` +
176    (parts.length > 0 ? `${show}{opacity:1}` : "") +
177    `</style>`;
178  return (
179    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${DETAIL_SVG_HEIGHT}" width="${width}" height="${DETAIL_SVG_HEIGHT}">` +
180    `${style}${rects}${boxes}</svg>`
181  );
182}
183
184// The colour key of a kind, a small rounded square
185export function swatchSvg(index: number): string {
186  return (
187    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10">` +
188    `<style>${colorCss()}</style><rect class="k${index}" x="0" y="0" width="10" height="10" rx="2"/></svg>`
189  );
190}
191
hooks/mod/lib/format.ts 832 lines
1// What an answer's CO2 line says and when it raises its voice. Pure: no Claude Code API, so
2// Node runs it directly (tests/run-mod-tests.mjs).
3
4export type Lang = "fr" | "en";
5
6export type AnswerCo2View = {
7  // "16 gCO₂", or "230 gCO₂ · 14× votre médiane" for an unusual answer
8  main: string;
9  // "dont 3 sous-agents : 22 gCO₂", only on an unusual answer the subagents weighed on
10  sub: string | null;
11  isUnusual: boolean;
12};
13
14export type TurnTotals = {
15  grams: number;
16  subagentGrams: number;
17  subagents: number;
18};
19
20export const HISTORY_SIZE = 200;
21export const MIN_HISTORY = 50;
22// About 1 answer in 27 stands out: above the 97th percentile of the history. The 3x
23// median and the 10 g floor stay as guards: over a flat history the percentile is
24// the median itself.
25export const UNUSUAL_PERCENTILE = 0.97;
26export const UNUSUAL_RATIO = 3;
27export const UNUSUAL_FLOOR_GRAMS = 10;
28export const SUBAGENT_SHARE = 0.1;
29
30const NBSP = " ";
31const UNIT = "CO₂";
32
33// Unset, empty, C and POSIX say nothing about the language.
34function isLocaleValue(value: string | undefined): value is string {
35  return (
36    value !== undefined &&
37    value !== "" &&
38    value !== "C" &&
39    !value.startsWith("C.") &&
40    value !== "POSIX" &&
41    !value.startsWith("POSIX.")
42  );
43}
44
45// Same order and sentinels as detect_equiv_set (scripts/equiv-lib.sh). With no
46// variable set, the language setting decides; with none, French, as in the bash.
47export function detectLang(
48  envValues: Array<string | undefined>,
49  setting?: string,
50): Lang {
51  const value = envValues.find(isLocaleValue);
52  if (value !== undefined) {
53    return value.toLowerCase().startsWith("fr") ? "fr" : "en";
54  }
55  if (setting !== undefined && setting !== "") {
56    return setting.toLowerCase().startsWith("fr") ? "fr" : "en";
57  }
58  return "fr";
59}
60
61// Whether one of the variables decides alone, so nothing else needs to be asked.
62export function hasLangVariable(envValues: Array<string | undefined>): boolean {
63  return envValues.some(isLocaleValue);
64}
65
66// The `language` setting is free text ("Français", "English", "japanese"). It goes
67// to detectLang as a locale would: French when it starts with "fr", English otherwise.
68export function languageSetting(value: unknown): string | undefined {
69  if (typeof value !== "string") return undefined;
70  const text = value.trim();
71  return text === "" ? undefined : text;
72}
73
74function decimal(value: number, digits: number, lang: Lang): string {
75  const text = value.toFixed(digits);
76  return lang === "fr" ? text.replace(".", ",") : text;
77}
78
79// < 0.1 g, one decimal under 10 g, whole grams under 1 kg, then kg with one decimal.
80// Rounding keeps the figure readable; the estimate itself is far less precise than one
81// decimal.
82export function formatGrams(grams: number, lang: Lang): string {
83  if (grams < 0.1) return `<${NBSP}${decimal(0.1, 1, lang)}${NBSP}g${UNIT}`;
84  const tenths = Math.round(grams * 10) / 10;
85  if (tenths < 10) return `${decimal(tenths, 1, lang)}${NBSP}g${UNIT}`;
86  const whole = Math.round(grams);
87  if (whole < 1000) return `${whole}${NBSP}g${UNIT}`;
88  const kilos = Math.round(grams / 100) / 10;
89  return `${decimal(kilos, 1, lang)}${NBSP}kg${UNIT}`;
90}
91
92export function median(values: number[]): number {
93  if (values.length === 0) return 0;
94  const sorted = [...values].sort((a, b) => a - b);
95  const mid = Math.floor(sorted.length / 2);
96  const upper = sorted[mid] ?? 0;
97  return sorted.length % 2 === 1 ? upper : ((sorted[mid - 1] ?? 0) + upper) / 2;
98}
99
100// Linear interpolation between the two closest ranks, q from 0 to 1.
101export function percentile(values: number[], q: number): number {
102  if (values.length === 0) return 0;
103  const sorted = [...values].sort((a, b) => a - b);
104  const rank = (sorted.length - 1) * Math.min(Math.max(q, 0), 1);
105  const lower = Math.floor(rank);
106  const low = sorted[lower] ?? 0;
107  const high = sorted[Math.min(lower + 1, sorted.length - 1)] ?? low;
108  return low + (high - low) * (rank - lower);
109}
110
111// The current answer is compared before it joins the history.
112export function isUnusual(grams: number, history: number[]): boolean {
113  if (history.length < MIN_HISTORY || grams < UNUSUAL_FLOOR_GRAMS) return false;
114  const m = median(history);
115  return (
116    m > 0 &&
117    grams > UNUSUAL_RATIO * m &&
118    grams > percentile(history, UNUSUAL_PERCENTILE)
119  );
120}
121
122export function buildAnswerCo2(
123  turn: TurnTotals,
124  history: number[],
125  lang: Lang,
126): AnswerCo2View {
127  const amount = formatGrams(turn.grams, lang);
128  if (!isUnusual(turn.grams, history))
129    return { main: amount, sub: null, isUnusual: false };
130  const ratio = Math.round(turn.grams / median(history));
131  const main = `${amount} · ${ratio}× ${lang === "fr" ? "votre médiane" : "your median"}`;
132  const share = turn.grams > 0 ? turn.subagentGrams / turn.grams : 0;
133  if (turn.subagents === 0 || share < SUBAGENT_SHARE)
134    return { main, sub: null, isUnusual: true };
135  const n = turn.subagents;
136  const grams = formatGrams(turn.subagentGrams, lang);
137  const sub =
138    lang === "fr"
139      ? `dont ${n} sous-agent${n > 1 ? "s" : ""}${NBSP}: ${grams}`
140      : `incl. ${n} subagent${n > 1 ? "s" : ""}: ${grams}`;
141  return { main, sub, isUnusual: true };
142}
143
144// The single line drawn under the answer where the turn duration line is not
145// (the Desktop app): only ever for an unusual answer.
146export function answerLine(view: AnswerCo2View): string {
147  return view.sub === null
148    ? view.main
149    : `${view.main} · ${view.sub}`;
150}
151
152// Two decimals, as the status line rounds it; "< 0,01 $" under a cent. French puts the
153// sign after the number, English before it.
154export function formatUsd(usd: number, lang: Lang): string {
155  const isTiny = usd < 0.01;
156  const amount = decimal(isTiny ? 0.01 : usd, 2, lang);
157  const money = lang === "fr" ? `${amount}${NBSP}$` : `$${amount}`;
158  return isTiny ? `<${NBSP}${money}` : money;
159}
160
161// The entry pinned under the prompt. The surface already heads it with the plugin's name.
162// The cost is left out when there is none to show (no price list read), never shown as 0.
163// What the status line ends with follows, in its order: the quota, then the hints.
164export function sessionLine(
165  sessionGrams: number,
166  lang: Lang,
167  sessionUsd: number | null = null,
168  ...after: (string | null)[]
169): string {
170  const fr = lang === "fr";
171  const head = fr ? `Cette session${NBSP}:` : "This session:";
172  const total = `${head} ${formatGrams(sessionGrams, lang)}`;
173  const cost = sessionUsd !== null && sessionUsd > 0 ? formatUsd(sessionUsd, lang) : null;
174  return [total, cost, ...after].filter((part) => part !== null).join(" · ");
175}
176
177// The status line's two hints, for the entry: a newer release, and from the 1st to the
178// 10th the month just closed with its total
179export function updateHint(version: string): string {
180  return `⬆ ${version} ${UPDATE_COMMAND}`;
181}
182
183const MONTH_NAMES_FR = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
184const MONTH_NAMES_EN = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
185
186export function cardHint(month: number, grams: number, lang: Lang): string {
187  const fr = lang === "fr";
188  const name = (fr ? MONTH_NAMES_FR : MONTH_NAMES_EN)[month] ?? "";
189  return `📊 ${name}${fr ? `${NBSP}:` : ":"} ${formatGrams(grams, lang)} · /carbon-card`;
190}
191
192export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string };
193
194// The 5-hour window of a subscription as the terminal status line shows it, "Usage 23 %
195// ↻14:00": rounded half to even like its awk printf "%.0f" (22.5 reads 22 on both),
196// capped at 100, the reset in local time. Null off a subscription or before the first
197// response has reported the window.
198export function quotaText(
199  limits: readonly RateLimit[] | undefined,
200  lang: Lang,
201): string | null {
202  const fiveHour = limits?.find((limit) => limit.kind === "five_hour");
203  if (fiveHour === undefined || !Number.isFinite(fiveHour.percentUsed)) return null;
204  const used = Math.max(0, fiveHour.percentUsed);
205  const floor = Math.floor(used);
206  const rounded =
207    used - floor === 0.5 ? (floor % 2 === 0 ? floor : floor + 1) : Math.round(used);
208  const percent = Math.min(100, rounded);
209  const head = lang === "fr" ? `Usage ${percent}${NBSP}%` : `Use ${percent}%`;
210  const reset = fiveHour.resetsAt === undefined ? NaN : Date.parse(fiveHour.resetsAt);
211  if (Number.isNaN(reset)) return head;
212  const d = new Date(reset);
213  const time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
214  return `${head} ↻${time}`;
215}
216
217// Shown once per machine, the same on every surface.
218export function welcomeText(lang: Lang): string {
219  return lang === "fr"
220    ? "Le CO₂ s'affiche maintenant pour chaque réponse."
221    : "CO₂ now shows for each answer.";
222}
223
224export function pushHistory(history: number[], grams: number): number[] {
225  if (!(grams > 0)) return history;
226  return [...history, grams].slice(-HISTORY_SIZE);
227}
228
229// The claude-carbon status line already shows the session total: no second one.
230export function isCarbonStatusLine(command: unknown): boolean {
231  return (
232    typeof command === "string" &&
233    command.includes("claude-carbon") &&
234    command.includes("statusline.sh")
235  );
236}
237
238// ── The /carbon-panel pane ──────────────────────────────────────────────────
239
240// The pane's tab: the plugin's name, as the person asked for it
241export function paneTitle(_lang: Lang): string {
242  return "claude-carbon";
243}
244
245export function commandDescription(lang: Lang): string {
246  return lang === "fr"
247    ? "Votre molécule de CO₂ et l'historique de vos sessions"
248    : "Your CO₂ molecule and the history of your sessions";
249}
250
251// Shown once per machine to someone already welcomed before the pane existed.
252export function paneHint(lang: Lang): string {
253  return lang === "fr"
254    ? "Tapez /carbon-panel pour voir votre molécule et l'historique de vos sessions."
255    : "Type /carbon-panel to see your molecule and the history of your sessions.";
256}
257
258export function paneUnplaced(lang: Lang): string {
259  return lang === "fr"
260    ? `Le panneau carbone ne peut pas s'ouvrir ici${NBSP}: élargissez la fenêtre ou mettez Claude Code à jour.`
261    : "The carbon pane cannot open here: widen the window or update Claude Code.";
262}
263
264// The molecule's line: the session so far, and its ratio to the median of past sessions.
265export function currentLine(
266  grams: number,
267  sessionMedian: number | null,
268  lang: Lang,
269): string {
270  const fr = lang === "fr";
271  const head = fr ? `Cette session${NBSP}:` : "This session:";
272  const total = `${head} ${formatGrams(grams, lang)}`;
273  if (sessionMedian === null || !(sessionMedian > 0) || !(grams > 0)) return total;
274  const r = grams / sessionMedian;
275  const ratio =
276    r >= 10 ? `${Math.round(r)}` : decimal(r, r >= 1 ? 1 : 2, lang);
277  return `${total} · ${ratio}×${NBSP}${fr ? "votre médiane" : "your median"}`;
278}
279
280// Before 10 past sessions the colour compares with a starting reference (0.5 kgCO₂),
281// said simply to someone who just arrived
282export function colorNote(pastSessions: number, lang: Lang): string {
283  return lang === "fr"
284    ? `Couleur provisoire${NBSP}: elle s'ajustera à vos habitudes après 10 sessions (${pastSessions} pour l'instant).`
285    : `Provisional colour: it adjusts to your habits after 10 sessions (${pastSessions} so far).`;
286}
287
288export function noHistoryText(lang: Lang): string {
289  return lang === "fr"
290    ? "L'historique de vos sessions vient avec l'installation complète (voir le README)."
291    : "The history of your sessions comes with the full install (see the README).";
292}
293
294export function emptyRangeText(lang: Lang): string {
295  return lang === "fr"
296    ? "Aucune session sur cette période."
297    : "No session in this period.";
298}
299
300
301const RANGE_LABELS: Record<string, [string, string]> = {
302  "7d": ["7 j", "7 d"],
303  "30d": ["30 j", "30 d"],
304  "1y": ["12 mois", "12 months"],
305  all: ["Tout", "All"],
306  custom: ["Personnalisée", "Custom"],
307};
308function pick(pair: [string, string] | undefined, lang: Lang): string {
309  return pair === undefined ? "" : lang === "fr" ? pair[0] : pair[1];
310}
311
312export function rangeLabel(range: string, lang: Lang): string {
313  return pick(RANGE_LABELS[range], lang);
314}
315
316
317function countOf(n: number, step: string, lang: Lang): string {
318  const fr = lang === "fr";
319  if (step === "week") return fr ? `${n} semaine${n > 1 ? "s" : ""}` : `${n} week${n > 1 ? "s" : ""}`;
320  if (step === "month") return fr ? `${n} mois` : `${n} month${n > 1 ? "s" : ""}`;
321  return `${n} session${n > 1 ? "s" : ""}`;
322}
323
324// Under the stripes: what one stripe is, and the median their colours measure against
325const PER: Record<string, [string, string]> = {
326  day: ["jour", "day"],
327  week: ["semaine", "week"],
328  month: ["mois", "month"],
329};
330// Before three periods with sessions in them there is nothing to colour: the stripes
331// wait, and say what they will show
332export function stripesWaitText(step: string, filled: number, lang: Lang): string {
333  const fr = lang === "fr";
334  const units: Record<string, [string, string]> = {
335    day: ["jours", "days"],
336    week: ["semaines", "weeks"],
337    month: ["mois", "months"],
338  };
339  const unit = pick(units[step], lang);
340  return fr
341    ? `Vos bandes de couleur apparaissent après 3 ${unit} d'usage (${filled} pour l'instant)${NBSP}: une par période, du bleu au rouge selon son CO₂.`
342    : `Your colour stripes show after 3 ${unit} of use (${filled} so far): one per period, blue to red by its CO₂.`;
343}
344
345export function stripesCaption(step: string, stripeMedian: number | null, lang: Lang): string {
346  const fr = lang === "fr";
347  const unit = pick(PER[step], lang);
348  const one = fr ? `une bande par ${unit}` : `one stripe per ${unit}`;
349  if (stripeMedian === null) return one;
350  const per = fr ? ` par ${unit}` : ` a ${unit}`;
351  return `${one} · ${fr ? "médiane" : "median"} ${formatGrams(stripeMedian, lang)}${per}`;
352}
353
354// The period's figure, the pane's main one
355export function periodHeadline(grams: number, lang: Lang): string {
356  return lang === "fr"
357    ? `${formatGrams(grams, lang)} sur la période`
358    : `${formatGrams(grams, lang)} over the period`;
359}
360
361export function sessionsCount(n: number, lang: Lang): string {
362  return countOf(n, "session", lang);
363}
364
365// The custom range's fields: a date typed day first, or as 2026-05-01
366export function datePlaceholder(lang: Lang): string {
367  return lang === "fr" ? "JJ/MM/AAAA" : "DD/MM/YYYY";
368}
369
370export function dateInvalid(lang: Lang): string {
371  return lang === "fr"
372    ? `Date non reconnue${NBSP}: tapez-la comme 01/05/2026.`
373    : "Date not recognised: type it as 01/05/2026.";
374}
375
376// A day key shown back in its field: "01/05/2026"
377export function dayInputValue(key: string): string {
378  const [y, m, d] = key.split("-");
379  return `${d ?? ""}/${m ?? ""}/${y ?? ""}`;
380}
381
382export function fromLabel(lang: Lang): string {
383  return lang === "fr" ? "Du" : "From";
384}
385
386export function toLabel(lang: Lang): string {
387  return lang === "fr" ? "au" : "to";
388}
389
390export function waitingText(lang: Lang): string {
391  return lang === "fr"
392    ? `Cette session${NBSP}: en attente de la première réponse`
393    : "This session: waiting for the first answer";
394}
395
396
397
398const MONTHS_FR = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];
399const MONTHS_EN = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
400
401// A day ("22 août", "Aug 22", with the year when asked), or a month for monthly
402// stripes ("août 2026", "Aug 2026").
403export function dateLabel(
404  ms: number,
405  step: string,
406  lang: Lang,
407  withYear = false,
408): string {
409  const d = new Date(ms);
410  const month = (lang === "fr" ? MONTHS_FR : MONTHS_EN)[d.getMonth()] ?? "";
411  if (step === "month") return `${month}${NBSP}${d.getFullYear()}`;
412  const year = withYear ? `${NBSP}${d.getFullYear()}` : "";
413  return lang === "fr"
414    ? `${d.getDate()}${NBSP}${month}${year}`
415    : `${month}${NBSP}${d.getDate()}${withYear ? `,${NBSP}${d.getFullYear()}` : ""}`;
416}
417
418// A stripe's tooltip in the desktop app.
419export function stripeTitle(
420  start: number,
421  step: string,
422  grams: number,
423  sessions: number,
424  lang: Lang,
425): string {
426  const fr = lang === "fr";
427  const when =
428    step === "week"
429      ? `${fr ? "semaine du" : "week of"} ${dateLabel(start, "session", lang)}`
430      : dateLabel(start, step, lang);
431  const amount = grams > 0 ? formatGrams(grams, lang) : fr ? "aucune session" : "no session";
432  return sessions === 0
433    ? `${when} · ${amount}`
434    : `${when} · ${amount} · ${countOf(sessions, "session", lang)}`;
435}
436
437// Against the same length of time just before: "+12 % par rapport aux 30 jours
438// d'avant". Nothing when there is nothing before to compare with.
439const BEFORE: Record<string, [string, string]> = {
440  "7d": ["aux 7 jours d'avant", "the 7 days before"],
441  "30d": ["aux 30 jours d'avant", "the 30 days before"],
442  "1y": ["aux 12 mois d'avant", "the 12 months before"],
443  custom: ["à la période d'avant", "the period before"],
444};
445
446// The change against the period before, in whole percent; null when there is none
447export function changePercent(grams: number, previous: number): number | null {
448  return previous > 0 ? Math.round(((grams - previous) / previous) * 100) : null;
449}
450export function compareText(
451  grams: number,
452  previous: number,
453  range: string,
454  lang: Lang,
455): string | null {
456  const before = BEFORE[range];
457  const change = changePercent(grams, previous);
458  if (before === undefined || change === null) return null;
459  const sign = change > 0 ? "+" : change < 0 ? "-" : "";
460  const amount = `${sign}${Math.abs(change)}${NBSP}%`;
461  return lang === "fr"
462    ? `${amount} par rapport ${before[0]}`
463    : `${amount} vs ${before[1]}`;
464}
465
466// ── Model families, as the session block names them ─────
467
468const FAMILY_NAMES: Record<string, string> = {
469  fable: "Fable",
470  opus: "Opus",
471  sonnet: "Sonnet",
472  haiku: "Haiku",
473};
474export function familyName(f: string): string {
475  return FAMILY_NAMES[f] ?? f;
476}
477
478
479// The car factor as the pane prints it, the unit spelled out: "142 gCO₂/km, ADEME 2025"
480export function carTag(tag: string): string {
481  return tag.replace(/(\d)\s*g\//, `$1${NBSP}gCO₂/`);
482}
483
484// A subagent's molecule, on hover: "Sous-agent 2 · 12 gCO₂"
485export function subagentTitle(n: number, grams: number, lang: Lang): string {
486  return `${lang === "fr" ? "Sous-agent" : "Subagent"} ${n} · ${formatGrams(grams, lang)}`;
487}
488
489export function subagentsAlt(n: number, lang: Lang): string {
490  return lang === "fr"
491    ? `${n} sous-agent${n > 1 ? "s" : ""} de cette session, une petite molécule chacun, colorée selon son CO₂`
492    : `${n} subagent${n > 1 ? "s" : ""} of this session, a small molecule each, coloured by its CO₂`;
493}
494
495// More subagents than the row shows: "+4"
496export function moreAgentsText(n: number): string {
497  return `+${n}`;
498}
499
500// The context window's fill: "Contexte 42 %"
501export function contextText(percentUsed: number, lang: Lang): string {
502  const p = `${Math.round(percentUsed)}${NBSP}%`;
503  return lang === "fr" ? `Contexte ${p}` : `Context ${p}`;
504}
505
506// The running session, under its line: "12 réponses · 3 sous-agents · Opus"
507export function sessionStatsText(
508  answers: number,
509  subagents: number,
510  f: string | null,
511  lang: Lang,
512): string {
513  const fr = lang === "fr";
514  const parts = [
515    fr ? `${answers} réponse${answers > 1 ? "s" : ""}` : `${answers} answer${answers > 1 ? "s" : ""}`,
516    fr ? `${subagents} sous-agent${subagents > 1 ? "s" : ""}` : `${subagents} subagent${subagents > 1 ? "s" : ""}`,
517  ];
518  if (f !== null) parts.push(familyName(f));
519  return parts.join(" · ");
520}
521
522// The pane's last line: who made it, and the version for a team
523export const AUTHOR_URL = "https://www.linkedin.com/in/gwittebolle/";
524// The French site is at the root; only the English one has a prefix
525export function teamUrl(lang: Lang): string {
526  return lang === "fr"
527    ? "https://tokenclimate.com/?ref=carbon-panel"
528    : "https://tokenclimate.com/en?ref=carbon-panel";
529}
530
531// The project's home: its README says what the tool does and leads to the methodology
532export const REPO_URL = "https://github.com/gwittebolle/claude-carbon";
533export function repoLabel(lang: Lang): string {
534  return lang === "fr" ? "En savoir plus sur claude-carbon" : "Learn more about claude-carbon";
535}
536
537// A newer release, at the top of the foot: what to ask Claude, the plugin command
538// The one command for every install: the skill updates the plugin, the clone, or both
539export const UPDATE_COMMAND = "/carbon-update";
540export function updateText(version: string, lang: Lang): string {
541  return lang === "fr"
542    ? `Version ${version} disponible${NBSP}: tapez ${UPDATE_COMMAND}, puis redémarrez.`
543    : `Version ${version} is out: type ${UPDATE_COMMAND}, then restart.`;
544}
545
546// The foot's two credit lines, a label and a colon each, the link after it
547export function builtByLabel(lang: Lang): string {
548  return lang === "fr" ? `Développé par${NBSP}:` : "Built by:";
549}
550export function forTeamLabel(lang: Lang): string {
551  return lang === "fr" ? `Découvrez la version entreprise${NBSP}:` : "Discover the business version:";
552}
553
554export function blockTitle(kind: "session" | "usage", lang: Lang): string {
555  if (kind === "session") return lang === "fr" ? "Cette session" : "This session";
556  return lang === "fr" ? "Mon usage" : "My usage";
557}
558
559// The tiles at the top of the desktop pane: a label over a figure
560const TILE_LABELS: Record<string, [string, string]> = {
561  period: ["Sur la période", "Over the period"],
562  change: ["Par rapport à avant", "Against before"],
563  sessions: ["Sessions", "Sessions"],
564  cost: ["Valeur au prix API", "API-price value"],
565  car: ["En voiture", "By car"],
566};
567export function tileLabel(kind: string, lang: Lang): string {
568  return pick(TILE_LABELS[kind], lang);
569}
570
571// "+29 %", "-18 %"
572export function changeValue(change: number): string {
573  const sign = change > 0 ? "+" : change < 0 ? "-" : "";
574  return `${sign}${Math.abs(change)}${NBSP}%`;
575}
576
577// "27 616 $", "$27,616", "12,30 $"
578export function moneyValue(usd: number, lang: Lang): string {
579  return costText(usd, lang).replace(lang === "fr" ? " au prix API" : " at API prices", "");
580}
581
582// Under the value tile, so it holds whoever pays: a subscription, an API key, extra
583// usage, or sessions of several kinds. Which session was billed how is not recorded.
584export function apiValueNote(lang: Lang): string {
585  return lang === "fr"
586    ? `Le prix de cet usage facturé à l'API${NBSP}; un abonnement Pro ou Max en couvre tout ou partie.`
587    : "What this usage costs billed through the API; a Pro or Max subscription covers some or all of it.";
588}
589
590// "12,34 $ au prix API", "$12.34 at API prices"
591export function costText(usd: number, lang: Lang): string {
592  // Whole dollars from a thousand up, grouped: "27 608 $", "$27,608"
593  const money =
594    usd >= 1000
595      ? lang === "fr"
596        ? `${thousands(usd, lang)}${NBSP}$`
597        : `$${thousands(usd, lang)}`
598      : formatUsd(usd, lang);
599  return lang === "fr" ? `${money} au prix API` : `${money} at API prices`;
600}
601
602function thousands(n: number, lang: Lang): string {
603  const whole = String(Math.round(n));
604  const sep = lang === "fr" ? NBSP : ",";
605  return whole.replace(/\B(?=(\d{3})+(?!\d))/g, sep);
606}
607
608// "≈ 1 680 km en voiture (142 g/km, ADEME 2025)", the reports' and cards' car line
609export function equivalenceText(
610  grams: number,
611  car: { divisor: number; label: string; tag: string },
612  lang: Lang,
613): string {
614  return `≈${NBSP}${thousands(grams / car.divisor, lang)} ${car.label} (${carTag(car.tag)})`;
615}
616
617// The car tile's figure, the period's CO2 in the locale's unit: "≈ 1 684 km"
618export function carValue(
619  grams: number,
620  car: { divisor: number; unit: string },
621  lang: Lang,
622): string {
623  const distance = grams / car.divisor;
624  // Under a unit, "≈ 0 km" reads as nothing at all
625  if (distance < 1) return `<${NBSP}1 ${car.unit}`;
626  return `≈${NBSP}${thousands(distance, lang)} ${car.unit}`;
627}
628
629// The blocks a person can show or hide in the pane, under the gear
630
631const BLOCK_LABELS: Record<string, [string, string]> = {
632  compare: ["Comparaison", "Comparison"],
633  cost: ["Coût API", "API cost"],
634  equivalence: ["Équivalence", "Equivalence"],
635  projects: ["Projets", "Projects"],
636  detail: ["Détail", "Detail"],
637};
638export function blockLabel(block: string, lang: Lang): string {
639  return pick(BLOCK_LABELS[block], lang);
640}
641
642// ── The "Détail" block: a period's tokens, energy and CO2 by kind of token ──
643const KIND_LABELS: Record<string, [string, string]> = {
644  input: ["Entrée", "Input"],
645  cacheWrite: ["Cache écrit", "Cache write"],
646  cacheRead: ["Cache relu", "Cache read"],
647  output: ["Sortie", "Output"],
648};
649export function kindLabel(kind: string, lang: Lang): string {
650  return pick(KIND_LABELS[kind], lang);
651}
652
653// Above each bar: what it splits
654export function detailBarLabel(bar: "tokens" | "co2", lang: Lang): string {
655  if (bar === "tokens") return "Tokens";
656  return lang === "fr" ? `${UNIT} et énergie` : `${UNIT} and energy`;
657}
658
659// 820, 12k, 371M, then billions with one decimal: 25,3 Md / 25.3B
660export function formatTokens(n: number, lang: Lang): string {
661  if (n >= 999.5e6)
662    return lang === "fr" ? `${decimal(n / 1e9, 1, lang)}${NBSP}Md` : `${decimal(n / 1e9, 1, lang)}B`;
663  const space = lang === "fr" ? NBSP : "";
664  if (n >= 999.5e3) return `${Math.round(n / 1e6)}${space}M`;
665  if (n >= 1000) return `${Math.round(n / 1e3)}${space}k`;
666  return String(Math.round(n));
667}
668
669// Wh under a kWh, then kWh (one decimal under 100), then MWh
670export function formatWh(wh: number, lang: Lang): string {
671  if (wh < 999.5) return `${Math.round(wh)}${NBSP}Wh`;
672  const kwh = wh / 1000;
673  if (kwh < 99.95) return `${decimal(kwh, 1, lang)}${NBSP}kWh`;
674  if (kwh < 999.5) return `${Math.round(kwh)}${NBSP}kWh`;
675  return `${decimal(kwh / 1000, 1, lang)}${NBSP}MWh`;
676}
677
678// One decimal, "98,4 %", "< 0,1 %" for a share that is there but rounds to nothing,
679// "0 %" for none; a space before % in both languages, as the rest of the pane writes it
680export function formatShare(share: number, lang: Lang): string {
681  if (share <= 0) return `0${NBSP}%`;
682  if (share < 0.0005) return `<${NBSP}${decimal(0.1, 1, lang)}${NBSP}%`;
683  return `${decimal(share * 100, 1, lang)}${NBSP}%`;
684}
685
686// Under a kind's name: "23,8 Md tokens (98,4 %) · 21,6 kWh · 6,2 kgCO₂ (60,9 %)"
687export function detailLine(
688  part: { tokens: number; tokenShare: number; wh: number; grams: number; gramShare: number },
689  lang: Lang,
690): string {
691  return (
692    `${formatTokens(part.tokens, lang)} tokens (${formatShare(part.tokenShare, lang)}) · ` +
693    `${formatWh(part.wh, lang)} · ${formatGrams(part.grams, lang)} (${formatShare(part.gramShare, lang)})`
694  );
695}
696
697export function detailTotalLine(
698  total: { tokens: number; wh: number; grams: number },
699  lang: Lang,
700): string {
701  return (
702    `Total${lang === "fr" ? NBSP : ""}: ${formatTokens(total.tokens, lang)} tokens · ` +
703    `${formatWh(total.wh, lang)} · ${formatGrams(total.grams, lang)}`
704  );
705}
706
707// What a hovered part of a bar says: its kind, its figures on that bar, its share
708// "Cache relu · 23,9 Md tokens · 98,4 %", "Cache relu · 535 kWh · 153,5 kgCO₂ · 60,9 %"
709export function detailHover(
710  part: { kind: string; tokens: number; tokenShare: number; wh: number; grams: number; gramShare: number },
711  bar: "tokens" | "co2",
712  lang: Lang,
713): string {
714  const name = kindLabel(part.kind, lang);
715  return bar === "tokens"
716    ? `${name} · ${formatTokens(part.tokens, lang)} tokens · ${formatShare(part.tokenShare, lang)}`
717    : `${name} · ${formatWh(part.wh, lang)} · ${formatGrams(part.grams, lang)} · ${formatShare(part.gramShare, lang)}`;
718}
719
720// The methodology, straight from the detail
721export const METHODOLOGY_URL =
722  "https://github.com/gwittebolle/claude-carbon/blob/main/METHODOLOGY.md#the-panes-detail-by-kind-of-token";
723export function methodologyLabel(lang: Lang): string {
724  return lang === "fr" ? "Lire la méthodologie" : "Read the methodology";
725}
726
727// When some sessions of the period are left out: stored with older factors, or the
728// running one before its first answer
729export function detailCoverage(n: number, total: number, lang: Lang): string {
730  return lang === "fr"
731    ? `Sur ${n} des ${total} sessions de la période${NBSP}: les autres ont été enregistrées avec des facteurs plus anciens.`
732    : `Over ${n} of the period's ${total} sessions: the others were recorded with older factors.`;
733}
734
735// Before the hook has written the tokens by kind: after the next answer
736export function detailWaitText(lang: Lang): string {
737  return lang === "fr"
738    ? "Le détail s'affichera après la prochaine réponse."
739    : "The detail shows after the next answer.";
740}
741
742export function detailAlt(bar: "tokens" | "co2", lang: Lang): string {
743  return lang === "fr"
744    ? `Répartition ${bar === "tokens" ? "des tokens" : `du ${UNIT}`} entre entrée, cache écrit, cache relu et sortie`
745    : `Share of the ${bar === "tokens" ? "tokens" : UNIT} between input, cache write, cache read and output`;
746}
747
748export function showLabel(lang: Lang): string {
749  return lang === "fr" ? "Afficher" : "Show";
750}
751
752
753// The button that puts /carbon-card in the prompt, for the person to send. The card
754// covers the calendar year so far, whatever range the pane shows: the label says which.
755export function cardButtonLabel(year: number, lang: Lang): string {
756  return lang === "fr" ? `Obtenir ma carte ${year}` : `Get my ${year} card`;
757}
758
759// After the button filled the prompt: what is there and what to do
760export function cardReadyText(lang: Lang): string {
761  return lang === "fr"
762    ? `/carbon-card est dans le prompt${NBSP}: appuyez sur Entrée pour créer la carte.`
763    : "/carbon-card is in the prompt: press Enter to make the card.";
764}
765
766// The prompt could not take it (a dialog is open, or no prompt box here)
767export function cardFillFailed(lang: Lang): string {
768  return lang === "fr"
769    ? `Le prompt n'a pas pu recevoir /carbon-card${NBSP}: tapez-le vous-même.`
770    : "The prompt could not take /carbon-card: type it yourself.";
771}
772
773// When the prompt already holds a draft, the button leaves it alone and says why
774export function cardDraftBusy(lang: Lang): string {
775  return lang === "fr"
776    ? `Le prompt contient déjà un brouillon${NBSP}: videz-le pour obtenir la carte.`
777    : "The prompt already holds a draft: clear it to get the card.";
778}
779
780
781function percent(share: number): string {
782  const p = Math.round(share * 100);
783  return p < 1 ? `<${NBSP}1${NBSP}%` : `${p}${NBSP}%`;
784}
785
786
787// A project as a bar, left-aligned so bars compare whatever the font:
788// "███████ 41 % carbonara · 103,5 kgCO₂"
789export function projectBarLine(
790  project: string,
791  grams: number,
792  share: number,
793  lang: Lang,
794): string {
795  const name = project === "" ? (lang === "fr" ? "sans projet" : "no project") : project;
796  const bar = "█".repeat(Math.max(1, Math.round(share * 16)));
797  return `${bar} ${percent(share)} ${name} · ${formatGrams(grams, lang)}`;
798}
799
800// The rest after the projects listed
801export function otherProjectsLine(count: number, grams: number, share: number, lang: Lang): string {
802  const fr = lang === "fr";
803  const label = fr
804    ? `${count} autre${count > 1 ? "s" : ""} projet${count > 1 ? "s" : ""}`
805    : `${count} other project${count > 1 ? "s" : ""}`;
806  return `${label} · ${formatGrams(grams, lang)} · ${percent(share)}`;
807}
808
809export function mascotAlt(lang: Lang): string {
810  return lang === "fr"
811    ? "Molécule de CO₂ en pixels, colorée selon cette session par rapport à votre médiane, du bleu (en dessous) au rouge (au-dessus)"
812    : "Pixel CO₂ molecule, coloured by this session against your median, from blue (below) to red (above)";
813}
814
815// The scale under the molecule, read aloud: where this session sits on it
816export function scaleAlt(cls: number | null, lang: Lang): string {
817  const fr = lang === "fr";
818  if (cls === null)
819    return fr
820      ? "Échelle des couleurs, du bleu (sous votre médiane) au rouge (au-dessus)"
821      : "Colour scale, from blue (under your median) to red (over it)";
822  return fr
823    ? `Échelle des couleurs, du bleu au rouge : cette session est en ${cls + 1}e position sur 8`
824    : `Colour scale, from blue to red: this session is ${cls + 1} of 8`;
825}
826
827export function stripesAlt(lang: Lang): string {
828  return lang === "fr"
829    ? "Une bande par période, la plus ancienne à gauche, du bleu (sous la médiane) au rouge (au-dessus)"
830    : "One stripe per period, oldest on the left, from blue (below the median) to red (above)";
831}
832
hooks/mod/lib/lines.ts 52 lines
1// Which turn a duration line belongs to. Pure: no Claude Code API, so Node runs it
2// directly (tests/run-mod-tests.mjs).
3
4// A line drawn for the first time this close to a turn's end is that turn's line.
5// Measured in a terminal: 8 to 13 ms from turn.complete to the line's first draw.
6export const BIND_WINDOW_MS = 1000;
7
8// What the rules read of an entry. An entry written before the turnId was kept has
9// none and is never bound.
10export type LineEntry = {
11  turnId?: unknown;
12  at?: unknown;
13};
14
15export type LineMatch<E> = { entry: E; isNew: boolean } | undefined;
16
17// The lines bound so far: each line's turn, and the turns that have a line.
18export type Bound = {
19  turnOf: ReadonlyMap<string, string>;
20  taken: ReadonlySet<string>;
21};
22
23// 1. The entry of the turn this line was bound to. 2. A line drawn for the first
24// time within a second of a turn's end takes the newest such entry no line holds
25// yet. 3. None: the engine's line stays as it is. The duration is never compared:
26// after background agents the line can show another one than the turn reports.
27export function lineEntry<E extends LineEntry>(
28  entries: readonly E[],
29  requestId: string,
30  firstDrawnAt: number,
31  bound: Bound,
32): LineMatch<E> {
33  const turnId = bound.turnOf.get(requestId);
34  if (turnId !== undefined) {
35    const entry = entries.find((x) => x.turnId === turnId);
36    return entry === undefined ? undefined : { entry, isNew: false };
37  }
38  for (let i = entries.length - 1; i >= 0; i -= 1) {
39    const entry = entries[i];
40    if (
41      entry !== undefined &&
42      typeof entry.turnId === "string" &&
43      typeof entry.at === "number" &&
44      !bound.taken.has(entry.turnId) &&
45      Math.abs(firstDrawnAt - entry.at) < BIND_WINDOW_MS
46    ) {
47      return { entry, isNew: true };
48    }
49  }
50  return undefined;
51}
52
hooks/mod/lib/mascot.ts 620 lines
1// The mascot, a pixel CO2 molecule (O=C=O: the carbon in the middle carries the eyes),
2// and the warming stripes, drawn for the /carbon-panel pane: SVGs in the desktop app, the
3// molecule alone in terminal cells (Raster) in a terminal. docs/mascot-stripes.svg,
4// the README banner, is drawn from the same frames and palette (scripts/render-mascot.mjs).
5// Pure: no Claude Code API, so Node runs it directly (tests/run-mod-tests.mjs).
6
7// 18 x 14 pixels: # body. Frame B is the hop: the whole molecule one pixel up, its legs
8// apart; the two alternate into a bouncing walk. Both frames are the same size, as a
9// blit wants. The face is drawn over the body (FACES): k eyes and mouth, s a drop of
10// sweat, z a sleeper's z.
11const BODY: readonly string[] = [
12  ".......####.......",
13  "......######......",
14  ".##...######...##.",
15  "##################",
16  "####..######..####",
17  "##################",
18  ".##...######...##.",
19  "......######......",
20  ".......####.......",
21];
22const EMPTY_ROW = "..................";
23// Where BODY's first row sits in each hop frame
24const HOP_TOP = [2, 1] as const;
25const HOPS: readonly (readonly string[])[] = [
26  [EMPTY_ROW, EMPTY_ROW, ...BODY, ".......#..#.......", ".......#..#.......", EMPTY_ROW],
27  [EMPTY_ROW, ...BODY, "......#....#......", "......#....#......", EMPTY_ROW, EMPTY_ROW],
28];
29
30// The terminal's molecule, small enough for an editor's terminal: 13 x 8 pixels, four
31// rows of half blocks, about the size of the engine's own welcome mascot. No outline.
32// Frame B hops one pixel, half a terminal row, legs apart.
33const MINI_BODY: readonly string[] = [
34  "....#####....",
35  ".##.#####.##.",
36  "#############",
37  ".##.#####.##.",
38  "....#####....",
39];
40const MINI_EMPTY = ".............";
41const MINI_HOPS: readonly (readonly string[])[] = [
42  [MINI_EMPTY, MINI_EMPTY, ...MINI_BODY, ".....#.#....."],
43  [MINI_EMPTY, ...MINI_BODY, "....#...#....", MINI_EMPTY],
44];
45
46// The molecule's faces. Each is a set of marks in BODY's coordinates (x, y), the same
47// names for the big molecule and the terminal's small one.
48export type Face =
49  | "neutral"
50  | "blink"
51  | "lookLeft"
52  | "lookRight"
53  | "lookUp"
54  | "wink"
55  | "happy"
56  | "surprised"
57  | "worried"
58  | "worriedBlink"
59  | "sleep"
60  | "doze";
61// k eyes and mouth, s sweat, z a Z in pixels; g a cell of the terminal's molecule that
62// shows the letter z instead (a Z of a few pixels does not read there)
63type Marks = {
64  k: readonly (readonly [number, number])[];
65  s?: readonly (readonly [number, number])[];
66  z?: readonly (readonly [number, number])[];
67  g?: readonly (readonly [number, number])[];
68};
69// A Z of 4 x 4 with its diagonal, above the right oxygen: room the first hop alone has,
70// so the molecule asleep does not hop
71const Z = [
72  [14, -2], [15, -2], [16, -2], [17, -2],
73  [16, -1],
74  [15, 0],
75  [14, 1], [15, 1], [16, 1], [17, 1],
76] as const;
77const DROP = [[13, 0], [13, 1]] as const;
78const SMILE = [[7, 6], [8, 7], [9, 7], [10, 6]] as const;
79const FLAT = [[8, 6], [9, 6]] as const;
80const EYES = [[7, 3], [7, 4], [10, 3], [10, 4]] as const;
81const SHUT = [[7, 4], [10, 4]] as const;
82const FACES: Record<Face, Marks> = {
83  neutral: { k: EYES },
84  blink: { k: SHUT },
85  lookLeft: { k: [[6, 3], [6, 4], [9, 3], [9, 4]] },
86  lookRight: { k: [[8, 3], [8, 4], [11, 3], [11, 4]] },
87  lookUp: { k: [[7, 2], [7, 3], [10, 2], [10, 3]] },
88  wink: { k: [[7, 3], [7, 4], [10, 4], ...SMILE] },
89  happy: { k: [[7, 3], [6, 4], [8, 4], [10, 3], [9, 4], [11, 4], ...SMILE] },
90  surprised: { k: [[7, 2], [7, 3], [7, 4], [10, 2], [10, 3], [10, 4], [8, 6], [9, 6], [8, 7], [9, 7]] },
91  worried: { k: [...EYES, ...FLAT], s: DROP },
92  worriedBlink: { k: [...SHUT, ...FLAT], s: DROP },
93  sleep: { k: SHUT, z: Z },
94  doze: { k: SHUT },
95};
96const MINI_SMILE = [[5, 3], [6, 4], [7, 3]] as const;
97const MINI_EYES = [[5, 1], [7, 1]] as const;
98const MINI_FACES: Record<Face, Marks> = {
99  neutral: { k: MINI_EYES },
100  // One row of eyes: shut, they are gone for a moment
101  blink: { k: [] },
102  lookLeft: { k: [[4, 1], [6, 1]] },
103  lookRight: { k: [[6, 1], [8, 1]] },
104  lookUp: { k: [[5, 0], [7, 0]] },
105  wink: { k: [[5, 1], ...MINI_SMILE] },
106  happy: { k: [...MINI_EYES, ...MINI_SMILE] },
107  surprised: { k: [[5, 0], [5, 1], [7, 0], [7, 1], [6, 3], [6, 4]] },
108  worried: { k: [...MINI_EYES, [5, 3], [6, 3], [7, 3]], s: [[10, 0], [10, -1]] },
109  worriedBlink: { k: [[5, 3], [6, 3], [7, 3]], s: [[10, 0], [10, -1]] },
110  sleep: { k: [], g: [[10, -2], [12, -2]] },
111  doze: { k: [] },
112};
113
114function withMarks(hop: readonly string[], top: number, marks: Marks): string[] {
115  const rows = hop.map((r) => [...r]);
116  const put = (list: Marks["k"] | undefined, c: string) =>
117    list?.forEach(([x, y]) => {
118      const row = rows[y + top];
119      if (row !== undefined && x >= 0 && x < row.length) row[x] = c;
120    });
121  put(marks.k, "k");
122  put(marks.s, "s");
123  put(marks.z, "z");
124  put(marks.g, "g");
125  return rows.map((r) => r.join(""));
126}
127
128// A hop frame (0 or 1) with a face, big or small
129export function faceFrame(hop: 0 | 1, face: Face): string[] {
130  return withMarks(HOPS[hop] ?? HOPS[0]!, HOP_TOP[hop], FACES[face]);
131}
132export function miniFaceFrame(hop: 0 | 1, face: Face): string[] {
133  return withMarks(MINI_HOPS[hop] ?? MINI_HOPS[0]!, HOP_TOP[hop], MINI_FACES[face]);
134}
135
136export const FRAME_A: readonly string[] = faceFrame(0, "neutral");
137export const FRAME_B: readonly string[] = faceFrame(1, "neutral");
138export const FRAMES = [FRAME_A, FRAME_B] as const;
139export const MINI_FRAMES = [miniFaceFrame(0, "neutral"), miniFaceFrame(1, "neutral")] as const;
140
141// What the molecule is up to, and the faces it pulls meanwhile, in a loop: each face
142// with how long it holds (ms).
143export type Mood =
144  | "idle"
145  | "waiting"
146  | "working"
147  | "cheerful"
148  | "strained"
149  | "pleased"
150  | "phew"
151  | "asleep";
152export const MOODS: Record<Mood, ReadonlyArray<readonly [Face, number]>> = {
153  idle: [
154    ["neutral", 2400], ["blink", 150], ["neutral", 1700], ["lookLeft", 800],
155    ["neutral", 250], ["lookRight", 800], ["neutral", 1500], ["wink", 500],
156    ["neutral", 1300], ["lookUp", 700], ["neutral", 1900], ["blink", 120],
157    ["neutral", 140], ["blink", 120], ["neutral", 1100], ["happy", 1300],
158  ],
159  // No answer yet: it looks around
160  waiting: [
161    ["lookLeft", 900], ["neutral", 500], ["lookRight", 900], ["neutral", 600],
162    ["lookUp", 700], ["blink", 150], ["neutral", 1200],
163  ],
164  working: [
165    ["neutral", 1300], ["blink", 120], ["neutral", 900], ["lookRight", 450],
166    ["neutral", 1100], ["lookLeft", 450], ["neutral", 800], ["blink", 120],
167    ["neutral", 600], ["lookUp", 400],
168  ],
169  // A light session at work
170  cheerful: [
171    ["happy", 900], ["neutral", 900], ["blink", 120], ["neutral", 700],
172    ["happy", 700], ["lookRight", 400], ["neutral", 500],
173  ],
174  // A heavy session at work: it sweats
175  strained: [
176    ["worried", 1300], ["worriedBlink", 120], ["worried", 900], ["surprised", 400],
177    ["worried", 1100], ["worriedBlink", 120],
178  ],
179  // Right after an answer
180  pleased: [["happy", 2400]],
181  phew: [["surprised", 700], ["worriedBlink", 150], ["worried", 1550]],
182  asleep: [["sleep", 1400], ["doze", 1000]],
183};
184
185// A mood in which the molecule does not hop
186export function isStill(mood: Mood): boolean {
187  return mood === "asleep";
188}
189
190// How long the molecule reacts to an answer, and how long it stays idle before it sleeps
191export const REACT_MS = 2400;
192export const SLEEP_AFTER_MS = 5 * 60_000;
193
194export function moodOf(o: {
195  working: boolean;
196  cls: number | null;
197  hasAnswer: boolean;
198  // Since the last turn started or ended, ms
199  idleMs: number;
200  // Within REACT_MS of an answer
201  reacting: boolean;
202}): Mood {
203  const heavy = o.cls !== null && o.cls >= 6;
204  const light = o.cls !== null && o.cls <= 1;
205  if (o.working) return heavy ? "strained" : light ? "cheerful" : "working";
206  if (o.reacting) return heavy ? "phew" : "pleased";
207  if (!o.hasAnswer) return "waiting";
208  return o.idleMs >= SLEEP_AFTER_MS ? "asleep" : "idle";
209}
210
211// The face `t` ms into a mood's loop, and how long it holds from there
212export function faceAt(mood: Mood, t: number): { face: Face; holdMs: number } {
213  const loop = MOODS[mood];
214  const total = loop.reduce((sum, [, ms]) => sum + ms, 0);
215  let at = ((t % total) + total) % total;
216  for (const [face, ms] of loop) {
217    if (at < ms) return { face, holdMs: ms - at };
218    at -= ms;
219  }
220  const first = loop[0];
221  return { face: first?.[0] ?? "neutral", holdMs: first?.[1] ?? total };
222}
223
224// Dark blue to dark red, one colour per power of two around the median: the bluest under
225// an eighth of it, the reddest over eight times it.
226export const PALETTE = [
227  "#08306b",
228  "#2166ac",
229  "#6aa6d0",
230  "#c6dbef",
231  "#fcbba1",
232  "#ef6548",
233  "#c41a1d",
234  "#67000d",
235] as const;
236// Too little history to compare against: the molecule stays grey.
237export const NEUTRAL = "#8b949e";
238// The outline that keeps the darkest colours visible on a dark background (the SVGs).
239export const OUTLINE = "#8b949e";
240const EYES_DARK = "#0b0b0b";
241const EYES_LIGHT = "#d9dce3";
242
243export const SPRITE_WIDTH = 20;
244export const SPRITE_HEIGHT = 16;
245// The terminal's Raster: two pixel rows per terminal row (half blocks)
246export const CELL_COLUMNS = 13;
247export const CELL_ROWS = 4;
248
249export function classOf(grams: number, median: number): number {
250  if (!(median > 0) || !(grams > 0)) return 0;
251  const cls = Math.floor(Math.log2(grams / median)) + 4;
252  return Math.min(7, Math.max(0, cls));
253}
254
255// At rest the molecule still breathes: a slow bob, one frame every 1.2 s
256export const IDLE_STEP_MS = 1200;
257
258// One step of the walk: 460 ms for the bluest, 124 ms for the reddest.
259export function stepMs(cls: number): number {
260  return 460 - Math.min(7, Math.max(0, cls)) * 48;
261}
262
263export function colorOf(cls: number | null): string {
264  return cls === null ? NEUTRAL : (PALETTE[cls] ?? NEUTRAL);
265}
266
267export function eyesFor(color: string): string {
268  return color === PALETTE[0] || color === PALETTE[7] ? EYES_LIGHT : EYES_DARK;
269}
270
271// A drop of sweat, and a sleeper's z
272export const SWEAT = "#4f9fd8";
273export const ZED = OUTLINE;
274
275type Pixel = "body" | "eye" | "sweat" | "zed" | "outline" | null;
276const KIND: Record<string, Pixel> = { "#": "body", k: "eye", s: "sweat", z: "zed" };
277
278// The frame on a 20 x 16 grid: one pixel of outline around the 18 x 14 drawing (around
279// the body and the face, not around a drop or a z).
280export function pixels(frame: readonly string[]): Pixel[][] {
281  const grid: Pixel[][] = Array.from({ length: SPRITE_HEIGHT }, () =>
282    Array.from({ length: SPRITE_WIDTH }, () => null as Pixel),
283  );
284  frame.forEach((row, y) =>
285    [...row].forEach((c, x) => {
286      const line = grid[y + 1];
287      if (line === undefined) return;
288      line[x + 1] = KIND[c] ?? null;
289    }),
290  );
291  for (let y = 0; y < SPRITE_HEIGHT; y++)
292    for (let x = 0; x < SPRITE_WIDTH; x++) {
293      if (grid[y]?.[x] !== null) continue;
294      const near = [
295        [1, 0],
296        [-1, 0],
297        [0, 1],
298        [0, -1],
299      ].some(([dx, dy]) => {
300        const v = grid[y + (dy ?? 0)]?.[x + (dx ?? 0)];
301        return v === "body" || v === "eye";
302      });
303      const line = grid[y];
304      if (near && line !== undefined) line[x] = "outline";
305    }
306  return grid;
307}
308
309function rects(grid: Pixel[][], kind: Pixel, px: number, ox = 0): string {
310  let d = "";
311  grid.forEach((row, y) =>
312    row.forEach((v, x) => {
313      if (v === kind) d += `M${ox + x * px} ${y * px}h${px}v${px}h-${px}z`;
314    }),
315  );
316  return d;
317}
318
319function escapeXml(text: string): string {
320  return text
321    .replaceAll("&", "&amp;")
322    .replaceAll("<", "&lt;")
323    .replaceAll(">", "&gt;")
324    .replaceAll('"', "&quot;");
325}
326
327function path(fill: string, d: string, extra = ""): string {
328  return d === "" ? "" : `<path fill="${fill}"${extra} d="${d}"/>`;
329}
330
331// One hop of a molecule: its outline and body, then each face it may pull, stacked and
332// hidden but for the one the animation shows. The body is the same under every face.
333export function moleculeHop(
334  hop: 0 | 1,
335  color: string,
336  faces: readonly Face[],
337  px: number,
338  ox: number,
339): string {
340  const bare = pixels(withMarks(HOPS[hop] ?? HOPS[0]!, HOP_TOP[hop], { k: [] }));
341  const face = (f: Face) => {
342    const grid = pixels(faceFrame(hop, f));
343    return (
344      `<g class="f f-${f}">` +
345      path(eyesFor(color), rects(grid, "eye", px, ox)) +
346      path(SWEAT, rects(grid, "sweat", px, ox)) +
347      path(ZED, rects(grid, "zed", px, ox)) +
348      `</g>`
349    );
350  };
351  return (
352    `<g class="${hop === 0 ? "a" : "b"}">` +
353    path(OUTLINE, rects(bare, "outline", px, ox), ` fill-opacity="0.45"`) +
354    path(color, rects(bare, "body", px, ox)) +
355    faces.map(face).join("") +
356    `</g>`
357  );
358}
359
360// The CSS that walks or breathes (the two hops) and runs a mood's faces in a loop. Under
361// reduced motion: the first hop and the mood's first face, still. With a scope (a class
362// on the molecule's group), several molecules in one drawing each keep their own mood
363// and phase: the README's banner and its row of moods.
364export function moleculeCss(
365  mood: Mood,
366  hopPeriod: number,
367  opts: { scope?: string; hopDelay?: number; faceDelay?: number } = {},
368): { css: string; faces: Face[] } {
369  const loop = MOODS[mood];
370  const faces = [...new Set(loop.map(([f]) => f))];
371  const total = loop.reduce((sum, [, ms]) => sum + ms, 0);
372  const p = opts.scope !== undefined ? `.${opts.scope} ` : "";
373  const k = opts.scope !== undefined ? `${opts.scope}-` : "";
374  const hopDelay = opts.hopDelay ? ` -${opts.hopDelay}ms` : "";
375  const faceDelay = opts.faceDelay ? ` -${opts.faceDelay}ms` : "";
376  const css = [`${p}.b{opacity:0}${p}.f{opacity:0}`];
377  // Asleep it lies still: its Z takes the room the hop would
378  if (!isStill(mood))
379    css.push(
380      `@keyframes fa{0%{opacity:1}50%{opacity:0}100%{opacity:0}}`,
381      `@keyframes fb{0%{opacity:0}50%{opacity:1}100%{opacity:1}}`,
382      `${p}.a{animation:fa ${hopPeriod}ms steps(1,end) infinite${hopDelay}}`,
383      `${p}.b{animation:fb ${hopPeriod}ms steps(1,end) infinite${hopDelay}}`,
384    );
385  if (faces.length === 1) {
386    css.push(`${p}.f-${faces[0]}{opacity:1}`);
387  } else {
388    for (const f of faces) {
389      let at = 0;
390      const stops: string[] = [];
391      for (const [g, ms] of loop) {
392        stops.push(`${((at / total) * 100).toFixed(3)}%{opacity:${g === f ? 1 : 0}}`);
393        at += ms;
394      }
395      const last = loop[loop.length - 1];
396      stops.push(`100%{opacity:${last !== undefined && last[0] === f ? 1 : 0}}`);
397      css.push(
398        `@keyframes k-${k}${f}{${stops.join("")}}`,
399        `${p}.f-${f}{animation:k-${k}${f} ${total}ms steps(1,end) infinite${faceDelay}}`,
400      );
401    }
402  }
403  css.push(
404    `@media (prefers-reduced-motion: reduce){${p}.a,${p}.b,${p}.f{animation:none}${p}.a{opacity:1}${p}.b{opacity:0}${p}.f{opacity:0}${p}.f-${faces[0] ?? "neutral"}{opacity:1}}`,
405  );
406  return { css: css.join(""), faces };
407}
408
409// The molecule alone. Walking, it alternates its two hops at `step` ms; at rest it bobs
410// slowly, IDLE_STEP_MS a hop. Its face follows its mood. No script: CSS animations.
411export function mascotSvg(opts: {
412  color: string;
413  walking: boolean;
414  step: number;
415  title: string;
416  mood?: Mood;
417}): string {
418  const w = SPRITE_WIDTH * 10;
419  const h = SPRITE_HEIGHT * 10;
420  const period = (opts.walking ? opts.step : IDLE_STEP_MS) * 2;
421  const { css, faces } = moleculeCss(opts.mood ?? (opts.walking ? "working" : "idle"), period);
422  return (
423    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" shape-rendering="crispEdges">` +
424    `<title>${escapeXml(opts.title)}</title><style>${css}</style>` +
425    moleculeHop(0, opts.color, faces, 10, 0) +
426    moleculeHop(1, opts.color, faces, 10, 0) +
427    `</svg>`
428  );
429}
430
431export type Stripe = {
432  // null: an empty period, drawn in the empty colour
433  color: string | null;
434  // Shown on hover in the desktop app: the period and its total
435  title: string;
436  // Start of the period, ms since the epoch
437  start?: number;
438};
439
440// The running session's subagents, a small molecule each, in a row under the big one,
441// at 3 px a pixel, each with its own colour and a <title> (its CO2). They move and pull
442// faces like the big one (working or idle, never its sweat), each a little out of step.
443export const SUBAGENT_PX = 3;
444export function subagentsSvg(
445  agents: ReadonlyArray<{ color: string; title: string }>,
446  opts: { walking: boolean; step: number },
447): string {
448  const w = SPRITE_WIDTH * SUBAGENT_PX;
449  const h = SPRITE_HEIGHT * SUBAGENT_PX;
450  const gap = 6;
451  const period = (opts.walking ? opts.step : IDLE_STEP_MS) * 2;
452  const { css, faces } = moleculeCss(opts.walking ? "working" : "idle", period);
453  const delays: string[] = [];
454  const items = agents
455    .map((a, i) => {
456      const ox = i * (w + gap);
457      // Out of step with each other, so they do not move as one
458      delays.push(`.m${i} .a,.m${i} .b,.m${i} .f{animation-delay:-${(i * 1170) % 9000}ms}`);
459      return (
460        `<g class="m${i}"><title>${escapeXml(a.title)}</title>` +
461        moleculeHop(0, a.color, faces, SUBAGENT_PX, ox) +
462        moleculeHop(1, a.color, faces, SUBAGENT_PX, ox) +
463        `</g>`
464      );
465    })
466    .join("");
467  const total = Math.max(1, agents.length) * (w + gap) - gap;
468  return (
469    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${total} ${h}" width="${total}" height="${h}" shape-rendering="crispEdges">` +
470    `<style>${css}${delays.join("")}</style>${items}</svg>`
471  );
472}
473
474// The colour scale under the molecule: the eight colours, bluest to reddest, and a marker
475// under this session's. No marker while the molecule is grey (no median yet).
476export const SCALE_WIDTH = 112;
477export const SCALE_HEIGHT = 22;
478export function scaleSvg(cls: number | null): string {
479  const swatch = SCALE_WIDTH / PALETTE.length;
480  const swatches = PALETTE.map(
481    (c, i) => `<rect x="${(i * swatch).toFixed(2)}" y="0" width="${swatch.toFixed(2)}" height="8" fill="${c}"/>`,
482  ).join("");
483  const marker =
484    cls === null
485      ? ""
486      : (() => {
487          const x = (Math.min(7, Math.max(0, cls)) + 0.5) * swatch;
488          return `<path fill="${OUTLINE}" d="M${x.toFixed(2)} 11l5 8h-10z"/>`;
489        })();
490  return (
491    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${SCALE_WIDTH} ${SCALE_HEIGHT}" width="${SCALE_WIDTH}" height="${SCALE_HEIGHT}" shape-rendering="crispEdges">` +
492    `${swatches}${marker}</svg>`
493  );
494}
495
496export const STRIPES_HEIGHT = 72;
497// The hovered stripe's label shows over the stripes' foot: no room kept for it
498export const STRIPES_SVG_HEIGHT = STRIPES_HEIGHT;
499
500// A hover label, shared by the stripes and the detail's bars: a dark box with white
501// text, readable on a light or a dark pane, centred on `centre` and kept inside `width`
502// (half a pixel in, so its outline is not cut). About 6 px a character at 12 px; a text
503// too long for the drawing is set smaller, down to 8 px, rather than cut.
504export const HOVER_LABEL_HEIGHT = 22;
505export function hoverLabelSvg(o: {
506  id: string;
507  cls: string;
508  text: string;
509  centre: number;
510  y: number;
511  width: number;
512}): string {
513  const natural = o.text.length * 6;
514  const size = natural + 14 <= o.width - 1 ? 12 : Math.max(8, (12 * (o.width - 15)) / natural);
515  const boxW = Math.min(o.width - 1, (natural * size) / 12 + 14);
516  const boxX = Math.max(0.5, Math.min(o.width - 0.5 - boxW, o.centre - boxW / 2));
517  return (
518    `<g id="${o.id}" class="${o.cls}"><rect x="${boxX.toFixed(2)}" y="${o.y}" width="${boxW.toFixed(2)}" height="${HOVER_LABEL_HEIGHT}" rx="4" fill="#1f2328" stroke="${OUTLINE}" stroke-opacity="0.6"/>` +
519    `<text x="${(boxX + 7).toFixed(2)}" y="${o.y + 15}" font-size="${Number(size.toFixed(1))}" font-family="system-ui,-apple-system,sans-serif" fill="#ffffff">${escapeXml(o.text)}</text></g>`
520  );
521}
522
523// One rect per stripe across `width` CSS pixels (the viewBox matches the drawn size, so
524// labels keep their shape), oldest on the left; an empty period is a faint grey. All the
525// stripes come first, then all the labels, hidden, in a layer above them: hovering
526// stripe i lights it up and shows label i at once over the stripes' foot, in a dark box
527// readable on a light or a dark pane, never under the next stripe. A CSS :hover and the
528// sibling selector, no script, and no <title>: the app's own tooltip would show a second
529// label late. The Svg's alt says what the drawing is.
530export function stripesSvg(
531  stripes: readonly Stripe[],
532  _title: string,
533  width: number,
534): string {
535  const n = Math.max(1, stripes.length);
536  const sw = width / n;
537  const h = STRIPES_HEIGHT;
538  const rects = stripes
539    .map((s, i) => {
540      const fill = s.color === null ? `fill="${OUTLINE}" fill-opacity="0.2"` : `fill="${s.color}"`;
541      return `<rect id="b${i}" class="b" x="${(i * sw).toFixed(2)}" y="0" width="${sw.toFixed(2)}" height="${h}" ${fill}/>`;
542    })
543    .join("");
544  const labels = stripes
545    .map((s, i) =>
546      hoverLabelSvg({ id: `t${i}`, cls: "t", text: s.title, centre: i * sw + sw / 2, y: h - 26, width }),
547    )
548    .join("");
549  const show = stripes.map((_, i) => `#b${i}:hover~#t${i}`).join(",");
550  const style =
551    `<style>.t{opacity:0;pointer-events:none}` +
552    `.b:hover{opacity:.7;stroke:#ffffff;stroke-width:2}` +
553    (stripes.length > 0 ? `${show}{opacity:1}` : "") +
554    `</style>`;
555  return (
556    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${STRIPES_SVG_HEIGHT}" width="${width}" height="${STRIPES_SVG_HEIGHT}">` +
557    `${style}${rects}${labels}</svg>`
558  );
559}
560
561// ── Terminal cells (Raster) ─────────────────────────────────────────────────
562
563const DEFAULT_COLOR = 0x01000000;
564const UPPER_HALF = 0x2580; // ▀
565const LOWER_HALF = 0x2584; // ▄
566const LETTER_Z = 0x7a; // z
567const SPACE = 0x20;
568
569function rgb(hex: string): number {
570  return Number.parseInt(hex.slice(1), 16) & 0xffffff;
571}
572
573// Standard padded base64 of little-endian u32 triplets, as RasterProps.cells wants.
574// No Uint8Array.toBase64: Node 22, where the pure tests run, does not have it.
575export function encodeCells(words: readonly number[]): string {
576  const bytes = new Uint8Array(words.length * 4);
577  const view = new DataView(bytes.buffer);
578  words.forEach((w, i) => view.setUint32(i * 4, w >>> 0, true));
579  let binary = "";
580  const CHUNK = 0x8000;
581  for (let i = 0; i < bytes.length; i += CHUNK) {
582    binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
583  }
584  return btoa(binary);
585}
586
587// One triplet per cell, two pixels a cell: the top pixel in the foreground of an upper
588// half block, the bottom one in its background. A transparent pixel is the terminal's
589// default colour, so a cell with only its bottom pixel takes a lower half block instead.
590export function mascotWords(frame: readonly string[], color: string): number[] {
591  const paint = (c: string | undefined): number | null =>
592    c === "#"
593      ? rgb(color)
594      : c === "k"
595        ? rgb(eyesFor(color))
596        : c === "s"
597          ? rgb(SWEAT)
598          : c === "z"
599            ? rgb(ZED)
600            : null;
601  const words: number[] = [];
602  for (let row = 0; row < CELL_ROWS; row++)
603    for (let x = 0; x < CELL_COLUMNS; x++) {
604      if (frame[row * 2]?.[x] === "g" || frame[row * 2 + 1]?.[x] === "g") {
605        words.push(LETTER_Z, rgb(ZED), DEFAULT_COLOR);
606        continue;
607      }
608      const top = paint(frame[row * 2]?.[x]);
609      const bottom = paint(frame[row * 2 + 1]?.[x]);
610      if (top !== null) words.push(UPPER_HALF, top, bottom ?? DEFAULT_COLOR);
611      else if (bottom !== null) words.push(LOWER_HALF, bottom, DEFAULT_COLOR);
612      else words.push(SPACE, DEFAULT_COLOR, DEFAULT_COLOR);
613    }
614  return words;
615}
616
617export function mascotCells(frame: readonly string[], color: string): string {
618  return encodeCells(mascotWords(frame, color));
619}
620
hooks/mod/lib/sessions.ts 487 lines
1// The session history the /carbon-panel pane draws: read from sessions-history.tsv, which
2// the Stop hook writes next to carbon.db (cc_export_sessions in scripts/portable-lib.sh).
3// The mod never opens the database. Pure: no Claude Code API, so Node runs it directly
4// (tests/run-mod-tests.mjs).
5
6import { median } from "./format.ts";
7
8export type SessionRow = {
9  id: string;
10  // Start of the session, ms since the epoch
11  at: number;
12  grams: number;
13  // Methodology version: 1 for legacy rows whose transcript is gone, kept as stored
14  version: number;
15  // The project's folder name, as the hooks record it; "" when unknown
16  project: string;
17  // The API-price cost, null when the file does not carry it
18  usd: number | null;
19  // The session's dominant model as the hooks record it, "" when unknown
20  model: string;
21  // Its tokens by kind, null when the file does not carry them (a hook older than
22  // the pane's detail)
23  tokens: TokenSplit | null;
24};
25
26// A session's tokens by kind: uncached input, cache writes, cache reads, output
27export type TokenSplit = {
28  input: number;
29  cacheWrite: number;
30  cacheRead: number;
31  output: number;
32};
33
34// The current methodology: what the running session is measured with
35export const CURRENT_VERSION = 2;
36
37export type Range = "7d" | "30d" | "1y" | "all" | "custom";
38// One stripe per day, week or month: picked from the period's length, so the stripes
39// always cover the whole period.
40export type Step = "day" | "week" | "month";
41// A custom range runs from the start of day `from` to the end of day `to`
42// ("2026-05-01"), local time.
43export type View = { range: Range; from?: string; to?: string };
44
45export const RANGES: readonly Range[] = ["7d", "30d", "1y", "all", "custom"];
46export const DEFAULT_VIEW: View = { range: "30d" };
47export const HISTORY_FILE = "sessions-history.tsv";
48// Below this many past sessions there is no median of one's own: the molecule is coloured
49// against a starting reference instead, 0.5 kgCO₂ a session.
50export const MIN_SESSIONS = 10;
51export const START_MEDIAN_GRAMS = 500;
52// Below this many periods with sessions in them the stripes stay uncoloured.
53export const MIN_STRIPES = 3;
54
55const DAY_MS = 86_400_000;
56const RANGE_DAYS: Record<"7d" | "30d" | "1y", number> = {
57  "7d": 7,
58  "30d": 30,
59  "1y": 365,
60};
61const DAY_KEY = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
62
63export function isView(value: unknown): value is View {
64  const v = value as Partial<View> | null | undefined;
65  if (typeof v !== "object" || v === null || !RANGES.includes(v.range as Range))
66    return false;
67  if (v.range !== "custom") return true;
68  return (
69    typeof v.from === "string" &&
70    DAY_KEY.test(v.from) &&
71    typeof v.to === "string" &&
72    DAY_KEY.test(v.to) &&
73    v.from <= v.to
74  );
75}
76
77// The file's directory, resolved as the bash hooks resolve carbon.db: CLAUDE_CARBON_DB's
78// directory, else CLAUDE_CONFIG_DIR/claude-carbon, else the home directory's
79// .claude/claude-carbon (HOME, or USERPROFILE on Windows, where the native process has
80// no HOME). Null when nothing names a directory.
81export function historyPath(env: {
82  db?: string;
83  configDir?: string;
84  home?: string;
85  userProfile?: string;
86}): string | null {
87  const nonEmpty = (v: string | undefined) =>
88    v !== undefined && v !== "" ? v : undefined;
89  const db = nonEmpty(env.db);
90  if (db !== undefined) {
91    const cut = Math.max(db.lastIndexOf("/"), db.lastIndexOf("\\"));
92    let dir = cut > 0 ? db.slice(0, cut) : cut === 0 ? "" : ".";
93    // A Git Bash spelling (/c/Users/...) as the bash side accepts it, on Windows
94    const msys = /^\/([a-zA-Z])(\/.*)?$/.exec(dir);
95    if (msys !== null && env.userProfile !== undefined)
96      dir = `${(msys[1] ?? "").toUpperCase()}:${msys[2] ?? "/"}`;
97    return `${dir}/${HISTORY_FILE}`;
98  }
99  const config = nonEmpty(env.configDir);
100  if (config !== undefined) return `${config}/claude-carbon/${HISTORY_FILE}`;
101  const home = nonEmpty(env.home) ?? nonEmpty(env.userProfile);
102  if (home !== undefined)
103    return `${home}/.claude/claude-carbon/${HISTORY_FILE}`;
104  return null;
105}
106
107// The flag a marketplace install's SessionStart hook writes once a day (check-update.sh):
108// the newest released version. In the config's claude-carbon folder, where the hooks keep
109// their state, whatever CLAUDE_CARBON_DB says.
110export const UPDATE_FILE = "plugin-update-check.json";
111// The one a git clone gets. The mod runs from a copy of either install, so it reads both.
112export const CLONE_UPDATE_FILE = "update-check.json";
113// When the last card was made, "YYYY-MM", written by the card's script
114export const CARD_STAMP_FILE = "last-card-month";
115
116type StateEnv = { configDir?: string; home?: string; userProfile?: string };
117
118// A file in that folder, null when nothing names it
119export function statePath(env: StateEnv, name: string): string | null {
120  const nonEmpty = (v: string | undefined) =>
121    v !== undefined && v !== "" ? v : undefined;
122  const config = nonEmpty(env.configDir);
123  if (config !== undefined) return `${config}/claude-carbon/${name}`;
124  const home = nonEmpty(env.home) ?? nonEmpty(env.userProfile);
125  if (home !== undefined) return `${home}/.claude/claude-carbon/${name}`;
126  return null;
127}
128
129export function updateFlagPath(env: StateEnv): string | null {
130  return statePath(env, UPDATE_FILE);
131}
132
133export function updateFlagPaths(env: StateEnv): string[] {
134  return [UPDATE_FILE, CLONE_UPDATE_FILE]
135    .map((name) => statePath(env, name))
136    .filter((p): p is string => p !== null);
137}
138
139const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
140function isNewer(a: string, b: string): boolean {
141  const x = SEMVER.exec(a);
142  const y = SEMVER.exec(b);
143  if (x === null || y === null) return false;
144  for (let i = 1; i <= 3; i++) {
145    const d = Number(x[i]) - Number(y[i]);
146    if (d !== 0) return d > 0;
147  }
148  return false;
149}
150
151// The released version this install lacks, or null. Compared with the running plugin's
152// own version, not the flag's, so an update applied since the last check says nothing;
153// a flag older than a week is ignored, as the status line ignores its own.
154export function newerRelease(
155  flagText: string,
156  ownVersion: string | null,
157  nowMs: number,
158): string | null {
159  if (ownVersion === null) return null;
160  let flag: unknown;
161  try {
162    flag = JSON.parse(flagText);
163  } catch {
164    return null;
165  }
166  if (typeof flag !== "object" || flag === null) return null;
167  const { remote, checked_at } = flag as { remote?: unknown; checked_at?: unknown };
168  if (typeof remote !== "string" || typeof checked_at !== "number") return null;
169  if (nowMs - checked_at * 1000 > 7 * 86400 * 1000) return null;
170  return isNewer(remote, ownVersion) ? remote : null;
171}
172
173// The newest release any of the flags names above this copy's version
174export function newestRelease(
175  flagTexts: readonly string[],
176  ownVersion: string | null,
177  nowMs: number,
178): string | null {
179  let newest: string | null = null;
180  for (const text of flagTexts) {
181    const found = newerRelease(text, ownVersion, nowMs);
182    if (found !== null && (newest === null || isNewer(found, newest))) newest = found;
183  }
184  return newest;
185}
186
187export const CARD_NUDGE_UNTIL_DAY = 10;
188const CARD_NUDGE_MIN_DAYS = 7;
189
190// The status line's monthly nudge: from the 1st to the `untilDay`th, unless a card was made
191// this month (the stamp), the month just closed and its total, as the card's bar for it.
192// Like the card, months and days are those of the sessions' UTC start; a month with
193// sessions on fewer than 7 days shows nothing, which keeps a near-empty card unadvertised.
194export function cardNudge(
195  rows: readonly SessionRow[],
196  nowMs: number,
197  stamp: string | null,
198  untilDay: number = CARD_NUDGE_UNTIL_DAY,
199): { month: number; grams: number } | null {
200  const now = new Date(nowMs);
201  const pad = (n: number) => String(n).padStart(2, "0");
202  if (now.getDate() > untilDay) return null;
203  if (stamp?.trim() === `${now.getFullYear()}-${pad(now.getMonth() + 1)}`) return null;
204  const closed = new Date(now.getFullYear(), now.getMonth() - 1, 1);
205  const key = `${closed.getFullYear()}-${pad(closed.getMonth() + 1)}`;
206  const days = new Set<string>();
207  let grams = 0;
208  for (const row of rows) {
209    const day = new Date(row.at).toISOString().slice(0, 10);
210    if (day.slice(0, 7) !== key) continue;
211    days.add(day);
212    grams += row.grams;
213  }
214  if (days.size < CARD_NUDGE_MIN_DAYS || !(grams > 0)) return null;
215  return { month: closed.getMonth(), grams };
216}
217
218// One line per session: id, start in epoch seconds, grams, methodology version, project,
219// API-price cost, model, then the tokens by kind (uncached input, cache write, cache
220// read, output), tab-separated. Fields an older hook did not write read as the current
221// version and as unknown.
222// A line that does not read as that is skipped, never guessed.
223export function parseHistory(text: string): SessionRow[] {
224  const rows: SessionRow[] = [];
225  for (const line of text.split(/\r?\n/)) {
226    const [id, start, grams, version, project, cost, model, ...counts] =
227      line.split("\t");
228    if (
229      id === undefined ||
230      id === "" ||
231      start === undefined ||
232      grams === undefined
233    )
234      continue;
235    const seconds = Number(start);
236    const g = Number(grams);
237    if (!Number.isFinite(seconds) || !Number.isFinite(g) || !(g > 0)) continue;
238    const v = version === undefined || version === "" ? CURRENT_VERSION : Number(version);
239    rows.push({
240      id,
241      at: seconds * 1000,
242      grams: g,
243      version: Number.isFinite(v) ? v : CURRENT_VERSION,
244      project: project ?? "",
245      usd: numberOrNull(cost),
246      model: model ?? "",
247      tokens: tokenSplitOf(counts),
248    });
249  }
250  return rows.sort((a, b) => a.at - b.at);
251}
252
253function tokenSplitOf(fields: string[]): TokenSplit | null {
254  if (fields.length < 4) return null;
255  const n = fields.slice(0, 4).map((f) => (f === "" ? NaN : Number(f)));
256  if (!n.every((v) => Number.isFinite(v) && v >= 0)) return null;
257  return { input: n[0] ?? 0, cacheWrite: n[1] ?? 0, cacheRead: n[2] ?? 0, output: n[3] ?? 0 };
258}
259
260function numberOrNull(field: string | undefined): number | null {
261  return field === undefined || field === "" || !Number.isFinite(Number(field))
262    ? null
263    : Number(field);
264}
265
266// The past sessions: the one running now is in the file with a partial total, and the
267// pane shows it from its live total instead.
268export function pastSessions(
269  rows: readonly SessionRow[],
270  currentId: string | null,
271) {
272  return currentId === null
273    ? [...rows]
274    : rows.filter((r) => r.id !== currentId);
275}
276
277// The median the molecule's colour is measured against: all past sessions, as the
278// reports and the published figures count them, or null with too few of them.
279export function sessionMedian(past: readonly SessionRow[]): number | null {
280  if (past.length < MIN_SESSIONS) return null;
281  const m = median(past.map((r) => r.grams));
282  return m > 0 ? m : null;
283}
284
285// What the colours are measured against: the person's own median once there is one, the
286// starting reference before, so the molecule has a colour from the first answer.
287export function colourMedian(past: readonly SessionRow[]): number {
288  return sessionMedian(past) ?? START_MEDIAN_GRAMS;
289}
290
291// Where /carbon-panel shows: the band above a terminal's prompt when it was typed there,
292// the side pane otherwise. A session run in a terminal and driven from the desktop app
293// or a phone (Remote Control, origin "bridge") opens the pane where it was asked for.
294export function panelSite(
295  surfaces: readonly string[],
296  originKind: string,
297): "band" | "pane" {
298  return surfaces.includes("terminal") && originKind !== "bridge" ? "band" : "pane";
299}
300
301// A folder's name from a path, as the hooks' basename gives it
302export function folderName(path: string): string {
303  const parts = path.split(/[\\/]/).filter((p) => p !== "");
304  return parts.at(-1) ?? "";
305}
306
307export type ProjectTotal = { project: string; grams: number; share: number };
308export type PeriodTotal = {
309  grams: number;
310  sessions: number;
311  // The API-price cost of the sessions that carry one, null when none does
312  usd: number | null;
313  // Heaviest first
314  projects: ProjectTotal[];
315};
316
317export type Bar = {
318  // Start of the period, ms since the epoch, local time
319  start: number;
320  grams: number;
321  sessions: number;
322};
323
324// Days, weeks and months are built from the date's parts, never by moving an hour:
325// where midnight is skipped for summer time, the period still starts at its first
326// instant.
327function dayStart(ms: number): number {
328  const d = new Date(ms);
329  return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
330}
331
332// Monday 00:00, local time
333function weekStart(ms: number): number {
334  const d = new Date(ms);
335  const offset = (d.getDay() + 6) % 7;
336  return new Date(d.getFullYear(), d.getMonth(), d.getDate() - offset).getTime();
337}
338
339function monthStart(ms: number): number {
340  const d = new Date(ms);
341  return new Date(d.getFullYear(), d.getMonth(), 1).getTime();
342}
343
344function startOf(step: Step, ms: number): number {
345  return step === "day" ? dayStart(ms) : step === "week" ? weekStart(ms) : monthStart(ms);
346}
347
348function nextPeriod(start: number, step: Step): number {
349  const d = new Date(start);
350  return step === "day"
351    ? new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime()
352    : step === "week"
353      ? new Date(d.getFullYear(), d.getMonth(), d.getDate() + 7).getTime()
354      : new Date(d.getFullYear(), d.getMonth() + 1, 1).getTime();
355}
356
357// "2026-05-01" for a time, local
358export function dayKey(ms: number): string {
359  const d = new Date(ms);
360  const pad = (n: number) => String(n).padStart(2, "0");
361  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
362}
363
364function dayOf(key: string): number {
365  const [y, m, d] = key.split("-").map(Number);
366  return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1).getTime();
367}
368
369// A date the person typed, "01/05/2026" (day first) or "2026-05-01", as a day key; null
370// when it does not read as a real date.
371export function parseDay(text: string): string | null {
372  const s = text.trim();
373  const dmy = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/.exec(s);
374  const ymd = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(s);
375  const [y, m, d] = dmy
376    ? [Number(dmy[3]), Number(dmy[2]), Number(dmy[1])]
377    : ymd
378      ? [Number(ymd[1]), Number(ymd[2]), Number(ymd[3])]
379      : [NaN, NaN, NaN];
380  if (!Number.isFinite(y) || !Number.isFinite(m) || !Number.isFinite(d)) return null;
381  const date = new Date(y, m - 1, d);
382  if (date.getFullYear() !== y || date.getMonth() !== m - 1 || date.getDate() !== d)
383    return null;
384  return dayKey(date.getTime());
385}
386
387export type Window = { start: number; end: number; step: Step };
388
389// The period a view covers and its stripe: a day for up to 45 days, a week for up to
390// 400, a month beyond. The presets end now; the whole history starts at the first
391// session's period; a custom range covers its days whole, up to now, from its first day
392// exactly (its first stripe, a week or a month, is then partial).
393export function windowOf(
394  view: View,
395  rows: readonly SessionRow[],
396  now: number,
397): Window {
398  const stepFor = (span: number): Step =>
399    span <= 45 * DAY_MS ? "day" : span <= 400 * DAY_MS ? "week" : "month";
400  if (view.range === "custom" && view.from !== undefined && view.to !== undefined) {
401    const from = dayOf(view.from);
402    const end = Math.min(now, nextPeriod(dayOf(view.to), "day") - 1);
403    return { start: from, end, step: stepFor(end - from) };
404  }
405  if (view.range === "all" || view.range === "custom") {
406    const first = rows[0]?.at ?? now;
407    const step = stepFor(now - first);
408    return { start: startOf(step, first), end: now, step };
409  }
410  const days = RANGE_DAYS[view.range];
411  const step: Step = days <= 45 ? "day" : "week";
412  // The current day or week is the last of `days` days, as a calendar reads it. A
413  // history younger than the range starts the stripes at its first session: before it
414  // there is no data, not a pause.
415  const first = rows[0]?.at;
416  // Back by calendar days, not by 24-hour spans: a change of clock in between moves
417  // neither the first day nor the count of stripes.
418  const today = new Date(now);
419  const from = startOf(
420    step,
421    new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1)).getTime(),
422  );
423  return {
424    start: first === undefined ? from : Math.max(from, startOf(step, first)),
425    end: now,
426    step,
427  };
428}
429
430function sumOf(rows: readonly SessionRow[]): PeriodTotal {
431  const grams = rows.reduce((s, r) => s + r.grams, 0);
432  const priced = rows.filter((r) => r.usd !== null);
433  const usd = priced.length > 0 ? priced.reduce((s, r) => s + (r.usd ?? 0), 0) : null;
434  const byProject = new Map<string, number>();
435  for (const r of rows)
436    byProject.set(r.project, (byProject.get(r.project) ?? 0) + r.grams);
437  const projects = [...byProject.entries()]
438    .map(([project, g]) => ({ project, grams: g, share: grams > 0 ? g / grams : 0 }))
439    .sort((a, b) => b.grams - a.grams);
440  return { grams, sessions: rows.length, usd, projects };
441}
442
443
444// What the stripes cover, summed, as the reports sum it.
445export function periodTotal(rows: readonly SessionRow[], w: Window): PeriodTotal {
446  return sumOf(rows.filter((r) => r.at >= w.start && r.at <= w.end));
447}
448
449// The same length of time just before, for the comparison; null for the whole history.
450export function previousTotal(
451  rows: readonly SessionRow[],
452  w: Window,
453  view: View,
454): PeriodTotal | null {
455  if (view.range === "all") return null;
456  const before = w.start - (w.end - w.start);
457  return sumOf(rows.filter((r) => r.at >= before && r.at < w.start));
458}
459
460// One stripe per period of the window, empty ones included (0 g): a quiet day or week
461// shows as a gap, and the stripes always run from the window's start to its end.
462export function bars(rows: readonly SessionRow[], w: Window): Bar[] {
463  const totals = new Map<number, Bar>();
464  for (const r of rows) {
465    if (r.at < w.start || r.at > w.end) continue;
466    const start = startOf(w.step, r.at);
467    const bar = totals.get(start) ?? { start, grams: 0, sessions: 0 };
468    bar.grams += r.grams;
469    bar.sessions += 1;
470    totals.set(start, bar);
471  }
472  const out: Bar[] = [];
473  const last = startOf(w.step, w.end);
474  for (let s = startOf(w.step, w.start); s <= last; s = nextPeriod(s, w.step))
475    out.push(totals.get(s) ?? { start: s, grams: 0, sessions: 0 });
476  return out;
477}
478
479// The median the stripes' colours are measured against: over the periods that have
480// sessions, or null with too few of them.
481export function barMedian(list: readonly Bar[]): number | null {
482  const full = list.filter((b) => b.grams > 0).map((b) => b.grams);
483  if (full.length < MIN_STRIPES) return null;
484  const m = median(full);
485  return m > 0 ? m : null;
486}
487
hooks/mod/lib/equiv.ts 64 lines
1// The car equivalence of the /carbon-panel pane: the same set, factor, label and source
2// as /carbon-report and the cards (data/factors.json "equivalences", set picked as
3// scripts/equiv-lib.sh detect_equiv_set picks it). Pure: no Claude Code API.
4
5export type CarEquivalence = {
6  // gCO2e per unit driven
7  divisor: number;
8  // "km" or "miles"
9  unit: string;
10  // "km en voiture", "miles driven by car"
11  label: string;
12  // "142 g/km, ADEME 2025"
13  tag: string;
14};
15
16// The first locale variable that speaks (C and POSIX are sentinels), as the bash
17// does: France's set for fr / fr_FR, the US set for a US locale, the world set
18// otherwise. None set (the desktop app): French when the language is French, else
19// the world set.
20export function equivalenceSet(
21  envValues: ReadonlyArray<string | undefined>,
22  lang: "fr" | "en",
23): "fr" | "us" | "world" {
24  const value = envValues.find(
25    (v) =>
26      v !== undefined &&
27      v !== "" &&
28      v !== "C" &&
29      !v.startsWith("C.") &&
30      v !== "POSIX" &&
31      !v.startsWith("POSIX."),
32  );
33  if (value === undefined) return lang === "fr" ? "fr" : "world";
34  if (/^(fr|fr\..*|fr_FR.*|fr-FR.*)$/.test(value)) return "fr";
35  if (/^(us|US|.*_US.*|.*-US.*)$/.test(value)) return "us";
36  return "world";
37}
38
39// The set's car row, or null when the file does not hold one that reads.
40export function carEquivalence(
41  factorsJson: unknown,
42  set: string,
43): CarEquivalence | null {
44  const sets = (factorsJson as { equivalences?: Record<string, unknown> })
45    ?.equivalences;
46  const rows = sets?.[set];
47  if (!Array.isArray(rows)) return null;
48  const car = rows.find(
49    (r): r is Record<string, unknown> =>
50      typeof r === "object" && r !== null && (r as { id?: unknown }).id === "car",
51  );
52  if (car === undefined) return null;
53  const { divisor, unit, label, tag } = car;
54  if (
55    typeof divisor !== "number" ||
56    !(divisor > 0) ||
57    typeof unit !== "string" ||
58    typeof label !== "string" ||
59    typeof tag !== "string"
60  )
61    return null;
62  return { divisor, unit, label, tag };
63}
64
types/index.d.ts 62 lines
1// The values the claude-carbon mod keeps in $.state for the session.
2
3export type AnswerCo2 = {
4  main: string;
5  sub: string | null;
6  isUnusual: boolean;
7};
8
9// One main-loop turn, written when it ends (`at`, ms since the epoch). Its duration
10// line takes it when first drawn within a second of that (hooks/mod/lib/lines.ts).
11// A turn that counted nothing (an excluded model, no usage) keeps a null co2.
12export type AnswerCo2Entry = {
13  turnId: string;
14  durationMs: number;
15  at: number;
16  co2: AnswerCo2 | null;
17};
18
19// usd: the API-price cost (data/prices.json) of the same requests as grams. Absent once
20// one of them could not be priced (no price list read, or a total kept from code that
21// counted no cost): a part of the cost is never shown as the whole.
22export type SessionTotal = {
23  grams: number;
24  usd?: number;
25  turns: number;
26  // The session's tokens by kind, for the pane's detail; absent in a total kept from
27  // code that did not count them
28  tokens?: { input: number; cacheWrite: number; cacheRead: number; output: number };
29};
30
31// What the /carbon-panel pane covers: a preset range, or months picked by the person
32// ("2026-05"); one stripe per day, week or month follows from its length.
33export type PaneView = {
34  range: "7d" | "30d" | "1y" | "all" | "custom";
35  from?: string;
36  to?: string;
37};
38
39// The blocks the /carbon-panel pane shows under the stripes, besides the total
40export type PaneBlocks = {
41  compare: boolean;
42  cost: boolean;
43  equivalence: boolean;
44  projects: boolean;
45  detail: boolean;
46};
47
48declare module "claude-code" {
49  interface PluginState {
50    "claude-carbon": {
51      answers: AnswerCo2Entry[];
52      session: SessionTotal;
53      // True from a main-loop turn's start to its end: the molecule walks.
54      working: boolean;
55      // True while /carbon-panel shows the molecule in the band above a terminal's prompt
56      band: boolean;
57      view: PaneView;
58      blocks: PaneBlocks;
59    };
60  }
61}
62