spendbyteam 0.2.1 → 0.2.3

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,7 +20,23 @@ 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.3 report
29
+ ```
30
+
31
+ Costs use Anthropic's API list prices, including cache reads, 5-minute and 1-hour cache writes, and fast mode.
32
+
33
+ **Claude Code deletes these logs after 30 days by default** ([`cleanupPeriodDays`](https://code.claude.com/docs/en/settings)), so `report` can never look further back than that. It tells you when your logs are on the default and shows the oldest one left. To keep them, add this to `~/.claude/settings.json`:
34
+
35
+ ```json
36
+ { "cleanupPeriodDays": 3650 }
37
+ ```
38
+
39
+ If your organization sets `cleanupPeriodDays` in managed settings, that value wins and `report` says so.
24
40
 
25
41
  | Option | |
26
42
  |---|---|
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/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
@@ -5,6 +5,37 @@ import { costOf, normalizeModel } from './pricing.js';
5
5
  import { UsageError } from './env.js';
6
6
  export const GROUPS = ['project', 'model', 'branch', 'day', 'session'];
7
7
  const emptySplit = () => ({ input: 0, output: 0, cacheWrite: 0, cacheRead: 0 });
8
+ /** Claude Code's documented default for cleanupPeriodDays. */
9
+ export const DEFAULT_CLEANUP_DAYS = 30;
10
+ function readCleanupDays(file) {
11
+ try {
12
+ const v = JSON.parse(fs.readFileSync(file, 'utf8'))?.cleanupPeriodDays;
13
+ return typeof v === 'number' && Number.isFinite(v) && v >= 1 ? v : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ /** Managed settings win over user settings; without either, Claude Code uses 30 days. */
20
+ export function cleanupPeriod(env = process.env, platform = process.platform) {
21
+ const managed = env.SPENDBYTEAM_MANAGED_SETTINGS ??
22
+ (platform === 'darwin'
23
+ ? '/Library/Application Support/ClaudeCode/managed-settings.json'
24
+ : platform === 'win32'
25
+ ? 'C:\\Program Files\\ClaudeCode\\managed-settings.json'
26
+ : '/etc/claude-code/managed-settings.json');
27
+ const m = readCleanupDays(managed);
28
+ if (m !== undefined)
29
+ return { days: m, source: 'managed' };
30
+ const configured = env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
31
+ const bases = configured?.length ? configured : [path.join(homeDir(), '.claude')];
32
+ for (const b of bases) {
33
+ const u = readCleanupDays(path.join(b, 'settings.json'));
34
+ if (u !== undefined)
35
+ return { days: u, source: 'settings' };
36
+ }
37
+ return { days: DEFAULT_CLEANUP_DAYS, source: 'default' };
38
+ }
8
39
  /** Where Claude Code keeps its session logs: $CLAUDE_CONFIG_DIR (comma-separated), else ~/.claude and ~/.config/claude. */
9
40
  export function logDirs() {
10
41
  const configured = process.env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
@@ -81,6 +112,8 @@ async function* usageLines(file) {
81
112
  }
82
113
  async function readRequests(files, since, onProgress) {
83
114
  const requests = new Map();
115
+ // Earliest turn seen per session, inside the window or not, to tell when a session really began.
116
+ const sessionStart = new Map();
84
117
  const project = projectResolver();
85
118
  const todo = files.map((file) => ({ file, stat: fs.statSync(file) })).filter(({ stat }) => since === null || stat.mtimeMs >= since);
86
119
  const totalBytes = todo.reduce((n, f) => n + f.stat.size, 0);
@@ -102,7 +135,12 @@ async function readRequests(files, since, onProgress) {
102
135
  if (row?.type !== 'assistant' || !usage || typeof model !== 'string' || model === '<synthetic>')
103
136
  continue;
104
137
  const at = Date.parse(row.timestamp);
105
- if (Number.isNaN(at) || (since !== null && at < since))
138
+ if (Number.isNaN(at))
139
+ continue;
140
+ const sessionId = row.sessionId ?? file;
141
+ if (at < (sessionStart.get(sessionId) ?? Infinity))
142
+ sessionStart.set(sessionId, at);
143
+ if (since !== null && at < since)
106
144
  continue;
107
145
  // One API response is logged once per content block; the last copy carries the final usage.
108
146
  const key = `${message.id ?? row.uuid}:${row.requestId ?? ''}`;
@@ -116,7 +154,7 @@ async function readRequests(files, since, onProgress) {
116
154
  cacheWrite: usage.cache_creation_input_tokens ?? 0,
117
155
  cacheRead: usage.cache_read_input_tokens ?? 0,
118
156
  },
119
- session: row.sessionId ?? file,
157
+ session: sessionId,
120
158
  project: project(row.cwd),
121
159
  branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
122
160
  day: localDay(at),
@@ -125,7 +163,7 @@ async function readRequests(files, since, onProgress) {
125
163
  }
126
164
  }
127
165
  onProgress?.(totalBytes, totalBytes);
128
- return requests;
166
+ return { requests, sessionStart };
129
167
  }
130
168
  export async function buildReport(opts = {}) {
131
169
  const now = opts.now ?? new Date();
@@ -141,7 +179,10 @@ export async function buildReport(opts = {}) {
141
179
  const since = opts.all ? null : start.getTime();
142
180
  const dirs = opts.dirs ?? logDirs();
143
181
  const files = dirs.flatMap((d) => jsonlFiles(d));
144
- const requests = await readRequests(files, since, opts.onProgress);
182
+ const { requests, sessionStart } = await readRequests(files, since, opts.onProgress);
183
+ let oldestMs = Infinity;
184
+ for (const f of files)
185
+ oldestMs = Math.min(oldestMs, fs.statSync(f).mtimeMs);
145
186
  const groups = new Map();
146
187
  const unpriced = new Map();
147
188
  const sessions = new Set();
@@ -192,7 +233,11 @@ export async function buildReport(opts = {}) {
192
233
  split: g.split,
193
234
  topModel: [...g.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
194
235
  ...(by === 'session'
195
- ? { startedAt: new Date(g.first).toISOString(), project: [...g.projects.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '' }
236
+ ? {
237
+ startedAt: new Date(sessionStart.get(key) ?? g.first).toISOString(),
238
+ startedBeforeWindow: since !== null && (sessionStart.get(key) ?? g.first) < since,
239
+ project: [...g.projects.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
240
+ }
196
241
  : {}),
197
242
  }))
198
243
  .sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
@@ -204,6 +249,7 @@ export async function buildReport(opts = {}) {
204
249
  total: { cost: total, requests: [...groups.values()].reduce((n, g) => n + g.requests, 0), sessions: sessions.size, tokens },
205
250
  unpriced: [...unpriced.entries()].map(([model, n]) => ({ model, requests: n })).sort((a, b) => b.requests - a.requests),
206
251
  files: files.length,
252
+ retention: { ...cleanupPeriod(), oldestLog: Number.isFinite(oldestMs) ? localDay(oldestMs) : null },
207
253
  };
208
254
  }
209
255
  const usd = (n) => `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
@@ -263,13 +309,25 @@ export function renderReport(r) {
263
309
  out.push(bold(fmt(totalRow)));
264
310
  return finish(r, out);
265
311
  }
312
+ /** Claude Code deletes session logs after cleanupPeriodDays (30 by default); say so, since this report can't see past it. */
313
+ export function retentionNote(t) {
314
+ if (t.days > 90)
315
+ return [];
316
+ const since = t.oldestLog ? `, so the oldest log left on this machine is from ${t.oldestLog}` : '';
317
+ const why = t.source === 'default' ? 'by default' : t.source === 'managed' ? 'set by your organization' : 'set in your settings.json';
318
+ const lines = ['', `${bold('Heads-up:')} Claude Code deletes these logs after ${t.days} days (${why})${since}.`];
319
+ if (t.source !== 'managed')
320
+ lines.push(dim(`To keep them, add "cleanupPeriodDays": 3650 to ~/.claude/settings.json.`));
321
+ return lines;
322
+ }
266
323
  function finish(r, out) {
267
324
  if (r.unpriced.length) {
268
325
  out.push('');
269
326
  out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
270
327
  }
328
+ out.push(...retentionNote(r.retention));
271
329
  out.push('');
272
- out.push(`This is one machine. To see it for your whole team, per project and client:`);
330
+ out.push(`This is one machine. To see it for your whole team, per project and client, with up to 13 months of history:`);
273
331
  out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
274
332
  return out.join('\n');
275
333
  }
@@ -281,9 +339,9 @@ function localDateTime(iso) {
281
339
  /** --by=session: the most expensive sessions, with where their tokens went. */
282
340
  function renderSessions(r, out) {
283
341
  const shown = r.rows.slice(0, MAX_ROWS);
284
- const header = ['Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
342
+ const header = [' Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
285
343
  const body = shown.map((row) => [
286
- localDateTime(row.startedAt),
344
+ `${row.startedBeforeWindow ? '≤' : ' '}${localDateTime(row.startedAt)}`,
287
345
  row.project ?? '',
288
346
  usd(row.cost),
289
347
  String(row.requests),
@@ -309,7 +367,9 @@ function renderSessions(r, out) {
309
367
  out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
310
368
  const rest = r.rows.length - shown.length;
311
369
  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.'));
370
+ if (shown.some((row) => row.startedBeforeWindow))
371
+ out.push(dim('≤ started before this window; only its turns inside the window are counted.'));
372
+ out.push(dim('Long sessions re-read their whole context every turn; /clear resets it.'));
313
373
  return finish(r, out);
314
374
  }
315
375
  /** A "Reading logs… 42%" line on stderr while reading, only on a terminal and never with --json. */
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.1",
3
+ "version": "0.2.3",
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",