spendbyteam 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,7 @@ Total $1,086.20 112 2.4B
26
26
  |---|---|
27
27
  | `--days=N` | Last N days, including today (default 30) |
28
28
  | `--all` | Everything in the logs |
29
- | `--by=project\|model\|branch\|day` | How to group (default `project`; sub-folders of a git repo count as one project) |
29
+ | `--by=project\|model\|branch\|day\|session` | How to group (default `project`; sub-folders of a git repo count as one project). `session` lists your most expensive sessions with turns and the input / output / cache-write / cache-read split |
30
30
  | `--json` | Machine-readable output |
31
31
 
32
32
  ## Track it for the whole team
package/dist/cli.js CHANGED
@@ -14,7 +14,7 @@ import { consoleLogger } from './log.js';
14
14
  const HELP = `spendbyteam — see and share what Claude Code costs (metrics only, no prompts or code)
15
15
 
16
16
  Usage:
17
- npx spendbyteam report [--days=30 | --all] [--by=project|model|branch|day] [--json]
17
+ npx spendbyteam report [--days=30 | --all] [--by=project|model|branch|day|session] [--json]
18
18
  npx spendbyteam connect [--team-id=ID] [--no-browser]
19
19
  npx spendbyteam init --token=sbt_ing_... [--endpoint=URL] [--team-id=ID] [--no-ping]
20
20
  npx spendbyteam uninstall
@@ -23,7 +23,7 @@ Usage:
23
23
  npx spendbyteam print-managed --token=sbt_ing_... [--endpoint=URL] [--team-id=ID]
24
24
 
25
25
  Commands:
26
- report What Claude Code cost on this machine, per project, model, branch or day, at API list
26
+ report What Claude Code cost on this machine, per project, model, branch, day or session, at API list
27
27
  prices. Reads the local session logs only: works offline, no account or token needed.
28
28
  connect Sign up or log in in the browser, approve this machine, and set it up: no token to copy.
29
29
  init Merge the OTel env + context hook into ~/.claude/settings.json (backup: settings.json.bak),
@@ -40,7 +40,7 @@ Options:
40
40
  --no-ping Skip the GET /v1/ping connectivity test.
41
41
  --days report: how many days back to look, including today (default 30).
42
42
  --all report: everything in the logs.
43
- --by report: group by project (default), model, branch or day.
43
+ --by report: group by project (default), model, branch, day or session.
44
44
  --json report: print JSON instead of a table.
45
45
  --no-browser connect: print the approval link instead of opening a browser.
46
46
  --app-url connect: panel URL (default https://app.spendbyteam.com).
package/dist/report.js CHANGED
@@ -3,7 +3,8 @@ import path from 'node:path';
3
3
  import { homeDir } from './paths.js';
4
4
  import { costOf, normalizeModel } from './pricing.js';
5
5
  import { UsageError } from './env.js';
6
- export const GROUPS = ['project', 'model', 'branch', 'day'];
6
+ export const GROUPS = ['project', 'model', 'branch', 'day', 'session'];
7
+ const emptySplit = () => ({ input: 0, output: 0, cacheWrite: 0, cacheRead: 0 });
7
8
  /** Where Claude Code keeps its session logs: $CLAUDE_CONFIG_DIR (comma-separated), else ~/.claude and ~/.config/claude. */
8
9
  export function logDirs() {
9
10
  const configured = process.env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
@@ -78,12 +79,15 @@ async function* usageLines(file) {
78
79
  yield text;
79
80
  }
80
81
  }
81
- async function readRequests(files, since) {
82
+ async function readRequests(files, since, onProgress) {
82
83
  const requests = new Map();
83
84
  const project = projectResolver();
84
- for (const file of files) {
85
- if (since !== null && fs.statSync(file).mtimeMs < since)
86
- continue;
85
+ const todo = files.map((file) => ({ file, stat: fs.statSync(file) })).filter(({ stat }) => since === null || stat.mtimeMs >= since);
86
+ const totalBytes = todo.reduce((n, f) => n + f.stat.size, 0);
87
+ let doneBytes = 0;
88
+ for (const { file, stat } of todo) {
89
+ onProgress?.(doneBytes, totalBytes);
90
+ doneBytes += stat.size;
87
91
  for await (const line of usageLines(file)) {
88
92
  let row;
89
93
  try {
@@ -106,6 +110,12 @@ async function readRequests(files, since) {
106
110
  model: normalizeModel(model),
107
111
  cost: costOf(model, usage),
108
112
  tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0),
113
+ split: {
114
+ input: usage.input_tokens ?? 0,
115
+ output: usage.output_tokens ?? 0,
116
+ cacheWrite: usage.cache_creation_input_tokens ?? 0,
117
+ cacheRead: usage.cache_read_input_tokens ?? 0,
118
+ },
109
119
  session: row.sessionId ?? file,
110
120
  project: project(row.cwd),
111
121
  branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
@@ -114,6 +124,7 @@ async function readRequests(files, since) {
114
124
  });
115
125
  }
116
126
  }
127
+ onProgress?.(totalBytes, totalBytes);
117
128
  return requests;
118
129
  }
119
130
  export async function buildReport(opts = {}) {
@@ -130,7 +141,7 @@ export async function buildReport(opts = {}) {
130
141
  const since = opts.all ? null : start.getTime();
131
142
  const dirs = opts.dirs ?? logDirs();
132
143
  const files = dirs.flatMap((d) => jsonlFiles(d));
133
- const requests = await readRequests(files, since);
144
+ const requests = await readRequests(files, since, opts.onProgress);
134
145
  const groups = new Map();
135
146
  const unpriced = new Map();
136
147
  const sessions = new Set();
@@ -143,11 +154,26 @@ export async function buildReport(opts = {}) {
143
154
  continue;
144
155
  }
145
156
  const key = by === 'model' ? r.model : r[by];
146
- const g = groups.get(key) ?? { cost: 0, requests: 0, sessions: new Set(), tokens: 0, models: new Map() };
157
+ const g = groups.get(key) ?? {
158
+ cost: 0,
159
+ requests: 0,
160
+ sessions: new Set(),
161
+ tokens: 0,
162
+ split: emptySplit(),
163
+ models: new Map(),
164
+ first: Infinity,
165
+ projects: new Map(),
166
+ };
147
167
  g.cost += r.cost;
148
168
  g.requests += 1;
149
169
  g.sessions.add(r.session);
150
170
  g.tokens += r.tokens;
171
+ g.split.input += r.split.input;
172
+ g.split.output += r.split.output;
173
+ g.split.cacheWrite += r.split.cacheWrite;
174
+ g.split.cacheRead += r.split.cacheRead;
175
+ g.first = Math.min(g.first, r.at);
176
+ g.projects.set(r.project, (g.projects.get(r.project) ?? 0) + r.cost);
151
177
  g.models.set(r.model, (g.models.get(r.model) ?? 0) + r.cost);
152
178
  groups.set(key, g);
153
179
  sessions.add(r.session);
@@ -163,7 +189,11 @@ export async function buildReport(opts = {}) {
163
189
  requests: g.requests,
164
190
  sessions: g.sessions.size,
165
191
  tokens: g.tokens,
192
+ split: g.split,
166
193
  topModel: [...g.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
194
+ ...(by === 'session'
195
+ ? { startedAt: new Date(g.first).toISOString(), project: [...g.projects.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '' }
196
+ : {}),
167
197
  }))
168
198
  .sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
169
199
  return {
@@ -182,7 +212,7 @@ const shortModel = (m) => m.replace(/^claude-/, '');
182
212
  const style = (code) => (s) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
183
213
  const bold = style('1');
184
214
  const dim = style('2');
185
- const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day' };
215
+ const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day', session: 'Session' };
186
216
  const MAX_ROWS = 15;
187
217
  export const CTA_URL = 'https://spendbyteam.com/?utm_source=cli&utm_medium=report';
188
218
  export function renderReport(r) {
@@ -197,6 +227,8 @@ export function renderReport(r) {
197
227
  : 'No priced Claude Code usage in this period. Try --days=90 or --all.');
198
228
  return out.join('\n');
199
229
  }
230
+ if (r.by === 'session')
231
+ return renderSessions(r, out);
200
232
  const shown = r.rows.slice(0, MAX_ROWS);
201
233
  const rest = r.rows.slice(MAX_ROWS);
202
234
  const showModel = r.by !== 'model';
@@ -229,6 +261,9 @@ export function renderReport(r) {
229
261
  out.push(fmt(cells));
230
262
  out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
231
263
  out.push(bold(fmt(totalRow)));
264
+ return finish(r, out);
265
+ }
266
+ function finish(r, out) {
232
267
  if (r.unpriced.length) {
233
268
  out.push('');
234
269
  out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
@@ -238,8 +273,77 @@ export function renderReport(r) {
238
273
  out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
239
274
  return out.join('\n');
240
275
  }
276
+ function localDateTime(iso) {
277
+ const d = new Date(iso);
278
+ const pad = (n) => String(n).padStart(2, '0');
279
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
280
+ }
281
+ /** --by=session: the most expensive sessions, with where their tokens went. */
282
+ function renderSessions(r, out) {
283
+ const shown = r.rows.slice(0, MAX_ROWS);
284
+ const header = ['Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
285
+ const body = shown.map((row) => [
286
+ localDateTime(row.startedAt),
287
+ row.project ?? '',
288
+ usd(row.cost),
289
+ String(row.requests),
290
+ compact(row.split.input),
291
+ compact(row.split.output),
292
+ compact(row.split.cacheWrite),
293
+ compact(row.split.cacheRead),
294
+ shortModel(row.topModel),
295
+ ]);
296
+ const left = new Set([0, 1, 8]);
297
+ const projectWidth = Math.min(28, Math.max(...[header, ...body].map((t) => t[1].length)));
298
+ const widths = header.map((_, i) => (i === 1 ? projectWidth : Math.max(...[header, ...body].map((t) => t[i].length))));
299
+ const fmt = (cells) => cells
300
+ .map((c, i) => {
301
+ const cell = i === 1 && c.length > projectWidth ? `${c.slice(0, projectWidth - 1)}…` : c;
302
+ return left.has(i) ? cell.padEnd(widths[i]) : cell.padStart(widths[i]);
303
+ })
304
+ .join(' ')
305
+ .trimEnd();
306
+ out.push(bold(fmt(header)));
307
+ for (const cells of body)
308
+ out.push(fmt(cells));
309
+ out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
310
+ const rest = r.rows.length - shown.length;
311
+ out.push(`${bold(`${r.rows.length} sessions, ${usd(r.total.cost)}`)}${rest > 0 ? dim(` (top ${shown.length} shown; --json for all)`) : ''}`);
312
+ out.push(dim('Each turn re-sends the conversation so far, mostly as cheap cache reads: long sessions grow fast. /clear or /compact resets that.'));
313
+ return finish(r, out);
314
+ }
315
+ /** A "Reading logs… 42%" line on stderr while reading, only on a terminal and never with --json. */
316
+ function progressLine() {
317
+ if (!process.stderr.isTTY)
318
+ return { clear: () => { } };
319
+ let shown = false;
320
+ let last = -1;
321
+ return {
322
+ onProgress: (done, total) => {
323
+ if (total < 50_000_000)
324
+ return; // small log folders finish before a line is worth showing
325
+ const pct = Math.floor((done / total) * 100);
326
+ if (pct === last)
327
+ return;
328
+ last = pct;
329
+ shown = true;
330
+ process.stderr.write(`\r\x1b[2KReading ${(total / 1e9).toFixed(1)} GB of Claude Code logs… ${pct}%`);
331
+ },
332
+ clear: () => {
333
+ if (shown)
334
+ process.stderr.write('\r\x1b[2K');
335
+ },
336
+ };
337
+ }
241
338
  export async function report(opts = {}) {
242
- const r = await buildReport(opts);
339
+ const progress = progressLine();
340
+ let r;
341
+ try {
342
+ r = await buildReport({ onProgress: progress.onProgress, ...opts });
343
+ }
344
+ finally {
345
+ progress.clear();
346
+ }
243
347
  console.log(opts.json ? JSON.stringify(r, null, 2) : renderReport(r));
244
348
  return r;
245
349
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spendbyteam",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "See what Claude Code costs per project, model, branch or day (offline), and connect it to SpendByTeam for your team.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://spendbyteam.com/docs/install",