spendbyteam 0.1.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
@@ -1,6 +1,43 @@
1
1
  # spendbyteam
2
2
 
3
- Connect [Claude Code](https://code.claude.com) to **SpendByTeam** and see AI coding spend per team, project and client.
3
+ See what [Claude Code](https://code.claude.com) costs, per project, model, branch or day. Then share it with your team on **SpendByTeam**.
4
+
5
+ ## See your own spend (no account needed)
6
+
7
+ ```bash
8
+ npx spendbyteam report
9
+ ```
10
+
11
+ ```
12
+ Claude Code spend on this machine 2026-10-20 → 2026-11-18
13
+ At API list prices. On a Pro, Max or Team seat you pay a flat fee; this is what the same tokens cost on the API.
14
+
15
+ Project Cost Share Sessions Tokens Top model
16
+ checkout-api $412.80 38% 41 980.2M opus-5-5
17
+ web $301.15 28% 33 702.6M opus-5-5
18
+ infra $118.40 11% 9 250.1M sonnet-5-5
19
+ …
20
+ Total $1,086.20 112 2.4B
21
+ ```
22
+
23
+ `report` reads the session logs Claude Code already keeps on your machine (`~/.claude/projects`, or `$CLAUDE_CONFIG_DIR`). It works offline and **sends nothing anywhere**. Costs use Anthropic's API list prices, including cache reads, 5-minute and 1-hour cache writes, and fast mode.
24
+
25
+ | Option | |
26
+ |---|---|
27
+ | `--days=N` | Last N days, including today (default 30) |
28
+ | `--all` | Everything in the logs |
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
+ | `--json` | Machine-readable output |
31
+
32
+ ## Track it for the whole team
33
+
34
+ ```bash
35
+ npx spendbyteam connect
36
+ ```
37
+
38
+ `connect` prints a short code and opens your browser. Sign up (free for 3 developers) or log in, check the code matches, and click **Connect**. The panel issues an ingest token for this machine and the CLI installs it, so there is nothing to copy. Before you approve, the only thing sent is this machine's name, so the page can show which machine is asking. Use `--no-browser` on a server or over SSH.
39
+
40
+ Already have a token, or setting up many machines? Use `init` directly:
4
41
 
5
42
  ```bash
6
43
  npx spendbyteam init --token=sbt_ing_xxxxxxxx
package/dist/cli.js CHANGED
@@ -6,12 +6,16 @@ import { uninstall } from './uninstall.js';
6
6
  import { status } from './status.js';
7
7
  import { doctor } from './doctor.js';
8
8
  import { managedSettingsJson } from './managed.js';
9
+ import { report, GROUPS } from './report.js';
10
+ import { connect } from './connect.js';
9
11
  import { UsageError } from './env.js';
10
12
  import { JsonFileError } from './fsutil.js';
11
13
  import { consoleLogger } from './log.js';
12
- const HELP = `spendbyteam — connect Claude Code to SpendByTeam (metrics only, no prompts or code)
14
+ const HELP = `spendbyteam — see and share what Claude Code costs (metrics only, no prompts or code)
13
15
 
14
16
  Usage:
17
+ npx spendbyteam report [--days=30 | --all] [--by=project|model|branch|day|session] [--json]
18
+ npx spendbyteam connect [--team-id=ID] [--no-browser]
15
19
  npx spendbyteam init --token=sbt_ing_... [--endpoint=URL] [--team-id=ID] [--no-ping]
16
20
  npx spendbyteam uninstall
17
21
  npx spendbyteam status
@@ -19,6 +23,9 @@ Usage:
19
23
  npx spendbyteam print-managed --token=sbt_ing_... [--endpoint=URL] [--team-id=ID]
20
24
 
21
25
  Commands:
26
+ report What Claude Code cost on this machine, per project, model, branch, day or session, at API list
27
+ prices. Reads the local session logs only: works offline, no account or token needed.
28
+ connect Sign up or log in in the browser, approve this machine, and set it up: no token to copy.
22
29
  init Merge the OTel env + context hook into ~/.claude/settings.json (backup: settings.json.bak),
23
30
  write ~/.spendbyteam/config.json (mode 600) and ~/.spendbyteam/hook.sh. Safe to re-run.
24
31
  uninstall Undo everything init did (restores env values that existed before).
@@ -31,6 +38,12 @@ Options:
31
38
  --endpoint Ingest endpoint (default https://ingest.spendbyteam.com).
32
39
  --team-id Optional static team id, sent as OTEL_RESOURCE_ATTRIBUTES=team.id=<id>.
33
40
  --no-ping Skip the GET /v1/ping connectivity test.
41
+ --days report: how many days back to look, including today (default 30).
42
+ --all report: everything in the logs.
43
+ --by report: group by project (default), model, branch, day or session.
44
+ --json report: print JSON instead of a table.
45
+ --no-browser connect: print the approval link instead of opening a browser.
46
+ --app-url connect: panel URL (default https://app.spendbyteam.com).
34
47
  -h, --help Show this help.
35
48
  -v, --version Show version.
36
49
  `;
@@ -48,6 +61,12 @@ export async function main(argv) {
48
61
  endpoint: { type: 'string' },
49
62
  'team-id': { type: 'string' },
50
63
  'no-ping': { type: 'boolean', default: false },
64
+ days: { type: 'string' },
65
+ all: { type: 'boolean', default: false },
66
+ by: { type: 'string' },
67
+ json: { type: 'boolean', default: false },
68
+ 'no-browser': { type: 'boolean', default: false },
69
+ 'app-url': { type: 'string' },
51
70
  help: { type: 'boolean', short: 'h', default: false },
52
71
  version: { type: 'boolean', short: 'v', default: false },
53
72
  },
@@ -65,6 +84,17 @@ export async function main(argv) {
65
84
  throw new UsageError(`Unexpected argument: ${positionals[1]}`);
66
85
  const envOpts = { token: values.token ?? '', endpoint: values.endpoint, teamId: values['team-id'] };
67
86
  switch (cmd) {
87
+ case 'report': {
88
+ const days = values.days === undefined ? undefined : Number(values.days);
89
+ if (values.by !== undefined && !GROUPS.includes(values.by)) {
90
+ throw new UsageError(`--by must be one of: ${GROUPS.join(', ')}.`);
91
+ }
92
+ await report({ days, all: values.all, by: values.by, json: values.json });
93
+ return 0;
94
+ }
95
+ case 'connect':
96
+ await connect({ appUrl: values['app-url'], teamId: values['team-id'], open: !values['no-browser'], ping: !values['no-ping'] });
97
+ return 0;
68
98
  case 'init':
69
99
  await init({ ...envOpts, ping: !values['no-ping'] });
70
100
  return 0;
@@ -0,0 +1,124 @@
1
+ import os from 'node:os';
2
+ import { spawn } from 'node:child_process';
3
+ import { init } from './init.js';
4
+ import { UsageError } from './env.js';
5
+ import { consoleLogger } from './log.js';
6
+ /**
7
+ * `spendbyteam connect`: set up this machine without copying a token.
8
+ *
9
+ * Device-authorization flow: ask the panel for a code, open the browser where the person signs
10
+ * up or logs in and approves that code, then poll until the panel hands over an ingest token,
11
+ * and run `init` with it. The only thing sent before approval is this machine's hostname, so the
12
+ * approval page can say which machine is asking.
13
+ */
14
+ export const DEFAULT_APP_URL = 'https://app.spendbyteam.com';
15
+ export function normalizeAppUrl(raw) {
16
+ const value = (raw ?? process.env.SPENDBYTEAM_APP_URL ?? DEFAULT_APP_URL).trim();
17
+ let url;
18
+ try {
19
+ url = new URL(value);
20
+ }
21
+ catch {
22
+ throw new UsageError(`Invalid --app-url: ${value}`);
23
+ }
24
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
25
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
26
+ throw new UsageError('--app-url must use https:// (http:// is only allowed for localhost).');
27
+ }
28
+ return url.origin;
29
+ }
30
+ /** A name the approval page can show. macOS sometimes reports a LAN IP as the hostname: say "Mac" instead. */
31
+ export function machineLabel(hostname = os.hostname(), platform = process.platform) {
32
+ const name = hostname.replace(/\.local$/i, '').trim();
33
+ if (!name || /^\d{1,3}(\.\d{1,3}){3}$/.test(name) || name.includes(':')) {
34
+ return platform === 'darwin' ? 'Mac' : platform === 'win32' ? 'Windows PC' : platform === 'linux' ? 'Linux machine' : 'machine';
35
+ }
36
+ return name.slice(0, 64);
37
+ }
38
+ export function openInBrowser(url) {
39
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
40
+ try {
41
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
42
+ child.on('error', () => { });
43
+ child.unref();
44
+ }
45
+ catch {
46
+ // No browser here (SSH, container): the URL is printed anyway.
47
+ }
48
+ }
49
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50
+ async function postJson(fetchImpl, url, body) {
51
+ const res = await fetchImpl(url, {
52
+ method: 'POST',
53
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
54
+ body: JSON.stringify(body),
55
+ signal: AbortSignal.timeout(15_000),
56
+ });
57
+ let data = null;
58
+ try {
59
+ data = await res.json();
60
+ }
61
+ catch {
62
+ // Non-JSON error page: status code says enough.
63
+ }
64
+ return { status: res.status, data };
65
+ }
66
+ export async function connect(opts = {}) {
67
+ const log = opts.logger ?? consoleLogger;
68
+ const fetchImpl = opts.fetchImpl ?? fetch;
69
+ const sleep = opts.sleep ?? wait;
70
+ const appUrl = normalizeAppUrl(opts.appUrl);
71
+ let start;
72
+ try {
73
+ start = await postJson(fetchImpl, `${appUrl}/cli/connect/start`, { client_name: machineLabel() });
74
+ }
75
+ catch (err) {
76
+ throw new UsageError(`Could not reach ${appUrl} (${err.message}). Check your connection and try again.`);
77
+ }
78
+ if (start.status !== 200 || !start.data?.device_code) {
79
+ throw new UsageError(start.status === 429 ? 'Too many attempts. Wait a minute and try again.' : `${appUrl} answered ${start.status}. Try again in a moment.`);
80
+ }
81
+ const s = start.data;
82
+ log.info('');
83
+ log.info(` Your code: ${s.user_code}`);
84
+ log.info('');
85
+ log.info(`Approve it in your browser (sign up free if you have no account):`);
86
+ log.info(` ${s.verification_uri_complete}`);
87
+ if (opts.open !== false)
88
+ (opts.openBrowser ?? openInBrowser)(s.verification_uri_complete);
89
+ log.info('');
90
+ log.info('Waiting for approval… (Ctrl+C to stop)');
91
+ let interval = Math.max(1, s.interval) * 1000;
92
+ const deadline = Date.now() + s.expires_in * 1000;
93
+ let failures = 0;
94
+ while (Date.now() < deadline) {
95
+ await sleep(interval);
96
+ let poll;
97
+ try {
98
+ poll = await postJson(fetchImpl, `${appUrl}/cli/connect/poll`, { device_code: s.device_code });
99
+ failures = 0;
100
+ }
101
+ catch {
102
+ if (++failures >= 5)
103
+ throw new UsageError(`Lost the connection to ${appUrl}. Run \`npx spendbyteam connect\` again.`);
104
+ continue;
105
+ }
106
+ if (poll.status === 429) {
107
+ interval += 2000;
108
+ continue;
109
+ }
110
+ if (poll.status === 200 && poll.data?.status === 'approved' && typeof poll.data.token === 'string') {
111
+ log.ok('Approved. Setting up Claude Code on this machine…');
112
+ const result = await init({ token: poll.data.token, endpoint: poll.data.endpoint, teamId: opts.teamId, ping: opts.ping, logger: log });
113
+ log.info('');
114
+ log.ok('Connected. New Claude Code sessions here now show up in your SpendByTeam workspace.');
115
+ return result;
116
+ }
117
+ if (poll.status === 410) {
118
+ throw new UsageError(poll.data?.status === 'denied'
119
+ ? 'The connection was cancelled in the browser. Nothing was changed on this machine.'
120
+ : 'The code expired. Run `npx spendbyteam connect` again.');
121
+ }
122
+ }
123
+ throw new UsageError('The code expired before it was approved. Run `npx spendbyteam connect` again.');
124
+ }
@@ -0,0 +1,66 @@
1
+ /** Longest prefix wins, so `claude-opus-5-5` is matched before `claude-opus-5`. */
2
+ const PRICES = {
3
+ 'claude-fable-5-1': { input: 10, output: 50, cacheRead: 0.25 },
4
+ 'claude-mythos-5-1': { input: 10, output: 50, cacheRead: 0.25 },
5
+ 'claude-fable-5': { input: 10, output: 50, cacheRead: 1 },
6
+ 'claude-mythos-5': { input: 10, output: 50, cacheRead: 1 },
7
+ 'claude-opus-5-5': { input: 4, output: 20, cacheRead: 0.2 },
8
+ 'claude-opus-5': { input: 5, output: 25 },
9
+ 'claude-opus-4-8': { input: 5, output: 25 },
10
+ 'claude-opus-4-7': { input: 5, output: 25 },
11
+ 'claude-opus-4-6': { input: 5, output: 25 },
12
+ 'claude-opus-4-5': { input: 5, output: 25 },
13
+ 'claude-opus-4-1': { input: 15, output: 75 },
14
+ 'claude-opus-4': { input: 15, output: 75 },
15
+ 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.2 },
16
+ 'claude-sonnet-5': { input: 2, output: 10, cacheRead: 0.2 },
17
+ 'claude-sonnet-4-6': { input: 3, output: 15 },
18
+ 'claude-sonnet-4-5': { input: 3, output: 15 },
19
+ 'claude-sonnet-4': { input: 3, output: 15 },
20
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5 },
21
+ 'claude-haiku-4-5': { input: 1, output: 5 },
22
+ 'claude-3-5-haiku': { input: 0.8, output: 4 },
23
+ };
24
+ /** Claude Haiku 5.5 bills prompts above 100K tokens at a higher rate. */
25
+ const HAIKU_5_5_LONG = { input: 0.5, output: 2.5 };
26
+ const HAIKU_5_5_LONG_AFTER = 100_000;
27
+ /** Fast mode bills 2x the standard rate (Opus 5.5: $8 / $40). */
28
+ const FAST_MULTIPLIER = 2;
29
+ /** `us.anthropic.claude-opus-4-8-v1:0`, `claude-sonnet-4-5@20250929`, `claude-opus-4-1-20250805` → canonical id. */
30
+ export function normalizeModel(model) {
31
+ return model
32
+ .toLowerCase()
33
+ .replace(/\[.*?\]$/, '')
34
+ .replace(/^(?:[a-z]{2,4}\.)?anthropic\./, '')
35
+ .replace(/@.*$/, '')
36
+ .replace(/-v\d+(?::\d+)?$/, '')
37
+ .replace(/-\d{8}$/, '');
38
+ }
39
+ export function priceFor(model) {
40
+ const id = normalizeModel(model);
41
+ let best;
42
+ for (const key of Object.keys(PRICES)) {
43
+ if ((id === key || id.startsWith(`${key}-`)) && (!best || key.length > best.length))
44
+ best = key;
45
+ }
46
+ return best ? PRICES[best] : undefined;
47
+ }
48
+ /** Cost in USD of one API response, or undefined when the model has no known price. */
49
+ export function costOf(model, usage) {
50
+ let price = priceFor(model);
51
+ if (!price)
52
+ return undefined;
53
+ const input = usage.input_tokens ?? 0;
54
+ const output = usage.output_tokens ?? 0;
55
+ const cacheRead = usage.cache_read_input_tokens ?? 0;
56
+ const cacheWrite = usage.cache_creation_input_tokens ?? 0;
57
+ const write1h = usage.cache_creation?.ephemeral_1h_input_tokens ?? 0;
58
+ const write5m = usage.cache_creation ? (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) : cacheWrite;
59
+ if (normalizeModel(model).startsWith('claude-haiku-5-5') && input + cacheRead + cacheWrite > HAIKU_5_5_LONG_AFTER) {
60
+ price = HAIKU_5_5_LONG;
61
+ }
62
+ const readRate = price.cacheRead ?? price.input * 0.1;
63
+ const dollars = (input * price.input + output * price.output + cacheRead * readRate + write5m * price.input * 1.25 + write1h * price.input * 2) /
64
+ 1_000_000;
65
+ return usage.speed === 'fast' ? dollars * FAST_MULTIPLIER : dollars;
66
+ }
package/dist/report.js ADDED
@@ -0,0 +1,349 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { homeDir } from './paths.js';
4
+ import { costOf, normalizeModel } from './pricing.js';
5
+ import { UsageError } from './env.js';
6
+ export const GROUPS = ['project', 'model', 'branch', 'day', 'session'];
7
+ const emptySplit = () => ({ input: 0, output: 0, cacheWrite: 0, cacheRead: 0 });
8
+ /** Where Claude Code keeps its session logs: $CLAUDE_CONFIG_DIR (comma-separated), else ~/.claude and ~/.config/claude. */
9
+ export function logDirs() {
10
+ const configured = process.env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
11
+ const bases = configured?.length ? configured : [path.join(homeDir(), '.claude'), path.join(homeDir(), '.config', 'claude')];
12
+ return bases.map((b) => path.join(b, 'projects')).filter((d) => fs.existsSync(d));
13
+ }
14
+ function jsonlFiles(dir, out = []) {
15
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
16
+ const full = path.join(dir, entry.name);
17
+ if (entry.isDirectory())
18
+ jsonlFiles(full, out);
19
+ else if (entry.isFile() && entry.name.endsWith('.jsonl'))
20
+ out.push(full);
21
+ }
22
+ return out;
23
+ }
24
+ /** Maps a working directory to its repository root's name, so sub-folders of one repo count as one project. */
25
+ function projectResolver() {
26
+ const cache = new Map();
27
+ const home = homeDir();
28
+ return (cwd) => {
29
+ if (!cwd)
30
+ return '(unknown)';
31
+ const hit = cache.get(cwd);
32
+ if (hit)
33
+ return hit;
34
+ let label;
35
+ for (let dir = cwd;; dir = path.dirname(dir)) {
36
+ if (fs.existsSync(path.join(dir, '.git'))) {
37
+ label = path.basename(dir);
38
+ break;
39
+ }
40
+ if (dir === home || path.dirname(dir) === dir)
41
+ break;
42
+ }
43
+ label ??= cwd === home ? '~ (no repo)' : cwd.startsWith(`${home}${path.sep}`) ? `~${cwd.slice(home.length)}` : cwd;
44
+ cache.set(cwd, label);
45
+ return label;
46
+ };
47
+ }
48
+ function localDay(ms) {
49
+ const d = new Date(ms);
50
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
51
+ }
52
+ const ASSISTANT = Buffer.from('"type":"assistant"');
53
+ const USAGE = Buffer.from('"usage"');
54
+ /**
55
+ * Yields only the lines that can carry an API response's usage. Logs run to gigabytes, mostly tool
56
+ * output, so lines are filtered as bytes and only the matches are decoded: decoding every line was
57
+ * four times slower than reading the files.
58
+ */
59
+ async function* usageLines(file) {
60
+ let parts = [];
61
+ const emit = (line) => (line.indexOf(ASSISTANT) !== -1 && line.indexOf(USAGE) !== -1 ? line.toString('utf8') : undefined);
62
+ for await (const chunk of fs.createReadStream(file, { highWaterMark: 1 << 20 })) {
63
+ let start = 0;
64
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
65
+ const piece = chunk.subarray(start, nl);
66
+ const line = parts.length ? Buffer.concat([...parts, piece]) : piece;
67
+ parts = [];
68
+ start = nl + 1;
69
+ const text = emit(line);
70
+ if (text !== undefined)
71
+ yield text;
72
+ }
73
+ if (start < chunk.length)
74
+ parts.push(chunk.subarray(start));
75
+ }
76
+ if (parts.length) {
77
+ const text = emit(Buffer.concat(parts));
78
+ if (text !== undefined)
79
+ yield text;
80
+ }
81
+ }
82
+ async function readRequests(files, since, onProgress) {
83
+ const requests = new Map();
84
+ const project = projectResolver();
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;
91
+ for await (const line of usageLines(file)) {
92
+ let row;
93
+ try {
94
+ row = JSON.parse(line);
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ const message = row?.message;
100
+ const usage = message?.usage;
101
+ const model = message?.model;
102
+ if (row?.type !== 'assistant' || !usage || typeof model !== 'string' || model === '<synthetic>')
103
+ continue;
104
+ const at = Date.parse(row.timestamp);
105
+ if (Number.isNaN(at) || (since !== null && at < since))
106
+ continue;
107
+ // One API response is logged once per content block; the last copy carries the final usage.
108
+ const key = `${message.id ?? row.uuid}:${row.requestId ?? ''}`;
109
+ requests.set(key, {
110
+ model: normalizeModel(model),
111
+ cost: costOf(model, usage),
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
+ },
119
+ session: row.sessionId ?? file,
120
+ project: project(row.cwd),
121
+ branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
122
+ day: localDay(at),
123
+ at,
124
+ });
125
+ }
126
+ }
127
+ onProgress?.(totalBytes, totalBytes);
128
+ return requests;
129
+ }
130
+ export async function buildReport(opts = {}) {
131
+ const now = opts.now ?? new Date();
132
+ const days = opts.days ?? 30;
133
+ if (!opts.all && (!Number.isInteger(days) || days < 1))
134
+ throw new UsageError('--days must be a whole number of 1 or more.');
135
+ const by = opts.by ?? 'project';
136
+ if (!GROUPS.includes(by))
137
+ throw new UsageError(`--by must be one of: ${GROUPS.join(', ')}.`);
138
+ const start = new Date(now);
139
+ start.setHours(0, 0, 0, 0);
140
+ start.setDate(start.getDate() - (days - 1));
141
+ const since = opts.all ? null : start.getTime();
142
+ const dirs = opts.dirs ?? logDirs();
143
+ const files = dirs.flatMap((d) => jsonlFiles(d));
144
+ const requests = await readRequests(files, since, opts.onProgress);
145
+ const groups = new Map();
146
+ const unpriced = new Map();
147
+ const sessions = new Set();
148
+ let total = 0;
149
+ let tokens = 0;
150
+ let first = Infinity;
151
+ for (const r of requests.values()) {
152
+ if (r.cost === undefined) {
153
+ unpriced.set(r.model, (unpriced.get(r.model) ?? 0) + 1);
154
+ continue;
155
+ }
156
+ const key = by === 'model' ? r.model : r[by];
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
+ };
167
+ g.cost += r.cost;
168
+ g.requests += 1;
169
+ g.sessions.add(r.session);
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);
177
+ g.models.set(r.model, (g.models.get(r.model) ?? 0) + r.cost);
178
+ groups.set(key, g);
179
+ sessions.add(r.session);
180
+ total += r.cost;
181
+ tokens += r.tokens;
182
+ first = Math.min(first, r.at);
183
+ }
184
+ const rows = [...groups.entries()]
185
+ .map(([key, g]) => ({
186
+ key,
187
+ cost: g.cost,
188
+ share: total > 0 ? g.cost / total : 0,
189
+ requests: g.requests,
190
+ sessions: g.sessions.size,
191
+ tokens: g.tokens,
192
+ split: g.split,
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
+ : {}),
197
+ }))
198
+ .sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
199
+ return {
200
+ from: since !== null ? localDay(since) : Number.isFinite(first) ? localDay(first) : null,
201
+ to: localDay(now.getTime()),
202
+ by,
203
+ rows,
204
+ total: { cost: total, requests: [...groups.values()].reduce((n, g) => n + g.requests, 0), sessions: sessions.size, tokens },
205
+ unpriced: [...unpriced.entries()].map(([model, n]) => ({ model, requests: n })).sort((a, b) => b.requests - a.requests),
206
+ files: files.length,
207
+ };
208
+ }
209
+ const usd = (n) => `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
210
+ const compact = (n) => n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
211
+ const shortModel = (m) => m.replace(/^claude-/, '');
212
+ const style = (code) => (s) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
213
+ const bold = style('1');
214
+ const dim = style('2');
215
+ const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day', session: 'Session' };
216
+ const MAX_ROWS = 15;
217
+ export const CTA_URL = 'https://spendbyteam.com/?utm_source=cli&utm_medium=report';
218
+ export function renderReport(r) {
219
+ const out = [];
220
+ const range = r.from ? `${r.from} → ${r.to}` : 'no usage found';
221
+ out.push(`${bold('Claude Code spend on this machine')} ${dim(range)}`);
222
+ out.push(dim('At API list prices. On a Pro, Max or Team seat you pay a flat fee; this is what the same tokens cost on the API.'));
223
+ out.push('');
224
+ if (r.rows.length === 0) {
225
+ out.push(r.files === 0
226
+ ? 'No Claude Code session logs found (looked in ~/.claude/projects and ~/.config/claude/projects; set CLAUDE_CONFIG_DIR if yours live elsewhere).'
227
+ : 'No priced Claude Code usage in this period. Try --days=90 or --all.');
228
+ return out.join('\n');
229
+ }
230
+ if (r.by === 'session')
231
+ return renderSessions(r, out);
232
+ const shown = r.rows.slice(0, MAX_ROWS);
233
+ const rest = r.rows.slice(MAX_ROWS);
234
+ const showModel = r.by !== 'model';
235
+ const header = [HEADINGS[r.by], 'Cost', 'Share', 'Sessions', 'Tokens', ...(showModel ? ['Top model'] : [])];
236
+ const body = shown.map((row) => [
237
+ row.key,
238
+ usd(row.cost),
239
+ `${Math.round(row.share * 100)}%`,
240
+ String(row.sessions),
241
+ compact(row.tokens),
242
+ ...(showModel ? [shortModel(row.topModel)] : []),
243
+ ]);
244
+ if (rest.length) {
245
+ const cost = rest.reduce((n, x) => n + x.cost, 0);
246
+ body.push([`… ${rest.length} more`, usd(cost), `${Math.round((cost / r.total.cost) * 100)}%`, '', compact(rest.reduce((n, x) => n + x.tokens, 0)), ...(showModel ? [''] : [])]);
247
+ }
248
+ const totalRow = ['Total', usd(r.total.cost), '', String(r.total.sessions), compact(r.total.tokens), ...(showModel ? [''] : [])];
249
+ const table = [header, ...body, totalRow];
250
+ const firstWidth = Math.min(36, Math.max(...table.map((t) => t[0].length)));
251
+ const widths = header.map((_, i) => (i === 0 ? firstWidth : Math.max(...table.map((t) => t[i].length))));
252
+ const fmt = (cells) => cells
253
+ .map((c, i) => {
254
+ const cell = i === 0 && c.length > firstWidth ? `${c.slice(0, firstWidth - 1)}…` : c;
255
+ return i === 0 || (showModel && i === cells.length - 1) ? cell.padEnd(widths[i]) : cell.padStart(widths[i]);
256
+ })
257
+ .join(' ')
258
+ .trimEnd();
259
+ out.push(bold(fmt(header)));
260
+ for (const cells of body)
261
+ out.push(fmt(cells));
262
+ out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
263
+ out.push(bold(fmt(totalRow)));
264
+ return finish(r, out);
265
+ }
266
+ function finish(r, out) {
267
+ if (r.unpriced.length) {
268
+ out.push('');
269
+ out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
270
+ }
271
+ out.push('');
272
+ out.push(`This is one machine. To see it for your whole team, per project and client:`);
273
+ out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
274
+ return out.join('\n');
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
+ }
338
+ export async function report(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
+ }
347
+ console.log(opts.json ? JSON.stringify(r, null, 2) : renderReport(r));
348
+ return r;
349
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "spendbyteam",
3
- "version": "0.1.0",
4
- "description": "Connect Claude Code to SpendByTeam: metrics-only OpenTelemetry + a tiny branch/ticket context hook.",
3
+ "version": "0.2.1",
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",
7
7
  "repository": {
@@ -36,6 +36,8 @@
36
36
  "claude-code",
37
37
  "opentelemetry",
38
38
  "cost",
39
+ "usage",
40
+ "tokens",
39
41
  "spendbyteam"
40
42
  ],
41
43
  "devDependencies": {