spendbyteam 0.2.2 → 0.3.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/README.md +20 -2
- package/dist/cli.js +6 -2
- package/dist/html.js +323 -0
- package/dist/report.js +105 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,8 +25,26 @@ Total $1,086.20 112 2.4B
|
|
|
25
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
26
|
|
|
27
27
|
```bash
|
|
28
|
-
npx spendbyteam@0.
|
|
29
|
-
```
|
|
28
|
+
npx spendbyteam@0.3.0 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
|
+
### In the browser
|
|
34
|
+
|
|
35
|
+
On a terminal, `report` asks whether to open the same numbers as an interactive page (Enter = yes). `--web` opens it without asking, `--no-web` never asks.
|
|
36
|
+
|
|
37
|
+
The page has a cost-per-day chart, the split by model and by token type, and tabs for projects, models, branches, days and sessions, each with a filter, sorting and paging. **Save as PDF** uses your browser's print dialog, **Export CSV** saves the current tab, and **Share** copies a short summary or opens a pre-filled post on X.
|
|
38
|
+
|
|
39
|
+
It is a single local HTML file (in your temp folder) with its data inline. Its Content-Security-Policy blocks every network request, so it works with Wi-Fi off and uploads nothing; links only open when you click them.
|
|
40
|
+
|
|
41
|
+
**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`:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{ "cleanupPeriodDays": 3650 }
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
If your organization sets `cleanupPeriodDays` in managed settings, that value wins and `report` says so.
|
|
30
48
|
|
|
31
49
|
| Option | |
|
|
32
50
|
|---|---|
|
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|session] [--json]
|
|
17
|
+
npx spendbyteam report [--days=30 | --all] [--by=project|model|branch|day|session] [--json] [--web | --no-web]
|
|
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
|
|
@@ -42,6 +42,8 @@ Options:
|
|
|
42
42
|
--all report: everything in the logs.
|
|
43
43
|
--by report: group by project (default), model, branch, day or session.
|
|
44
44
|
--json report: print JSON instead of a table.
|
|
45
|
+
--web report: also open it in your browser as a local HTML page (asked by default on a terminal).
|
|
46
|
+
--no-web report: don't ask to open it in the browser.
|
|
45
47
|
--no-browser connect: print the approval link instead of opening a browser.
|
|
46
48
|
--app-url connect: panel URL (default https://app.spendbyteam.com).
|
|
47
49
|
-h, --help Show this help.
|
|
@@ -65,6 +67,8 @@ export async function main(argv) {
|
|
|
65
67
|
all: { type: 'boolean', default: false },
|
|
66
68
|
by: { type: 'string' },
|
|
67
69
|
json: { type: 'boolean', default: false },
|
|
70
|
+
web: { type: 'boolean' },
|
|
71
|
+
'no-web': { type: 'boolean', default: false },
|
|
68
72
|
'no-browser': { type: 'boolean', default: false },
|
|
69
73
|
'app-url': { type: 'string' },
|
|
70
74
|
help: { type: 'boolean', short: 'h', default: false },
|
|
@@ -89,7 +93,7 @@ export async function main(argv) {
|
|
|
89
93
|
if (values.by !== undefined && !GROUPS.includes(values.by)) {
|
|
90
94
|
throw new UsageError(`--by must be one of: ${GROUPS.join(', ')}.`);
|
|
91
95
|
}
|
|
92
|
-
await report({ days, all: values.all, by: values.by, json: values.json });
|
|
96
|
+
await report({ days, all: values.all, by: values.by, json: values.json, web: values['no-web'] ? false : values.web });
|
|
93
97
|
return 0;
|
|
94
98
|
}
|
|
95
99
|
case 'connect':
|
package/dist/html.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `report --web`: an interactive, self-contained HTML report opened from a local file.
|
|
3
|
+
* Everything is inline (styles, data, script); the page's CSP forbids any network request,
|
|
4
|
+
* so it renders with Wi-Fi off and uploads nothing. The only outbound things are links a
|
|
5
|
+
* person chooses to click (the team sign-up, "Post on X").
|
|
6
|
+
*/
|
|
7
|
+
export const HTML_CTA_URL = 'https://app.spendbyteam.com/register?src=cli&cmp=html';
|
|
8
|
+
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
9
|
+
/** Compact row tuple for the embedded data: [key, cost, requests, sessions, tokens, [in, out, cw, cr], topModel, startedAt, project, startedBefore]. */
|
|
10
|
+
function pack(row) {
|
|
11
|
+
return [
|
|
12
|
+
row.key,
|
|
13
|
+
Math.round(row.cost * 10000) / 10000,
|
|
14
|
+
row.requests,
|
|
15
|
+
row.sessions,
|
|
16
|
+
row.tokens,
|
|
17
|
+
[row.split.input, row.split.output, row.split.cacheWrite, row.split.cacheRead],
|
|
18
|
+
row.topModel.replace(/^claude-/, ''),
|
|
19
|
+
row.startedAt ?? null,
|
|
20
|
+
row.project ?? null,
|
|
21
|
+
row.startedBeforeWindow ? 1 : 0,
|
|
22
|
+
];
|
|
23
|
+
}
|
|
24
|
+
export function reportData(r, opts = {}) {
|
|
25
|
+
const views = r.views ?? { [r.by]: r.rows };
|
|
26
|
+
return {
|
|
27
|
+
from: r.from,
|
|
28
|
+
to: r.to,
|
|
29
|
+
by: r.by,
|
|
30
|
+
generated: (opts.generatedAt ?? new Date()).toISOString(),
|
|
31
|
+
version: opts.version ?? null,
|
|
32
|
+
total: r.total,
|
|
33
|
+
retention: r.retention ?? null,
|
|
34
|
+
unpriced: r.unpriced,
|
|
35
|
+
views: Object.fromEntries(Object.entries(views).map(([k, rows]) => [k, (rows ?? []).map(pack)])),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function renderHtml(r, opts = {}) {
|
|
39
|
+
const data = JSON.stringify(reportData(r, opts)).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
|
|
40
|
+
const range = r.from ? `${r.from} → ${r.to}` : 'no usage found';
|
|
41
|
+
return `<!doctype html>
|
|
42
|
+
<html lang="en">
|
|
43
|
+
<head>
|
|
44
|
+
<meta charset="utf-8">
|
|
45
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
46
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:">
|
|
47
|
+
<title>Claude Code spend · ${esc(range)}</title>
|
|
48
|
+
<style>
|
|
49
|
+
:root{color-scheme:light;--bg:#f6f6f4;--card:#fcfcfb;--ink:#0b0b0b;--ink2:#52514e;--ink3:#8a8984;--rule:#e6e5e0;--grid:#ecebe7;--accent:#6250d6;--accent-soft:#eceaff;--warn:#fff6e0;--warnb:#efd9a3;
|
|
50
|
+
--s1:#2a78d6;--s2:#eb6834;--s3:#1baf7a;--s4:#eda100;--s5:#e87ba4;--other:#b9b8b2}
|
|
51
|
+
@media (prefers-color-scheme:dark){:root{color-scheme:dark;--bg:#111110;--card:#1a1a19;--ink:#f0efec;--ink2:#c3c2b7;--ink3:#8f8e86;--rule:#2c2c2a;--grid:#262624;--accent:#9085e9;--accent-soft:#25213f;--warn:#2a2413;--warnb:#5b4b1e;
|
|
52
|
+
--s1:#3987e5;--s2:#d95926;--s3:#199e70;--s4:#c98500;--s5:#d55181;--other:#5d5c57}}
|
|
53
|
+
*{box-sizing:border-box}
|
|
54
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
|
|
55
|
+
main{max-width:1120px;margin:0 auto;padding:28px 16px 56px}
|
|
56
|
+
.num{font-variant-numeric:tabular-nums}
|
|
57
|
+
header.top{display:flex;flex-wrap:wrap;gap:16px;align-items:flex-end;justify-content:space-between;margin-bottom:20px}
|
|
58
|
+
h1{font-size:1.4rem;letter-spacing:-.01em;margin:0}
|
|
59
|
+
.sub{color:var(--ink2);margin:4px 0 0;font-size:.88rem}
|
|
60
|
+
.actions{display:flex;gap:8px;flex-wrap:wrap;position:relative}
|
|
61
|
+
button,.btn{font:inherit;font-weight:600;font-size:.85rem;border-radius:999px;padding:8px 14px;border:1px solid var(--rule);background:var(--card);color:var(--ink);cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
|
|
62
|
+
button:hover{border-color:var(--ink3)}
|
|
63
|
+
.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
|
64
|
+
.menu{position:absolute;right:0;top:42px;background:var(--card);border:1px solid var(--rule);border-radius:12px;padding:6px;min-width:200px;box-shadow:0 8px 24px rgba(0,0,0,.12);z-index:5;display:none}
|
|
65
|
+
.menu.open{display:block}
|
|
66
|
+
.menu button{width:100%;border:0;border-radius:8px;justify-content:flex-start;font-weight:500}
|
|
67
|
+
.menu button:hover{background:var(--bg)}
|
|
68
|
+
.toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:var(--ink);color:var(--bg);padding:8px 14px;border-radius:999px;font-size:.85rem;opacity:0;transition:opacity .2s;pointer-events:none}
|
|
69
|
+
.toast.show{opacity:1}
|
|
70
|
+
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:14px}
|
|
71
|
+
.kpi{background:var(--card);border:1px solid var(--rule);border-radius:14px;padding:14px 16px;min-width:0}
|
|
72
|
+
.kpi .v{font-size:1.45rem;font-weight:650;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
73
|
+
.kpi .l{color:var(--ink2);font-size:.78rem}
|
|
74
|
+
.kpi .h{color:var(--ink3);font-size:.75rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
75
|
+
.note{background:var(--warn);border:1px solid var(--warnb);border-radius:12px;padding:10px 14px;margin-bottom:14px;font-size:.87rem}
|
|
76
|
+
.grid2{display:grid;grid-template-columns:2fr 1fr;gap:10px;margin-bottom:14px}
|
|
77
|
+
@media (max-width:820px){.grid2{grid-template-columns:1fr}}
|
|
78
|
+
.panel{background:var(--card);border:1px solid var(--rule);border-radius:16px;padding:16px;min-width:0}
|
|
79
|
+
.panel h2{font-size:.82rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink2);margin:0 0 12px;font-weight:650}
|
|
80
|
+
.chart{position:relative}
|
|
81
|
+
.chart svg{display:block;width:100%;height:auto;overflow:visible}
|
|
82
|
+
.tip{position:absolute;pointer-events:none;background:var(--ink);color:var(--bg);font-size:.78rem;padding:6px 9px;border-radius:8px;white-space:nowrap;transform:translate(-50%,-110%);display:none;z-index:3}
|
|
83
|
+
.stack{display:flex;height:14px;border-radius:4px;overflow:hidden;gap:2px;margin:6px 0 12px}
|
|
84
|
+
.stack span{display:block;height:100%}
|
|
85
|
+
.legend{list-style:none;margin:0;padding:0;display:grid;gap:6px}
|
|
86
|
+
.legend li{display:grid;grid-template-columns:10px 1fr auto auto;gap:8px;align-items:center;font-size:.84rem}
|
|
87
|
+
.legend i{width:10px;height:10px;border-radius:3px;display:block}
|
|
88
|
+
.legend .p{color:var(--ink3);min-width:38px;text-align:right}
|
|
89
|
+
.tabs{display:flex;gap:4px;flex-wrap:wrap;border-bottom:1px solid var(--rule);margin:-4px -4px 12px;padding:0 4px}
|
|
90
|
+
.tabs button{border:0;border-radius:0;background:none;padding:10px 12px;color:var(--ink2);border-bottom:2px solid transparent;margin-bottom:-1px}
|
|
91
|
+
.tabs button[aria-selected=true]{color:var(--ink);border-bottom-color:var(--accent)}
|
|
92
|
+
.tools{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px}
|
|
93
|
+
.tools input{font:inherit;flex:1;min-width:180px;padding:8px 12px;border:1px solid var(--rule);border-radius:999px;background:var(--bg);color:var(--ink)}
|
|
94
|
+
.tools .count{color:var(--ink3);font-size:.82rem}
|
|
95
|
+
.tablewrap{overflow-x:auto}
|
|
96
|
+
table{width:100%;border-collapse:collapse;table-layout:fixed}
|
|
97
|
+
th,td{padding:9px 10px;border-bottom:1px solid var(--rule);text-align:left;vertical-align:middle}
|
|
98
|
+
th{font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink2);font-weight:650;cursor:pointer;user-select:none;white-space:nowrap}
|
|
99
|
+
th.n,td.n{text-align:right}
|
|
100
|
+
th[aria-sort=ascending]::after{content:" ↑"}th[aria-sort=descending]::after{content:" ↓"}
|
|
101
|
+
td.k{overflow:hidden}
|
|
102
|
+
td.k .t{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
103
|
+
td.k small{display:block;color:var(--ink3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
104
|
+
.bar{height:4px;background:var(--accent-soft);border-radius:2px;margin-top:5px}
|
|
105
|
+
.bar span{display:block;height:100%;background:var(--accent);border-radius:2px}
|
|
106
|
+
tfoot td{font-weight:650;border-top:2px solid var(--ink);border-bottom:0}
|
|
107
|
+
.pager{display:flex;gap:8px;align-items:center;justify-content:flex-end;margin-top:10px;color:var(--ink2);font-size:.84rem}
|
|
108
|
+
.pager button[disabled]{opacity:.4;cursor:default}
|
|
109
|
+
.cta{margin-top:14px;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;background:var(--accent-soft);border:1px solid var(--rule);border-radius:16px;padding:18px 20px}
|
|
110
|
+
.cta p{margin:0;max-width:640px}.cta p span{color:var(--ink2)}
|
|
111
|
+
footer{color:var(--ink3);font-size:.78rem;margin-top:18px}footer a{color:inherit}
|
|
112
|
+
code{font:.85em ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
113
|
+
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
|
|
114
|
+
@media print{
|
|
115
|
+
body{background:#fff;color:#000;font-size:11px}
|
|
116
|
+
.no-print,.tools,.pager,.tabs,.menu,.tip,.toast{display:none!important}
|
|
117
|
+
.panel,.kpi,.cta{break-inside:avoid;border-color:#ddd}
|
|
118
|
+
main{padding:0;max-width:none}
|
|
119
|
+
.grid2{grid-template-columns:2fr 1fr}
|
|
120
|
+
.print-title{display:block!important;font-size:.8rem;color:#555;margin:0 0 8px}
|
|
121
|
+
}
|
|
122
|
+
.print-title{display:none}
|
|
123
|
+
</style>
|
|
124
|
+
</head>
|
|
125
|
+
<body>
|
|
126
|
+
<main>
|
|
127
|
+
<header class="top">
|
|
128
|
+
<div>
|
|
129
|
+
<h1>Claude Code spend on this machine</h1>
|
|
130
|
+
<p class="sub" id="sub"></p>
|
|
131
|
+
</div>
|
|
132
|
+
<div class="actions no-print">
|
|
133
|
+
<button type="button" id="pdf" title="Opens the print dialog; choose “Save as PDF”">Save as PDF</button>
|
|
134
|
+
<button type="button" id="csv">Export CSV</button>
|
|
135
|
+
<button type="button" id="share" aria-haspopup="true" aria-expanded="false">Share ▾</button>
|
|
136
|
+
<div class="menu" id="menu" role="menu">
|
|
137
|
+
<button type="button" role="menuitem" data-share="copy">Copy summary</button>
|
|
138
|
+
<button type="button" role="menuitem" data-share="x">Post on X</button>
|
|
139
|
+
</div>
|
|
140
|
+
<a class="btn primary" href="${HTML_CTA_URL}">See it for your team</a>
|
|
141
|
+
</div>
|
|
142
|
+
</header>
|
|
143
|
+
|
|
144
|
+
<section class="kpis" id="kpis" aria-label="Summary"></section>
|
|
145
|
+
<div id="note"></div>
|
|
146
|
+
|
|
147
|
+
<div class="grid2">
|
|
148
|
+
<section class="panel">
|
|
149
|
+
<h2>Cost per day</h2>
|
|
150
|
+
<div class="chart" id="daily"><div class="tip" id="tip"></div></div>
|
|
151
|
+
</section>
|
|
152
|
+
<section class="panel">
|
|
153
|
+
<h2>By model</h2>
|
|
154
|
+
<div id="models"></div>
|
|
155
|
+
<h2 style="margin-top:18px">Where the tokens went</h2>
|
|
156
|
+
<div id="mix"></div>
|
|
157
|
+
</section>
|
|
158
|
+
</div>
|
|
159
|
+
|
|
160
|
+
<section class="panel">
|
|
161
|
+
<p class="print-title" id="ptitle"></p>
|
|
162
|
+
<div class="tabs" role="tablist" id="tabs"></div>
|
|
163
|
+
<div class="tools">
|
|
164
|
+
<input type="search" id="q" placeholder="Filter…" aria-label="Filter rows">
|
|
165
|
+
<span class="count num" id="count"></span>
|
|
166
|
+
</div>
|
|
167
|
+
<div class="tablewrap"><table class="num" id="tbl"><thead></thead><tbody></tbody><tfoot></tfoot></table></div>
|
|
168
|
+
<div class="pager" id="pager"></div>
|
|
169
|
+
</section>
|
|
170
|
+
|
|
171
|
+
<section class="cta">
|
|
172
|
+
<p><strong>This is one machine.</strong><br><span>See it for your whole team, per project and client, with budgets, alerts and client-ready PDF reports. Free for up to 3 developers.</span></p>
|
|
173
|
+
<a class="btn primary" href="${HTML_CTA_URL}">See it for your team</a>
|
|
174
|
+
</section>
|
|
175
|
+
<footer id="foot"></footer>
|
|
176
|
+
<div class="toast" id="toast" role="status"></div>
|
|
177
|
+
</main>
|
|
178
|
+
<script id="data" type="application/json">${data}</script>
|
|
179
|
+
<script>
|
|
180
|
+
(function(){
|
|
181
|
+
const D=JSON.parse(document.getElementById('data').textContent);
|
|
182
|
+
const $=id=>document.getElementById(id);
|
|
183
|
+
const el=(tag,attrs,kids)=>{const e=document.createElement(tag);for(const k in attrs||{}){if(k==='text')e.textContent=attrs[k];else if(k==='style')e.style.cssText=attrs[k];else e.setAttribute(k,attrs[k]);}(kids||[]).forEach(c=>c&&e.appendChild(c));return e;};
|
|
184
|
+
const usd=n=>'$'+n.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2});
|
|
185
|
+
const usd0=n=>n>=1000?'$'+Math.round(n).toLocaleString('en-US'):usd(n);
|
|
186
|
+
const cmp=n=>n>=1e9?(n/1e9).toFixed(1)+'B':n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?(n/1e3).toFixed(1)+'K':String(n);
|
|
187
|
+
const pct=x=>(x*100>=10?Math.round(x*100):(x*100).toFixed(1))+'%';
|
|
188
|
+
const NAMES={project:'Projects',model:'Models',branch:'Branches',day:'Days',session:'Sessions'};
|
|
189
|
+
const ONE={project:'Project',model:'Model',branch:'Branch',day:'Day',session:'Session'};
|
|
190
|
+
const V=D.views, T=D.total;
|
|
191
|
+
const row=a=>({key:a[0],cost:a[1],requests:a[2],sessions:a[3],tokens:a[4],split:a[5],model:a[6],started:a[7],project:a[8],before:a[9]});
|
|
192
|
+
const views={};for(const k in V)views[k]=V[k].map(row);
|
|
193
|
+
|
|
194
|
+
/* ---- header + KPIs ---- */
|
|
195
|
+
const dayCount=D.from?Math.round((Date.parse(D.to)-Date.parse(D.from))/864e5)+1:0;
|
|
196
|
+
$('sub').textContent=(D.from?D.from+' → '+D.to+' · '+dayCount+' days':'No usage found')+' · at API list prices. On a Pro, Max or Team seat you pay a flat fee; this is what the same tokens would cost on the API.';
|
|
197
|
+
$('ptitle').textContent='Claude Code spend · '+(D.from?D.from+' → '+D.to:'');
|
|
198
|
+
const sum=(rows,i)=>rows.reduce((n,r)=>n+r.split[i],0);
|
|
199
|
+
const all=views[D.by]||[];
|
|
200
|
+
const inTok=sum(all,0),outTok=sum(all,1),cw=sum(all,2),cr=sum(all,3);
|
|
201
|
+
const cacheShare=(inTok+cw+cr)>0?cr/(inTok+cw+cr):0;
|
|
202
|
+
const top=(k)=>(views[k]||[]).slice().sort((a,b)=>b.cost-a.cost)[0];
|
|
203
|
+
const tp=top('project'),tm=top('model');
|
|
204
|
+
const activeDays=(views.day||[]).filter(r=>r.cost>0).length;
|
|
205
|
+
const kpis=[
|
|
206
|
+
[usd0(T.cost),'Total cost',D.from?usd(T.cost/Math.max(1,dayCount))+' a day'+(views.day?' · '+activeDays+' of '+dayCount+' days active':''):''],
|
|
207
|
+
[String(T.sessions),'Sessions',T.sessions?usd(T.cost/T.sessions)+' per session':''],
|
|
208
|
+
[cmp(T.tokens),'Tokens',T.requests.toLocaleString('en-US')+' requests'],
|
|
209
|
+
[pct(cacheShare),'Read from cache','of input-side tokens'],
|
|
210
|
+
[tp?pct(tp.cost/T.cost):'–','Top project',tp?tp.key:''],
|
|
211
|
+
[tm?pct(tm.cost/T.cost):'–','Top model',tm?tm.key.replace(/^claude-/,''):''],
|
|
212
|
+
];
|
|
213
|
+
kpis.forEach(([v,l,h])=>$('kpis').appendChild(el('div',{class:'kpi'},[el('div',{class:'v num',text:v,title:v}),el('div',{class:'l',text:l}),el('div',{class:'h',text:h,title:h})])));
|
|
214
|
+
|
|
215
|
+
const R=D.retention;
|
|
216
|
+
if(R&&R.days<=90){const a=el('aside',{class:'note'});a.appendChild(el('strong',{text:'Heads-up: '}));
|
|
217
|
+
a.appendChild(document.createTextNode('Claude Code deletes these logs after '+R.days+' days ('+(R.source==='default'?'by default':R.source==='managed'?'set by your organization':'set in your settings.json')+')'+(R.oldestLog?', so the oldest log left on this machine is from '+R.oldestLog:'')+'.'));
|
|
218
|
+
if(R.source!=='managed'){a.appendChild(document.createTextNode(' To keep them, add '));a.appendChild(el('code',{text:'"cleanupPeriodDays": 3650'}));a.appendChild(document.createTextNode(' to '));a.appendChild(el('code',{text:'~/.claude/settings.json'}));a.appendChild(document.createTextNode('.'));}
|
|
219
|
+
$('note').appendChild(a);}
|
|
220
|
+
|
|
221
|
+
/* ---- daily chart (inline SVG, one series, hover tooltip) ---- */
|
|
222
|
+
(function(){
|
|
223
|
+
const box=$('daily');
|
|
224
|
+
if(!views.day||!D.from){box.appendChild(el('p',{class:'sub',text:'No daily data.'}));return;}
|
|
225
|
+
const byDay=new Map(views.day.map(r=>[r.key,r]));
|
|
226
|
+
const days=[];for(let t=Date.parse(D.from);t<=Date.parse(D.to);t+=864e5){const k=new Date(t).toISOString().slice(0,10);days.push({k,r:byDay.get(k)});}
|
|
227
|
+
const W=640,H=250,L=48,B=24,TP=8,n=days.length,max=Math.max(1,...days.map(d=>d.r?d.r.cost:0));
|
|
228
|
+
const step=niceStep(max/3),top=Math.ceil(max/step)*step,bw=(W-L)/n,gap=Math.min(2,bw*.25);
|
|
229
|
+
const ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 '+W+' '+H);svg.setAttribute('role','img');
|
|
230
|
+
svg.setAttribute('aria-label','Cost per day, '+D.from+' to '+D.to+'; highest '+usd(max));
|
|
231
|
+
const S=(t,a)=>{const e=document.createElementNS(ns,t);for(const k in a)e.setAttribute(k,a[k]);return e;};
|
|
232
|
+
const y=v=>TP+(H-B-TP)*(1-v/top);
|
|
233
|
+
for(let v=0;v<=top+1e-9;v+=step){svg.appendChild(S('line',{x1:L,x2:W,y1:y(v),y2:y(v),stroke:'var(--grid)','stroke-width':1}));const t=S('text',{x:L-8,y:y(v)+4,'text-anchor':'end','font-size':11,fill:'var(--ink3)'});t.textContent='$'+Math.round(v).toLocaleString('en-US');svg.appendChild(t);}
|
|
234
|
+
const every=Math.ceil(n/8);
|
|
235
|
+
days.forEach((d,i)=>{const x=L+i*bw,c=d.r?d.r.cost:0,h=(H-B-TP)*(c/top);
|
|
236
|
+
if(c>0){const w=Math.max(1,bw-gap),r=Math.min(4,w/2,h);
|
|
237
|
+
svg.appendChild(S('path',{d:'M'+(x+gap/2)+','+(H-B)+'v'+(-(h-r))+'q0,'+(-r)+' '+r+','+(-r)+'h'+(w-2*r)+'q'+r+',0 '+r+','+r+'v'+(h-r)+'z',fill:'var(--accent)'}));}
|
|
238
|
+
if(i%every===0){const t=S('text',{x:x+bw/2,y:H-6,'text-anchor':'middle','font-size':11,fill:'var(--ink3)'});t.textContent=d.k.slice(5);svg.appendChild(t);}
|
|
239
|
+
const hit=S('rect',{x:x,y:TP,width:bw,height:H-B-TP,fill:'transparent'});
|
|
240
|
+
hit.addEventListener('mousemove',ev=>{const tip=$('tip'),rb=box.getBoundingClientRect();tip.textContent=d.k+' · '+usd(c)+(d.r?' · '+d.r.sessions+' sessions':'');tip.style.display='block';tip.style.left=(ev.clientX-rb.left)+'px';tip.style.top=(ev.clientY-rb.top)+'px';});
|
|
241
|
+
hit.addEventListener('mouseleave',()=>{$('tip').style.display='none';});
|
|
242
|
+
svg.appendChild(hit);});
|
|
243
|
+
box.appendChild(svg);
|
|
244
|
+
function niceStep(x){const p=Math.pow(10,Math.floor(Math.log10(x||1))),m=x/p;return (m<=1?1:m<=2?2:m<=5?5:10)*p;}
|
|
245
|
+
})();
|
|
246
|
+
|
|
247
|
+
/* ---- model share + token mix (100% stacks, legend always shown) ---- */
|
|
248
|
+
const COLORS=['var(--s1)','var(--s2)','var(--s3)','var(--s4)','var(--s5)'];
|
|
249
|
+
function stack(target,items){
|
|
250
|
+
const tot=items.reduce((n,i)=>n+i.v,0)||1,bar=el('div',{class:'stack',role:'img','aria-label':items.map(i=>i.label+' '+pct(i.v/tot)).join(', ')}),ul=el('ul',{class:'legend'});
|
|
251
|
+
items.forEach(i=>{if(i.v<=0)return;bar.appendChild(el('span',{style:'flex:'+i.v+' 0 0;background:'+i.c,title:i.label+' · '+pct(i.v/tot)}));
|
|
252
|
+
ul.appendChild(el('li',{},[el('i',{style:'background:'+i.c}),el('span',{text:i.label}),el('span',{class:'num',text:i.fmt(i.v)}),el('span',{class:'p num',text:pct(i.v/tot)})]));});
|
|
253
|
+
target.appendChild(bar);target.appendChild(ul);
|
|
254
|
+
}
|
|
255
|
+
(function(){
|
|
256
|
+
const m=(views.model||[]).slice().sort((a,b)=>b.cost-a.cost),head=m.slice(0,4),rest=m.slice(4);
|
|
257
|
+
const items=head.map((r,i)=>({label:r.key.replace(/^claude-/,''),v:r.cost,c:COLORS[i],fmt:usd0}));
|
|
258
|
+
if(rest.length)items.push({label:'Other ('+rest.length+')',v:rest.reduce((n,r)=>n+r.cost,0),c:'var(--other)',fmt:usd0});
|
|
259
|
+
stack($('models'),items);
|
|
260
|
+
stack($('mix'),[{label:'Cache reads',v:cr,c:COLORS[0],fmt:cmp},{label:'Cache writes',v:cw,c:COLORS[1],fmt:cmp},{label:'Input',v:inTok,c:COLORS[2],fmt:cmp},{label:'Output',v:outTok,c:COLORS[3],fmt:cmp}]);
|
|
261
|
+
})();
|
|
262
|
+
|
|
263
|
+
/* ---- table: tabs, filter, sort, pagination ---- */
|
|
264
|
+
const PAGE=25;let tab=V[D.by]?D.by:Object.keys(V)[0],q='',sortK='cost',sortDir=-1,page=0,printing=false;
|
|
265
|
+
const COLS={
|
|
266
|
+
default:[['key','',0],['cost','Cost',1],['share','Share',1],['sessions','Sessions',1],['tokens','Tokens',1],['model','Model',0]],
|
|
267
|
+
session:[['started','Started',0],['cost','Cost',1],['requests','Turns',1],['tokens','Tokens',1],['cache','Cache read',1],['model','Model',0]],
|
|
268
|
+
};
|
|
269
|
+
const cols=()=>tab==='session'?COLS.session:COLS.default;
|
|
270
|
+
Object.keys(NAMES).filter(k=>V[k]).forEach(k=>{const b=el('button',{type:'button',role:'tab','aria-selected':String(k===tab),text:NAMES[k]+' ('+V[k].length+')'});b.onclick=()=>{tab=k;page=0;q='';$('q').value='';sortK=k==='day'?'key':'cost';sortDir=k==='day'?1:-1;[...$('tabs').children].forEach(c=>c.setAttribute('aria-selected',String(c===b)));draw();};$('tabs').appendChild(b);});
|
|
271
|
+
$('q').addEventListener('input',e=>{q=e.target.value.trim().toLowerCase();page=0;draw();});
|
|
272
|
+
const val=(r,k)=>k==='share'?r.cost:k==='cache'?r.split[3]/Math.max(1,r.split[0]+r.split[2]+r.split[3]):k==='started'?(r.started||''):r[k];
|
|
273
|
+
function rowsNow(){
|
|
274
|
+
let rows=views[tab]||[];
|
|
275
|
+
if(q)rows=rows.filter(r=>(r.key+' '+(r.project||'')+' '+r.model).toLowerCase().includes(q));
|
|
276
|
+
return rows.slice().sort((a,b)=>{const x=val(a,sortK),y=val(b,sortK);return (typeof x==='string'?x.localeCompare(y):x-y)*sortDir;});
|
|
277
|
+
}
|
|
278
|
+
function draw(){
|
|
279
|
+
const tbl=$('tbl'),C=cols(),rows=rowsNow(),pages=Math.max(1,Math.ceil(rows.length/PAGE));page=Math.min(page,pages-1);
|
|
280
|
+
const shown=printing?rows:rows.slice(page*PAGE,page*PAGE+PAGE);
|
|
281
|
+
const head=el('tr');C.forEach(([k,label,num],i)=>{const th=el('th',{class:num?'n':'',text:i===0&&!label?ONE[tab]:label,style:i===0?'width:44%':''});if(k===sortK)th.setAttribute('aria-sort',sortDir>0?'ascending':'descending');th.onclick=()=>{if(sortK===k)sortDir=-sortDir;else{sortK=k;sortDir=num?-1:1;}draw();};head.appendChild(th);});
|
|
282
|
+
tbl.tHead.replaceChildren(head);
|
|
283
|
+
const body=document.createDocumentFragment(),max=Math.max(...(views[tab]||[]).map(r=>r.cost),1e-9);
|
|
284
|
+
shown.forEach(r=>{const tr=el('tr');C.forEach(([k,,num],i)=>{let td;
|
|
285
|
+
if(i===0){td=el('td',{class:'k'});const label=tab==='session'?(r.before?'≤ ':'')+(r.started||'').slice(0,16).replace('T',' '):r.key;td.appendChild(el('span',{class:'t',text:label,title:label}));if(tab==='session'&&r.project)td.appendChild(el('small',{text:r.project,title:r.project}));td.appendChild(el('div',{class:'bar'},[el('span',{style:'width:'+Math.max(.5,r.cost/max*100).toFixed(1)+'%'})]));}
|
|
286
|
+
else{const v=k==='cost'?usd(r.cost):k==='share'?pct(T.cost?r.cost/T.cost:0):k==='tokens'?cmp(r.tokens):k==='cache'?pct(val(r,'cache')):k==='model'?(tab==='model'?'':r.model):String(r[k]);td=el('td',{class:num?'n':'',text:v});}
|
|
287
|
+
tr.appendChild(td);});body.appendChild(tr);});
|
|
288
|
+
if(!shown.length)body.appendChild(el('tr',{},[el('td',{colspan:'6',text:q?'No rows match “'+q+'”.':'No data.'})]));
|
|
289
|
+
tbl.tBodies[0].replaceChildren(body);
|
|
290
|
+
const fc=rows.reduce((n,r)=>n+r.cost,0),ft=rows.reduce((n,r)=>n+r.tokens,0);
|
|
291
|
+
const f=el('tr',{},[el('td',{text:q?'Filtered total':'Total'}),el('td',{class:'n',text:usd(fc)}),el('td',{class:'n',text:tab==='session'?String(rows.reduce((n,r)=>n+r.requests,0)):pct(T.cost?fc/T.cost:0)}),el('td',{class:'n',text:tab==='session'?cmp(ft):String(tab==='session'?'':rows.reduce((n,r)=>n+r.sessions,0))}),el('td',{class:'n',text:tab==='session'?'':cmp(ft)}),el('td')]);
|
|
292
|
+
tbl.tFoot.replaceChildren(f);
|
|
293
|
+
$('count').textContent=rows.length+' of '+(views[tab]||[]).length+' '+NAMES[tab].toLowerCase();
|
|
294
|
+
const pg=$('pager');pg.replaceChildren();
|
|
295
|
+
if(rows.length>PAGE){const prev=el('button',{type:'button',text:'← Prev'}),next=el('button',{type:'button',text:'Next →'});prev.disabled=page===0;next.disabled=page>=pages-1;prev.onclick=()=>{page--;draw();};next.onclick=()=>{page++;draw();};
|
|
296
|
+
pg.appendChild(el('span',{class:'num',text:(page*PAGE+1)+'–'+Math.min(rows.length,(page+1)*PAGE)+' of '+rows.length}));pg.appendChild(prev);pg.appendChild(next);}
|
|
297
|
+
}
|
|
298
|
+
draw();
|
|
299
|
+
|
|
300
|
+
/* ---- PDF, CSV, share ---- */
|
|
301
|
+
window.addEventListener('beforeprint',()=>{printing=true;draw();});
|
|
302
|
+
window.addEventListener('afterprint',()=>{printing=false;draw();});
|
|
303
|
+
$('pdf').onclick=()=>window.print();
|
|
304
|
+
$('csv').onclick=()=>{const C=cols(),q2=s=>'"'+String(s).replace(/"/g,'""')+'"';
|
|
305
|
+
const lines=[[ONE[tab],'Cost USD','Requests','Sessions','Tokens','Input','Output','Cache write','Cache read','Model'].map(q2).join(',')].concat(rowsNow().map(r=>[tab==='session'?r.started:r.key,r.cost.toFixed(4),r.requests,r.sessions,r.tokens,...r.split,r.model].map(q2).join(',')));
|
|
306
|
+
const a=el('a',{href:URL.createObjectURL(new Blob([lines.join('\\n')],{type:'text/csv'})),download:'claude-code-'+tab+'-'+(D.to||'report')+'.csv'});document.body.appendChild(a);a.click();a.remove();toast('CSV saved');};
|
|
307
|
+
const menu=$('menu');$('share').onclick=e=>{e.stopPropagation();const o=menu.classList.toggle('open');$('share').setAttribute('aria-expanded',String(o));};
|
|
308
|
+
document.addEventListener('click',()=>{menu.classList.remove('open');$('share').setAttribute('aria-expanded','false');});
|
|
309
|
+
function summary(){const tops=(views.project||[]).slice().sort((a,b)=>b.cost-a.cost).slice(0,3).map(r=>'- '+r.key+': '+usd(r.cost)).join('\\n');
|
|
310
|
+
return 'My Claude Code usage, '+D.from+' → '+D.to+': '+usd(T.cost)+' at API prices, '+T.sessions+' sessions, '+cmp(T.tokens)+' tokens ('+pct(cacheShare)+' from cache).'+(tops?'\\nTop projects:\\n'+tops:'')+'\\n\\nMeasured offline with npx spendbyteam report';}
|
|
311
|
+
menu.addEventListener('click',e=>{const k=e.target.getAttribute('data-share');if(!k)return;
|
|
312
|
+
if(k==='copy'){navigator.clipboard.writeText(summary()).then(()=>toast('Summary copied'),()=>toast('Copy failed'));}
|
|
313
|
+
if(k==='x'){const t='My Claude Code usage over '+dayCount+' days: '+usd(T.cost)+' at API prices, '+T.sessions+' sessions, '+pct(cacheShare)+' read from cache.\\n\\nMeasured offline with npx spendbyteam report';window.open('https://x.com/intent/post?text='+encodeURIComponent(t),'_blank','noopener');}});
|
|
314
|
+
function toast(t){const e=$('toast');e.textContent=t;e.classList.add('show');setTimeout(()=>e.classList.remove('show'),1600);}
|
|
315
|
+
|
|
316
|
+
const f=$('foot');f.appendChild(document.createTextNode('Generated on this machine by '));f.appendChild(el('code',{text:'npx spendbyteam report'+(D.version?' '+D.version:'')}));
|
|
317
|
+
f.appendChild(document.createTextNode(' at '+D.generated.slice(0,16).replace('T',' ')+' UTC. Nothing was uploaded; this page makes no network requests. '));f.appendChild(el('a',{href:'https://github.com/spendbyteam/cli',text:'Source'}));
|
|
318
|
+
})();
|
|
319
|
+
</script>
|
|
320
|
+
</body>
|
|
321
|
+
</html>
|
|
322
|
+
`;
|
|
323
|
+
}
|
package/dist/report.js
CHANGED
|
@@ -3,8 +3,43 @@ 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
|
+
import os from 'node:os';
|
|
7
|
+
import readline from 'node:readline/promises';
|
|
8
|
+
import { renderHtml } from './html.js';
|
|
9
|
+
import { openInBrowser } from './connect.js';
|
|
6
10
|
export const GROUPS = ['project', 'model', 'branch', 'day', 'session'];
|
|
7
11
|
const emptySplit = () => ({ input: 0, output: 0, cacheWrite: 0, cacheRead: 0 });
|
|
12
|
+
/** Claude Code's documented default for cleanupPeriodDays. */
|
|
13
|
+
export const DEFAULT_CLEANUP_DAYS = 30;
|
|
14
|
+
function readCleanupDays(file) {
|
|
15
|
+
try {
|
|
16
|
+
const v = JSON.parse(fs.readFileSync(file, 'utf8'))?.cleanupPeriodDays;
|
|
17
|
+
return typeof v === 'number' && Number.isFinite(v) && v >= 1 ? v : undefined;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Managed settings win over user settings; without either, Claude Code uses 30 days. */
|
|
24
|
+
export function cleanupPeriod(env = process.env, platform = process.platform) {
|
|
25
|
+
const managed = env.SPENDBYTEAM_MANAGED_SETTINGS ??
|
|
26
|
+
(platform === 'darwin'
|
|
27
|
+
? '/Library/Application Support/ClaudeCode/managed-settings.json'
|
|
28
|
+
: platform === 'win32'
|
|
29
|
+
? 'C:\\Program Files\\ClaudeCode\\managed-settings.json'
|
|
30
|
+
: '/etc/claude-code/managed-settings.json');
|
|
31
|
+
const m = readCleanupDays(managed);
|
|
32
|
+
if (m !== undefined)
|
|
33
|
+
return { days: m, source: 'managed' };
|
|
34
|
+
const configured = env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
|
|
35
|
+
const bases = configured?.length ? configured : [path.join(homeDir(), '.claude')];
|
|
36
|
+
for (const b of bases) {
|
|
37
|
+
const u = readCleanupDays(path.join(b, 'settings.json'));
|
|
38
|
+
if (u !== undefined)
|
|
39
|
+
return { days: u, source: 'settings' };
|
|
40
|
+
}
|
|
41
|
+
return { days: DEFAULT_CLEANUP_DAYS, source: 'default' };
|
|
42
|
+
}
|
|
8
43
|
/** Where Claude Code keeps its session logs: $CLAUDE_CONFIG_DIR (comma-separated), else ~/.claude and ~/.config/claude. */
|
|
9
44
|
export function logDirs() {
|
|
10
45
|
const configured = process.env.CLAUDE_CONFIG_DIR?.split(',').map((d) => d.trim()).filter(Boolean);
|
|
@@ -149,17 +184,39 @@ export async function buildReport(opts = {}) {
|
|
|
149
184
|
const dirs = opts.dirs ?? logDirs();
|
|
150
185
|
const files = dirs.flatMap((d) => jsonlFiles(d));
|
|
151
186
|
const { requests, sessionStart } = await readRequests(files, since, opts.onProgress);
|
|
152
|
-
|
|
187
|
+
let oldestMs = Infinity;
|
|
188
|
+
for (const f of files)
|
|
189
|
+
oldestMs = Math.min(oldestMs, fs.statSync(f).mtimeMs);
|
|
153
190
|
const unpriced = new Map();
|
|
154
|
-
const
|
|
155
|
-
let total = 0;
|
|
156
|
-
let tokens = 0;
|
|
157
|
-
let first = Infinity;
|
|
191
|
+
const priced = [];
|
|
158
192
|
for (const r of requests.values()) {
|
|
159
|
-
if (r.cost === undefined)
|
|
193
|
+
if (r.cost === undefined)
|
|
160
194
|
unpriced.set(r.model, (unpriced.get(r.model) ?? 0) + 1);
|
|
161
|
-
|
|
162
|
-
|
|
195
|
+
else
|
|
196
|
+
priced.push(r);
|
|
197
|
+
}
|
|
198
|
+
const sessions = new Set(priced.map((r) => r.session));
|
|
199
|
+
const total = priced.reduce((n, r) => n + r.cost, 0);
|
|
200
|
+
const tokens = priced.reduce((n, r) => n + r.tokens, 0);
|
|
201
|
+
const first = priced.reduce((n, r) => Math.min(n, r.at), Infinity);
|
|
202
|
+
const rows = groupRows(priced, by, total, sessionStart, since);
|
|
203
|
+
const views = opts.views ? Object.fromEntries(GROUPS.map((g) => [g, g === by ? rows : groupRows(priced, g, total, sessionStart, since)])) : undefined;
|
|
204
|
+
return {
|
|
205
|
+
from: since !== null ? localDay(since) : Number.isFinite(first) ? localDay(first) : null,
|
|
206
|
+
to: localDay(now.getTime()),
|
|
207
|
+
by,
|
|
208
|
+
rows,
|
|
209
|
+
total: { cost: total, requests: priced.length, sessions: sessions.size, tokens },
|
|
210
|
+
unpriced: [...unpriced.entries()].map(([model, n]) => ({ model, requests: n })).sort((a, b) => b.requests - a.requests),
|
|
211
|
+
files: files.length,
|
|
212
|
+
retention: { ...cleanupPeriod(), oldestLog: Number.isFinite(oldestMs) ? localDay(oldestMs) : null },
|
|
213
|
+
...(views ? { views } : {}),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/** One pass over the priced requests, grouped one way. */
|
|
217
|
+
function groupRows(priced, by, total, sessionStart, since) {
|
|
218
|
+
const groups = new Map();
|
|
219
|
+
for (const r of priced) {
|
|
163
220
|
const key = by === 'model' ? r.model : r[by];
|
|
164
221
|
const g = groups.get(key) ?? {
|
|
165
222
|
cost: 0,
|
|
@@ -183,12 +240,8 @@ export async function buildReport(opts = {}) {
|
|
|
183
240
|
g.projects.set(r.project, (g.projects.get(r.project) ?? 0) + r.cost);
|
|
184
241
|
g.models.set(r.model, (g.models.get(r.model) ?? 0) + r.cost);
|
|
185
242
|
groups.set(key, g);
|
|
186
|
-
sessions.add(r.session);
|
|
187
|
-
total += r.cost;
|
|
188
|
-
tokens += r.tokens;
|
|
189
|
-
first = Math.min(first, r.at);
|
|
190
243
|
}
|
|
191
|
-
|
|
244
|
+
return [...groups.entries()]
|
|
192
245
|
.map(([key, g]) => ({
|
|
193
246
|
key,
|
|
194
247
|
cost: g.cost,
|
|
@@ -207,15 +260,6 @@ export async function buildReport(opts = {}) {
|
|
|
207
260
|
: {}),
|
|
208
261
|
}))
|
|
209
262
|
.sort((a, b) => (by === 'day' ? a.key.localeCompare(b.key) : b.cost - a.cost));
|
|
210
|
-
return {
|
|
211
|
-
from: since !== null ? localDay(since) : Number.isFinite(first) ? localDay(first) : null,
|
|
212
|
-
to: localDay(now.getTime()),
|
|
213
|
-
by,
|
|
214
|
-
rows,
|
|
215
|
-
total: { cost: total, requests: [...groups.values()].reduce((n, g) => n + g.requests, 0), sessions: sessions.size, tokens },
|
|
216
|
-
unpriced: [...unpriced.entries()].map(([model, n]) => ({ model, requests: n })).sort((a, b) => b.requests - a.requests),
|
|
217
|
-
files: files.length,
|
|
218
|
-
};
|
|
219
263
|
}
|
|
220
264
|
const usd = (n) => `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
221
265
|
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);
|
|
@@ -274,13 +318,25 @@ export function renderReport(r) {
|
|
|
274
318
|
out.push(bold(fmt(totalRow)));
|
|
275
319
|
return finish(r, out);
|
|
276
320
|
}
|
|
321
|
+
/** Claude Code deletes session logs after cleanupPeriodDays (30 by default); say so, since this report can't see past it. */
|
|
322
|
+
export function retentionNote(t) {
|
|
323
|
+
if (t.days > 90)
|
|
324
|
+
return [];
|
|
325
|
+
const since = t.oldestLog ? `, so the oldest log left on this machine is from ${t.oldestLog}` : '';
|
|
326
|
+
const why = t.source === 'default' ? 'by default' : t.source === 'managed' ? 'set by your organization' : 'set in your settings.json';
|
|
327
|
+
const lines = ['', `${bold('Heads-up:')} Claude Code deletes these logs after ${t.days} days (${why})${since}.`];
|
|
328
|
+
if (t.source !== 'managed')
|
|
329
|
+
lines.push(dim(`To keep them, add "cleanupPeriodDays": 3650 to ~/.claude/settings.json.`));
|
|
330
|
+
return lines;
|
|
331
|
+
}
|
|
277
332
|
function finish(r, out) {
|
|
278
333
|
if (r.unpriced.length) {
|
|
279
334
|
out.push('');
|
|
280
335
|
out.push(dim(`Not priced (unknown model): ${r.unpriced.map((u) => `${u.model} × ${u.requests}`).join(', ')}`));
|
|
281
336
|
}
|
|
337
|
+
out.push(...retentionNote(r.retention));
|
|
282
338
|
out.push('');
|
|
283
|
-
out.push(`This is one machine. To see it for your whole team, per project and client:`);
|
|
339
|
+
out.push(`This is one machine. To see it for your whole team, per project and client, with up to 13 months of history:`);
|
|
284
340
|
out.push(` ${bold('npx spendbyteam connect')} ${dim(`(free for 3 developers · ${CTA_URL})`)}`);
|
|
285
341
|
return out.join('\n');
|
|
286
342
|
}
|
|
@@ -352,11 +408,36 @@ export async function report(opts = {}) {
|
|
|
352
408
|
const progress = progressLine();
|
|
353
409
|
let r;
|
|
354
410
|
try {
|
|
355
|
-
r = await buildReport({ onProgress: progress.onProgress, ...opts });
|
|
411
|
+
r = await buildReport({ onProgress: progress.onProgress, views: !opts.json, ...opts });
|
|
356
412
|
}
|
|
357
413
|
finally {
|
|
358
414
|
progress.clear();
|
|
359
415
|
}
|
|
360
416
|
console.log(opts.json ? JSON.stringify(r, null, 2) : renderReport(r));
|
|
417
|
+
if (!opts.json && r.rows.length > 0 && (opts.web ?? (await askToOpen())))
|
|
418
|
+
openHtml(r);
|
|
361
419
|
return r;
|
|
362
420
|
}
|
|
421
|
+
/** Only on a real terminal, never in CI or with piped input/output. Enter means yes. */
|
|
422
|
+
async function askToOpen() {
|
|
423
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CI)
|
|
424
|
+
return false;
|
|
425
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
426
|
+
try {
|
|
427
|
+
const a = (await rl.question('\nOpen this report in your browser, with bars? [Y/n] ')).trim().toLowerCase();
|
|
428
|
+
return a === '' || a === 'y' || a === 'yes';
|
|
429
|
+
}
|
|
430
|
+
finally {
|
|
431
|
+
rl.close();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** Writes the HTML report to a local file and opens it. Nothing is uploaded. */
|
|
435
|
+
export function htmlReportPath() {
|
|
436
|
+
return path.join(os.tmpdir(), 'spendbyteam-report.html');
|
|
437
|
+
}
|
|
438
|
+
function openHtml(r) {
|
|
439
|
+
const file = htmlReportPath();
|
|
440
|
+
fs.writeFileSync(file, renderHtml(r), { mode: 0o600 });
|
|
441
|
+
console.log(`Opened ${file} (a local file; nothing was uploaded).`);
|
|
442
|
+
openInBrowser(file);
|
|
443
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "spendbyteam",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
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",
|