@farryq/llmbill 0.0.0-stage → 0.1.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 +33 -2
- package/dist/chunk-CHPWFF3J.js +327 -0
- package/dist/chunk-CHPWFF3J.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +51 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +71 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 llmbill contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 💸 llmbill
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**1-second local AI coding agent cost & token ledger — scan Claude Code (`~/.claude/projects`) and Codex (`~/.codex/sessions`) JSONL logs to see your exact daily spend, prompt-cache hit rate, per-project breakdown, and most expensive sessions.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/farryq/llmbill/actions/workflows/ci.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](https://nodejs.org)
|
|
8
|
+
|
|
9
|
+
> 100% local · Zero network calls · Zero telemetry.
|
|
10
|
+
> Part of the **AI Agent Cost & Context Suite** alongside [`mcpweigh`](https://github.com/mcpweigh/mcpweigh), [`ruleweigh`](https://github.com/farryq/ruleweigh), and [`tokendiff`](https://github.com/farryq/tokendiff).
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Quick Start
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
# Preview immediately with realistic demo sessions (no local logs needed)
|
|
18
|
+
npx @farryq/llmbill --demo
|
|
19
|
+
|
|
20
|
+
# Audit your real local Claude Code & Codex usage from the last 7 days
|
|
21
|
+
npx @farryq/llmbill --days 7
|
|
22
|
+
|
|
23
|
+
# Export a standalone dark-mode HTML cost dashboard
|
|
24
|
+
npx @farryq/llmbill --days 30 --format html --out ai-bill.html
|
|
25
|
+
|
|
26
|
+
# Enforce a daily/window USD budget alert in scripts
|
|
27
|
+
npx @farryq/llmbill --days 7 --budget 25
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## License
|
|
33
|
+
|
|
34
|
+
[MIT](LICENSE) © 2026 llmbill contributors
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// src/pricing.ts
|
|
2
|
+
var PRICING_TABLE = [
|
|
3
|
+
{ match: /opus/i, price: { inputPer1M: 15, outputPer1M: 75, cacheReadPer1M: 1.5, cacheWritePer1M: 18.75 } },
|
|
4
|
+
{ match: /sonnet/i, price: { inputPer1M: 3, outputPer1M: 15, cacheReadPer1M: 0.3, cacheWritePer1M: 3.75 } },
|
|
5
|
+
{ match: /haiku/i, price: { inputPer1M: 0.8, outputPer1M: 4, cacheReadPer1M: 0.08, cacheWritePer1M: 1 } },
|
|
6
|
+
{ match: /gpt-5|o3|o4/i, price: { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.125, cacheWritePer1M: 1.25 } },
|
|
7
|
+
{ match: /gpt-4\.1/i, price: { inputPer1M: 2, outputPer1M: 8, cacheReadPer1M: 0.5, cacheWritePer1M: 2 } },
|
|
8
|
+
{ match: /gemini.*pro/i, price: { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.31, cacheWritePer1M: 1.25 } },
|
|
9
|
+
{ match: /gemini.*flash/i, price: { inputPer1M: 0.15, outputPer1M: 0.6, cacheReadPer1M: 0.0375, cacheWritePer1M: 0.15 } }
|
|
10
|
+
];
|
|
11
|
+
var DEFAULT_PRICE = {
|
|
12
|
+
inputPer1M: 3,
|
|
13
|
+
outputPer1M: 15,
|
|
14
|
+
cacheReadPer1M: 0.3,
|
|
15
|
+
cacheWritePer1M: 3.75
|
|
16
|
+
};
|
|
17
|
+
function resolveModelPrice(model) {
|
|
18
|
+
for (const row of PRICING_TABLE) {
|
|
19
|
+
if (row.match.test(model)) return row.price;
|
|
20
|
+
}
|
|
21
|
+
return DEFAULT_PRICE;
|
|
22
|
+
}
|
|
23
|
+
function computeUsageCostUsd(model, usage) {
|
|
24
|
+
const p = resolveModelPrice(model);
|
|
25
|
+
return usage.inputTokens / 1e6 * p.inputPer1M + usage.outputTokens / 1e6 * p.outputPer1M + usage.cacheReadTokens / 1e6 * p.cacheReadPer1M + usage.cacheWriteTokens / 1e6 * p.cacheWritePer1M;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// src/reporter.ts
|
|
29
|
+
import chalk from "chalk";
|
|
30
|
+
import Table from "cli-table3";
|
|
31
|
+
function renderTerminalReport(report) {
|
|
32
|
+
const lines = [];
|
|
33
|
+
lines.push(chalk.bold.cyan(`
|
|
34
|
+
llmbill \u2014 Local AI Coding Agent Cost Ledger (Last ${report.days}d)
|
|
35
|
+
`));
|
|
36
|
+
lines.push(
|
|
37
|
+
` Total Spend : ${chalk.bold.green(`$${report.totalCostUsd.toFixed(2)}`)} across ${report.sessionCount} session(s) (${report.eventCount} turns)`
|
|
38
|
+
);
|
|
39
|
+
lines.push(
|
|
40
|
+
` Total Tokens : ${chalk.bold(report.totalTokens.toLocaleString())} (cache hit rate: ${chalk.cyan(`${report.cacheHitRatePct}%`)})
|
|
41
|
+
`
|
|
42
|
+
);
|
|
43
|
+
const dayTable = new Table({
|
|
44
|
+
head: ["Date", "Turns", "Total Tokens", "Cache Read", "Est. USD"],
|
|
45
|
+
style: { head: ["cyan"] }
|
|
46
|
+
});
|
|
47
|
+
for (const row of report.byDay) {
|
|
48
|
+
dayTable.push([
|
|
49
|
+
row.key,
|
|
50
|
+
String(row.events),
|
|
51
|
+
row.totalTokens.toLocaleString(),
|
|
52
|
+
row.cacheReadTokens.toLocaleString(),
|
|
53
|
+
`$${row.costUsd.toFixed(2)}`
|
|
54
|
+
]);
|
|
55
|
+
}
|
|
56
|
+
lines.push(dayTable.toString());
|
|
57
|
+
if (report.byModel.length > 0) {
|
|
58
|
+
const modelTable = new Table({
|
|
59
|
+
head: ["Model", "Turns", "Total Tokens", "Est. USD"],
|
|
60
|
+
style: { head: ["cyan"] }
|
|
61
|
+
});
|
|
62
|
+
for (const row of report.byModel) {
|
|
63
|
+
modelTable.push([row.key, String(row.events), row.totalTokens.toLocaleString(), `$${row.costUsd.toFixed(2)}`]);
|
|
64
|
+
}
|
|
65
|
+
lines.push(`
|
|
66
|
+
${modelTable.toString()}`);
|
|
67
|
+
}
|
|
68
|
+
if (report.budgetExceeded && report.budgetUsd !== void 0) {
|
|
69
|
+
lines.push(
|
|
70
|
+
chalk.red(`
|
|
71
|
+
\u2717 Spend budget exceeded: $${report.totalCostUsd.toFixed(2)} > $${report.budgetUsd.toFixed(2)}`)
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
lines.push(
|
|
75
|
+
chalk.gray(
|
|
76
|
+
"\n Tip: Cut context bloat with `npx @farryq/mcpweigh`, `npx @farryq/ruleweigh`, and `npx @farryq/tokendiff`."
|
|
77
|
+
)
|
|
78
|
+
);
|
|
79
|
+
return `${lines.join("\n")}
|
|
80
|
+
`;
|
|
81
|
+
}
|
|
82
|
+
function renderMarkdownReport(report) {
|
|
83
|
+
const rows = report.byDay.map(
|
|
84
|
+
(r) => `| ${r.key} | ${r.events} | ${r.totalTokens.toLocaleString()} | ${r.cacheReadTokens.toLocaleString()} | $${r.costUsd.toFixed(2)} |`
|
|
85
|
+
);
|
|
86
|
+
return [
|
|
87
|
+
`## llmbill \u2014 AI Agent Cost Summary (Last ${report.days}d)`,
|
|
88
|
+
"",
|
|
89
|
+
`- **Total Spend**: **$${report.totalCostUsd.toFixed(2)}** (${report.sessionCount} sessions, ${report.eventCount} turns)`,
|
|
90
|
+
`- **Total Tokens**: ${report.totalTokens.toLocaleString()} (Prompt Cache Hit Rate: ${report.cacheHitRatePct}%)`,
|
|
91
|
+
"",
|
|
92
|
+
"| Date | Turns | Total Tokens | Cache Read | Est. USD |",
|
|
93
|
+
"| :--- | ---: | ---: | ---: | ---: |",
|
|
94
|
+
...rows,
|
|
95
|
+
""
|
|
96
|
+
].join("\n");
|
|
97
|
+
}
|
|
98
|
+
function renderHtmlReport(report) {
|
|
99
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
100
|
+
const dayRows = report.byDay.map(
|
|
101
|
+
(r) => `<tr><td>${esc(r.key)}</td><td>${r.events}</td><td>${r.totalTokens.toLocaleString()}</td><td>${r.cacheReadTokens.toLocaleString()}</td><td><strong>$${r.costUsd.toFixed(2)}</strong></td></tr>`
|
|
102
|
+
).join("");
|
|
103
|
+
const projRows = report.byProject.map(
|
|
104
|
+
(r) => `<tr><td><code>${esc(r.key)}</code></td><td>${r.events}</td><td>${r.totalTokens.toLocaleString()}</td><td><strong>$${r.costUsd.toFixed(2)}</strong></td></tr>`
|
|
105
|
+
).join("");
|
|
106
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>llmbill Cost Dashboard</title><style>body{background:#0b1020;color:#e5e7eb;font-family:system-ui,sans-serif;max-width:960px;margin:2rem auto;padding:0 1rem}h1{color:#38bdf8}table{width:100%;border-collapse:collapse;margin:1rem 0 2rem}th,td{border-bottom:1px solid #1f2937;padding:.6rem;text-align:left}th{color:#7dd3fc}</style></head><body><h1>llmbill Cost Dashboard (Last ${report.days}d)</h1><p>Total Spend: <strong>$${report.totalCostUsd.toFixed(2)}</strong> · Tokens: <strong>${report.totalTokens.toLocaleString()}</strong> · Cache Hit Rate: <strong>${report.cacheHitRatePct}%</strong></p><h2>Daily Breakdown</h2><table><thead><tr><th>Date</th><th>Turns</th><th>Total Tokens</th><th>Cache Read</th><th>Est. USD</th></tr></thead><tbody>${dayRows}</tbody></table><h2>By Project</h2><table><thead><tr><th>Project</th><th>Turns</th><th>Total Tokens</th><th>Est. USD</th></tr></thead><tbody>${projRows}</tbody></table></body></html>`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/scanner.ts
|
|
110
|
+
import fs from "fs";
|
|
111
|
+
import os from "os";
|
|
112
|
+
import path from "path";
|
|
113
|
+
function walkJsonl(dir, out, depth = 0) {
|
|
114
|
+
if (depth > 4 || !fs.existsSync(dir)) return;
|
|
115
|
+
let entries;
|
|
116
|
+
try {
|
|
117
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
118
|
+
} catch {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
for (const e of entries) {
|
|
122
|
+
const full = path.join(dir, e.name);
|
|
123
|
+
if (e.isDirectory()) walkJsonl(full, out, depth + 1);
|
|
124
|
+
else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(full);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function asNumber(v) {
|
|
128
|
+
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0;
|
|
129
|
+
}
|
|
130
|
+
function parseUsageJsonlFile(filePath, source) {
|
|
131
|
+
let raw;
|
|
132
|
+
try {
|
|
133
|
+
raw = fs.readFileSync(filePath, "utf8");
|
|
134
|
+
} catch {
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
const events = [];
|
|
138
|
+
const project = path.basename(path.dirname(filePath)) || "default";
|
|
139
|
+
const sessionId = path.basename(filePath, ".jsonl");
|
|
140
|
+
const fallbackDate = fs.statSync(filePath).mtime.toISOString().slice(0, 10);
|
|
141
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
142
|
+
const trimmed = line.trim();
|
|
143
|
+
if (!trimmed || !trimmed.startsWith("{")) continue;
|
|
144
|
+
let obj;
|
|
145
|
+
try {
|
|
146
|
+
obj = JSON.parse(trimmed);
|
|
147
|
+
} catch {
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const msg = obj.message && typeof obj.message === "object" ? obj.message : void 0;
|
|
151
|
+
const payload = obj.payload && typeof obj.payload === "object" ? obj.payload : void 0;
|
|
152
|
+
const info = payload?.info && typeof payload.info === "object" ? payload.info : void 0;
|
|
153
|
+
const usageObj = (msg?.usage && typeof msg.usage === "object" ? msg.usage : void 0) ?? (info?.last_token_usage && typeof info.last_token_usage === "object" ? info.last_token_usage : void 0) ?? (obj.usage && typeof obj.usage === "object" ? obj.usage : void 0);
|
|
154
|
+
if (!usageObj) continue;
|
|
155
|
+
const inputTokens = asNumber(usageObj.input_tokens ?? usageObj.prompt_tokens);
|
|
156
|
+
const outputTokens = asNumber(usageObj.output_tokens ?? usageObj.completion_tokens);
|
|
157
|
+
const cacheReadTokens = asNumber(usageObj.cache_read_input_tokens ?? usageObj.cached_input_tokens);
|
|
158
|
+
const cacheWriteTokens = asNumber(usageObj.cache_creation_input_tokens);
|
|
159
|
+
if (inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens === 0) continue;
|
|
160
|
+
const model = String(msg?.model ?? obj.model ?? payload?.model ?? "claude-sonnet-4-5");
|
|
161
|
+
const tsRaw = String(obj.timestamp ?? obj.created_at ?? `${fallbackDate}T00:00:00Z`);
|
|
162
|
+
const date = /^\d{4}-\d{2}-\d{2}/.test(tsRaw) ? tsRaw.slice(0, 10) : fallbackDate;
|
|
163
|
+
const costUsd = computeUsageCostUsd(model, {
|
|
164
|
+
inputTokens,
|
|
165
|
+
outputTokens,
|
|
166
|
+
cacheReadTokens,
|
|
167
|
+
cacheWriteTokens
|
|
168
|
+
});
|
|
169
|
+
events.push({
|
|
170
|
+
timestamp: tsRaw,
|
|
171
|
+
date,
|
|
172
|
+
source,
|
|
173
|
+
project: String(obj.project ?? project),
|
|
174
|
+
sessionId: String(obj.session_id ?? sessionId),
|
|
175
|
+
model,
|
|
176
|
+
inputTokens,
|
|
177
|
+
outputTokens,
|
|
178
|
+
cacheReadTokens,
|
|
179
|
+
cacheWriteTokens,
|
|
180
|
+
costUsd
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return events;
|
|
184
|
+
}
|
|
185
|
+
function discoverAndScanLogs(options = {}) {
|
|
186
|
+
const events = [];
|
|
187
|
+
if (options.customPath) {
|
|
188
|
+
const abs = path.resolve(options.customPath);
|
|
189
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
|
|
190
|
+
return parseUsageJsonlFile(abs, "custom");
|
|
191
|
+
}
|
|
192
|
+
const files = [];
|
|
193
|
+
walkJsonl(abs, files);
|
|
194
|
+
for (const f of files) events.push(...parseUsageJsonlFile(f, "custom"));
|
|
195
|
+
return events;
|
|
196
|
+
}
|
|
197
|
+
const home = options.homeDir ?? os.homedir();
|
|
198
|
+
const roots = [
|
|
199
|
+
{ dir: path.join(home, ".claude", "projects"), source: "claude-code" },
|
|
200
|
+
{ dir: path.join(home, ".codex", "sessions"), source: "codex" }
|
|
201
|
+
];
|
|
202
|
+
for (const r of roots) {
|
|
203
|
+
const files = [];
|
|
204
|
+
walkJsonl(r.dir, files);
|
|
205
|
+
for (const f of files) events.push(...parseUsageJsonlFile(f, r.source));
|
|
206
|
+
}
|
|
207
|
+
return events;
|
|
208
|
+
}
|
|
209
|
+
function summarizeBy(events, keyFn, sortByKeyDesc = false) {
|
|
210
|
+
const map = /* @__PURE__ */ new Map();
|
|
211
|
+
for (const e of events) {
|
|
212
|
+
const key = keyFn(e);
|
|
213
|
+
const cur = map.get(key) ?? {
|
|
214
|
+
key,
|
|
215
|
+
events: 0,
|
|
216
|
+
inputTokens: 0,
|
|
217
|
+
outputTokens: 0,
|
|
218
|
+
cacheReadTokens: 0,
|
|
219
|
+
totalTokens: 0,
|
|
220
|
+
costUsd: 0
|
|
221
|
+
};
|
|
222
|
+
cur.events += 1;
|
|
223
|
+
cur.inputTokens += e.inputTokens;
|
|
224
|
+
cur.outputTokens += e.outputTokens;
|
|
225
|
+
cur.cacheReadTokens += e.cacheReadTokens;
|
|
226
|
+
cur.totalTokens += e.inputTokens + e.outputTokens + e.cacheReadTokens + e.cacheWriteTokens;
|
|
227
|
+
cur.costUsd += e.costUsd;
|
|
228
|
+
map.set(key, cur);
|
|
229
|
+
}
|
|
230
|
+
const rows = [...map.values()].map((r) => ({ ...r, costUsd: Number(r.costUsd.toFixed(4)) }));
|
|
231
|
+
if (sortByKeyDesc) {
|
|
232
|
+
return rows.sort((a, b) => b.key.localeCompare(a.key));
|
|
233
|
+
}
|
|
234
|
+
return rows.sort((a, b) => b.costUsd - a.costUsd);
|
|
235
|
+
}
|
|
236
|
+
function buildBillReport(allEvents, options = {}) {
|
|
237
|
+
const days = options.days ?? 7;
|
|
238
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
239
|
+
const cutoffDate = new Date(nowMs - days * 864e5).toISOString().slice(0, 10);
|
|
240
|
+
const events = days > 0 ? allEvents.filter((e) => e.date >= cutoffDate) : allEvents;
|
|
241
|
+
const totalInputTokens = events.reduce((s, e) => s + e.inputTokens, 0);
|
|
242
|
+
const totalOutputTokens = events.reduce((s, e) => s + e.outputTokens, 0);
|
|
243
|
+
const totalCacheReadTokens = events.reduce((s, e) => s + e.cacheReadTokens, 0);
|
|
244
|
+
const totalCacheWriteTokens = events.reduce((s, e) => s + e.cacheWriteTokens, 0);
|
|
245
|
+
const totalTokens = totalInputTokens + totalOutputTokens + totalCacheReadTokens + totalCacheWriteTokens;
|
|
246
|
+
const totalInputPool = totalInputTokens + totalCacheReadTokens + totalCacheWriteTokens;
|
|
247
|
+
const cacheHitRatePct = totalInputPool > 0 ? Number((totalCacheReadTokens / totalInputPool * 100).toFixed(1)) : 0;
|
|
248
|
+
const totalCostUsd = Number(events.reduce((s, e) => s + e.costUsd, 0).toFixed(4));
|
|
249
|
+
const sessions = new Set(events.map((e) => `${e.project}/${e.sessionId}`));
|
|
250
|
+
return {
|
|
251
|
+
days,
|
|
252
|
+
eventCount: events.length,
|
|
253
|
+
sessionCount: sessions.size,
|
|
254
|
+
totalInputTokens,
|
|
255
|
+
totalOutputTokens,
|
|
256
|
+
totalCacheReadTokens,
|
|
257
|
+
totalCacheWriteTokens,
|
|
258
|
+
totalTokens,
|
|
259
|
+
cacheHitRatePct,
|
|
260
|
+
totalCostUsd,
|
|
261
|
+
budgetUsd: options.budgetUsd,
|
|
262
|
+
budgetExceeded: options.budgetUsd !== void 0 ? totalCostUsd > options.budgetUsd : false,
|
|
263
|
+
byDay: summarizeBy(events, (e) => e.date, true),
|
|
264
|
+
byModel: summarizeBy(events, (e) => e.model),
|
|
265
|
+
byProject: summarizeBy(events, (e) => e.project),
|
|
266
|
+
topSessions: summarizeBy(events, (e) => `${e.project}/${e.sessionId}`).slice(0, 5)
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function buildDemoEvents() {
|
|
270
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
271
|
+
const yest = new Date(Date.now() - 864e5).toISOString().slice(0, 10);
|
|
272
|
+
const raw = [
|
|
273
|
+
{
|
|
274
|
+
timestamp: `${today}T09:15:00Z`,
|
|
275
|
+
date: today,
|
|
276
|
+
source: "claude-code",
|
|
277
|
+
project: "checkout-service",
|
|
278
|
+
sessionId: "sess-refactor-auth",
|
|
279
|
+
model: "claude-sonnet-4-5",
|
|
280
|
+
inputTokens: 18e4,
|
|
281
|
+
outputTokens: 32e3,
|
|
282
|
+
cacheReadTokens: 125e4,
|
|
283
|
+
cacheWriteTokens: 45e3
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
timestamp: `${today}T14:20:00Z`,
|
|
287
|
+
date: today,
|
|
288
|
+
source: "codex",
|
|
289
|
+
project: "analytics-worker",
|
|
290
|
+
sessionId: "sess-sql-migration",
|
|
291
|
+
model: "gpt-5",
|
|
292
|
+
inputTokens: 95e3,
|
|
293
|
+
outputTokens: 18500,
|
|
294
|
+
cacheReadTokens: 42e4,
|
|
295
|
+
cacheWriteTokens: 0
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
timestamp: `${yest}T19:40:00Z`,
|
|
299
|
+
date: yest,
|
|
300
|
+
source: "claude-code",
|
|
301
|
+
project: "checkout-service",
|
|
302
|
+
sessionId: "sess-heavy-mcp-loop",
|
|
303
|
+
model: "claude-opus-4-5",
|
|
304
|
+
inputTokens: 21e4,
|
|
305
|
+
outputTokens: 28e3,
|
|
306
|
+
cacheReadTokens: 64e4,
|
|
307
|
+
cacheWriteTokens: 6e4
|
|
308
|
+
}
|
|
309
|
+
];
|
|
310
|
+
return raw.map((e) => ({
|
|
311
|
+
...e,
|
|
312
|
+
costUsd: computeUsageCostUsd(e.model, e)
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export {
|
|
317
|
+
resolveModelPrice,
|
|
318
|
+
computeUsageCostUsd,
|
|
319
|
+
renderTerminalReport,
|
|
320
|
+
renderMarkdownReport,
|
|
321
|
+
renderHtmlReport,
|
|
322
|
+
parseUsageJsonlFile,
|
|
323
|
+
discoverAndScanLogs,
|
|
324
|
+
buildBillReport,
|
|
325
|
+
buildDemoEvents
|
|
326
|
+
};
|
|
327
|
+
//# sourceMappingURL=chunk-CHPWFF3J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pricing.ts","../src/reporter.ts","../src/scanner.ts"],"sourcesContent":["export interface ModelPrice {\n inputPer1M: number;\n outputPer1M: number;\n cacheReadPer1M: number;\n cacheWritePer1M: number;\n}\n\nconst PRICING_TABLE: Array<{ match: RegExp; price: ModelPrice }> = [\n { match: /opus/i, price: { inputPer1M: 15.0, outputPer1M: 75.0, cacheReadPer1M: 1.5, cacheWritePer1M: 18.75 } },\n { match: /sonnet/i, price: { inputPer1M: 3.0, outputPer1M: 15.0, cacheReadPer1M: 0.3, cacheWritePer1M: 3.75 } },\n { match: /haiku/i, price: { inputPer1M: 0.8, outputPer1M: 4.0, cacheReadPer1M: 0.08, cacheWritePer1M: 1.0 } },\n { match: /gpt-5|o3|o4/i, price: { inputPer1M: 1.25, outputPer1M: 10.0, cacheReadPer1M: 0.125, cacheWritePer1M: 1.25 } },\n { match: /gpt-4\\.1/i, price: { inputPer1M: 2.0, outputPer1M: 8.0, cacheReadPer1M: 0.5, cacheWritePer1M: 2.0 } },\n { match: /gemini.*pro/i, price: { inputPer1M: 1.25, outputPer1M: 10.0, cacheReadPer1M: 0.31, cacheWritePer1M: 1.25 } },\n { match: /gemini.*flash/i, price: { inputPer1M: 0.15, outputPer1M: 0.6, cacheReadPer1M: 0.0375, cacheWritePer1M: 0.15 } },\n];\n\nconst DEFAULT_PRICE: ModelPrice = {\n inputPer1M: 3.0,\n outputPer1M: 15.0,\n cacheReadPer1M: 0.3,\n cacheWritePer1M: 3.75,\n};\n\nexport function resolveModelPrice(model: string): ModelPrice {\n for (const row of PRICING_TABLE) {\n if (row.match.test(model)) return row.price;\n }\n return DEFAULT_PRICE;\n}\n\nexport function computeUsageCostUsd(\n model: string,\n usage: { inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }\n): number {\n const p = resolveModelPrice(model);\n return (\n (usage.inputTokens / 1_000_000) * p.inputPer1M +\n (usage.outputTokens / 1_000_000) * p.outputPer1M +\n (usage.cacheReadTokens / 1_000_000) * p.cacheReadPer1M +\n (usage.cacheWriteTokens / 1_000_000) * p.cacheWritePer1M\n );\n}\n","import chalk from 'chalk';\nimport Table from 'cli-table3';\nimport type { BillReport } from './scanner.js';\n\nexport function renderTerminalReport(report: BillReport): string {\n const lines: string[] = [];\n lines.push(chalk.bold.cyan(`\\n llmbill — Local AI Coding Agent Cost Ledger (Last ${report.days}d)\\n`));\n lines.push(\n ` Total Spend : ${chalk.bold.green(`$${report.totalCostUsd.toFixed(2)}`)} across ${report.sessionCount} session(s) (${report.eventCount} turns)`\n );\n lines.push(\n ` Total Tokens : ${chalk.bold(report.totalTokens.toLocaleString())} (cache hit rate: ${chalk.cyan(`${report.cacheHitRatePct}%`)})\\n`\n );\n\n const dayTable = new Table({\n head: ['Date', 'Turns', 'Total Tokens', 'Cache Read', 'Est. USD'],\n style: { head: ['cyan'] },\n });\n for (const row of report.byDay) {\n dayTable.push([\n row.key,\n String(row.events),\n row.totalTokens.toLocaleString(),\n row.cacheReadTokens.toLocaleString(),\n `$${row.costUsd.toFixed(2)}`,\n ]);\n }\n lines.push(dayTable.toString());\n\n if (report.byModel.length > 0) {\n const modelTable = new Table({\n head: ['Model', 'Turns', 'Total Tokens', 'Est. USD'],\n style: { head: ['cyan'] },\n });\n for (const row of report.byModel) {\n modelTable.push([row.key, String(row.events), row.totalTokens.toLocaleString(), `$${row.costUsd.toFixed(2)}`]);\n }\n lines.push(`\\n${modelTable.toString()}`);\n }\n\n if (report.budgetExceeded && report.budgetUsd !== undefined) {\n lines.push(\n chalk.red(`\\n ✗ Spend budget exceeded: $${report.totalCostUsd.toFixed(2)} > $${report.budgetUsd.toFixed(2)}`)\n );\n }\n lines.push(\n chalk.gray(\n '\\n Tip: Cut context bloat with `npx @farryq/mcpweigh`, `npx @farryq/ruleweigh`, and `npx @farryq/tokendiff`.'\n )\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nexport function renderMarkdownReport(report: BillReport): string {\n const rows = report.byDay.map(\n (r) => `| ${r.key} | ${r.events} | ${r.totalTokens.toLocaleString()} | ${r.cacheReadTokens.toLocaleString()} | $${r.costUsd.toFixed(2)} |`\n );\n return [\n `## llmbill — AI Agent Cost Summary (Last ${report.days}d)`,\n '',\n `- **Total Spend**: **$${report.totalCostUsd.toFixed(2)}** (${report.sessionCount} sessions, ${report.eventCount} turns)`,\n `- **Total Tokens**: ${report.totalTokens.toLocaleString()} (Prompt Cache Hit Rate: ${report.cacheHitRatePct}%)`,\n '',\n '| Date | Turns | Total Tokens | Cache Read | Est. USD |',\n '| :--- | ---: | ---: | ---: | ---: |',\n ...rows,\n '',\n ].join('\\n');\n}\n\nexport function renderHtmlReport(report: BillReport): string {\n const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n const dayRows = report.byDay\n .map(\n (r) =>\n `<tr><td>${esc(r.key)}</td><td>${r.events}</td><td>${r.totalTokens.toLocaleString()}</td><td>${r.cacheReadTokens.toLocaleString()}</td><td><strong>$${r.costUsd.toFixed(2)}</strong></td></tr>`\n )\n .join('');\n const projRows = report.byProject\n .map(\n (r) =>\n `<tr><td><code>${esc(r.key)}</code></td><td>${r.events}</td><td>${r.totalTokens.toLocaleString()}</td><td><strong>$${r.costUsd.toFixed(2)}</strong></td></tr>`\n )\n .join('');\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>llmbill Cost Dashboard</title><style>body{background:#0b1020;color:#e5e7eb;font-family:system-ui,sans-serif;max-width:960px;margin:2rem auto;padding:0 1rem}h1{color:#38bdf8}table{width:100%;border-collapse:collapse;margin:1rem 0 2rem}th,td{border-bottom:1px solid #1f2937;padding:.6rem;text-align:left}th{color:#7dd3fc}</style></head><body><h1>llmbill Cost Dashboard (Last ${report.days}d)</h1><p>Total Spend: <strong>$${report.totalCostUsd.toFixed(2)}</strong> · Tokens: <strong>${report.totalTokens.toLocaleString()}</strong> · Cache Hit Rate: <strong>${report.cacheHitRatePct}%</strong></p><h2>Daily Breakdown</h2><table><thead><tr><th>Date</th><th>Turns</th><th>Total Tokens</th><th>Cache Read</th><th>Est. USD</th></tr></thead><tbody>${dayRows}</tbody></table><h2>By Project</h2><table><thead><tr><th>Project</th><th>Turns</th><th>Total Tokens</th><th>Est. USD</th></tr></thead><tbody>${projRows}</tbody></table></body></html>`;\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { computeUsageCostUsd } from './pricing.js';\n\nexport interface UsageEvent {\n timestamp: string;\n date: string;\n source: 'claude-code' | 'codex' | 'custom';\n project: string;\n sessionId: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n costUsd: number;\n}\n\nexport interface GroupSummary {\n key: string;\n events: number;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n totalTokens: number;\n costUsd: number;\n}\n\nexport interface BillReport {\n days: number;\n eventCount: number;\n sessionCount: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n totalCacheReadTokens: number;\n totalCacheWriteTokens: number;\n totalTokens: number;\n cacheHitRatePct: number;\n totalCostUsd: number;\n budgetUsd?: number;\n budgetExceeded: boolean;\n byDay: GroupSummary[];\n byModel: GroupSummary[];\n byProject: GroupSummary[];\n topSessions: GroupSummary[];\n}\n\nfunction walkJsonl(dir: string, out: string[], depth = 0): void {\n if (depth > 4 || !fs.existsSync(dir)) return;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const full = path.join(dir, e.name);\n if (e.isDirectory()) walkJsonl(full, out, depth + 1);\n else if (e.isFile() && e.name.endsWith('.jsonl')) out.push(full);\n }\n}\n\nfunction asNumber(v: unknown): number {\n return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0;\n}\n\nexport function parseUsageJsonlFile(\n filePath: string,\n source: 'claude-code' | 'codex' | 'custom'\n): UsageEvent[] {\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf8');\n } catch {\n return [];\n }\n\n const events: UsageEvent[] = [];\n const project = path.basename(path.dirname(filePath)) || 'default';\n const sessionId = path.basename(filePath, '.jsonl');\n const fallbackDate = fs.statSync(filePath).mtime.toISOString().slice(0, 10);\n\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith('{')) continue;\n let obj: Record<string, unknown>;\n try {\n obj = JSON.parse(trimmed) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n // Support Claude Code (`message.usage`), Codex (`payload.info.last_token_usage` / `usage`), and generic JSONL (`usage`)\n const msg = obj.message && typeof obj.message === 'object' ? (obj.message as Record<string, unknown>) : undefined;\n const payload = obj.payload && typeof obj.payload === 'object' ? (obj.payload as Record<string, unknown>) : undefined;\n const info = payload?.info && typeof payload.info === 'object' ? (payload.info as Record<string, unknown>) : undefined;\n\n const usageObj =\n (msg?.usage && typeof msg.usage === 'object' ? (msg.usage as Record<string, unknown>) : undefined) ??\n (info?.last_token_usage && typeof info.last_token_usage === 'object'\n ? (info.last_token_usage as Record<string, unknown>)\n : undefined) ??\n (obj.usage && typeof obj.usage === 'object' ? (obj.usage as Record<string, unknown>) : undefined);\n\n if (!usageObj) continue;\n\n const inputTokens = asNumber(usageObj.input_tokens ?? usageObj.prompt_tokens);\n const outputTokens = asNumber(usageObj.output_tokens ?? usageObj.completion_tokens);\n const cacheReadTokens = asNumber(usageObj.cache_read_input_tokens ?? usageObj.cached_input_tokens);\n const cacheWriteTokens = asNumber(usageObj.cache_creation_input_tokens);\n if (inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens === 0) continue;\n\n const model = String(msg?.model ?? obj.model ?? payload?.model ?? 'claude-sonnet-4-5');\n const tsRaw = String(obj.timestamp ?? obj.created_at ?? `${fallbackDate}T00:00:00Z`);\n const date = /^\\d{4}-\\d{2}-\\d{2}/.test(tsRaw) ? tsRaw.slice(0, 10) : fallbackDate;\n const costUsd = computeUsageCostUsd(model, {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n });\n\n events.push({\n timestamp: tsRaw,\n date,\n source,\n project: String(obj.project ?? project),\n sessionId: String(obj.session_id ?? sessionId),\n model,\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n costUsd,\n });\n }\n\n return events;\n}\n\nexport function discoverAndScanLogs(options: { homeDir?: string; customPath?: string } = {}): UsageEvent[] {\n const events: UsageEvent[] = [];\n if (options.customPath) {\n const abs = path.resolve(options.customPath);\n if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {\n return parseUsageJsonlFile(abs, 'custom');\n }\n const files: string[] = [];\n walkJsonl(abs, files);\n for (const f of files) events.push(...parseUsageJsonlFile(f, 'custom'));\n return events;\n }\n\n const home = options.homeDir ?? os.homedir();\n const roots: Array<{ dir: string; source: 'claude-code' | 'codex' }> = [\n { dir: path.join(home, '.claude', 'projects'), source: 'claude-code' },\n { dir: path.join(home, '.codex', 'sessions'), source: 'codex' },\n ];\n\n for (const r of roots) {\n const files: string[] = [];\n walkJsonl(r.dir, files);\n for (const f of files) events.push(...parseUsageJsonlFile(f, r.source));\n }\n return events;\n}\n\nfunction summarizeBy(events: UsageEvent[], keyFn: (e: UsageEvent) => string, sortByKeyDesc = false): GroupSummary[] {\n const map = new Map<string, GroupSummary>();\n for (const e of events) {\n const key = keyFn(e);\n const cur = map.get(key) ?? {\n key,\n events: 0,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n totalTokens: 0,\n costUsd: 0,\n };\n cur.events += 1;\n cur.inputTokens += e.inputTokens;\n cur.outputTokens += e.outputTokens;\n cur.cacheReadTokens += e.cacheReadTokens;\n cur.totalTokens += e.inputTokens + e.outputTokens + e.cacheReadTokens + e.cacheWriteTokens;\n cur.costUsd += e.costUsd;\n map.set(key, cur);\n }\n const rows = [...map.values()].map((r) => ({ ...r, costUsd: Number(r.costUsd.toFixed(4)) }));\n if (sortByKeyDesc) {\n return rows.sort((a, b) => b.key.localeCompare(a.key));\n }\n return rows.sort((a, b) => b.costUsd - a.costUsd);\n}\n\nexport function buildBillReport(\n allEvents: UsageEvent[],\n options: { days?: number; budgetUsd?: number; nowMs?: number } = {}\n): BillReport {\n const days = options.days ?? 7;\n const nowMs = options.nowMs ?? Date.now();\n const cutoffDate = new Date(nowMs - days * 86_400_000).toISOString().slice(0, 10);\n const events = days > 0 ? allEvents.filter((e) => e.date >= cutoffDate) : allEvents;\n\n const totalInputTokens = events.reduce((s, e) => s + e.inputTokens, 0);\n const totalOutputTokens = events.reduce((s, e) => s + e.outputTokens, 0);\n const totalCacheReadTokens = events.reduce((s, e) => s + e.cacheReadTokens, 0);\n const totalCacheWriteTokens = events.reduce((s, e) => s + e.cacheWriteTokens, 0);\n const totalTokens = totalInputTokens + totalOutputTokens + totalCacheReadTokens + totalCacheWriteTokens;\n const totalInputPool = totalInputTokens + totalCacheReadTokens + totalCacheWriteTokens;\n const cacheHitRatePct =\n totalInputPool > 0 ? Number(((totalCacheReadTokens / totalInputPool) * 100).toFixed(1)) : 0;\n const totalCostUsd = Number(events.reduce((s, e) => s + e.costUsd, 0).toFixed(4));\n const sessions = new Set(events.map((e) => `${e.project}/${e.sessionId}`));\n\n return {\n days,\n eventCount: events.length,\n sessionCount: sessions.size,\n totalInputTokens,\n totalOutputTokens,\n totalCacheReadTokens,\n totalCacheWriteTokens,\n totalTokens,\n cacheHitRatePct,\n totalCostUsd,\n budgetUsd: options.budgetUsd,\n budgetExceeded: options.budgetUsd !== undefined ? totalCostUsd > options.budgetUsd : false,\n byDay: summarizeBy(events, (e) => e.date, true),\n byModel: summarizeBy(events, (e) => e.model),\n byProject: summarizeBy(events, (e) => e.project),\n topSessions: summarizeBy(events, (e) => `${e.project}/${e.sessionId}`).slice(0, 5),\n };\n}\n\nexport function buildDemoEvents(): UsageEvent[] {\n const today = new Date().toISOString().slice(0, 10);\n const yest = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10);\n const raw: Array<Omit<UsageEvent, 'costUsd'>> = [\n {\n timestamp: `${today}T09:15:00Z`,\n date: today,\n source: 'claude-code',\n project: 'checkout-service',\n sessionId: 'sess-refactor-auth',\n model: 'claude-sonnet-4-5',\n inputTokens: 180_000,\n outputTokens: 32_000,\n cacheReadTokens: 1_250_000,\n cacheWriteTokens: 45_000,\n },\n {\n timestamp: `${today}T14:20:00Z`,\n date: today,\n source: 'codex',\n project: 'analytics-worker',\n sessionId: 'sess-sql-migration',\n model: 'gpt-5',\n inputTokens: 95_000,\n outputTokens: 18_500,\n cacheReadTokens: 420_000,\n cacheWriteTokens: 0,\n },\n {\n timestamp: `${yest}T19:40:00Z`,\n date: yest,\n source: 'claude-code',\n project: 'checkout-service',\n sessionId: 'sess-heavy-mcp-loop',\n model: 'claude-opus-4-5',\n inputTokens: 210_000,\n outputTokens: 28_000,\n cacheReadTokens: 640_000,\n cacheWriteTokens: 60_000,\n },\n ];\n return raw.map((e) => ({\n ...e,\n costUsd: computeUsageCostUsd(e.model, e),\n }));\n}\n"],"mappings":";AAOA,IAAM,gBAA6D;AAAA,EACjE,EAAE,OAAO,SAAS,OAAO,EAAE,YAAY,IAAM,aAAa,IAAM,gBAAgB,KAAK,iBAAiB,MAAM,EAAE;AAAA,EAC9G,EAAE,OAAO,WAAW,OAAO,EAAE,YAAY,GAAK,aAAa,IAAM,gBAAgB,KAAK,iBAAiB,KAAK,EAAE;AAAA,EAC9G,EAAE,OAAO,UAAU,OAAO,EAAE,YAAY,KAAK,aAAa,GAAK,gBAAgB,MAAM,iBAAiB,EAAI,EAAE;AAAA,EAC5G,EAAE,OAAO,gBAAgB,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,cAAc;AAAA,MACd,iBAAiB;AAAA,MACjB,kBAAkB;AAAA,IACpB;AAAA,IACA;AAAA,MACE,WAAW,GAAG,IAAI;AAAA,MAClB,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,WAAW;AAAA,MACX,OAAO;AAAA,MACP,aAAa;AAAA,MACb,cAAc;AAAA,MACd,iBAAiB;AAAA,MACjB,kBAAkB;AAAA,IACpB;AAAA,EACF;AACA,SAAO,IAAI,IAAI,CAAC,OAAO;AAAA,IACrB,GAAG;AAAA,IACH,SAAS,oBAAoB,EAAE,OAAO,CAAC;AAAA,EACzC,EAAE;AACJ;","names":[]}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
buildBillReport,
|
|
4
|
+
buildDemoEvents,
|
|
5
|
+
discoverAndScanLogs,
|
|
6
|
+
renderHtmlReport,
|
|
7
|
+
renderMarkdownReport,
|
|
8
|
+
renderTerminalReport
|
|
9
|
+
} from "./chunk-CHPWFF3J.js";
|
|
10
|
+
|
|
11
|
+
// src/cli.ts
|
|
12
|
+
import fs from "fs";
|
|
13
|
+
import path from "path";
|
|
14
|
+
import chalk from "chalk";
|
|
15
|
+
import { Command } from "commander";
|
|
16
|
+
var program = new Command();
|
|
17
|
+
program.name("llmbill").description(
|
|
18
|
+
"1-second local AI coding agent cost & token ledger \u2014 scan Claude Code & Codex JSONL logs for daily spend and cache hit rates."
|
|
19
|
+
).version("0.1.0").option("-d, --days <n>", "Number of days to include (0 = all time)", "7").option("-p, --path <dirOrFile>", "Custom JSONL file or log directory to scan").option("-f, --format <type>", "Output format: table | json | markdown | html", "table").option("-o, --out <path>", "Write report to file").option("-b, --budget <usd>", "Exit with code 1 if spend exceeds this USD threshold").option("--demo", "Run with realistic demo agent sessions (no local logs needed)", false).action((opts) => {
|
|
20
|
+
try {
|
|
21
|
+
const days = Number.parseInt(String(opts.days), 10);
|
|
22
|
+
const budgetUsd = opts.budget !== void 0 ? Number.parseFloat(String(opts.budget)) : void 0;
|
|
23
|
+
const events = opts.demo ? buildDemoEvents() : discoverAndScanLogs({ customPath: opts.path });
|
|
24
|
+
const report = buildBillReport(events, {
|
|
25
|
+
days: Number.isFinite(days) ? days : 7,
|
|
26
|
+
budgetUsd: budgetUsd !== void 0 && Number.isFinite(budgetUsd) ? budgetUsd : void 0
|
|
27
|
+
});
|
|
28
|
+
const fmt = String(opts.format).toLowerCase();
|
|
29
|
+
let output;
|
|
30
|
+
if (fmt === "json") output = JSON.stringify(report, null, 2);
|
|
31
|
+
else if (fmt === "markdown") output = renderMarkdownReport(report);
|
|
32
|
+
else if (fmt === "html") output = renderHtmlReport(report);
|
|
33
|
+
else output = renderTerminalReport(report);
|
|
34
|
+
if (opts.out) {
|
|
35
|
+
const dest = path.resolve(String(opts.out));
|
|
36
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
37
|
+
fs.writeFileSync(dest, output, "utf8");
|
|
38
|
+
console.log(chalk.green(`\u2713 Report written to ${dest}`));
|
|
39
|
+
} else {
|
|
40
|
+
console.log(output);
|
|
41
|
+
}
|
|
42
|
+
if (report.budgetExceeded) {
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
}
|
|
45
|
+
} catch (err) {
|
|
46
|
+
console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
|
|
47
|
+
process.exitCode = 2;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
program.parse();
|
|
51
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport { Command } from 'commander';\nimport { renderHtmlReport, renderMarkdownReport, renderTerminalReport } from './reporter.js';\nimport { buildBillReport, buildDemoEvents, discoverAndScanLogs } from './scanner.js';\n\nconst program = new Command();\n\nprogram\n .name('llmbill')\n .description(\n '1-second local AI coding agent cost & token ledger — scan Claude Code & Codex JSONL logs for daily spend and cache hit rates.'\n )\n .version('0.1.0')\n .option('-d, --days <n>', 'Number of days to include (0 = all time)', '7')\n .option('-p, --path <dirOrFile>', 'Custom JSONL file or log directory to scan')\n .option('-f, --format <type>', 'Output format: table | json | markdown | html', 'table')\n .option('-o, --out <path>', 'Write report to file')\n .option('-b, --budget <usd>', 'Exit with code 1 if spend exceeds this USD threshold')\n .option('--demo', 'Run with realistic demo agent sessions (no local logs needed)', false)\n .action((opts) => {\n try {\n const days = Number.parseInt(String(opts.days), 10);\n const budgetUsd = opts.budget !== undefined ? Number.parseFloat(String(opts.budget)) : undefined;\n const events = opts.demo ? buildDemoEvents() : discoverAndScanLogs({ customPath: opts.path });\n const report = buildBillReport(events, {\n days: Number.isFinite(days) ? days : 7,\n budgetUsd: budgetUsd !== undefined && Number.isFinite(budgetUsd) ? budgetUsd : undefined,\n });\n\n const fmt = String(opts.format).toLowerCase();\n let output: string;\n if (fmt === 'json') output = JSON.stringify(report, null, 2);\n else if (fmt === 'markdown') output = renderMarkdownReport(report);\n else if (fmt === 'html') output = renderHtmlReport(report);\n else output = renderTerminalReport(report);\n\n if (opts.out) {\n const dest = path.resolve(String(opts.out));\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, output, 'utf8');\n console.log(chalk.green(`✓ Report written to ${dest}`));\n } else {\n console.log(output);\n }\n\n if (report.budgetExceeded) {\n process.exitCode = 1;\n }\n } catch (err) {\n console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));\n process.exitCode = 2;\n }\n });\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;AACA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,WAAW;AAClB,SAAS,e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AI,MAAM;AAAA,IACpB;AAEA,QAAI,OAAO,gBAAgB;AACzB,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF,SAAS,KAAK;AACZ,YAAQ,MAAM,MAAM,IAAI,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE,CAAC;AACrF,YAAQ,WAAW;AAAA,EACrB;AACF,CAAC;AAEH,QAAQ,MAAM;","names":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
interface ModelPrice {
|
|
2
|
+
inputPer1M: number;
|
|
3
|
+
outputPer1M: number;
|
|
4
|
+
cacheReadPer1M: number;
|
|
5
|
+
cacheWritePer1M: number;
|
|
6
|
+
}
|
|
7
|
+
declare function resolveModelPrice(model: string): ModelPrice;
|
|
8
|
+
declare function computeUsageCostUsd(model: string, usage: {
|
|
9
|
+
inputTokens: number;
|
|
10
|
+
outputTokens: number;
|
|
11
|
+
cacheReadTokens: number;
|
|
12
|
+
cacheWriteTokens: number;
|
|
13
|
+
}): number;
|
|
14
|
+
|
|
15
|
+
interface UsageEvent {
|
|
16
|
+
timestamp: string;
|
|
17
|
+
date: string;
|
|
18
|
+
source: 'claude-code' | 'codex' | 'custom';
|
|
19
|
+
project: string;
|
|
20
|
+
sessionId: string;
|
|
21
|
+
model: string;
|
|
22
|
+
inputTokens: number;
|
|
23
|
+
outputTokens: number;
|
|
24
|
+
cacheReadTokens: number;
|
|
25
|
+
cacheWriteTokens: number;
|
|
26
|
+
costUsd: number;
|
|
27
|
+
}
|
|
28
|
+
interface GroupSummary {
|
|
29
|
+
key: string;
|
|
30
|
+
events: number;
|
|
31
|
+
inputTokens: number;
|
|
32
|
+
outputTokens: number;
|
|
33
|
+
cacheReadTokens: number;
|
|
34
|
+
totalTokens: number;
|
|
35
|
+
costUsd: number;
|
|
36
|
+
}
|
|
37
|
+
interface BillReport {
|
|
38
|
+
days: number;
|
|
39
|
+
eventCount: number;
|
|
40
|
+
sessionCount: number;
|
|
41
|
+
totalInputTokens: number;
|
|
42
|
+
totalOutputTokens: number;
|
|
43
|
+
totalCacheReadTokens: number;
|
|
44
|
+
totalCacheWriteTokens: number;
|
|
45
|
+
totalTokens: number;
|
|
46
|
+
cacheHitRatePct: number;
|
|
47
|
+
totalCostUsd: number;
|
|
48
|
+
budgetUsd?: number;
|
|
49
|
+
budgetExceeded: boolean;
|
|
50
|
+
byDay: GroupSummary[];
|
|
51
|
+
byModel: GroupSummary[];
|
|
52
|
+
byProject: GroupSummary[];
|
|
53
|
+
topSessions: GroupSummary[];
|
|
54
|
+
}
|
|
55
|
+
declare function parseUsageJsonlFile(filePath: string, source: 'claude-code' | 'codex' | 'custom'): UsageEvent[];
|
|
56
|
+
declare function discoverAndScanLogs(options?: {
|
|
57
|
+
homeDir?: string;
|
|
58
|
+
customPath?: string;
|
|
59
|
+
}): UsageEvent[];
|
|
60
|
+
declare function buildBillReport(allEvents: UsageEvent[], options?: {
|
|
61
|
+
days?: number;
|
|
62
|
+
budgetUsd?: number;
|
|
63
|
+
nowMs?: number;
|
|
64
|
+
}): BillReport;
|
|
65
|
+
declare function buildDemoEvents(): UsageEvent[];
|
|
66
|
+
|
|
67
|
+
declare function renderTerminalReport(report: BillReport): string;
|
|
68
|
+
declare function renderMarkdownReport(report: BillReport): string;
|
|
69
|
+
declare function renderHtmlReport(report: BillReport): string;
|
|
70
|
+
|
|
71
|
+
export { type BillReport, type GroupSummary, type ModelPrice, type UsageEvent, buildBillReport, buildDemoEvents, computeUsageCostUsd, discoverAndScanLogs, parseUsageJsonlFile, renderHtmlReport, renderMarkdownReport, renderTerminalReport, resolveModelPrice };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildBillReport,
|
|
3
|
+
buildDemoEvents,
|
|
4
|
+
computeUsageCostUsd,
|
|
5
|
+
discoverAndScanLogs,
|
|
6
|
+
parseUsageJsonlFile,
|
|
7
|
+
renderHtmlReport,
|
|
8
|
+
renderMarkdownReport,
|
|
9
|
+
renderTerminalReport,
|
|
10
|
+
resolveModelPrice
|
|
11
|
+
} from "./chunk-CHPWFF3J.js";
|
|
12
|
+
export {
|
|
13
|
+
buildBillReport,
|
|
14
|
+
buildDemoEvents,
|
|
15
|
+
computeUsageCostUsd,
|
|
16
|
+
discoverAndScanLogs,
|
|
17
|
+
parseUsageJsonlFile,
|
|
18
|
+
renderHtmlReport,
|
|
19
|
+
renderMarkdownReport,
|
|
20
|
+
renderTerminalReport,
|
|
21
|
+
resolveModelPrice
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farryq/llmbill",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "1-second local AI coding agent cost & token ledger — scan Claude Code & Codex JSONL session logs to see daily spend, cache hit rate, per-project breakdown, and top expensive sessions.",
|
|
5
|
+
"homepage": "https://github.com/farryq/llmbill#readme",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/farryq/llmbill.git"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"claude-code",
|
|
12
|
+
"codex",
|
|
13
|
+
"llm-cost",
|
|
14
|
+
"tokens",
|
|
15
|
+
"ai-agent",
|
|
16
|
+
"prompt-caching",
|
|
17
|
+
"billing",
|
|
18
|
+
"cli",
|
|
19
|
+
"devtools"
|
|
20
|
+
],
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"bin": {
|
|
24
|
+
"llmbill": "dist/cli.js"
|
|
25
|
+
},
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.js"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=20.0.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"demo": "node dist/cli.js --demo",
|
|
47
|
+
"prepublishOnly": "npm run typecheck && npm run test && npm run build"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"chalk": "^5.4.1",
|
|
51
|
+
"cli-table3": "^0.6.5",
|
|
52
|
+
"commander": "^13.1.0"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^22.15.0",
|
|
56
|
+
"tsup": "^8.4.0",
|
|
57
|
+
"typescript": "^5.8.3",
|
|
58
|
+
"vitest": "^3.1.3"
|
|
59
|
+
}
|
|
60
|
+
}
|