ccnav 1.1.0 → 1.2.0

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
@@ -34,6 +34,8 @@ npm install -g ./ccnav-1.0.0.tgz
34
34
 
35
35
  New tabs (`t`) use Windows Terminal, iTerm2, WezTerm, kitty, GNOME Terminal or Konsole. Terminal.app gets a new window, because real tabs need Accessibility permission. On macOS the first new tab asks for permission to control the terminal; if it is refused, allow it again under System Settings → Privacy & Security → Automation.
36
36
 
37
+ On Windows, PowerShell 7 preserves forwarded arguments including quotes and shell characters. With the built-in Windows PowerShell 5.1 fallback, arguments containing quotes, shell characters or line breaks are rejected because its npm command shim cannot pass them safely.
38
+
37
39
  ## Agents
38
40
 
39
41
  Sessions are listed whether or not the agent that wrote them is still installed, so an
@@ -59,6 +61,8 @@ ccnav --json print sessions as JSON and exit
59
61
  ccnav --model opus any other arguments are passed to the agent
60
62
  ccnav here new session in the current directory, running unattended
61
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
62
66
  ```
63
67
 
64
68
  ## Start one here
@@ -102,7 +106,7 @@ Codex removed `--full-auto` in 0.156, so the sandboxed middle ground is now spel
102
106
  | o | open the directory in Explorer, Finder or the Linux file manager |
103
107
  | c | copy the session id |
104
108
  | / | filter titles, paths, branches and prompts; Tab switches to full-transcript search |
105
- | 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) |
106
110
  | x | archive the selected session |
107
111
  | X | archive every listed session not used in N days |
108
112
  | a | show or hide Claude Desktop scratch sessions |
@@ -120,10 +124,46 @@ Codex removed `--full-auto` in 0.156, so the sandboxed middle ground is now spel
120
124
  | Resume / fork | `claude --resume <id>` / `--fork-session` | `codex resume <id>` / `codex fork <id>` |
121
125
  | Hidden | subagent sidechain folders, Desktop scratch workspaces | subagent threads spawned by other sessions |
122
126
 
123
- Only the first and last 256 KB of each transcript are read when listing, so a 21 MB session costs the same as a small one. Full-text search reads whole files.
127
+ Only the first and last 256 KB of each transcript are read when listing, so a 21 MB session costs the same as a small one. Full-text search streams each file in full and can be cancelled while it runs.
124
128
 
125
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.
126
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
+
127
167
  ## Test
128
168
 
129
169
  ```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.0",
3
+ "version": "1.2.0",
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"
@@ -19,6 +19,7 @@
19
19
  "ccnav": "bin/ccnav.mjs"
20
20
  },
21
21
  "dependencies": {
22
+ "cross-spawn": "^7.0.6",
22
23
  "ink": "^7.1.1",
23
24
  "react": "^19.3.0"
24
25
  },
package/src/actions.mjs CHANGED
@@ -1,31 +1,40 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import readline from 'node:readline';
4
+ import { setImmediate as yieldToUi } from 'node:timers/promises';
3
5
  export { askUser, copyToClipboard, ensureAgent, hasCommand, installShellFunction, launchAgent, openFolder, openInNewTab } from './platform.mjs';
4
6
 
5
7
  // Sessions touched this recently may be open in another terminal.
6
8
  export const LIVE_WINDOW_MS = 10 * 60 * 1000;
7
9
  export const isMaybeLive = s => Date.now() - s.lastUsed < LIVE_WINDOW_MS;
8
10
 
9
- // Case-insensitive search through the whole transcript; returns a short snippet or null.
10
- export function searchTranscript(session, query) {
11
+ // Stream the transcript so a search does not block the picker or load whole files into memory.
12
+ export async function searchTranscript(session, query, signal) {
13
+ if (!query || signal?.aborted) return null;
11
14
  const q = query.toLowerCase();
12
- let text;
13
- try { text = fs.readFileSync(session.file, 'utf8'); } catch { return null; }
14
- const lower = text.toLowerCase();
15
- const idx = lower.indexOf(q);
16
- if (idx < 0) return null;
17
- // Prefer the matching string value from the parsed record over raw JSON.
18
- const lineStart = text.lastIndexOf('\n', idx) + 1;
19
- const lineEnd = text.indexOf('\n', idx);
20
- let hay = text.slice(Math.max(0, idx - 60), idx + q.length + 80);
15
+ const stream = fs.createReadStream(session.file, { encoding: 'utf8', signal });
16
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
21
17
  try {
22
- const found = findString(JSON.parse(text.slice(lineStart, lineEnd < 0 ? undefined : lineEnd)), q);
23
- if (found) {
24
- const i = found.toLowerCase().indexOf(q);
25
- hay = found.slice(Math.max(0, i - 60), i + q.length + 80);
18
+ let count = 0;
19
+ for await (const line of lines) {
20
+ if (signal?.aborted) return null;
21
+ if (++count % 256 === 0) await yieldToUi();
22
+ const idx = line.toLowerCase().indexOf(q);
23
+ if (idx < 0) continue;
24
+ // Prefer the matching string value from the parsed record over raw JSON.
25
+ let hay = line.slice(Math.max(0, idx - 60), idx + q.length + 80);
26
+ try {
27
+ const found = findString(JSON.parse(line), q);
28
+ if (found) {
29
+ const i = found.toLowerCase().indexOf(q);
30
+ hay = found.slice(Math.max(0, i - 60), i + q.length + 80);
31
+ }
32
+ } catch { /* fall back to the raw line */ }
33
+ return hay.replace(/\\[nrt]/g, ' ').replace(/\s+/g, ' ').trim();
26
34
  }
27
- } catch { /* fall back to raw slice */ }
28
- return hay.replace(/\\[nrt]/g, ' ').replace(/\s+/g, ' ').trim();
35
+ } catch { /* unreadable or cancelled transcript */ }
36
+ finally { lines.close(); stream.destroy(); }
37
+ return null;
29
38
  }
30
39
 
31
40
  function findString(v, q) {
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;
@@ -34,27 +55,33 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
34
55
  const [mode, setMode] = useState('list');
35
56
  const [deep, setDeep] = useState(false);
36
57
  const [deepHits, setDeepHits] = useState(null); // Map id -> snippet, for the last deep query
37
- const [searching, setSearching] = useState(false);
58
+ const [searchQuery, setSearchQuery] = useState(null);
38
59
  const [showScratch, setShowScratch] = useState(false);
39
60
  const [agentIdx, setAgentIdx] = useState(0); // 0 = all agents, then one per agent
40
61
  const [message, setMessage] = useState(null); // { text, color }
41
62
  const [days, setDays] = useState('30');
42
63
 
43
- // Deep search reads whole transcripts, so it runs once per submitted query rather than per keystroke.
64
+ // Search once per submitted query, cancelling when the query or session list changes.
44
65
  useEffect(() => {
45
- if (!searching) return;
46
- const t = setTimeout(() => {
66
+ if (searchQuery === null) return;
67
+ const controller = new AbortController();
68
+ const search = async () => {
47
69
  const hits = new Map();
48
70
  for (const s of sessions) {
49
- const snip = searchTranscript(s, filter);
71
+ if (controller.signal.aborted) return;
72
+ const snip = await searchTranscript(s, searchQuery, controller.signal);
50
73
  if (snip) hits.set(keyOf(s), snip);
51
74
  }
75
+ if (controller.signal.aborted) return;
52
76
  setDeepHits(hits);
53
- setSearching(false);
77
+ setSearchQuery(null);
54
78
  setCursor(0);
55
- }, 10);
56
- return () => clearTimeout(t);
57
- }, [searching]);
79
+ };
80
+ search();
81
+ return () => controller.abort();
82
+ }, [searchQuery, sessions]);
83
+
84
+ const searching = searchQuery !== null;
58
85
 
59
86
  const sorted = useMemo(() => {
60
87
  const q = filter.toLowerCase();
@@ -91,7 +118,7 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
91
118
  }, [rows, days]);
92
119
 
93
120
  const sel = rows[Math.min(cursor, rows.length - 1)];
94
- const listHeight = Math.max(4, height - 13);
121
+ const listHeight = Math.max(4, height - 14);
95
122
 
96
123
  // Display lines: a (possibly wrapping) header per directory, then its sessions.
97
124
  const items = useMemo(() => {
@@ -162,11 +189,11 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
162
189
  setMessage(null);
163
190
 
164
191
  if (mode === 'filter') {
165
- if (key.escape) { setMode('list'); setFilter(''); setDeepHits(null); return; }
166
- if (key.tab) { setDeep(d => !d); setDeepHits(null); return; }
167
- if (key.return) { setMode('list'); if (deep && filter) setSearching(true); return; }
168
- if (key.backspace || key.delete) { setFilter(f => f.slice(0, -1)); setDeepHits(null); setCursor(0); return; }
169
- if (input && !key.ctrl && !key.meta) { setFilter(f => f + input); setDeepHits(null); setCursor(0); }
192
+ if (key.escape) { setMode('list'); setFilter(''); setDeepHits(null); setSearchQuery(null); return; }
193
+ if (key.tab) { setDeep(d => !d); setDeepHits(null); setSearchQuery(null); return; }
194
+ if (key.return) { setMode('list'); if (deep && filter) { setDeepHits(null); setSearchQuery(filter); } return; }
195
+ if (key.backspace || key.delete) { setFilter(f => f.slice(0, -1)); setDeepHits(null); setSearchQuery(null); setCursor(0); return; }
196
+ if (input && !key.ctrl && !key.meta) { setFilter(f => f + input); setDeepHits(null); setSearchQuery(null); setCursor(0); }
170
197
  return;
171
198
  }
172
199
 
@@ -234,13 +261,18 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
234
261
  else if (input === 's') { setSortIdx(i => (i + 1) % SORTS.length); setCursor(0); }
235
262
  else if (key.tab) { setAgentIdx(i => (i + 1) % (AGENTS.length + 1)); setCursor(0); }
236
263
  else if (input === 'a') { setShowScratch(v => !v); setCursor(0); }
237
- else if (key.escape && filter) { setFilter(''); setDeepHits(null); setCursor(0); }
264
+ else if (key.escape && filter) { setFilter(''); setDeepHits(null); setSearchQuery(null); setCursor(0); }
238
265
  else if (input === 'q' || key.escape) exit();
239
266
  });
240
267
 
241
- 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);
242
269
  const header = pad('TITLE', cTitle) + ' ' + pad('BRANCH', 14) + ' '
243
- + 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)` : '');
244
276
  const hiddenScratch = showScratch ? 0 : sessions.filter(s => s.scratch).length;
245
277
  const agentCounts = AGENTS
246
278
  .map(a => [a, rows.filter(s => s.agent === a).length])
@@ -272,11 +304,12 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
272
304
 
273
305
  return h(Box, { flexDirection: 'column', width },
274
306
  h(Box, null,
275
- h(Text, { bold: true, color: 'cyan' }, 'ccnav'),
276
- h(Text, { dimColor: true },
307
+ h(Box, { flexShrink: 0 }, h(Text, { bold: true, color: 'cyan' }, 'ccnav')),
308
+ h(Text, { dimColor: true, wrap: 'truncate' },
277
309
  ` ${rows.length} sessions${agentCounts} · sorted by ${SORTS[sortIdx].label}`
278
310
  + (AGENTS[agentIdx - 1] ? ` · ${AGENTS[agentIdx - 1]} only (tab)` : '')
279
- + (hiddenScratch ? ` · ${hiddenScratch} desktop scratch hidden (a)` : '')),
311
+ + (hiddenScratch ? ` · ${hiddenScratch} desktop scratch hidden (a)` : '')
312
+ + costNote),
280
313
  ),
281
314
  filterLine,
282
315
  h(Text, { bold: true, dimColor: true }, ' ' + header),
@@ -289,7 +322,8 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
289
322
  const active = it.index === cursor;
290
323
  const line = pad(oneLine(s.title || s.firstPrompt) || '(untitled)', cTitle) + ' '
291
324
  + pad(s.branch, 14) + ' ' + pad(ago(s.created), 10) + ' ' + pad(ago(s.lastUsed), 10) + ' '
292
- + 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);
293
327
  return h(Text, { key: keyOf(s), inverse: active, color: s.cwdExists ? undefined : 'red', wrap: 'truncate' },
294
328
  (active ? ' › ' : ' '),
295
329
  h(Text, { color: s.cwdExists ? p.color : 'red' }, p.glyph + ' '),
@@ -304,6 +338,7 @@ export function App({ sessions: initialSessions, onChoose, passthrough = [] }) {
304
338
  h(Text, { dimColor: true }, ` · ${sel.agent}${sel.origin === 'desktop' ? ' (desktop/IDE)' : ''}`
305
339
  + `${sel.version ? ' ' + sel.version : ''}`
306
340
  + ` · started ${sel.created.toLocaleString()} · last ${sel.lastUsed.toLocaleString()}`)),
341
+ h(Text, { key: 'u', wrap: 'truncate' }, h(Text, { dimColor: true }, 'usage '), usageLine(sel)),
307
342
  h(Text, { key: 'f', wrap: 'truncate' }, h(Text, { dimColor: true }, 'first '), oneLine(sel.firstPrompt)),
308
343
  snippet
309
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;
@@ -25,14 +27,17 @@ export function parseLines(text, { dropFirst = false, dropLast = false } = {}) {
25
27
  // Returns { stat, head, tail }; tail === head when the file fits in one read.
26
28
  export function readEnds(file) {
27
29
  const stat = fs.statSync(file);
30
+ if (!stat.isFile()) throw new Error('not a regular file');
28
31
  const fd = fs.openSync(file, 'r');
29
32
  try {
30
33
  const headLen = Math.min(HEAD_BYTES, stat.size);
31
34
  const head = parseLines(readSlice(fd, 0, headLen), { dropLast: headLen < stat.size });
32
35
  const tailStart = Math.max(0, stat.size - TAIL_BYTES);
33
- const tail = tailStart > headLen
34
- ? parseLines(readSlice(fd, tailStart, stat.size - tailStart), { dropFirst: true })
36
+ const tail = stat.size > HEAD_BYTES
37
+ ? parseLines(readSlice(fd, tailStart, stat.size - tailStart),
38
+ { dropFirst: tailStart > 0 && readSlice(fd, tailStart - 1, 1) !== '\n' })
35
39
  : head;
40
+ if (stat.size && !head.length && !tail.length) throw new Error('no readable JSONL records');
36
41
  return { stat, head, tail };
37
42
  } finally {
38
43
  fs.closeSync(fd);
@@ -43,3 +48,27 @@ export function readEnds(file) {
43
48
  export function humanText(text) {
44
49
  return String(text || '').replace(/<([\w-]+)[^>]*>[\s\S]*?<\/\1>/g, '').trim();
45
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
@@ -4,6 +4,8 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import readline from 'node:readline';
6
6
  import { spawn, spawnSync } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ import crossSpawn from 'cross-spawn';
7
9
 
8
10
  export const IS_WIN = process.platform === 'win32';
9
11
  export const IS_MAC = process.platform === 'darwin';
@@ -17,9 +19,29 @@ export const hasCommand = has;
17
19
 
18
20
  // POSIX single-quote escaping for building `sh -c` / AppleScript command lines.
19
21
  const shq = s => `'${String(s).replace(/'/g, `'\\''`)}'`;
20
- // Windows command lines: quote args with spaces, strip embedded quotes (args are UUIDs and flags).
21
- const winq = s => /[\s"]/.test(s) ? `"${String(s).replace(/"/g, '')}"` : s;
22
22
  const osaString = s => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
23
+ // Encode the command and argv as data before handing them to PowerShell.
24
+ function windowsCommand(cmd, args, { keepOpen = false } = {}) {
25
+ const spec = Buffer.from(JSON.stringify({ command: cmd, args }), 'utf8').toString('base64');
26
+ const run = `$ErrorActionPreference = 'Stop'; $spec = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${spec}')) | ConvertFrom-Json; $arguments = [string[]]$spec.args; $global:LASTEXITCODE = 0; try { & $spec.command @arguments } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 127 }`;
27
+ const script = keepOpen ? run : `${run}; exit $LASTEXITCODE`;
28
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
29
+ const shell = has('pwsh') ? 'pwsh' : 'powershell.exe';
30
+ return [shell, ['-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', ...(keepOpen ? ['-NoExit'] : []), '-EncodedCommand', encoded]];
31
+ }
32
+
33
+ // PowerShell 5 changes quoted arguments when its npm .ps1 shim forwards them to Node.
34
+ // For that fallback, use the .cmd shim and reject values it can reinterpret.
35
+ function legacyWindowsArgs(cmd, args) {
36
+ if (args.some(arg => /\0/.test(String(arg)))) return null;
37
+ const extension = path.extname(cmd).toLowerCase();
38
+ const where = spawnSync('where', [cmd], { encoding: 'utf8' });
39
+ const found = String(where.stdout || '').split(/\r?\n/);
40
+ const cmdShim = extension === '.cmd' || extension === '.bat'
41
+ || (extension !== '.exe' && found.some(p => /\.(cmd|bat)$/i.test(p)));
42
+ if (cmdShim && args.some(arg => /[\r\n"%!^&|<>]/.test(String(arg)))) return null;
43
+ return args;
44
+ }
23
45
 
24
46
  export const INSTALL_PKG = {
25
47
  claude: '@anthropic-ai/claude-code',
@@ -30,16 +52,24 @@ const hint = cmd => INSTALL_PKG[cmd] ? ` Install it: npm install -g ${INSTALL_PK
30
52
  // Runs the agent in the foreground with the session's directory as cwd; resolves with its exit code.
31
53
  export function launchAgent(cmd, cwd, args) {
32
54
  return new Promise(resolve => {
33
- // On Windows these are npm .cmd shims, which need a shell; elsewhere spawn them directly.
34
- const child = IS_WIN
35
- ? spawn([cmd, ...args.map(winq)].join(' '), { cwd, stdio: 'inherit', shell: true })
36
- : spawn(cmd, args, { cwd, stdio: 'inherit' });
37
- child.on('error', e => {
55
+ const legacy = IS_WIN && !has('pwsh');
56
+ const passedArgs = legacy ? legacyWindowsArgs(cmd, args) : args;
57
+ if (passedArgs === null) {
58
+ console.error('could not start agent: Windows PowerShell 5 cannot safely pass these arguments through a command shim; use PowerShell 7');
59
+ resolve(127);
60
+ return;
61
+ }
62
+ const [shell, shellArgs] = IS_WIN && !legacy ? windowsCommand(cmd, args) : [cmd, passedArgs];
63
+ const fail = e => {
38
64
  console.error(e.code === 'ENOENT'
39
- ? `${cmd} was not found on PATH.${hint(cmd)}`
65
+ ? `${shell} was not found on PATH.${shell === cmd ? hint(cmd) : ''}`
40
66
  : `could not start ${cmd}: ${e.message}`);
41
67
  resolve(127);
42
- });
68
+ };
69
+ let child;
70
+ try { child = legacy ? crossSpawn(shell, shellArgs, { cwd, stdio: 'inherit' }) : spawn(shell, shellArgs, { cwd, stdio: 'inherit' }); }
71
+ catch (error) { fail(error); return; }
72
+ child.on('error', fail);
43
73
  child.on('exit', code => resolve(code ?? 0));
44
74
  });
45
75
  }
@@ -85,7 +115,10 @@ export async function ensureAgent(cmd) {
85
115
  }
86
116
 
87
117
  console.log(`\nnpm install -g ${pkg}\n`);
88
- const r = spawnSync(IS_WIN ? 'npm.cmd' : 'npm', ['install', '-g', pkg], { stdio: 'inherit', shell: IS_WIN });
118
+ const [installer, installArgs] = IS_WIN
119
+ ? windowsCommand('npm', ['install', '-g', pkg])
120
+ : ['npm', ['install', '-g', pkg]];
121
+ const r = spawnSync(installer, installArgs, { stdio: 'inherit' });
89
122
  if (r.error || r.status !== 0) {
90
123
  console.error(`\nInstall failed${r.error ? `: ${r.error.message}` : ` (npm exited with ${r.status})`}.`);
91
124
  console.error(`If it was a permissions error, npm's global folder is not writable by you.`);
@@ -124,10 +157,13 @@ function macAutomationError(e, app) {
124
157
  // Opens a new terminal tab (or window) in `cwd` running `cmd` with `args`. Throws if nothing worked.
125
158
  export function openInNewTab(cmd, cwd, args, title = cmd) {
126
159
  if (IS_WIN) {
127
- const argv = ['-w', '0', 'new-tab', '--title', title.replace(/[;"]/g, ' ').slice(0, 40), '-d', cwd,
128
- 'pwsh', '-NoExit', '-Command', cmd, ...args];
129
- // wt.exe is an app execution alias, which needs a shell to launch reliably; it returns immediately.
130
- const r = spawnSync(['wt.exe', ...argv.map(winq)].join(' '), { shell: true, stdio: 'ignore', windowsHide: true });
160
+ const spec = Buffer.from(JSON.stringify({ cmd, cwd, args }), 'utf8').toString('base64');
161
+ const helper = fileURLToPath(new URL('./windows-tab.mjs', import.meta.url));
162
+ const [agentShell, agentArgs] = windowsCommand(process.execPath, [helper, spec], { keepOpen: true });
163
+ const argv = ['-w', '0', 'new-tab', '--title', title.replace(/[\r\n;"]/g, ' ').slice(0, 40), '-d', cwd,
164
+ agentShell, ...agentArgs];
165
+ const [terminalShell, terminalArgs] = windowsCommand('wt.exe', argv);
166
+ const r = spawnSync(terminalShell, terminalArgs, { stdio: 'ignore', windowsHide: true });
131
167
  if (r.error || r.status !== 0) throw new Error(r.error?.message || `wt.exe exited with ${r.status}`);
132
168
  return 'Windows Terminal tab';
133
169
  }
@@ -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,29 +65,81 @@ 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
  };
68
78
  }
69
79
 
70
80
  // Top-level *.jsonl only: <sessionId>/ subdirectories hold subagent sidechains.
71
- export function listSessions() {
81
+ export function listSessions({ onError = (file, error) => console.error(`ccnav: could not read Claude session at ${file}: ${error.message}`) } = {}) {
72
82
  if (!fs.existsSync(SESSIONS_ROOT)) return [];
73
83
  const out = [];
74
84
  for (const dir of fs.readdirSync(SESSIONS_ROOT, { withFileTypes: true })) {
75
85
  if (!dir.isDirectory()) continue;
76
86
  const projectDir = path.join(SESSIONS_ROOT, dir.name);
77
- for (const f of fs.readdirSync(projectDir)) {
87
+ let files;
88
+ try { files = fs.readdirSync(projectDir); }
89
+ catch (error) { onError(projectDir, error); continue; }
90
+ for (const f of files) {
78
91
  if (!f.endsWith('.jsonl')) continue;
92
+ const file = path.join(projectDir, f);
79
93
  try {
80
- const s = readSession(path.join(projectDir, f));
94
+ const s = readSession(file);
81
95
  if (s) out.push(s);
82
- } catch { /* unreadable file */ }
96
+ } catch (error) { onError(file, error); }
83
97
  }
84
98
  }
85
99
  return out;
86
100
  }
87
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
+
88
143
  export function launchArgs(action, session, passthrough = []) {
89
144
  if (action === 'fork') return ['--resume', session.id, '--fork-session', ...passthrough];
90
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';
@@ -18,10 +19,14 @@ export const ARCHIVE_ROOT = path.join(HOME_DIR, 'ccnav-archive');
18
19
  const INDEX_FILE = path.join(HOME_DIR, 'session_index.jsonl');
19
20
 
20
21
  // session_index.jsonl names about half the sessions; read it once per listing.
21
- function readIndex() {
22
+ function readIndex(onError = () => {}) {
22
23
  const map = new Map();
23
24
  let text;
24
- try { text = fs.readFileSync(INDEX_FILE, 'utf8'); } catch { return map; }
25
+ try { text = fs.readFileSync(INDEX_FILE, 'utf8'); }
26
+ catch (error) {
27
+ if (error.code !== 'ENOENT') onError(INDEX_FILE, error);
28
+ return map;
29
+ }
25
30
  for (const line of text.split('\n')) {
26
31
  if (!line.trim()) continue;
27
32
  try {
@@ -46,10 +51,12 @@ export function readSession(file, index = readIndex()) {
46
51
  .map(r => humanText(textOf(r.payload.content)))
47
52
  .find(Boolean) || '';
48
53
 
49
- let lastText = '', lastTs;
54
+ let lastText = '', lastTs, model = meta.model || '', tokens;
50
55
  for (const r of tail) {
51
56
  if (r.timestamp) lastTs = r.timestamp;
52
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;
53
60
  if (p?.type === 'task_complete' && p.last_agent_message) lastText = p.last_agent_message;
54
61
  else if (p?.type === 'agent_message' && p.message) lastText = p.message;
55
62
  }
@@ -72,6 +79,8 @@ export function readSession(file, index = readIndex()) {
72
79
  origin,
73
80
  // A session spawned by another session, like a Claude sidechain.
74
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
75
84
  title: indexed?.title || '',
76
85
  firstPrompt,
77
86
  lastText: humanText(lastText),
@@ -79,33 +88,95 @@ export function readSession(file, index = readIndex()) {
79
88
  created: new Date(meta.timestamp || head[0]?.timestamp || stat.birthtime),
80
89
  lastUsed: new Date(Math.max(...stamps.map(Number))),
81
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,
82
98
  scratch: false,
83
99
  };
84
100
  }
85
101
 
86
102
  // sessions/YYYY/MM/DD/*.jsonl
87
- export function listSessions() {
103
+ export function listSessions({ onError = (file, error) => console.error(`ccnav: could not read Codex session at ${file}: ${error.message}`) } = {}) {
88
104
  if (!fs.existsSync(SESSIONS_ROOT)) return [];
89
- const index = readIndex();
105
+ const index = readIndex(onError);
90
106
  const out = [];
107
+ const subagents = [];
91
108
  const walk = (dir, depth) => {
92
109
  let entries;
93
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
110
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
111
+ catch (error) { onError(dir, error); return; }
94
112
  for (const e of entries) {
95
113
  const p = path.join(dir, e.name);
96
114
  if (e.isDirectory() && depth < 3) walk(p, depth + 1);
97
115
  else if (e.isFile() && e.name.endsWith('.jsonl')) {
98
116
  try {
99
117
  const s = readSession(p, index);
100
- if (s && !s.subagent) out.push(s);
101
- } catch { /* unreadable file */ }
118
+ if (s) (s.subagent ? subagents : out).push(s);
119
+ } catch (error) { onError(p, error); }
102
120
  }
103
121
  }
104
122
  };
105
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
+ }
106
131
  return out;
107
132
  }
108
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
+
109
180
  export function launchArgs(action, session, passthrough = []) {
110
181
  if (action === 'fork') return ['fork', session.id, ...passthrough];
111
182
  if (action === 'new') return [...passthrough];
package/src/sessions.mjs CHANGED
@@ -5,11 +5,17 @@ import * as codex from './providers/codex.mjs';
5
5
  export const PROVIDERS = { claude, codex };
6
6
  export const AGENTS = Object.keys(PROVIDERS);
7
7
 
8
- // Both agents' sessions in one list, newest use first.
9
- export function listSessions({ agents = AGENTS } = {}) {
8
+ const reportError = (agent, file, error) =>
9
+ console.error(`ccnav: could not read ${agent} sessions${file ? ` at ${file}` : ''}: ${error.message}`);
10
+
11
+ // Both agents' sessions in one list, newest use first. Report unreadable sources on stderr.
12
+ export function listSessions({ agents = AGENTS, onError = reportError } = {}) {
10
13
  const out = [];
11
14
  for (const name of agents) {
12
- try { out.push(...PROVIDERS[name].listSessions()); } catch { /* provider not installed */ }
15
+ const provider = PROVIDERS[name];
16
+ if (!provider) { onError(name, null, new Error('unknown agent')); continue; }
17
+ try { out.push(...provider.listSessions({ onError: (file, error) => onError(name, file, error) })); }
18
+ catch (error) { onError(name, null, error); }
13
19
  }
14
20
  return out.sort((a, b) => b.lastUsed - a.lastUsed);
15
21
  }
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
+ }
@@ -0,0 +1,11 @@
1
+ // Started in a new Windows Terminal tab. The payload is data, so neither shell
2
+ // interprets session IDs or forwarded arguments as command source.
3
+ import { launchAgent } from './platform.mjs';
4
+
5
+ try {
6
+ const { cmd, cwd, args } = JSON.parse(Buffer.from(process.argv[2], 'base64').toString('utf8'));
7
+ process.exit(await launchAgent(cmd, cwd, args));
8
+ } catch (error) {
9
+ console.error(`ccnav: could not start agent in new tab: ${error.message}`);
10
+ process.exit(127);
11
+ }