spendbyteam 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +176 -2
- package/dist/checks.js +81 -0
- package/dist/cli.js +128 -0
- package/dist/connect.js +124 -0
- package/dist/constants.js +11 -0
- package/dist/doctor.js +71 -0
- package/dist/env.js +90 -0
- package/dist/fsutil.js +51 -0
- package/dist/init.js +76 -0
- package/dist/log.js +11 -0
- package/dist/managed.js +11 -0
- package/dist/paths.js +26 -0
- package/dist/pricing.js +66 -0
- package/dist/report.js +245 -0
- package/dist/settings.js +164 -0
- package/dist/state.js +35 -0
- package/dist/status.js +83 -0
- package/dist/uninstall.js +34 -0
- package/hook/hook.sh +37 -0
- package/package.json +46 -4
package/dist/env.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { DEFAULT_ENDPOINT, TOKEN_RE } from './constants.js';
|
|
2
|
+
export function validateToken(token) {
|
|
3
|
+
if (!token)
|
|
4
|
+
throw new UsageError('Missing --token (get it from the SpendByTeam panel: sbt_ing_...).');
|
|
5
|
+
const t = token.trim();
|
|
6
|
+
if (!TOKEN_RE.test(t)) {
|
|
7
|
+
throw new UsageError('Invalid token: expected an ingest token like "sbt_ing_..." (letters, digits, "_" or "-").');
|
|
8
|
+
}
|
|
9
|
+
return t;
|
|
10
|
+
}
|
|
11
|
+
/** Normalises the ingest endpoint. Only https is allowed, except http for localhost (development). */
|
|
12
|
+
export function normalizeEndpoint(endpoint) {
|
|
13
|
+
const raw = (endpoint ?? DEFAULT_ENDPOINT).trim();
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(raw);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new UsageError(`Invalid --endpoint: ${raw}`);
|
|
20
|
+
}
|
|
21
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
22
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
|
|
23
|
+
throw new UsageError('--endpoint must use https:// (http:// is only allowed for localhost).');
|
|
24
|
+
}
|
|
25
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
26
|
+
throw new UsageError('--endpoint must not contain credentials, query or fragment.');
|
|
27
|
+
}
|
|
28
|
+
return url.toString().replace(/\/+$/, '');
|
|
29
|
+
}
|
|
30
|
+
export function validateTeamId(teamId) {
|
|
31
|
+
if (teamId === undefined)
|
|
32
|
+
return undefined;
|
|
33
|
+
const t = teamId.trim();
|
|
34
|
+
// OTEL_RESOURCE_ATTRIBUTES is a comma separated k=v list; keep the value static and simple (§3.3).
|
|
35
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(t)) {
|
|
36
|
+
throw new UsageError('--team-id may only contain letters, digits, ".", "_" or "-" (max 64 chars).');
|
|
37
|
+
}
|
|
38
|
+
return t;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The OTel env block from TECHNICAL.md §3.1. Metrics only: logs and traces exporters are
|
|
42
|
+
* explicitly "none" and content flags (OTEL_LOG_USER_PROMPTS etc.) are never touched.
|
|
43
|
+
*/
|
|
44
|
+
export function buildEnv(opts) {
|
|
45
|
+
const token = validateToken(opts.token);
|
|
46
|
+
const endpoint = normalizeEndpoint(opts.endpoint);
|
|
47
|
+
const teamId = validateTeamId(opts.teamId);
|
|
48
|
+
const env = {
|
|
49
|
+
CLAUDE_CODE_ENABLE_TELEMETRY: '1',
|
|
50
|
+
OTEL_METRICS_EXPORTER: 'otlp',
|
|
51
|
+
OTEL_LOGS_EXPORTER: 'none',
|
|
52
|
+
OTEL_TRACES_EXPORTER: 'none',
|
|
53
|
+
OTEL_EXPORTER_OTLP_PROTOCOL: 'http/json',
|
|
54
|
+
OTEL_EXPORTER_OTLP_ENDPOINT: endpoint,
|
|
55
|
+
OTEL_EXPORTER_OTLP_HEADERS: `Authorization=Bearer ${token}`,
|
|
56
|
+
OTEL_METRICS_INCLUDE_SESSION_ID: 'true',
|
|
57
|
+
OTEL_METRICS_INCLUDE_REPOSITORY: 'true',
|
|
58
|
+
OTEL_METRICS_INCLUDE_VERSION: 'true',
|
|
59
|
+
OTEL_METRIC_EXPORT_INTERVAL: '60000',
|
|
60
|
+
};
|
|
61
|
+
if (teamId)
|
|
62
|
+
env.OTEL_RESOURCE_ATTRIBUTES = `team.id=${teamId}`;
|
|
63
|
+
return env;
|
|
64
|
+
}
|
|
65
|
+
/** Keys we may write; used by uninstall/status even when the original state file is gone. */
|
|
66
|
+
export const MANAGED_ENV_KEYS = [
|
|
67
|
+
'CLAUDE_CODE_ENABLE_TELEMETRY',
|
|
68
|
+
'OTEL_METRICS_EXPORTER',
|
|
69
|
+
'OTEL_LOGS_EXPORTER',
|
|
70
|
+
'OTEL_TRACES_EXPORTER',
|
|
71
|
+
'OTEL_EXPORTER_OTLP_PROTOCOL',
|
|
72
|
+
'OTEL_EXPORTER_OTLP_ENDPOINT',
|
|
73
|
+
'OTEL_EXPORTER_OTLP_HEADERS',
|
|
74
|
+
'OTEL_METRICS_INCLUDE_SESSION_ID',
|
|
75
|
+
'OTEL_METRICS_INCLUDE_REPOSITORY',
|
|
76
|
+
'OTEL_METRICS_INCLUDE_VERSION',
|
|
77
|
+
'OTEL_METRIC_EXPORT_INTERVAL',
|
|
78
|
+
'OTEL_RESOURCE_ATTRIBUTES',
|
|
79
|
+
];
|
|
80
|
+
export function maskToken(token) {
|
|
81
|
+
if (token.length <= 12)
|
|
82
|
+
return 'sbt_ing_****';
|
|
83
|
+
return `sbt_ing_****${token.slice(-4)}`;
|
|
84
|
+
}
|
|
85
|
+
export class UsageError extends Error {
|
|
86
|
+
constructor(message) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.name = 'UsageError';
|
|
89
|
+
}
|
|
90
|
+
}
|
package/dist/fsutil.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export class JsonFileError extends Error {
|
|
4
|
+
}
|
|
5
|
+
/** Returns undefined when the file does not exist; throws (never clobbers) when it is not valid JSON. */
|
|
6
|
+
export function readJsonObject(file) {
|
|
7
|
+
let text;
|
|
8
|
+
try {
|
|
9
|
+
text = fs.readFileSync(file, 'utf8');
|
|
10
|
+
}
|
|
11
|
+
catch (err) {
|
|
12
|
+
if (err.code === 'ENOENT')
|
|
13
|
+
return undefined;
|
|
14
|
+
throw err;
|
|
15
|
+
}
|
|
16
|
+
if (text.trim() === '')
|
|
17
|
+
return {};
|
|
18
|
+
let data;
|
|
19
|
+
try {
|
|
20
|
+
data = JSON.parse(text);
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
throw new JsonFileError(`${file} is not valid JSON (${err.message}). Fix it first; nothing was changed.`);
|
|
24
|
+
}
|
|
25
|
+
if (!isPlainObject(data)) {
|
|
26
|
+
throw new JsonFileError(`${file} must contain a JSON object. Fix it first; nothing was changed.`);
|
|
27
|
+
}
|
|
28
|
+
return data;
|
|
29
|
+
}
|
|
30
|
+
export function isPlainObject(v) {
|
|
31
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
32
|
+
}
|
|
33
|
+
/** Write via temp file + rename so a crash never leaves a half-written settings file. */
|
|
34
|
+
export function writeFileAtomic(file, content, mode) {
|
|
35
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
36
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
37
|
+
fs.writeFileSync(tmp, content, { mode });
|
|
38
|
+
fs.chmodSync(tmp, mode);
|
|
39
|
+
fs.renameSync(tmp, file);
|
|
40
|
+
}
|
|
41
|
+
export function fileMode(file) {
|
|
42
|
+
try {
|
|
43
|
+
return fs.statSync(file).mode & 0o777;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function toJson(data) {
|
|
50
|
+
return `${JSON.stringify(data, null, 2)}\n`;
|
|
51
|
+
}
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { buildEnv, normalizeEndpoint, validateToken } from './env.js';
|
|
3
|
+
import { bundledHookPath, paths } from './paths.js';
|
|
4
|
+
import { fileMode, readJsonObject, toJson, writeFileAtomic } from './fsutil.js';
|
|
5
|
+
import { mergeSettings } from './settings.js';
|
|
6
|
+
import { readState, writeConfig, writeState, ensureSbtDir } from './state.js';
|
|
7
|
+
import { checkClaudeVersion, describeClaudeVersion, missingDeps, ping } from './checks.js';
|
|
8
|
+
import { consoleLogger } from './log.js';
|
|
9
|
+
export async function init(opts) {
|
|
10
|
+
const log = opts.logger ?? consoleLogger;
|
|
11
|
+
const token = validateToken(opts.token);
|
|
12
|
+
const endpoint = normalizeEndpoint(opts.endpoint);
|
|
13
|
+
const env = buildEnv({ token, endpoint, teamId: opts.teamId });
|
|
14
|
+
const p = paths();
|
|
15
|
+
// 1. Claude Code version (warn only).
|
|
16
|
+
const claude = checkClaudeVersion();
|
|
17
|
+
if (claude.status === 'ok')
|
|
18
|
+
log.ok(describeClaudeVersion(claude));
|
|
19
|
+
else
|
|
20
|
+
log.warn(describeClaudeVersion(claude));
|
|
21
|
+
const missing = missingDeps();
|
|
22
|
+
if (missing.length > 0) {
|
|
23
|
+
log.warn(`Missing ${missing.join(', ')}: the branch/ticket hook will silently do nothing until installed. Cost metrics still work.`);
|
|
24
|
+
}
|
|
25
|
+
// 2. Merge into ~/.claude/settings.json (reads first; aborts on invalid JSON before writing anything).
|
|
26
|
+
const existing = readJsonObject(p.settings);
|
|
27
|
+
const current = existing ?? {};
|
|
28
|
+
const prevState = readState();
|
|
29
|
+
const merged = mergeSettings(current, env, prevState ? { previousEnv: prevState.previous_env, appliedEnv: prevState.applied_env } : undefined);
|
|
30
|
+
const before = existing === undefined ? undefined : toJson(existing);
|
|
31
|
+
const after = toJson(merged.settings);
|
|
32
|
+
const settingsChanged = before !== after;
|
|
33
|
+
let backupPath;
|
|
34
|
+
if (settingsChanged) {
|
|
35
|
+
if (existing !== undefined) {
|
|
36
|
+
fs.copyFileSync(p.settings, p.settingsBackup);
|
|
37
|
+
backupPath = p.settingsBackup;
|
|
38
|
+
}
|
|
39
|
+
// The file now contains the ingest token in OTEL_EXPORTER_OTLP_HEADERS: keep it private.
|
|
40
|
+
const mode = (fileMode(p.settings) ?? 0o600) & 0o700;
|
|
41
|
+
writeFileAtomic(p.settings, after, mode);
|
|
42
|
+
log.ok(`Updated ${p.settings}${backupPath ? ` (backup: ${backupPath})` : ''}`);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
log.ok(`${p.settings} already up to date`);
|
|
46
|
+
}
|
|
47
|
+
for (const k of merged.overwritten)
|
|
48
|
+
log.warn(`Replaced existing env ${k} (restored on uninstall).`);
|
|
49
|
+
// 3. ~/.spendbyteam/config.json (chmod 600) + state for a clean uninstall.
|
|
50
|
+
ensureSbtDir();
|
|
51
|
+
writeConfig({ token, endpoint });
|
|
52
|
+
const now = new Date().toISOString();
|
|
53
|
+
writeState({
|
|
54
|
+
version: 1,
|
|
55
|
+
installed_at: prevState?.installed_at ?? now,
|
|
56
|
+
updated_at: now,
|
|
57
|
+
previous_env: merged.previousEnv,
|
|
58
|
+
applied_env: env,
|
|
59
|
+
});
|
|
60
|
+
log.ok(`Wrote ${p.config} (mode 600)`);
|
|
61
|
+
// 4. Hook script.
|
|
62
|
+
fs.copyFileSync(bundledHookPath(), p.hook);
|
|
63
|
+
fs.chmodSync(p.hook, 0o755);
|
|
64
|
+
log.ok(`Installed ${p.hook}`);
|
|
65
|
+
// 5. Connectivity test.
|
|
66
|
+
let pingResult;
|
|
67
|
+
if (opts.ping !== false) {
|
|
68
|
+
pingResult = await ping(endpoint, token);
|
|
69
|
+
if (pingResult.ok)
|
|
70
|
+
log.ok(`Connected to ${endpoint} — the panel will show this machine as connected.`);
|
|
71
|
+
else
|
|
72
|
+
log.warn(`Could not reach ${endpoint}/v1/ping: ${pingResult.error}. Settings are installed; run "npx spendbyteam doctor" later.`);
|
|
73
|
+
}
|
|
74
|
+
log.info('Restart Claude Code sessions for the new settings to take effect.');
|
|
75
|
+
return { settingsChanged, backupPath, overwritten: merged.overwritten, missingDeps: missing, claude, ping: pingResult };
|
|
76
|
+
}
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const color = (code) => (s) => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${s}\x1b[0m` : s;
|
|
2
|
+
const green = color('32');
|
|
3
|
+
const yellow = color('33');
|
|
4
|
+
const red = color('31');
|
|
5
|
+
export const consoleLogger = {
|
|
6
|
+
info: (m) => console.log(m),
|
|
7
|
+
ok: (m) => console.log(`${green('✓')} ${m}`),
|
|
8
|
+
warn: (m) => console.warn(`${yellow('!')} ${m}`),
|
|
9
|
+
error: (m) => console.error(`${red('✗')} ${m}`),
|
|
10
|
+
};
|
|
11
|
+
export const silentLogger = { info() { }, ok() { }, warn() { }, error() { } };
|
package/dist/managed.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { buildEnv } from './env.js';
|
|
2
|
+
/**
|
|
3
|
+
* Managed settings (TECHNICAL.md §3.1) for Team/Enterprise admins. Only the env block: the hook
|
|
4
|
+
* needs ~/.spendbyteam/hook.sh on each machine, so it is installed per developer with `init`.
|
|
5
|
+
*/
|
|
6
|
+
export function managedSettings(opts) {
|
|
7
|
+
return { env: buildEnv(opts) };
|
|
8
|
+
}
|
|
9
|
+
export function managedSettingsJson(opts) {
|
|
10
|
+
return `${JSON.stringify(managedSettings(opts), null, 2)}\n`;
|
|
11
|
+
}
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** Resolved lazily so tests (and users) can point HOME somewhere else. */
|
|
5
|
+
export function homeDir() {
|
|
6
|
+
return process.env.HOME && process.env.HOME.length > 0 ? process.env.HOME : os.homedir();
|
|
7
|
+
}
|
|
8
|
+
export function paths() {
|
|
9
|
+
const home = homeDir();
|
|
10
|
+
const claudeDir = path.join(home, '.claude');
|
|
11
|
+
const sbtDir = path.join(home, '.spendbyteam');
|
|
12
|
+
return {
|
|
13
|
+
home,
|
|
14
|
+
claudeDir,
|
|
15
|
+
settings: path.join(claudeDir, 'settings.json'),
|
|
16
|
+
settingsBackup: path.join(claudeDir, 'settings.json.bak'),
|
|
17
|
+
sbtDir,
|
|
18
|
+
config: path.join(sbtDir, 'config.json'),
|
|
19
|
+
state: path.join(sbtDir, 'state.json'),
|
|
20
|
+
hook: path.join(sbtDir, 'hook.sh'),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** hook/hook.sh shipped in the package (works from src/ under vitest and from dist/ when built). */
|
|
24
|
+
export function bundledHookPath() {
|
|
25
|
+
return fileURLToPath(new URL('../hook/hook.sh', import.meta.url));
|
|
26
|
+
}
|
package/dist/pricing.js
ADDED
|
@@ -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,245 @@
|
|
|
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'];
|
|
7
|
+
/** Where Claude Code keeps its session logs: $CLAUDE_CONFIG_DIR (comma-separated), else ~/.claude and ~/.config/claude. */
|
|
8
|
+
export function logDirs() {
|
|
9
|
+
const configured = process.env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
|
|
10
|
+
const bases = configured?.length ? configured : [path.join(homeDir(), '.claude'), path.join(homeDir(), '.config', 'claude')];
|
|
11
|
+
return bases.map((b) => path.join(b, 'projects')).filter((d) => fs.existsSync(d));
|
|
12
|
+
}
|
|
13
|
+
function jsonlFiles(dir, out = []) {
|
|
14
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
15
|
+
const full = path.join(dir, entry.name);
|
|
16
|
+
if (entry.isDirectory())
|
|
17
|
+
jsonlFiles(full, out);
|
|
18
|
+
else if (entry.isFile() && entry.name.endsWith('.jsonl'))
|
|
19
|
+
out.push(full);
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
/** Maps a working directory to its repository root's name, so sub-folders of one repo count as one project. */
|
|
24
|
+
function projectResolver() {
|
|
25
|
+
const cache = new Map();
|
|
26
|
+
const home = homeDir();
|
|
27
|
+
return (cwd) => {
|
|
28
|
+
if (!cwd)
|
|
29
|
+
return '(unknown)';
|
|
30
|
+
const hit = cache.get(cwd);
|
|
31
|
+
if (hit)
|
|
32
|
+
return hit;
|
|
33
|
+
let label;
|
|
34
|
+
for (let dir = cwd;; dir = path.dirname(dir)) {
|
|
35
|
+
if (fs.existsSync(path.join(dir, '.git'))) {
|
|
36
|
+
label = path.basename(dir);
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
if (dir === home || path.dirname(dir) === dir)
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
label ??= cwd === home ? '~ (no repo)' : cwd.startsWith(`${home}${path.sep}`) ? `~${cwd.slice(home.length)}` : cwd;
|
|
43
|
+
cache.set(cwd, label);
|
|
44
|
+
return label;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function localDay(ms) {
|
|
48
|
+
const d = new Date(ms);
|
|
49
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
50
|
+
}
|
|
51
|
+
const ASSISTANT = Buffer.from('"type":"assistant"');
|
|
52
|
+
const USAGE = Buffer.from('"usage"');
|
|
53
|
+
/**
|
|
54
|
+
* Yields only the lines that can carry an API response's usage. Logs run to gigabytes, mostly tool
|
|
55
|
+
* output, so lines are filtered as bytes and only the matches are decoded: decoding every line was
|
|
56
|
+
* four times slower than reading the files.
|
|
57
|
+
*/
|
|
58
|
+
async function* usageLines(file) {
|
|
59
|
+
let parts = [];
|
|
60
|
+
const emit = (line) => (line.indexOf(ASSISTANT) !== -1 && line.indexOf(USAGE) !== -1 ? line.toString('utf8') : undefined);
|
|
61
|
+
for await (const chunk of fs.createReadStream(file, { highWaterMark: 1 << 20 })) {
|
|
62
|
+
let start = 0;
|
|
63
|
+
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
|
|
64
|
+
const piece = chunk.subarray(start, nl);
|
|
65
|
+
const line = parts.length ? Buffer.concat([...parts, piece]) : piece;
|
|
66
|
+
parts = [];
|
|
67
|
+
start = nl + 1;
|
|
68
|
+
const text = emit(line);
|
|
69
|
+
if (text !== undefined)
|
|
70
|
+
yield text;
|
|
71
|
+
}
|
|
72
|
+
if (start < chunk.length)
|
|
73
|
+
parts.push(chunk.subarray(start));
|
|
74
|
+
}
|
|
75
|
+
if (parts.length) {
|
|
76
|
+
const text = emit(Buffer.concat(parts));
|
|
77
|
+
if (text !== undefined)
|
|
78
|
+
yield text;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function readRequests(files, since) {
|
|
82
|
+
const requests = new Map();
|
|
83
|
+
const project = projectResolver();
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
if (since !== null && fs.statSync(file).mtimeMs < since)
|
|
86
|
+
continue;
|
|
87
|
+
for await (const line of usageLines(file)) {
|
|
88
|
+
let row;
|
|
89
|
+
try {
|
|
90
|
+
row = JSON.parse(line);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const message = row?.message;
|
|
96
|
+
const usage = message?.usage;
|
|
97
|
+
const model = message?.model;
|
|
98
|
+
if (row?.type !== 'assistant' || !usage || typeof model !== 'string' || model === '<synthetic>')
|
|
99
|
+
continue;
|
|
100
|
+
const at = Date.parse(row.timestamp);
|
|
101
|
+
if (Number.isNaN(at) || (since !== null && at < since))
|
|
102
|
+
continue;
|
|
103
|
+
// One API response is logged once per content block; the last copy carries the final usage.
|
|
104
|
+
const key = `${message.id ?? row.uuid}:${row.requestId ?? ''}`;
|
|
105
|
+
requests.set(key, {
|
|
106
|
+
model: normalizeModel(model),
|
|
107
|
+
cost: costOf(model, usage),
|
|
108
|
+
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,
|
|
110
|
+
project: project(row.cwd),
|
|
111
|
+
branch: row.gitBranch && row.gitBranch !== 'HEAD' ? row.gitBranch : '(no branch)',
|
|
112
|
+
day: localDay(at),
|
|
113
|
+
at,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return requests;
|
|
118
|
+
}
|
|
119
|
+
export async function buildReport(opts = {}) {
|
|
120
|
+
const now = opts.now ?? new Date();
|
|
121
|
+
const days = opts.days ?? 30;
|
|
122
|
+
if (!opts.all && (!Number.isInteger(days) || days < 1))
|
|
123
|
+
throw new UsageError('--days must be a whole number of 1 or more.');
|
|
124
|
+
const by = opts.by ?? 'project';
|
|
125
|
+
if (!GROUPS.includes(by))
|
|
126
|
+
throw new UsageError(`--by must be one of: ${GROUPS.join(', ')}.`);
|
|
127
|
+
const start = new Date(now);
|
|
128
|
+
start.setHours(0, 0, 0, 0);
|
|
129
|
+
start.setDate(start.getDate() - (days - 1));
|
|
130
|
+
const since = opts.all ? null : start.getTime();
|
|
131
|
+
const dirs = opts.dirs ?? logDirs();
|
|
132
|
+
const files = dirs.flatMap((d) => jsonlFiles(d));
|
|
133
|
+
const requests = await readRequests(files, since);
|
|
134
|
+
const groups = new Map();
|
|
135
|
+
const unpriced = new Map();
|
|
136
|
+
const sessions = new Set();
|
|
137
|
+
let total = 0;
|
|
138
|
+
let tokens = 0;
|
|
139
|
+
let first = Infinity;
|
|
140
|
+
for (const r of requests.values()) {
|
|
141
|
+
if (r.cost === undefined) {
|
|
142
|
+
unpriced.set(r.model, (unpriced.get(r.model) ?? 0) + 1);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
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() };
|
|
147
|
+
g.cost += r.cost;
|
|
148
|
+
g.requests += 1;
|
|
149
|
+
g.sessions.add(r.session);
|
|
150
|
+
g.tokens += r.tokens;
|
|
151
|
+
g.models.set(r.model, (g.models.get(r.model) ?? 0) + r.cost);
|
|
152
|
+
groups.set(key, g);
|
|
153
|
+
sessions.add(r.session);
|
|
154
|
+
total += r.cost;
|
|
155
|
+
tokens += r.tokens;
|
|
156
|
+
first = Math.min(first, r.at);
|
|
157
|
+
}
|
|
158
|
+
const rows = [...groups.entries()]
|
|
159
|
+
.map(([key, g]) => ({
|
|
160
|
+
key,
|
|
161
|
+
cost: g.cost,
|
|
162
|
+
share: total > 0 ? g.cost / total : 0,
|
|
163
|
+
requests: g.requests,
|
|
164
|
+
sessions: g.sessions.size,
|
|
165
|
+
tokens: g.tokens,
|
|
166
|
+
topModel: [...g.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
|
|
167
|
+
}))
|
|
168
|
+
.sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
|
|
169
|
+
return {
|
|
170
|
+
from: since !== null ? localDay(since) : Number.isFinite(first) ? localDay(first) : null,
|
|
171
|
+
to: localDay(now.getTime()),
|
|
172
|
+
by,
|
|
173
|
+
rows,
|
|
174
|
+
total: { cost: total, requests: [...groups.values()].reduce((n, g) => n + g.requests, 0), sessions: sessions.size, tokens },
|
|
175
|
+
unpriced: [...unpriced.entries()].map(([model, n]) => ({ model, requests: n })).sort((a, b) => b.requests - a.requests),
|
|
176
|
+
files: files.length,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const usd = (n) => `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
180
|
+
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);
|
|
181
|
+
const shortModel = (m) => m.replace(/^claude-/, '');
|
|
182
|
+
const style = (code) => (s) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
183
|
+
const bold = style('1');
|
|
184
|
+
const dim = style('2');
|
|
185
|
+
const HEADINGS = { project: 'Project', model: 'Model', branch: 'Branch', day: 'Day' };
|
|
186
|
+
const MAX_ROWS = 15;
|
|
187
|
+
export const CTA_URL = 'https://spendbyteam.com/?utm_source=cli&utm_medium=report';
|
|
188
|
+
export function renderReport(r) {
|
|
189
|
+
const out = [];
|
|
190
|
+
const range = r.from ? `${r.from} → ${r.to}` : 'no usage found';
|
|
191
|
+
out.push(`${bold('Claude Code spend on this machine')} ${dim(range)}`);
|
|
192
|
+
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.'));
|
|
193
|
+
out.push('');
|
|
194
|
+
if (r.rows.length === 0) {
|
|
195
|
+
out.push(r.files === 0
|
|
196
|
+
? 'No Claude Code session logs found (looked in ~/.claude/projects and ~/.config/claude/projects; set CLAUDE_CONFIG_DIR if yours live elsewhere).'
|
|
197
|
+
: 'No priced Claude Code usage in this period. Try --days=90 or --all.');
|
|
198
|
+
return out.join('\n');
|
|
199
|
+
}
|
|
200
|
+
const shown = r.rows.slice(0, MAX_ROWS);
|
|
201
|
+
const rest = r.rows.slice(MAX_ROWS);
|
|
202
|
+
const showModel = r.by !== 'model';
|
|
203
|
+
const header = [HEADINGS[r.by], 'Cost', 'Share', 'Sessions', 'Tokens', ...(showModel ? ['Top model'] : [])];
|
|
204
|
+
const body = shown.map((row) => [
|
|
205
|
+
row.key,
|
|
206
|
+
usd(row.cost),
|
|
207
|
+
`${Math.round(row.share * 100)}%`,
|
|
208
|
+
String(row.sessions),
|
|
209
|
+
compact(row.tokens),
|
|
210
|
+
...(showModel ? [shortModel(row.topModel)] : []),
|
|
211
|
+
]);
|
|
212
|
+
if (rest.length) {
|
|
213
|
+
const cost = rest.reduce((n, x) => n + x.cost, 0);
|
|
214
|
+
body.push([`… ${rest.length} more`, usd(cost), `${Math.round((cost / r.total.cost) * 100)}%`, '', compact(rest.reduce((n, x) => n + x.tokens, 0)), ...(showModel ? [''] : [])]);
|
|
215
|
+
}
|
|
216
|
+
const totalRow = ['Total', usd(r.total.cost), '', String(r.total.sessions), compact(r.total.tokens), ...(showModel ? [''] : [])];
|
|
217
|
+
const table = [header, ...body, totalRow];
|
|
218
|
+
const firstWidth = Math.min(36, Math.max(...table.map((t) => t[0].length)));
|
|
219
|
+
const widths = header.map((_, i) => (i === 0 ? firstWidth : Math.max(...table.map((t) => t[i].length))));
|
|
220
|
+
const fmt = (cells) => cells
|
|
221
|
+
.map((c, i) => {
|
|
222
|
+
const cell = i === 0 && c.length > firstWidth ? `${c.slice(0, firstWidth - 1)}…` : c;
|
|
223
|
+
return i === 0 || (showModel && i === cells.length - 1) ? cell.padEnd(widths[i]) : cell.padStart(widths[i]);
|
|
224
|
+
})
|
|
225
|
+
.join(' ')
|
|
226
|
+
.trimEnd();
|
|
227
|
+
out.push(bold(fmt(header)));
|
|
228
|
+
for (const cells of body)
|
|
229
|
+
out.push(fmt(cells));
|
|
230
|
+
out.push(dim('─'.repeat(widths.reduce((n, w) => n + w + 2, -2))));
|
|
231
|
+
out.push(bold(fmt(totalRow)));
|
|
232
|
+
if (r.unpriced.length) {
|
|
233
|
+
out.push('');
|
|
234
|
+
out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
|
|
235
|
+
}
|
|
236
|
+
out.push('');
|
|
237
|
+
out.push(`This is one machine. To see it for your whole team, per project and client:`);
|
|
238
|
+
out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
|
|
239
|
+
return out.join('\n');
|
|
240
|
+
}
|
|
241
|
+
export async function report(opts = {}) {
|
|
242
|
+
const r = await buildReport(opts);
|
|
243
|
+
console.log(opts.json ? JSON.stringify(r, null, 2) : renderReport(r));
|
|
244
|
+
return r;
|
|
245
|
+
}
|