@trazum/core 1.40.0 → 1.42.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.
@@ -0,0 +1,616 @@
1
+ /**
2
+ * Your bill, read from the provider, without anybody exporting anything.
3
+ *
4
+ * Every command in this product reads a file somebody produced by hand, and
5
+ * the export step is where adoption dies: the person who would benefit most
6
+ * from a cost report is the person least likely to have a `usage.jsonl` lying
7
+ * around. Every provider that bills by the token also serves that data over an
8
+ * API, and this module turns those payloads into figures the rest of Trazum
9
+ * already knows how to reason about.
10
+ *
11
+ * **Pure, and in the core, so it is testable without a network.** The fetch,
12
+ * the credentials and the pagination live in the CLI — the same split
13
+ * `openrouterOverlay` has had since 1.13. Everything here is a transformation
14
+ * of a document the caller already holds.
15
+ *
16
+ * **The honest part is what the providers cannot tell you.** Usage APIs serve
17
+ * *aggregates*: tokens per bucket per model, and — depending on the provider —
18
+ * a request count or nothing at all. They do not serve per-call rows. That
19
+ * makes a whole class of Trazum's findings impossible on this source: the
20
+ * shape of the calls, the truncation retries, the conversations, the largest
21
+ * call's context pressure. Those findings need per-call data and no amount of
22
+ * arithmetic recovers them from a sum.
23
+ *
24
+ * So a connected report is a **restricted** report, and it is restricted out
25
+ * loud. It carries its own shape rather than a `UsageProfileReport` with holes
26
+ * in it, precisely so a per-call finding can never read a zero this module
27
+ * wrote and report "nothing found" about something nobody measured. Not
28
+ * recorded is not not-happened, at the level of the type system.
29
+ */
30
+
31
+ import { effectivePricing, multipliersFor } from './pricing.js';
32
+ import type { PricingCatalogue } from './pricing.js';
33
+
34
+ // --------------------------------------------------------------------------
35
+ // What a source can and cannot answer
36
+ // --------------------------------------------------------------------------
37
+
38
+ /**
39
+ * `per-call` sources serve one row per request and unlock every finding in
40
+ * the product. `bucketed` sources serve sums over a window.
41
+ */
42
+ export type ConnectorGranularity = 'per-call' | 'bucketed';
43
+
44
+ /**
45
+ * A finding this source cannot support, why, and what would unlock it.
46
+ *
47
+ * Carried into the report and printed there. A restricted report that only
48
+ * omits things reads as a report that found nothing wrong.
49
+ */
50
+ export interface UnavailableFinding {
51
+ finding: string;
52
+ because: string;
53
+ unlockedBy: string;
54
+ }
55
+
56
+ /** Every finding that needs a row per call, named once. */
57
+ const PER_CALL_FINDINGS: readonly UnavailableFinding[] = [
58
+ {
59
+ finding: 'inputShapes',
60
+ because: 'the provider serves sums over a window, and the spread of call sizes is not in a sum',
61
+ unlockedBy: 'a per-call usage log, or the gateway',
62
+ },
63
+ {
64
+ finding: 'truncationRetries',
65
+ because: 'pairing a truncated answer with its retry needs both calls, their order and their stop reasons',
66
+ unlockedBy: 'a per-call usage log recording stop_reason and session',
67
+ },
68
+ {
69
+ finding: 'repeatedTurns',
70
+ because: 'the same request sent twice is invisible once both are added together',
71
+ unlockedBy: 'a per-call usage log recording session',
72
+ },
73
+ {
74
+ finding: 'sessionCosts',
75
+ because: 'conversations are not a dimension any usage API groups by',
76
+ unlockedBy: 'a per-call usage log recording session',
77
+ },
78
+ {
79
+ finding: 'contextPressure',
80
+ because: 'it reads the largest single call, and a total has lost the maximum',
81
+ unlockedBy: 'a per-call usage log, or the gateway',
82
+ },
83
+ {
84
+ finding: 'duplicateLines',
85
+ because: 'a doubled bill is caught by finding identical rows, and there are no rows here',
86
+ unlockedBy: 'a per-call usage log',
87
+ },
88
+ ];
89
+
90
+ export interface ConnectorDescriptor {
91
+ id: string;
92
+ displayName: string;
93
+ granularity: ConnectorGranularity;
94
+ /**
95
+ * Environment variables the CLI reads the credential from, in order.
96
+ *
97
+ * Named here so `trazum connect` can say exactly what it looked for when it
98
+ * finds nothing. Trazum stores no secret: a key lives in the environment or
99
+ * in a keychain the operating system owns, and never in this repository's
100
+ * config, cache or output.
101
+ */
102
+ credentialEnv: readonly string[];
103
+ /** The narrowest key that works, so nobody hands this tool a wider one. */
104
+ keyKind: string;
105
+ /** Whether the source serves a request count, or only token sums. */
106
+ servesCallCounts: boolean;
107
+ /** Findings impossible on this source. */
108
+ unavailable: readonly UnavailableFinding[];
109
+ docs: string;
110
+ }
111
+
112
+ /**
113
+ * The two providers this release connects to, and the asymmetry between them
114
+ * that a report must not paper over.
115
+ *
116
+ * OpenAI's usage endpoint serves a request count per bucket; Anthropic's
117
+ * serves token sums without one. So a connected OpenAI report can say "$412
118
+ * over 9,004 calls" and a connected Anthropic report can only say "$412", and
119
+ * every per-call average is available on one and absent on the other. Printing
120
+ * a call count of zero, or dividing by a denominator that does not exist,
121
+ * would be this module inventing the number it is here to stop inventing.
122
+ */
123
+ export const CONNECTORS: readonly ConnectorDescriptor[] = [
124
+ {
125
+ id: 'anthropic',
126
+ displayName: 'Anthropic',
127
+ granularity: 'bucketed',
128
+ credentialEnv: ['TRAZUM_ANTHROPIC_ADMIN_KEY', 'ANTHROPIC_ADMIN_KEY'],
129
+ keyKind: 'an Admin API key (read access to the usage report)',
130
+ servesCallCounts: false,
131
+ unavailable: [
132
+ ...PER_CALL_FINDINGS,
133
+ {
134
+ finding: 'calls',
135
+ because: 'the usage report serves token sums per bucket and no request count',
136
+ unlockedBy: 'a per-call usage log, or the gateway',
137
+ },
138
+ ],
139
+ docs: 'https://docs.anthropic.com/en/api/admin-api/usage-cost/get-messages-usage-report',
140
+ },
141
+ {
142
+ id: 'openai',
143
+ displayName: 'OpenAI',
144
+ granularity: 'bucketed',
145
+ credentialEnv: ['TRAZUM_OPENAI_ADMIN_KEY', 'OPENAI_ADMIN_KEY'],
146
+ keyKind: 'an Admin key with the api.usage.read scope',
147
+ servesCallCounts: true,
148
+ unavailable: PER_CALL_FINDINGS,
149
+ docs: 'https://platform.openai.com/docs/api-reference/usage',
150
+ },
151
+ ];
152
+
153
+ export function connectorFor(id: string): ConnectorDescriptor | null {
154
+ return CONNECTORS.find((c) => c.id === id) ?? null;
155
+ }
156
+
157
+ // --------------------------------------------------------------------------
158
+ // What a pull returns
159
+ // --------------------------------------------------------------------------
160
+
161
+ /**
162
+ * One provider bucket: a window, a model, and the tokens billed inside it.
163
+ *
164
+ * The cache-write TTL split is kept apart for the same reason `UsageBreakdown`
165
+ * keeps it apart — the two are billed at different multipliers, and a total
166
+ * that has lost the split cannot be repriced, only guessed at.
167
+ */
168
+ export interface UsageBucket {
169
+ fromMs: number;
170
+ toMs: number;
171
+ model: string;
172
+ /** null when the provider serves no request count. Never zero for absent. */
173
+ calls: number | null;
174
+ inputTokens: number;
175
+ cacheReadTokens: number;
176
+ cacheWrite5mTokens: number;
177
+ cacheWrite1hTokens: number;
178
+ /** False when the provider reported writes without saying which TTL. */
179
+ writeTtlKnown: boolean;
180
+ outputTokens: number;
181
+ /** Whatever the provider grouped by beyond the model — workspace, key, tier. */
182
+ group: Record<string, string>;
183
+ }
184
+
185
+ /**
186
+ * Something the pull did not get.
187
+ *
188
+ * A bill quietly short by an unknown amount is the failure this repository
189
+ * refuses everywhere it can occur, and a paginated API behind a rate limit is
190
+ * exactly where it occurs. Every gap is carried to the report and printed.
191
+ */
192
+ export interface PullGap {
193
+ kind:
194
+ | 'rate-limited'
195
+ | 'retention-boundary'
196
+ | 'cursor-expired'
197
+ | 'page-limit'
198
+ | 'unreadable-entry'
199
+ | 'unreadable-field';
200
+ detail: string;
201
+ }
202
+
203
+ export interface ConnectorPull {
204
+ provider: string;
205
+ granularity: ConnectorGranularity;
206
+ buckets: UsageBucket[];
207
+ /** The window the buckets actually cover, or null when none parsed. */
208
+ window: { fromMs: number; toMs: number } | null;
209
+ gaps: PullGap[];
210
+ unavailable: readonly UnavailableFinding[];
211
+ }
212
+
213
+ // --------------------------------------------------------------------------
214
+ // Normalising provider payloads
215
+ // --------------------------------------------------------------------------
216
+
217
+ const num = (value: unknown): number | null =>
218
+ typeof value === 'number' && Number.isFinite(value) ? value : null;
219
+
220
+ const ms = (value: unknown): number | null => {
221
+ if (typeof value === 'number' && Number.isFinite(value)) return value * 1000;
222
+ if (typeof value !== 'string') return null;
223
+ const parsed = Date.parse(value);
224
+ return Number.isNaN(parsed) ? null : parsed;
225
+ };
226
+
227
+ /** Merges buckets that share a window, model and grouping. */
228
+ function collect(buckets: UsageBucket[]): UsageBucket[] {
229
+ const merged = new Map<string, UsageBucket>();
230
+ for (const bucket of buckets) {
231
+ const key = `${bucket.fromMs}\n${bucket.toMs}\n${bucket.model}\n${JSON.stringify(bucket.group)}`;
232
+ const seen = merged.get(key);
233
+ if (seen === undefined) {
234
+ merged.set(key, { ...bucket });
235
+ continue;
236
+ }
237
+ seen.inputTokens += bucket.inputTokens;
238
+ seen.cacheReadTokens += bucket.cacheReadTokens;
239
+ seen.cacheWrite5mTokens += bucket.cacheWrite5mTokens;
240
+ seen.cacheWrite1hTokens += bucket.cacheWrite1hTokens;
241
+ seen.outputTokens += bucket.outputTokens;
242
+ seen.writeTtlKnown = seen.writeTtlKnown && bucket.writeTtlKnown;
243
+ // A count merged with an absent count is still absent: adding a number to
244
+ // "unknown" produces a number that describes only part of the traffic.
245
+ seen.calls = seen.calls === null || bucket.calls === null ? null : seen.calls + bucket.calls;
246
+ }
247
+ return [...merged.values()].sort((a, b) => a.fromMs - b.fromMs || a.model.localeCompare(b.model));
248
+ }
249
+
250
+ function windowOf(buckets: UsageBucket[]): { fromMs: number; toMs: number } | null {
251
+ if (buckets.length === 0) return null;
252
+ return {
253
+ fromMs: Math.min(...buckets.map((b) => b.fromMs)),
254
+ toMs: Math.max(...buckets.map((b) => b.toMs)),
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Anthropic's messages usage report.
260
+ *
261
+ * Shape: `{ data: [ { starting_at, ending_at, results: [ {...tokens, model} ] } ] }`.
262
+ * The fields read are the documented ones; anything unreadable is reported as
263
+ * a gap rather than defaulted to zero, because a zero here is a bill that is
264
+ * quietly smaller than the real one.
265
+ */
266
+ export function normalizeAnthropicUsage(payload: unknown): ConnectorPull {
267
+ const descriptor = connectorFor('anthropic')!;
268
+ const gaps: PullGap[] = [];
269
+ const buckets: UsageBucket[] = [];
270
+
271
+ const data = (payload as { data?: unknown })?.data;
272
+ if (!Array.isArray(data)) {
273
+ throw new Error(
274
+ 'This payload has no "data" array — is it the response from the Anthropic usage report endpoint?',
275
+ );
276
+ }
277
+
278
+ for (const [index, entry] of data.entries()) {
279
+ const row = entry as { starting_at?: unknown; ending_at?: unknown; results?: unknown };
280
+ const fromMs = ms(row.starting_at);
281
+ const toMs = ms(row.ending_at) ?? (fromMs === null ? null : fromMs);
282
+ if (fromMs === null || toMs === null) {
283
+ gaps.push({
284
+ kind: 'unreadable-entry',
285
+ detail: `bucket ${index} has no readable time window, so its tokens are in no period and were left out`,
286
+ });
287
+ continue;
288
+ }
289
+ const results = Array.isArray(row.results) ? row.results : [];
290
+ if (results.length === 0 && row.results !== undefined && !Array.isArray(row.results)) {
291
+ gaps.push({ kind: 'unreadable-entry', detail: `bucket ${index} has an unreadable "results" field` });
292
+ continue;
293
+ }
294
+ for (const result of results) {
295
+ const r = result as Record<string, unknown>;
296
+ const model = typeof r.model === 'string' ? r.model : null;
297
+ if (model === null) {
298
+ gaps.push({
299
+ kind: 'unreadable-entry',
300
+ detail: `a result in bucket ${index} names no model, so its tokens could not be priced and were left out`,
301
+ });
302
+ continue;
303
+ }
304
+ const creation = (r.cache_creation ?? {}) as Record<string, unknown>;
305
+ const write5m = num(creation.ephemeral_5m_input_tokens) ?? 0;
306
+ const write1h = num(creation.ephemeral_1h_input_tokens) ?? 0;
307
+ const flatWrite = num(r.cache_creation_input_tokens) ?? 0;
308
+ const ttlKnown = !(flatWrite > 0 && write5m === 0 && write1h === 0);
309
+ buckets.push({
310
+ fromMs,
311
+ toMs,
312
+ model,
313
+ // Documented and deliberate: the usage report has no request count.
314
+ calls: null,
315
+ inputTokens: num(r.uncached_input_tokens) ?? num(r.input_tokens) ?? 0,
316
+ cacheReadTokens: num(r.cache_read_input_tokens) ?? 0,
317
+ cacheWrite5mTokens: ttlKnown ? write5m : flatWrite,
318
+ cacheWrite1hTokens: ttlKnown ? write1h : 0,
319
+ writeTtlKnown: ttlKnown,
320
+ outputTokens: num(r.output_tokens) ?? 0,
321
+ group: groupOf(r, ['workspace_id', 'api_key_id', 'service_tier', 'context_window']),
322
+ });
323
+ }
324
+ }
325
+
326
+ const merged = collect(buckets);
327
+ return {
328
+ provider: 'anthropic',
329
+ granularity: 'bucketed',
330
+ buckets: merged,
331
+ window: windowOf(merged),
332
+ gaps,
333
+ unavailable: descriptor.unavailable,
334
+ };
335
+ }
336
+
337
+ /**
338
+ * OpenAI's completions usage endpoint.
339
+ *
340
+ * Shape: `{ data: [ { start_time, end_time, results: [ { input_tokens,
341
+ * output_tokens, input_cached_tokens, num_model_requests, model } ] } ] }`.
342
+ *
343
+ * This one serves a request count, so every per-call average is available on
344
+ * it — and the report says so, rather than making both providers look alike.
345
+ */
346
+ export function normalizeOpenAIUsage(payload: unknown): ConnectorPull {
347
+ const descriptor = connectorFor('openai')!;
348
+ const gaps: PullGap[] = [];
349
+ const buckets: UsageBucket[] = [];
350
+
351
+ const data = (payload as { data?: unknown })?.data;
352
+ if (!Array.isArray(data)) {
353
+ throw new Error(
354
+ 'This payload has no "data" array — is it the response from the OpenAI usage endpoint?',
355
+ );
356
+ }
357
+
358
+ for (const [index, entry] of data.entries()) {
359
+ const row = entry as { start_time?: unknown; end_time?: unknown; results?: unknown };
360
+ const fromMs = ms(row.start_time);
361
+ const toMs = ms(row.end_time) ?? (fromMs === null ? null : fromMs);
362
+ if (fromMs === null || toMs === null) {
363
+ gaps.push({
364
+ kind: 'unreadable-entry',
365
+ detail: `bucket ${index} has no readable time window, so its tokens are in no period and were left out`,
366
+ });
367
+ continue;
368
+ }
369
+ const results = Array.isArray(row.results) ? row.results : [];
370
+ for (const result of results) {
371
+ const r = result as Record<string, unknown>;
372
+ const model = typeof r.model === 'string' ? r.model : null;
373
+ if (model === null) {
374
+ gaps.push({
375
+ kind: 'unreadable-entry',
376
+ detail: `a result in bucket ${index} names no model, so its tokens could not be priced and were left out`,
377
+ });
378
+ continue;
379
+ }
380
+ const cached = num(r.input_cached_tokens) ?? 0;
381
+ const input = num(r.input_tokens) ?? 0;
382
+ buckets.push({
383
+ fromMs,
384
+ toMs,
385
+ model,
386
+ calls: num(r.num_model_requests),
387
+ // OpenAI reports cached tokens *inside* the input total, so the
388
+ // uncached half is the subtraction. Reporting both at face value
389
+ // would bill the cached tokens twice, at the dearer rate.
390
+ inputTokens: Math.max(0, input - cached),
391
+ cacheReadTokens: cached,
392
+ cacheWrite5mTokens: 0,
393
+ cacheWrite1hTokens: 0,
394
+ // Nothing was assumed: this API reports no cache writes at all, and an
395
+ // absent field is not an assumed TTL.
396
+ writeTtlKnown: true,
397
+ outputTokens: num(r.output_tokens) ?? 0,
398
+ group: groupOf(r, ['project_id', 'api_key_id', 'batch']),
399
+ });
400
+ }
401
+ }
402
+
403
+ const merged = collect(buckets);
404
+ return {
405
+ provider: 'openai',
406
+ granularity: 'bucketed',
407
+ buckets: merged,
408
+ window: windowOf(merged),
409
+ gaps,
410
+ unavailable: descriptor.unavailable,
411
+ };
412
+ }
413
+
414
+ function groupOf(row: Record<string, unknown>, keys: readonly string[]): Record<string, string> {
415
+ const group: Record<string, string> = {};
416
+ for (const key of keys) {
417
+ const value = row[key];
418
+ if (typeof value === 'string' && value !== '') group[key] = value;
419
+ else if (typeof value === 'number' && Number.isFinite(value)) group[key] = String(value);
420
+ else if (typeof value === 'boolean') group[key] = String(value);
421
+ }
422
+ return group;
423
+ }
424
+
425
+ // --------------------------------------------------------------------------
426
+ // The restricted report
427
+ // --------------------------------------------------------------------------
428
+
429
+ export interface BucketedSlice {
430
+ model: string;
431
+ /** null when the source serves no request count. */
432
+ calls: number | null;
433
+ inputTokens: number;
434
+ cacheReadTokens: number;
435
+ cacheWriteTokens: number;
436
+ outputTokens: number;
437
+ inputUsd: number;
438
+ cacheReadUsd: number;
439
+ cacheWriteUsd: number;
440
+ outputUsd: number;
441
+ totalUsd: number;
442
+ /** What the cache-touched tokens would have cost as ordinary input. */
443
+ cachedTokensAtInputRateUsd: number;
444
+ /** Writes priced at the 1-hour rate, when the source did not state the TTL. */
445
+ cacheWriteUsdIfAssumed1h: number;
446
+ writeTtlKnown: boolean;
447
+ }
448
+
449
+ export interface BucketedReport {
450
+ schemaVersion: 1;
451
+ provider: string;
452
+ granularity: ConnectorGranularity;
453
+ span: { fromMs: number; toMs: number } | null;
454
+ total: {
455
+ totalUsd: number;
456
+ /** null when unknown — never zero, which would read as "no traffic". */
457
+ calls: number | null;
458
+ inputTokens: number;
459
+ cacheReadTokens: number;
460
+ cacheWriteTokens: number;
461
+ outputTokens: number;
462
+ };
463
+ byModel: BucketedSlice[];
464
+ /** Spend per UTC day, oldest first — the shape a total hides. */
465
+ byDay: { day: string; usd: number; calls: number | null }[];
466
+ /** Models the catalogue could not price: named, with their tokens kept. */
467
+ unpricedModels: { model: string; inputTokens: number; outputTokens: number }[];
468
+ gaps: PullGap[];
469
+ unavailable: readonly UnavailableFinding[];
470
+ }
471
+
472
+ /**
473
+ * Prices the buckets a connector pulled.
474
+ *
475
+ * Every figure here is the provider's own billed token count at the
476
+ * catalogue's rates — the same arithmetic `profile` does, over sums instead of
477
+ * rows. What it deliberately does not do is synthesise the per-call findings:
478
+ * they are listed as unavailable and left absent, so nothing downstream can
479
+ * read a zero this function wrote.
480
+ */
481
+ export function bucketedProfile(
482
+ pull: ConnectorPull,
483
+ options: { catalogue: PricingCatalogue; on?: Date },
484
+ ): BucketedReport {
485
+ const { catalogue, on = new Date() } = options;
486
+
487
+ const slices = new Map<string, BucketedSlice>();
488
+ const days = new Map<string, { usd: number; calls: number | null }>();
489
+ const unpriced = new Map<string, { inputTokens: number; outputTokens: number }>();
490
+
491
+ for (const bucket of pull.buckets) {
492
+ const model = catalogue.byId.get(bucket.model);
493
+ if (model === undefined) {
494
+ const seen = unpriced.get(bucket.model) ?? { inputTokens: 0, outputTokens: 0 };
495
+ seen.inputTokens += bucket.inputTokens + bucket.cacheReadTokens;
496
+ seen.outputTokens += bucket.outputTokens;
497
+ unpriced.set(bucket.model, seen);
498
+ continue;
499
+ }
500
+
501
+ const { inputPerMTok, outputPerMTok } = effectivePricing(model, on);
502
+ const rates = multipliersFor(model);
503
+ const per = (count: number, rate: number): number => (count / 1_000_000) * rate;
504
+
505
+ const inputUsd = per(bucket.inputTokens, inputPerMTok);
506
+ const cacheReadUsd = per(bucket.cacheReadTokens, inputPerMTok * rates.cacheRead);
507
+ const cacheWriteUsd =
508
+ per(bucket.cacheWrite5mTokens, inputPerMTok * rates.cacheWrite5m) +
509
+ per(bucket.cacheWrite1hTokens, inputPerMTok * rates.cacheWrite1h);
510
+ const outputUsd = per(bucket.outputTokens, outputPerMTok);
511
+ const writeTokens = bucket.cacheWrite5mTokens + bucket.cacheWrite1hTokens;
512
+ const atInputRate = per(bucket.cacheReadTokens + writeTokens, inputPerMTok);
513
+ const ifAssumed1h = bucket.writeTtlKnown
514
+ ? cacheWriteUsd
515
+ : per(writeTokens, inputPerMTok * rates.cacheWrite1h);
516
+
517
+ const slice = slices.get(bucket.model) ?? {
518
+ model: bucket.model,
519
+ calls: bucket.calls === null ? null : 0,
520
+ inputTokens: 0,
521
+ cacheReadTokens: 0,
522
+ cacheWriteTokens: 0,
523
+ outputTokens: 0,
524
+ inputUsd: 0,
525
+ cacheReadUsd: 0,
526
+ cacheWriteUsd: 0,
527
+ outputUsd: 0,
528
+ totalUsd: 0,
529
+ cachedTokensAtInputRateUsd: 0,
530
+ cacheWriteUsdIfAssumed1h: 0,
531
+ writeTtlKnown: true,
532
+ };
533
+ slice.calls = slice.calls === null || bucket.calls === null ? null : slice.calls + bucket.calls;
534
+ slice.inputTokens += bucket.inputTokens;
535
+ slice.cacheReadTokens += bucket.cacheReadTokens;
536
+ slice.cacheWriteTokens += writeTokens;
537
+ slice.outputTokens += bucket.outputTokens;
538
+ slice.inputUsd += inputUsd;
539
+ slice.cacheReadUsd += cacheReadUsd;
540
+ slice.cacheWriteUsd += cacheWriteUsd;
541
+ slice.outputUsd += outputUsd;
542
+ slice.totalUsd += inputUsd + cacheReadUsd + cacheWriteUsd + outputUsd;
543
+ slice.cachedTokensAtInputRateUsd += atInputRate;
544
+ slice.cacheWriteUsdIfAssumed1h += ifAssumed1h;
545
+ slice.writeTtlKnown = slice.writeTtlKnown && bucket.writeTtlKnown;
546
+ slices.set(bucket.model, slice);
547
+
548
+ const day = new Date(bucket.fromMs).toISOString().slice(0, 10);
549
+ const entry = days.get(day) ?? { usd: 0, calls: bucket.calls === null ? null : 0 };
550
+ entry.usd += inputUsd + cacheReadUsd + cacheWriteUsd + outputUsd;
551
+ entry.calls = entry.calls === null || bucket.calls === null ? null : entry.calls + bucket.calls;
552
+ days.set(day, entry);
553
+ }
554
+
555
+ const byModel = [...slices.values()].sort((a, b) => b.totalUsd - a.totalUsd);
556
+ const anyCallsUnknown = byModel.some((s) => s.calls === null) || byModel.length === 0;
557
+
558
+ return {
559
+ schemaVersion: 1,
560
+ provider: pull.provider,
561
+ granularity: pull.granularity,
562
+ span: pull.window,
563
+ total: {
564
+ totalUsd: byModel.reduce((sum, s) => sum + s.totalUsd, 0),
565
+ calls: anyCallsUnknown ? null : byModel.reduce((sum, s) => sum + (s.calls ?? 0), 0),
566
+ inputTokens: byModel.reduce((sum, s) => sum + s.inputTokens, 0),
567
+ cacheReadTokens: byModel.reduce((sum, s) => sum + s.cacheReadTokens, 0),
568
+ cacheWriteTokens: byModel.reduce((sum, s) => sum + s.cacheWriteTokens, 0),
569
+ outputTokens: byModel.reduce((sum, s) => sum + s.outputTokens, 0),
570
+ },
571
+ byModel,
572
+ byDay: [...days.entries()]
573
+ .sort((a, b) => a[0].localeCompare(b[0]))
574
+ .map(([day, entry]) => ({ day, usd: entry.usd, calls: entry.calls })),
575
+ unpricedModels: [...unpriced.entries()]
576
+ .map(([model, tokens]) => ({ model, ...tokens }))
577
+ .sort((a, b) => b.inputTokens + b.outputTokens - (a.inputTokens + a.outputTokens)),
578
+ gaps: pull.gaps,
579
+ unavailable: pull.unavailable,
580
+ };
581
+ }
582
+
583
+ /**
584
+ * The cache verdict over a connected report.
585
+ *
586
+ * Same counterfactual `cacheEconomics` runs on a per-call report: what the
587
+ * cache-touched tokens cost, against what they would have cost as ordinary
588
+ * input. The worst case is carried separately for the same reason it is
589
+ * there — when the source did not state the write TTL, the cheaper rate was
590
+ * assumed for the headline and the verdict can move under the other one.
591
+ */
592
+ export function bucketedCacheEconomics(report: BucketedReport): {
593
+ spentUsd: number;
594
+ withoutCachingUsd: number;
595
+ deltaUsd: number;
596
+ verdict: 'paid-off' | 'lost-money' | 'no-cache';
597
+ worstCaseVerdict: 'paid-off' | 'lost-money' | 'no-cache';
598
+ } {
599
+ const spent = report.byModel.reduce((sum, s) => sum + s.cacheReadUsd + s.cacheWriteUsd, 0);
600
+ const without = report.byModel.reduce((sum, s) => sum + s.cachedTokensAtInputRateUsd, 0);
601
+ const worst = report.byModel.reduce((sum, s) => sum + s.cacheReadUsd + s.cacheWriteUsdIfAssumed1h, 0);
602
+ const touched = report.byModel.reduce((sum, s) => sum + s.cacheReadTokens + s.cacheWriteTokens, 0);
603
+
604
+ const verdictOf = (paid: number): 'paid-off' | 'lost-money' | 'no-cache' => {
605
+ if (touched === 0) return 'no-cache';
606
+ return paid <= without ? 'paid-off' : 'lost-money';
607
+ };
608
+
609
+ return {
610
+ spentUsd: spent,
611
+ withoutCachingUsd: without,
612
+ deltaUsd: spent - without,
613
+ verdict: verdictOf(spent),
614
+ worstCaseVerdict: verdictOf(worst),
615
+ };
616
+ }
package/src/history.ts CHANGED
@@ -29,7 +29,12 @@ export interface StoredReport {
29
29
  name: string;
30
30
  span: { fromMs: number; toMs: number } | null;
31
31
  totalUsd: number;
32
- calls: number;
32
+ /**
33
+ * null when the source serves no request count — a bucketed usage API. Zero
34
+ * would read as "no traffic" against real spend, which is the reading this
35
+ * product refuses everywhere it can occur.
36
+ */
37
+ calls: number | null;
33
38
  /** Label → dollars this period. */
34
39
  byLabel: Map<string, number>;
35
40
  /** Model → dollars this period. */
@@ -70,7 +75,7 @@ export interface RepeatedPlanAction {
70
75
  export interface HistoryDocument {
71
76
  schemaVersion: 1;
72
77
  /** Ordered oldest first by span start. */
73
- periods: { name: string; fromMs: number; toMs: number; totalUsd: number; calls: number }[];
78
+ periods: { name: string; fromMs: number; toMs: number; totalUsd: number; calls: number | null }[];
74
79
  /** Per label, dollars per period — null where the label had no traffic. */
75
80
  labelSeries: { label: string; points: (number | null)[] }[];
76
81
  /** Per model, share of that period's total — null where absent. */
package/src/index.ts CHANGED
@@ -48,6 +48,34 @@ export { buildPlan, planLabelName } from './plan.js';
48
48
  export type { PlanAction, PlanActionKind, PlanAssumption, PlanDocument } from './plan.js';
49
49
  export { verifyPlan } from './verify.js';
50
50
  export { buildHistory, storedReportFrom, MIN_RUN } from './history.js';
51
+ export {
52
+ STORE_SCHEMA_VERSION,
53
+ identityOf,
54
+ resolveStore,
55
+ recordsFromBuckets,
56
+ bucketsFromRecords,
57
+ storeInventory,
58
+ pruneRecords,
59
+ } from './store.js';
60
+ export type { PruneResult, ResolvedStore, StoreInventory, StoreRecord } from './store.js';
61
+ export {
62
+ CONNECTORS,
63
+ connectorFor,
64
+ normalizeAnthropicUsage,
65
+ normalizeOpenAIUsage,
66
+ bucketedProfile,
67
+ bucketedCacheEconomics,
68
+ } from './connector.js';
69
+ export type {
70
+ BucketedReport,
71
+ BucketedSlice,
72
+ ConnectorDescriptor,
73
+ ConnectorGranularity,
74
+ ConnectorPull,
75
+ PullGap,
76
+ UnavailableFinding,
77
+ UsageBucket,
78
+ } from './connector.js';
51
79
  export type { HistoryDocument, HistoryRun, RepeatedPlanAction, StoredReport } from './history.js';
52
80
  export type { CannotTellReason, PlanVerification, VerifiedAction, VerifyOutcome } from './verify.js';
53
81
  export type { FleetSource, FleetRollup } from './fleet.js';