ccnav 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,6 +61,8 @@ ccnav --json print sessions as JSON and exit
61
61
  ccnav --model opus any other arguments are passed to the agent
62
62
  ccnav here new session in the current directory, running unattended
63
63
  ccnav here --codex the same, without being asked which agent
64
+ ccnav refresh update token and cost totals from changed transcripts, then print them
65
+ ccnav cost print the totals from the last refresh
64
66
  ```
65
67
 
66
68
  ## Start one here
@@ -104,7 +106,7 @@ Codex removed `--full-auto` in 0.156, so the sandboxed middle ground is now spel
104
106
  | o | open the directory in Explorer, Finder or the Linux file manager |
105
107
  | c | copy the session id |
106
108
  | / | filter titles, paths, branches and prompts; Tab switches to full-transcript search |
107
- | s | cycle sort: last used, created, size, directory name (sessions stay grouped by directory) |
109
+ | s | cycle sort: last used, created, size, context used, cost, directory name (sessions stay grouped by directory) |
108
110
  | x | archive the selected session |
109
111
  | X | archive every listed session not used in N days |
110
112
  | a | show or hide Claude Desktop scratch sessions |
@@ -126,6 +128,49 @@ Only the first and last 256 KB of each transcript are read when listing, so a 21
126
128
 
127
129
  Archived sessions move to `~/.claude/ccnav-archive/` or `~/.codex/ccnav-archive/`, keeping the folders they had underneath (`<project>/` for Claude, `YYYY/MM/DD/` for Codex). Moving a file back restores it. Sessions used in the last 10 minutes are never archived, because they may still be open. Archiving a Codex session leaves its line in `session_index.jsonl`; that is harmless but not cleaned up.
128
130
 
131
+ ## Context and cost
132
+
133
+ **CONTEXT** shows how full each session's context window was at its last request, for
134
+ example `187k 19%`. It comes from the end of the transcript, which ccnav reads anyway, so it
135
+ costs nothing extra. For Claude that is the request's input plus cache reads and writes, against
136
+ the model's window (1M for current models). For Codex it is the last request's input, against the
137
+ `model_context_window` that Codex records.
138
+
139
+ **COST** is an estimate at API list prices. Working it out means reading every transcript in
140
+ full, so ccnav never does that on its own. Run it when you want fresh numbers:
141
+
142
+ ```
143
+ ccnav refresh read every transcript that changed since the last refresh
144
+ ccnav refresh --all read them all again
145
+ ccnav cost print the last totals without reading any transcripts
146
+ ```
147
+
148
+ `refresh` prints the total, then breakdowns by agent, model and directory. It stores token counts
149
+ per session (not dollars) in `~/.ccnav/usage.json`, or `$CCNAV_HOME/usage.json`. Prices are applied
150
+ when the numbers are shown, so a price change never needs a rescan. The picker and `--list`
151
+ read that file, and a `+` after a cost means the session has changed since the last refresh.
152
+
153
+ - Claude: each message is counted once, though Claude Code writes several records per message.
154
+ Subagent transcripts count towards their session. Cache writes are split into 5-minute and
155
+ 1-hour writes, Haiku 5.5's prices for prompts over 100K tokens and fast mode are applied, and
156
+ web searches are charged at $0.01 each.
157
+ - Codex: each model response is counted once. Subagent rollouts count towards the session that
158
+ spawned them, and prompts over 272K tokens pay the higher rates.
159
+ - Archived or deleted sessions stay in the total and are shown on their own line.
160
+ - Prices date from 2026-10-30 (`PRICES` in `src/usage.mjs`). To add a model or override a
161
+ price, put entries of the same shape in `~/.ccnav/prices.json`:
162
+ `{ "gpt-7": { "input": 3, "output": 12, "cacheRead": 0.3 } }` (USD per million tokens).
163
+ - Not included: subscription billing (Pro, Max, ChatGPT plans charge differently), batch and
164
+ regional pricing, and server-tool fees other than web search. A forked session repeats its
165
+ parent's history, so that history can be counted twice.
166
+
167
+ ## Troubleshooting
168
+
169
+ If a resumed session ignores the keyboard, or drops keys, set `CCNAV_DEBUG=1` before running
170
+ ccnav. Each launch appends two lines to `ccnav-debug.log` in your temp folder (`%TEMP%` on Windows,
171
+ `$TMPDIR` or `/tmp` elsewhere) recording ccnav's stdin state just before the agent starts. The
172
+ `after` line should show `destroyed=true`, meaning ccnav has stopped reading the terminal.
173
+
129
174
  ## Test
130
175
 
131
176
  ```sh
package/bin/ccnav.mjs CHANGED
@@ -4,6 +4,7 @@ import { render } from 'ink';
4
4
  import { App } from '../src/app.mjs';
5
5
  import { AGENTS, PROVIDERS, ago, humanSize, listSessions, providerOf, shortPath } from '../src/sessions.mjs';
6
6
  import { askUser, ensureAgent, installShellFunction, launchAgent, reportCwd } from '../src/actions.mjs';
7
+ import { CACHE_FILE, attachUsage, contextLabel, loadUsageCache, money, refreshUsage, saveUsageCache, summaryLines } from '../src/usage.mjs';
7
8
 
8
9
  const args = process.argv.slice(2);
9
10
 
@@ -20,6 +21,10 @@ usage:
20
21
  ccnav here skip the picker: start a NEW session in the current
21
22
  directory, running unattended with no permission prompts
22
23
  (ccnav here --claude / --codex picks the agent outright)
24
+ ccnav refresh read every changed transcript in full and update token and
25
+ cost totals, then print them (--all rereads everything)
26
+ ccnav cost print the totals from the last refresh without reading
27
+ any transcripts
23
28
  ccnav --install-shell add a shell function (PowerShell, zsh, bash or fish) so
24
29
  your shell is left in the session's directory afterwards
25
30
 
@@ -61,6 +66,37 @@ if (args[0] === 'here') {
61
66
  process.exit(await launchAgent(provider.command, process.cwd(), argv));
62
67
  }
63
68
 
69
+ // Cost is the one thing that needs whole transcripts, so it is only ever read here, on request.
70
+ if (args[0] === 'refresh') {
71
+ const started = Date.now();
72
+ const sessions = listSessions();
73
+ const tty = process.stderr.isTTY;
74
+ const { cache, scanned, reused, failed } = await refreshUsage(sessions, {
75
+ all: args.includes('--all'),
76
+ providers: PROVIDERS,
77
+ onProgress: (i, n) => { if (tty && (i % 5 === 0 || i === n)) process.stderr.write(`\rreading transcripts ${i}/${n}`); },
78
+ });
79
+ if (tty) process.stderr.write('\r\x1b[K');
80
+ saveUsageCache(cache);
81
+ console.log(`Read ${scanned} changed session${scanned === 1 ? '' : 's'}, ${reused} unchanged, `
82
+ + (failed ? `${failed} unreadable (kept their previous totals), ` : '')
83
+ + `in ${((Date.now() - started) / 1000).toFixed(1)}s. Saved to ${CACHE_FILE}\n`);
84
+ console.log(summaryLines(cache, { shortPath }).join('\n'));
85
+ process.exit(0);
86
+ }
87
+
88
+ if (args[0] === 'cost') {
89
+ const cache = loadUsageCache();
90
+ if (!cache.refreshedAt) { console.log('No usage recorded yet. Run: ccnav refresh'); process.exit(0); }
91
+ const sessions = listSessions();
92
+ attachUsage(sessions, cache);
93
+ const changed = sessions.filter(s => s.cost == null || s.costStale).length;
94
+ console.log(`From the refresh ${ago(new Date(cache.refreshedAt))}`
95
+ + (changed ? `; ${changed} session${changed === 1 ? ' has' : 's have'} changed since (ccnav refresh to update)` : '') + '\n');
96
+ console.log(summaryLines(cache, { shortPath }).join('\n'));
97
+ process.exit(0);
98
+ }
99
+
64
100
  if (args.includes('--install-shell')) {
65
101
  const { shell, file, reload } = installShellFunction();
66
102
  console.log(`ccnav ${shell} function written to ${file}\nto use it now: ${reload}`);
@@ -72,6 +108,7 @@ const OWN_FLAGS = new Set(['--list', '--json', '--install-shell', '--claude', '-
72
108
  const passthrough = args.filter(a => !OWN_FLAGS.has(a));
73
109
  const agents = ['claude', 'codex'].filter(a => args.includes(`--${a}`));
74
110
  const sessions = listSessions(agents.length ? { agents } : {});
111
+ const usageCache = attachUsage(sessions);
75
112
 
76
113
  if (args.includes('--json')) {
77
114
  console.log(JSON.stringify(sessions, null, 2));
@@ -81,6 +118,7 @@ if (args.includes('--json')) {
81
118
  if (args.includes('--list')) {
82
119
  for (const s of sessions) {
83
120
  console.log([s.agent.padEnd(6), ago(s.lastUsed).padEnd(9), ago(s.created).padEnd(9), humanSize(s.size).padStart(6),
121
+ contextLabel(s.context).padStart(9), (money(s.cost) + (s.costStale ? '+' : '')).padStart(9),
84
122
  shortPath(s.cwd).padEnd(40), (s.title || s.firstPrompt).replace(/\s+/g, ' ').slice(0, 60)].join(' '));
85
123
  }
86
124
  process.exit(0);
@@ -92,7 +130,7 @@ if (!process.stdin.isTTY) {
92
130
  }
93
131
 
94
132
  let choice = null;
95
- const app = render(React.createElement(App, { sessions, passthrough, onChoose: c => { choice = c; } }));
133
+ const app = render(React.createElement(App, { sessions, passthrough, refreshedAt: usageCache.refreshedAt, onChoose: c => { choice = c; } }));
96
134
  await app.waitUntilExit();
97
135
 
98
136
  if (!choice) process.exit(0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccnav",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "Claude Codex Navigator - pick a Claude Code or Codex session and resume it in its directory",
5
5
  "scripts": {
6
6
  "test": "node --test"
package/src/app.mjs CHANGED
@@ -2,6 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
2
2
  import { Box, Text, useApp, useInput, useStdout } from 'ink';
3
3
  import { AGENTS, ago, humanSize, providerOf } from './sessions.mjs';
4
4
  import { archiveSession, copyToClipboard, hasCommand, isMaybeLive, openFolder, openInNewTab, searchTranscript } from './actions.mjs';
5
+ import { contextLabel, humanTokens, money, tokensOf } from './usage.mjs';
5
6
 
6
7
  const h = React.createElement;
7
8
 
@@ -9,6 +10,8 @@ const SORTS = [
9
10
  { key: 'lastUsed', label: 'last used', fn: (a, b) => b.lastUsed - a.lastUsed },
10
11
  { key: 'created', label: 'created', fn: (a, b) => b.created - a.created },
11
12
  { key: 'size', label: 'size', fn: (a, b) => b.size - a.size },
13
+ { key: 'context', label: 'context used', fn: (a, b) => (b.context?.used ?? -1) - (a.context?.used ?? -1) || b.lastUsed - a.lastUsed },
14
+ { key: 'cost', label: 'cost', fn: (a, b) => (b.cost ?? -1) - (a.cost ?? -1) || b.lastUsed - a.lastUsed },
12
15
  { key: 'project', label: 'directory name', fn: (a, b) => a.cwd.toLowerCase().localeCompare(b.cwd.toLowerCase()) || b.lastUsed - a.lastUsed },
13
16
  ];
14
17
 
@@ -18,10 +21,28 @@ const pad = (s, n) => {
18
21
  };
19
22
  const oneLine = s => String(s || '').replace(/\s+/g, ' ').trim();
20
23
  const keyOf = s => `${s.agent}:${s.id}`;
24
+
25
+ // Model and context window come from the transcript's tail; tokens and cost from the last refresh.
26
+ function usageLine(s) {
27
+ const parts = [];
28
+ if (s.model) parts.push(s.model);
29
+ if (s.context?.used) parts.push(`context ${humanTokens(s.context.used)} of ${humanTokens(s.context.window)}`
30
+ + ` (${Math.round((s.context.used / s.context.window) * 100)}%)`);
31
+ if (s.usage) {
32
+ const t = Object.values(s.usage).reduce((a, x) => ({
33
+ input: a.input + x.input, write: a.write + x.cacheWrite5m + x.cacheWrite1h,
34
+ read: a.read + x.cacheRead, output: a.output + x.output, all: a.all + tokensOf(x),
35
+ }), { input: 0, write: 0, read: 0, output: 0, all: 0 });
36
+ parts.push(`${humanTokens(t.all)} tokens (in ${humanTokens(t.input)} · cache write ${humanTokens(t.write)}`
37
+ + ` · cache read ${humanTokens(t.read)} · out ${humanTokens(t.output)})`);
38
+ parts.push(`~${money(s.cost)}${s.costStale ? ', changed since the last refresh' : ''}`);
39
+ } else parts.push('cost: run ccnav refresh');
40
+ return parts.join(' · ');
41
+ }
21
42
  const DAY = 86400 * 1000;
22
43
 
23
44
  // mode: list | filter | confirm-archive | prune-days | confirm-prune
24
- export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
45
+ export function App({ sessions: initialSessions, onChoose, passthrough = [], refreshedAt = null }) {
25
46
  const { exit } = useApp();
26
47
  const { stdout } = useStdout();
27
48
  const width = stdout?.columns || 120;
@@ -97,7 +118,7 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
97
118
  }, [rows, days]);
98
119
 
99
120
  const sel = rows[Math.min(cursor, rows.length - 1)];
100
- const listHeight = Math.max(4, height - 13);
121
+ const listHeight = Math.max(4, height - 14);
101
122
 
102
123
  // Display lines: a (possibly wrapping) header per directory, then its sessions.
103
124
  const items = useMemo(() => {
@@ -244,9 +265,14 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
244
265
  else if (input === 'q' || key.escape) exit();
245
266
  });
246
267
 
247
- const cTitle = Math.max(20, width - 4 - 2 - 14 - 10 - 10 - 7 - 5);
268
+ const cTitle = Math.max(20, width - 4 - 2 - 14 - 10 - 10 - 7 - 9 - 9 - 7);
248
269
  const header = pad('TITLE', cTitle) + ' ' + pad('BRANCH', 14) + ' '
249
- + pad('CREATED', 10) + ' ' + pad('LAST USED', 10) + ' ' + pad('SIZE', 7);
270
+ + pad('CREATED', 10) + ' ' + pad('LAST USED', 10) + ' ' + pad('SIZE', 7) + ' '
271
+ + pad('CONTEXT', 9) + ' ' + 'COST'.padStart(9);
272
+ const costed = rows.filter(s => s.cost != null);
273
+ const costNote = !refreshedAt ? ' · ccnav refresh for costs'
274
+ : ` · ${money(costed.reduce((a, s) => a + s.cost, 0))} est.`
275
+ + (costed.some(s => s.costStale) || costed.length < rows.length ? ` as of ${ago(new Date(refreshedAt))} (+ changed since)` : '');
250
276
  const hiddenScratch = showScratch ? 0 : sessions.filter(s => s.scratch).length;
251
277
  const agentCounts = AGENTS
252
278
  .map(a => [a, rows.filter(s => s.agent === a).length])
@@ -278,11 +304,12 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
278
304
 
279
305
  return h(Box, { flexDirection: 'column', width },
280
306
  h(Box, null,
281
- h(Text, { bold: true, color: 'cyan' }, 'ccnav'),
282
- h(Text, { dimColor: true },
307
+ h(Box, { flexShrink: 0 }, h(Text, { bold: true, color: 'cyan' }, 'ccnav')),
308
+ h(Text, { dimColor: true, wrap: 'truncate' },
283
309
  ` ${rows.length} sessions${agentCounts} · sorted by ${SORTS[sortIdx].label}`
284
310
  + (AGENTS[agentIdx - 1] ? ` · ${AGENTS[agentIdx - 1]} only (tab)` : '')
285
- + (hiddenScratch ? ` · ${hiddenScratch} desktop scratch hidden (a)` : '')),
311
+ + (hiddenScratch ? ` · ${hiddenScratch} desktop scratch hidden (a)` : '')
312
+ + costNote),
286
313
  ),
287
314
  filterLine,
288
315
  h(Text, { bold: true, dimColor: true }, ' ' + header),
@@ -295,7 +322,8 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
295
322
  const active = it.index === cursor;
296
323
  const line = pad(oneLine(s.title || s.firstPrompt) || '(untitled)', cTitle) + ' '
297
324
  + pad(s.branch, 14) + ' ' + pad(ago(s.created), 10) + ' ' + pad(ago(s.lastUsed), 10) + ' '
298
- + pad(humanSize(s.size), 7);
325
+ + pad(humanSize(s.size), 7) + ' ' + pad(contextLabel(s.context), 9) + ' '
326
+ + (s.cost == null ? '' : money(s.cost) + (s.costStale ? '+' : '')).padStart(9);
299
327
  return h(Text, { key: keyOf(s), inverse: active, color: s.cwdExists ? undefined : 'red', wrap: 'truncate' },
300
328
  (active ? ' › ' : ' '),
301
329
  h(Text, { color: s.cwdExists ? p.color : 'red' }, p.glyph + ' '),
@@ -310,6 +338,7 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
310
338
  h(Text, { dimColor: true }, ` · ${sel.agent}${sel.origin === 'desktop' ? ' (desktop/IDE)' : ''}`
311
339
  + `${sel.version ? ' ' + sel.version : ''}`
312
340
  + ` · started ${sel.created.toLocaleString()} · last ${sel.lastUsed.toLocaleString()}`)),
341
+ h(Text, { key: 'u', wrap: 'truncate' }, h(Text, { dimColor: true }, 'usage '), usageLine(sel)),
313
342
  h(Text, { key: 'f', wrap: 'truncate' }, h(Text, { dimColor: true }, 'first '), oneLine(sel.firstPrompt)),
314
343
  snippet
315
344
  ? h(Text, { key: 'm', wrap: 'truncate' }, h(Text, { dimColor: true }, 'match '), h(Text, { color: 'yellow' }, '…' + snippet + '…'))
package/src/jsonl.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // Shared JSONL reading: transcripts reach tens of MB, so only the ends are read.
2
2
  import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import readline from 'node:readline';
3
5
 
4
6
  export const HEAD_BYTES = 256 * 1024;
5
7
  export const TAIL_BYTES = 256 * 1024;
@@ -46,3 +48,27 @@ export function readEnds(file) {
46
48
  export function humanText(text) {
47
49
  return String(text || '').replace(/<([\w-]+)[^>]*>[\s\S]*?<\/\1>/g, '').trim();
48
50
  }
51
+
52
+ // Streams every record of a whole file; lines without any of `needles` are skipped unparsed,
53
+ // which keeps a full pass over hundreds of MB of transcripts to a few seconds.
54
+ export async function forEachRecord(file, needles, fn) {
55
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
56
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
57
+ try {
58
+ for await (const line of lines) {
59
+ if (!needles.some(n => line.includes(n))) continue;
60
+ let r;
61
+ try { r = JSON.parse(line); } catch { continue; }
62
+ fn(r);
63
+ }
64
+ } finally { lines.close(); stream.destroy(); }
65
+ }
66
+
67
+ // Every *.jsonl below dir (none if it does not exist), in a stable order.
68
+ export function jsonlFilesUnder(dir) {
69
+ let entries;
70
+ try { entries = fs.readdirSync(dir, { withFileTypes: true, recursive: true }); }
71
+ catch { return []; }
72
+ return entries.filter(e => e.isFile() && e.name.endsWith('.jsonl'))
73
+ .map(e => path.join(e.parentPath ?? e.path, e.name)).sort();
74
+ }
package/src/platform.mjs CHANGED
@@ -49,8 +49,37 @@ export const INSTALL_PKG = {
49
49
  };
50
50
  const hint = cmd => INSTALL_PKG[cmd] ? ` Install it: npm install -g ${INSTALL_PKG[cmd]}` : '';
51
51
 
52
+ // Before the agent takes over the terminal, ccnav must stop reading it. Ink only turns raw mode off
53
+ // and detaches its listener; the stream keeps reading, and on Windows that leaves a ReadConsole call
54
+ // pending in this process that wins keystrokes (Ctrl+C too) from the agent sharing the console.
55
+ // pause() does not stop a TTY read; closing the handle does. libuv reads through its own duplicate of
56
+ // the console handle (and never closes fd 0-2 on POSIX), so the child still inherits a working fd 0.
57
+ async function releaseStdin() {
58
+ const stdin = process.stdin;
59
+ const state = label => process.env.CCNAV_DEBUG && fs.appendFileSync(path.join(os.tmpdir(), 'ccnav-debug.log'),
60
+ `${new Date().toISOString()} ${label} isTTY=${stdin.isTTY} isRaw=${stdin.isRaw} reading=${stdin._handle?.reading}`
61
+ + ` flowing=${stdin.readableFlowing} destroyed=${stdin.destroyed} data=${stdin.listenerCount('data')}`
62
+ + ` readable=${stdin.listenerCount('readable')} keypress=${stdin.listenerCount('keypress')}\n`);
63
+ try {
64
+ state('before');
65
+ if (!stdin.isTTY || stdin.destroyed) return;
66
+ try { if (stdin.isRaw) stdin.setRawMode(false); } catch { /* already restored */ }
67
+ stdin.removeAllListeners('data');
68
+ stdin.removeAllListeners('readable');
69
+ stdin.removeAllListeners('keypress');
70
+ stdin.pause();
71
+ await new Promise(done => {
72
+ const timer = setTimeout(done, 250);
73
+ stdin.once('close', () => { clearTimeout(timer); done(); });
74
+ stdin.destroy();
75
+ });
76
+ state('after');
77
+ } catch { /* never block the launch on this */ }
78
+ }
79
+
52
80
  // Runs the agent in the foreground with the session's directory as cwd; resolves with its exit code.
53
- export function launchAgent(cmd, cwd, args) {
81
+ export async function launchAgent(cmd, cwd, args) {
82
+ await releaseStdin();
54
83
  return new Promise(resolve => {
55
84
  const legacy = IS_WIN && !has('pwsh');
56
85
  const passedArgs = legacy ? legacyWindowsArgs(cmd, args) : args;
@@ -2,7 +2,8 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { humanText, readEnds } from '../jsonl.mjs';
5
+ import { forEachRecord, humanText, jsonlFilesUnder, readEnds } from '../jsonl.mjs';
6
+ import { addTally, contextWindow, fingerprint, tallyKey } from '../usage.mjs';
6
7
 
7
8
  export const agent = 'claude';
8
9
  export const command = 'claude';
@@ -27,8 +28,9 @@ export function readSession(file) {
27
28
  const { stat, head, tail } = readEnds(file);
28
29
  const firstMsg = head.find(r => r.cwd && r.timestamp);
29
30
  const firstPrompt = head.map(promptText).find(Boolean);
30
- let title, lastPrompt, lastTs, bridge, lastCwd, branch;
31
+ let title, lastPrompt, lastTs, bridge, lastCwd, branch, lastTurn;
31
32
  for (const r of tail) {
33
+ if (r.type === 'assistant' && !r.isSidechain && r.message?.usage && r.message.model !== '<synthetic>') lastTurn = r.message;
32
34
  if (r.type === 'ai-title' && r.aiTitle) title = r.aiTitle;
33
35
  if (r.type === 'custom-title' && r.customTitle) title = r.customTitle;
34
36
  if (r.type === 'last-prompt' && r.lastPrompt) lastPrompt = r.lastPrompt;
@@ -43,6 +45,7 @@ export function readSession(file) {
43
45
  if (!cwd) return null; // no conversation ever happened
44
46
 
45
47
  const id = path.basename(file, '.jsonl');
48
+ const u = lastTurn?.usage;
46
49
  return {
47
50
  agent, id, file,
48
51
  // Subagent sidechains live in a folder named after the session; archive it alongside.
@@ -62,6 +65,13 @@ export function readSession(file) {
62
65
  created: new Date(firstMsg?.timestamp || stat.birthtime),
63
66
  lastUsed: lastTs ? new Date(Math.max(new Date(lastTs), stat.mtime)) : stat.mtime,
64
67
  size: stat.size,
68
+ fingerprint: fingerprint(stat),
69
+ model: lastTurn?.model || '',
70
+ // What the last request sent, i.e. how full the context window is now.
71
+ context: u ? {
72
+ used: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0),
73
+ window: contextWindow(lastTurn.model),
74
+ } : null,
65
75
  // Claude Desktop scratch folders: %APPDATA%\Claude\... on Windows, ~/Library/Application Support/Claude/... on macOS.
66
76
  scratch: /[\\/]Claude[\\/]scratch-workspaces[\\/]/i.test(cwd),
67
77
  };
@@ -89,6 +99,47 @@ export function listSessions({ onError = (file, error) => console.error(`ccnav:
89
99
  return out;
90
100
  }
91
101
 
102
+ // The transcript plus its subagent transcripts (<id>/subagents/*.jsonl), which bill to this session.
103
+ const usageFiles = s => [s.file, ...(s.extraPaths || []).flatMap(jsonlFilesUnder)];
104
+
105
+ export function usageFingerprint(s) {
106
+ return usageFiles(s).map(f => {
107
+ try { return fingerprint(fs.statSync(f)); } catch { return '-'; }
108
+ }).join(';');
109
+ }
110
+
111
+ // Claude Code writes one record per content block, all carrying the message's usage, and later
112
+ // copies can have higher output counts while streaming finishes: keep the last copy of each id.
113
+ export async function scanUsage(s) {
114
+ const turns = new Map();
115
+ let anon = 0;
116
+ for (const f of usageFiles(s)) {
117
+ await forEachRecord(f, ['"usage"'], r => {
118
+ const m = r.message;
119
+ if (r.type !== 'assistant' || !m?.usage || m.model === '<synthetic>') return;
120
+ turns.set(m.id || `anon-${anon++}`, m);
121
+ });
122
+ }
123
+ const byModel = {};
124
+ for (const m of turns.values()) {
125
+ const u = m.usage;
126
+ const write = u.cache_creation_input_tokens || 0;
127
+ const write1h = Math.min(write, u.cache_creation?.ephemeral_1h_input_tokens || 0);
128
+ const t = {
129
+ input: u.input_tokens || 0,
130
+ cacheWrite5m: write - write1h,
131
+ cacheWrite1h: write1h,
132
+ cacheRead: u.cache_read_input_tokens || 0,
133
+ output: u.output_tokens || 0,
134
+ webSearches: u.server_tool_use?.web_search_requests || 0,
135
+ requests: 1,
136
+ };
137
+ const prompt = t.input + write + t.cacheRead;
138
+ addTally(byModel, tallyKey(m.model || 'unknown', { prompt, fast: u.speed === 'fast' }), t);
139
+ }
140
+ return byModel;
141
+ }
142
+
92
143
  export function launchArgs(action, session, passthrough = []) {
93
144
  if (action === 'fork') return ['--resume', session.id, '--fork-session', ...passthrough];
94
145
  if (action === 'new') return [...passthrough];
@@ -2,7 +2,8 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { humanText, readEnds } from '../jsonl.mjs';
5
+ import { forEachRecord, humanText, readEnds } from '../jsonl.mjs';
6
+ import { addTally, contextWindow, emptyTally, fingerprint, tallyKey } from '../usage.mjs';
6
7
 
7
8
  export const agent = 'codex';
8
9
  export const command = 'codex';
@@ -50,10 +51,12 @@ export function readSession(file, index = readIndex()) {
50
51
  .map(r => humanText(textOf(r.payload.content)))
51
52
  .find(Boolean) || '';
52
53
 
53
- let lastText = '', lastTs;
54
+ let lastText = '', lastTs, model = meta.model || '', tokens;
54
55
  for (const r of tail) {
55
56
  if (r.timestamp) lastTs = r.timestamp;
56
57
  const p = r.payload;
58
+ if (r.type === 'turn_context' && p?.model) model = p.model;
59
+ if (p?.type === 'token_count' && p.info?.last_token_usage) tokens = p.info;
57
60
  if (p?.type === 'task_complete' && p.last_agent_message) lastText = p.last_agent_message;
58
61
  else if (p?.type === 'agent_message' && p.message) lastText = p.message;
59
62
  }
@@ -76,6 +79,8 @@ export function readSession(file, index = readIndex()) {
76
79
  origin,
77
80
  // A session spawned by another session, like a Claude sidechain.
78
81
  subagent: !!(meta.source && typeof meta.source === 'object' && meta.source.subagent),
82
+ parentId: meta.source?.subagent?.thread_spawn?.parent_thread_id || '',
83
+ childFiles: [], // subagent rollouts, filled in by listSessions; their tokens bill to this session
79
84
  title: indexed?.title || '',
80
85
  firstPrompt,
81
86
  lastText: humanText(lastText),
@@ -83,6 +88,13 @@ export function readSession(file, index = readIndex()) {
83
88
  created: new Date(meta.timestamp || head[0]?.timestamp || stat.birthtime),
84
89
  lastUsed: new Date(Math.max(...stamps.map(Number))),
85
90
  size: stat.size,
91
+ fingerprint: fingerprint(stat),
92
+ model,
93
+ // input_tokens already includes the cached part, so this is the whole prompt of the last request.
94
+ context: tokens ? {
95
+ used: tokens.last_token_usage.input_tokens || 0,
96
+ window: tokens.model_context_window || contextWindow(model),
97
+ } : null,
86
98
  scratch: false,
87
99
  };
88
100
  }
@@ -92,6 +104,7 @@ export function listSessions({ onError = (file, error) => console.error(`ccnav:
92
104
  if (!fs.existsSync(SESSIONS_ROOT)) return [];
93
105
  const index = readIndex(onError);
94
106
  const out = [];
107
+ const subagents = [];
95
108
  const walk = (dir, depth) => {
96
109
  let entries;
97
110
  try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
@@ -102,15 +115,68 @@ export function listSessions({ onError = (file, error) => console.error(`ccnav:
102
115
  else if (e.isFile() && e.name.endsWith('.jsonl')) {
103
116
  try {
104
117
  const s = readSession(p, index);
105
- if (s && !s.subagent) out.push(s);
118
+ if (s) (s.subagent ? subagents : out).push(s);
106
119
  } catch (error) { onError(p, error); }
107
120
  }
108
121
  }
109
122
  };
110
123
  walk(SESSIONS_ROOT, 0);
124
+ // Hand each subagent rollout to the listed session at the top of its spawn chain.
125
+ const byId = new Map([...out, ...subagents].map(s => [s.id, s]));
126
+ for (const sub of subagents) {
127
+ let top = sub;
128
+ for (let hops = 0; top?.subagent && hops < 32; hops++) top = byId.get(top.parentId);
129
+ if (top && !top.subagent) top.childFiles.push(sub.file);
130
+ }
111
131
  return out;
112
132
  }
113
133
 
134
+ const usageFiles = s => [s.file, ...(s.childFiles || [])];
135
+
136
+ export function usageFingerprint(s) {
137
+ return usageFiles(s).map(f => {
138
+ try { return fingerprint(fs.statSync(f)); } catch { return '-'; }
139
+ }).join(';');
140
+ }
141
+
142
+ // One token_usage_record per model response. Rollouts from before those records existed only have
143
+ // running totals in token_count events, so the last of those is used instead.
144
+ export async function scanUsage(s) {
145
+ const byModel = {};
146
+ for (const f of usageFiles(s)) {
147
+ let model = 'unknown', total = null, totalModel = model, records = 0;
148
+ const seen = new Set();
149
+ await forEachRecord(f, ['"turn_context"', '"session_meta"', '"token_usage_record"', '"token_count"'], r => {
150
+ const p = r.payload;
151
+ if ((r.type === 'turn_context' || r.type === 'session_meta') && p?.model) model = p.model;
152
+ else if (r.type === 'token_usage_record' && p?.usage) {
153
+ if (p.response_id && seen.has(p.response_id)) return;
154
+ seen.add(p.response_id);
155
+ records++;
156
+ addUsage(byModel, model, p.usage, 1);
157
+ } else if (p?.type === 'token_count' && p.info?.total_token_usage) {
158
+ total = p.info.total_token_usage;
159
+ totalModel = model;
160
+ }
161
+ });
162
+ if (!records && total) addUsage(byModel, totalModel, total, 0);
163
+ }
164
+ return byModel;
165
+ }
166
+
167
+ function addUsage(byModel, model, u, requests) {
168
+ const cached = u.cached_input_tokens || 0;
169
+ const written = u.cache_write_input_tokens || 0;
170
+ const t = { ...emptyTally(),
171
+ input: Math.max(0, (u.input_tokens || 0) - cached - written),
172
+ cacheWrite5m: written,
173
+ cacheRead: cached,
174
+ output: u.output_tokens || 0, // reasoning tokens are included and billed as output
175
+ requests,
176
+ };
177
+ addTally(byModel, tallyKey(model, { prompt: requests ? u.input_tokens || 0 : 0 }), t);
178
+ }
179
+
114
180
  export function launchArgs(action, session, passthrough = []) {
115
181
  if (action === 'fork') return ['fork', session.id, ...passthrough];
116
182
  if (action === 'new') return [...passthrough];
package/src/usage.mjs ADDED
@@ -0,0 +1,237 @@
1
+ // Token usage, context size and estimated cost.
2
+ // Listing only reads the cached tallies; `ccnav refresh` is the one thing that reads whole transcripts.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ export const CCNAV_HOME = process.env.CCNAV_HOME || path.join(os.homedir(), '.ccnav');
8
+ export const CACHE_FILE = path.join(CCNAV_HOME, 'usage.json');
9
+ export const PRICES_FILE = path.join(CCNAV_HOME, 'prices.json');
10
+
11
+ // List prices in USD per million tokens, from platform.claude.com/docs/en/about-claude/pricing and
12
+ // openai.com/index/introducing-gpt-6-1-sol. cacheWrite5m / cacheWrite1h default to 1.25x / 2x input.
13
+ // `long` applies to a whole request whose prompt exceeds `over` tokens; `fast` multiplies everything.
14
+ export const PRICES_AS_OF = '2026-10-30';
15
+ export const DEFAULT_WINDOW = 1_000_000;
16
+ const BUILTIN_PRICES = {
17
+ 'claude-fable-5-1': { input: 10, output: 50, cacheRead: 0.25 },
18
+ 'claude-mythos-5-1': { input: 10, output: 50, cacheRead: 0.25 },
19
+ 'claude-fable-5': { input: 10, output: 50, cacheRead: 1 },
20
+ 'claude-mythos-5': { input: 10, output: 50, cacheRead: 1 },
21
+ 'claude-opus-5-5': { input: 4, output: 20, cacheRead: 0.2, fast: 2 },
22
+ 'claude-opus-5': { input: 5, output: 25, cacheRead: 0.5, fast: 2 },
23
+ 'claude-opus-4-8': { input: 5, output: 25, cacheRead: 0.5, fast: 2 },
24
+ 'claude-opus-4-7': { input: 5, output: 25, cacheRead: 0.5 },
25
+ 'claude-opus-4-6': { input: 5, output: 25, cacheRead: 0.5 },
26
+ 'claude-opus-4-5': { input: 5, output: 25, cacheRead: 0.5, window: 200_000 },
27
+ 'claude-opus-4-1': { input: 15, output: 75, cacheRead: 1.5, window: 200_000 },
28
+ 'claude-opus-4': { input: 15, output: 75, cacheRead: 1.5, window: 200_000 },
29
+ 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.1 },
30
+ 'claude-sonnet-5': { input: 2, output: 10, cacheRead: 0.2 },
31
+ 'claude-sonnet-4-6': { input: 3, output: 15, cacheRead: 0.3 },
32
+ 'claude-sonnet-4-5': { input: 3, output: 15, cacheRead: 0.3, window: 200_000 },
33
+ 'claude-sonnet-4': { input: 3, output: 15, cacheRead: 0.3, window: 200_000 },
34
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5, cacheRead: 0.01, long: { over: 100_000, input: 0.5, output: 2.5, cacheRead: 0.05 } },
35
+ 'claude-haiku-4-5': { input: 1, output: 5, cacheRead: 0.1, window: 200_000 },
36
+ 'claude-3-5-haiku': { input: 0.8, output: 4, cacheRead: 0.08, window: 200_000 },
37
+ 'gpt-6.1-sol': { input: 2, output: 10, cacheRead: 0.1, cacheWrite5m: 2.5, long: { over: 272_000, input: 4, output: 15, cacheRead: 0.2, cacheWrite5m: 5 } },
38
+ };
39
+ export const WEB_SEARCH_USD = 0.01; // $10 per 1,000 searches
40
+
41
+ // ~/.ccnav/prices.json can add models or override any of the above, in the same shape.
42
+ function loadPrices() {
43
+ try { return { ...BUILTIN_PRICES, ...JSON.parse(fs.readFileSync(PRICES_FILE, 'utf8')) }; }
44
+ catch { return BUILTIN_PRICES; }
45
+ }
46
+ export const PRICES = loadPrices();
47
+
48
+ // Longest key contained in the id, so `claude-opus-5-5` beats `claude-opus-5` and dated
49
+ // (`-20251001`) or provider-prefixed (`anthropic.`) ids still match.
50
+ export function priceOf(model, prices = PRICES) {
51
+ const id = String(model || '').toLowerCase();
52
+ let best = null;
53
+ for (const key of Object.keys(prices)) if (id.includes(key) && (!best || key.length > best.length)) best = key;
54
+ return best ? prices[best] : null;
55
+ }
56
+
57
+ export function contextWindow(model) {
58
+ return priceOf(model)?.window || DEFAULT_WINDOW;
59
+ }
60
+
61
+ // Tallies are keyed by model plus the per-request pricing tier, e.g. `claude-haiku-5-5@long`
62
+ // or `claude-opus-5-5@fast`; prices are applied when displayed, so a price change needs no rescan.
63
+ const FIELDS = ['input', 'cacheWrite5m', 'cacheWrite1h', 'cacheRead', 'output', 'webSearches', 'requests'];
64
+ export const emptyTally = () => Object.fromEntries(FIELDS.map(f => [f, 0]));
65
+
66
+ export function tallyKey(model, { prompt = 0, fast = false } = {}) {
67
+ const p = priceOf(model);
68
+ let key = model;
69
+ if (p?.long && prompt > p.long.over) key += '@long';
70
+ if (fast) key += '@fast';
71
+ return key;
72
+ }
73
+
74
+ export function addTally(byModel, key, t) {
75
+ const into = byModel[key] ||= emptyTally();
76
+ for (const f of FIELDS) into[f] += t[f] || 0;
77
+ }
78
+
79
+ export function tokensOf(t) {
80
+ return t.input + t.cacheWrite5m + t.cacheWrite1h + t.cacheRead + t.output;
81
+ }
82
+
83
+ // Returns { cost, unpriced } for a byModel tally map; unpriced lists models with no known price.
84
+ export function costOf(byModel = {}) {
85
+ let cost = 0;
86
+ const unpriced = new Set();
87
+ for (const [key, t] of Object.entries(byModel)) {
88
+ const [model, ...tags] = key.split('@');
89
+ const base = priceOf(model);
90
+ if (!base) { if (tokensOf(t)) unpriced.add(model); continue; }
91
+ const p = tags.includes('long') && base.long ? { ...base, ...base.long } : base;
92
+ const mult = tags.includes('fast') ? base.fast || 1 : 1;
93
+ const w5 = p.cacheWrite5m ?? p.input * 1.25;
94
+ const w1 = p.cacheWrite1h ?? p.input * 2;
95
+ cost += mult * (t.input * p.input + t.cacheWrite5m * w5 + t.cacheWrite1h * w1
96
+ + t.cacheRead * p.cacheRead + t.output * p.output) / 1e6;
97
+ cost += t.webSearches * WEB_SEARCH_USD;
98
+ }
99
+ return { cost, unpriced: [...unpriced] };
100
+ }
101
+
102
+ export function sumTallies(list) {
103
+ const out = {};
104
+ for (const byModel of list) for (const [k, t] of Object.entries(byModel || {})) addTally(out, k, t);
105
+ return out;
106
+ }
107
+
108
+ // --- the cache written by `ccnav refresh` ---
109
+
110
+ export const fingerprint = stat => `${stat.size}:${Math.round(stat.mtimeMs)}`;
111
+ export const usageKey = s => `${s.agent}:${s.id}`;
112
+
113
+ export function loadUsageCache(file = CACHE_FILE) {
114
+ try {
115
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
116
+ if (data?.version === 1 && data.sessions) return data;
117
+ } catch { /* none yet, or unreadable: treated as never refreshed */ }
118
+ return { version: 1, refreshedAt: null, sessions: {} };
119
+ }
120
+
121
+ export function saveUsageCache(cache, file = CACHE_FILE) {
122
+ fs.mkdirSync(path.dirname(file), { recursive: true });
123
+ const tmp = `${file}.${process.pid}.tmp`;
124
+ fs.writeFileSync(tmp, JSON.stringify(cache));
125
+ fs.renameSync(tmp, file);
126
+ }
127
+
128
+ // Puts the cached tallies on each session. `costStale` means the transcript changed after the refresh.
129
+ export function attachUsage(sessions, cache = loadUsageCache()) {
130
+ for (const s of sessions) {
131
+ const entry = cache.sessions[usageKey(s)];
132
+ if (!entry) continue;
133
+ s.usage = entry.byModel;
134
+ s.cost = costOf(entry.byModel).cost;
135
+ s.costStale = entry.mainFp !== s.fingerprint;
136
+ }
137
+ return cache;
138
+ }
139
+
140
+ // Scans every session whose files changed since the last refresh (all of them with `all`).
141
+ // Entries for sessions that are no longer listed (archived or deleted) are kept, flagged `gone`,
142
+ // so the total still counts money already spent.
143
+ export async function refreshUsage(sessions, {
144
+ all = false, cache = loadUsageCache(), providers, onProgress = () => {},
145
+ onError = (s, error) => console.error(`ccnav: could not read usage for ${s.file}: ${error.message}`),
146
+ } = {}) {
147
+ let scanned = 0, reused = 0, failed = 0;
148
+ const listed = new Set();
149
+ for (const [i, s] of sessions.entries()) {
150
+ const key = usageKey(s);
151
+ listed.add(key);
152
+ const provider = providers[s.agent];
153
+ const fullFp = provider.usageFingerprint(s);
154
+ const prev = cache.sessions[key];
155
+ onProgress(i + 1, sessions.length, s);
156
+ if (!all && prev && prev.fp === fullFp) { prev.gone = false; reused++; continue; }
157
+ // A transcript archived or locked mid-refresh keeps its previous entry and fingerprint,
158
+ // so the next refresh tries it again; the rest of the run still gets saved.
159
+ let byModel;
160
+ try { byModel = await provider.scanUsage(s); }
161
+ catch (error) { onError(s, error); failed++; if (prev) prev.gone = false; continue; }
162
+ cache.sessions[key] = { agent: s.agent, id: s.id, cwd: s.cwd, title: s.title || s.firstPrompt?.slice(0, 80) || '',
163
+ fp: fullFp, mainFp: s.fingerprint, byModel, gone: false };
164
+ scanned++;
165
+ }
166
+ for (const [key, entry] of Object.entries(cache.sessions)) if (!listed.has(key)) entry.gone = true;
167
+ cache.refreshedAt = new Date().toISOString();
168
+ return { cache, scanned, reused, failed };
169
+ }
170
+
171
+ // --- formatting ---
172
+
173
+ export function humanTokens(n) {
174
+ if (!n) return '0';
175
+ if (n < 1000) return String(n);
176
+ if (n < 1e6) return `${Math.round(n / 1000)}k`;
177
+ if (n < 1e9) return `${+(n / 1e6).toFixed(n < 1e7 ? 2 : 1)}M`;
178
+ return `${+(n / 1e9).toFixed(2)}B`;
179
+ }
180
+
181
+ export function money(n) {
182
+ if (n == null) return '';
183
+ if (n >= 1000) return `$${Math.round(n).toLocaleString('en-US')}`;
184
+ return `$${n.toFixed(2)}`;
185
+ }
186
+
187
+ export function contextLabel(ctx) {
188
+ if (!ctx?.used) return '';
189
+ return `${humanTokens(ctx.used)} ${Math.round((ctx.used / ctx.window) * 100)}%`;
190
+ }
191
+
192
+ // The report printed by `ccnav refresh` and `ccnav cost`.
193
+ export function summaryLines(cache, { top = 10, shortPath = p => p } = {}) {
194
+ const entries = Object.values(cache.sessions);
195
+ if (!entries.length) return ['No usage recorded yet. Run: ccnav refresh'];
196
+ const row = (label, byModel, extra = '') => {
197
+ const { cost } = costOf(byModel);
198
+ const t = Object.values(byModel).reduce((a, x) => a + tokensOf(x), 0);
199
+ return ` ${label.padEnd(34)} ${money(cost).padStart(11)} ${humanTokens(t).padStart(7)} tokens${extra}`;
200
+ };
201
+ // Grouped case-insensitively, as the picker does, and labelled with the first spelling seen.
202
+ const group = keyFn => {
203
+ const m = new Map();
204
+ for (const e of entries) {
205
+ const label = keyFn(e), k = label.toLowerCase();
206
+ if (!m.has(k)) m.set(k, { label, list: [] });
207
+ m.get(k).list.push(e.byModel);
208
+ }
209
+ return [...m.values()].map(({ label, list }) => [label, sumTallies(list)])
210
+ .sort((a, b) => costOf(b[1]).cost - costOf(a[1]).cost);
211
+ };
212
+ const all = sumTallies(entries.map(e => e.byModel));
213
+ const gone = entries.filter(e => e.gone);
214
+ const out = [`Estimated cost at API list prices (prices as of ${PRICES_AS_OF})`, ''];
215
+ out.push(row(`all ${entries.length} sessions`, all));
216
+ for (const [agent, t] of group(e => e.agent)) out.push(row(agent, t));
217
+ if (gone.length) out.push(row(` of which archived or deleted (${gone.length})`, sumTallies(gone.map(e => e.byModel))));
218
+
219
+ out.push('', 'by model');
220
+ const byModel = Object.entries(all).map(([k, t]) => [k, { [k]: t }])
221
+ .sort((a, b) => costOf(b[1]).cost - costOf(a[1]).cost);
222
+ for (const [k, t] of byModel) out.push(row(k, t, ` ${t[k].requests.toLocaleString('en-US')} requests`));
223
+
224
+ const dirs = group(e => e.cwd || '?');
225
+ out.push('', `by directory${dirs.length > top ? ` (top ${top} of ${dirs.length})` : ''}`);
226
+ for (const [dir, t] of dirs.slice(0, top)) {
227
+ const label = shortPath(dir);
228
+ out.push(row(label.length > 34 ? '…' + label.slice(-33) : label, t));
229
+ }
230
+
231
+ const { unpriced } = costOf(all);
232
+ out.push('');
233
+ if (unpriced.length) out.push(`Not priced (add them to ${PRICES_FILE}): ${unpriced.join(', ')}`);
234
+ out.push('List-price estimate: subscription plans bill differently. Web search is included; other',
235
+ 'server-tool fees, batch and regional pricing are not. Forked sessions can count shared history twice.');
236
+ return out;
237
+ }