ccnav 1.2.0 → 1.3.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
@@ -61,8 +61,10 @@ 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 new myapp new project: make <projects folder>/myapp, git init, start there unattended
64
65
  ccnav refresh update token and cost totals from changed transcripts, then print them
65
66
  ccnav cost print the totals from the last refresh
67
+ ccnav cost --since 7d the same, for the last 7 days only (--daily adds a per-day table)
66
68
  ```
67
69
 
68
70
  ## Start one here
@@ -94,6 +96,28 @@ Codex removed `--full-auto` in 0.156, so the sandboxed middle ground is now spel
94
96
  `--ask-for-approval never --sandbox workspace-write` if you would rather edit
95
97
  `src/providers/codex.mjs` to use that instead.
96
98
 
99
+ ## Start a new project
100
+
101
+ `ccnav new myapp` makes a folder named `myapp` in your projects folder, runs `git init`
102
+ in it, and then does what `ccnav here` does there: asks which agent and starts it
103
+ **unattended**, with the same flags and the same warnings as above.
104
+
105
+ ```
106
+ ccnav new asks for the name
107
+ ccnav new myapp --codex skips the agent question; other arguments go to the agent
108
+ ccnav new --projects-dir ~/code change the projects folder (on its own, just saves it)
109
+ ```
110
+
111
+ The first `ccnav new` asks which folder to create projects in (enter takes `~/Apps`)
112
+ and saves the answer as `projectsDir` in `~/.ccnav/config.json` (or `$CCNAV_HOME/config.json`).
113
+ It never reuses a folder: if `myapp` already exists it stops, so `cd` there and use
114
+ `ccnav here` instead. The name has to be a single folder name that works on every OS, so
115
+ no `/ \ : * ? " < > |`, no trailing dot or space, and none of Windows' reserved names
116
+ (`CON`, `NUL`, `COM1` …). The folder is only made once the agent is chosen and installed,
117
+ so answering no or pressing ctrl-D leaves nothing behind. If git is missing, the folder is
118
+ made anyway and ccnav says that git init was skipped. With the `--install-shell` function,
119
+ your shell ends up in the new project when the agent exits.
120
+
97
121
  | Key | Action |
98
122
  |---|---|
99
123
  | ↑ ↓ / j k, PgUp PgDn, g G | move |
@@ -143,10 +167,12 @@ full, so ccnav never does that on its own. Run it when you want fresh numbers:
143
167
  ccnav refresh read every transcript that changed since the last refresh
144
168
  ccnav refresh --all read them all again
145
169
  ccnav cost print the last totals without reading any transcripts
170
+ ccnav cost --since 7d only usage from the last 7 days (or --since 2026-11-01)
171
+ ccnav cost --daily add a cost-per-day table (both flags work with refresh too)
146
172
  ```
147
173
 
148
174
  `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
175
+ per session and per day (not dollars) in `~/.ccnav/usage.json`, or `$CCNAV_HOME/usage.json`. Prices are applied
150
176
  when the numbers are shown, so a price change never needs a rescan. The picker and `--list`
151
177
  read that file, and a `+` after a cost means the session has changed since the last refresh.
152
178
 
@@ -157,6 +183,10 @@ read that file, and a `+` after a cost means the session has changed since the l
157
183
  - Codex: each model response is counted once. Subagent rollouts count towards the session that
158
184
  spawned them, and prompts over 272K tokens pay the higher rates.
159
185
  - Archived or deleted sessions stay in the total and are shown on their own line.
186
+ - Days are local calendar days, taken from each request's timestamp. Older Codex rollouts that only
187
+ record running totals are put on the day of their last total. Totals saved by ccnav 1.2.1 or
188
+ earlier have no days, so the first refresh after upgrading reads every transcript again. Sessions
189
+ archived or deleted before then cannot be dated; `--since` and `--daily` leave them out and say how many.
160
190
  - Prices date from 2026-10-30 (`PRICES` in `src/usage.mjs`). To add a model or override a
161
191
  price, put entries of the same shape in `~/.ccnav/prices.json`:
162
192
  `{ "gpt-7": { "input": 3, "output": 12, "cacheRead": 0.3 } }` (USD per million tokens).
@@ -164,9 +194,17 @@ read that file, and a `+` after a cost means the session has changed since the l
164
194
  regional pricing, and server-tool fees other than web search. A forked session repeats its
165
195
  parent's history, so that history can be counted twice.
166
196
 
197
+ ## Troubleshooting
198
+
199
+ If a resumed session ignores the keyboard, or drops keys, set `CCNAV_DEBUG=1` before running
200
+ ccnav. Each launch appends two lines to `ccnav-debug.log` in your temp folder (`%TEMP%` on Windows,
201
+ `$TMPDIR` or `/tmp` elsewhere) recording ccnav's stdin state just before the agent starts. The
202
+ `after` line should show `destroyed=true`, meaning ccnav has stopped reading the terminal.
203
+
167
204
  ## Test
168
205
 
169
206
  ```sh
170
207
  npm test # unit + UI tests, any OS
208
+ # (on Windows, also a real-console handoff test)
171
209
  docker run --rm -v "$PWD:/src:ro" node:24 bash /src/test/docker-e2e.sh # Linux install + zsh end-to-end
172
210
  ```
package/bin/ccnav.mjs CHANGED
@@ -1,10 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import React from 'react';
3
- import { render } from 'ink';
4
- import { App } from '../src/app.mjs';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
5
4
  import { AGENTS, PROVIDERS, ago, humanSize, listSessions, providerOf, shortPath } from '../src/sessions.mjs';
6
5
  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';
6
+ import { CACHE_FILE, attachUsage, contextLabel, loadUsageCache, money, parseSince, refreshUsage, saveUsageCache, summaryLines } from '../src/usage.mjs';
8
7
 
9
8
  const args = process.argv.slice(2);
10
9
 
@@ -21,10 +20,17 @@ usage:
21
20
  ccnav here skip the picker: start a NEW session in the current
22
21
  directory, running unattended with no permission prompts
23
22
  (ccnav here --claude / --codex picks the agent outright)
23
+ ccnav new [name] start a NEW project: make <projects folder>/<name>, git init
24
+ it, and start an agent there unattended, as ccnav here does.
25
+ Asks for the projects folder the first time and saves it;
26
+ --projects-dir <path> changes it (on its own, just saves it)
24
27
  ccnav refresh read every changed transcript in full and update token and
25
28
  cost totals, then print them (--all rereads everything)
26
29
  ccnav cost print the totals from the last refresh without reading
27
30
  any transcripts
31
+ --since 7d (refresh or cost) only usage from the last 7 days, or
32
+ --since 2026-11-01 on or after a date; days are local calendar days
33
+ --daily (refresh or cost) add a cost-per-day table
28
34
  ccnav --install-shell add a shell function (PowerShell, zsh, bash or fish) so
29
35
  your shell is left in the session's directory afterwards
30
36
 
@@ -32,13 +38,13 @@ Any other arguments are passed to the agent (e.g. ccnav --model opus).`);
32
38
  process.exit(0);
33
39
  }
34
40
 
35
- // `ccnav here` never touches the session list: it starts a new one in this directory.
36
- async function chooseAgent() {
41
+ // `ccnav here` and `ccnav new` never touch the session list: they start a new session in `dir`.
42
+ async function chooseAgent(dir, command) {
37
43
  if (!process.stdin.isTTY) {
38
- console.error('ccnav here needs an interactive terminal, or name the agent: ccnav here --claude');
44
+ console.error(`${command} needs an interactive terminal, or name the agent: ${command} --claude`);
39
45
  process.exit(1);
40
46
  }
41
- console.log(`\nNew session in ${process.cwd()}\n`);
47
+ console.log(`\nNew session in ${dir}\n`);
42
48
  AGENTS.forEach((a, i) => {
43
49
  const p = PROVIDERS[a];
44
50
  console.log(` ${i + 1}) ${p.glyph} ${a.padEnd(7)} ${p.command} ${p.AUTO_ARGS.join(' ')}`);
@@ -59,15 +65,89 @@ if (args[0] === 'here') {
59
65
  const rest = args.slice(1);
60
66
  const named = AGENTS.find(a => rest.includes(`--${a}`));
61
67
  const extra = rest.filter(a => a !== '--' && !AGENTS.some(x => a === `--${x}`));
62
- const provider = PROVIDERS[named || await chooseAgent()];
68
+ const provider = PROVIDERS[named || await chooseAgent(process.cwd(), 'ccnav here')];
63
69
  if (!await ensureAgent(provider.command)) process.exit(127);
64
70
  const argv = [...provider.AUTO_ARGS, ...extra];
65
71
  console.log(`\n\u2192 ${process.cwd()}\n\u2192 ${provider.command} ${argv.join(' ')}\n`);
66
72
  process.exit(await launchAgent(provider.command, process.cwd(), argv));
67
73
  }
68
74
 
75
+ // `ccnav new [name]`: a new folder in the saved projects folder, git init, then `here` in it.
76
+ // Everything that can stop it is asked or checked before the folder is made, so a "no" leaves nothing behind.
77
+ if (args[0] === 'new') {
78
+ const { CONFIG_FILE, DEFAULT_PROJECTS_DIR, expandDir, gitInit, loadConfig, projectNameProblem, saveConfig } = await import('../src/project.mjs');
79
+ const fail = message => { console.error(message); process.exit(1); };
80
+ const rest = args.slice(1);
81
+ const d = rest.indexOf('--projects-dir');
82
+ if (d >= 0 && !rest[d + 1]) fail('--projects-dir needs a folder, e.g. ccnav new --projects-dir ~/Apps');
83
+ const named = AGENTS.find(a => rest.includes(`--${a}`));
84
+ const others = rest.filter((a, i) => (d < 0 || (i !== d && i !== d + 1)) && a !== '--' && !AGENTS.some(x => a === `--${x}`));
85
+ // The first bare word is the name; anything else goes to the agent, as with `here`.
86
+ const nameArg = others[0] && !others[0].startsWith('-') ? others[0] : null;
87
+ const extra = nameArg ? others.slice(1) : others;
88
+ const tty = process.stdin.isTTY;
89
+ let config;
90
+ try { config = loadConfig(); } catch (error) { fail(error.message); }
91
+
92
+ let projectsDir = config.projectsDir;
93
+ if (d >= 0) {
94
+ projectsDir = expandDir(rest[d + 1]);
95
+ saveConfig({ projectsDir });
96
+ console.log(`Projects folder: ${projectsDir} (saved to ${CONFIG_FILE})`);
97
+ } else if (!projectsDir) {
98
+ if (!tty) fail('ccnav new needs a projects folder the first time: ccnav new <name> --projects-dir <path>');
99
+ const answer = await askUser(`\nWhich folder should ccnav new create projects in? [${shortPath(DEFAULT_PROJECTS_DIR)}] `, { keepCase: true });
100
+ if (answer === null) fail('\nNo answer given, nothing created.');
101
+ projectsDir = answer ? expandDir(answer) : DEFAULT_PROJECTS_DIR;
102
+ saveConfig({ projectsDir });
103
+ console.log(`Saved to ${CONFIG_FILE}; ccnav new --projects-dir <path> changes it.`);
104
+ }
105
+
106
+ let name = nameArg;
107
+ if (!name) {
108
+ // `ccnav new --projects-dir X` on its own only changes the setting.
109
+ if (d >= 0) process.exit(0);
110
+ if (!tty) fail('ccnav new needs a project name: ccnav new <name>');
111
+ name = await askUser(`\nNew project in ${shortPath(projectsDir)}, name: `, { keepCase: true });
112
+ if (!name) fail('\nNo name given, nothing created.');
113
+ }
114
+ const problem = projectNameProblem(name);
115
+ if (problem) fail(problem);
116
+ const dir = path.join(projectsDir, name);
117
+ if (fs.existsSync(dir)) fail(`${dir} already exists, and ccnav new only starts new projects. To work in it: cd there and run ccnav here`);
118
+
119
+ const provider = PROVIDERS[named || await chooseAgent(dir, 'ccnav new')];
120
+ if (!await ensureAgent(provider.command)) process.exit(127);
121
+
122
+ try {
123
+ fs.mkdirSync(projectsDir, { recursive: true });
124
+ fs.mkdirSync(dir); // not recursive: if it appeared in the meantime, stop rather than share it
125
+ } catch (error) {
126
+ fail(error.code === 'EEXIST' ? `${dir} already exists, nothing started` : `could not create ${dir}: ${error.message}`);
127
+ }
128
+ const gitProblem = gitInit(dir);
129
+ console.log(`\nCreated ${dir}${gitProblem ? `; git init skipped: ${gitProblem}` : ' (git repository)'}`);
130
+ reportCwd(dir);
131
+ const argv = [...provider.AUTO_ARGS, ...extra];
132
+ console.log(`\u2192 ${provider.command} ${argv.join(' ')}\n`);
133
+ process.exit(await launchAgent(provider.command, dir, argv));
134
+ }
135
+
136
+ // `--since 7d` / `--since 2026-11-01` and `--daily`, shared by refresh and cost.
137
+ function reportOptions() {
138
+ const i = args.indexOf('--since');
139
+ const raw = i >= 0 ? args[i + 1] : null;
140
+ const since = i >= 0 ? parseSince(raw) : null;
141
+ if (i >= 0 && !since) {
142
+ console.error(`--since needs a number of days or a date, e.g. --since 7d or --since 2026-11-01 (got ${raw ?? 'nothing'})`);
143
+ process.exit(1);
144
+ }
145
+ return { shortPath, since, daily: args.includes('--daily') };
146
+ }
147
+
69
148
  // Cost is the one thing that needs whole transcripts, so it is only ever read here, on request.
70
149
  if (args[0] === 'refresh') {
150
+ const report = reportOptions();
71
151
  const started = Date.now();
72
152
  const sessions = listSessions();
73
153
  const tty = process.stderr.isTTY;
@@ -81,11 +161,12 @@ if (args[0] === 'refresh') {
81
161
  console.log(`Read ${scanned} changed session${scanned === 1 ? '' : 's'}, ${reused} unchanged, `
82
162
  + (failed ? `${failed} unreadable (kept their previous totals), ` : '')
83
163
  + `in ${((Date.now() - started) / 1000).toFixed(1)}s. Saved to ${CACHE_FILE}\n`);
84
- console.log(summaryLines(cache, { shortPath }).join('\n'));
164
+ console.log(summaryLines(cache, report).join('\n'));
85
165
  process.exit(0);
86
166
  }
87
167
 
88
168
  if (args[0] === 'cost') {
169
+ const report = reportOptions();
89
170
  const cache = loadUsageCache();
90
171
  if (!cache.refreshedAt) { console.log('No usage recorded yet. Run: ccnav refresh'); process.exit(0); }
91
172
  const sessions = listSessions();
@@ -93,7 +174,7 @@ if (args[0] === 'cost') {
93
174
  const changed = sessions.filter(s => s.cost == null || s.costStale).length;
94
175
  console.log(`From the refresh ${ago(new Date(cache.refreshedAt))}`
95
176
  + (changed ? `; ${changed} session${changed === 1 ? ' has' : 's have'} changed since (ccnav refresh to update)` : '') + '\n');
96
- console.log(summaryLines(cache, { shortPath }).join('\n'));
177
+ console.log(summaryLines(cache, report).join('\n'));
97
178
  process.exit(0);
98
179
  }
99
180
 
@@ -129,6 +210,8 @@ if (!process.stdin.isTTY) {
129
210
  process.exit(1);
130
211
  }
131
212
 
213
+ // Ink and React take most of a second to load, so only the picker pays for them.
214
+ const [{ default: React }, { render }, { App }] = await Promise.all([import('react'), import('ink'), import('../src/app.mjs')]);
132
215
  let choice = null;
133
216
  const app = render(React.createElement(App, { sessions, passthrough, refreshedAt: usageCache.refreshedAt, onChoose: c => { choice = c; } }));
134
217
  await app.waitUntilExit();
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "ccnav",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Claude Codex Navigator - pick a Claude Code or Codex session and resume it in its directory",
5
5
  "scripts": {
6
- "test": "node --test"
6
+ "test": "node --test test/ccnav.test.mjs"
7
7
  },
8
8
  "keywords": [
9
9
  "claude",
@@ -12,7 +12,7 @@
12
12
  "cli",
13
13
  "codex"
14
14
  ],
15
- "author": "rts-mb",
15
+ "author": "Michael Brown (https://github.com/mab0130)",
16
16
  "license": "MIT",
17
17
  "type": "module",
18
18
  "bin": {
@@ -37,10 +37,10 @@
37
37
  ],
38
38
  "repository": {
39
39
  "type": "git",
40
- "url": "git+https://github.com/rts-mb/ccnav.git"
40
+ "url": "git+https://github.com/mab0130/ccnav.git"
41
41
  },
42
- "homepage": "https://github.com/rts-mb/ccnav#readme",
42
+ "homepage": "https://github.com/mab0130/ccnav#readme",
43
43
  "bugs": {
44
- "url": "https://github.com/rts-mb/ccnav/issues"
44
+ "url": "https://github.com/mab0130/ccnav/issues"
45
45
  }
46
46
  }
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;
@@ -78,11 +107,12 @@ export function launchAgent(cmd, cwd, args) {
78
107
 
79
108
  // Resolves the trimmed answer, or null when stdin closed without one (ctrl-D, a closed pipe).
80
109
  // Resolving on 'close' rather than only in the callback keeps the promise from hanging on EOF.
81
- export function askUser(question) {
110
+ // Answers are lowercased unless keepCase is set, for names and paths.
111
+ export function askUser(question, { keepCase = false } = {}) {
82
112
  return new Promise(resolve => {
83
113
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
84
114
  let answer = null;
85
- rl.question(question, a => { answer = String(a).trim().toLowerCase(); rl.close(); });
115
+ rl.question(question, a => { answer = String(a).trim(); if (!keepCase) answer = answer.toLowerCase(); rl.close(); });
86
116
  rl.on('close', () => resolve(answer));
87
117
  });
88
118
  }
@@ -0,0 +1,55 @@
1
+ // `ccnav new`: the saved projects folder new projects are made in, and the checks on a new project.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { CCNAV_HOME } from './usage.mjs';
7
+
8
+ export const CONFIG_FILE = path.join(CCNAV_HOME, 'config.json');
9
+ export const DEFAULT_PROJECTS_DIR = path.join(os.homedir(), 'Apps');
10
+
11
+ // A missing file is an empty config; an unreadable one throws rather than being overwritten.
12
+ export function loadConfig() {
13
+ let text;
14
+ try { text = fs.readFileSync(CONFIG_FILE, 'utf8'); } catch (error) {
15
+ if (error.code === 'ENOENT') return {};
16
+ throw error;
17
+ }
18
+ try { return JSON.parse(text) || {}; } catch {
19
+ throw new Error(`${CONFIG_FILE} is not valid JSON; fix or delete it`);
20
+ }
21
+ }
22
+
23
+ export function saveConfig(changes) {
24
+ const next = { ...loadConfig(), ...changes };
25
+ fs.mkdirSync(CCNAV_HOME, { recursive: true });
26
+ fs.writeFileSync(CONFIG_FILE, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
27
+ return next;
28
+ }
29
+
30
+ // A folder as typed at a prompt: quotes dropped, `~` is the home directory, relative to cwd.
31
+ export function expandDir(text, cwd = process.cwd()) {
32
+ const s = String(text).trim().replace(/^(["'])(.*)\1$/, '$2');
33
+ const home = s === '~' || /^~[\\/]/.test(s) ? path.join(os.homedir(), s.slice(1)) : s;
34
+ return path.resolve(cwd, home);
35
+ }
36
+
37
+ const RESERVED = /^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i;
38
+
39
+ // One folder name that is valid on Windows, macOS and Linux alike. Null when it is fine.
40
+ export function projectNameProblem(name) {
41
+ if (!name) return 'a project name is needed';
42
+ if (name === '.' || name === '..') return `"${name}" is not a folder name`;
43
+ if (/[<>:"/\\|?*\x00-\x1f]/.test(name)) return 'a project name cannot contain / \\ : * ? " < > |';
44
+ if (/^\s|[\s.]$/.test(name)) return 'a project name cannot start with a space or end with a space or dot';
45
+ if (RESERVED.test(name)) return `"${name}" is a reserved name on Windows`;
46
+ return null;
47
+ }
48
+
49
+ // Null on success, otherwise why it did not happen.
50
+ export function gitInit(dir) {
51
+ const r = spawnSync('git', ['init', '-q'], { cwd: dir, encoding: 'utf8' });
52
+ if (r.error?.code === 'ENOENT') return 'git is not installed';
53
+ if (r.status !== 0) return (r.stderr || r.error?.message || 'git init failed').trim();
54
+ return null;
55
+ }
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { forEachRecord, humanText, jsonlFilesUnder, readEnds } from '../jsonl.mjs';
6
- import { addTally, contextWindow, fingerprint, tallyKey } from '../usage.mjs';
6
+ import { addTally, contextWindow, dayOf, fingerprint, tallyKey } from '../usage.mjs';
7
7
 
8
8
  export const agent = 'claude';
9
9
  export const command = 'claude';
@@ -110,6 +110,7 @@ export function usageFingerprint(s) {
110
110
 
111
111
  // Claude Code writes one record per content block, all carrying the message's usage, and later
112
112
  // copies can have higher output counts while streaming finishes: keep the last copy of each id.
113
+ // Returns the tallies per local day, dated by that last copy.
113
114
  export async function scanUsage(s) {
114
115
  const turns = new Map();
115
116
  let anon = 0;
@@ -117,11 +118,11 @@ export async function scanUsage(s) {
117
118
  await forEachRecord(f, ['"usage"'], r => {
118
119
  const m = r.message;
119
120
  if (r.type !== 'assistant' || !m?.usage || m.model === '<synthetic>') return;
120
- turns.set(m.id || `anon-${anon++}`, m);
121
+ turns.set(m.id || `anon-${anon++}`, { m, day: dayOf(r.timestamp) });
121
122
  });
122
123
  }
123
- const byModel = {};
124
- for (const m of turns.values()) {
124
+ const byDay = {};
125
+ for (const { m, day } of turns.values()) {
125
126
  const u = m.usage;
126
127
  const write = u.cache_creation_input_tokens || 0;
127
128
  const write1h = Math.min(write, u.cache_creation?.ephemeral_1h_input_tokens || 0);
@@ -135,9 +136,9 @@ export async function scanUsage(s) {
135
136
  requests: 1,
136
137
  };
137
138
  const prompt = t.input + write + t.cacheRead;
138
- addTally(byModel, tallyKey(m.model || 'unknown', { prompt, fast: u.speed === 'fast' }), t);
139
+ addTally(byDay[day] ||= {}, tallyKey(m.model || 'unknown', { prompt, fast: u.speed === 'fast' }), t);
139
140
  }
140
- return byModel;
141
+ return byDay;
141
142
  }
142
143
 
143
144
  export function launchArgs(action, session, passthrough = []) {
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { forEachRecord, humanText, readEnds } from '../jsonl.mjs';
6
- import { addTally, contextWindow, emptyTally, fingerprint, tallyKey } from '../usage.mjs';
6
+ import { addTally, contextWindow, dayOf, emptyTally, fingerprint, tallyKey } from '../usage.mjs';
7
7
 
8
8
  export const agent = 'codex';
9
9
  export const command = 'codex';
@@ -140,11 +140,12 @@ export function usageFingerprint(s) {
140
140
  }
141
141
 
142
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.
143
+ // running totals in token_count events, so the last of those is used instead, dated by that event.
144
+ // Returns the tallies per local day.
144
145
  export async function scanUsage(s) {
145
- const byModel = {};
146
+ const byDay = {};
146
147
  for (const f of usageFiles(s)) {
147
- let model = 'unknown', total = null, totalModel = model, records = 0;
148
+ let model = 'unknown', total = null, totalModel = model, totalDay = '', records = 0;
148
149
  const seen = new Set();
149
150
  await forEachRecord(f, ['"turn_context"', '"session_meta"', '"token_usage_record"', '"token_count"'], r => {
150
151
  const p = r.payload;
@@ -153,15 +154,16 @@ export async function scanUsage(s) {
153
154
  if (p.response_id && seen.has(p.response_id)) return;
154
155
  seen.add(p.response_id);
155
156
  records++;
156
- addUsage(byModel, model, p.usage, 1);
157
+ addUsage(byDay[dayOf(r.timestamp)] ||= {}, model, p.usage, 1);
157
158
  } else if (p?.type === 'token_count' && p.info?.total_token_usage) {
158
159
  total = p.info.total_token_usage;
159
160
  totalModel = model;
161
+ totalDay = dayOf(r.timestamp);
160
162
  }
161
163
  });
162
- if (!records && total) addUsage(byModel, totalModel, total, 0);
164
+ if (!records && total) addUsage(byDay[totalDay] ||= {}, totalModel, total, 0);
163
165
  }
164
- return byModel;
166
+ return byDay;
165
167
  }
166
168
 
167
169
  function addUsage(byModel, model, u, requests) {
package/src/usage.mjs CHANGED
@@ -105,6 +105,28 @@ export function sumTallies(list) {
105
105
  return out;
106
106
  }
107
107
 
108
+ // --- days ---
109
+
110
+ // Usage is bucketed by the local calendar day of each request, as YYYY-MM-DD.
111
+ export const UNDATED = 'undated';
112
+ const ymd = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
113
+ export function dayOf(ts) {
114
+ const d = new Date(ts);
115
+ return ts && !Number.isNaN(d.getTime()) ? ymd(d) : UNDATED;
116
+ }
117
+
118
+ // `7d` is today and the six days before it; a YYYY-MM-DD date is taken as is. Null when unrecognised.
119
+ export function parseSince(text, now = new Date()) {
120
+ const s = String(text || '').trim().toLowerCase();
121
+ if (s === 'today') return ymd(now);
122
+ const n = /^(\d+)d$/.exec(s);
123
+ if (n && Number(n[1]) >= 1) return ymd(new Date(now.getFullYear(), now.getMonth(), now.getDate() - (Number(n[1]) - 1)));
124
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s) && dayOf(`${s}T12:00:00`) === s) return s;
125
+ return null;
126
+ }
127
+
128
+ const inPeriod = (day, since) => day !== UNDATED && (!since || day >= since);
129
+
108
130
  // --- the cache written by `ccnav refresh` ---
109
131
 
110
132
  export const fingerprint = stat => `${stat.size}:${Math.round(stat.mtimeMs)}`;
@@ -153,14 +175,16 @@ export async function refreshUsage(sessions, {
153
175
  const fullFp = provider.usageFingerprint(s);
154
176
  const prev = cache.sessions[key];
155
177
  onProgress(i + 1, sessions.length, s);
156
- if (!all && prev && prev.fp === fullFp) { prev.gone = false; reused++; continue; }
178
+ // Entries from before daily totals were kept are read again once, to add them.
179
+ if (!all && prev && prev.fp === fullFp && prev.byDay) { prev.gone = false; reused++; continue; }
157
180
  // A transcript archived or locked mid-refresh keeps its previous entry and fingerprint,
158
181
  // 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); }
182
+ let byDay;
183
+ try { byDay = await provider.scanUsage(s); }
161
184
  catch (error) { onError(s, error); failed++; if (prev) prev.gone = false; continue; }
185
+ // The session totals are the sum of its days, so the two can never disagree.
162
186
  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 };
187
+ fp: fullFp, mainFp: s.fingerprint, byModel: sumTallies(Object.values(byDay)), byDay, gone: false };
164
188
  scanned++;
165
189
  }
166
190
  for (const [key, entry] of Object.entries(cache.sessions)) if (!listed.has(key)) entry.gone = true;
@@ -189,10 +213,37 @@ export function contextLabel(ctx) {
189
213
  return `${humanTokens(ctx.used)} ${Math.round((ctx.used / ctx.window) * 100)}%`;
190
214
  }
191
215
 
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'];
216
+ // The report printed by `ccnav refresh` and `ccnav cost`. `since` (YYYY-MM-DD) limits it to usage on
217
+ // or after that day; `daily` adds a by-day section. Sessions with no daily totals cannot be placed in a
218
+ // period, so they are left out of one and the report says how many.
219
+ export function summaryLines(cache, { top = 10, shortPath = p => p, since = null, daily = false } = {}) {
220
+ const recorded = Object.values(cache.sessions);
221
+ if (!recorded.length) return ['No usage recorded yet. Run: ccnav refresh'];
222
+ const undated = recorded.filter(e => !e.byDay);
223
+ const entries = !since ? recorded : recorded.flatMap(e => {
224
+ if (!e.byDay) return [];
225
+ const byModel = sumTallies(Object.entries(e.byDay).filter(([day]) => inPeriod(day, since)).map(([, t]) => t));
226
+ return Object.values(byModel).some(t => tokensOf(t) || t.webSearches) ? [{ ...e, byModel }] : [];
227
+ });
228
+ // Requests with no readable timestamp belong to no day, so a period or daily view cannot count them either.
229
+ const untimed = recorded.filter(e => e.byDay?.[UNDATED]);
230
+ const notCounted = () => {
231
+ const out = [];
232
+ if (undated.length) {
233
+ const n = undated.length, refreshable = undated.filter(e => !e.gone).length, gone = n - refreshable;
234
+ const parts = [];
235
+ if (refreshable) parts.push(`ccnav refresh adds ${refreshable === n ? 'them' : refreshable}`);
236
+ if (gone) parts.push(`${gone === n ? (n === 1 ? 'it was' : 'they were') : `${gone} were`} archived or deleted, so cannot be read again`);
237
+ out.push(`${n} session${n === 1 ? '' : 's'} not counted here, from before ccnav kept daily totals: ${parts.join('; ')}.`);
238
+ }
239
+ if (untimed.length) {
240
+ const t = sumTallies(untimed.map(e => e.byDay[UNDATED]));
241
+ out.push(`Not counted here: ${humanTokens(Object.values(t).reduce((a, x) => a + tokensOf(x), 0))} tokens`
242
+ + ` (${money(costOf(t).cost)}) in ${untimed.length} session${untimed.length === 1 ? '' : 's'} with no timestamp on the request.`);
243
+ }
244
+ return out;
245
+ };
246
+ if (!entries.length) return [`No usage on or after ${since}.`, ...notCounted()];
196
247
  const row = (label, byModel, extra = '') => {
197
248
  const { cost } = costOf(byModel);
198
249
  const t = Object.values(byModel).reduce((a, x) => a + tokensOf(x), 0);
@@ -211,11 +262,24 @@ export function summaryLines(cache, { top = 10, shortPath = p => p } = {}) {
211
262
  };
212
263
  const all = sumTallies(entries.map(e => e.byModel));
213
264
  const gone = entries.filter(e => e.gone);
214
- const out = [`Estimated cost at API list prices (prices as of ${PRICES_AS_OF})`, ''];
265
+ const out = [`Estimated cost at API list prices (prices as of ${PRICES_AS_OF})`
266
+ + (since ? `, for usage on or after ${since}` : ''), ''];
215
267
  out.push(row(`all ${entries.length} sessions`, all));
216
268
  for (const [agent, t] of group(e => e.agent)) out.push(row(agent, t));
217
269
  if (gone.length) out.push(row(` of which archived or deleted (${gone.length})`, sumTallies(gone.map(e => e.byModel))));
218
270
 
271
+ if (daily) {
272
+ const days = new Map();
273
+ for (const e of entries) {
274
+ for (const [day, t] of Object.entries(e.byDay || {})) if (inPeriod(day, since)) days.set(day, sumTallies([days.get(day), t]));
275
+ }
276
+ const newest = [...days.entries()].sort((a, b) => (a[0] < b[0] ? 1 : -1));
277
+ const shown = since ? newest : newest.slice(0, 31);
278
+ out.push('', `by day${shown.length < newest.length ? ` (latest ${shown.length} of ${newest.length}; --since for more)` : ''}`);
279
+ for (const [day, t] of shown) out.push(row(day, t));
280
+ }
281
+ if (since || daily) out.push(...notCounted().map(l => ` ${l}`));
282
+
219
283
  out.push('', 'by model');
220
284
  const byModel = Object.entries(all).map(([k, t]) => [k, { [k]: t }])
221
285
  .sort((a, b) => costOf(b[1]).cost - costOf(a[1]).cost);