-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathusage.js
More file actions
executable file
·431 lines (403 loc) · 15.1 KB
/
Copy pathusage.js
File metadata and controls
executable file
·431 lines (403 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#!/usr/bin/env node
// honey-usage — actual token usage of local AI coding apps, with approximate USD
// (bench/pricing.json) and served CO2 (hooks/eco.js EcoLogits port).
//
// Apps: claude (Claude Code), codex (Codex CLI), opencode (OpenCode).
// Only apps with data on this machine are scanned; missing roots are skipped.
//
// honey-usage [--json] [--daily] [--client claude,codex,opencode]
// [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--today] [--help]
"use strict";
const fs = require("fs");
const os = require("os");
const path = require("path");
const { execFileSync } = require("child_process");
const eco = require("../hooks/eco.js");
const pricing = JSON.parse(
fs.readFileSync(path.join(__dirname, "..", "bench", "pricing.json"), "utf8")
);
// mirrors bench/src/report.js (bench/ isn't shipped; only its pricing.json is)
function rateFor(model) {
const hit = pricing.rates.find((r) => String(model).toLowerCase().includes(r.match));
return hit || pricing._default;
}
function dollars(model, { input = 0, cache_write = 0, cache_read = 0, output = 0 }) {
const r = rateFor(model);
const cw = r.cache_write ?? pricing._default.cache_write;
const cr = r.cache_read ?? pricing._default.cache_read;
return (input * r.in + cache_write * r.in * cw + cache_read * r.in * cr + output * r.out) / 1e6;
}
function walk(dir, out = []) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries) {
const p = path.join(dir, e.name);
if (e.isDirectory()) walk(p, out);
else if (e.name.endsWith(".jsonl")) out.push(p);
}
return out;
}
// Claude Code assistant lines repeat across retries/continuations with identical
// usage — count each (message.id, requestId) once via the caller's `seen` set.
function parseAssistant(line, seen) {
if (!line.includes('"type":"assistant"')) return null;
let rec;
try {
rec = JSON.parse(line);
} catch {
return null;
}
const m = rec.message;
const u = m && m.usage;
if (rec.type !== "assistant" || !u || !m.model || m.model === "<synthetic>") return null;
const key = m.id + ":" + (rec.requestId || "");
if (seen.has(key)) return null;
seen.add(key);
return {
model: m.model,
ts: Date.parse(rec.timestamp) || null,
input: u.input_tokens || 0,
output: u.output_tokens || 0,
cacheRead: u.cache_read_input_tokens || 0,
cacheWrite: u.cache_creation_input_tokens || 0,
};
}
function scanClaude(root) {
const recs = [];
const seen = new Set();
for (const file of walk(path.join(root, "projects"))) {
let text;
try {
text = fs.readFileSync(file, "utf8");
} catch {
continue;
}
for (const line of text.split("\n")) {
const r = parseAssistant(line, seen);
if (r) recs.push({ app: "claude", cost: null, ...r });
}
}
return recs;
}
// Codex: model comes from turn_context (can change mid-file); usage from
// token_count events' last_token_usage. cached_input_tokens is a subset of
// input_tokens, so split it out to price cache reads at the cached rate.
function scanCodex(root) {
const recs = [];
for (const file of walk(path.join(root, "sessions"))) {
let text;
try {
text = fs.readFileSync(file, "utf8");
} catch {
continue;
}
let model = null;
for (const line of text.split("\n")) {
const isTurn = line.includes('"turn_context"');
if (!isTurn && !line.includes('"token_count"')) continue;
let rec;
try {
rec = JSON.parse(line);
} catch {
continue;
}
const p = rec.payload || {};
if (isTurn) {
if (p.model) model = p.model;
continue;
}
const l = p.info && p.info.last_token_usage;
if (!l) continue;
const cached = l.cached_input_tokens || 0;
recs.push({
app: "codex",
model: model || "gpt-5-codex",
ts: Date.parse(rec.timestamp) || null,
input: Math.max(0, (l.input_tokens || 0) - cached),
output: l.output_tokens || 0,
cacheRead: cached,
cacheWrite: 0,
cost: null,
});
}
}
return recs;
}
// OpenCode: sqlite db read via the system sqlite3 (ships with macOS). Messages
// embed their exact cost and tokens; `input` already excludes cache reads and
// `reasoning` is billed as output.
function scanOpencode(db) {
if (!fs.existsSync(db)) return [];
let out;
try {
out = execFileSync("sqlite3", ["-readonly", "-json", db, "select data from message"], {
encoding: "utf8",
maxBuffer: 1 << 28,
});
} catch (e) {
const why = e.code === "ENOENT" ? "sqlite3 not found" : String(e.message).split("\n")[0];
process.stderr.write(`honey-usage: skipping opencode (${why})\n`);
return [];
}
if (!out.trim()) return [];
const recs = [];
for (const row of JSON.parse(out)) {
let d;
try {
d = JSON.parse(row.data);
} catch {
continue;
}
if (d.role !== "assistant" || !d.tokens) continue;
const t = d.tokens;
recs.push({
app: "opencode",
model: d.modelID || "unknown",
ts: (d.time && d.time.created) || null,
input: t.input || 0,
output: (t.output || 0) + (t.reasoning || 0),
cacheRead: (t.cache && t.cache.read) || 0,
cacheWrite: (t.cache && t.cache.write) || 0,
cost: typeof d.cost === "number" && d.cost > 0 ? d.cost : null,
});
}
return recs;
}
// Savings ledger: hooks/honey-session.js appends {ts, transcript_path, mode}
// per Honey session start. Savings is claimed ONLY for these sessions — the
// modeled counterfactual needs to know Honey was active and in which mode.
// Dedup by transcript path (resume re-fires SessionStart); last mode wins.
function ledgerSessions(dir) {
let text;
try {
text = fs.readFileSync(path.join(dir, ".honey-usage-ledger.jsonl"), "utf8");
} catch {
return [];
}
const byTx = new Map();
for (const line of text.split("\n")) {
if (!line.trim()) continue;
try {
const e = JSON.parse(line);
if (e.transcript_path && e.mode) byTx.set(e.transcript_path, e);
} catch {}
}
return [...byTx.values()];
}
function scanSavings(dir) {
const recs = [];
const seen = new Set();
let since = null;
for (const s of ledgerSessions(dir)) {
if (s.ts && (!since || s.ts < since)) since = s.ts;
let text;
try {
text = fs.readFileSync(s.transcript_path, "utf8");
} catch {
continue; // transcript deleted since — nothing to claim
}
for (const line of text.split("\n")) {
const r = parseAssistant(line, seen);
if (r) recs.push({ mode: s.mode, model: r.model, ts: r.ts, output: r.output, tx: s.transcript_path });
}
}
return { recs, trackedSince: since };
}
// One row per mode+model with a committed bench stamp; models without one get
// no savings claim (they'd be an invented counterfactual) and are footnoted.
function aggregateSavings(recs) {
const cfg = eco.loadConfig();
const groups = new Map();
for (const r of recs) {
const k = r.mode + " " + r.model;
let g = groups.get(k);
if (!g) groups.set(k, (g = { mode: r.mode, model: r.model, output: 0, txs: new Set() }));
g.output += r.output;
g.txs.add(r.tx);
}
const rows = [];
const labels = new Set();
const skipped = { output: 0, models: new Set() };
const totals = { sessions: 0, output: 0, savedTokens: 0, savedUsd: 0, savedGco2: 0 };
for (const g of groups.values()) {
const sv = eco.savingsInfo(cfg, g.mode, g.model);
if (!sv || !(sv.k > 0)) {
skipped.output += g.output;
skipped.models.add(g.model);
continue;
}
const savedTokens = g.output * sv.k;
const row = {
mode: g.mode,
model: g.model,
sessions: g.txs.size,
output: g.output,
savedTokens,
savedUsd: dollars(g.model, { output: savedTokens }),
savedGco2: eco.estimate(g.model, savedTokens, cfg).gco2,
};
labels.add(sv.label);
rows.push(row);
for (const f of Object.keys(totals)) totals[f] += row[f];
}
rows.sort((a, b) => (a.mode + a.model < b.mode + b.model ? -1 : 1));
return { rows, totals, labels: [...labels], skipped };
}
function renderSavings(sv, trackedSince) {
const heads = ["MODE", "MODEL", "SESSIONS", "OUTPUT", "SAVED-TOK", "SAVED-USD", "SAVED-CO2"];
const line = (r) => [
String(r.mode ?? "total"), String(r.model ?? ""), fmtN(r.sessions), fmtN(r.output),
fmtN(Math.round(r.savedTokens)), "$" + r.savedUsd.toFixed(2), fmtG(r.savedGco2),
];
const table = [heads, ...sv.rows.map(line), line(sv.totals)];
const w = heads.map((_, i) => Math.max(...table.map((r) => r[i].length)));
const out = table.map((r) =>
r.map((c, i) => (i < 2 ? c.padEnd(w[i]) : c.padStart(w[i]))).join(" ").trimEnd()
);
out.splice(out.length - 1, 0, out[0].replace(/./g, "-"));
if (trackedSince) out.push(`tracked since ${day(trackedSince)} (Honey sessions only)`);
else out.push("no tracked Honey sessions yet — the ledger starts with the first Honey session after install");
for (const l of sv.labels) out.push("est. " + l);
if (sv.skipped.output)
out.push(
`${fmtN(sv.skipped.output)} output tokens (${[...sv.skipped.models].join(", ")}) ` +
"have no committed bench stamp — no savings claimed"
);
return out.join("\n");
}
// Local calendar day — usage reports should follow the user's clock, not UTC.
function day(ts) {
const d = new Date(ts);
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
function aggregate(records, keys) {
const groups = new Map();
for (const rec of records) {
if (keys.includes("day")) rec.day = rec.ts ? day(rec.ts) : "unknown";
const k = keys.map((f) => rec[f]).join("