Skip to content
Back to search

claude-carbon

SkillWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/gwittebolle--claude-carbon/badge.svg)](/listings/gwittebolle--claude-carbon)

HTML

<a href="/listings/gwittebolle--claude-carbon"><img src="/api/listings/gwittebolle--claude-carbon/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

In Claude Code, type:

/plugin install claude-carbon --marketplace gwittebolle/claude-carbon

Claude Code asks you to confirm the marketplace, shows what the plugin installs, then asks where to install it: pick **Install for you**. The same line works on macOS, Linux and Windows. In the **Code** tab of the Claude desktop app, if the line is not taken, paste this message instead and accept when Claude asks:

Install the claude-carbon plugin for me: claude plugin install claude-carbon --marketplace gwittebolle/claude-carbon

Then quit Claude Code completely, open it again and start a new session. Your CO2 now shows next to the session's cost:

- in a terminal, in the status line: `$0.50 · 65gCO₂` - in the desktop app, under the prompt: `This session: 3.6 gCO₂ · $0.12`

The plugin sets that status line once, at its first session start, and only when you have none: another tool's status line is left as it is (to add the CO2 to it, see [ccstatusline](#using-with-ccstatusline)). `/carbon-report` gives your totals, and `/carbon-panel` opens the pane in the desktop app. The `$` is an API-equivalent cost, not what your subscription bills. To update later, run `/carbon-update`.

<details> <summary><b>If the install stops</b></summary>

- **macOS opens a window about "command line developer tools".** That is `git`, which Claude Code needs to fetch the plugin and a Mac without developer tools does not have yet. Click **Install**, wait until it finishes (a few minutes), then install again. - **"jq is not installed" or "sqlite3 is not installed".** Tell Claude: "Install what is missing.", then restart Claude Code. Every Mac has `sqlite3`, and macOS 15 and later also have `jq`. On an older Mac, Claude can install `jq` with Homebrew, or the installer (under Other ways to install) fetches the official `jq` itself, checked against its published checksum. On Windows, `/carbon-panel` names the one missing and Claude can install it with `winget`. If `winget` answers "Access is denied", security software on the PC is blocking it: allow `winget` there, then try again. - **Windows says Git Bash is missing.** Install [Git for Windows](https://git-scm.com/downloads/win) (Claude Code needs it on Windows anyway), quit the app completely and reopen it, then install 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. - **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 as above.

</details>

<details> <summary><b>Other ways to install</b></summary>

- **The installer**, a script that clones this repository and wires everything into `~/.claude/settings.json` itself. Paste this message into Claude Code, or run the command after the colon yourself in a terminal:

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

On Windows, in PowerShell (it needs [Git for Windows](https://git-scm.com/downloads/win) and two packages first, see [Windows](#windows)):

  Install claude-carbon for me by running this command in PowerShell:
  irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex

If the mode selector under the prompt shows **Auto**, pick **Manual** first: auto mode blocks a command that downloads a script and runs it. You can read [install.sh](install.sh) before running it. - **With Node.js:** `npx claude-carbon` runs the same installer.

Use one way only: the plugin and the installer together would run every hook twice. Already installed with the installer? Nothing to change, `/carbon-update` keeps it up to date.

</details>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 32 lines
  1. {
  2. "name": "claude-carbon",
  3. "owner": {
  4. "name": "Gaetan Wittebolle"
  5. },
  6. "metadata": {
  7. "description": "Track the carbon footprint of your Claude Code sessions, in the terminal and the Claude desktop app"
  8. },
  9. "plugins": [
  10. {
  11. "name": "claude-carbon",
  12. "source": {
  13. "source": "url",
  14. "url": "https://github.com/gwittebolle/claude-carbon.git"
  15. },
  16. "description": "Track the carbon footprint of your Claude Code sessions, in the terminal and the Claude desktop app",
  17. "version": "1.20.1",
  18. "author": {
  19. "name": "Gaetan Wittebolle"
  20. },
  21. "homepage": "https://github.com/gwittebolle/claude-carbon",
  22. "repository": "https://github.com/gwittebolle/claude-carbon",
  23. "license": "MIT",
  24. "keywords": [
  25. "carbon-footprint",
  26. "sustainability",
  27. "claude-code",
  28. "green-it"
  29. ]
  30. }
  31. ]
  32. }
README.md · README · 654 lines · 4 findings marked
  1. <p><img src="docs/banner.png" width="100%" alt="claude-carbon, free and open source: the CO2 of your Claude Code sessions, in the terminal and in the Claude app. Eight pixel molecules from dark blue to dark red, a terminal whose status line reads 8.2gCO2, and the /carbon-panel pane: this session's molecule and CO2, the last 30 days as tiles and warming stripes, a button for the yearly card"></p>
  2. [![GitHub stars](https://img.shields.io/github/stars/gwittebolle/claude-carbon)](https://github.com/gwittebolle/claude-carbon/stargazers)
  3. [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
  4. [![GitHub release](https://img.shields.io/github/v/release/gwittebolle/claude-carbon)](https://github.com/gwittebolle/claude-carbon/releases)
  5. [![npm](https://img.shields.io/npm/v/claude-carbon)](https://www.npmjs.com/package/claude-carbon)
  6. [![CI](https://github.com/gwittebolle/claude-carbon/actions/workflows/ci.yml/badge.svg)](https://github.com/gwittebolle/claude-carbon/actions/workflows/ci.yml)
  7. 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.
  8. <p align="center"><img src="https://github.com/user-attachments/assets/f52b2653-28b9-4efc-82a6-02dfe256e193" width="480" alt="claude-carbon in 16 seconds: Claude Code never shows its CO2; claude-carbon puts it in the terminal status line, then in the Claude desktop app, where /carbon-panel opens a pane with a pixel molecule coloured by this session's CO2 against the median of your past sessions"></p>
  9. ## What claude-carbon does
  10. - `/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](#the-mod-carbon-panel-and-the-co2-of-each-answer)
  11. - 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
  12. - Persists each session to a local SQLite database, so history survives the 30-day transcript purge
  13. - Backfills historical data from existing `~/.claude` transcripts
  14. - Slash commands: `/carbon-report` (text), `/carbon-card` (PNG), `/carbon-pr` (footprint of a pull request)
  15. - A README badge with your all-time total, and a public methodology with every factor sourced
  16. > **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, Max or Ultra subscription you do not pay it; it shows the value of what you used, next to its CO2. See [How it works](#how-it-works).
  17. ## Install
  18. In Claude Code, type:
  19. ```text
  20. /plugin install claude-carbon --marketplace gwittebolle/claude-carbon
  21. ```
  22. Claude Code asks you to confirm the marketplace, shows what the plugin installs, then asks where to install it: pick **Install for you**. The same line works on macOS, Linux and Windows. In the **Code** tab of the Claude desktop app, if the line is not taken, paste this message instead and accept when Claude asks:
  23. ```text
  24. Install the claude-carbon plugin for me: claude plugin install claude-carbon --marketplace gwittebolle/claude-carbon
  25. ```
  26. Then quit Claude Code completely, open it again and start a new session. Your CO2 now shows next to the session's cost:
  27. - in a terminal, in the status line: `$0.50 · 65gCO₂`
  28. - in the desktop app, under the prompt: `This session: 3.6 gCO₂ · $0.12`
  29. The plugin sets that status line once, at its first session start, and only when you have none: another tool's status line is left as it is (to add the CO2 to it, see [ccstatusline](#using-with-ccstatusline)). `/carbon-report` gives your totals, and `/carbon-panel` opens the pane in the desktop app. The `$` is an API-equivalent cost, not what your subscription bills. To update later, run `/carbon-update`.
  30. <p align="center"><img src="docs/desktop-pane.png" width="560" alt="Illustration of the Claude desktop app with the claude-carbon pane open: a blue pixel molecule, &quot;This session: 8.2 gCO₂ · 0.04× your median&quot;, the last 30 days as tiles and warming stripes, a &quot;Get my 2026 card&quot; button, and &quot;This session: 8.2 gCO₂&quot; under the prompt"></p>
  31. <details>
  32. <summary><b>If the install stops</b></summary>
  33. - **macOS opens a window about "command line developer tools".** That is `git`, which Claude Code needs to fetch the plugin and a Mac without developer tools does not have yet. Click **Install**, wait until it finishes (a few minutes), then install again.
  34. - **"jq is not installed" or "sqlite3 is not installed".** Tell Claude: "Install what is missing.", then restart Claude Code. Every Mac has `sqlite3`, and macOS 15 and later also have `jq`. On an older Mac, Claude can install `jq` with Homebrew, or the installer (under Other ways to install) fetches the official `jq` itself, checked against its published checksum. On Windows, `/carbon-panel` names the one missing and Claude can install it with `winget`. If `winget` answers "Access is denied", security software on the PC is blocking it: allow `winget` there, then try again.
  35. - **Windows says Git Bash is missing.** Install [Git for Windows](https://git-scm.com/downloads/win) (Claude Code needs it on Windows anyway), quit the app completely and reopen it, then install 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.
  36. - **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 as above.
  37. </details>
  38. <details>
  39. <summary><b>Other ways to install</b></summary>
  40. - **The installer**, a script that clones this repository and wires everything into `~/.claude/settings.json` itself. Paste this message into Claude Code, or run the command after the colon yourself in a terminal:
  41. ```text
  42. Install claude-carbon for me by running this command:
  43. curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 64 on GitHub
  44. ```
  45. On Windows, in PowerShell (it needs [Git for Windows](https://git-scm.com/downloads/win) and two packages first, see [Windows](#windows)):
  46. ```text
  47. Install claude-carbon for me by running this command in PowerShell:
  48. irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex
  49. ```
  50. If the mode selector under the prompt shows **Auto**, pick **Manual** first: auto mode blocks a command that downloads a script and runs it. You can read [install.sh](install.sh) before running it.
  51. - **With Node.js:** `npx claude-carbon` runs the same installer.
  52. Use one way only: the plugin and the installer together would run every hook twice. Already installed with the installer? Nothing to change, `/carbon-update` keeps it up to date.
  53. </details>
  54. Not covered: the chat and Cowork tabs and the web app (claude.ai/code). Their sessions run on Anthropic's servers, so nothing reaches your machine to count.
  55. ## Example report
  56. <p align="center">
  57. <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">
  58. </p>
  59. Generate yours with `/carbon-card` in Claude Code. The summary and detailed PNGs land in
  60. `~/Downloads/claude-carbon/` (the Windows Downloads folder follows the system setting, so a
  61. OneDrive-redirected one is honoured) and the folder opens in your file manager, with the
  62. card selected on macOS. `CLAUDE_CARBON_EXPORT_DIR` picks another folder;
  63. `CLAUDE_CARBON_NO_OPEN=1` skips the opening.
  64. Without Playwright or Chromium there is no PNG and the command still finishes: the summary
  65. card is saved as an HTML page in the same folder and opens in your browser, scaled to fit the
  66. window, and a screenshot of it does the job.
  67. 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.
  68. From the 1st to the 10th of each month the status line ends with `📊 September: 84.2kgCO₂ · /carbon-card`:
  69. the total of the month just closed, the bar the card draws for it, in the same format as the
  70. session figure. It is read from carbon.db once a day while the nudge shows, and kept in
  71. `~/.claude/claude-carbon/last-month-total`. A month with fewer than 7 days of sessions gets no
  72. nudge, so a fresh install is not pushed to share a near-empty card. Generating a card
  73. clears it for the month; it goes quiet on its own after the 10th. In December it gives the year
  74. so far instead, `📊 2026: 1444.4kgCO₂ · /carbon-card`, and stays the whole month, the card covering
  75. the calendar year. From the 1st to the 10th of January it gives the year just ended, and over those
  76. days `/carbon-card` covers that year, whole, unless you pass a period or that year has no session (the
  77. card keeps those ten days even when the reminder is turned off). `CLAUDE_CARBON_CARD_NUDGE_UNTIL_DAY`
  78. moves the cut-off (0 removes the nudge, December included), `CLAUDE_CARBON_NO_CARD_NUDGE=1` removes the nudge. Nothing is posted anywhere:
  79. sharing stays a human decision.
  80. <details>
  81. <summary>Advanced options (CLI)</summary>
  82. ```bash
  83. # Since a specific date
  84. bash ~/code/claude-carbon/scripts/generate-report.sh --since 2026-03-01
  85. # All time
  86. bash ~/code/claude-carbon/scripts/generate-report.sh --all
  87. # A closed period (--until is an exclusive upper bound: this one stops at June 30th)
  88. bash ~/code/claude-carbon/scripts/generate-report.sh --since 2026-01-01 --until 2026-07-01
  89. ```
  90. </details>
  91. <details>
  92. <summary>Custom install directory</summary>
  93. ```bash
  94. curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | CLAUDE_CARBON_DIR=~/my-path/claude-carbon bash
  95. ```
  96. The env var has to sit on the `bash` side of the pipe, not the `curl` side, or the installer never sees it.
  97. </details>
  98. <details>
  99. <summary>Second Claude environment (CLAUDE_CONFIG_DIR)</summary>
  100. If you run a second Claude Code environment out of its own config directory, e.g.
  101. ```bash
  102. alias claude-work="CLAUDE_CONFIG_DIR=~/.claude-work claude"
  103. ```
  104. install claude-carbon into that same directory by passing `CLAUDE_CONFIG_DIR` to the installer:
  105. ```bash
  106. curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | CLAUDE_CONFIG_DIR=~/.claude-work bash
  107. ```
  108. 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.
  109. </details>
  110. <details>
  111. <summary>Manual install</summary>
  112. ```bash
  113. git clone https://github.com/gwittebolle/claude-carbon.git ~/code/claude-carbon
  114. bash ~/code/claude-carbon/scripts/setup.sh
  115. bash ~/code/claude-carbon/scripts/configure-settings.sh
  116. ```
  117. 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:
  118. ```json
  119. {
  120. "statusLine": {
  121. "type": "command",
  122. "command": "~/code/claude-carbon/scripts/statusline.sh"
  123. },
  124. "hooks": {
  125. "Stop": [
  126. {
  127. "matcher": "",
  128. "hooks": [
  129. {
  130. "type": "command",
  131. "command": "~/code/claude-carbon/scripts/persist-session.sh"
  132. }
  133. ]
  134. }
  135. ],
  136. "SessionEnd": [
  137. {
  138. "matcher": "",
  139. "hooks": [
  140. {
  141. "type": "command",
  142. "command": "~/code/claude-carbon/scripts/persist-on-exit.sh"
  143. }
  144. ]
  145. }
  146. ],
  147. "SessionStart": [
  148. {
  149. "matcher": "",
  150. "hooks": [
  151. {
  152. "type": "command",
  153. "command": "~/code/claude-carbon/scripts/safety-rescan.sh"
  154. }
  155. ]
  156. }
  157. ],
  158. "SubagentStop": [
  159. {
  160. "matcher": ".+",
  161. "hooks": [
  162. {
  163. "type": "command",
  164. "command": "~/code/claude-carbon/scripts/agent-stop.sh"
  165. }
  166. ]
  167. }
  168. ]
  169. }
  170. }
  171. ```
  172. 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`.
  173. Restart Claude Code.
  174. </details>
  175. ## For teams
  176. 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:
  177. - [Free calculator](https://tokenclimate.com/en/calculator?ref=github) and [per-model factor sheets](https://tokenclimate.com/en/models?ref=github) - the exact versioned factors of this repo, browsable.
  178. - [TokenClimate](https://tokenclimate.com/en?ref=github) - hosted team dashboards. Both sides share this repo's golden vectors, verified weekly in CI.
  179. The OSS points there from five places: a one-line footer in `/carbon-report`, a small credit on the `/carbon-card` PNGs, the last line of a `/carbon-pr` comment, the foot of the `/carbon-panel` pane and the `url` field of `CITATION.cff`. No status-line promo, no email capture: nothing leaves your machine.
  180. ### PR dev footprint (/carbon-pr)
  181. 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.
  182. ```
  183. **Claude Code carbon report** · developing this PR
  184. | CO2e | Cost* | Tokens (in + cache write + out) | Cache reads | Sessions |
  185. |---|---|---|---|---|
  186. | **124 g** | $3.00 | 180k | 1.5M | 2 |
  187. ```
  188. Under the table come the car equivalence, a foldable token detail per model and a one-line footer.
  189. 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.
  190. 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:
  191. - 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;
  192. - 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.
  193. 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.
  194. 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.
  195. 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.
  196. #### For every PR of a repository
  197. A repository can ask for the report on its pull requests. Its maintainers commit this in `.claude/settings.json`, a change the team reviews like any other:
  198. ```json
  199. { "env": { "CLAUDE_CARBON_PR": "1" } }
  200. ```
  201. Nothing is posted on that alone. The first time a developer who has the plugin opens a pull request there with Claude Code (`gh pr create`), Claude asks them once whether to post the report of their own sessions under their own GitHub account. Their answer stays on their machine, per repository (`pr-consent.tsv` in the data folder):
  202. - **yes**: the comment is posted when that answer ends, then updated in place after each `git push` or `gh pr create` Claude runs there, once the answer that pushed is recorded and while the pushed branch is still the one checked out. A push you type yourself in a terminal triggers nothing. One comment per PR, and never by itself on a PR whose branch lives in a fork.
  203. - **no**, or no answer: nothing is posted and the question does not come back. `/carbon-pr` still works when they run it.
  204. Change your answer from the repository with `scripts/generate-pr-report.sh --consent yes` or `--consent never` (after a yes typed in a terminal, the first comment comes with your next push or `gh pr create` in Claude Code); a yes is only taken once the question was put to you there, which also covers a question that never showed because the turn was interrupted. The answer is kept under the repository's `origin` URL (without credentials): rename the remote and the question comes back once. A repository cannot answer for you: the answers are never read from a config folder or a database placed inside the repository, and posted by itself the comment only goes to the repository `origin` names, whatever `GH_REPO` says. `CLAUDE_CARBON_NO_PR_AUTO=1` in your own environment turns the question and the posting off everywhere. To stop it for the repository, remove the `CLAUDE_CARBON_PR` line. It needs the plugin's hooks (a marketplace install): an installer-only clone is not asked and posts nothing by itself. It is meant for a team's repository; on a public project, contributors from outside would see comments they did not ask for.
  205. #### The repository's total
  206. `scripts/generate-pr-report.sh --summary` reads back, through `gh`, the reports already posted on the repository's merged pull requests and totals them per month merged and per author. `--since 2026-10-01` narrows it. It prints in your terminal only, posts nothing and does not read your database: the figures are the ones each author posted.
  207. ```
  208. Month merged PRs Sessions CO2e Cost
  209. 2026-09 2 4 1.8 kg $57.26
  210. 2026-10 1 1 69 g $1.92
  211. Author PRs Sessions CO2e Cost
  212. alice 2 2 644 g $19.18
  213. bob-dev 1 3 1.2 kg $40.00
  214. Total: 3 PRs, 5 sessions, 1.8 kg CO2e, $59.18 at API list price.
  215. ```
  216. A comment in the older one-line form, or edited by hand, is counted as unread and left out. It covers the pull requests that carry a report, not the repository's whole footprint, and reads at most 100 of them at a time.
  217. Outside such a repository, 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.
  218. ## How it works
  219. ![claude-carbon data flow: Claude Code transcripts and status line JSON to a local SQLite database and a CO2 estimate](docs/data-flow.svg)
  220. **Three data paths, two levels of accuracy:**
  221. | Script | Trigger | Data source | Subagents | Cache reads | Accuracy |
  222. | -------------------- | ----------------------- | --------------------- | ------------ | ------------------- | ------------- |
  223. | `backfill.sh` | Manual / setup | JSONL files | Included | Counted (8% energy) | Best estimate |
  224. | `persist-session.sh` | Stop + SessionEnd hooks | JSONL files | Included | Counted (8% energy) | Best estimate |
  225. | `statusline.sh` | Every turn (live) | `carbon.db` row | Included | Counted (8% energy) | One turn late |
  226. **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.
  227. 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.
  228. **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`.
  229. **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.
  230. ### The status line
  231. Segments, left to right: project + git branch, model + context window %, API-equivalent session cost + CO2, subscription quota % + reset time. The quota is the 5-hour window, or the weekly one when no 5-hour window is open (always, on a verified Ultra account; on Pro and Max, between a 5-hour window's reset and your next request): `Use 41% 7d ↻Thu`, the reset as a weekday while it is more than a day away. A 🔥 prefix appears when the sustained burn rate would overshoot 100% of the limit by the end of the window (once usage reaches 15%, after a grace of 15 min for the 5-hour window and of a day for the weekly one).
  232. > **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](#the-mod-carbon-panel-and-the-co2-of-each-answer) draws the CO2 in its Code tab.
  233. **Quota source.** The percentage is Anthropic's own, the same data Claude Code displays in `/usage`. No heuristic, no token-limit file to seed. Two sources in order:
  234. 1. **stdin** (preferred): the `rate_limits` Claude Code passes in the statusline JSON, `five_hour` first, else `seven_day`. When `rate_limits` is there, a window it leaves out does not exist, and nothing else is asked.
  235. 2. **OAuth API fallback**, only when stdin has no `rate_limits` (before the session's first response, or with an older Claude Code): `GET https://api.anthropic.com/api/oauth/usage` with the bearer token from macOS Keychain, `CLAUDE_CODE_OAUTH_TOKEN`, or `~/.claude/.credentials.json`, at most once a minute whether it answers or not. The answer is cached in `~/.claude/claude-carbon/oauth-usage.json`; a window without a reset time, or whose reset has passed, is left out.
  236. Accurate on Pro, Max and Ultra.
  237. ### Surviving the 30-day transcript purge
  238. 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.json` + `data/prices.json` at any time, with no transcript needed. When Anthropic changes a price or a factor is revised, edit the config and run:
  239. ```bash
  240. bash scripts/recompute.sh
  241. ```
  242. Sessions recorded since September 2026 are re-derived model by model, exactly. Older sessions without a per-model split keep their stored values; `--include-unsplit` re-derives them at their dominant model, an approximation (see METHODOLOGY.md, "Surviving the 30-day transcript purge").
  243. ## Commands
  244. | Command | What it does |
  245. | ---------------- | --------------------------------------------------- |
  246. | `/carbon-report` | Text report with totals, car equivalent, share of a 2 t budget, top sessions |
  247. | `/carbon-card` | Generate shareable PNG report cards |
  248. | `/carbon-badge` | Shields.io badge of your total footprint for your READMEs |
  249. | `/carbon-pr` | Post the dev footprint of the current branch on its PR |
  250. | `/carbon-update` | Update to the latest version, whichever way you installed |
  251. <details>
  252. <summary>Scripts (run automatically, rarely needed manually)</summary>
  253. | Script | What it does |
  254. | -------------------- | ----------------------------------------------------------------------------------------- |
  255. | `setup.sh` | Init database, backfill historical sessions, show total |
  256. | `statusline.sh` | Status line script (called automatically by Claude Code) |
  257. | `persist-session.sh` | Stop hook (saves session data after each turn) |
  258. | `persist-on-exit.sh` | SessionEnd hook (saves the session once more as it closes, in the background) |
  259. | `safety-rescan.sh` | SessionStart hook (throttled background re-scan, catches missed sessions) |
  260. | `agent-stop.sh` | SubagentStop hook (the branch an agent worked on, for `/carbon-pr`) |
  261. | `backfill.sh` | Re-parse all historical JSONL transcripts (incl. subagents) |
  262. | `recompute.sh` | Re-derive cost/CO2 from stored tokens after a price/factor change (no transcripts needed) |
  263. | `generate-report.sh` | Export PNG report cards (CLI, with `--since` / `--until` / `--all`) |
  264. | `generate-badge.sh` | Print the shields.io badge markdown + URL (CLI) |
  265. | `generate-pr-report.sh` | Post the branch's dev footprint on its PR (CLI, `--dry-run` / `--pr`) |
  266. Note: backfill now derives project names from the transcript's `cwd` (matching the live hook). Sessions backfilled before this change keep their old, possibly truncated names; delete those rows and re-run `backfill.sh` to normalize them.
  267. </details>
  268. ## Badge
  269. `/carbon-badge` prints a ready-to-paste shields.io badge with your measured all-time footprint and the month it was taken, clickable to the methodology:
  270. [![Claude Code carbon footprint](https://img.shields.io/badge/claude--carbon-1139.2%20kg%20CO2e%2C%202026--09-2f6f4f)](https://github.com/gwittebolle/claude-carbon/blob/main/METHODOLOGY.md)
  271. <sub>That badge is live, not a mockup: the author's own total, 1,208 sessions measured between 15 January 2026 and 16 September 2026. It is one developer's footprint, not the project's.</sub>
  272. ```markdown
  273. [![Claude Code carbon footprint](https://img.shields.io/badge/claude--carbon-1139.2%20kg%20CO2e%2C%202026--09-2f6f4f)](https://github.com/gwittebolle/claude-carbon/blob/main/METHODOLOGY.md)
  274. ```
  275. The badge is a static image built from your local database, so the number is measured, not estimated on the fly, and nothing is sent anywhere. The month in the message says how old the figure is; re-run `/carbon-badge` whenever you want to refresh both.
  276. It is one developer's total, so it belongs in your profile README or a personal project. In a team or organisation repository, reviewers will ask what produced the number and why it links out of the organisation, and they will be right to.
  277. Numbers follow the locale the report uses (`fr` prints `12,4 kg`, `us` and the world default print `12.4 kg`); `CLAUDE_CARBON_LOCALE` forces a set.
  278. ## The mod: /carbon-panel and the CO2 of each answer
  279. The claude-carbon plugin also holds a [Claude Code mod](https://code.claude.com/docs/en/plugins/mods/overview) that shows the CO2 of each answer when it ends, computed locally with the same formula and factors as the status line, and the session's total with its API-price cost.
  280. - **Terminal**, including the integrated terminal of an editor and the JetBrains plugin: at the right end of the line that closes each answer, `✻ Worked for 38s · done 10:32 PM 16 gCO₂`. A line keeps its own answer's figure when it is drawn again (a resize, a scroll, ctrl+o); a line drawn for the first time later, such as one only ctrl+o shows, gets no figure.
  281. - **Desktop app, Code tab**: a line under the answer, only for an unusual answer.
  282. - **An unusual answer** shows the ratio, and the subagents' share when they weighed on it: `230 gCO₂ · 14× your median`. An answer is unusual when it is above the 97th percentile of your last 200 answers, over 3× their median and at least 10 g, which is about one answer in 27; none is flagged before 50 answers are recorded.
  283. - **The session total** is pinned under the prompt, CO2 and API-price cost: `This session: 142 gCO₂ · $3.41`, in French `Cette session : 142 gCO₂ · 3,41 $`. It shows unless the claude-carbon status line already gives it or the `showSessionTotal` option is off (both in a terminal only, see [ccstatusline](#using-with-ccstatusline)). The cost is the pay-as-you-go API list price of the same requests as the CO2, from `data/prices.json` with the formula of `/carbon-report`, cache writes at the 1-hour tier Claude Code uses; under a cent it reads `< $0.01`, and it is left out when the price list cannot be read, then until the total starts over, so the cost never covers only part of the requests. It is what the usage would cost on the API, not what a subscription bills. On a subscription the entry ends with the quota as the status line shows it, `Use 23% ↻14:00` (`Usage 23 % ↻14:00`): the share of the 5-hour window used and the local time it resets, or without a 5-hour window the weekly one, `Use 41% 7d ↻Sat` (`Usage 41 % 7j ↻sam.`), read from Claude Code itself after each answer, with no network call. Then come the status line's two hints: `⬆ 1.18.0 /carbon-update` when a newer version is out, and from the 1st to the 10th of the month the month just closed with its total, `📊 September: 84.2 kgCO₂ · /carbon-card`, until you make the card. Background subagents, which is how Claude Code starts most of them, count in the session total only: never in an answer, nor in your median. A foreground subagent counts in the answer that started it, not in the next one.
  284. - **`/carbon-panel` opens a pane** with the mascot, a pixel CO2 molecule. Its colour compares this session with the median of your past sessions, from dark blue (under an eighth of it) to dark red (over eight times it). Until 10 sessions are recorded it compares with a starting reference of 0.5 kgCO₂ instead, so it has a colour from the first answer. It hops a pixel up and down while Claude works, faster as it gets redder, and pulls faces as it goes: it looks around before the first answer, blinks and glances aside at work, smiles through a light session and sweats through a heavy one, reacts to each answer, winks at rest, and falls asleep after five minutes without a turn.
  285. <p align="center"><img src="docs/molecule-moods.svg" width="560" alt="The molecule's eight moods: it looks around before the first answer, glances aside at work, smiles through a light session, sweats through a heavy one, smiles or startles after an answer, winks at rest and falls asleep after five idle minutes"></p>
  286. - **In the desktop app** the pane opens on the right, its tab titled "claude-carbon", in two blocks. Under the molecule, the colour scale, the eight colours from blue to red, with a marker under this session's. *This session*: its CO2, answers, subagents and model, its context window's fill and API-price value, and a small molecule per subagent, coloured by its own CO2. *My usage*: the period you pick (the last 7 or 30 days, 12 months, everything, or two dates you type, `01/05/2026`), its figures as tiles (CO2 as the reports sum it, change against the same length of time before, sessions, API-price value, car equivalence), then warming stripes of that period, a day, a week or a month a stripe after its length, each coloured against the median of the periods shown. The stripe under the pointer lights up and its date, total and sessions show under the stripes. A tile with an (i) shows its note when you click the (i), and hides it at a second click: the API-price value is what this usage costs billed through the API, and a Pro, Max or Ultra subscription covers some or all of it (which session was billed how is not recorded, so the pane never says what you paid). A gear beside "My usage" turns the change, the API-price value, the car, the split by project (off until you turn it on, each folder with its share and kgCO2) and the detail on or off; the pane keeps your choices for the next session. The detail (off until you turn it on) splits the period by kind of token, uncached input, cache writes, cache reads and output: two coloured bars give each kind's share of the tokens and of the CO2 (the part under the pointer lights up and its figures show under the bar), then a line per kind its tokens, energy and CO2 with their shares. The CO2 of each session is the one stored, split with the weights the factors give each kind (cache reads 0.08 of an input token, output about 21 times one), so the parts add up to what was stored; a session stored with older factors (before July 2026), whose CO2 no longer matches its tokens, is left out and the block says over how many sessions it splits; the energy is the one the factors start from (energy per token, PUE included, converted to CO2 with the AWS us-east grid at 287 gCO2/kWh), found back by dividing that CO2 by the same intensity. It needs the tokens by kind in `sessions-history.tsv`, which the hooks write from this version on: after an update, the detail shows from the next answer. A "Get my 2026 card" button puts `/carbon-card` in an empty prompt for you to send (the card covers the calendar year so far, whatever range the pane shows); it never sends it and leaves a draft you have started alone. A few short lines at the foot link to this repository, the author's LinkedIn profile and TokenClimate, the business version.
  287. - **In the terminal** `/carbon-panel` typed at the prompt shows this session in the band right above it, in the classic and the fullscreen rendering alike (sent from the desktop app or a phone to a session running in a terminal, through Remote Control, it opens the side pane there instead): a small molecule of 13 columns by 4 rows in half blocks, and beside it the session's CO2, answers, subagents (a dot each, in its colour), model, context window and API-price value. The period and the stripes live in the desktop app.
  288. - Run `/carbon-panel` again to close the pane or clear the band. The command is also a skill of the plugin, so the desktop app lists it; where the mod does not run (the VS Code chat panel, a cloud session) it only says where the pane opens.
  289. - **The stripes' history** is `sessions-history.tsv`, which the Stop hook writes next to `carbon.db` after each answer, read-only on the database. Every recorded session is in it, older rows as they were stored (they keep the factors of their time and are never recomputed), so the stripes, the median and the totals count what `/carbon-report` counts. Another session running at the same time counts with its total so far. With no database yet (before the first session start of a plugin installed alone, or with `jq` or `sqlite3` missing), the pane shows the molecule and says what the history waits for.
  290. Claude Code draws mods in the terminal and in the desktop app's Code tab only: nothing appears in the VS Code extension's chat panel, in cloud sessions or with `claude -p`. Mods need Claude Code 2.1.287 or later (2.1.286 in the desktop app).
  291. The mod comes with the plugin. Already installed from the marketplace: run `/plugin marketplace update claude-carbon` and `/plugin update claude-carbon@claude-carbon`, then restart Claude Code.
  292. The plugin alone records your sessions, and sets the terminal status line when you have none (see [Install](#install)):
  293. ```
  294. /plugin install claude-carbon --marketplace gwittebolle/claude-carbon
  295. ```
  296. At the first session start after the install, the plugin creates its database in `~/.claude/claude-carbon/` and fills it with the sessions whose transcripts are still on disk (about the last 30 days, every project), then records each session as it goes. A one-time message says so at one of the next session starts. It needs `jq` and `sqlite3`: when one is missing nothing is created, and `/carbon-panel` names it. This happens once: a database you delete is not brought back (delete the `auto-setup` file beside it to ask for a new one), a database path set with `CLAUDE_CARBON_DB` is never created for you, and `CLAUDE_CARBON_NO_AUTOSETUP=1` turns it off. From then on the daily background check for a newer release runs as it does for the installer (`CLAUDE_CARBON_NO_UPDATE_NOTIFIER=1` to opt out).
  297. #### In a team repository
  298. To offer the plugin to everyone who works in a repository, commit this in its `.claude/settings.json`:
  299. ```json
  300. {
  301. "extraKnownMarketplaces": {
  302. "claude-carbon": { "source": { "source": "github", "repo": "gwittebolle/claude-carbon" } }
  303. },
  304. "enabledPlugins": { "claude-carbon@claude-carbon": true }
  305. }
  306. ```
  307. Enabling it in the repository does not download it to anyone's machine, since the plugin comes from a remote marketplace: each collaborator runs `claude plugin install claude-carbon@claude-carbon --scope project` once in their clone, after trusting the folder. Anyone who does not want it sets `"claude-carbon@claude-carbon": false` under `enabledPlugins` in their own `.claude/settings.local.json`. Each person's figures stay on their machine.
  308. The curl, PowerShell and npm installers set up the status line, the database and the hooks, and copy the mod alone to `~/.claude/skills/claude-carbon/`, which Claude Code loads as `claude-carbon@skills-dir`. `/carbon-update` keeps that copy up to date. The copy holds no hook, so nothing runs twice. Restart Claude Code after the install; the mod loads once the folder you open is trusted. Its median starts from zero: answers recorded by another install of the mod do not carry over. With this copy the mod shows in the terminal, in the editor's integrated terminal and in the desktop app's Code tab.
  309. To turn it off, run `claude plugin disable claude-carbon@skills-dir`. To remove it, run the installer with `CLAUDE_CARBON_NO_MOD=1` on the `bash` side (`curl … | CLAUDE_CARBON_NO_MOD=1 bash`); keep the variable set, in your shell or in the `env` block of `settings.json`, or the next `/carbon-update` puts it back. The installer leaves alone a `skills/claude-carbon/` folder it did not make, and skips the copy while the claude-carbon plugin is enabled. Pick one of the two: the plugin added on top of an installer runs the hooks twice.
  310. Turn the per-answer figure off with the `showPerTurn` option in `/config`. The mod writes no database, starts no process, makes no network call and never changes what Claude does; besides its own data files, it reads only `sessions-history.tsv`, the two release flags of the daily check (`plugin-update-check.json`, `update-check.json`), `last-card-month`, and the two files the SessionStart hook leaves when it finds no database (`setup-needed`, `auto-setup`). Text is in French when the first of `CLAUDE_CARBON_LOCALE`, `LC_ALL`, `LC_MESSAGES` and `LANG` that is set starts with `fr`, and in English otherwise. When none is set, as in the desktop app and often on Windows, the `language` setting decides (`Français`, `English`), then French.
  311. The mod's own tests run with `bash tests/run-mod-kit.sh`, under `claude plugin test`, which mocks the engine: no login needed. CI runs them on every push with Claude Code 2.1.296.
  312. ## Using with ccstatusline
  313. Claude Code accepts a single `statusLine` command, so claude-carbon's full status line and [ccstatusline](https://github.com/sirmalloc/ccstatusline) cannot run side by side. If ccstatusline drives your status line, embed the CO2 segment instead: in the ccstatusline TUI, add a `Custom Command` widget pointing to
  314. ```
  315. ~/code/claude-carbon/scripts/statusline.sh --segment
  316. ```
  317. (adjust the path if you installed with `CLAUDE_CARBON_DIR`). The widget receives the same status JSON on stdin and prints just the cost + CO2 pair, e.g. `$0.68 · 35gCO₂`. Segment mode never touches the network. Recording to the local database is unaffected either way: persistence runs from hooks, not from the status line.
  318. With the segment in ccstatusline, the [mod](#the-mod-carbon-panel-and-the-co2-of-each-answer)'s session entry under the prompt shows the total a second time. Turn it off with the `showSessionTotal` option in `/config`; the desktop app, which has no status line, keeps it.
  319. ## Emission factors
  320. Factors from [Jegham et al. 2025](https://arxiv.org/abs/2505.09598), an arXiv preprint that estimates the energy consumption of LLM inference on AWS infrastructure from public API performance data (latency, throughput) over inferred hardware configurations.
  321. | Model | Read for the first time (input, cache write) | Re-read (cache read) | Written (output) | Basis |
  322. | ------ | -------------------------------------------- | -------------------- | ---------------- | --------------------------- |
  323. | Fable | 156 | 12.5 | 3304 | Extrapolated (2x Opus) |
  324. | Opus | 78 | 6.2 | 1652 | Extrapolated (2x Sonnet) |
  325. | Sonnet | 39 | 3.1 | 826 | 3-point fit (Jegham v6) |
  326. | Haiku | 10 | 0.8 | 207 | Extrapolated (0.25x Sonnet) |
  327. In gCO2e per million tokens. In a Claude Code session, about 98% of the tokens are context Claude re-reads at each step. Each of them weighs little, but together they make about 60% of the CO2; the text Claude writes is under 1% of the tokens and about 30% of the CO2 (30 days of the author's sessions, October 2026).
  328. **Important: these are order-of-magnitude estimates, not precise measurements.**
  329. - Sonnet factors are a 3-point least-squares fit to the three Claude 3.7 Sonnet per-query energies estimated in Jegham et al. v6 (0.950 / 2.989 / 5.671 Wh), giving a ~21:1 output:input ratio; independent public estimates land within the same order of magnitude. Fable, Opus and Haiku are extrapolated (no public data from Anthropic on per-model energy consumption): Opus = 2x Sonnet (honest band 2x-5x), Haiku = 0.25x, Fable = 2x Opus. See [METHODOLOGY.md](METHODOLOGY.md).
  330. - Sessions run on non-Anthropic models (e.g. local models behind `ANTHROPIC_BASE_URL`) are stored with their raw tokens but zero cost/CO2 and excluded from reports - a datacenter factor doesn't apply to them. Add patterns to `exclude_models` in `data/factors.json` to exclude more models by name.
  331. - Cache read tokens are counted at a reduced factor (default 0.08 of an input token, set in `data/factors.json`). A cached token skips most of the prefill compute; the factor is the residual. This is an engineering estimate derived from the literature, not Anthropic's 0.1x billing ratio. The decode-phase re-read of the cache grows with context length x generated tokens and is not modelled yet; every session stores that product (`output_context_sum`) so a calibrated term can be applied to history later. See [METHODOLOGY.md](METHODOLOGY.md).
  332. - Reviewed against the April-September 2026 literature (measurement papers, provider disclosures, the Watershed framework) with a sensitivity run on 30 days of real transcripts: no factor moved, the displayed figure is more likely low than high, next review March 2027. See [Where the estimate stands](METHODOLOGY.md#where-the-estimate-stands-september-2026).
  333. - Carbon intensity uses the AWS region grid (location-based, 0.287 kgCO2e/kWh), not real-time grid data. This sits at the low end of the location-based range; the US national average is ~380 g/kWh.
  334. - Anthropic does not publish Scope 1, 2, or 3 emissions. These estimates are independent and based on academic research, not provider data.
  335. The car equivalent in reports and cards follows your locale, since a km by car emits up to ~1.7x more in one country than in another: ADEME's 142 gCO2e/km on a French or undetected locale, EPA's 393 gCO2e/mile on a US locale, a 200 gCO2/km world average otherwise. Force a set with `CLAUDE_CARBON_LOCALE` (`fr`, `us`, `world`, or any locale string). The factors live in `data/factors.json` under `equivalences`.
  336. `/carbon-report` also gives this calendar year's total as a share of 2 tCO2e, the 2050 per-person target for a whole footprint (ADEME, [Nos Gestes Climat](https://nosgestesclimat.fr/blog/environnement/reduire-empreinte-carbone-objectif-deux-tonnes), from the IPCC 1.5 °C scenarios; also Carbone 4, *Faire sa part ?*, 2019). It is there for scale: the 2 t covers everything a person emits in a year, AI included. Sources and caveats: [METHODOLOGY.md](METHODOLOGY.md#annual-budget-line).
  337. Factors are editable in `data/factors.json`. See [METHODOLOGY.md](METHODOLOGY.md) for the full scientific basis, formula, and equivalences.
  338. ### Golden vectors
  339. The methodology is pinned by golden test vectors in [`tests/methodology-vectors.json`](tests/methodology-vectors.json): hand-computed expected CO2/cost values for known token breakdowns, replayed by `bash tests/run-vectors.sh` in CI on every push. Downstream consumers (such as TokenClimate) keep a copy of this file and verify weekly that their implementation produces the same numbers. If you edit `data/factors.json` or `data/prices.json`, update the vectors in the same commit, otherwise CI fails.
  340. ## Updating
  341. When a newer version is available, the status line shows a discreet `⬆ /carbon-update` hint. The check runs in the background (at most once a day, never on the status line's hot path); opt out with `CLAUDE_CARBON_NO_UPDATE_NOTIFIER=1`.
  342. - **In a terminal with a git-clone install**, that hint appears at the end of the status line, naming the new version.
  343. - **Everywhere the mod runs** (the desktop app, and a terminal without the claude-carbon status line), the same hint ends the session entry under the prompt, and the `/carbon-panel` pane names the version at the top of its foot. For a plugin install, the same daily background check asks GitHub for the release tags only and never touches Claude Code's plugin cache.
  344. - **Installed before the summer of 2026** (version 1.0, no hint at all)? Run the install again, from the app or the terminal, as in [Install](#install).
  345. To update, run `/carbon-update` in Claude Code, whichever way you installed: for the plugin it runs Claude Code's `claude plugin marketplace update claude-carbon` and `claude plugin update claude-carbon@claude-carbon`, for the installer's clone its own updater. Restart Claude Code afterwards. With both installs, as when the status line runs from a clone, only the plugin is updated and the command gives the `git pull` for the clone. You can also re-run the installer:
  346. ```bash
  347. curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 501 on GitHub
  348. ```
  349. - Updating an installer's clone re-prices your stored history with the new factors automatically (CO2 only; cost figures are left intact); updating the plugin does not. Run `scripts/recompute.sh --with-cost` yourself only after a price change.
  350. - If you edited `data/factors.json` or `data/prices.json` locally, the update keeps your edits; on a conflict with upstream it saves yours to `*.local.bak` and tells you.
  351. - The update also refreshes the [mod](#the-mod-carbon-panel-and-the-co2-of-each-answer)'s copy. When it asks for a restart (on Windows, a copy in use cannot be replaced), restart Claude Code and run it again; until then the previous copy stays.
  352. - Installed from the plugin marketplace, you can also let Claude Code update it by itself: in `/plugin`, tab **Marketplaces**, select `claude-carbon`, then **Enable auto-update**. The new version loads with the next session.
  353. ## Uninstalling
  354. For an install made by the curl, PowerShell or npm installer:
  355. ```bash
  356. bash ~/code/claude-carbon/scripts/configure-settings.sh --remove
  357. ```
  358. (adjust the path if you installed with `CLAUDE_CARBON_DIR`). It takes the status line, the hooks, the `/carbon-*` commands and the mod's copy out of `~/.claude`, and nothing that belongs to another tool: a status line that calls `statusline.sh --segment` stays, and so does any other hook of a group it shared. Your history stays in `~/.claude/claude-carbon/`. To remove everything, delete that folder and the clone afterwards.
  359. For the plugin: `claude plugin uninstall claude-carbon@claude-carbon`, then take the `statusLine` entry that names `claude-carbon/statusline.sh` out of `~/.claude/settings.json`: the plugin cannot do it as it goes, and once it is gone that status line prints nothing. A plugin turned off rather than uninstalled keeps drawing it, until you take that entry out. `CLAUDE_CARBON_NO_STATUSLINE=1` keeps the plugin from setting a status line at all. The plugin sets it once: to have it set again after you removed it, delete `~/.claude/claude-carbon/statusline-set`.
  360. Installing a second copy on top of a first one (another folder, or the installer after the plugin's clone) would run every hook twice. The installer stops when it finds another install wired into `settings.json`, names it, and gives the command that takes its place (`configure-settings.sh --replace`). Hooks left by an install whose folder was deleted are replaced without asking.
  361. ## Dependencies
  362. - `jq` - JSON parsing
  363. - `sqlite3` - local database
  364. - `git` - branch detection in status line (optional)
  365. - `curl` - subscription quota via Anthropic's `/api/oauth/usage` endpoint when Claude Code does not pass it (optional, at most once a minute)
  366. - `node` + Google Chrome, Microsoft Edge, Chromium or Brave (or `playwright-core` and its Chromium) - PNG export for `/carbon-card` (optional)
  367. `sqlite3` is pre-installed on every Mac, and `jq` from macOS 15 (Sequoia) on. On an older Mac with no `jq`, the installer downloads the official jq 1.8.1 binary for the Mac's processor, checks it against the SHA-256 the jq project publishes, and puts it in `~/.claude/claude-carbon/bin/`, where the scripts and the slash commands find it; a `jq` installed later (Homebrew, for one) takes precedence. On Linux: `apt install jq sqlite3`. On Windows, see below.
  368. `/carbon-card` draws its PNGs with a Chromium-family browser run headless, in a throwaway profile. It uses Playwright's Chromium when `playwright-core` is installed (looked for in node's own resolution, the global npm root, `~/node_modules` and Homebrew's node modules), and otherwise the first browser found in its usual place: Google Chrome, Microsoft Edge, Chromium or Brave on macOS, Chrome or Edge on Windows, and on Linux the first of them on the `PATH`. `CLAUDE_CARBON_BROWSER` names another one, by path or by command, or `none` to skip the lookup. A browser that has drawn nothing after 60 seconds is stopped and not tried again. With no browser at all, the card opens in your default browser as a page, and a screenshot of it is the card.
  369. ## Windows
  370. claude-carbon is bash, and stays bash on Windows. That is deliberate rather than a
  371. shortcut: on native Windows, Claude Code runs status line and hook commands through
  372. the bash that ships with [Git for Windows](https://git-scm.com/downloads/win), falling
  373. back to PowerShell only when Git Bash is absent
  374. ([status line docs](https://code.claude.com/docs/en/statusline#windows-configuration),
  375. [hooks docs](https://code.claude.com/docs/en/hooks)). The plugin speaks the shell its
  376. host already spawns.
  377. **Native Windows.** Install Git for Windows first, then restart Claude Code so that it finds Git Bash:
  378. ```powershell
  379. winget install Git.Git --source winget
  380. ```
  381. Then, in the same terminal, install `jq` and `sqlite3`, the two commands Git for Windows does not ship, and run the installer:
  382. ```powershell
  383. winget install jqlang.jq --source winget
  384. winget install SQLite.SQLite --source winget
  385. irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex
  386. ```
  387. The installer checks for both and prints the `winget` command for any still missing; it does not run `winget` itself.
  388. Everything else the plugin needs - `bash`, `awk`, `sed`, `grep`, `date`, `curl`,
  389. `git`, `cygpath` - comes with Git for Windows.
  390. **WSL 2.** Nothing special: run the `curl | bash` installer inside your distribution.
  391. Claude Code, its transcripts and claude-carbon all live on the Linux side. This is
  392. the path to pick if your projects are already in WSL. VS Code reaches it through the
  393. Remote - WSL extension.
  394. **Marketplace install.** `/plugin install claude-carbon@claude-carbon` behaves the
  395. same as on macOS, once Git for Windows, `jq` and `sqlite3` are present.
  396. ### Windows specifics
  397. - **Git Bash is required.** Without it Claude Code routes commands to PowerShell,
  398. which cannot run a `.sh` file. `claude doctor` tells you which shell it picked. If
  399. Git is installed somewhere unusual, point Claude Code at it in `settings.json`:
  400. `{"env": {"CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"}}`.
  401. - **Paths in `settings.json` use forward slashes** (`C:/Users/you/code/claude-carbon/...`).
  402. Git Bash eats unquoted backslashes, and the command then fails with no visible error.
  403. The installer writes them correctly; only hand-edits need the care.
  404. - **Slash commands are copied, not symlinked.** Git Bash cannot create a real symlink
  405. without Developer Mode, so `/carbon-report` and friends are copied into
  406. `~/.claude/commands/` and refreshed on every update.
  407. - **Sandboxing is not available** on native Windows (a Claude Code limitation, not
  408. this plugin's). Use WSL 2 if you need it.
  409. - **`/carbon-card` additionally needs Node.js**: `winget install OpenJS.NodeJS --source winget`.
  410. - **`winget` answers "Access is denied" (`0x80070005`)**: security software on the PC is
  411. blocking it, an antivirus's behaviour protection for one. Allow `winget` there and run
  412. the command again.
  413. - **Behind a TLS-inspecting proxy or antivirus**, the clone fails with
  414. `SSL certificate problem: unable to get local issuer certificate`. Git for Windows
  415. checks certificates against its own bundled CA list, which does not know the root
  416. such tools re-sign traffic with; the Windows certificate store does. Switch git to
  417. it (verification stays on) and rerun the installer:
  418. `git config --global http.sslBackend schannel`. The installer prints this hint
  419. when it detects the case. The same interception is why `winget` needs
  420. `--source winget` on those machines: the Microsoft Store source fails its
  421. certificate check and, without an explicit source, winget aborts instead of
  422. falling back.
  423. CI runs the full test suite on `windows-latest` under Git Bash, alongside Ubuntu,
  424. plus two Windows-only suites: `tests/run-windows-e2e.sh` (native paths through the Stop
  425. hook and the status line, hook manifests spawned the way Claude Code spawns them) and
  426. `tests/run-install-ps1-tests.ps1`.
  427. ## Reduce your footprint
  428. Measuring is step one. The levers below are ordered by what the 2026 measurement literature and this tool's own sensitivity run on real transcripts say matters most. None of them comes with a percentage: the emission factors carry a wider uncertainty band than any gain figure would. `/carbon-report` before and after a change, over several sessions, is the measurement that applies to you. The mechanism, the direction and the sources of each lever are in [docs/reduce.md](docs/reduce.md).
  429. - **Keep the context short when the model generates.** Almost every token of a session is a cache read, and the energy of a generated token grows with the context it is generated in. One session per task, `/clear` when the subject changes, `/btw` for side questions, subagents for exploration and verbose operations.
  430. - **Compact on your terms.** `/compact <instructions>` at a natural break, `/rewind` when abandoning a path, `/autocompact 150k` to bound the window, `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` on models that run at 1M by default.
  431. - **Trim what every turn carries.** `/context` shows it. A short `CLAUDE.md` with the rest in skills, unused MCP servers off with `/mcp`, a CLI over an MCP server where both exist.
  432. - **Do not break the cache mid-session.** Pick the model and the effort level at the start; `/usage` shows the hit ratio and the likely cause of the last miss.
  433. - **Fewer turns, fewer failed loops.** A spec and a test the agent can run, a deterministic tool over a retry, `/clear` after two failed corrections, no `/loop` left running on an idle session.
  434. - **Ask the agent only what needs an agent.** An agentic task runs on the order of a thousand times the tokens of a chat exchange. A `--help` costs nothing.
  435. - **Match reasoning and model to the task.** `/effort low` on routine work, set at session start; Haiku for subagents via `CLAUDE_CODE_SUBAGENT_MODEL`.
  436. The same document covers what does not hold up (shell output filters, prompt compressors, adding up percentages), the harness as a lever, and what is out of your hands for now.
  437. ### Related projects
  438. - [EcoLogits](https://ecologits.ai) - Python library estimating the footprint of GenAI API calls across providers.
  439. - [CodeCarbon](https://github.com/mlco2/codecarbon) - measures the emissions of compute you run yourself (training, local inference).
  440. - [ImpactIA](https://github.com/SNCFdevelopers/ImpactIA) - AI impact calculator and guide by SNCF, Wavestone and Resilio.
  441. - [green-claude](https://github.com/Institut-du-Numerique-Responsable/green-claude) - Claude Code skill that steers generated code toward eco-design rules (RGESN, GR491).
  442. ### Further reading
  443. - [IEA - Energy and AI (2025)](https://www.iea.org/reports/energy-and-ai/) - data center projections
  444. - [Jegham et al. - How Hungry is AI?](https://arxiv.org/abs/2505.09598) - per-model energy estimates
  445. - [UCL/UNESCO - 90% AI energy reduction](https://www.ucl.ac.uk/news/2025/jul/practical-changes-could-reduce-ai-energy-demand-90) - frugal AI approaches
  446. - [GreenIT.fr - AI impacts 2025-2030](https://www.greenit.fr/impacts-ia-monde-2025-2030-rapport/) - French data
  447. ## Why
  448. Every Claude Code session uses real compute, real energy, real emissions. The number is small per query, but it adds up. Making it visible is the first step to owning it.
  449. ## Citing
  450. If claude-carbon's numbers or methodology end up in your article, talk or product, a citation is appreciated. GitHub's "Cite this repository" button generates BibTeX/APA from [CITATION.cff](CITATION.cff). Short form:
  451. > Wittebolle, G. (2026). claude-carbon: carbon footprint tracker for Claude Code sessions. https://github.com/gwittebolle/claude-carbon
  452. The shareable report cards already carry this attribution in their footer, so reposting a card as-is credits the tool.
  453. ## Open source
  454. claude-carbon is free and open source under the [MIT license](LICENSE). Contributions welcome.
  455. <p align="center"><img src="docs/mascot-stripes.svg" width="696" alt="Eight pixel CO2 molecules, the claude-carbon mascot, walking from dark blue to dark red, the redder the faster: the blue ones smile, the red ones sweat"></p>
  456. The stripes of the banner and of `/carbon-panel` are inspired by Ed Hawkins' [warming stripes](https://showyourstripes.info), drawn here from your own sessions.
  457. Built by [Gaëtan Wittebolle](https://gaetanwittebolle.com), carbon consultant turned solo builder in Bordeaux, France. Team version: [TokenClimate](https://tokenclimate.com).
bin/claude-carbon.js · Bundled script · 99 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. // npx claude-carbon — thin wrapper around the git-based installer.
  3. // Downloads the installer from the repo and runs it; the plugin itself
  4. // lives in a git clone, not in this npm package.
  5. "use strict";
  6. const { spawnSync } = require("node:child_process");
  7. const { mkdtempSync, writeFileSync } = require("node:fs");
  8. const { tmpdir } = require("node:os");
  9. const { join } = require("node:path");
  10. const pkg = require("../package.json");
  11. // macOS and Linux run install.sh through bash. Windows runs install.ps1, the same
  12. // bootstrap as `irm ... | iex`: it finds Git Bash, checks for the jq and sqlite3 that
  13. // Git for Windows does not ship, printing the winget command for each missing one,
  14. // then hands over to install.sh. Running install.sh straight from here stopped at
  15. // the first missing one.
  16. const WINDOWS = process.platform === "win32";
  17. const INSTALL_URL = WINDOWS
  18. ? process.env.CLAUDE_CARBON_INSTALL_PS1_URL ||
  19. "https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1"
  20. : process.env.CLAUDE_CARBON_INSTALL_URL ||
  21. "https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh";
  22. const arg = process.argv[2];
  23. if (arg === "--version" || arg === "-v") {
  24. console.log(pkg.version);
  25. process.exit(0);
  26. }
  27. if (arg === "--help" || arg === "-h") {
  28. console.log(`claude-carbon ${pkg.version}
  29. Track the carbon footprint of your Claude Code sessions.
  30. Usage: npx claude-carbon [--dry-run]
  31. Downloads and runs the installer from:
  32. ${INSTALL_URL}
  33. Options:
  34. --dry-run Download the installer and print its path without running it
  35. --version Print the wrapper version
  36. --help Show this help
  37. Docs: ${pkg.homepage}`);
  38. process.exit(0);
  39. }
  40. if (arg !== undefined && arg !== "--dry-run") {
  41. console.error(`Unknown option: ${arg}\nTry: npx claude-carbon --help`);
  42. process.exit(2);
  43. }
  44. async function main() {
  45. const res = await fetch(INSTALL_URL);
  46. if (!res.ok) {
  47. console.error(
  48. `Could not download the installer (HTTP ${res.status}): ${INSTALL_URL}`,
  49. );
  50. process.exit(1);
  51. }
  52. let script = await res.text();
  53. const file = join(
  54. mkdtempSync(join(tmpdir(), "claude-carbon-")),
  55. WINDOWS ? "install.ps1" : "install.sh",
  56. );
  57. // Windows PowerShell 5.1 reads a script file without a BOM in the ANSI code page
  58. if (WINDOWS && !script.startsWith("")) script = `${script}`;
  59. writeFileSync(file, script, { mode: 0o700 });
  60. if (arg === "--dry-run") {
  61. console.log(`Downloaded installer to ${file} (not run: --dry-run)`);
  62. process.exit(0);
  63. }
  64. // -ExecutionPolicy Bypass for this one process only, as `irm | iex` already is:
  65. // the default Restricted policy refuses any script file.
  66. const [cmd, args] = WINDOWS
  67. ? [
  68. "powershell.exe",
  69. ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", file],
  70. ]
  71. : ["bash", [file]];
  72. const { status, error } = spawnSync(cmd, args, { stdio: "inherit" });
  73. if (error) {
  74. console.error(`Could not run ${cmd}: ${error.message}`);
  75. process.exit(1);
  76. }
  77. process.exit(status ?? 1);
  78. }
  79. main().catch((err) => {
  80. console.error(err && err.message ? err.message : String(err));
  81. process.exit(1);
  82. });
install.ps1 · Bundled script · 192 lines · 2 findings marked
  1. #Requires -Version 5.1
  2. <#
  3. install.ps1 - Windows bootstrap for claude-carbon.
  4. Usage (PowerShell):
  5. irm https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 6 on GitHub
  6. claude-carbon itself is bash, and stays bash on Windows: Claude Code spawns the
  7. bash.exe from Git for Windows to run hooks and the status line, so the plugin
  8. has to speak the same shell its host does. This script only does the part
  9. PowerShell is needed for - finding that bash.exe, checking for the two commands
  10. Git for Windows does not ship (and printing the winget commands for the missing
  11. ones) - and then hands over to install.sh.
  12. #>
  13. $CallerErrorAction = $ErrorActionPreference
  14. $ErrorActionPreference = 'Stop'
  15. # `irm | iex` runs this script inside the user's own PowerShell session, where `exit`
  16. # closes their window and the message they needed with it. There `break` ends the
  17. # script and leaves the session open, with its error preference as it found it.
  18. # Run as a file (the npm wrapper), or by a host started with -Command and no -NoExit
  19. # (a tool running the one-liner), the host closes after the script anyway and its
  20. # caller reads the exit code, so `exit` hands it back. VS Code's terminal starts
  21. # with -NoExit. Never call Exit-Installer inside a loop or a switch: `break` would
  22. # only leave that.
  23. function Test-HostClosesAfterCommand {
  24. $hostArgs = @([Environment]::GetCommandLineArgs() | Select-Object -Skip 1)
  25. if (@($hostArgs | Where-Object { $_ -match '^[-/]noe' }).Count -gt 0) { return $false }
  26. for ($i = 0; $i -lt $hostArgs.Count; $i++) {
  27. # Parameter names abbreviate: -c and -Com are -Command, -e and -ec -EncodedCommand.
  28. $name = ($hostArgs[$i] -replace '^[-/]+', '').ToLower()
  29. if ($name -eq $hostArgs[$i].ToLower() -or -not $name) { continue }
  30. if ($name -eq 'ec' -or 'encodedcommand'.StartsWith($name)) { return $true }
  31. # `-Command -` reads stdin line by line, like a prompt: the session goes on.
  32. if ('command'.StartsWith($name)) {
  33. return ($i + 1 -lt $hostArgs.Count) -and ($hostArgs[$i + 1] -ne '-')
  34. }
  35. }
  36. return $false
  37. }
  38. $KeepSession = ($MyInvocation.MyCommand -isnot [System.Management.Automation.ExternalScriptInfo]) -and
  39. -not (Test-HostClosesAfterCommand)
  40. function Exit-Installer([int]$Code) {
  41. if ($KeepSession) {
  42. $global:LASTEXITCODE = $Code
  43. Set-Variable -Name ErrorActionPreference -Value $CallerErrorAction -Scope 1
  44. break
  45. }
  46. exit $Code
  47. }
  48. $InstallUrl = if ($env:CLAUDE_CARBON_INSTALL_URL) {
  49. $env:CLAUDE_CARBON_INSTALL_URL
  50. } else {
  51. 'https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh'
  52. }
  53. Write-Host ''
  54. Write-Host ' claude-carbon installer'
  55. Write-Host ' Track the carbon footprint of your Claude Code sessions.'
  56. Write-Host ''
  57. # ── 1. Locate Git Bash ───────────────────────────────────────────────────────
  58. function Find-GitBash {
  59. $candidates = @(
  60. # The same variable Claude Code reads, so a non-default Git install only
  61. # has to be declared once.
  62. $env:CLAUDE_CODE_GIT_BASH_PATH,
  63. (Join-Path $env:ProgramFiles 'Git\bin\bash.exe'),
  64. (Join-Path ${env:ProgramFiles(x86)} 'Git\bin\bash.exe'),
  65. (Join-Path $env:LOCALAPPDATA 'Programs\Git\bin\bash.exe')
  66. ) | Where-Object { $_ }
  67. foreach ($candidate in $candidates) {
  68. if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate }
  69. }
  70. # PATH as a last resort. C:\Windows\System32\bash.exe is skipped deliberately:
  71. # that one launches WSL, and installing through it would put claude-carbon
  72. # inside the Linux distribution rather than on Windows.
  73. Get-Command bash.exe -All -ErrorAction SilentlyContinue |
  74. Where-Object { $_.Source -and $_.Source -notmatch '\\System32\\' } |
  75. Select-Object -First 1 -ExpandProperty Source
  76. }
  77. $bash = Find-GitBash
  78. if (-not $bash) {
  79. Write-Host 'ERROR: Git for Windows was not found.' -ForegroundColor Red
  80. Write-Host ' claude-carbon runs on its bash, and so does Claude Code''s own Bash tool.'
  81. Write-Host ''
  82. Write-Host ' Install it: winget install Git.Git --source winget'
  83. Write-Host ' Already installed elsewhere? Point at it and rerun:'
  84. Write-Host ' $env:CLAUDE_CODE_GIT_BASH_PATH = "D:\Git\bin\bash.exe"'
  85. Exit-Installer 1
  86. }
  87. Write-Host " Git Bash: $bash"
  88. # ── 2. Check the two commands Git for Windows does not ship ──────────────────
  89. # jq and sqlite3 are the whole Windows prerequisite list: bash, awk, sed, grep,
  90. # date, curl and git all come with Git for Windows.
  91. # winget records its install directory in the registry PATH, but a terminal opened
  92. # before that keeps the old value, and the bash spawned below inherits it. Merge
  93. # the registry PATH in first, so `winget install` followed by a rerun in the same
  94. # terminal finds the new commands. Entries already present are left alone.
  95. function Merge-RegistryPath {
  96. $current = @($env:Path -split ';' | Where-Object { $_ })
  97. $registry = @('Machine', 'User') |
  98. ForEach-Object { [Environment]::GetEnvironmentVariable('Path', $_) } |
  99. Where-Object { $_ } |
  100. ForEach-Object { $_ -split ';' } |
  101. Where-Object { $_ }
  102. $absent = @($registry | Where-Object { $current -notcontains $_ })
  103. if ($absent.Count -gt 0) {
  104. $env:Path = ($current + $absent) -join ';'
  105. }
  106. }
  107. Merge-RegistryPath
  108. $deps = @(
  109. @{ Name = 'jq'; Package = 'jqlang.jq' },
  110. @{ Name = 'sqlite3'; Package = 'SQLite.SQLite' }
  111. )
  112. function Find-Missing {
  113. $absent = @()
  114. foreach ($dep in $deps) {
  115. # Resolved through Git Bash, not PowerShell: that is the PATH the plugin will
  116. # actually run under, and it includes the Git usr\bin directory.
  117. & $bash -lc "command -v $($dep.Name)" *> $null
  118. if ($LASTEXITCODE -ne 0) { $absent += $dep }
  119. }
  120. return ,$absent
  121. }
  122. $missing = Find-Missing
  123. $missingNames = @($missing | ForEach-Object { $_.Name })
  124. foreach ($dep in $deps) {
  125. if ($missingNames -notcontains $dep.Name) { Write-Host " $($dep.Name): OK" }
  126. }
  127. # The installer prints the winget commands and never runs them. An antivirus's
  128. # behaviour protection denied winget access (0x80070005), typed by hand as well, and
  129. # when this script ran it under the npm wrapper, reported install.ps1 itself as the
  130. # threat. Left to the user, the block stays between winget and the antivirus, and
  131. # the message below says how to lift it.
  132. if ($missing.Count -gt 0) {
  133. Write-Host ''
  134. Write-Host "ERROR: missing dependencies: $($missingNames -join ', ')." -ForegroundColor Red
  135. Write-Host ' Install with:'
  136. Write-Host ''
  137. # `--source winget`: without it winget also queries the Microsoft Store source,
  138. # and when that one is unreachable (a TLS-inspecting proxy, a locked-down
  139. # Store) it aborts the whole install with exit code 94 instead of falling back.
  140. foreach ($dep in $missing) {
  141. Write-Host " winget install $($dep.Package) --source winget"
  142. }
  143. Write-Host ''
  144. Write-Host ' Then rerun this installer. The same terminal is fine: PATH is re-read.'
  145. Write-Host ' If winget answers "Access is denied" (0x80070005), security software on'
  146. Write-Host ' this PC is blocking it: allow winget there, then run the command again.'
  147. Exit-Installer 1
  148. }
  149. # ── 3. Hand over to install.sh ───────────────────────────────────────────────
  150. Write-Host ''
  151. Write-Host 'Running the installer...'
  152. $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("claude-carbon-" + [System.Guid]::NewGuid().ToString('N').Substring(0, 8))
  153. New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
  154. $scriptPath = Join-Path $tempDir 'install.sh'
  155. try {
  156. Invoke-WebRequest -Uri $InstallUrl -OutFile $scriptPath -UseBasicParsing
  157. } catch {
  158. Write-Host "ERROR: could not download the installer from $InstallUrl" -ForegroundColor Red
  159. Write-Host " $($_.Exception.Message)"
  160. Exit-Installer 1
  161. }
  162. # The download arrives with whatever line endings the server sent. bash treats a
  163. # trailing carriage return as part of every command, so normalise before running.
  164. $content = [System.IO.File]::ReadAllText($scriptPath)
  165. [System.IO.File]::WriteAllText($scriptPath, $content.Replace("`r`n", "`n"))
  166. & $bash $scriptPath
  167. $code = $LASTEXITCODE
  168. Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue
  169. Exit-Installer $code
install.sh · Bundled script · 186 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. # install.sh — One-line installer for claude-carbon.
  4. # Usage: curl -fsSL https://raw.githubusercontent.com/gwittebolle/claude-carbon/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 5 on GitHub
  5. # `curl … | bash` leaves BASH_SOURCE unset, which `set -u` would treat as fatal.
  6. SCRIPT_SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || echo "")"
  7. # The installer is normally curl-piped into bash, with no clone on disk yet, so it
  8. # carries a minimal copy of the two helpers it needs before the dependency check:
  9. # the platform probe behind the install hints, and the Windows path conversion.
  10. # tests/run-portability-tests.sh asserts this fallback agrees with the real
  11. # scripts/portable-lib.sh on every input, so the two cannot drift apart.
  12. if [ -n "$SCRIPT_SELF_DIR" ] && [ -f "${SCRIPT_SELF_DIR}/scripts/portable-lib.sh" ]; then
  13. # shellcheck source=scripts/portable-lib.sh
  14. . "${SCRIPT_SELF_DIR}/scripts/portable-lib.sh"
  15. else
  16. # >>> portable-lib fallback
  17. case "${OSTYPE:-}" in
  18. darwin*) CC_OS="darwin" ;;
  19. msys*|cygwin*) CC_OS="windows" ;;
  20. *) CC_OS="linux" ;;
  21. esac
  22. cc_install_hint() {
  23. case "$CC_OS" in
  24. darwin) printf 'brew install %s' "$1" ;;
  25. windows)
  26. case "$1" in
  27. jq) printf 'winget install jqlang.jq --source winget' ;;
  28. sqlite3) printf 'winget install SQLite.SQLite --source winget' ;;
  29. git) printf 'winget install Git.Git --source winget' ;;
  30. node) printf 'winget install OpenJS.NodeJS --source winget' ;;
  31. *) printf 'winget install %s --source winget' "$1" ;;
  32. esac
  33. ;;
  34. *) printf 'apt install %s' "$1" ;;
  35. esac
  36. }
  37. cc_path() {
  38. local p="${1:-}"
  39. [ -n "$p" ] || return 0
  40. if [ "$CC_OS" != "windows" ]; then printf '%s' "$p"; return 0; fi
  41. case "$p" in
  42. [A-Za-z]:[\\/]*|*\\*)
  43. if command -v cygpath >/dev/null 2>&1; then
  44. cygpath -u "$p" 2>/dev/null || printf '%s' "$p"
  45. else
  46. p="${p//\\//}"
  47. case "$p" in
  48. [A-Za-z]:/*) printf '/%s%s' "$(printf '%s' "${p%%:*}" | tr 'A-Z' 'a-z')" "${p#*:}" ;;
  49. *) printf '%s' "$p" ;;
  50. esac
  51. fi
  52. ;;
  53. *) printf '%s' "$p" ;;
  54. esac
  55. }
  56. # <<< portable-lib fallback
  57. fi
  58. INSTALL_DIR="$(cc_path "${CLAUDE_CARBON_DIR:-$HOME/code/claude-carbon}")"
  59. # Honour Claude Code's own CLAUDE_CONFIG_DIR so a second environment
  60. # (e.g. CLAUDE_CONFIG_DIR=~/.claude-work claude) installs into its own dir.
  61. CONFIG_DIR="$(cc_path "${CLAUDE_CONFIG_DIR:-$HOME/.claude}")"
  62. echo ""
  63. echo " claude-carbon installer"
  64. echo " Track the carbon footprint of your Claude Code sessions."
  65. echo ""
  66. # >>> fetch jq
  67. # macOS ships jq from 15 (Sequoia) on. On an older Mac with no Homebrew, a person who
  68. # only uses the desktop app has no simple way to get it: fetch the official jq binary,
  69. # checked against the SHA-256 jq publishes for the release, into the data folder every
  70. # script looks in (scripts/portable-lib.sh puts it on PATH when the system has none).
  71. # CLAUDE_CARBON_JQ_BASE points the download elsewhere, for the tests only.
  72. cc_fetch_jq() {
  73. local dir="$1" asset sha tmp
  74. case "$(uname -m 2>/dev/null)" in
  75. arm64) asset="jq-macos-arm64"; sha="a9fe3ea2f86dfc72f6728417521ec9067b343277152b114f4e98d8cb0e263603" ;;
  76. x86_64) asset="jq-macos-amd64"; sha="e80dbe0d2a2597e3c11c404f03337b981d74b4a8504b70586c354b7697a7c27f" ;;
  77. *) return 1 ;;
  78. esac
  79. mkdir -p "$dir" || return 1
  80. tmp="${dir}/jq.download.$$"
  81. if curl -fsSL --retry 2 -o "$tmp" "${CLAUDE_CARBON_JQ_BASE:-https://github.com/jqlang/jq/releases/download/jq-1.8.1}/${asset}" \
  82. && [ "$(shasum -a 256 "$tmp" 2>/dev/null | cut -d' ' -f1)" = "$sha" ] \
  83. && chmod +x "$tmp" && mv -f "$tmp" "${dir}/jq"; then
  84. return 0
  85. fi
  86. rm -f "$tmp"
  87. return 1
  88. }
  89. # <<< fetch jq
  90. # 1. Check dependencies
  91. if [ "$CC_OS" = "darwin" ] && ! command -v jq &>/dev/null; then
  92. JQ_DIR="${CONFIG_DIR}/claude-carbon/bin"
  93. echo "jq is not installed: fetching the official jq 1.8.1 into ${JQ_DIR}..."
  94. if cc_fetch_jq "$JQ_DIR"; then
  95. PATH="${JQ_DIR}:${PATH}"
  96. export PATH
  97. else
  98. echo " Could not fetch jq, or its checksum did not match." >&2
  99. fi
  100. fi
  101. for cmd in jq sqlite3 git; do
  102. if ! command -v "$cmd" &>/dev/null; then
  103. echo "ERROR: $cmd is not installed." >&2
  104. echo " Install with: $(cc_install_hint "$cmd")" >&2
  105. [ "$CC_OS" = "windows" ] && echo " Then reopen this shell so PATH picks it up." >&2
  106. exit 1
  107. fi
  108. done
  109. # 2. Clone (fresh) or update (existing, dirty-safe against locally-edited data files)
  110. WAS_UPDATE=0
  111. if [ -d "$INSTALL_DIR/.git" ]; then
  112. echo "Updating existing installation at $INSTALL_DIR..."
  113. WAS_UPDATE=1
  114. export GIT_TERMINAL_PROMPT=0 GIT_HTTP_LOW_SPEED_LIMIT=1000 GIT_HTTP_LOW_SPEED_TIME=20
  115. # The README invites editing data/factors.json, which breaks `git pull --ff-only`.
  116. # Stash just those two tracked files, pull, restore; on conflict keep upstream + back up theirs.
  117. STASHED=0
  118. if [ -n "$(git -C "$INSTALL_DIR" status --porcelain -- data/factors.json data/prices.json 2>/dev/null || true)" ]; then
  119. if git -C "$INSTALL_DIR" stash push --quiet -m "claude-carbon-install" -- data/factors.json data/prices.json 2>/dev/null; then
  120. STASHED=1
  121. fi
  122. fi
  123. git -C "$INSTALL_DIR" pull --ff-only --quiet \
  124. || echo " WARNING: could not fast-forward. Resolve with: cd $INSTALL_DIR && git status"
  125. if [ "$STASHED" = "1" ]; then
  126. if ! git -C "$INSTALL_DIR" stash pop --quiet 2>/dev/null; then
  127. for f in data/factors.json data/prices.json; do
  128. git -C "$INSTALL_DIR" show "stash@{0}:$f" > "${INSTALL_DIR}/${f}.local.bak" 2>/dev/null || true
  129. done
  130. git -C "$INSTALL_DIR" checkout --quiet HEAD -- data/factors.json data/prices.json 2>/dev/null || true
  131. git -C "$INSTALL_DIR" stash drop --quiet 2>/dev/null || true
  132. echo " Your local factors/prices edits were saved to *.local.bak (re-apply manually)."
  133. fi
  134. fi
  135. else
  136. echo "Cloning to $INSTALL_DIR..."
  137. mkdir -p "$(dirname "$INSTALL_DIR")"
  138. if ! CLONE_ERR="$(git clone --quiet https://github.com/gwittebolle/claude-carbon.git "$INSTALL_DIR" 2>&1)"; then
  139. [ -n "$CLONE_ERR" ] && echo "$CLONE_ERR" >&2
  140. echo "ERROR: could not clone claude-carbon." >&2
  141. # Git for Windows verifies TLS against its own bundled CA list, which does not
  142. # know the root a TLS-inspecting proxy or antivirus re-signs HTTPS with. The
  143. # Windows certificate store does, or the user could not browse either.
  144. if [ "$CC_OS" = "windows" ] \
  145. && printf '%s' "$CLONE_ERR" | grep -q "unable to get local issuer certificate" \
  146. && [ "$(git config --get http.sslBackend 2>/dev/null || true)" != "schannel" ]; then
  147. echo " Something on this machine re-signs HTTPS traffic with a root that git's bundled" >&2
  148. echo " CA list does not trust. Point git at the Windows certificate store instead;" >&2
  149. echo " verification stays on, only the trust store changes:" >&2
  150. echo " git config --global http.sslBackend schannel" >&2
  151. echo " Then rerun this installer." >&2
  152. fi
  153. exit 1
  154. fi
  155. fi
  156. # 3. Configure Claude Code settings and install the /carbon-* commands. First, because it
  157. # is the step that can refuse (another install already wired): nothing is read or re-priced
  158. # before it agrees.
  159. echo ""
  160. echo "Configuring Claude Code..."
  161. bash "$INSTALL_DIR/scripts/configure-settings.sh"
  162. # 4. Run setup (creates DB, backfills history)
  163. echo ""
  164. CLAUDE_CARBON_INSTALLER=1 bash "$INSTALL_DIR/scripts/setup.sh"
  165. # 4b. On update, re-price stored history with the new factors (CO2-only; cost left intact).
  166. if [ "$WAS_UPDATE" = "1" ]; then
  167. DB_PATH="$(cc_path "${CLAUDE_CARBON_DB:-${CONFIG_DIR}/claude-carbon/carbon.db}")"
  168. if [ -f "$DB_PATH" ]; then
  169. bash "$INSTALL_DIR/scripts/recompute.sh" || echo " (history not re-priced; see message above)"
  170. fi
  171. fi
  172. echo ""
  173. echo "Done. Restart Claude Code to see your CO2 in the status line."
  174. echo ""

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.