spendbyteam 0.2.0 → 0.2.2

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
@@ -20,13 +20,19 @@ infra $118.40 11% 9 250.1M sonnet-5-5
20
20
  Total $1,086.20 112 2.4B
21
21
  ```
22
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.
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**.
24
+
25
+ **`report` makes no network calls at all.** It only reads those files and prints a table; you can run it with Wi-Fi off. The network code in this package belongs to `connect` and `init`, and runs only when you call them. On a work laptop you may prefer to pin a version instead of pulling the latest each time:
26
+
27
+ ```bash
28
+ npx spendbyteam@0.2.2 report
29
+ ``` Costs use Anthropic's API list prices, including cache reads, 5-minute and 1-hour cache writes, and fast mode.
24
30
 
25
31
  | Option | |
26
32
  |---|---|
27
33
  | `--days=N` | Last N days, including today (default 30) |
28
34
  | `--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) |
35
+ | `--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
36
  | `--json` | Machine-readable output |
31
37
 
32
38
  ## Track it for the whole team
package/dist/checks.js CHANGED
@@ -23,7 +23,7 @@ export function missingDeps(envPath) {
23
23
  return HOOK_DEPS.filter((d) => !which(d, envPath));
24
24
  }
25
25
  export function parseVersion(text) {
26
- const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
26
+ const m = /(\d{1,9})\.(\d{1,9})\.(\d{1,9})/.exec(text);
27
27
  if (!m)
28
28
  return undefined;
29
29
  return [Number(m[1]), Number(m[2]), Number(m[3])];
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/env.js CHANGED
@@ -25,7 +25,10 @@ export function normalizeEndpoint(endpoint) {
25
25
  if (url.username || url.password || url.search || url.hash) {
26
26
  throw new UsageError('--endpoint must not contain credentials, query or fragment.');
27
27
  }
28
- return url.toString().replace(/\/+$/, '');
28
+ let out = url.toString();
29
+ while (out.endsWith('/'))
30
+ out = out.slice(0, -1);
31
+ return out;
29
32
  }
30
33
  export function validateTeamId(teamId) {
31
34
  if (teamId === undefined)
package/dist/init.js CHANGED
@@ -60,7 +60,7 @@ export async function init(opts) {
60
60
  log.ok(`Wrote ${p.config} (mode 600)`);
61
61
  // 4. Hook script.
62
62
  fs.copyFileSync(bundledHookPath(), p.hook);
63
- fs.chmodSync(p.hook, 0o755);
63
+ fs.chmodSync(p.hook, 0o700); // only the user who runs Claude Code needs it
64
64
  log.ok(`Installed ${p.hook}`);
65
65
  // 5. Connectivity test.
66
66
  let pingResult;
package/dist/pricing.js CHANGED
@@ -28,11 +28,14 @@ const HAIKU_5_5_LONG_AFTER = 100_000;
28
28
  const FAST_MULTIPLIER = 2;
29
29
  /** `us.anthropic.claude-opus-4-8-v1:0`, `claude-sonnet-4-5@20250929`, `claude-opus-4-1-20250805` → canonical id. */
30
30
  export function normalizeModel(model) {
31
- return model
32
- .toLowerCase()
33
- .replace(/\[.*?\]$/, '')
31
+ let id = model.toLowerCase();
32
+ if (id.endsWith(']') && id.includes('['))
33
+ id = id.slice(0, id.lastIndexOf('['));
34
+ const at = id.indexOf('@');
35
+ if (at !== -1)
36
+ id = id.slice(0, at);
37
+ return id
34
38
  .replace(/^(?:[a-z]{2,4}\.)?anthropic\./, '')
35
- .replace(/@.*$/, '')
36
39
  .replace(/-v\d+(?::\d+)?$/, '')
37
40
  .replace(/-\d{8}$/, '');
38
41
  }
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,17 @@ 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();
84
+ // Earliest turn seen per session, inside the window or not, to tell when a session really began.
85
+ const sessionStart = new Map();
83
86
  const project = projectResolver();
84
- for (const file of files) {
85
- if (since !== null && fs.statSync(file).mtimeMs < since)
86
- continue;
87
+ const todo = files.map((file) => ({ file, stat: fs.statSync(file) })).filter(({ stat }) => since === null || stat.mtimeMs >= since);
88
+ const totalBytes = todo.reduce((n, f) => n + f.stat.size, 0);
89
+ let doneBytes = 0;
90
+ for (const { file, stat } of todo) {
91
+ onProgress?.(doneBytes, totalBytes);
92
+ doneBytes += stat.size;
87
93
  for await (const line of usageLines(file)) {
88
94
  let row;
89
95
  try {
@@ -98,7 +104,12 @@ async function readRequests(files, since) {
98
104
  if (row?.type !== 'assistant' || !usage || typeof model !== 'string' || model === '<synthetic>')
99
105
  continue;
100
106
  const at = Date.parse(row.timestamp);
101
- if (Number.isNaN(at) || (since !== null && at < since))
107
+ if (Number.isNaN(at))
108
+ continue;
109
+ const sessionId = row.sessionId ?? file;
110
+ if (at < (sessionStart.get(sessionId) ?? Infinity))
111
+ sessionStart.set(sessionId, at);
112
+ if (since !== null && at < since)
102
113
  continue;
103
114
  // One API response is logged once per content block; the last copy carries the final usage.
104
115
  const key = `${message.id ?? row.uuid}:${row.requestId ?? ''}`;
@@ -106,7 +117,13 @@ async function readRequests(files, since) {
106
117
  model: normalizeModel(model),
107
118
  cost: costOf(model, usage),
108
119
  tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0),
109
- session: row.sessionId ?? file,
120
+ split: {
121
+ input: usage.input_tokens ?? 0,
122
+ output: usage.output_tokens ?? 0,
123
+ cacheWrite: usage.cache_creation_input_tokens ?? 0,
124
+ cacheRead: usage.cache_read_input_tokens ?? 0,
125
+ },
126
+ session: sessionId,
110
127
  project: project(row.cwd),
111
128
  branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
112
129
  day: localDay(at),
@@ -114,7 +131,8 @@ async function readRequests(files, since) {
114
131
  });
115
132
  }
116
133
  }
117
- return requests;
134
+ onProgress?.(totalBytes, totalBytes);
135
+ return { requests, sessionStart };
118
136
  }
119
137
  export async function buildReport(opts = {}) {
120
138
  const now = opts.now ?? new Date();
@@ -130,7 +148,7 @@ export async function buildReport(opts = {}) {
130
148
  const since = opts.all ? null : start.getTime();
131
149
  const dirs = opts.dirs ?? logDirs();
132
150
  const files = dirs.flatMap((d) => jsonlFiles(d));
133
- const requests = await readRequests(files, since);
151
+ const { requests, sessionStart } = await readRequests(files, since, opts.onProgress);
134
152
  const groups = new Map();
135
153
  const unpriced = new Map();
136
154
  const sessions = new Set();
@@ -143,11 +161,26 @@ export async function buildReport(opts = {}) {
143
161
  continue;
144
162
  }
145
163
  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() };
164
+ const g = groups.get(key) ?? {
165
+ cost: 0,
166
+ requests: 0,
167
+ sessions: new Set(),
168
+ tokens: 0,
169
+ split: emptySplit(),
170
+ models: new Map(),
171
+ first: Infinity,
172
+ projects: new Map(),
173
+ };
147
174
  g.cost += r.cost;
148
175
  g.requests += 1;
149
176
  g.sessions.add(r.session);
150
177
  g.tokens += r.tokens;
178
+ g.split.input += r.split.input;
179
+ g.split.output += r.split.output;
180
+ g.split.cacheWrite += r.split.cacheWrite;
181
+ g.split.cacheRead += r.split.cacheRead;
182
+ g.first = Math.min(g.first, r.at);
183
+ g.projects.set(r.project, (g.projects.get(r.project) ?? 0) + r.cost);
151
184
  g.models.set(r.model, (g.models.get(r.model) ?? 0) + r.cost);
152
185
  groups.set(key, g);
153
186
  sessions.add(r.session);
@@ -163,7 +196,15 @@ export async function buildReport(opts = {}) {
163
196
  requests: g.requests,
164
197
  sessions: g.sessions.size,
165
198
  tokens: g.tokens,
199
+ split: g.split,
166
200
  topModel: [...g.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
201
+ ...(by === 'session'
202
+ ? {
203
+ startedAt: new Date(sessionStart.get(key) ?? g.first).toISOString(),
204
+ startedBeforeWindow: since !== null && (sessionStart.get(key) ?? g.first) < since,
205
+ project: [...g.projects.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
206
+ }
207
+ : {}),
167
208
  }))
168
209
  .sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
169
210
  return {
@@ -182,7 +223,7 @@ const shortModel = (m) => m.replace(/^claude-/, '');
182
223
  const style = (code) => (s) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
183
224
  const bold = style('1');
184
225
  const dim = style('2');
185
- const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day' };
226
+ const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day', session: 'Session' };
186
227
  const MAX_ROWS = 15;
187
228
  export const CTA_URL = 'https://spendbyteam.com/?utm_source=cli&utm_medium=report';
188
229
  export function renderReport(r) {
@@ -197,6 +238,8 @@ export function renderReport(r) {
197
238
  : 'No priced Claude Code usage in this period. Try --days=90 or --all.');
198
239
  return out.join('\n');
199
240
  }
241
+ if (r.by === 'session')
242
+ return renderSessions(r, out);
200
243
  const shown = r.rows.slice(0, MAX_ROWS);
201
244
  const rest = r.rows.slice(MAX_ROWS);
202
245
  const showModel = r.by !== 'model';
@@ -229,6 +272,9 @@ export function renderReport(r) {
229
272
  out.push(fmt(cells));
230
273
  out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
231
274
  out.push(bold(fmt(totalRow)));
275
+ return finish(r, out);
276
+ }
277
+ function finish(r, out) {
232
278
  if (r.unpriced.length) {
233
279
  out.push('');
234
280
  out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
@@ -238,8 +284,79 @@ export function renderReport(r) {
238
284
  out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
239
285
  return out.join('\n');
240
286
  }
287
+ function localDateTime(iso) {
288
+ const d = new Date(iso);
289
+ const pad = (n) => String(n).padStart(2, '0');
290
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
291
+ }
292
+ /** --by=session: the most expensive sessions, with where their tokens went. */
293
+ function renderSessions(r, out) {
294
+ const shown = r.rows.slice(0, MAX_ROWS);
295
+ const header = [' Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
296
+ const body = shown.map((row) => [
297
+ `${row.startedBeforeWindow ? '≤' : ' '}${localDateTime(row.startedAt)}`,
298
+ row.project ?? '',
299
+ usd(row.cost),
300
+ String(row.requests),
301
+ compact(row.split.input),
302
+ compact(row.split.output),
303
+ compact(row.split.cacheWrite),
304
+ compact(row.split.cacheRead),
305
+ shortModel(row.topModel),
306
+ ]);
307
+ const left = new Set([0, 1, 8]);
308
+ const projectWidth = Math.min(28, Math.max(...[header, ...body].map((t) => t[1].length)));
309
+ const widths = header.map((_, i) => (i === 1 ? projectWidth : Math.max(...[header, ...body].map((t) => t[i].length))));
310
+ const fmt = (cells) => cells
311
+ .map((c, i) => {
312
+ const cell = i === 1 && c.length > projectWidth ? `${c.slice(0, projectWidth - 1)}…` : c;
313
+ return left.has(i) ? cell.padEnd(widths[i]) : cell.padStart(widths[i]);
314
+ })
315
+ .join(' ')
316
+ .trimEnd();
317
+ out.push(bold(fmt(header)));
318
+ for (const cells of body)
319
+ out.push(fmt(cells));
320
+ out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
321
+ const rest = r.rows.length - shown.length;
322
+ out.push(`${bold(`${r.rows.length} sessions, ${usd(r.total.cost)}`)}${rest > 0 ? dim(` (top ${shown.length} shown; --json for all)`) : ''}`);
323
+ if (shown.some((row) => row.startedBeforeWindow))
324
+ out.push(dim('≤ started before this window; only its turns inside the window are counted.'));
325
+ out.push(dim('Long sessions re-read their whole context every turn; /clear resets it.'));
326
+ return finish(r, out);
327
+ }
328
+ /** A "Reading logs… 42%" line on stderr while reading, only on a terminal and never with --json. */
329
+ function progressLine() {
330
+ if (!process.stderr.isTTY)
331
+ return { clear: () => { } };
332
+ let shown = false;
333
+ let last = -1;
334
+ return {
335
+ onProgress: (done, total) => {
336
+ if (total < 50_000_000)
337
+ return; // small log folders finish before a line is worth showing
338
+ const pct = Math.floor((done / total) * 100);
339
+ if (pct === last)
340
+ return;
341
+ last = pct;
342
+ shown = true;
343
+ process.stderr.write(`\r\x1b[2KReading ${(total / 1e9).toFixed(1)} GB of Claude Code logs… ${pct}%`);
344
+ },
345
+ clear: () => {
346
+ if (shown)
347
+ process.stderr.write('\r\x1b[2K');
348
+ },
349
+ };
350
+ }
241
351
  export async function report(opts = {}) {
242
- const r = await buildReport(opts);
352
+ const progress = progressLine();
353
+ let r;
354
+ try {
355
+ r = await buildReport({ onProgress: progress.onProgress, ...opts });
356
+ }
357
+ finally {
358
+ progress.clear();
359
+ }
243
360
  console.log(opts.json ? JSON.stringify(r, null, 2) : renderReport(r));
244
361
  return r;
245
362
  }
package/hook/hook.sh CHANGED
@@ -2,23 +2,24 @@
2
2
  # SpendByTeam context hook — açık kaynak, sadece aşağıdaki alanları gönderir.
3
3
  set -u
4
4
  CFG="$HOME/.spendbyteam/config.json"
5
- [ -r "$CFG" ] || exit 0
5
+ [[ -r "$CFG" ]] || exit 0
6
6
 
7
7
  INPUT=$(cat)
8
8
  SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty')
9
9
  CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty')
10
10
  EVENT=$(printf '%s' "$INPUT" | jq -r '.hook_event_name // empty')
11
- [ -n "$SESSION_ID" ] && [ -n "$CWD" ] || exit 0
11
+ [[ -n "$SESSION_ID" ]] && [[ -n "$CWD" ]] || exit 0
12
12
 
13
13
  TOKEN=$(jq -r '.token // empty' "$CFG"); ENDPOINT=$(jq -r '.endpoint // empty' "$CFG")
14
14
  # Token yalnızca güvenli karakterler (header enjeksiyonu yok); endpoint https (http sadece localhost).
15
15
  printf '%s' "$TOKEN" | grep -qE '^sbt_ing_[A-Za-z0-9_-]{1,120}$' || exit 0
16
- printf '%s' "$ENDPOINT" | grep -qE '^(https://[^[:space:]]+|http://(localhost|127\.0\.0\.1|\[::1\])(:[0-9]+)?(/[^[:space:]]*)?)$' || exit 0
16
+ # http:// is accepted for localhost only (local development); anything else must be https. NOSONAR
17
+ printf '%s' "$ENDPOINT" | grep -qE '^(https://[^[:space:]]+|http://(localhost|127\.0\.0\.1|\[::1\])(:[0-9]+)?(/[^[:space:]]*)?)$' || exit 0 # NOSONAR
17
18
 
18
19
  REMOTE=$(git -C "$CWD" config --get remote.origin.url 2>/dev/null || true)
19
20
  # Commit'siz repo ve detached HEAD'de rev-parse "HEAD" döner: branch yok say.
20
21
  BRANCH=$(git -C "$CWD" rev-parse --abbrev-ref HEAD 2>/dev/null) || BRANCH=""
21
- [ "$BRANCH" = "HEAD" ] && BRANCH=""
22
+ [[ "$BRANCH" = "HEAD" ]] && BRANCH=""
22
23
  TICKET=$(printf '%s' "$BRANCH" | grep -oE '[A-Z][A-Z0-9]+-[0-9]+' | head -1 || true)
23
24
 
24
25
  # Remote URL'den kimlik bilgisini (scheme://user:token@host/...), query ve fragment'ı temizle.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spendbyteam",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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",