spendbyteam 0.2.1 → 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,7 +20,13 @@ 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
  |---|---|
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
@@ -81,6 +81,8 @@ async function* usageLines(file) {
81
81
  }
82
82
  async function readRequests(files, since, onProgress) {
83
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();
84
86
  const project = projectResolver();
85
87
  const todo = files.map((file) => ({ file, stat: fs.statSync(file) })).filter(({ stat }) => since === null || stat.mtimeMs >= since);
86
88
  const totalBytes = todo.reduce((n, f) => n + f.stat.size, 0);
@@ -102,7 +104,12 @@ async function readRequests(files, since, onProgress) {
102
104
  if (row?.type !== 'assistant' || !usage || typeof model !== 'string' || model === '<synthetic>')
103
105
  continue;
104
106
  const at = Date.parse(row.timestamp);
105
- 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)
106
113
  continue;
107
114
  // One API response is logged once per content block; the last copy carries the final usage.
108
115
  const key = `${message.id ?? row.uuid}:${row.requestId ?? ''}`;
@@ -116,7 +123,7 @@ async function readRequests(files, since, onProgress) {
116
123
  cacheWrite: usage.cache_creation_input_tokens ?? 0,
117
124
  cacheRead: usage.cache_read_input_tokens ?? 0,
118
125
  },
119
- session: row.sessionId ?? file,
126
+ session: sessionId,
120
127
  project: project(row.cwd),
121
128
  branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
122
129
  day: localDay(at),
@@ -125,7 +132,7 @@ async function readRequests(files, since, onProgress) {
125
132
  }
126
133
  }
127
134
  onProgress?.(totalBytes, totalBytes);
128
- return requests;
135
+ return { requests, sessionStart };
129
136
  }
130
137
  export async function buildReport(opts = {}) {
131
138
  const now = opts.now ?? new Date();
@@ -141,7 +148,7 @@ export async function buildReport(opts = {}) {
141
148
  const since = opts.all ? null : start.getTime();
142
149
  const dirs = opts.dirs ?? logDirs();
143
150
  const files = dirs.flatMap((d) => jsonlFiles(d));
144
- const requests = await readRequests(files, since, opts.onProgress);
151
+ const { requests, sessionStart } = await readRequests(files, since, opts.onProgress);
145
152
  const groups = new Map();
146
153
  const unpriced = new Map();
147
154
  const sessions = new Set();
@@ -192,7 +199,11 @@ export async function buildReport(opts = {}) {
192
199
  split: g.split,
193
200
  topModel: [...g.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
194
201
  ...(by === 'session'
195
- ? { startedAt: new Date(g.first).toISOString(), project: [...g.projects.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '' }
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
+ }
196
207
  : {}),
197
208
  }))
198
209
  .sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
@@ -281,9 +292,9 @@ function localDateTime(iso) {
281
292
  /** --by=session: the most expensive sessions, with where their tokens went. */
282
293
  function renderSessions(r, out) {
283
294
  const shown = r.rows.slice(0, MAX_ROWS);
284
- const header = ['Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
295
+ const header = [' Started', 'Project', 'Cost', 'Turns', 'Input', 'Output', 'Cache write', 'Cache read', 'Model'];
285
296
  const body = shown.map((row) => [
286
- localDateTime(row.startedAt),
297
+ `${row.startedBeforeWindow ? '≤' : ' '}${localDateTime(row.startedAt)}`,
287
298
  row.project ?? '',
288
299
  usd(row.cost),
289
300
  String(row.requests),
@@ -309,7 +320,9 @@ function renderSessions(r, out) {
309
320
  out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
310
321
  const rest = r.rows.length - shown.length;
311
322
  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.'));
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.'));
313
326
  return finish(r, out);
314
327
  }
315
328
  /** 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.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",