@aispendbook/cli 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/dist/cli.js ADDED
@@ -0,0 +1,402 @@
1
+ /** Command-line entry: argument parsing and the report, sync and mcp commands. */
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { join } from "node:path";
5
+ import { auditCaching, formatAudit } from "./cache-audit.js";
6
+ import { compareUsage, formatComparison, toSavingsSummary } from "./compare.js";
7
+ import { DEFAULTS, ENV, loadConfig } from "./config.js";
8
+ import { McpServer } from "./mcp.js";
9
+ import { localDay, parseDay, parseRange } from "./range.js";
10
+ import { buildReport, collectUsage, filterTools, formatTable, GROUPINGS, PRICE_BASIS } from "./report.js";
11
+ import { FileSavingsState, FileSkillInstaller } from "./savings.js";
12
+ import { ClaudeCodeSource } from "./sources/claude-code.js";
13
+ import { ClaudePromptChainSource } from "./sources/claude-prefix.js";
14
+ import { CodexSource } from "./sources/codex.js";
15
+ import { GeminiSource } from "./sources/gemini.js";
16
+ import { SyncStateStore, toIngestEvent } from "./sync.js";
17
+ import { TOOLS } from "./types.js";
18
+ export function packageVersion() {
19
+ try {
20
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
21
+ }
22
+ catch {
23
+ return "0.0.0";
24
+ }
25
+ }
26
+ export function buildSources(fs, paths) {
27
+ return [new ClaudeCodeSource(fs, paths.claudeDirs), new CodexSource(fs, paths.codexHome), new GeminiSource(fs, paths.geminiTmpDirs)];
28
+ }
29
+ export const HELP = `aispendbook: token usage and API-equivalent cost of your AI coding tools, from their local logs.
30
+
31
+ Usage:
32
+ aispendbook report [--since 7d|YYYY-MM-DD] [--until YYYY-MM-DD] [--by day|project|model|tool]
33
+ [--source claude-code|codex|gemini] [--json]
34
+ aispendbook sync [--key afk_...] [--api URL] [--since 30d|YYYY-MM-DD] [--source ...]
35
+ [--project-names hashed|plain] [--dry-run]
36
+ aispendbook report --compare [--split YYYY-MM-DD|ISO time | --marker NAME | --before A..B --after C..D]
37
+ [--window ${DEFAULTS.compareWindowDays}] [--min-sessions ${DEFAULTS.compareMinSessions}] [--source ...] [--json]
38
+ [--sync [--key afk_...] [--api URL] [--label TEXT]]
39
+ aispendbook cache-audit [--since 30d|YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
40
+ aispendbook skill install|uninstall|status [--dir PATH]
41
+ aispendbook marker add NAME [--at YYYY-MM-DD|ISO time] | marker list | marker remove NAME
42
+ aispendbook mcp Run a local MCP server on stdin/stdout (tool: my_local_ai_usage)
43
+ aispendbook --help | --version
44
+
45
+ Sources: Claude Code (~/.claude/projects, or $${ENV.claudeConfigDir}), OpenAI Codex CLI
46
+ (~/.codex/sessions, or $${ENV.codexHome}) and Gemini CLI (~/.gemini/tmp, or $${ENV.geminiHome}/.gemini/tmp).
47
+
48
+ report Reads local logs only and never uploads. --since defaults to ${DEFAULTS.reportSince} (today and the
49
+ 6 days before). --until names the last day included. --source may repeat or take a comma list.
50
+ sync Uploads counts only (no prompts, code or messages) to {api}/api/v1/ingest/batch.
51
+ --key defaults to $${ENV.ingestionKey}; --api defaults to $${ENV.apiBase} or ${DEFAULTS.apiBase}.
52
+ Project names are hashed unless --project-names plain. --dry-run shows what would be sent.
53
+ Without --since it starts ${DEFAULTS.syncOverlapDays} day before the last sync (state in $${ENV.home},
54
+ default ~/${DEFAULTS.stateDirName}), or ${DEFAULTS.firstSyncSince} back on the first run. Re-sent events are deduplicated.
55
+ --compare Splits sessions at the savings skill install (default), a marker, or --split, using
56
+ --window days on each side; or compares --before and --after date ranges. Shows each side's
57
+ sessions, requests, tokens, cost, and cost per session, request and output token with the
58
+ median and 25th to 75th percentiles. Below --min-sessions on either side it says "not enough
59
+ data". Differences are observations, not savings: the work differs. --sync sends the summary
60
+ (numbers only) to your workspace.
61
+ cache-audit Claude Code only. Hashes message chains in memory to find prompts repeated from an earlier
62
+ request, and counts repeated tokens read from cache, billed at full price or written again,
63
+ with an estimated saving at dated list prices. Nothing is uploaded or printed but totals.
64
+ skill Copies the savings skill to ~/${DEFAULTS.skillsDir}/${DEFAULTS.skillName} (or --dir) and records the time
65
+ in ${DEFAULTS.savingsFileName} in the state directory, for --compare.
66
+
67
+ ${PRICE_BASIS}
68
+ `;
69
+ class UsageError extends Error {
70
+ }
71
+ function tools(values) {
72
+ if (!values?.length)
73
+ return null;
74
+ const list = values.flatMap((v) => v.split(",")).map((v) => v.trim()).filter(Boolean);
75
+ for (const t of list)
76
+ if (!TOOLS.includes(t))
77
+ throw new UsageError(`--source must be one of ${TOOLS.join(", ")}`);
78
+ return list;
79
+ }
80
+ function grouping(v) {
81
+ const by = v ?? "day";
82
+ if (!GROUPINGS.includes(by))
83
+ throw new UsageError(`--by must be one of ${GROUPINGS.join(", ")}`);
84
+ return by;
85
+ }
86
+ function makeService(deps) {
87
+ const sources = buildSources(deps.fs, loadConfig(deps.env, deps.home).sources);
88
+ return {
89
+ async report(q) {
90
+ const range = parseRange(q.since, q.until, deps.clock.now());
91
+ return buildReport(await collectUsage(filterTools(sources, q.source), range), deps.prices, q.by, range);
92
+ },
93
+ };
94
+ }
95
+ const DAY_MS = 86_400_000;
96
+ /** A point in time: YYYY-MM-DD (start of that local day), Nd, or an ISO timestamp with a time. */
97
+ function parsePoint(value, now, flag) {
98
+ if (/^\d{4}-\d{2}-\d{2}T/.test(value.trim())) {
99
+ const d = new Date(value);
100
+ if (Number.isNaN(d.getTime()))
101
+ throw new UsageError(`${flag} is not a valid time: "${value}"`);
102
+ return d;
103
+ }
104
+ try {
105
+ return parseDay(value, now, flag);
106
+ }
107
+ catch (e) {
108
+ throw new UsageError(e.message);
109
+ }
110
+ }
111
+ function parseSpan(value, now, flag) {
112
+ const [a, b] = value.split("..");
113
+ if (!a || !b)
114
+ throw new UsageError(`${flag} must look like 2026-10-01..2026-10-31`);
115
+ const r = parseRange(a, b, now);
116
+ return { since: r.since, until: r.until };
117
+ }
118
+ function positiveInt(v, fallback, flag) {
119
+ if (v === undefined)
120
+ return fallback;
121
+ const n = Number(v);
122
+ if (!Number.isInteger(n) || n < 1)
123
+ throw new UsageError(`${flag} must be a whole number of at least 1`);
124
+ return n;
125
+ }
126
+ async function comparePeriods(values, deps) {
127
+ const now = deps.clock.now();
128
+ const str = (k) => values[k];
129
+ if (str("before") || str("after")) {
130
+ if (!str("before") || !str("after"))
131
+ throw new UsageError("--before and --after go together");
132
+ const before = parseSpan(str("before"), now, "--before");
133
+ const after = parseSpan(str("after"), now, "--after");
134
+ if (after.since < before.until)
135
+ throw new UsageError("--after must start after --before ends");
136
+ return { before, after: { ...after, until: after.until > now ? now : after.until }, splitAt: null, splitSource: "date ranges" };
137
+ }
138
+ const state = await new FileSavingsState(deps.fs, loadConfig(deps.env, deps.home).stateDir).load();
139
+ let split;
140
+ let source;
141
+ let end = now;
142
+ if (str("split")) {
143
+ split = parsePoint(str("split"), now, "--split");
144
+ source = "split";
145
+ }
146
+ else if (str("marker")) {
147
+ const at = state.markers[str("marker")];
148
+ if (!at)
149
+ throw new UsageError(`No marker named "${str("marker")}". Set one with: aispendbook marker add NAME`);
150
+ split = new Date(at);
151
+ source = `marker ${str("marker")}`;
152
+ }
153
+ else if (state.skill.installedAt) {
154
+ split = new Date(state.skill.installedAt);
155
+ source = "skill install";
156
+ if (state.skill.uninstalledAt)
157
+ end = new Date(Math.min(now.getTime(), Date.parse(state.skill.uninstalledAt)));
158
+ }
159
+ else {
160
+ throw new UsageError("Nothing to split on: install the skill (aispendbook skill install), add a marker (aispendbook marker add NAME), or pass --split, or --before and --after.");
161
+ }
162
+ if (split >= now)
163
+ throw new UsageError("The split point is in the future; nothing to compare yet.");
164
+ const window = positiveInt(str("window"), DEFAULTS.compareWindowDays, "--window") * DAY_MS;
165
+ return {
166
+ before: { since: new Date(split.getTime() - window), until: split },
167
+ after: { since: split, until: new Date(Math.min(split.getTime() + window, end.getTime())) },
168
+ splitAt: split, splitSource: source,
169
+ };
170
+ }
171
+ async function compare(values, deps) {
172
+ const periods = await comparePeriods(values, deps);
173
+ const minSessions = positiveInt(values["min-sessions"], DEFAULTS.compareMinSessions, "--min-sessions");
174
+ const cfg = loadConfig(deps.env, deps.home, { api: values.api, key: values.key });
175
+ if (values.sync && !cfg.ingestionKey)
176
+ throw new UsageError(`--sync needs an ingestion key: pass --key afk_... or set ${ENV.ingestionKey}.`);
177
+ const sources = filterTools(buildSources(deps.fs, cfg.sources), tools(values.source));
178
+ const usage = await collectUsage(sources, { since: periods.before.since, until: periods.after.until });
179
+ const c = compareUsage(usage.events, deps.prices, periods, { minSessions, workShift: DEFAULTS.compareWorkShift });
180
+ deps.output.out(values.json ? JSON.stringify({ ...c, cost_unit: "USD micros" }, null, 2) : formatComparison(c));
181
+ if (!values.sync)
182
+ return 0;
183
+ const label = values.label ?? `${periods.splitSource} ${localDay(periods.after.since)}`;
184
+ const r = await deps.poster.post(toSavingsSummary(c, label.slice(0, 200), { name: DEFAULTS.sdkName, version: deps.version }), {
185
+ apiBase: cfg.apiBase, path: DEFAULTS.savingsPath, key: cfg.ingestionKey,
186
+ });
187
+ if (r.error) {
188
+ deps.output.err(`Comparison not sent: ${r.error}`);
189
+ return 1;
190
+ }
191
+ deps.output.err(`Comparison summary sent to ${cfg.apiBase} (numbers only). It shows on the Usage page.`);
192
+ return 0;
193
+ }
194
+ async function cacheAudit(args, deps) {
195
+ const { values } = parseArgs({
196
+ args, strict: true, allowPositionals: false,
197
+ options: { since: { type: "string" }, until: { type: "string" }, json: { type: "boolean" } },
198
+ });
199
+ const range = parseRange(values.since ?? DEFAULTS.firstSyncSince, values.until, deps.clock.now());
200
+ const src = new ClaudePromptChainSource(deps.fs, loadConfig(deps.env, deps.home).sources.claudeDirs);
201
+ const { links } = await src.read({ since: range.since });
202
+ const inRange = links.filter((l) => l.at >= range.since && (range.until === null || l.at < range.until));
203
+ const lastDay = range.until ? localDay(new Date(range.until.getTime() - 1)) : null;
204
+ const a = auditCaching(inRange, deps.prices, { since: localDay(range.since), until: lastDay });
205
+ a.notes.push("Codex CLI and Gemini CLI are not audited: their providers cache automatically and the logs carry no message chain to hash.");
206
+ deps.output.out(values.json ? JSON.stringify({ ...a, cost_unit: "USD micros" }, null, 2) : formatAudit(a));
207
+ return 0;
208
+ }
209
+ async function skill(args, deps) {
210
+ const { values, positionals } = parseArgs({ args, strict: true, allowPositionals: true, options: { dir: { type: "string" } } });
211
+ const cfg = loadConfig(deps.env, deps.home);
212
+ const state = new FileSavingsState(deps.fs, cfg.stateDir);
213
+ const installer = new FileSkillInstaller(deps.fs, deps.skillSourceDir, values.dir ?? join(deps.home, DEFAULTS.skillsDir), state, deps.clock);
214
+ switch (positionals[0]) {
215
+ case "install": {
216
+ const r = await installer.install();
217
+ deps.output.out(`Installed the savings skill (${r.files} file(s)) in ${r.path}. ` +
218
+ (r.alreadyInstalled ? `Kept the first install time, ${r.installedAt}.` : `Install time recorded: ${r.installedAt}.`) +
219
+ " Start a new Claude Code session to load it. Compare later with: aispendbook report --compare");
220
+ return 0;
221
+ }
222
+ case "uninstall": {
223
+ const r = await installer.uninstall();
224
+ deps.output.out(r.removed ? `Removed ${r.path}. Removal time recorded for --compare.` : `Nothing at ${r.path}; removal time recorded.`);
225
+ return 0;
226
+ }
227
+ case "status": {
228
+ const s = (await state.load()).skill;
229
+ deps.output.out(s.installedAt
230
+ ? `Installed ${s.installedAt}${s.uninstalledAt ? `, removed ${s.uninstalledAt}` : ""} at ${s.path ?? "unknown path"}.`
231
+ : "The savings skill has not been installed with this tool.");
232
+ return 0;
233
+ }
234
+ default:
235
+ throw new UsageError("Use: aispendbook skill install | uninstall | status");
236
+ }
237
+ }
238
+ async function marker(args, deps) {
239
+ const { values, positionals } = parseArgs({ args, strict: true, allowPositionals: true, options: { at: { type: "string" } } });
240
+ const store = new FileSavingsState(deps.fs, loadConfig(deps.env, deps.home).stateDir);
241
+ const s = await store.load();
242
+ const [action, name] = positionals;
243
+ if (action === "list") {
244
+ const rows = Object.entries(s.markers).sort((a, b) => a[1].localeCompare(b[1]));
245
+ deps.output.out(rows.length ? rows.map(([k, v]) => `${v} ${k}`).join("\n") : "No markers.");
246
+ return 0;
247
+ }
248
+ if (!name || !/^[\w.@:-]{1,64}$/.test(name))
249
+ throw new UsageError("A marker name is 1 to 64 letters, digits, '.', '_', '-', '@' or ':'.");
250
+ if (action === "add") {
251
+ const at = values.at ? parsePoint(values.at, deps.clock.now(), "--at") : deps.clock.now();
252
+ s.markers[name] = at.toISOString();
253
+ await store.save(s);
254
+ deps.output.out(`Marker ${name} set at ${s.markers[name]}. Compare with: aispendbook report --compare --marker ${name}`);
255
+ return 0;
256
+ }
257
+ if (action === "remove") {
258
+ const had = name in s.markers;
259
+ delete s.markers[name];
260
+ await store.save(s);
261
+ deps.output.out(had ? `Removed marker ${name}.` : `No marker named ${name}.`);
262
+ return 0;
263
+ }
264
+ throw new UsageError("Use: aispendbook marker add NAME [--at TIME] | marker list | marker remove NAME");
265
+ }
266
+ async function report(args, deps) {
267
+ const { values } = parseArgs({
268
+ args, strict: true, allowPositionals: false,
269
+ options: {
270
+ since: { type: "string" }, until: { type: "string" }, by: { type: "string" }, source: { type: "string", multiple: true }, json: { type: "boolean" },
271
+ compare: { type: "boolean" }, split: { type: "string" }, marker: { type: "string" }, before: { type: "string" }, after: { type: "string" },
272
+ window: { type: "string" }, "min-sessions": { type: "string" }, sync: { type: "boolean" }, key: { type: "string" }, api: { type: "string" },
273
+ label: { type: "string" },
274
+ },
275
+ });
276
+ if (values.compare) {
277
+ if (values.since || values.until || values.by)
278
+ throw new UsageError("--compare takes --split, --marker, --window or --before/--after, not --since, --until or --by");
279
+ return compare(values, deps);
280
+ }
281
+ for (const k of ["split", "marker", "before", "after", "window", "min-sessions", "sync", "key", "api", "label"]) {
282
+ if (values[k] !== undefined)
283
+ throw new UsageError(`--${k} works with --compare only`);
284
+ }
285
+ const r = await makeService(deps).report({
286
+ since: values.since ?? DEFAULTS.reportSince, until: values.until, by: grouping(values.by), source: tools(values.source),
287
+ });
288
+ deps.output.out(values.json ? JSON.stringify({ ...r, cost_unit: "USD micros" }, null, 2) : formatTable(r));
289
+ return 0;
290
+ }
291
+ async function sync(args, deps) {
292
+ const { values } = parseArgs({
293
+ args, strict: true, allowPositionals: false,
294
+ options: {
295
+ key: { type: "string" }, api: { type: "string" }, since: { type: "string" }, source: { type: "string", multiple: true },
296
+ "project-names": { type: "string" }, "dry-run": { type: "boolean" },
297
+ },
298
+ });
299
+ const names = values["project-names"] ?? "hashed";
300
+ if (names !== "hashed" && names !== "plain")
301
+ throw new UsageError("--project-names must be hashed or plain");
302
+ const cfg = loadConfig(deps.env, deps.home, { api: values.api, key: values.key });
303
+ const dryRun = values["dry-run"] === true;
304
+ if (!dryRun && !cfg.ingestionKey) {
305
+ throw new UsageError(`An ingestion key is needed: pass --key afk_... or set ${ENV.ingestionKey}. Create one in AI Spendbook under Settings, Ingestion keys.`);
306
+ }
307
+ if (!/^https?:\/\//.test(cfg.apiBase))
308
+ throw new UsageError("--api must start with https:// or http://");
309
+ const now = deps.clock.now();
310
+ const state = new SyncStateStore(deps.fs, cfg.stateDir);
311
+ const saved = await state.load();
312
+ let range;
313
+ const last = saved.lastSyncAt[cfg.apiBase];
314
+ if (values.since)
315
+ range = parseRange(values.since, undefined, now);
316
+ else if (last && !Number.isNaN(Date.parse(last))) {
317
+ range = { since: new Date(Date.parse(last) - DEFAULTS.syncOverlapDays * 86_400_000), until: null };
318
+ }
319
+ else
320
+ range = parseRange(DEFAULTS.firstSyncSince, undefined, now);
321
+ const oldest = new Date(now.getTime() - DEFAULTS.maxEventAgeDays * 86_400_000);
322
+ if (range.since < oldest)
323
+ range = { ...range, since: oldest };
324
+ const sources = filterTools(buildSources(deps.fs, cfg.sources), tools(values.source));
325
+ const usage = await collectUsage(sources, range);
326
+ const events = usage.events
327
+ .filter((e) => e.occurredAt <= now)
328
+ .map((e) => toIngestEvent(e, { plainProjectNames: names === "plain", version: deps.version }));
329
+ const batches = Math.ceil(events.length / DEFAULTS.batchSize);
330
+ deps.output.err(`Found ${events.length} request(s) since ${range.since.toISOString()} in ${batches} batch(es) of up to ${DEFAULTS.batchSize}.`);
331
+ for (const n of usage.notes)
332
+ deps.output.err(n);
333
+ if (dryRun) {
334
+ deps.output.out(JSON.stringify({ dry_run: true, endpoint: `${cfg.apiBase}${DEFAULTS.ingestPath}`, events: events.length, batches, sample: events.slice(0, 3) }, null, 2));
335
+ return 0;
336
+ }
337
+ if (!events.length) {
338
+ deps.output.out("Nothing to upload.");
339
+ return 0;
340
+ }
341
+ const r = await deps.uploader.upload(events, {
342
+ apiBase: cfg.apiBase, ingestPath: DEFAULTS.ingestPath, key: cfg.ingestionKey, batchSize: DEFAULTS.batchSize,
343
+ maxRetries: DEFAULTS.maxRetries, maxRetryWaitMs: DEFAULTS.maxRetryWaitMs,
344
+ });
345
+ deps.output.out(`Written: ${r.accepted}. Already uploaded (duplicates): ${r.duplicates + r.crossSourceDuplicates}. Rejected: ${r.rejected}. Batches sent: ${r.batchesSent} of ${batches}.`);
346
+ for (const reason of r.rejectedReasons)
347
+ deps.output.err(`Rejected: ${reason}`);
348
+ if (r.error) {
349
+ deps.output.err(`Upload stopped: ${r.error}`);
350
+ return 1;
351
+ }
352
+ saved.lastSyncAt[cfg.apiBase] = now.toISOString();
353
+ await state.save(saved);
354
+ return 0;
355
+ }
356
+ async function mcp(deps) {
357
+ const server = new McpServer(makeService(deps), { name: "aispendbook", version: deps.version }, DEFAULTS.reportSince);
358
+ await server.serve(deps.stdin, deps.stdout);
359
+ return 0;
360
+ }
361
+ export async function runCli(argv, deps) {
362
+ const [command, ...rest] = argv;
363
+ try {
364
+ switch (command) {
365
+ case undefined:
366
+ case "help":
367
+ case "--help":
368
+ case "-h":
369
+ deps.output.out(HELP);
370
+ return 0;
371
+ case "--version":
372
+ case "-v":
373
+ deps.output.out(deps.version);
374
+ return 0;
375
+ case "report":
376
+ if (rest.includes("--help"))
377
+ return deps.output.out(HELP), 0;
378
+ return await report(rest, deps);
379
+ case "sync":
380
+ if (rest.includes("--help"))
381
+ return deps.output.out(HELP), 0;
382
+ return await sync(rest, deps);
383
+ case "cache-audit":
384
+ if (rest.includes("--help"))
385
+ return deps.output.out(HELP), 0;
386
+ return await cacheAudit(rest, deps);
387
+ case "skill":
388
+ return await skill(rest, deps);
389
+ case "marker":
390
+ return await marker(rest, deps);
391
+ case "mcp":
392
+ return await mcp(deps);
393
+ default:
394
+ throw new UsageError(`Unknown command "${command}". Run aispendbook --help.`);
395
+ }
396
+ }
397
+ catch (e) {
398
+ const msg = e instanceof Error ? e.message : String(e);
399
+ deps.output.err(`aispendbook: ${msg}`);
400
+ return 2;
401
+ }
402
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * report --compare: usage before and after a split point (the savings skill install, a marker, or a
3
+ * date), or in two date ranges, per session and per request.
4
+ *
5
+ * A session is one tool session id. It belongs to the period its first request falls in, and all of
6
+ * its requests count there. Requests without a session id are counted in the totals but not in the
7
+ * per-session figures. Costs are API-equivalent estimates at the dated list prices in prices.json.
8
+ *
9
+ * The result is an observed difference, never a saving: the work done in the two periods differs.
10
+ * Below the minimum number of sessions on either side the verdict is "not_enough_data".
11
+ */
12
+ import { formatUsd } from "./pricing.js";
13
+ import { localDay } from "./range.js";
14
+ export const COMPARE_BASIS = "Observed difference between two periods of your own logs, not a measured saving: the work differs between " +
15
+ "periods. Cost is an API-equivalent estimate at dated public list prices, not a bill.";
16
+ /** Linear interpolation between closest ranks (the common "type 7" percentile). */
17
+ export function percentile(sorted, p) {
18
+ if (!sorted.length)
19
+ return 0;
20
+ const pos = (sorted.length - 1) * p;
21
+ const lo = Math.floor(pos);
22
+ const hi = Math.ceil(pos);
23
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
24
+ }
25
+ export function spread(values) {
26
+ if (!values.length)
27
+ return null;
28
+ const s = [...values].sort((a, b) => a - b);
29
+ return { median: percentile(s, 0.5), p25: percentile(s, 0.25), p75: percentile(s, 0.75) };
30
+ }
31
+ function periodOf(at, p) {
32
+ if (at >= p.before.since && at < p.before.until)
33
+ return "before";
34
+ if (at >= p.after.since && at < p.after.until)
35
+ return "after";
36
+ return null;
37
+ }
38
+ function emptyPeriod(label, r) {
39
+ return {
40
+ label, since: r.since.toISOString(), until: r.until.toISOString(), sessions: 0, requests: 0,
41
+ requestsWithoutSession: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0,
42
+ costMicros: 0, unpricedRequests: 0, sessionsWithUnpricedRequests: 0, costPerSessionMicros: null,
43
+ costPerRequestMicros: null, meanCostPerRequestMicros: null, costPer1kOutputMicros: null,
44
+ sessionCostPer1kOutputMicros: null, requestsPerSession: null, sessionMinutes: null,
45
+ outputTokensPerSession: null, priceSources: [],
46
+ };
47
+ }
48
+ const pct = (before, after) => (before === 0 ? null : (after - before) / before);
49
+ export function compareUsage(events, prices, periods, o) {
50
+ const sessions = new Map();
51
+ const costs = new Map();
52
+ for (const e of events) {
53
+ const c = prices.cost(e);
54
+ costs.set(e, c);
55
+ if (!e.sessionId)
56
+ continue;
57
+ const key = `${e.tool}\u0000${e.sessionId}`;
58
+ const s = sessions.get(key) ?? { first: e.occurredAt, last: e.occurredAt, requests: 0, outputTokens: 0, costMicros: 0, unpriced: false };
59
+ sessions.set(key, s);
60
+ if (e.occurredAt < s.first)
61
+ s.first = e.occurredAt;
62
+ if (e.occurredAt > s.last)
63
+ s.last = e.occurredAt;
64
+ s.requests++;
65
+ s.outputTokens += e.outputTokens;
66
+ if (c.costMicros === null)
67
+ s.unpriced = true;
68
+ else
69
+ s.costMicros += c.costMicros;
70
+ }
71
+ const sessionPeriod = new Map();
72
+ for (const [k, s] of sessions)
73
+ sessionPeriod.set(k, periodOf(s.first, periods));
74
+ const stats = { before: emptyPeriod("before", periods.before), after: emptyPeriod("after", periods.after) };
75
+ const perRequest = { before: [], after: [] };
76
+ const sources = { before: new Map(), after: new Map() };
77
+ for (const e of events) {
78
+ const side = e.sessionId ? sessionPeriod.get(`${e.tool}\u0000${e.sessionId}`) ?? null : periodOf(e.occurredAt, periods);
79
+ if (!side)
80
+ continue;
81
+ const p = stats[side];
82
+ const priced = costs.get(e);
83
+ const cost = priced.costMicros;
84
+ p.requests++;
85
+ if (!e.sessionId)
86
+ p.requestsWithoutSession++;
87
+ p.inputTokens += e.inputTokens;
88
+ p.outputTokens += e.outputTokens;
89
+ p.cacheReadTokens += e.cacheReadTokens;
90
+ p.cacheWriteTokens += e.cacheWriteTokens;
91
+ if (cost === null)
92
+ p.unpricedRequests++;
93
+ else {
94
+ p.costMicros += cost;
95
+ perRequest[side].push(cost);
96
+ const src = priced.source;
97
+ if (src)
98
+ sources[side].set(`${src.url}\u0000${src.observedAt}`, src);
99
+ }
100
+ }
101
+ for (const side of ["before", "after"]) {
102
+ const list = [...sessions.entries()].filter(([k]) => sessionPeriod.get(k) === side).map(([, s]) => s);
103
+ const priced = list.filter((s) => !s.unpriced);
104
+ const p = stats[side];
105
+ p.sessions = list.length;
106
+ p.sessionsWithUnpricedRequests = list.length - priced.length;
107
+ p.costPerSessionMicros = spread(priced.map((s) => s.costMicros));
108
+ p.sessionCostPer1kOutputMicros = spread(priced.filter((s) => s.outputTokens > 0).map((s) => (s.costMicros * 1000) / s.outputTokens));
109
+ p.requestsPerSession = spread(list.map((s) => s.requests));
110
+ p.sessionMinutes = spread(list.map((s) => (s.last.getTime() - s.first.getTime()) / 60_000));
111
+ p.outputTokensPerSession = spread(list.map((s) => s.outputTokens));
112
+ p.costPerRequestMicros = spread(perRequest[side]);
113
+ const pricedRequests = p.requests - p.unpricedRequests;
114
+ p.meanCostPerRequestMicros = pricedRequests ? p.costMicros / pricedRequests : null;
115
+ p.costPer1kOutputMicros = p.outputTokens ? (p.costMicros * 1000) / p.outputTokens : null;
116
+ p.priceSources = [...sources[side].values()].sort((a, b) => a.url.localeCompare(b.url) || a.observedAt.localeCompare(b.observedAt));
117
+ }
118
+ const { before, after } = stats;
119
+ const base = {
120
+ basis: COMPARE_BASIS, splitAt: periods.splitAt?.toISOString() ?? null, splitSource: periods.splitSource,
121
+ minSessions: o.minSessions, before, after,
122
+ };
123
+ if (before.sessions < o.minSessions || after.sessions < o.minSessions) {
124
+ return {
125
+ ...base, verdict: "not_enough_data", differences: [],
126
+ verdictText: `Not enough data: ${before.sessions} session(s) before and ${after.sessions} after; at least ${o.minSessions} on each side are needed before any difference is shown.`,
127
+ caveats: [],
128
+ };
129
+ }
130
+ const differences = [];
131
+ const add = (metric, b, a) => {
132
+ if (b === null || b === undefined || a === null || a === undefined)
133
+ return;
134
+ differences.push({ metric, before: b, after: a, change: a - b, changePct: pct(b, a) });
135
+ };
136
+ add("median cost per session (micros)", before.costPerSessionMicros?.median, after.costPerSessionMicros?.median);
137
+ add("median cost per request (micros)", before.costPerRequestMicros?.median, after.costPerRequestMicros?.median);
138
+ add("cost per 1,000 output tokens (micros)", before.costPer1kOutputMicros, after.costPer1kOutputMicros);
139
+ add("median requests per session", before.requestsPerSession?.median, after.requestsPerSession?.median);
140
+ add("median session minutes", before.sessionMinutes?.median, after.sessionMinutes?.median);
141
+ add("median output tokens per session", before.outputTokensPerSession?.median, after.outputTokensPerSession?.median);
142
+ const caveats = ["Not a controlled experiment: the tasks, projects and models in the two periods differ, so a difference is not proof of a saving."];
143
+ const len = pct(before.requestsPerSession.median, after.requestsPerSession.median);
144
+ if (len !== null && Math.abs(len) > o.workShift) {
145
+ caveats.push(`Sessions differ in length: median requests per session changed by ${Math.round(len * 100)}%. Per-session cost mostly follows session length; read the per-request figures.`);
146
+ }
147
+ const bs = before.costPerSessionMicros;
148
+ const am = after.costPerSessionMicros?.median;
149
+ if (bs && am !== undefined && am >= bs.p25 && am <= bs.p75) {
150
+ caveats.push("The after median cost per session lies between the before period's 25th and 75th percentiles: within its usual spread.");
151
+ }
152
+ const srcKey = (p) => p.priceSources.map((s) => `${s.url}@${s.observedAt}`).join(",");
153
+ if (srcKey(before) !== srcKey(after))
154
+ caveats.push("The two periods were priced with different price sheets; list prices changed between them.");
155
+ if (before.sessionsWithUnpricedRequests || after.sessionsWithUnpricedRequests) {
156
+ caveats.push("Sessions with a model that has no list price are left out of the per-session cost figures.");
157
+ }
158
+ const c = differences[0];
159
+ return {
160
+ ...base, verdict: "observed_difference", differences, caveats,
161
+ verdictText: `Observed difference in median cost per session: ${signedUsd(c.change)} (${signedPct(c.changePct)}), ${before.sessions} sessions before and ${after.sessions} after. An observation, not a measured saving.`,
162
+ };
163
+ }
164
+ function signedUsd(micros) {
165
+ return `${micros < 0 ? "-" : "+"}${formatUsd(Math.abs(Math.round(micros)))}`;
166
+ }
167
+ function signedPct(v) {
168
+ return v === null ? "n/a" : `${v < 0 ? "" : "+"}${(v * 100).toFixed(1)}%`;
169
+ }
170
+ const n = (v) => Math.round(v).toLocaleString("en-US");
171
+ const usd = (micros) => (micros === null || micros === undefined ? "n/a" : formatUsd(Math.round(micros)));
172
+ const usdFine = (micros) => micros === null || micros === undefined ? "n/a" : `$${(micros / 1_000_000).toFixed(4)}`;
173
+ function spreadText(s, f) {
174
+ return s ? `${f(s.median)} (${f(s.p25)} to ${f(s.p75)})` : "n/a";
175
+ }
176
+ export function formatComparison(c) {
177
+ const day = (iso) => localDay(new Date(iso));
178
+ const rows = [
179
+ ["period", (p) => `${day(p.since)} to ${day(new Date(new Date(p.until).getTime() - 1).toISOString())}`],
180
+ ["sessions", (p) => n(p.sessions)],
181
+ ["requests", (p) => n(p.requests)],
182
+ ["input tokens (uncached)", (p) => n(p.inputTokens)],
183
+ ["output tokens", (p) => n(p.outputTokens)],
184
+ ["cache read tokens", (p) => n(p.cacheReadTokens)],
185
+ ["cache write tokens", (p) => n(p.cacheWriteTokens)],
186
+ ["cost (API-equivalent)", (p) => usd(p.costMicros)],
187
+ ["cost per session, median (p25 to p75)", (p) => spreadText(p.costPerSessionMicros, (v) => usd(v))],
188
+ ["cost per request, median (p25 to p75)", (p) => spreadText(p.costPerRequestMicros, (v) => usdFine(v))],
189
+ ["cost per request, mean", (p) => usdFine(p.meanCostPerRequestMicros)],
190
+ ["cost per 1,000 output tokens", (p) => usdFine(p.costPer1kOutputMicros)],
191
+ ["requests per session, median (p25 to p75)", (p) => spreadText(p.requestsPerSession, n)],
192
+ ["session minutes, median (p25 to p75)", (p) => spreadText(p.sessionMinutes, n)],
193
+ ["output tokens per session, median", (p) => spreadText(p.outputTokensPerSession, n)],
194
+ ];
195
+ const w0 = Math.max(...rows.map(([k]) => k.length));
196
+ const w1 = Math.max(6, ...rows.map(([, f]) => f(c.before).length));
197
+ const lines = [
198
+ `Before and after${c.splitAt ? ` ${c.splitSource} at ${c.splitAt}` : ` (${c.splitSource})`}`,
199
+ "",
200
+ `${"".padEnd(w0)} ${"before".padEnd(w1)} after`,
201
+ ...rows.map(([k, f]) => `${k.padEnd(w0)} ${f(c.before).padEnd(w1)} ${f(c.after)}`),
202
+ "",
203
+ c.verdictText,
204
+ ...c.caveats.map((x) => `- ${x}`),
205
+ ];
206
+ if (c.before.requestsWithoutSession || c.after.requestsWithoutSession) {
207
+ lines.push(`- ${n(c.before.requestsWithoutSession + c.after.requestsWithoutSession)} request(s) had no session id: in the totals, not in per-session figures.`);
208
+ }
209
+ const srcs = new Map();
210
+ for (const s of [...c.before.priceSources, ...c.after.priceSources])
211
+ srcs.set(`${s.url}@${s.observedAt}`, s);
212
+ lines.push("", "Prices: " + ([...srcs.values()].map((s) => `${s.url} (read ${s.observedAt})`).join("; ") || "none used"));
213
+ lines.push(c.basis);
214
+ return lines.join("\n");
215
+ }
216
+ const roundSpread = (s, f = Math.round) => s ? { median: f(s.median), p25: f(s.p25), p75: f(s.p75) } : null;
217
+ const oneDecimal = (v) => Math.round(v * 10) / 10;
218
+ /** The comparison as sent by `report --compare --sync`: counts, costs and dates only. */
219
+ export function toSavingsSummary(c, label, sdk) {
220
+ const period = (p) => ({
221
+ label: p.label, since: p.since, until: p.until, sessions: p.sessions, requests: p.requests,
222
+ input_tokens: p.inputTokens, output_tokens: p.outputTokens, cache_read_tokens: p.cacheReadTokens,
223
+ cache_write_tokens: p.cacheWriteTokens, cost_micros: p.costMicros, unpriced_requests: p.unpricedRequests,
224
+ cost_per_session_micros: roundSpread(p.costPerSessionMicros),
225
+ cost_per_request_micros: roundSpread(p.costPerRequestMicros),
226
+ cost_per_1k_output_micros: p.costPer1kOutputMicros === null ? null : Math.round(p.costPer1kOutputMicros),
227
+ requests_per_session: roundSpread(p.requestsPerSession, oneDecimal),
228
+ session_minutes: roundSpread(p.sessionMinutes, oneDecimal),
229
+ });
230
+ const sources = new Map();
231
+ for (const s of [...c.before.priceSources, ...c.after.priceSources])
232
+ sources.set(`${s.url}@${s.observedAt}`, s);
233
+ return {
234
+ label, split_at: c.splitAt, split_source: c.splitSource, min_sessions: c.minSessions, verdict: c.verdict,
235
+ verdict_text: c.verdictText, caveats: c.caveats, basis: c.basis, periods: [period(c.before), period(c.after)],
236
+ price_sources: [...sources.values()].map((s) => ({ url: s.url, observed_at: s.observedAt })), sdk,
237
+ };
238
+ }