SLOPSHOPPER

chef-station

A Chef Station sidebar of sections that open and close: plan limits, today's spend, the hourly trend, models and projects, thirteen weeks of activity, the…

panecommandprocesstimer
v0.7.2MITupdated 2026-10-23schalkneethling/claude-chef
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · chef-station
│ ┃ Chef Station ✕ › fix the failing auth test and add an audit log call │ ┃ ✻ Claude │ ┃ ⏺ Read(src/auth.ts) │ ┃ ╭────────────────────────────────────────── ⎿ Read 6 lines │ ┃ │ 1: ▾ Usage $0.00 today · Session 31% ⏺ Update(src/auth.ts) │ ┃ │ ⎿ Added 2 lines, removed 1 line │ ┃ │ Session ██████░░░░░░░░░░░░░░ 31% ⏺ Bash(bun test) │ ┃ │ Today $0.00 API value · 98.9k tokens ⎿ 3 pass, 1 fail │ ┃ │ cache │ ┃ │ Now ● app · Opus 5.5 · 1.5k writte ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ last turn 0:42 │ ┃ ╰────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ╭────────────────────────────────────────╮ › /chef │ ┃ │ 2: ▸ Trend $0.00 this hour │ ⎿ chef-station: Chef Station is open. │ ┃ ╰────────────────────────────────────────╯ │ ┃ │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ 3: ▸ Breakdown Opus 5.5 $0.00 │ │ ┃ ╰────────────────────────────────────────╯ │ ┃ │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ 4: ▸ Activity 1-day streak │ │ ┃ ╰────────────────────────────────────────╯ │ ┃ │ ┃ ╭────────────────────────────────────────╮ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Chef Station
✻ Claude ╭────────────────────────────────────────────────────────── │ 1: ▾ Usage $0.00 today · Session 31% │ │ Session ██████░░░░░░░░░░░░░░ 31% │ Today $0.00 API value · 98.9k tokens · 93% from cach │ Now ● app · Opus 5.5 · 1.5k written · $0.42 · cont │ last turn 0:42 ╰────────────────────────────────────────────────────────── ╭────────────────────────────────────────────────────────╮ │ 2: ▸ Trend $0.00 this hour │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ 3: ▸ Breakdown Opus 5.5 $0.00 │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ 4: ▸ Activity 1-day streak │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ 5: ▸ Context 49% used │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ 6: ▸ Agents 0 active of 0 │ ╰────────────────────────────────────────────────────────╯
README

Chef Station

A Claude Code mod that opens a Chef Station sidebar beside your conversation, so you can keep an eye on the kitchen without leaving the session. The sidebar does not open on its own: type /chef to open it. In the desktop app it docks beside the conversation. In a terminal the sidebar docks beside the transcript in a fullscreen terminal at least 110 columns wide, and sits above the prompt otherwise. The repository is called claude-chef, but the plugin is named chef-station because Claude Code reserves plugin names that begin with claude-.

See it in action

https://github.com/user-attachments/assets/33ad4494-3bfb-48da-80f3-af303e1bfc2a

Stations

The sidebar has six stations, each a section that opens and closes like a disclosure: press its header, or focus the sidebar with ctrl+x tab and press the station's number. A closed section still shows one figure beside its header: today's spend and the tightest rate limit for Usage, this hour's spend for Trend, today's top model for Breakdown, the streak for Activity, how full the context window is for Context, and how many sessions are active or waiting for Agents. Usage starts open, and the sidebar remembers which sections you leave open across sessions. /chef <station> opens that station's section. /chef backfill rescans your Claude Code history. Keyboard shortcuts lists every key and command in one place.

  1. Usage shows your plan's rate-limit windows (the five-hour session and the week) with their reset countdowns, what today has cost in API value along with the token count and the share served from cache, and a "Now" row for the current session: the project, the model, the tokens written, the session cost, how full the context window is, how long the prompt cache stays warm, and a stopwatch for the running turn (once the turn ends, it shows how long the turn took).
  2. Trend draws today's spend hour by hour.
  3. Breakdown ranks today's spend by model and by project.
  4. Activity draws a thirteen-week heat map of tokens per day, with the total, the number of active days, the busiest day and your current streak.
  5. Context shows how the current context window is divided, as /context breaks it down: the system prompt, system tools, MCP tools, custom agents, memory files, skills and messages, then the free space and the auto-compact buffer. A legend below the bar names each category with its tokens and its share of the window. Tool schemas that load on demand sit outside the window, so they are left out. The breakdown is estimated locally, the same way /context estimates it, and refreshes after every turn. Below the legend, Compact (hotkey c) compacts the conversation the way /compact does and says how many tokens it saved. Clear (hotkey x) ends the conversation and starts a new one, as /clear does, after asking you to confirm with y or cancel with n. Neither can run during a turn, so while Claude is working the buttons give way to a short note.
  6. Agents lists every Claude Code session running on this machine, in the desktop app, in a terminal or in the background. Sessions that are busy, waiting on you, or active in the last fifteen minutes are shown in full, waiting ones first: the session's name and topic, where it runs, its project and process ID, what it is doing now or did last, and the last thing you asked it. The other, idle sessions fold into one row that opens to a line each. The list comes from the files each running session writes to ~/.claude/sessions (or $CLAUDE_CONFIG_DIR/sessions), checked against ps so a session that has ended, or whose process ID was reused, is left out, and from the end of each session's transcript. It refreshes as the session starts, every five seconds while the section is open, once a minute while it is closed so its header's figure stays current, and not at all while the sidebar is out of sight. It needs ps and tail, so it works on macOS and Linux.

The Context station's colors come from a categorical palette checked with a data-visualization validator against both a light and a dark terminal background, because the sidebar cannot rely on knowing which one you use. Segments that touch are always colors validated as a pair, including for protanopia and deuteranopia. The colors are handed out in the bar's order to guarantee that, so a category's color can change when another category appears or disappears. A one-cell gap separates segments, free space and the buffer are drawn as textures rather than hues, and the legend names every color, so nothing is told apart by color alone.

Keyboard shortcuts

The station and button keys work only while the sidebar has focus, so they never interfere with typing a prompt. Focus the sidebar with ctrl+x tab (or click it), and press Esc to return to the prompt.

| Keys | Where | What it does | | :- | :- | :- | | ctrl+x tab | Anywhere | Focuses the sidebar. | | Esc | Sidebar focused | Returns to the prompt. | | ctrl+x x | Anywhere | Closes the sidebar, as its close mark does. /chef opens it again. | | 1 to 6 | Sidebar focused | Opens or closes Usage, Trend, Breakdown, Activity, Context or Agents. | | c | Context station | Compacts the conversation. | | x | Context station | Asks to clear the conversation. | | y | Clear confirmation | Clears the conversation and starts a new one. | | n | Clear confirmation | Cancels the clear. |

The sidebar also answers to /chef at the prompt:

| Command | What it does | | :- | :- | | /chef | Opens the sidebar. | | /chef usage, /chef trend, /chef breakdown, /chef activity, /chef context, /chef agents | Opens the sidebar with that station's section open. | | /chef backfill | Rescans your Claude Code history. |

The prompt cache countdown

The "Now" row shows "cache warm · ~42m left" while the main conversation's prompt cache is likely still warm, and "cache expired" once it has likely lapsed. "Warm" means the cache entries have likely not reached the end of their lifetime, not that the next prompt is guaranteed a cache read: a read also needs the start of the prompt to match what was cached, so anything that changes earlier content, such as switching models or compacting, misses the cache even while it is warm. An expired cache means the next prompt pays to write the cache again. The countdown is the sidebar's own estimate, which the tilde marks: Claude Code does not report it. A cache entry lives for a fixed time from the start of the last request that read or wrote it, so the sidebar restarts the countdown as each request of the main conversation starts (a subagent's requests use a cache of their own). How long an entry lives, five minutes or an hour, depends on how it was written, which only the session's transcript records. The sidebar reads the end of the transcript as each turn ends, and until then it assumes the shorter five minutes, so it never calls a cold cache warm. A /clear starts the countdown over.

Where the numbers come from

The rate-limit windows, the session cost and the context fill come straight from Claude Code ($.session.usage()), so they match the status line and /cost. Rate-limit windows only appear on a subscription and only after the first reply of a session.

Today's spend, the trend, the breakdown and the activity grid come from two sources that the sidebar adds together.

The first is what the mod records live. Each time a turn completes, in the main conversation or in a subagent, the mod records the session cost added since the previous turn, along with the tokens the turn reported, the model that answered and the project. Every session stores its turns under a store key of its own (turns:<session id>), and the sidebar adds all of them up when it reads them, so two sessions running at the same time never overwrite each other's turns. The sidebar picks up other sessions' spending once a minute, and sessions older than thirteen weeks are removed. The cost attributed to each model is an approximation: when a subagent runs, the parent's requests made before the subagent finished are counted against the subagent's model.

The second is a backfill from the session transcripts Claude Code keeps in ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects). The backfill reads the last thirteen weeks, a few seconds after the first session of each day starts, and again whenever you run /chef backfill. It leaves out every session the sidebar has already recorded live, so nothing is counted twice. Each response appears on several lines of a transcript, so the backfill counts each response once by its message and request IDs. Transcripts hold token counts but no cost, so the backfill estimates cost from first-party API list prices, including the separate rates for cache reads, five-minute and one-hour cache writes, and fast mode. Those prices live in hooks/transcript.mjs. A model with no known price still counts its tokens, and /chef backfill names it.

A mod can only read files of up to 4 MiB, and long sessions write larger transcripts. So when Node is installed, the mod runs the helper script scripts/backfill.mjs, which streams files of any size and prints the tally as JSON. Without Node, the mod reads the transcripts itself and skips the large ones, and /chef backfill says how many it skipped. A transcript that cannot be read at all, for example because it was removed during the scan, adds nothing rather than part of its usage, and /chef backfill reports the backfill as incomplete and says how many transcripts were affected. The helper also works on its own, which is handy for checking the numbers:

echo '[]' | node scripts/backfill.mjs --projects ~/.claude/projects

The JSON array on standard input lists session IDs to leave out.

Claude Code does not tell plugins which plan you are on, so the plan badge is a setting. Set it in /config under the chef-station rows, for example to Max 5×, or leave it empty to hide the badge.

Install

At the prompt of a Claude Code terminal session, run:

/plugin install chef-station --marketplace schalkneethling/claude-chef

Answer y to add the marketplace, then pick a scope. The user scope loads it in every session, the desktop app's included.

Update

Claude Code keeps the copy of the plugin it made when you installed it. Auto-update is off by default for marketplaces outside Anthropic's own, including this one, so new versions do not arrive on their own until you turn it on. To turn it on, run /plugin, open the Marketplaces tab, select chef-station and choose Enable auto-update. Claude Code then refreshes the marketplace in the background shortly after a session starts and updates the plugin on disk.

To update right away instead, fetch the latest marketplace listing and then update the plugin:

claude plugin marketplace update chef-station
claude plugin update chef-station

Either way, a session that is already running keeps the version it loaded. Run /reload-plugins to load the new version there, or start a new session. If you load the mod from a clone with --plugin-dir, a git pull is enough, because Claude Code reads that folder directly.

An update installs the version named in .claude-plugin/plugin.json, so every change meant to reach people who installed the plugin raises that version.

Develop locally

Load the mod straight from your clone for a single session:

claude --plugin-dir /path/to/claude-chef

Claude Code watches the folder in an interactive session, so saving a file reloads the mod. The ledger and the selected station survive a reload. Run with claude --debug to see why a hook was skipped or a drawing was refused.

To test the marketplace install flow against your working copy instead of GitHub, add the folder as a marketplace and install from it. Edits are then picked up with /reload-plugins:

claude plugin marketplace add /path/to/claude-chef
claude plugin install chef-station@chef-station

Check and test

claude plugin validate .
claude plugin test .

validate reads the manifest, the marketplace file and the hooks module the way Claude Code will. test runs the tests/*.test.ts files against the engine. agents.test.ts, format.test.ts, ledger.test.ts and transcript.test.ts cover the pure session parsing, formatting, bookkeeping, transcript parsing and pricing. register.test.ts mounts the sidebar on the terminal and desktop surfaces with a stubbed session, clock, store, helper script, ps and tail.

Run both with the Claude Code build your sessions use. The desktop app bundles its own copy of Claude Code, which can be older than the terminal's claude, and an older engine refuses some modules a newer one loads: 2.1.295, for one, refuses a hooks module that passes $ into a function imported from another file, which is why every function that is handed $ lives in hooks/register.tsx. The desktop app's copy is under ~/Library/Application Support/Claude/claude-code/<version>/ on macOS.

Once Claude Code has loaded the mod from your folder it writes its type declarations to .claude-plugin/types/, and npx tsc -p . type-checks the mod against them.

Source 10 files
hooks/register.tsx 821 lines
1import { atom, read, update } from "claude-code";
2import type { EngineInterface, Register, SessionMeasureInput, SessionUsage, Timer } from "claude-code";
3
4import type {
5  ChefStationAgents,
6  ChefStationBackfill,
7  ChefStationCache,
8  ChefStationContext,
9  ChefStationContextAction,
10  ChefStationLedger,
11  ChefStationLive,
12  ChefStationName,
13} from "../types";
14import {
15  isSameProcess,
16  parsePsOutput,
17  parseRegistryEntry,
18  projectFolderOf,
19  type RegistryEntry,
20  sortAgents,
21  summariseTranscriptTail,
22  toAgent,
23  type TranscriptSummary,
24} from "./agents";
25import { cacheTtlFromTranscript } from "./cache";
26import { describeBackfill, MAX_READ_BYTES, SCAN_TIMEOUT_MS, type Tallied, toBackfill } from "./backfill";
27import { modelName, short } from "./format";
28import { backfillSince, composeLedger, dayKey, emptyLedger, isStale, recordTurn } from "./ledger";
29import { sidebar, STATIONS } from "./stations";
30import { addTranscript, createTally } from "./transcript.mjs";
31
32/**
33 * Each session stores its own turns under `turns:<session id>`, and the sidebar
34 * adds every session's up when it reads them, so two sessions never write
35 * the same key. `$.store` has no conditional write to make a shared key safe.
36 */
37const SESSION_KEY_PREFIX = "turns:";
38/** The last scan of the transcripts, which any session may replace whole. */
39const BACKFILL_KEY = "backfill";
40/** The single shared ledger of version 0.2.0, still read so its turns are not lost. */
41const LEGACY_LEDGER_KEY = "ledger";
42/** The stations whose sections are open, kept across sessions. */
43const OPEN_SECTIONS_KEY = "openSections";
44/** The one station shown by version 0.6.0 and earlier, still read once so its section starts open. */
45const LEGACY_STATION_KEY = "station";
46/** Usage is open until the person says otherwise. */
47const DEFAULT_OPEN_SECTIONS: readonly ChefStationName[] = ["usage"];
48/** Countdowns and other sessions' spending move while this one is idle. */
49const TICK_MS = 60_000;
50/** The turn's stopwatch moves every second while a turn runs. */
51const TURN_TICK_MS = 1_000;
52/** The daily scan waits until the session has settled in. */
53const SCAN_DELAY_MS = 5_000;
54/** The sidebar pane the stations draw in. */
55const PANE_ID = "chef-station";
56const PANE_TITLE = "Chef Station";
57/** Other sessions start, finish and move on, so the Agents station looks again this often while it shows. */
58const AGENTS_TICK_MS = 5_000;
59/** While the Agents section is closed only its header's figure shows, so once a minute is enough. */
60const AGENTS_CLOSED_REFRESH_MS = 60_000;
61/** Enough of a transcript's end to hold a session's latest steps, title and prompt. */
62const AGENTS_TAIL_BYTES = 256 * 1024;
63
64// Held by the host, so the sidebar survives a hot reload of this file.
65const openSections = atom({ plugin: "chef-station", key: "openSections" } as const, [...DEFAULT_OPEN_SECTIONS] as ChefStationName[]);
66const isIdleOpen = atom({ plugin: "chef-station", key: "isIdleOpen" } as const, false);
67const ledger = atom({ plugin: "chef-station", key: "ledger" } as const, emptyLedger());
68const live = atom({ plugin: "chef-station", key: "live" } as const, null as ChefStationLive | null);
69const now = atom({ plugin: "chef-station", key: "now" } as const, 0);
70const recordedUsd = atom({ plugin: "chef-station", key: "recordedUsd" } as const, 0);
71const cache = atom({ plugin: "chef-station", key: "cache" } as const, {} as ChefStationCache);
72const contextBreakdown = atom({ plugin: "chef-station", key: "context" } as const, null as ChefStationContext | null);
73const contextAction = atom({ plugin: "chef-station", key: "contextAction" } as const, {
74  isRunning: false,
75  isConfirmingClear: false,
76} as ChefStationContextAction);
77const backfillStatus = atom({ plugin: "chef-station", key: "backfillStatus" } as const, { isRunning: false } as {
78  isRunning: boolean;
79  message?: string;
80});
81const agents = atom({ plugin: "chef-station", key: "agents" } as const, { agents: [], refreshedAt: 0 } as ChefStationAgents);
82
83/**
84 * What one loaded copy of the module keeps between refreshes of the Agents
85 * station: each transcript's summary until the file changes, so an idle
86 * session costs one stat per refresh, and the refresh under way.
87 */
88type AgentsRefresher = {
89  transcripts: Map<string, { mtimeMs: number; summary: TranscriptSummary }>;
90  /** The refresh under way, which a caller joins instead of starting another. */
91  inFlight?: Promise<void>;
92};
93
94export const register: Register = (on, options) => {
95  const plan = typeof options.plan === "string" && options.plan.trim() !== "" ? options.plan.trim() : undefined;
96
97  // Turns that complete together (a subagent and its parent) are recorded one
98  // at a time, so neither reads the session cost the other is about to claim.
99  let recording: Promise<unknown> = Promise.resolve();
100  let turnTicker: Timer | undefined;
101  const agentsRefresher: AgentsRefresher = { transcripts: new Map() };
102
103  on("session.start", async ($, e, next) => {
104    const result = await next(e);
105    const usage = await $.session.usage();
106    const root = await $.session.root();
107    const model = modelName(await $.session.model());
108    const saved = await restoreOpenSections($);
109
110    await update($, live, () => ({
111      project: basename(root),
112      model,
113      outputTokens: 0,
114      usd: usage.cost?.usd ?? 0,
115      startedAt: usage.startedAt,
116      contextPercent: usage.context.percent,
117      rateLimits: [...usage.rateLimits],
118    }));
119    // Whatever the session cost before this load is already in the ledger, or predates Chef Station.
120    await update($, recordedUsd, () => usage.cost?.usd ?? 0);
121    await tick($);
122    await refreshContext($).catch(() => undefined);
123
124    await update($, openSections, () => saved);
125
126    await $.command.register({
127      name: "chef",
128      description: "Open the Chef Station sidebar or one of its stations, or rescan your Claude Code history with backfill.",
129      argumentHint: "[usage|trend|breakdown|activity|context|agents|backfill]",
130      immediate: true,
131    });
132
133    $.clock.every(TICK_MS, () => {
134      tick($).catch(() => undefined);
135    });
136
137    $.clock.every(AGENTS_TICK_MS, () => {
138      refreshAgentsWhileShown($, agentsRefresher).catch(() => undefined);
139    });
140
141    // After the command, so a slow `ps` never holds the session's start. Even a
142    // closed Agents section shows how many sessions are active in its header.
143    refreshAgents($, agentsRefresher).catch(() => undefined);
144
145    // Fill in the history from Claude Code's transcripts once a day, in the background.
146    const stored = await read($, ledger);
147    const at = await $.clock.now();
148
149    if (!stored.backfill || dayKey(stored.backfill.scannedAt) !== dayKey(at)) {
150      $.clock.after(SCAN_DELAY_MS, () => {
151        runBackfill($).catch(() => undefined);
152      });
153    }
154
155    return result;
156  });
157
158  // Every model request is a step. A request reads or writes the prompt cache and restarts its
159  // lifetime from the moment it starts, so the main conversation's steps start the countdown.
160  on("turn.step", async function* ($, e, next) {
161    if (!e.agentId) {
162      const at = await $.clock.now();
163      await update($, cache, (before) => ({ ...before, lastRequestAt: at }));
164    }
165
166    return yield* next(e);
167  });
168
169  // The settings hooks' Stop fires as the main conversation's turn ends and names its transcript,
170  // whose latest cache write says whether the cache lives for five minutes or an hour.
171  on("classic.Stop", async ($, e, next) => {
172    const result = await next(e);
173    const ttl = cacheTtlFromTranscript(await readTranscriptTail($, e.transcript_path));
174
175    if (ttl) {
176      await update($, cache, (before) => ({ ...before, ttl }));
177    }
178
179    return result;
180  });
181
182  // A /clear raises no session.start: the conversation ends here, its cost starts over from nothing,
183  // and the new conversation has no cache yet.
184  on("session.end", async ($, e, next) => {
185    const result = await next(e);
186
187    if (e.reason === "clear") {
188      await update($, recordedUsd, () => 0);
189      // The breakdown on screen is the previous conversation's; the next turn measures the new one.
190      await update($, contextBreakdown, () => null);
191      await update($, cache, () => ({}));
192    }
193
194    return result;
195  });
196
197  // Raised for the main conversation's turns only; subagents' runs raise none.
198  on("turn.start", async ($, e, next) => {
199    const at = await $.clock.now();
200    // Read again each turn, so a /model switch shows before the turn completes.
201    const model = modelName(await $.session.model());
202    await update($, live, (before) => (before === null ? before : { ...before, model, turnStartedAt: at }));
203    await update($, now, () => at);
204
205    turnTicker?.cancel();
206    turnTicker = $.clock.every(TURN_TICK_MS, () => {
207      $.clock
208        .now()
209        .then((moment) => update($, now, () => moment))
210        .catch(() => undefined);
211    });
212
213    return next(e);
214  });
215
216  on("session.measure", async ($, e, next) => {
217    await applyMeasure($, e);
218    return next(e);
219  });
220
221  on("turn.complete", async ($, e, next) => {
222    const result = await next(e);
223
224    if (!e.agentId) {
225      turnTicker?.cancel();
226      turnTicker = undefined;
227      await update($, live, (before) =>
228        before === null ? before : { ...before, turnStartedAt: undefined, lastTurnMs: e.durationMs },
229      );
230    }
231
232    recording = recording.then(async () => {
233      const usage = await $.session.usage();
234      const totalUsd = usage.cost?.usd ?? 0;
235      const alreadyRecorded = await read($, recordedUsd);
236      // A total below what was recorded means the session's cost started over (a /clear): all of it is new.
237      const usd = totalUsd < alreadyRecorded ? totalUsd : totalUsd - alreadyRecorded;
238      const current = await read($, live);
239      const model = e.usage ? modelName(e.usage.model) : current?.model ?? "—";
240
241      if (usd === 0 && !e.usage) {
242        return;
243      }
244
245      const at = await $.clock.now();
246      const sessionId = await $.session.id();
247      const sessionKey = `${SESSION_KEY_PREFIX}${sessionId}`;
248      const own = asLedger(await $.store.get(sessionKey));
249      const recorded = recordTurn(own, {
250        at,
251        usd,
252        model,
253        project: current?.project ?? "unknown",
254        sessionId,
255        usage: e.usage && {
256          input: e.usage.input_tokens,
257          output: e.usage.output_tokens,
258          cacheRead: e.usage.cache_read_input_tokens,
259          cacheCreation: e.usage.cache_creation_input_tokens,
260        },
261      });
262
263      await $.store.set(sessionKey, recorded);
264      await refreshLedger($);
265      await update($, recordedUsd, () => totalUsd);
266      await update($, live, (before) => ({
267        ...(before ?? { project: "unknown", model, outputTokens: 0, usd: 0, startedAt: at, rateLimits: [] }),
268        // The "Now" row names the main conversation's model, not a subagent's.
269        model: e.agentId && before ? before.model : model,
270        outputTokens: (before?.outputTokens ?? 0) + (e.usage?.output_tokens ?? 0),
271        usd: totalUsd,
272        contextPercent: usage.context.percent,
273        rateLimits: [...usage.rateLimits],
274      }));
275      await update($, now, () => at);
276    });
277
278    await recording.catch(() => undefined);
279
280    // The window changes with every turn of the main conversation; a subagent has its own.
281    if (!e.agentId) {
282      await refreshContext($).catch(() => undefined);
283    }
284
285    return result;
286  });
287
288  on("command.run", { command: "chef" }, async ($, e) => {
289    const asked = e.args.trim().toLowerCase();
290
291    if (asked === "backfill") {
292      return { text: await runBackfill($) };
293    }
294
295    if (!isStation(asked) && asked !== "") {
296      return {
297        text: `No station called "${asked}". Try ${STATIONS.map((entry) => entry.name).join(", ")}, or backfill to rescan your history.`,
298      };
299    }
300
301    // Opened from the person's command, so the pane is placed at any width. Another plugin
302    // may refuse it; the section still opens, for when the sidebar next shows.
303    await $.ui.open({ id: PANE_ID, title: PANE_TITLE }).catch(() => undefined);
304
305    if (asked === "") {
306      return { text: "Chef Station is open." };
307    }
308
309    await openSection($, asked, agentsRefresher);
310    return { text: `Chef Station: ${asked} is open.` };
311  });
312
313  on("ui.render", { component: "Pane", requestId: PANE_ID }, async ($, e) => {
314    const ui = $.ui.resolve(e);
315    const currentLive = await read($, live);
316    const currentLedger = await read($, ledger);
317    const currentNow = await read($, now);
318
319    // A pane always draws something; the figures arrive once the session has started.
320    if (currentLive === null) {
321      const { Text } = ui;
322      return <Text dimColor>Getting the kitchen ready…</Text>;
323    }
324
325    return sidebar({
326      ui,
327      openSections: await read($, openSections),
328      ledger: currentLedger,
329      live: currentLive,
330      now: currentNow || currentLive.startedAt,
331      plan,
332      backfillStatus: await read($, backfillStatus),
333      cache: await read($, cache),
334      context: await read($, contextBreakdown),
335      contextAction: await read($, contextAction),
336      onContextAction: (action) => void runContextAction($, action),
337      agents: await read($, agents),
338      isIdleOpen: await read($, isIdleOpen),
339      // The pane is told nothing about turns, so the running turn's start says Claude is working.
340      isWorking: currentLive.turnStartedAt !== undefined,
341      columns: e.props.bodyColumns,
342      onToggle: (name) => {
343        toggleSection($, name, agentsRefresher).catch(() => undefined);
344      },
345      onToggleIdle: () => {
346        update($, isIdleOpen, (before) => !before).catch(() => undefined);
347      },
348    });
349  });
350};
351
352/**
353 * Scans Claude Code's transcripts for every session the sidebar did not record
354 * live and stores the result beside the live turns. Returns a line saying how
355 * it went, for `/chef backfill` and the activity station.
356 */
357async function runBackfill($: EngineInterface): Promise<string> {
358  const status = await read($, backfillStatus);
359
360  if (status.isRunning) {
361    return "Already reading your Claude Code history.";
362  }
363
364  await update($, backfillStatus, () => ({ isRunning: true, message: status.message }));
365  let message: string;
366
367  try {
368    const at = await $.clock.now();
369    const before = await loadLedger($);
370    const options = {
371      since: backfillSince(at),
372      excludeSessions: [...Object.keys(before.liveSessions ?? {}), await $.session.id()],
373    };
374    const projects = await projectsDirectory($);
375    const viaNode = await scanWithNode($, projects, options);
376    const backfill = toBackfill(viaNode ?? (await scanWithFs($, projects, options)), viaNode ? "node" : "fs", at);
377
378    await $.store.set(BACKFILL_KEY, backfill);
379    await refreshLedger($);
380    message = describeBackfill(backfill);
381  } catch (error) {
382    message = `Could not read your Claude Code history: ${error instanceof Error ? error.message : String(error)}`;
383  }
384
385  await update($, backfillStatus, () => ({ isRunning: false, message }));
386  return message;
387}
388
389type ScanOptions = { since: number; excludeSessions: string[] };
390
391/** Where Claude Code keeps its state: `$CLAUDE_CONFIG_DIR`, else `~/.claude`. */
392async function configDirectory($: EngineInterface): Promise<string> {
393  const configured = await $.env.get("CLAUDE_CONFIG_DIR");
394
395  if (configured) {
396    return configured;
397  }
398
399  const home = (await $.env.get("HOME")) ?? (await $.env.get("USERPROFILE")) ?? "";
400  return `${home}/.claude`;
401}
402
403async function projectsDirectory($: EngineInterface): Promise<string> {
404  return `${await configDirectory($)}/projects`;
405}
406
407/** The Node helper streams transcripts of any size; a mod may read 4 MiB at most. */
408async function scanWithNode($: EngineInterface, projects: string, options: ScanOptions): Promise<Tallied | undefined> {
409  try {
410    const { exitCode, stdout, isStdoutTruncated } = await $.process.run(
411      ["node", `${$.plugin.root}/scripts/backfill.mjs`, "--projects", projects, "--since", String(options.since)],
412      { stdin: JSON.stringify(options.excludeSessions), timeoutMs: SCAN_TIMEOUT_MS },
413    );
414
415    if (exitCode !== 0 || isStdoutTruncated) {
416      return undefined;
417    }
418
419    return JSON.parse(stdout) as Tallied;
420  } catch {
421    // Node is not installed, or the scan could not finish: read the files directly instead.
422    return undefined;
423  }
424}
425
426async function scanWithFs($: EngineInterface, projects: string, options: ScanOptions): Promise<Tallied> {
427  const tally = createTally(options);
428  let files = 0;
429  let skippedFiles = 0;
430  let unreadableFiles = 0;
431
432  for (const file of await listTranscripts($, projects)) {
433    files += 1;
434
435    if (file.size > MAX_READ_BYTES) {
436      skippedFiles += 1;
437      continue;
438    }
439
440    let text: string;
441
442    try {
443      text = await $.fs.read(file.path);
444    } catch {
445      // Counted apart from the size-limited skips, so the backfill can say it is incomplete.
446      unreadableFiles += 1;
447      continue;
448    }
449
450    await addTranscript(text.split("\n"), tally);
451  }
452
453  return { ...tally.result(), files, skippedFiles, unreadableFiles };
454}
455
456/** Every .jsonl file under `directory`, subagent transcripts included. */
457async function listTranscripts($: EngineInterface, directory: string): Promise<{ path: string; size: number }[]> {
458  const entries = await $.fs.list(directory).catch(() => []);
459  const found: { path: string; size: number }[] = [];
460
461  for (const entry of entries) {
462    const path = `${directory}/${entry.name}`;
463
464    if (entry.kind === "dir") {
465      found.push(...(await listTranscripts($, path)));
466    } else if (entry.kind === "file" && entry.name.endsWith(".jsonl")) {
467      found.push({ path, size: entry.size });
468    }
469  }
470
471  return found;
472}
473
474/** How much of a transcript's end is enough to find the latest response that wrote the cache. */
475const TRANSCRIPT_TAIL_BYTES = 1024 * 1024;
476
477/**
478 * The end of a transcript: the whole file when the mod may read it (4 MiB at
479 * most), otherwise its last megabyte through `tail`. Empty when neither works,
480 * which leaves the lifetime as it was.
481 */
482async function readTranscriptTail($: EngineInterface, path: string): Promise<string> {
483  try {
484    const { size } = await $.fs.stat(path);
485
486    if (size <= MAX_READ_BYTES) {
487      return await $.fs.read(path);
488    }
489
490    const { exitCode, stdout } = await $.process.run(["tail", "-c", String(TRANSCRIPT_TAIL_BYTES), path]);
491    return exitCode === 0 ? stdout : "";
492  } catch {
493    return "";
494  }
495}
496
497/**
498 * The open sections the person left, from the store. The first time 0.7.0
499 * runs there are none yet: the defaults then open, with the one station
500 * 0.6.0 and earlier showed, and that older key makes way for the new one.
501 */
502async function restoreOpenSections($: EngineInterface): Promise<ChefStationName[]> {
503  const stored = await $.store.get(OPEN_SECTIONS_KEY);
504
505  if (Array.isArray(stored)) {
506    return stored.filter(isStation);
507  }
508
509  const legacy = await $.store.get(LEGACY_STATION_KEY);
510  const restored =
511    isStation(legacy) && !DEFAULT_OPEN_SECTIONS.includes(legacy) ? [...DEFAULT_OPEN_SECTIONS, legacy] : [...DEFAULT_OPEN_SECTIONS];
512  await $.store.set(OPEN_SECTIONS_KEY, restored);
513  await $.store.delete(LEGACY_STATION_KEY);
514  return restored;
515}
516
517/** Opens a station's section, or closes it when it is open. */
518async function toggleSection($: EngineInterface, name: ChefStationName, refresher: AgentsRefresher) {
519  if ((await read($, openSections)).includes(name)) {
520    await setOpenSections($, (before) => before.filter((open) => open !== name));
521  } else {
522    await openSection($, name, refresher);
523  }
524}
525
526/**
527 * Opens a station's section, remembers it for the next session, and fills in
528 * what that station needs: a measurement of the context, or the list of live sessions.
529 */
530async function openSection($: EngineInterface, name: ChefStationName, refresher: AgentsRefresher) {
531  // Kept in the stations' own order, so the stored list reads the way the sidebar does.
532  await setOpenSections($, (before) => STATIONS.map((entry) => entry.name).filter((open) => open === name || before.includes(open)));
533
534  if (name === "context") {
535    await refreshContext($).catch(() => undefined);
536  }
537
538  if (name === "agents") {
539    await refreshAgents($, refresher);
540  }
541}
542
543async function setOpenSections($: EngineInterface, change: (before: ChefStationName[]) => ChefStationName[]) {
544  const after = await update($, openSections, change);
545  await $.store.set(OPEN_SECTIONS_KEY, after);
546}
547
548/** Whether the person can see the sidebar: open, placed (not waiting for a wider terminal) and not behind another tab. */
549async function isSidebarShown($: EngineInterface): Promise<boolean> {
550  const panes = await $.ui.panes();
551  return panes.some((pane) => pane.id === PANE_ID && pane.isPlaced && pane.isShown);
552}
553
554/**
555 * The timer's refresh, only while the sidebar is in view: every tick while
556 * the Agents section is open, and once a minute for its header's figure while
557 * it is closed.
558 */
559async function refreshAgentsWhileShown($: EngineInterface, refresher: AgentsRefresher) {
560  if (!(await isSidebarShown($))) {
561    return;
562  }
563
564  const isOpen = (await read($, openSections)).includes("agents");
565  const { refreshedAt } = await read($, agents);
566
567  if (isOpen || (await $.clock.now()) - refreshedAt >= AGENTS_CLOSED_REFRESH_MS) {
568    await refreshAgents($, refresher);
569  }
570}
571
572/**
573 * Looks at the live sessions again. A slow `ps` or `tail` must not stack
574 * refreshes on top of each other, so a call made while one runs waits for
575 * that one, whose result is at most a moment old.
576 */
577async function refreshAgents($: EngineInterface, refresher: AgentsRefresher): Promise<void> {
578  refresher.inFlight ??= (async () => {
579    try {
580      const found = await collectAgents($, refresher);
581      await update($, agents, () => found);
582    } catch (error) {
583      const message = error instanceof Error ? error.message : String(error);
584      await update($, agents, (before) => ({ ...before, error: message }));
585    } finally {
586      refresher.inFlight = undefined;
587    }
588  })();
589
590  return refresher.inFlight;
591}
592
593/** Every live session: the registry's entries whose process still runs, each with its transcript's summary. */
594async function collectAgents($: EngineInterface, refresher: AgentsRefresher): Promise<ChefStationAgents> {
595  const config = await configDirectory($);
596  const live = await liveEntriesOf($, await readRegistry($, `${config}/sessions`));
597  const found = await Promise.all(
598    live.map(async (entry) => toAgent(entry, await summariseSession($, `${config}/projects`, entry, refresher))),
599  );
600  const liveIds = new Set(live.map((entry) => entry.sessionId));
601
602  for (const sessionId of refresher.transcripts.keys()) {
603    if (!liveIds.has(sessionId)) {
604      refresher.transcripts.delete(sessionId);
605    }
606  }
607
608  return { agents: sortAgents(found), refreshedAt: await $.clock.now() };
609}
610
611/** Every running Claude Code process writes `<pid>.json` into the sessions folder; one that does not parse is left out. */
612async function readRegistry($: EngineInterface, directory: string): Promise<RegistryEntry[]> {
613  // No sessions folder means no session has registered yet: an empty list, not an error.
614  const files = await $.fs.list(directory).catch(() => []);
615  const entries = await Promise.all(
616    files
617      .filter((file) => file.kind === "file" && file.name.endsWith(".json"))
618      .map((file) =>
619        $.fs
620          .read(`${directory}/${file.name}`)
621          .then(parseRegistryEntry)
622          .catch(() => undefined),
623      ),
624  );
625
626  return entries.filter((entry): entry is RegistryEntry => entry !== undefined);
627}
628
629/** The entries whose process still runs and is still the one that wrote the entry. */
630async function liveEntriesOf($: EngineInterface, entries: RegistryEntry[]): Promise<RegistryEntry[]> {
631  if (entries.length === 0) {
632    return [];
633  }
634
635  // The registry records `procStart` in UTC, so ps must print UTC for the two to match.
636  // ps prints only the pids that still run, so its exit code says nothing the output does not.
637  const { stdout } = await $.process.run(["ps", "-o", "pid=,lstart=", "-p", entries.map((entry) => entry.pid).join(",")], {
638    env: { TZ: "UTC" },
639  });
640  const started = parsePsOutput(stdout);
641
642  return entries.filter((entry) => isSameProcess(entry, started));
643}
644
645/** One unreadable transcript leaves its card without details rather than failing the whole list. */
646async function summariseSession(
647  $: EngineInterface,
648  projects: string,
649  entry: RegistryEntry,
650  refresher: AgentsRefresher,
651): Promise<TranscriptSummary> {
652  const path = `${projects}/${projectFolderOf(entry.cwd)}/${entry.sessionId}.jsonl`;
653  const stat = await $.fs.stat(path).catch(() => undefined);
654
655  if (stat === undefined) {
656    return {};
657  }
658
659  const cached = refresher.transcripts.get(entry.sessionId);
660
661  if (cached?.mtimeMs === stat.mtimeMs) {
662    return cached.summary;
663  }
664
665  // Transcripts grow past the 4 MiB a mod may read, so only the end is read, through `tail`.
666  const tail = await $.process.run(["tail", "-c", String(AGENTS_TAIL_BYTES), path]).catch(() => undefined);
667
668  if (tail === undefined || tail.exitCode !== 0) {
669    return {};
670  }
671
672  const summary = summariseTranscriptTail(tail.stdout);
673  refresher.transcripts.set(entry.sessionId, { mtimeMs: stat.mtimeMs, summary });
674  return summary;
675}
676
677/** What the Context station's Compact and Clear buttons, and Clear's confirmation, do. */
678async function runContextAction($: EngineInterface, action: "compact" | "clear" | "confirm-clear" | "cancel-clear") {
679  if (action === "clear") {
680    await update($, contextAction, (before) => ({ ...before, isConfirmingClear: true, message: undefined }));
681    return;
682  }
683
684  if (action === "cancel-clear") {
685    await update($, contextAction, (before) => ({ ...before, isConfirmingClear: false }));
686    return;
687  }
688
689  // Two quick presses can both arrive before the redraw hides the buttons. Claiming the
690  // running flag in one read-and-write lets only the first of them start the action.
691  let isClaimed = false;
692  await update($, contextAction, (before) => {
693    isClaimed = !before.isRunning;
694    return isClaimed ? { isRunning: true, isConfirmingClear: false } : before;
695  });
696
697  if (!isClaimed) {
698    return;
699  }
700
701  let message: string | undefined;
702
703  try {
704    if (action === "compact") {
705      const result = await $.session.compact();
706
707      if (result.skip !== undefined) {
708        message = `Compacting was skipped: ${result.skip}`;
709      } else if (result.tokensBefore !== undefined && result.tokensAfter !== undefined) {
710        message = `Compacted from ${short(result.tokensBefore)} to ${short(result.tokensAfter)} tokens.`;
711      } else {
712        message = "Compacted.";
713      }
714    } else {
715      // There is no call for this on $; the button runs /clear as if it were typed.
716      await $.command.run({ command: "clear" });
717      message = "Cleared. A new conversation has started.";
718    }
719  } catch (error) {
720    message = `Could not ${action === "compact" ? "compact" : "clear"}: ${error instanceof Error ? error.message : String(error)}`;
721  }
722
723  await update($, contextAction, () => ({ isRunning: false, isConfirmingClear: false, message }));
724  await refreshContext($).catch(() => undefined);
725}
726
727/**
728 * Measures the context window by category, as /context does. The `summary`
729 * level estimates locally and sends no token-count requests, so it is cheap
730 * enough to run after every turn.
731 */
732async function refreshContext($: EngineInterface) {
733  const { context } = await $.session.usage({ breakdown: "summary" });
734  const breakdown = context.breakdown;
735
736  if (!breakdown) {
737    return;
738  }
739
740  const measured: ChefStationContext = {
741    categories: breakdown.categories.map(({ name, tokens, kind }) => ({ name, tokens, kind })),
742    totalTokens: breakdown.totalTokens,
743    maxTokens: breakdown.rawMaxTokens,
744  };
745
746  await update($, contextBreakdown, () => measured);
747}
748
749/** Moves the sidebar's clock on and picks up what other sessions have recorded. */
750async function tick($: EngineInterface) {
751  const at = await $.clock.now();
752  await update($, now, () => at);
753  await refreshLedger($);
754}
755
756async function refreshLedger($: EngineInterface) {
757  const composed = await loadLedger($);
758  await update($, ledger, () => composed);
759}
760
761/**
762 * Every session's turns and the last scan, read from the store and added up.
763 * A session whose days have all fallen out of the thirteen weeks is deleted
764 * on the way, so the store does not grow without end.
765 */
766async function loadLedger($: EngineInterface): Promise<ChefStationLedger> {
767  const at = await $.clock.now();
768  const sessions: Record<string, ChefStationLedger> = {};
769
770  for (const key of await $.store.keys()) {
771    if (!key.startsWith(SESSION_KEY_PREFIX) && key !== LEGACY_LEDGER_KEY) {
772      continue;
773    }
774
775    const part = asLedger(await $.store.get(key));
776
777    if (isStale(part, at)) {
778      await $.store.delete(key);
779    } else {
780      sessions[key] = part;
781    }
782  }
783
784  const backfill = asBackfill(await $.store.get(BACKFILL_KEY)) ?? sessions[LEGACY_LEDGER_KEY]?.backfill;
785  return composeLedger(sessions, backfill, at);
786}
787
788async function applyMeasure($: EngineInterface, e: SessionMeasureInput | SessionUsage) {
789  await update($, live, (before) =>
790    before === null
791      ? before
792      : {
793          ...before,
794          usd: e.cost?.usd ?? before.usd,
795          contextPercent: e.context.percent ?? before.contextPercent,
796          rateLimits: [...e.rateLimits],
797        },
798  );
799}
800
801function asLedger(value: unknown): ChefStationLedger {
802  const isLedger =
803    typeof value === "object" && value !== null && (value as ChefStationLedger).version === 1 && typeof (value as ChefStationLedger).days === "object";
804
805  return isLedger ? (value as ChefStationLedger) : emptyLedger();
806}
807
808function asBackfill(value: unknown): ChefStationBackfill | undefined {
809  const isBackfill = typeof value === "object" && value !== null && typeof (value as ChefStationBackfill).days === "object";
810  return isBackfill ? (value as ChefStationBackfill) : undefined;
811}
812
813function isStation(value: unknown): value is ChefStationName {
814  return STATIONS.some((entry) => entry.name === value);
815}
816
817function basename(path: string): string {
818  const parts = path.split(/[\\/]/).filter(Boolean);
819  return parts[parts.length - 1] ?? path;
820}
821
hooks/agents.ts 326 lines
1// Pure parsing for the Agents station: no file system or processes, so tests call it directly.
2// register.tsx reads the files and runs `ps` and `tail`, because a function handed `$` must be
3// declared in the hooks module itself.
4
5import type { ChefStationAgent, ChefStationAgentAction, ChefStationAgentStatus, ChefStationAgentSurface } from "../types";
6
7/** One `~/.claude/sessions/<pid>.json` file: what every running Claude Code process writes about itself. */
8export type RegistryEntry = {
9  pid: number;
10  sessionId: string;
11  cwd: string;
12  name: string;
13  kind: string;
14  entrypoint: string;
15  status: ChefStationAgentStatus;
16  startedAt?: number;
17  /** The process start time in UTC, as `TZ=UTC ps -o lstart=` prints it, so a reused pid is not mistaken for the session. */
18  procStart?: string;
19};
20
21export type TranscriptSummary = {
22  /** A title the person set (`custom-title`) wins over the one Claude generated (`ai-title`). */
23  customTitle?: string;
24  aiTitle?: string;
25  lastPrompt?: string;
26  lastAction?: ChefStationAgentAction;
27  lastActivityAt?: number;
28};
29
30type JsonObject = Record<string, unknown>;
31
32/** The marker Claude Code writes as a user line when the person presses Esc mid-turn. */
33const INTERRUPTION_MARKER = /^\[Request interrupted by user/;
34
35/** Sessions waiting on the person come first, as they are the ones that need them. */
36const STATUS_ORDER: Record<ChefStationAgentStatus, number> = { waiting: 0, busy: 1, unknown: 2, idle: 3 };
37
38/** A session that wrote a prompt or a response this recently still counts as active, though idle now. */
39export const ACTIVE_WINDOW_MS = 15 * 60_000;
40
41/** Every status a registry entry may name; anything else reads as `unknown`. */
42const STATUSES: readonly ChefStationAgentStatus[] = ["busy", "waiting", "idle"];
43
44export const SURFACE_LABELS: Record<ChefStationAgentSurface, string> = {
45  desktop: "Desktop app",
46  terminal: "Terminal",
47  background: "Background",
48};
49
50/** The folder name Claude Code stores a working directory's transcripts under. */
51export function projectFolderOf(cwd: string): string {
52  return cwd.replace(/[^A-Za-z0-9]/g, "-");
53}
54
55export function parseRegistryEntry(text: string): RegistryEntry | undefined {
56  let parsed: unknown;
57
58  try {
59    parsed = JSON.parse(text);
60  } catch {
61    return undefined;
62  }
63
64  if (!isObject(parsed)) {
65    return undefined;
66  }
67
68  const { pid, sessionId, cwd, startedAt } = parsed;
69
70  if (typeof pid !== "number" || typeof sessionId !== "string" || typeof cwd !== "string") {
71    return undefined;
72  }
73
74  return {
75    pid,
76    sessionId,
77    cwd,
78    name: stringOf(parsed.name) ?? lastSegmentOf(cwd),
79    kind: stringOf(parsed.kind) ?? "interactive",
80    entrypoint: stringOf(parsed.entrypoint) ?? "cli",
81    status: STATUSES.find((status) => status === parsed.status) ?? "unknown",
82    startedAt: typeof startedAt === "number" ? startedAt : undefined,
83    procStart: stringOf(parsed.procStart),
84  };
85}
86
87export function surfaceOf(entry: RegistryEntry): ChefStationAgentSurface {
88  if (entry.kind === "bg") {
89    return "background";
90  }
91
92  return entry.entrypoint === "claude-desktop" ? "desktop" : "terminal";
93}
94
95/** Reads `ps -o pid=,lstart= -p <pids>` output into pid → start time. */
96export function parsePsOutput(stdout: string): Map<number, string> {
97  const started = new Map<number, string>();
98
99  for (const line of stdout.split("\n")) {
100    const match = /^\s*(\d+)\s+(.+?)\s*$/.exec(line);
101
102    if (match?.[1] && match[2]) {
103      started.set(Number(match[1]), collapseWhitespace(match[2]));
104    }
105  }
106
107  return started;
108}
109
110/** True when the entry's pid is running and is still the process that wrote the entry. */
111export function isSameProcess(entry: RegistryEntry, started: Map<number, string>): boolean {
112  const startedAt = started.get(entry.pid);
113
114  if (startedAt === undefined) {
115    return false;
116  }
117
118  return entry.procStart === undefined || collapseWhitespace(entry.procStart) === startedAt;
119}
120
121/** A short, human description of one tool call, such as "Edit: AGENTS.md" or "Bash: Run the unit tests". */
122export function describeToolUse(name: string, input: unknown): string {
123  const args = isObject(input) ? input : {};
124  const tool = name.startsWith("mcp__") ? (name.split("__").pop() ?? name) : name;
125  const detail =
126    stringOf(args.description) ??
127    fileNameOf(args, "file_path") ??
128    fileNameOf(args, "notebook_path") ??
129    stringOf(args.pattern) ??
130    stringOf(args.url) ??
131    stringOf(args.query) ??
132    stringOf(args.skill) ??
133    stringOf(args.command);
134
135  return detail === undefined ? tool : truncate(`${tool}: ${detail}`, 140);
136}
137
138/**
139 * Summarises the end of a session transcript (JSON lines). The text may start
140 * mid-line, because only the file's tail is read, so a line that does not
141 * parse is skipped.
142 */
143export function summariseTranscriptTail(text: string): TranscriptSummary {
144  const summary: TranscriptSummary = {};
145  const lines = text.split("\n");
146
147  for (let index = lines.length - 1; index >= 0; index -= 1) {
148    const line = lines[index]?.trim();
149
150    if (!line) {
151      continue;
152    }
153
154    let entry: unknown;
155
156    try {
157      entry = JSON.parse(line);
158    } catch {
159      continue;
160    }
161
162    if (!isObject(entry)) {
163      continue;
164    }
165
166    if (entry.type === "custom-title") {
167      summary.customTitle ??= stringOf(entry.customTitle);
168    }
169
170    if (entry.type === "ai-title") {
171      summary.aiTitle ??= stringOf(entry.aiTitle);
172    }
173
174    if (entry.type === "last-prompt") {
175      summary.lastPrompt ??= stringOf(entry.lastPrompt);
176    }
177
178    if (entry.type === "user" || entry.type === "assistant") {
179      const timestamp = Date.parse(stringOf(entry.timestamp) ?? "");
180
181      if (summary.lastActivityAt === undefined && !Number.isNaN(timestamp)) {
182        summary.lastActivityAt = timestamp;
183      }
184    }
185
186    if (entry.type === "assistant") {
187      summary.lastAction ??= describeAssistantStep(contentBlocksOf(entry.message));
188    }
189
190    if (entry.type === "user") {
191      summary.lastPrompt ??= typedPromptOf(entry);
192    }
193
194    const isComplete =
195      (summary.customTitle ?? summary.aiTitle) !== undefined &&
196      summary.lastPrompt !== undefined &&
197      summary.lastAction !== undefined &&
198      summary.lastActivityAt !== undefined;
199
200    if (isComplete) {
201      break;
202    }
203  }
204
205  if (summary.lastPrompt !== undefined) {
206    summary.lastPrompt = truncate(summary.lastPrompt, 240);
207  }
208
209  return summary;
210}
211
212export function toAgent(entry: RegistryEntry, transcript: TranscriptSummary): ChefStationAgent {
213  const title = transcript.customTitle ?? transcript.aiTitle;
214
215  return {
216    pid: entry.pid,
217    sessionId: entry.sessionId,
218    name: entry.name,
219    title: title !== undefined && title !== entry.name ? title : undefined,
220    surface: surfaceOf(entry),
221    project: lastSegmentOf(entry.cwd),
222    status: entry.status,
223    lastPrompt: transcript.lastPrompt,
224    lastAction: transcript.lastAction,
225    lastActivityAt: transcript.lastActivityAt,
226    startedAt: entry.startedAt,
227  };
228}
229
230/**
231 * Splits sessions into the active ones, shown in full, and the idle ones,
232 * folded away: active means busy, waiting, or active within the last
233 * fifteen minutes. Each part keeps the order it was given.
234 */
235export function partitionAgents(
236  agents: readonly ChefStationAgent[],
237  now: number,
238): { active: ChefStationAgent[]; idle: ChefStationAgent[] } {
239  const isActive = (agent: ChefStationAgent) =>
240    agent.status === "busy" ||
241    agent.status === "waiting" ||
242    (agent.lastActivityAt !== undefined && now - agent.lastActivityAt <= ACTIVE_WINDOW_MS);
243
244  return { active: agents.filter(isActive), idle: agents.filter((agent) => !isActive(agent)) };
245}
246
247/** Waiting sessions first, then busy ones, then the most recently active. */
248export function sortAgents(agents: readonly ChefStationAgent[]): ChefStationAgent[] {
249  return [...agents].sort(
250    (a, b) =>
251      STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
252      (b.lastActivityAt ?? b.startedAt ?? 0) - (a.lastActivityAt ?? a.startedAt ?? 0),
253  );
254}
255
256function isObject(value: unknown): value is JsonObject {
257  return typeof value === "object" && value !== null && !Array.isArray(value);
258}
259
260function stringOf(value: unknown): string | undefined {
261  return typeof value === "string" && value.length > 0 ? value : undefined;
262}
263
264function collapseWhitespace(text: string): string {
265  return text.replace(/\s+/g, " ").trim();
266}
267
268function truncate(text: string, max: number): string {
269  const flat = collapseWhitespace(text);
270  return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
271}
272
273function lastSegmentOf(path: string): string {
274  return path.split("/").filter(Boolean).pop() ?? path;
275}
276
277function fileNameOf(input: JsonObject, key: string): string | undefined {
278  const path = stringOf(input[key]);
279  return path === undefined ? undefined : lastSegmentOf(path);
280}
281
282function contentBlocksOf(message: unknown): JsonObject[] {
283  if (!isObject(message)) {
284    return [];
285  }
286
287  const { content } = message;
288
289  if (typeof content === "string") {
290    return [{ type: "text", text: content }];
291  }
292
293  return Array.isArray(content) ? content.filter(isObject) : [];
294}
295
296function describeAssistantStep(blocks: JsonObject[]): ChefStationAgentAction | undefined {
297  const toolUse = blocks.filter((block) => block.type === "tool_use").pop();
298
299  if (toolUse) {
300    return { kind: "tool", text: describeToolUse(stringOf(toolUse.name) ?? "tool", toolUse.input) };
301  }
302
303  const text = blocks
304    .map((block) => (block.type === "text" ? stringOf(block.text) : undefined))
305    .filter((part): part is string => part !== undefined)
306    .join(" ");
307  // Bold and code markers, and a link's address, read as noise on a one-line card; the words stay.
308  const plain = text.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\*\*|`/g, "");
309
310  return plain.length > 0 ? { kind: "reply", text: truncate(plain, 160) } : undefined;
311}
312
313/** A prompt the person typed, rather than a tool result or a message the harness injected. */
314function typedPromptOf(entry: JsonObject): string | undefined {
315  // A compaction summary is written as a user line, but the person never typed it.
316  if (entry.isMeta === true || entry.isCompactSummary === true) {
317    return undefined;
318  }
319
320  const texts = contentBlocksOf(entry.message)
321    .map((block) => (block.type === "text" ? stringOf(block.text)?.trimStart() : undefined))
322    .filter((text): text is string => text !== undefined && !text.startsWith("<") && !INTERRUPTION_MARKER.test(text));
323
324  return texts.length > 0 ? texts.join(" ") : undefined;
325}
326
hooks/cache.ts 83 lines
1import type { ChefStationCache, ChefStationCacheTtl } from "../types";
2import { countdown } from "./format";
3
4const TTL_MS: Record<ChefStationCacheTtl, number> = { "5m": 5 * 60_000, "1h": 60 * 60_000 };
5
6export type CacheStatus = { state: "warm"; remainingMs: number } | { state: "expired" } | { state: "none" };
7
8/**
9 * The lifetime of the main conversation's latest prompt-cache write, read from
10 * the end of its transcript: `1h` or `5m`, or undefined when no write shows.
11 *
12 * Responses that only read the cache are skipped, since a read keeps the
13 * lifetime its entry was written with. So are subagents' responses, whose
14 * cache is their own. A text cut from the middle of a file may begin with a
15 * partial line, which does not parse and is skipped too.
16 */
17export function cacheTtlFromTranscript(text: string): ChefStationCacheTtl | undefined {
18  const lines = text.split("\n");
19
20  for (let index = lines.length - 1; index >= 0; index--) {
21    const line = lines[index]!;
22
23    if (!line.includes('"usage"') || !line.includes('"assistant"')) {
24      continue;
25    }
26
27    let record;
28
29    try {
30      record = JSON.parse(line);
31    } catch {
32      continue;
33    }
34
35    const usage = record?.message?.usage;
36
37    if (record.type !== "assistant" || record.isSidechain === true || !usage) {
38      continue;
39    }
40
41    const byTtl = usage.cache_creation;
42
43    if ((byTtl?.ephemeral_1h_input_tokens ?? 0) > 0) {
44      return "1h";
45    }
46
47    if ((byTtl?.ephemeral_5m_input_tokens ?? 0) > 0) {
48      return "5m";
49    }
50
51    // Older responses report cache writes without the breakdown; those are five-minute writes.
52    if (!byTtl && (usage.cache_creation_input_tokens ?? 0) > 0) {
53      return "5m";
54    }
55  }
56
57  return undefined;
58}
59
60/**
61 * Whether the main conversation's prompt cache is likely still warm, and for
62 * how long. An entry lives for its lifetime from the start of the last request
63 * that read or wrote it; with no lifetime known, the shorter five minutes is
64 * assumed, so the sidebar never calls a cold cache warm.
65 */
66export function cacheStatus(cache: ChefStationCache, now: number): CacheStatus {
67  if (cache.lastRequestAt === undefined) {
68    return { state: "none" };
69  }
70
71  const remainingMs = cache.lastRequestAt + TTL_MS[cache.ttl ?? "5m"] - now;
72  return remainingMs > 0 ? { state: "warm", remainingMs } : { state: "expired" };
73}
74
75/** The Now row's words for the cache: an estimate while warm, so it says so with a tilde. */
76export function cacheLabel(status: CacheStatus): string | undefined {
77  if (status.state === "warm") {
78    return `cache warm · ${status.remainingMs < 60_000 ? "<1m" : `~${countdown(status.remainingMs)}`} left`;
79  }
80
81  return status.state === "expired" ? "cache expired" : undefined;
82}
83
hooks/backfill.ts 66 lines
1import type { ChefStationBackfill, ChefStationDay } from "../types";
2import { modelName, money } from "./format";
3
4/** The most a mod may read in one `$.fs.read`. */
5export const MAX_READ_BYTES = 4 * 1024 * 1024;
6/** A first scan of thirteen weeks of transcripts can take a while. */
7export const SCAN_TIMEOUT_MS = 10 * 60_000;
8
9/** What a scan tallied, from the Node helper or from the mod's own reads. */
10export type Tallied = {
11  days: Record<string, ChefStationDay>;
12  unpricedModels: string[];
13  files: number;
14  /** Transcripts over 4 MiB that the mod could not read itself. */
15  skippedFiles: number;
16  /** Transcripts whose read failed; absent from helpers older than 0.3.1. */
17  unreadableFiles?: number;
18};
19
20/** Turns a tally into the backfill the ledger keeps, with models named as people say them. */
21export function toBackfill(tallied: Tallied, source: ChefStationBackfill["source"], scannedAt: number): ChefStationBackfill {
22  return {
23    days: Object.fromEntries(Object.entries(tallied.days).map(([key, day]) => [key, withModelNames(day)])),
24    scannedAt,
25    source,
26    files: tallied.files,
27    skippedFiles: tallied.skippedFiles,
28    unreadableFiles: tallied.unreadableFiles ?? 0,
29    unpricedModels: tallied.unpricedModels,
30  };
31}
32
33/** A line saying what a scan found, for `/chef backfill` and the activity station. */
34export function describeBackfill(backfill: ChefStationBackfill): string {
35  const usd = Object.values(backfill.days).reduce((sum, day) => sum + day.usd, 0);
36  const files = `${backfill.files} ${backfill.files === 1 ? "transcript" : "transcripts"}`;
37  const notes = [
38    `Read ${files}${backfill.source === "node" ? " with Node" : ""}: ${money(usd)} across ${Object.keys(backfill.days).length} days.`,
39  ];
40
41  if (backfill.skippedFiles > 0) {
42    notes.push(`${backfill.skippedFiles} over 4 MiB were skipped; install Node to include them.`);
43  }
44
45  if ((backfill.unreadableFiles ?? 0) > 0) {
46    notes.push(`Incomplete: ${backfill.unreadableFiles} could not be read, so their usage is missing.`);
47  }
48
49  if (backfill.unpricedModels.length > 0) {
50    notes.push(`No price for ${backfill.unpricedModels.join(", ")}; their tokens count but their cost does not.`);
51  }
52
53  return notes.join(" ");
54}
55
56function withModelNames(day: ChefStationDay): ChefStationDay {
57  const models: Record<string, number> = {};
58
59  for (const [id, usd] of Object.entries(day.models)) {
60    const name = modelName(id);
61    models[name] = (models[name] ?? 0) + usd;
62  }
63
64  return { ...day, models };
65}
66
hooks/format.ts 135 lines
1const EIGHTHS = " ▁▂▃▄▅▆▇█";
2
3export function short(n: number): string {
4  const units: [number, string][] = [
5    [1e9, "B"],
6    [1e6, "M"],
7    [1e3, "k"],
8  ];
9
10  for (const [size, suffix] of units) {
11    if (n >= size) {
12      return `${+(n / size).toFixed(1)}${suffix}`;
13    }
14  }
15
16  return String(Math.round(n));
17}
18
19export function money(usd: number): string {
20  return `$${usd.toFixed(2)}`;
21}
22
23/**
24 * A model id as people say it: `claude-opus-5-5` is "Opus 5.5",
25 * `claude-3-5-sonnet-20241022` is "Sonnet 3.5". A context-window suffix such
26 * as `[1m]`, which `/model` shows, is dropped. Anything else is kept as given.
27 */
28export function modelName(model: string): string {
29  const id = model.replace(/\[[^\]]*\]$/, "");
30  const familyFirst = /^claude-(opus|sonnet|haiku|fable)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(id);
31
32  if (familyFirst) {
33    const [, family = "", major = "", minor] = familyFirst;
34    return `${capitalize(family)} ${minor ? `${major}.${minor}` : major}`;
35  }
36
37  const versionFirst = /^claude-(\d+)(?:-(\d{1,2}))?-(opus|sonnet|haiku)(?:-\d{8})?$/.exec(id);
38
39  if (versionFirst) {
40    const [, major = "", minor, family = ""] = versionFirst;
41    return `${capitalize(family)} ${minor ? `${major}.${minor}` : major}`;
42  }
43
44  return model;
45}
46
47function capitalize(word: string): string {
48  return word.charAt(0).toUpperCase() + word.slice(1);
49}
50
51/** Time until a reset: "1d 23h", "2h 10m", "9m". */
52export function countdown(ms: number): string {
53  if (ms <= 0) {
54    return "now";
55  }
56
57  const minutes = Math.floor(ms / 60_000);
58  const hours = Math.floor(minutes / 60);
59  const days = Math.floor(hours / 24);
60
61  if (days > 0) {
62    return `${days}d ${hours % 24}h`;
63  }
64
65  if (hours > 0) {
66    return `${hours}h ${minutes % 60}m`;
67  }
68
69  return `${minutes}m`;
70}
71
72/** A stopwatch reading: "0:33", "12:05", and past an hour "1:02:03". */
73export function elapsed(ms: number): string {
74  const seconds = Math.max(0, Math.floor(ms / 1_000));
75  const minutes = Math.floor(seconds / 60);
76  const hours = Math.floor(minutes / 60);
77  const pad = (value: number) => String(value).padStart(2, "0");
78
79  if (hours > 0) {
80    return `${hours}:${pad(minutes % 60)}:${pad(seconds % 60)}`;
81  }
82
83  return `${minutes}:${pad(seconds % 60)}`;
84}
85
86/** How long ago something happened: "just now", "42s ago", "5m ago", "3h ago", "2d ago". */
87export function ago(ms: number): string {
88  const seconds = Math.max(0, Math.round(ms / 1_000));
89
90  if (seconds < 10) {
91    return "just now";
92  }
93
94  if (seconds < 60) {
95    return `${seconds}s ago`;
96  }
97
98  const minutes = Math.floor(seconds / 60);
99
100  if (minutes < 60) {
101    return `${minutes}m ago`;
102  }
103
104  const hours = Math.floor(minutes / 60);
105  return hours < 48 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
106}
107
108/** A horizontal meter `width` cells wide, split so each part can take its own color. */
109export function bar(percent: number, width: number): { filled: string; empty: string } {
110  const cells = Math.round((Math.min(Math.max(percent, 0), 100) / 100) * width);
111  return { filled: "█".repeat(cells), empty: "░".repeat(width - cells) };
112}
113
114/**
115 * Columns of eighth blocks, `rows` tall, one character per value, returned top
116 * row first. The largest value fills the height; any value above zero shows
117 * at least one eighth so a quiet hour is still visible.
118 */
119export function verticalBars(values: number[], rows: number): string[] {
120  const top = Math.max(...values, 0);
121  const levels = rows * 8;
122  const heights = values.map((value) => {
123    if (value <= 0 || top === 0) {
124      return 0;
125    }
126
127    return Math.max(1, Math.round((value / top) * levels));
128  });
129
130  return Array.from({ length: rows }, (_, rowFromTop) => {
131    const floor = (rows - 1 - rowFromTop) * 8;
132    return heights.map((height) => EIGHTHS[Math.min(Math.max(height - floor, 0), 8)]).join("");
133  });
134}
135
hooks/ledger.ts 233 lines
1import type { ChefStationBackfill, ChefStationDay, ChefStationLedger } from "../types";
2import { dayKey } from "./transcript.mjs";
3
4export { dayKey };
5
6/** How far back the ledger remembers: the thirteen weeks the activity grid shows. */
7export const WEEKS = 13;
8
9export type TurnUsage = {
10  input: number;
11  output: number;
12  cacheRead: number;
13  cacheCreation: number;
14};
15
16export type TurnRecord = {
17  /** When the turn completed, in milliseconds since the epoch. */
18  at: number;
19  /** What the turn cost, in US dollars. */
20  usd: number;
21  model: string;
22  project: string;
23  /** The session the turn ran in, so a scan of the transcripts does not count it again. */
24  sessionId: string;
25  usage?: TurnUsage;
26};
27
28export type Ranked = { name: string; usd: number };
29
30export type Activity = {
31  /** Thirteen columns of Monday to Sunday; `null` for a day still ahead. */
32  weeks: (number | null)[][];
33  totalTokens: number;
34  activeDays: number;
35  busiest?: { key: string; tokens: number };
36  /** Consecutive active days up to today, or up to yesterday before today's first turn. */
37  streak: number;
38};
39
40export function emptyLedger(): ChefStationLedger {
41  return { version: 1, days: {} };
42}
43
44function emptyDay(): ChefStationDay {
45  return {
46    usd: 0,
47    tokens: 0,
48    cacheReadTokens: 0,
49    inputTokens: 0,
50    hours: new Array(24).fill(0),
51    models: {},
52    projects: {},
53  };
54}
55
56/** Midnight, local time, `days` days before the day of `ms`. */
57function startOfDay(ms: number, daysBack = 0): number {
58  const date = new Date(ms);
59  return new Date(date.getFullYear(), date.getMonth(), date.getDate() - daysBack).getTime();
60}
61
62/**
63 * Adds one completed turn to the ledger and drops the days that have fallen
64 * out of the thirteen weeks. Returns a new ledger; the one passed in is left as it was.
65 */
66export function recordTurn(ledger: ChefStationLedger, turn: TurnRecord): ChefStationLedger {
67  const key = dayKey(turn.at);
68  const before = ledger.days[key] ?? emptyDay();
69  const usage = turn.usage ?? { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 };
70  const inputTokens = usage.input + usage.cacheRead + usage.cacheCreation;
71  const hour = new Date(turn.at).getHours();
72  const hours = before.hours.map((usd, index) => (index === hour ? usd + turn.usd : usd));
73
74  const day: ChefStationDay = {
75    usd: before.usd + turn.usd,
76    tokens: before.tokens + inputTokens + usage.output,
77    cacheReadTokens: before.cacheReadTokens + usage.cacheRead,
78    inputTokens: before.inputTokens + inputTokens,
79    hours,
80    models: addTo(before.models, turn.model, turn.usd),
81    projects: addTo(before.projects, turn.project, turn.usd),
82  };
83
84  return prune(
85    {
86      ...ledger,
87      days: { ...ledger.days, [key]: day },
88      liveSessions: { ...ledger.liveSessions, [turn.sessionId]: key },
89    },
90    turn.at,
91  );
92}
93
94/** Puts a fresh scan of the transcripts in place of the last one. */
95export function withBackfill(ledger: ChefStationLedger, backfill: ChefStationBackfill): ChefStationLedger {
96  return prune({ ...ledger, backfill }, backfill.scannedAt);
97}
98
99/** The earliest moment a scan needs to read: the first day the ledger keeps. */
100export function backfillSince(now: number): number {
101  return startOfDay(now, WEEKS * 7 - 1);
102}
103
104function addTo(record: Record<string, number>, name: string, usd: number): Record<string, number> {
105  return { ...record, [name]: (record[name] ?? 0) + usd };
106}
107
108function prune(ledger: ChefStationLedger, now: number): ChefStationLedger {
109  const oldest = dayKey(backfillSince(now));
110  const isKept = ([key]: [string, unknown]) => key >= oldest;
111  const keepDays = (days: Record<string, ChefStationDay>) => Object.fromEntries(Object.entries(days).filter(isKept));
112  // Sessions are keyed by id with their last day as the value.
113  const liveSessions = Object.fromEntries(Object.entries(ledger.liveSessions ?? {}).filter(([, key]) => key >= oldest));
114
115  return {
116    version: 1,
117    days: keepDays(ledger.days),
118    liveSessions,
119    ...(ledger.backfill ? { backfill: { ...ledger.backfill, days: keepDays(ledger.backfill.days) } } : {}),
120  };
121}
122
123/** One day as the sidebar shows it: what was recorded live plus what the last scan found. */
124function dayOf(ledger: ChefStationLedger, key: string): ChefStationDay | undefined {
125  const live = ledger.days[key];
126  const scanned = ledger.backfill?.days[key];
127
128  return live && scanned ? addDays(live, scanned) : (live ?? scanned);
129}
130
131function addDays(first: ChefStationDay, second: ChefStationDay): ChefStationDay {
132  return {
133    usd: first.usd + second.usd,
134    tokens: first.tokens + second.tokens,
135    cacheReadTokens: first.cacheReadTokens + second.cacheReadTokens,
136    inputTokens: first.inputTokens + second.inputTokens,
137    hours: first.hours.map((usd, hour) => usd + (second.hours[hour] ?? 0)),
138    models: sumRecords(first.models, second.models),
139    projects: sumRecords(first.projects, second.projects),
140  };
141}
142
143/**
144 * The ledger the sidebar reads, put together from the turns each session stored
145 * under a key of its own and the last scan of the transcripts. Each session
146 * writing only its own key keeps two sessions from overwriting each other.
147 */
148export function composeLedger(
149  sessions: Record<string, ChefStationLedger>,
150  backfill: ChefStationBackfill | undefined,
151  now: number,
152): ChefStationLedger {
153  const days: Record<string, ChefStationDay> = {};
154  const liveSessions: Record<string, string> = {};
155
156  for (const part of Object.values(sessions)) {
157    for (const [key, day] of Object.entries(part.days)) {
158      const before = days[key];
159      days[key] = before ? addDays(before, day) : day;
160    }
161
162    Object.assign(liveSessions, part.liveSessions);
163  }
164
165  return prune({ version: 1, days, liveSessions, ...(backfill ? { backfill } : {}) }, now);
166}
167
168/** Whether every day a session stored has fallen out of the thirteen weeks. */
169export function isStale(ledger: ChefStationLedger, now: number): boolean {
170  return Object.keys(prune(ledger, now).days).length === 0;
171}
172
173function sumRecords(first: Record<string, number>, second: Record<string, number>): Record<string, number> {
174  return Object.entries(second).reduce((sum, [name, usd]) => addTo(sum, name, usd), first);
175}
176
177export function today(ledger: ChefStationLedger, now: number): ChefStationDay {
178  return dayOf(ledger, dayKey(now)) ?? emptyDay();
179}
180
181export function hourly(ledger: ChefStationLedger, now: number): number[] {
182  return today(ledger, now).hours;
183}
184
185/** Entries sorted by cost, most expensive first, at most `limit` of them. */
186export function ranked(record: Record<string, number>, limit = Infinity): Ranked[] {
187  return Object.entries(record)
188    .map(([name, usd]) => ({ name, usd }))
189    .sort((a, b) => b.usd - a.usd)
190    .slice(0, limit);
191}
192
193export function activity(ledger: ChefStationLedger, now: number): Activity {
194  // getDay() counts from Sunday; the grid counts from Monday.
195  const weekday = (new Date(now).getDay() + 6) % 7;
196  const daysShown = (WEEKS - 1) * 7 + weekday + 1;
197  const weeks: (number | null)[][] = Array.from({ length: WEEKS }, () => new Array(7).fill(null));
198
199  let totalTokens = 0;
200  let activeDays = 0;
201  let busiest: Activity["busiest"];
202
203  for (let index = 0; index < daysShown; index++) {
204    const key = dayKey(startOfDay(now, daysShown - 1 - index));
205    const tokens = dayOf(ledger, key)?.tokens ?? 0;
206    weeks[Math.floor(index / 7)]![index % 7] = tokens;
207
208    if (tokens > 0) {
209      totalTokens += tokens;
210      activeDays += 1;
211
212      if (busiest === undefined || tokens > busiest.tokens) {
213        busiest = { key, tokens };
214      }
215    }
216  }
217
218  return { weeks, totalTokens, activeDays, busiest, streak: streak(ledger, now) };
219}
220
221function streak(ledger: ChefStationLedger, now: number): number {
222  const isActive = (daysBack: number) => (dayOf(ledger, dayKey(startOfDay(now, daysBack)))?.tokens ?? 0) > 0;
223  let daysBack = isActive(0) ? 0 : 1;
224  let count = 0;
225
226  while (daysBack <= WEEKS * 7 && isActive(daysBack)) {
227    count += 1;
228    daysBack += 1;
229  }
230
231  return count;
232}
233
hooks/stations.tsx 634 lines
1import type { Elements, RenderChildren } from "claude-code";
2
3import type {
4  ChefStationAgent,
5  ChefStationAgents,
6  ChefStationCache,
7  ChefStationContext,
8  ChefStationContextAction,
9  ChefStationLedger,
10  ChefStationLive,
11  ChefStationName,
12} from "../types";
13import { partitionAgents, SURFACE_LABELS } from "./agents";
14import { cacheLabel, cacheStatus } from "./cache";
15import { allocateCells, contextSegments } from "./context";
16import { ago, bar, countdown, elapsed, money, short, verticalBars } from "./format";
17import { activity, hourly, ranked, today } from "./ledger";
18
19/** The elements a station draws with; the terminal's and the desktop's tables both have them. */
20export type Ui = Pick<Elements["terminal"], "Box" | "Text" | "Button">;
21
22export type SidebarView = {
23  ui: Ui;
24  /** The stations whose sections are open, each drawing its body under its header. */
25  openSections: readonly ChefStationName[];
26  ledger: ChefStationLedger;
27  live?: ChefStationLive;
28  now: number;
29  plan?: string;
30  /** Whether a scan of the transcripts is running, and what the last one said. */
31  backfillStatus?: { isRunning: boolean; message?: string };
32  /** The main conversation's prompt cache: when it was last used, and how long its entries live. */
33  cache?: ChefStationCache;
34  /** The context window by category; null until the first measurement. */
35  context?: ChefStationContext | null;
36  /** Whether Clear or Compact is running, whether Clear awaits confirmation, and what the last one said. */
37  contextAction?: ChefStationContextAction;
38  onContextAction?: (action: "compact" | "clear" | "confirm-clear" | "cancel-clear") => void;
39  /** Every live Claude Code session on this machine, for the Agents station. */
40  agents?: ChefStationAgents;
41  /** Whether the Agents station lists its idle sessions or keeps them folded under one row. */
42  isIdleOpen: boolean;
43  isWorking: boolean;
44  columns: number;
45  onToggle: (station: ChefStationName) => void;
46  onToggleIdle: () => void;
47};
48
49export const STATIONS: { name: ChefStationName; label: string; hotkey: string }[] = [
50  { name: "usage", label: "Usage", hotkey: "1" },
51  { name: "trend", label: "Trend", hotkey: "2" },
52  { name: "breakdown", label: "Breakdown", hotkey: "3" },
53  { name: "activity", label: "Activity", hotkey: "4" },
54  { name: "context", label: "Context", hotkey: "5" },
55  { name: "agents", label: "Agents", hotkey: "6" },
56];
57
58const RATE_LIMIT_LABELS: Record<string, string> = {
59  five_hour: "Session",
60  seven_day: "Week",
61  seven_day_opus: "Week Opus",
62  seven_day_sonnet: "Week Sonnet",
63  spend_limit: "Spend",
64};
65
66const LABEL_WIDTH = 10;
67const ACCENT = "claude";
68const MUTED = "subtle";
69/** Cells of padding inside a section's border, each side. */
70const SECTION_PADDING = 2;
71/** What a section's frame takes from the width: its border and its padding, each side. */
72const SECTION_FRAME_COLUMNS = 2 * (1 + SECTION_PADDING);
73
74export function sidebar(view: SidebarView) {
75  const { Box, Text } = view.ui;
76
77  return (
78    <Box flexDirection="column" paddingX={1}>
79      <Box flexDirection="row" columnGap={1}>
80        <Text color={ACCENT} bold>
81          ✻ Claude
82        </Text>
83        {view.plan ? <Text color={ACCENT}>{view.plan}</Text> : null}
84      </Box>
85      {STATIONS.map((entry) => section(view, entry))}
86    </Box>
87  );
88}
89
90/**
91 * One station as a section that opens and closes like a disclosure: a header
92 * that toggles it, with a one-line summary beside it so a closed section
93 * still says something, and the station's body below while it is open.
94 */
95function section(view: SidebarView, entry: (typeof STATIONS)[number]) {
96  const { Box, Text, Button } = view.ui;
97  const isOpen = view.openSections.includes(entry.name);
98  const summary = summaryOf(entry.name, view);
99  // The body draws inside the frame, so it is told the width it really has.
100  const body = { ...view, columns: Math.max(10, view.columns - SECTION_FRAME_COLUMNS) };
101
102  return (
103    <Box flexDirection="column" borderStyle="round" borderColor="inactive" paddingX={SECTION_PADDING} marginTop={1}>
104      <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
105        <Button key={`section-${entry.name}`} plain hotkey={entry.hotkey} onPress={() => view.onToggle(entry.name)}>
106          {`${isOpen ? "▾" : "▸"} ${entry.label}`}
107        </Button>
108        {summary ? (
109          <Text dimColor wrap="truncate-end">
110            {summary}
111          </Text>
112        ) : null}
113      </Box>
114      {isOpen ? station(entry.name, body) : null}
115    </Box>
116  );
117}
118
119/** The line beside a section's header: the one figure worth seeing while the section is closed. */
120function summaryOf(name: ChefStationName, { ledger, live, now, context, agents }: SidebarView): string | undefined {
121  switch (name) {
122    case "usage": {
123      const spent = `${money(today(ledger, now).usd)} today`;
124      const tightest = [...(live?.rateLimits ?? [])].sort((a, b) => b.percentUsed - a.percentUsed)[0];
125      return tightest ? `${spent} · ${RATE_LIMIT_LABELS[tightest.kind] ?? tightest.kind} ${Math.round(tightest.percentUsed)}%` : spent;
126    }
127    case "trend":
128      return `${money(hourly(ledger, now)[new Date(now).getHours()] ?? 0)} this hour`;
129    case "breakdown": {
130      const top = ranked(today(ledger, now).models, 1)[0];
131      return top ? `${top.name} ${money(top.usd)}` : undefined;
132    }
133    case "activity": {
134      const { streak, activeDays } = activity(ledger, now);
135      return streak > 0 ? `${streak}-day streak` : `${activeDays} active days`;
136    }
137    case "context": {
138      const percent = context && context.maxTokens > 0 ? (context.totalTokens / context.maxTokens) * 100 : live?.contextPercent;
139      return percent === undefined ? undefined : `${Math.round(percent)}% used`;
140    }
141    case "agents": {
142      if (!agents || agents.refreshedAt === 0) {
143        return undefined;
144      }
145
146      const { active } = partitionAgents(agents.agents, now);
147      const waiting = agents.agents.filter((agent) => agent.status === "waiting").length;
148      return `${waiting > 0 ? `${waiting} waiting · ` : ""}${active.length} active of ${agents.agents.length}`;
149    }
150  }
151}
152
153/** The body of one station's section. */
154function station(name: ChefStationName, view: SidebarView) {
155  switch (name) {
156    case "trend":
157      return trend(view);
158    case "breakdown":
159      return breakdown(view);
160    case "activity":
161      return activityGrid(view);
162    case "context":
163      return contextWindow(view);
164    case "agents":
165      return agentsList(view);
166    default:
167      return usage(view);
168  }
169}
170
171function row(ui: Ui, label: string, ...children: RenderChildren[]) {
172  const { Box, Text } = ui;
173
174  return (
175    <Box flexDirection="row">
176      <Box width={LABEL_WIDTH} flexShrink={0}>
177        <Text dimColor>{label}</Text>
178      </Box>
179      <Box flexDirection="row" flexShrink={1}>
180        {children}
181      </Box>
182    </Box>
183  );
184}
185
186/**
187 * The Usage station: the plan's rate-limit windows, today's spend, and the
188 * Now row for this session, its prompt cache countdown included.
189 */
190function usage({ ui, ledger, live, now, isWorking, columns, cache }: SidebarView) {
191  const { Box, Text } = ui;
192  const day = today(ledger, now);
193  const cachePercent = day.inputTokens > 0 ? Math.round((day.cacheReadTokens / day.inputTokens) * 100) : 0;
194  const meterWidth = Math.min(Math.max(columns - LABEL_WIDTH - 20, 10), 40);
195
196  const limits = (live?.rateLimits ?? []).map((limit) => {
197    const meter = bar(limit.percentUsed, meterWidth);
198    const color = limit.percentUsed >= 90 ? "error" : limit.percentUsed >= 75 ? "warning" : ACCENT;
199    const resetsIn = limit.resetsAt ? Date.parse(limit.resetsAt) - now : undefined;
200
201    return row(
202      ui,
203      RATE_LIMIT_LABELS[limit.kind] ?? limit.kind,
204      <Text color={color}>{meter.filled}</Text>,
205      <Text color={MUTED}>{meter.empty}</Text>,
206      <Text bold>{` ${Math.round(limit.percentUsed)}%`.padStart(5)}</Text>,
207      resetsIn === undefined || Number.isNaN(resetsIn) ? null : <Text dimColor>{`  ↻ ${countdown(resetsIn)}`}</Text>,
208    );
209  });
210
211  const todayRow = row(
212    ui,
213    "Today",
214    <Text bold>{money(day.usd)}</Text>,
215    <Text dimColor>{` API value · ${short(day.tokens)} tokens · ${cachePercent}% from cache`}</Text>,
216  );
217
218  const cacheText = cacheLabel(cacheStatus(cache ?? {}, now));
219  const separator = cacheText ? " · " : "";
220
221  // The running turn's stopwatch, or how long the last turn took once it is done.
222  const turnTime =
223    live?.turnStartedAt !== undefined ? (
224      <Text color={ACCENT} bold>{`${separator}${elapsed(now - live.turnStartedAt)}`}</Text>
225    ) : live?.lastTurnMs !== undefined ? (
226      <Text dimColor wrap="truncate-end">{`${separator}last turn ${elapsed(live.lastTurnMs)}`}</Text>
227    ) : null;
228
229  // Two lines, the session's figures and then its cache and turn timing, so neither
230  // squeezes the other out of a narrow sidebar.
231  const nowRow = live ? (
232    <Box flexDirection="column">
233      {row(
234        ui,
235        "Now",
236        <Text color={isWorking ? ACCENT : MUTED}>● </Text>,
237        <Text bold wrap="truncate-end">
238          {live.project}
239        </Text>,
240        <Text dimColor wrap="truncate-end">
241          {[
242            ` · ${live.model}`,
243            ` · ${short(live.outputTokens)} written`,
244            ` · ${money(live.usd)}`,
245            live.contextPercent === undefined ? "" : ` · context ${Math.round(live.contextPercent)}%`,
246          ].join("")}
247        </Text>,
248      )}
249      {cacheText || turnTime
250        ? row(
251            ui,
252            "",
253            cacheText ? (
254              <Text dimColor wrap="truncate-end">
255                {cacheText}
256              </Text>
257            ) : null,
258            turnTime,
259          )
260        : null}
261    </Box>
262  ) : null;
263
264  return (
265    <Box flexDirection="column" marginTop={1}>
266      {limits}
267      {todayRow}
268      {nowRow}
269    </Box>
270  );
271}
272
273function trend({ ui, ledger, now, columns }: SidebarView) {
274  const { Box, Text } = ui;
275  const hours = hourly(ledger, now);
276  const total = hours.reduce((sum, usd) => sum + usd, 0);
277  // Two cells and a gap per hour when there is room, then one and a gap, then one.
278  const barWidth = columns >= 75 ? 2 : 1;
279  const gap = columns >= 50 ? 1 : 0;
280  const rows = verticalBars(hours, 4);
281  const currentHour = new Date(now).getHours();
282  const step = barWidth + gap;
283
284  const barRows = rows.map((line, rowIndex) => {
285    const isBaseline = rowIndex === rows.length - 1;
286
287    return (
288      <Box flexDirection="row">
289        {[...line].map((glyph, hour) => {
290          const isEmptyBaseline = isBaseline && glyph === " " && hour <= currentHour;
291          const cell = (isEmptyBaseline ? "▁" : glyph).repeat(barWidth) + " ".repeat(gap);
292
293          return <Text color={isEmptyBaseline ? MUTED : ACCENT}>{cell}</Text>;
294        })}
295      </Box>
296    );
297  });
298
299  const axisWidth = 24 * step;
300  const axis = "00".padEnd(12 * step) + "12".padEnd(axisWidth - 12 * step - 2) + "23";
301
302  return (
303    <Box flexDirection="column" marginTop={1}>
304      <Box flexDirection="row" width={axisWidth} justifyContent="space-between">
305        <Text bold>Spend by hour</Text>
306        <Text dimColor>{`Today · ${money(total)}`}</Text>
307      </Box>
308      {barRows}
309      <Text dimColor>{axis}</Text>
310    </Box>
311  );
312}
313
314function breakdown({ ui, ledger, now, columns }: SidebarView) {
315  const { Box, Text } = ui;
316  const day = today(ledger, now);
317  const isSideBySide = columns >= 90;
318  const listWidth = isSideBySide ? Math.floor((columns - 2) / 2) : columns;
319
320  const list = (title: string, record: Record<string, number>) => {
321    const entries = ranked(record, 5);
322    const top = entries[0]?.usd ?? 0;
323    const meterWidth = Math.min(16, Math.max(6, listWidth - 34));
324
325    return (
326      <Box flexDirection="column" width={listWidth}>
327        <Text bold>{title}</Text>
328        {entries.length === 0 ? <Text dimColor>Nothing cooked yet today</Text> : null}
329        {entries.map((entry) => {
330          const meter = bar(top > 0 ? (entry.usd / top) * 100 : 0, meterWidth);
331
332          return (
333            <Box flexDirection="row" columnGap={1}>
334              <Box width={20} flexShrink={1}>
335                <Text wrap="truncate-middle">{entry.name}</Text>
336              </Box>
337              <Text color={ACCENT}>{meter.filled}</Text>
338              <Text>{meter.empty.replaceAll("░", " ")}</Text>
339              <Text dimColor>{money(entry.usd).padStart(8)}</Text>
340            </Box>
341          );
342        })}
343      </Box>
344    );
345  };
346
347  return (
348    <Box flexDirection={isSideBySide ? "row" : "column"} columnGap={2} rowGap={1} marginTop={1}>
349      {list("Models", day.models)}
350      {list("Projects", day.projects)}
351    </Box>
352  );
353}
354
355const SHADES = ["░░", "▒▒", "▓▓", "██"];
356const WEEKDAYS = ["Mon", "", "Wed", "", "Fri", "", "Sun"];
357
358function activityGrid({ ui, ledger, now, columns, backfillStatus }: SidebarView) {
359  const { Box, Text } = ui;
360  const grid = activity(ledger, now);
361  const top = Math.max(...grid.weeks.flat().map((tokens) => tokens ?? 0), 0);
362
363  const cell = (tokens: number | null) => {
364    if (tokens === null) {
365      return <Text>{"  "}</Text>;
366    }
367
368    if (tokens === 0 || top === 0) {
369      return <Text color={MUTED}>{"· "}</Text>;
370    }
371
372    const level = Math.min(SHADES.length - 1, Math.ceil((tokens / top) * SHADES.length) - 1);
373    return <Text color={ACCENT}>{SHADES[level]}</Text>;
374  };
375
376  const rows = WEEKDAYS.map((weekday, dayIndex) => (
377    <Box flexDirection="row">
378      <Box width={4}>
379        <Text dimColor>{weekday}</Text>
380      </Box>
381      {grid.weeks.map((week) => cell(week[dayIndex] ?? null))}
382    </Box>
383  ));
384
385  const busiest = grid.busiest
386    ? `${new Date(`${grid.busiest.key}T12:00:00`).toLocaleDateString("en-US", { day: "2-digit", month: "short" })} · ${short(grid.busiest.tokens)}`
387    : "—";
388
389  const stats = (
390    <Box flexDirection="column" marginLeft={columns >= 60 ? 3 : 0}>
391      <Text bold>{`${short(grid.totalTokens)} tokens`}</Text>
392      <Text dimColor>{`${grid.weeks.length} weeks`}</Text>
393      <Text> </Text>
394      <Text>
395        <Text dimColor>Active days </Text>
396        {String(grid.activeDays)}
397      </Text>
398      <Text>
399        <Text dimColor>Busiest day </Text>
400        {busiest}
401      </Text>
402      <Text>
403        <Text dimColor>Streak </Text>
404        <Text color={ACCENT}>{`${grid.streak} ${grid.streak === 1 ? "day" : "days"}`}</Text>
405        {today(ledger, now).tokens > 0 ? "" : " (cook today to keep it)"}
406      </Text>
407    </Box>
408  );
409
410  const history = backfillStatus?.isRunning
411    ? "Reading your Claude Code history…"
412    : ledger.backfill
413      ? `History from ${ledger.backfill.files} transcripts, estimated at list prices. /chef backfill rescans it.`
414      : "Only turns since Chef Station was installed. /chef backfill reads your earlier history.";
415
416  return (
417    <Box flexDirection="column" marginTop={1}>
418      <Box flexDirection={columns >= 60 ? "row" : "column"}>
419        <Box flexDirection="column">{rows}</Box>
420        {stats}
421      </Box>
422      <Text dimColor wrap="wrap">
423        {history}
424      </Text>
425    </Box>
426  );
427}
428
429/** Each legend entry's width, so entries line up in columns as they wrap. */
430const LEGEND_ENTRY_WIDTH = 36;
431
432/**
433 * The Context station: the window as one bar of categories, a legend that
434 * names each color with its tokens and share, and the Compact and Clear buttons.
435 */
436function contextWindow({ ui, context, columns, isWorking, contextAction, onContextAction }: SidebarView) {
437  const { Box, Text } = ui;
438
439  if (!context) {
440    return (
441      <Box marginTop={1}>
442        <Text dimColor>Measuring the context window…</Text>
443      </Box>
444    );
445  }
446
447  const segments = contextSegments(context.categories);
448  // A one-cell gap separates segments, so a boundary shows without relying on color.
449  const gaps = Math.max(0, segments.length - 1);
450  const cells = allocateCells(
451    segments.map((segment) => segment.tokens),
452    Math.max(10, columns - 2 - gaps),
453  );
454  const share = (tokens: number) => {
455    const percent = (tokens / context.maxTokens) * 100;
456    return percent > 0 && percent < 1 ? "<1%" : `${Math.round(percent)}%`;
457  };
458
459  return (
460    <Box flexDirection="column" marginTop={1}>
461      <Box flexDirection="row" columnGap={1}>
462        <Text bold>Context window</Text>
463        <Text dimColor>{`${short(context.totalTokens)} of ${short(context.maxTokens)} tokens (${share(context.totalTokens)})`}</Text>
464      </Box>
465      <Box flexDirection="row">
466        {segments.map((segment, index) => (
467          <Text color={segment.color}>{(index > 0 ? " " : "") + segment.glyph.repeat(cells[index] ?? 0)}</Text>
468        ))}
469      </Box>
470      {/* Identity is never color alone: every color in the bar is named here, in the text color. */}
471      <Box flexDirection="row" flexWrap="wrap" marginTop={1}>
472        {segments.map((segment) => (
473          <Box flexDirection="row" width={LEGEND_ENTRY_WIDTH} columnGap={1}>
474            <Text color={segment.color}>{segment.glyph.repeat(2)}</Text>
475            <Box width={20} flexShrink={1}>
476              <Text wrap="truncate-end">{segment.name}</Text>
477            </Box>
478            <Text dimColor>{`${short(segment.tokens)} · ${share(segment.tokens)}`}</Text>
479          </Box>
480        ))}
481      </Box>
482      {contextActions(ui, isWorking, contextAction, onContextAction)}
483    </Box>
484  );
485}
486
487/**
488 * Compact and Clear. Neither can run during a turn (compacting is refused,
489 * and a /clear would wait for the turn to end), so while Claude works the
490 * buttons give way to a note. Clear ends the conversation, so it asks first.
491 */
492function contextActions(
493  ui: Ui,
494  isWorking: boolean,
495  action: ChefStationContextAction | undefined,
496  onAction: SidebarView["onContextAction"],
497) {
498  const { Box, Text, Button } = ui;
499  const message = action?.message ? <Text dimColor>{action.message}</Text> : null;
500
501  if (action?.isRunning) {
502    return (
503      <Box marginTop={1}>
504        <Text dimColor>Working on it…</Text>
505      </Box>
506    );
507  }
508
509  if (isWorking) {
510    return (
511      <Box flexDirection="column" marginTop={1}>
512        <Text dimColor>Clear and Compact are available once Claude finishes.</Text>
513        {message}
514      </Box>
515    );
516  }
517
518  if (action?.isConfirmingClear) {
519    return (
520      <Box flexDirection="column" marginTop={1}>
521        <Text>Clear the conversation? It ends here and a new one starts with an empty context.</Text>
522        <Box flexDirection="row" columnGap={1}>
523          <Button key="context-clear-confirm" label="Clear conversation" hotkey="y" variant="primary" onPress={() => onAction?.("confirm-clear")} />
524          <Button key="context-clear-cancel" label="Cancel" hotkey="n" onPress={() => onAction?.("cancel-clear")} />
525        </Box>
526      </Box>
527    );
528  }
529
530  return (
531    <Box flexDirection="column" marginTop={1}>
532      <Box flexDirection="row" columnGap={1}>
533        <Button key="context-compact" label="Compact" hotkey="c" onPress={() => onAction?.("compact")} />
534        <Button key="context-clear" label="Clear" hotkey="x" onPress={() => onAction?.("clear")} />
535      </Box>
536      {message}
537    </Box>
538  );
539}
540
541/**
542 * The Agents station: every live Claude Code session on this machine, busy
543 * ones first, with what each is doing and what it was last asked.
544 */
545function agentsList({ ui, agents, now, isIdleOpen, onToggleIdle }: SidebarView) {
546  const { Box, Text, Button } = ui;
547
548  if (!agents || (agents.refreshedAt === 0 && !agents.error)) {
549    return (
550      <Box marginTop={1}>
551        <Text dimColor>Looking for sessions…</Text>
552      </Box>
553    );
554  }
555
556  const { active, idle } = partitionAgents(agents.agents, now);
557
558  return (
559    <Box flexDirection="column" marginTop={1} gap={1}>
560      {/* Before the first refresh that worked there is no list to describe, only the error. */}
561      {agents.refreshedAt === 0 ? null : <Text dimColor>{`Updated ${ago(now - agents.refreshedAt)}`}</Text>}
562      {agents.error ? <Text color="error">{`Could not refresh: ${agents.error}`}</Text> : null}
563      {agents.refreshedAt !== 0 && active.length === 0 ? <Text dimColor>No session is busy or has been active in the last 15 minutes.</Text> : null}
564      {active.map((agent) => agentCard(ui, agent, now))}
565      {idle.length > 0 ? (
566        <Box flexDirection="column">
567          <Button key="agents-idle" plain onPress={onToggleIdle}>
568            {`${isIdleOpen ? "▾" : "▸"} ${idle.length} idle ${idle.length === 1 ? "session" : "sessions"}`}
569          </Button>
570          {isIdleOpen ? idle.map((agent) => idleRow(ui, agent, now)) : null}
571        </Box>
572      ) : null}
573    </Box>
574  );
575}
576
577const STATUS_LABELS: Record<ChefStationAgent["status"], string> = {
578  waiting: "Waiting",
579  busy: "Busy",
580  idle: "Idle",
581  unknown: "Status unknown",
582};
583
584const STATUS_COLORS: Record<ChefStationAgent["status"], string> = {
585  waiting: "warning",
586  busy: ACCENT,
587  idle: "text",
588  unknown: "text",
589};
590
591/** An active session in full: name, where it runs, what it is doing and what it was last asked. */
592function agentCard(ui: Ui, agent: ChefStationAgent, now: number) {
593  const { Box, Text } = ui;
594  const isBusy = agent.status === "busy";
595  const isUnderway = isBusy || agent.status === "waiting";
596  const activity = agent.lastActivityAt === undefined ? "" : ` · ${ago(now - agent.lastActivityAt)}`;
597
598  return (
599    <Box key={agent.sessionId} flexDirection="column">
600      <Text bold color={STATUS_COLORS[agent.status]} wrap="truncate-end">
601        {`${isUnderway ? "●" : "○"} ${agent.name}`}
602      </Text>
603      <Text dimColor wrap="truncate-end">
604        {`${STATUS_LABELS[agent.status]} · ${SURFACE_LABELS[agent.surface]} · ${agent.project} · pid ${agent.pid}`}
605      </Text>
606      {agent.title ? <Text wrap="truncate-end">{`Topic: ${agent.title}`}</Text> : null}
607      {agent.lastAction ? (
608        <Text wrap="truncate-end">{`${isBusy ? "Now" : "Last step"}: ${agent.lastAction.text}${activity}`}</Text>
609      ) : null}
610      {agent.lastPrompt ? (
611        <Text dimColor wrap="truncate-end">
612          {`Last asked: “${agent.lastPrompt}”`}
613        </Text>
614      ) : null}
615    </Box>
616  );
617}
618
619/**
620 * An idle session on one line, so a long list of them stays short. A session
621 * whose status could not be read folds here too, and its line says so.
622 */
623function idleRow(ui: Ui, agent: ChefStationAgent, now: number) {
624  const { Text } = ui;
625  const activity = agent.lastActivityAt === undefined ? "" : ` · ${ago(now - agent.lastActivityAt)}`;
626  const status = agent.status === "unknown" ? " · status unknown" : "";
627
628  return (
629    <Text key={agent.sessionId} dimColor wrap="truncate-end">
630      {`○ ${agent.name} · ${SURFACE_LABELS[agent.surface]} · ${agent.project}${activity}${status}`}
631    </Text>
632  );
633}
634
hooks/transcript.mjs 222 lines
1// Reads Claude Code's session transcripts (~/.claude/projects/**/*.jsonl) and
2// tallies what each day cost. Plain JavaScript so the mod and the Node helper
3// in scripts/backfill.mjs share one implementation.
4
5/**
6 * @typedef {{ input: number, output: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number }} EntryUsage
7 * @typedef {{ id: string, at: number, sessionId: string, project: string, model: string, isFast: boolean, usage: EntryUsage }} Entry
8 * @typedef {{ usd: number, tokens: number, cacheReadTokens: number, inputTokens: number, hours: number[], models: Record<string, number>, projects: Record<string, number> }} Day
9 * @typedef {{ days: Record<string, Day>, unpricedModels: string[], responses: number }} TallyResult
10 */
11
12/**
13 * US dollars per million tokens, first-party API list prices. Cache writes
14 * cost 1.25x input for the five-minute TTL and 2x input for the one-hour TTL.
15 * The first pattern that matches a model id wins, so specific ids come first.
16 */
17const PRICES = [
18  { pattern: /^claude-(fable|mythos)-5-1/, input: 10, output: 50, cacheRead: 0.25 },
19  { pattern: /^claude-(fable|mythos)-5/, input: 10, output: 50, cacheRead: 1 },
20  { pattern: /^claude-opus-5-5/, input: 4, output: 20, cacheRead: 0.2 },
21  { pattern: /^claude-opus-(5|4-8|4-7|4-6|4-5)/, input: 5, output: 25, cacheRead: 0.5 },
22  { pattern: /^claude-opus-4|^claude-3-opus/, input: 15, output: 75, cacheRead: 1.5 },
23  { pattern: /^claude-sonnet-5/, input: 2, output: 10, cacheRead: 0.2 },
24  { pattern: /^claude-sonnet-4|^claude-3-[57]-sonnet/, input: 3, output: 15, cacheRead: 0.3 },
25  { pattern: /^claude-haiku-4-5/, input: 1, output: 5, cacheRead: 0.1 },
26  { pattern: /^claude-3-5-haiku/, input: 0.8, output: 4, cacheRead: 0.08 },
27];
28
29/** Fast mode runs the same model at twice the price. */
30const FAST_MULTIPLIER = 2;
31
32/**
33 * One transcript line as a priced response, or undefined for every other line.
34 * Claude Code writes a response once per content block, so the same `id` can
35 * appear on several lines; the tally counts it once.
36 *
37 * @param {string} line
38 * @returns {Entry | undefined}
39 */
40export function readLine(line) {
41  // Most lines are prompts, tool results and content; skip them before parsing.
42  if (!line.includes('"usage"') || !line.includes('"assistant"')) {
43    return undefined;
44  }
45
46  let record;
47
48  try {
49    record = JSON.parse(line);
50  } catch {
51    return undefined;
52  }
53
54  const message = record?.message;
55  const usage = message?.usage;
56
57  if (record.type !== "assistant" || !usage || typeof message.model !== "string" || message.model === "<synthetic>") {
58    return undefined;
59  }
60
61  const at = Date.parse(record.timestamp);
62
63  if (Number.isNaN(at)) {
64    return undefined;
65  }
66
67  const cacheWrite = usage.cache_creation_input_tokens ?? 0;
68  const byTtl = usage.cache_creation;
69  const cacheWrite1h = byTtl?.ephemeral_1h_input_tokens ?? 0;
70  const cacheWrite5m = byTtl ? (byTtl.ephemeral_5m_input_tokens ?? 0) : cacheWrite;
71
72  return {
73    id: `${message.id}:${record.requestId}`,
74    at,
75    sessionId: String(record.sessionId ?? ""),
76    project: basename(String(record.cwd ?? "")) || "unknown",
77    model: message.model,
78    isFast: usage.speed === "fast",
79    usage: {
80      input: usage.input_tokens ?? 0,
81      output: usage.output_tokens ?? 0,
82      cacheRead: usage.cache_read_input_tokens ?? 0,
83      cacheWrite5m,
84      cacheWrite1h,
85    },
86  };
87}
88
89/**
90 * What a response cost in US dollars, or undefined when the model has no known price.
91 *
92 * @param {Entry} entry
93 * @returns {number | undefined}
94 */
95export function costOf(entry) {
96  const price = PRICES.find((candidate) => candidate.pattern.test(entry.model));
97
98  if (!price) {
99    return undefined;
100  }
101
102  const { input, output, cacheRead, cacheWrite5m, cacheWrite1h } = entry.usage;
103  const perMillion =
104    input * price.input +
105    output * price.output +
106    cacheRead * price.cacheRead +
107    cacheWrite5m * price.input * 1.25 +
108    cacheWrite1h * price.input * 2;
109
110  return (perMillion / 1_000_000) * (entry.isFast ? FAST_MULTIPLIER : 1);
111}
112
113/**
114 * Adds responses up by local calendar day, hour, model id and project.
115 *
116 * @param {{ since: number, excludeSessions?: Iterable<string> }} options
117 *   `since`: responses before this moment are left out; `excludeSessions`:
118 *   sessions the sidebar already recorded live, so they are not counted twice
119 */
120export function createTally({ since, excludeSessions = [] }) {
121  const excluded = new Set(excludeSessions);
122  const seen = new Set();
123  const unpriced = new Set();
124  /** @type {Record<string, Day>} */
125  const days = {};
126  let responses = 0;
127
128  return {
129    /** @param {Entry | undefined} entry */
130    add(entry) {
131      if (!entry || entry.at < since || excluded.has(entry.sessionId) || seen.has(entry.id)) {
132        return;
133      }
134
135      seen.add(entry.id);
136      responses += 1;
137
138      const usd = costOf(entry);
139
140      if (usd === undefined) {
141        unpriced.add(entry.model);
142      }
143
144      const cost = usd ?? 0;
145      const { input, output, cacheRead, cacheWrite5m, cacheWrite1h } = entry.usage;
146      const inputTokens = input + cacheRead + cacheWrite5m + cacheWrite1h;
147      const key = dayKey(entry.at);
148      const day = (days[key] ??= emptyDay());
149
150      day.usd += cost;
151      day.tokens += inputTokens + output;
152      day.cacheReadTokens += cacheRead;
153      day.inputTokens += inputTokens;
154      const hour = new Date(entry.at).getHours();
155      day.hours[hour] = (day.hours[hour] ?? 0) + cost;
156      day.models[entry.model] = (day.models[entry.model] ?? 0) + cost;
157      day.projects[entry.project] = (day.projects[entry.project] ?? 0) + cost;
158    },
159
160    /** @returns {TallyResult} */
161    result() {
162      return { days, unpricedModels: [...unpriced].sort(), responses };
163    },
164  };
165}
166
167/**
168 * Adds one transcript's responses to a tally, but only once the whole file
169 * has been read: a file that fails partway adds nothing, rather than part of
170 * its usage.
171 *
172 * @param {AsyncIterable<string> | Iterable<string>} lines
173 * @param {{ add: (entry: Entry | undefined) => void }} tally
174 * @returns {Promise<boolean>} whether the file was read to its end
175 */
176export async function addTranscript(lines, tally) {
177  /** @type {Entry[]} */
178  const staged = [];
179
180  try {
181    for await (const line of lines) {
182      const entry = readLine(line);
183
184      if (entry) {
185        staged.push(entry);
186      }
187    }
188  } catch {
189    return false;
190  }
191
192  for (const entry of staged) {
193    tally.add(entry);
194  }
195
196  return true;
197}
198
199/** @returns {Day} */
200function emptyDay() {
201  return { usd: 0, tokens: 0, cacheReadTokens: 0, inputTokens: 0, hours: new Array(24).fill(0), models: {}, projects: {} };
202}
203
204/**
205 * The local calendar date of a moment, as `YYYY-MM-DD`.
206 *
207 * @param {number} ms
208 */
209export function dayKey(ms) {
210  const date = new Date(ms);
211  const month = String(date.getMonth() + 1).padStart(2, "0");
212  const day = String(date.getDate()).padStart(2, "0");
213
214  return `${date.getFullYear()}-${month}-${day}`;
215}
216
217/** @param {string} path */
218function basename(path) {
219  const parts = path.split(/[\\/]/).filter(Boolean);
220  return parts[parts.length - 1] ?? "";
221}
222
hooks/context.ts 116 lines
1import type { ChefStationContextCategory } from "../types";
2
3/**
4 * Eight categorical colors, one per slot, in a fixed order. They are the
5 * dark-surface steps of the data-visualization reference palette, which pass
6 * every check on a light surface (#fcfcfb) and a dark surface (#1a1a19) alike:
7 * the lightness band, the chroma floor, protanopia and deuteranopia separation
8 * between neighbors (worst 8.4 against a target of 8), the normal-vision floor
9 * (worst 19.3 against 15) and contrast. The yellow sits at 2.99:1 on the light
10 * surface, which is why the legend always names each category beside its color.
11 *
12 * Only neighboring slots are validated as a pair: with all eight in play, some
13 * slots that are not neighbors (aqua and magenta under deuteranopia, red and
14 * orange for everyone) cannot be told apart. So the bar hands the slots out
15 * in its own order, and two segments that touch are always neighboring slots.
16 * The order is part of what makes neighbors distinguishable; never reorder it.
17 */
18export const CONTEXT_PALETTE = ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767"];
19
20/** A neutral gray for the categories folded into "Other": not a hue, so it claims no identity. */
21const OTHER_COLOR = "#8a8986";
22
23export type ContextSegment = {
24  name: string;
25  tokens: number;
26  kind: "used" | "free" | "buffer";
27  /** A palette color for a category, or a theme key for free space and the buffer. */
28  color: string;
29  /** The character the segment is drawn with, so free space and the buffer differ by texture as well. */
30  glyph: string;
31};
32
33/**
34 * The breakdown as the bar draws it, left to right: what fills the window, in
35 * the order /context lists it, then the free space, then the compaction
36 * buffer. Schemas loaded on demand sit outside the window and are left out.
37 * Each filled category takes the next palette slot in bar order; past the
38 * eighth, the rest fold into "Other" rather than reuse a color.
39 */
40export function contextSegments(categories: readonly ChefStationContextCategory[]): ContextSegment[] {
41  const used = categories.filter((category) => category.kind === "used" && category.tokens > 0);
42  const segments: ContextSegment[] = [];
43  let otherTokens = 0;
44
45  for (const [slot, category] of used.entries()) {
46    const color = CONTEXT_PALETTE[slot];
47
48    if (color === undefined) {
49      otherTokens += category.tokens;
50      continue;
51    }
52
53    segments.push({ name: category.name, tokens: category.tokens, kind: "used", color, glyph: "█" });
54  }
55
56  if (otherTokens > 0) {
57    segments.push({ name: "Other", tokens: otherTokens, kind: "used", color: OTHER_COLOR, glyph: "█" });
58  }
59
60  for (const category of categories) {
61    if (category.kind === "free" && category.tokens > 0) {
62      segments.push({ name: category.name, tokens: category.tokens, kind: "free", color: "subtle", glyph: "░" });
63    }
64  }
65
66  for (const category of categories) {
67    if (category.kind === "buffer" && category.tokens > 0) {
68      segments.push({ name: category.name, tokens: category.tokens, kind: "buffer", color: "subtle", glyph: "▒" });
69    }
70  }
71
72  return segments;
73}
74
75/**
76 * Shares `width` cells among `values` in proportion, adding up to exactly
77 * `width`. Any value above zero gets at least one cell, so every category the
78 * legend names is visible in the bar; those cells come from the largest share.
79 */
80export function allocateCells(values: readonly number[], width: number): number[] {
81  const total = values.reduce((sum, value) => sum + value, 0);
82
83  if (total <= 0 || width <= 0) {
84    return values.map(() => 0);
85  }
86
87  const exact = values.map((value) => (value / total) * width);
88  const cells = exact.map((share, index) => (values[index]! > 0 ? Math.max(1, Math.floor(share)) : 0));
89  let assigned = cells.reduce((sum, count) => sum + count, 0);
90
91  // Hand the cells rounding left over to the largest fractional parts, earliest first on a tie.
92  const byRemainder = exact
93    .map((share, index) => ({ index, remainder: share - Math.floor(share) }))
94    .filter(({ index }) => values[index]! > 0)
95    .sort((a, b) => b.remainder - a.remainder || a.index - b.index);
96
97  for (let next = 0; assigned < width && byRemainder.length > 0; next = (next + 1) % byRemainder.length) {
98    cells[byRemainder[next]!.index]! += 1;
99    assigned += 1;
100  }
101
102  // The one-cell minimums can overshoot; take the excess from the largest share.
103  while (assigned > width) {
104    const largest = cells.indexOf(Math.max(...cells));
105
106    if (cells[largest]! <= 1) {
107      break;
108    }
109
110    cells[largest]! -= 1;
111    assigned -= 1;
112  }
113
114  return cells;
115}
116
types/index.d.ts 188 lines
1/**
2 * The six stations of the sidebar, each a section that opens and closes.
3 */
4export type ChefStationName = "usage" | "trend" | "breakdown" | "activity" | "context" | "agents";
5
6/** One row of the context window's breakdown, as /context lists it. */
7export type ChefStationContextCategory = {
8  name: string;
9  tokens: number;
10  /** `used` fills the window, `free` is what is left, `buffer` the compaction reserve, `deferred` schemas outside the window. */
11  kind: "used" | "free" | "buffer" | "deferred";
12};
13
14export type ChefStationContextAction = {
15  isRunning: boolean;
16  isConfirmingClear: boolean;
17  message?: string;
18};
19
20/** The context window broken down by category, as the last measurement found it. */
21export type ChefStationContext = {
22  categories: ChefStationContextCategory[];
23  /** Tokens in use. */
24  totalTokens: number;
25  /** The window measured against: the model's limit, or a smaller compaction window. */
26  maxTokens: number;
27};
28
29/**
30 * What one calendar day (local time) has cost, across every session.
31 */
32export type ChefStationDay = {
33  /** US dollars, as `/cost` totals them. */
34  usd: number;
35  /** Every token the day's turns counted: input, output and both cache kinds. */
36  tokens: number;
37  /** Input tokens served from the prompt cache. */
38  cacheReadTokens: number;
39  /** Every input token: uncached, cache reads and cache writes. */
40  inputTokens: number;
41  /** US dollars per hour of the day, index 0 being midnight to 1am. */
42  hours: number[];
43  /** US dollars per model display name. */
44  models: Record<string, number>;
45  /** US dollars per project (the folder the session runs in). */
46  projects: Record<string, number>;
47};
48
49/**
50 * Every day the sidebar remembers, keyed `YYYY-MM-DD`; kept in `$.store` so it
51 * outlives the session, and pruned to the last thirteen weeks.
52 */
53export type ChefStationLedger = {
54  version: 1;
55  /** What the sidebar recorded live, turn by turn. */
56  days: Record<string, ChefStationDay>;
57  /** Sessions the sidebar recorded live, with the last day it saw each, so a backfill skips them. */
58  liveSessions?: Record<string, string>;
59  /** What the last scan of Claude Code's transcripts found, for every other session. */
60  backfill?: ChefStationBackfill;
61};
62
63/**
64 * The days a scan of `~/.claude/projects` tallied. Models are keyed by
65 * display name and costs are estimated from list prices, as the transcripts
66 * hold token counts and no cost.
67 */
68export type ChefStationBackfill = {
69  days: Record<string, ChefStationDay>;
70  /** When the scan finished, in milliseconds since the epoch. */
71  scannedAt: number;
72  /** `node` when the helper script ran, `fs` when the mod read the files itself. */
73  source: "node" | "fs";
74  files: number;
75  /** Transcripts too large for the mod to read itself (only when Node was not found). */
76  skippedFiles: number;
77  /** Transcripts whose read failed; the backfill is incomplete when there are any. Absent before 0.3.1. */
78  unreadableFiles?: number;
79  /** Model ids with no known price; their tokens count but their cost does not. */
80  unpricedModels: string[];
81};
82
83/**
84 * What this session alone is doing right now: the "Now" row.
85 */
86export type ChefStationLive = {
87  project: string;
88  model: string;
89  /** Output tokens this session's turns generated. */
90  outputTokens: number;
91  /** This session's cost so far, in US dollars. */
92  usd: number;
93  /** When the session began, in milliseconds since the epoch. */
94  startedAt: number;
95  /** When the running turn began; absent while the session is idle. */
96  turnStartedAt?: number;
97  /** How long the last completed turn took, in milliseconds. */
98  lastTurnMs?: number;
99  /** The context window's fill, 0 to 100, when a response reported one. */
100  contextPercent?: number;
101  /** The account's rate-limit windows, as the last response reported them. */
102  rateLimits: ChefStationRateLimit[];
103};
104
105export type ChefStationRateLimit = {
106  kind: string;
107  percentUsed: number;
108  resetsAt?: string;
109};
110
111/** How long a prompt-cache entry lives after the request that last read or wrote it. */
112export type ChefStationCacheTtl = "5m" | "1h";
113
114/** What the sidebar knows about the main conversation's prompt cache. */
115export type ChefStationCache = {
116  /** When the main conversation's last model request started, in milliseconds since the epoch. */
117  lastRequestAt?: number;
118  /** The lifetime of the latest cache write, as the transcript records it; unknown until a turn ends. */
119  ttl?: ChefStationCacheTtl;
120};
121
122/** Where a Claude Code session runs: the desktop app, a terminal, or in the background. */
123export type ChefStationAgentSurface = "desktop" | "terminal" | "background";
124
125/** What a session's own registry entry says it is doing; `waiting` sessions wait on the person. */
126export type ChefStationAgentStatus = "busy" | "waiting" | "idle" | "unknown";
127
128/** A session's latest assistant step: a tool call it made, or text it wrote. */
129export type ChefStationAgentAction = { kind: "tool" | "reply"; text: string };
130
131/** One live Claude Code session on this machine, as the Agents station lists it. */
132export type ChefStationAgent = {
133  pid: number;
134  sessionId: string;
135  name: string;
136  /** The conversation's title (one the person set, else Claude's), when it differs from `name`. */
137  title?: string;
138  surface: ChefStationAgentSurface;
139  /** The last folder of the session's working directory. */
140  project: string;
141  status: ChefStationAgentStatus;
142  /** The person's most recent prompt in that session. */
143  lastPrompt?: string;
144  lastAction?: ChefStationAgentAction;
145  /** When the session last wrote a prompt or a response, in milliseconds since the epoch. */
146  lastActivityAt?: number;
147  /** When the session began, in milliseconds since the epoch. */
148  startedAt?: number;
149};
150
151/** Every live session on this machine, as the last look at `~/.claude/sessions` found them. */
152export type ChefStationAgents = {
153  agents: ChefStationAgent[];
154  /** When the list was last refreshed, in milliseconds since the epoch; 0 before the first refresh. */
155  refreshedAt: number;
156  /** Why the last refresh failed; the agents are then the previous refresh's. */
157  error?: string;
158};
159
160declare module "claude-code" {
161  interface PluginState {
162    "chef-station": {
163      /** The stations whose sections are open, mirrored from `$.store` so they last across sessions. */
164      openSections: ChefStationName[];
165      /** Whether the Agents station lists its idle sessions or keeps them folded under one row. */
166      isIdleOpen: boolean;
167      /** The persisted ledger, mirrored here so the sidebar redraws when it moves. */
168      ledger: ChefStationLedger;
169      /** This session's live figures. */
170      live: ChefStationLive | null;
171      /** The time the sidebar last ticked, so countdowns move without a turn. */
172      now: number;
173      /** The session cost already written to the ledger, so no turn counts twice. */
174      recordedUsd: number;
175      /** The main conversation's prompt cache: when it was last used, and how long its entries live. */
176      cache: ChefStationCache;
177      /** The context window by category, refreshed after each turn; null before the first measurement. */
178      context: ChefStationContext | null;
179      /** The Context station's Clear and Compact: whether one is running, whether Clear awaits confirmation, and what the last one said. */
180      contextAction: ChefStationContextAction;
181      /** Whether a scan of the transcripts is running, and what the last one said. */
182      backfillStatus: { isRunning: boolean; message?: string };
183      /** Every live Claude Code session on this machine, refreshed while the Agents station shows. */
184      agents: ChefStationAgents;
185    };
186  }
187}
188