burnoff 1.0.0 → 1.2.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.
Files changed (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -0,0 +1,1033 @@
1
+ /**
2
+ * @file src/config/pricing.mjs
3
+ * Versioned, date-aware model rate card and valuation engine for Claude Code,
4
+ * Gemini, and OpenAI telemetry in burnoff.
5
+ */
6
+
7
+ export const RATE_CARD_VERSION = '2026-11-27';
8
+ export const DEFAULT_UNMAPPED_CACHED_WEIGHT = 0.05;
9
+ const UPCOMING_NOTICE_WINDOW_MS = 14 * 86_400_000;
10
+
11
+ export const SUBSCRIPTION_QUOTA_CONSTANTS = Object.freeze({
12
+ ARGON_CARBON_PER_USD_WEIGHT: 3.0,
13
+ HYDROGEN_BASELINE_PER_USD_WEIGHT: 1.0,
14
+ SDK_CLI_HEADLESS_MULTIPLIER: 1.8,
15
+ SDK_CLI_IS_HEURISTIC: true,
16
+ ACP_CUSTOM_AGENT_MULTIPLIER: 4.0,
17
+ ACP_CUSTOM_AGENT_AFFECTED_VERSION: '1.5.17'
18
+ });
19
+
20
+ export const CATALOG_QUOTA_MULTIPLIERS = Object.freeze({
21
+ 'gemini-4-carbon': Object.freeze({ low: 3.2, medium: 6, high: 10 }),
22
+ 'gemini-4-argon': Object.freeze({ low: 3, medium: 5.5, high: 9.25 }),
23
+ 'gemini-4-neon': Object.freeze({ low: 2.4, medium: 4.5, high: 7.5, xhigh: 11 }),
24
+ 'gemini-4-hydrogen': Object.freeze({ low: 1.5, medium: 2.5, high: 4, xhigh: 6 }),
25
+ 'gemini-3.8-flash': Object.freeze({ low: 1, medium: 1.5, high: 2.2 }),
26
+ 'gemini-3.1-pro': Object.freeze({ low: 2, medium: 3.5, high: 5.5 }),
27
+ 'gemini-2.5-pro': Object.freeze({ low: 2, medium: 3.5, high: 5.5 }),
28
+ 'claude-haiku-5-5': Object.freeze({ low: 0.5, medium: 0.8, high: 1.2 }),
29
+ 'claude-sonnet-5-5': Object.freeze({ low: 3, medium: 4.5, high: 7 }),
30
+ 'claude-opus-5-5': Object.freeze({ low: 6, medium: 9, high: 14 }),
31
+ 'claude-fable-5-2': Object.freeze({ low: 10, medium: 15, high: 22 }),
32
+ 'claude-fable-5-1': Object.freeze({ low: 12, medium: 18, high: 26 }),
33
+ 'claude-opus-4-6': Object.freeze({ low: 7.5, medium: 11, high: 16 }),
34
+ 'claude-sonnet-4-6': Object.freeze({ low: 3.5, medium: 5, high: 7.5 }),
35
+ 'claude-haiku-4-5': Object.freeze({ low: 1.2, medium: 1.8, high: 2.5 })
36
+ });
37
+
38
+ function freezeRates(inputPer1M, cachedReadPer1M, outputPer1M, write5mPer1M = inputPer1M, write1hPer1M = inputPer1M) {
39
+ return Object.freeze({
40
+ inputPer1M,
41
+ cachedReadPer1M,
42
+ write5mPer1M,
43
+ write1hPer1M,
44
+ outputPer1M
45
+ });
46
+ }
47
+
48
+ function freezeSchedule(id, effectiveFromUtc, effectiveUntilUtc, standard, priority = standard, cliff = null) {
49
+ return Object.freeze({
50
+ id,
51
+ effectiveFromUtc,
52
+ effectiveUntilUtc,
53
+ standard,
54
+ priority,
55
+ cliff
56
+ });
57
+ }
58
+
59
+ export const RATE_CARD_MODELS = Object.freeze({
60
+ 'gemini-4-neon': Object.freeze({
61
+ modelId: 'gemini-4-neon',
62
+ label: 'Gemini 4 Neon',
63
+ cachedReadWeight: 0.05,
64
+ minCacheableTokens: 4096,
65
+ sharedPoolCeiling: 1048576,
66
+ cliffThresholdTokens: null,
67
+ outputIncludesThinking: true,
68
+ schedules: Object.freeze([
69
+ freezeSchedule(
70
+ 'neon-standard',
71
+ null,
72
+ null,
73
+ freezeRates(3.0, 0.15, 15.0),
74
+ freezeRates(5.4, 0.15, 27.0)
75
+ )
76
+ ])
77
+ }),
78
+ 'gemini-4-carbon': Object.freeze({
79
+ modelId: 'gemini-4-carbon',
80
+ label: 'Gemini 4 Carbon',
81
+ cachedReadWeight: 0.05,
82
+ minCacheableTokens: 4096,
83
+ sharedPoolCeiling: 1048576,
84
+ cliffThresholdTokens: null,
85
+ outputIncludesThinking: true,
86
+ schedules: Object.freeze([
87
+ freezeSchedule(
88
+ 'carbon-introductory-pre-2026-12-01',
89
+ null,
90
+ '2026-11-30T23:59:59Z',
91
+ freezeRates(2.0, 0.10, 10.0),
92
+ freezeRates(3.6, 0.10, 18.0)
93
+ ),
94
+ freezeSchedule(
95
+ 'carbon-standard-from-2026-12-01',
96
+ '2026-12-01T00:00:00Z',
97
+ null,
98
+ freezeRates(4.0, 0.20, 20.0),
99
+ freezeRates(7.2, 0.20, 36.0)
100
+ )
101
+ ])
102
+ }),
103
+ 'gemini-4-argon': Object.freeze({
104
+ modelId: 'gemini-4-argon',
105
+ label: 'Gemini 4 Argon',
106
+ cachedReadWeight: 0.05,
107
+ minCacheableTokens: 4096,
108
+ sharedPoolCeiling: 1048576,
109
+ cliffThresholdTokens: null,
110
+ outputIncludesThinking: true,
111
+ schedules: Object.freeze([
112
+ freezeSchedule(
113
+ 'argon-introductory-pre-2026-12-01',
114
+ null,
115
+ '2026-11-30T23:59:59Z',
116
+ freezeRates(2.0, 0.10, 10.0),
117
+ freezeRates(3.6, 0.10, 18.0)
118
+ ),
119
+ freezeSchedule(
120
+ 'argon-standard-from-2026-12-01',
121
+ '2026-12-01T00:00:00Z',
122
+ null,
123
+ freezeRates(4.0, 0.20, 20.0),
124
+ freezeRates(7.2, 0.20, 36.0)
125
+ )
126
+ ])
127
+ }),
128
+ 'gemini-4-hydrogen': Object.freeze({
129
+ modelId: 'gemini-4-hydrogen',
130
+ label: 'Gemini 4 Hydrogen',
131
+ cachedReadWeight: 0.05,
132
+ minCacheableTokens: 4096,
133
+ sharedPoolCeiling: 1048576,
134
+ cliffThresholdTokens: null,
135
+ outputIncludesThinking: true,
136
+ schedules: Object.freeze([
137
+ freezeSchedule(
138
+ 'hydrogen-standard',
139
+ null,
140
+ null,
141
+ freezeRates(1.5, 0.075, 7.5),
142
+ freezeRates(2.7, 0.075, 13.5)
143
+ )
144
+ ])
145
+ }),
146
+ 'gemini-3.8-flash': Object.freeze({
147
+ modelId: 'gemini-3.8-flash',
148
+ label: 'Gemini 3.8 Flash',
149
+ cachedReadWeight: 0.10,
150
+ minCacheableTokens: 4096,
151
+ sharedPoolCeiling: 1000000,
152
+ cliffThresholdTokens: null,
153
+ outputIncludesThinking: true,
154
+ schedules: Object.freeze([
155
+ freezeSchedule(
156
+ 'flash-38-pre-2027-01-01',
157
+ null,
158
+ '2026-12-31T23:59:59Z',
159
+ freezeRates(0.75, 0.075, 3.75),
160
+ freezeRates(1.35, 0.075, 6.75)
161
+ ),
162
+ freezeSchedule(
163
+ 'flash-38-from-2027-01-01',
164
+ '2027-01-01T00:00:00Z',
165
+ null,
166
+ freezeRates(1.5, 0.15, 7.5),
167
+ freezeRates(2.7, 0.15, 13.5)
168
+ )
169
+ ])
170
+ }),
171
+ 'gemini-3.1-pro': Object.freeze({
172
+ modelId: 'gemini-3.1-pro',
173
+ label: 'Gemini 3.1 Pro',
174
+ cachedReadWeight: 0.10,
175
+ minCacheableTokens: 4096,
176
+ sharedPoolCeiling: 1048576,
177
+ cliffThresholdTokens: 200000,
178
+ outputIncludesThinking: true,
179
+ schedules: Object.freeze([
180
+ freezeSchedule(
181
+ 'gemini-3-1-pro-standard',
182
+ null,
183
+ null,
184
+ freezeRates(2.0, 0.20, 12.0),
185
+ freezeRates(2.0, 0.20, 12.0),
186
+ freezeRates(4.0, 0.40, 18.0)
187
+ )
188
+ ])
189
+ }),
190
+ 'gemini-2.5-pro': Object.freeze({
191
+ modelId: 'gemini-2.5-pro',
192
+ label: 'Gemini 2.5 Pro',
193
+ cachedReadWeight: 0.10,
194
+ minCacheableTokens: 4096,
195
+ sharedPoolCeiling: 1048576,
196
+ cliffThresholdTokens: 200000,
197
+ outputIncludesThinking: true,
198
+ schedules: Object.freeze([
199
+ freezeSchedule(
200
+ 'gemini-2-5-pro-standard',
201
+ null,
202
+ null,
203
+ freezeRates(1.25, 0.125, 10.0),
204
+ freezeRates(1.25, 0.125, 10.0),
205
+ freezeRates(2.5, 0.25, 15.0)
206
+ )
207
+ ])
208
+ }),
209
+ 'claude-opus-5-5': Object.freeze({
210
+ modelId: 'claude-opus-5-5',
211
+ label: 'Claude Opus 5.5',
212
+ cachedReadWeight: 0.05,
213
+ minCacheableTokens: 512,
214
+ sharedPoolCeiling: 1000000,
215
+ cliffThresholdTokens: null,
216
+ outputIncludesThinking: true,
217
+ schedules: Object.freeze([
218
+ freezeSchedule(
219
+ 'claude-opus-5-5-standard',
220
+ null,
221
+ null,
222
+ freezeRates(4.0, 0.20, 20.0, 5.0, 8.0)
223
+ )
224
+ ])
225
+ }),
226
+ 'claude-sonnet-5-5': Object.freeze({
227
+ modelId: 'claude-sonnet-5-5',
228
+ label: 'Claude Sonnet 5.5',
229
+ cachedReadWeight: 0.05,
230
+ minCacheableTokens: 512,
231
+ sharedPoolCeiling: 1000000,
232
+ cliffThresholdTokens: null,
233
+ outputIncludesThinking: true,
234
+ schedules: Object.freeze([
235
+ freezeSchedule(
236
+ 'claude-sonnet-5-5-standard',
237
+ null,
238
+ null,
239
+ freezeRates(2.0, 0.10, 10.0, 2.5, 4.0)
240
+ )
241
+ ])
242
+ }),
243
+ 'claude-fable-5-1': Object.freeze({
244
+ modelId: 'claude-fable-5-1',
245
+ label: 'Claude Fable 5.1',
246
+ cachedReadWeight: 0.025,
247
+ minCacheableTokens: 1024,
248
+ sharedPoolCeiling: 1000000,
249
+ cliffThresholdTokens: null,
250
+ outputIncludesThinking: true,
251
+ schedules: Object.freeze([
252
+ freezeSchedule(
253
+ 'claude-fable-5-1-standard',
254
+ null,
255
+ null,
256
+ freezeRates(10.0, 0.25, 50.0, 12.5, 20.0)
257
+ )
258
+ ])
259
+ }),
260
+ 'claude-fable-5-2': Object.freeze({
261
+ modelId: 'claude-fable-5-2',
262
+ label: 'Claude Fable 5.2',
263
+ cachedReadWeight: 0.025,
264
+ minCacheableTokens: 1024,
265
+ sharedPoolCeiling: 1000000,
266
+ cliffThresholdTokens: null,
267
+ outputIncludesThinking: true,
268
+ schedules: Object.freeze([
269
+ freezeSchedule(
270
+ 'claude-fable-5-2-standard',
271
+ null,
272
+ null,
273
+ freezeRates(8.0, 0.20, 40.0, 10.0, 16.0)
274
+ )
275
+ ])
276
+ }),
277
+ 'claude-haiku-5-5': Object.freeze({
278
+ modelId: 'claude-haiku-5-5',
279
+ label: 'Claude Haiku 5.5',
280
+ cachedReadWeight: 0.10,
281
+ minCacheableTokens: 512,
282
+ sharedPoolCeiling: 1000000,
283
+ cliffThresholdTokens: 100000,
284
+ outputIncludesThinking: true,
285
+ schedules: Object.freeze([
286
+ freezeSchedule(
287
+ 'claude-haiku-5-5-standard',
288
+ null,
289
+ null,
290
+ freezeRates(0.10, 0.01, 0.50, 0.125, 0.20),
291
+ freezeRates(0.10, 0.01, 0.50, 0.125, 0.20),
292
+ freezeRates(0.50, 0.05, 2.50, 0.625, 1.00)
293
+ )
294
+ ])
295
+ }),
296
+ 'claude-opus-4-6': Object.freeze({
297
+ modelId: 'claude-opus-4-6',
298
+ label: 'Claude Opus 4.6',
299
+ cachedReadWeight: 0.10,
300
+ minCacheableTokens: 1024,
301
+ sharedPoolCeiling: 200000,
302
+ cliffThresholdTokens: 200000,
303
+ outputIncludesThinking: true,
304
+ schedules: Object.freeze([
305
+ freezeSchedule(
306
+ 'claude-opus-4-6-standard',
307
+ null,
308
+ null,
309
+ freezeRates(5.0, 0.50, 25.0, 6.25, 10.0),
310
+ freezeRates(5.0, 0.50, 25.0, 6.25, 10.0),
311
+ freezeRates(10.0, 1.0, 37.5, 12.5, 20.0)
312
+ )
313
+ ])
314
+ }),
315
+ 'claude-sonnet-4-6': Object.freeze({
316
+ modelId: 'claude-sonnet-4-6',
317
+ label: 'Claude Sonnet 4.6',
318
+ cachedReadWeight: 0.10,
319
+ minCacheableTokens: 1024,
320
+ sharedPoolCeiling: 200000,
321
+ cliffThresholdTokens: 200000,
322
+ outputIncludesThinking: true,
323
+ schedules: Object.freeze([
324
+ freezeSchedule(
325
+ 'claude-sonnet-4-6-standard',
326
+ null,
327
+ null,
328
+ freezeRates(3.0, 0.30, 15.0, 3.75, 6.0),
329
+ freezeRates(3.0, 0.30, 15.0, 3.75, 6.0),
330
+ freezeRates(6.0, 0.60, 22.5, 7.5, 12.0)
331
+ )
332
+ ])
333
+ }),
334
+ 'claude-haiku-4-5': Object.freeze({
335
+ modelId: 'claude-haiku-4-5',
336
+ label: 'Claude Haiku 4.5',
337
+ cachedReadWeight: 0.10,
338
+ minCacheableTokens: 1024,
339
+ sharedPoolCeiling: 200000,
340
+ cliffThresholdTokens: null,
341
+ outputIncludesThinking: true,
342
+ schedules: Object.freeze([
343
+ freezeSchedule(
344
+ 'claude-haiku-4-5-standard',
345
+ null,
346
+ null,
347
+ freezeRates(1.0, 0.10, 5.0, 1.25, 2.0)
348
+ )
349
+ ])
350
+ }),
351
+ 'gpt-6.1-sol': Object.freeze({
352
+ modelId: 'gpt-6.1-sol',
353
+ label: 'GPT-6.1 Sol',
354
+ cachedReadWeight: 0.05,
355
+ minCacheableTokens: 512,
356
+ sharedPoolCeiling: 1048576,
357
+ cliffThresholdTokens: null,
358
+ outputIncludesThinking: true,
359
+ schedules: Object.freeze([
360
+ freezeSchedule(
361
+ 'gpt-6-1-sol-standard',
362
+ null,
363
+ null,
364
+ freezeRates(3.0, 0.15, 15.0, 3.75, 3.75)
365
+ )
366
+ ])
367
+ }),
368
+ 'gpt-5.4': Object.freeze({
369
+ modelId: 'gpt-5.4',
370
+ label: 'GPT-5.4',
371
+ cachedReadWeight: 0.10,
372
+ minCacheableTokens: 512,
373
+ sharedPoolCeiling: 1050000,
374
+ cliffThresholdTokens: 272000,
375
+ outputIncludesThinking: true,
376
+ schedules: Object.freeze([
377
+ freezeSchedule(
378
+ 'gpt-5-4-standard',
379
+ null,
380
+ null,
381
+ freezeRates(2.5, 0.25, 15.0),
382
+ freezeRates(2.5, 0.25, 15.0),
383
+ freezeRates(5.0, 0.50, 22.5)
384
+ )
385
+ ])
386
+ })
387
+ });
388
+
389
+ function toEpochMs(rawTs, fallbackMs = Date.now()) {
390
+ if (typeof rawTs === 'number' && Number.isFinite(rawTs)) {
391
+ return rawTs > 0 && rawTs < 1e12 ? rawTs * 1000 : rawTs;
392
+ }
393
+ if (rawTs instanceof Date) {
394
+ const ms = rawTs.getTime();
395
+ return Number.isFinite(ms) ? ms : fallbackMs;
396
+ }
397
+ if (typeof rawTs === 'string' && rawTs.trim()) {
398
+ const num = Number(rawTs.trim());
399
+ if (Number.isFinite(num) && /^\d+(?:\.\d+)?$/.test(rawTs.trim())) {
400
+ return num > 0 && num < 1e12 ? num * 1000 : num;
401
+ }
402
+ const ms = Date.parse(rawTs.trim());
403
+ if (Number.isFinite(ms)) return ms;
404
+ }
405
+ return fallbackMs;
406
+ }
407
+
408
+ function isWithinSchedule(tsMs, sched) {
409
+ if (sched.effectiveFromUtc) {
410
+ const fromMs = Date.parse(sched.effectiveFromUtc);
411
+ if (Number.isFinite(fromMs) && tsMs < fromMs) return false;
412
+ }
413
+ if (sched.effectiveUntilUtc) {
414
+ const untilStr = String(sched.effectiveUntilUtc).trim();
415
+ const untilMs = Date.parse(untilStr);
416
+ if (Number.isFinite(untilMs)) {
417
+ if (untilStr.endsWith('00:00:00Z')) {
418
+ if (tsMs >= untilMs) return false;
419
+ } else if (tsMs > untilMs + 999) {
420
+ return false;
421
+ }
422
+ }
423
+ }
424
+ return true;
425
+ }
426
+
427
+ function cleanModelString(raw = '') {
428
+ return String(raw ?? '')
429
+ .trim()
430
+ .toLowerCase()
431
+ .replace(/\[[12]m\]/gi, '')
432
+ .replace(/\s*\((?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking)(?:\s*[,/|]\s*(?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking))*\)\s*$/i, '')
433
+ .replace(/^(?:google|anthropic|openai|models)\//i, '')
434
+ .replace(/[()]+/g, ' ')
435
+ .replace(/\s+/g, '-')
436
+ .replace(/-+/g, '-')
437
+ .replace(/^-|-$/g, '')
438
+ .replace(/@\d{8}$/i, '')
439
+ .replace(/-\d{8}$/i, '')
440
+ .replace(/-\d{4}-\d{2}-\d{2}$/i, '')
441
+ .replace(/-tiered-(?:xhigh|extra-high|high|medium|med|low)$/i, '')
442
+ .replace(/-(?:thinking|fast|latest|xhigh|extra-high|high|medium|med|low)$/i, '');
443
+ }
444
+
445
+ const DIRECT_ALIASES = Object.freeze({
446
+ m427: 'gemini-4-carbon',
447
+ m437: 'gemini-4-carbon',
448
+ m438: 'gemini-4-carbon',
449
+ m670: 'gemini-4-carbon',
450
+ 'gemini-pro-orchestrator': 'gemini-4-carbon',
451
+ 'gemini-pro-orchestrator-carbon': 'gemini-4-carbon',
452
+ 'orchestrator-carbon': 'gemini-4-carbon',
453
+ 'gemini-pro-orchestrator-argon': 'gemini-4-argon',
454
+ 'orchestrator-argon': 'gemini-4-argon',
455
+ 'gemini-pro-orchestrator-neon': 'gemini-4-neon',
456
+ 'orchestrator-neon': 'gemini-4-neon',
457
+ 'gemini-pro-orchestrator-hydrogen': 'gemini-4-hydrogen',
458
+ 'orchestrator-hydrogen': 'gemini-4-hydrogen',
459
+ 'gemini-4-carbon-cyber-permissive': 'gemini-4-carbon',
460
+ 'gemini-3-8-flash': 'gemini-3.8-flash',
461
+ 'gemini-3.8-flash': 'gemini-3.8-flash',
462
+ 'gemini-3-1-pro': 'gemini-3.1-pro',
463
+ 'gemini-3.1-pro': 'gemini-3.1-pro',
464
+ 'gemini-2-5-pro': 'gemini-2.5-pro',
465
+ 'gemini-2.5-pro': 'gemini-2.5-pro',
466
+ 'claude-opus-5.5': 'claude-opus-5-5',
467
+ 'opus-5-5': 'claude-opus-5-5',
468
+ 'opus-5.5': 'claude-opus-5-5',
469
+ opus: 'claude-opus-5-5',
470
+ 'claude-sonnet-5.5': 'claude-sonnet-5-5',
471
+ 'sonnet-5-5': 'claude-sonnet-5-5',
472
+ 'sonnet-5.5': 'claude-sonnet-5-5',
473
+ sonnet: 'claude-sonnet-5-5',
474
+ 'claude-fable-5.1': 'claude-fable-5-1',
475
+ 'fable-5-1': 'claude-fable-5-1',
476
+ 'claude-fable-5.2': 'claude-fable-5-2',
477
+ 'fable-5-2': 'claude-fable-5-2',
478
+ 'claude-haiku-5.5': 'claude-haiku-5-5',
479
+ 'haiku-5-5': 'claude-haiku-5-5',
480
+ 'haiku-5.5': 'claude-haiku-5-5',
481
+ haiku: 'claude-haiku-5-5',
482
+ 'gpt-6-1-sol': 'gpt-6.1-sol',
483
+ 'gpt-6.1-sol': 'gpt-6.1-sol',
484
+ 'gpt-5-4': 'gpt-5.4',
485
+ 'gpt-5.4': 'gpt-5.4'
486
+ });
487
+
488
+ function detectFamilyFromText(cleanedText) {
489
+ if (!cleanedText) return null;
490
+ if (cleanedText.includes('neon')) return 'gemini-4-neon';
491
+ if (cleanedText.includes('carbon')) return 'gemini-4-carbon';
492
+ if (cleanedText.includes('argon')) return 'gemini-4-argon';
493
+ if (cleanedText.includes('hydrogen')) return 'gemini-4-hydrogen';
494
+ if (cleanedText.includes('3-8-flash') || cleanedText.includes('3.8-flash')) return 'gemini-3.8-flash';
495
+ if (cleanedText.includes('3-1-pro') || cleanedText.includes('3.1-pro')) return 'gemini-3.1-pro';
496
+ if (cleanedText.includes('2-5-pro') || cleanedText.includes('2.5-pro')) return 'gemini-2.5-pro';
497
+ if (cleanedText.includes('opus-5-5') || cleanedText.includes('opus-5.5')) return 'claude-opus-5-5';
498
+ if (cleanedText.includes('sonnet-5-5') || cleanedText.includes('sonnet-5.5')) return 'claude-sonnet-5-5';
499
+ if (cleanedText.includes('fable-5-2') || cleanedText.includes('fable-5.2')) return 'claude-fable-5-2';
500
+ if (cleanedText.includes('fable-5-1') || cleanedText.includes('fable-5.1')) return 'claude-fable-5-1';
501
+ if (cleanedText.includes('haiku-5-5') || cleanedText.includes('haiku-5.5')) return 'claude-haiku-5-5';
502
+ if (cleanedText.includes('opus-4-6') || cleanedText.includes('opus-4.6')) return 'claude-opus-4-6';
503
+ if (cleanedText.includes('sonnet-4-6') || cleanedText.includes('sonnet-4.6')) return 'claude-sonnet-4-6';
504
+ if (cleanedText.includes('haiku-4-5') || cleanedText.includes('haiku-4.5')) return 'claude-haiku-4-5';
505
+ if (cleanedText.includes('gpt-6-1-sol') || cleanedText.includes('gpt-6.1-sol')) return 'gpt-6.1-sol';
506
+ if (cleanedText.includes('gpt-5-4') || cleanedText.includes('gpt-5.4')) return 'gpt-5.4';
507
+ return null;
508
+ }
509
+
510
+ function resolveCanonicalModelId(model, label) {
511
+ const normModel = cleanModelString(model);
512
+ const normLabel = cleanModelString(label);
513
+
514
+ if (normModel === 'orchestrator') {
515
+ const labelMatch = detectFamilyFromText(normLabel);
516
+ return labelMatch || null;
517
+ }
518
+ if (normModel.startsWith('gemini-pro-orchestrator')) {
519
+ const labelMatch = detectFamilyFromText(normLabel);
520
+ if (labelMatch) return labelMatch;
521
+ if (DIRECT_ALIASES[normModel]) return DIRECT_ALIASES[normModel];
522
+ }
523
+
524
+ for (const candidate of [normModel, normLabel]) {
525
+ if (!candidate) continue;
526
+ if (RATE_CARD_MODELS[candidate]) return candidate;
527
+ if (DIRECT_ALIASES[candidate]) return DIRECT_ALIASES[candidate];
528
+ const dotVersion = candidate.replace(/^([a-z-]+-\d+)-(\d+)(-.+)?$/, (_, p, minor, rest) => `${p}.${minor}${rest || ''}`);
529
+ if (RATE_CARD_MODELS[dotVersion]) return dotVersion;
530
+ const altClaude = candidate.replace(/^claude-(\d+-\d+)-(opus|sonnet|haiku|fable)$/, 'claude-$2-$1');
531
+ if (RATE_CARD_MODELS[altClaude]) return altClaude;
532
+ const matched = detectFamilyFromText(candidate);
533
+ if (matched) return matched;
534
+ if (candidate === 'gemini-flash' || candidate.endsWith('-flash')) return 'gemini-3.8-flash';
535
+ }
536
+ return null;
537
+ }
538
+
539
+ /**
540
+ * Resolves the date-aware rate card entry for a call given `{ model, label, timestampMs, promptTokens, serviceTier }`.
541
+ */
542
+ export function resolveModelRateCard({
543
+ model = '',
544
+ label = '',
545
+ timestampMs = null,
546
+ promptTokens = 0,
547
+ serviceTier = 'standard'
548
+ } = {}) {
549
+ const rawModel = String(model || label || '').trim() || 'unknown';
550
+ const canonicalId = resolveCanonicalModelId(model, label);
551
+ const entry = canonicalId ? RATE_CARD_MODELS[canonicalId] : null;
552
+ const evalTsMs = toEpochMs(timestampMs, Date.now());
553
+ const prompt = Math.max(0, Number(promptTokens || 0));
554
+
555
+ if (!entry) {
556
+ return {
557
+ modelId: rawModel,
558
+ rawModel,
559
+ label: label ? String(label).trim() : null,
560
+ unmappedModel: true,
561
+ unmapped_model: true,
562
+ cachedReadWeight: DEFAULT_UNMAPPED_CACHED_WEIGHT,
563
+ inputPer1M: null,
564
+ cachedReadPer1M: null,
565
+ write5mPer1M: null,
566
+ write1hPer1M: null,
567
+ outputPer1M: null,
568
+ baseInputPer1M: null,
569
+ baseCachedReadPer1M: null,
570
+ baseWrite5mPer1M: null,
571
+ baseWrite1hPer1M: null,
572
+ baseOutputPer1M: null,
573
+ hasLongContextCliff: false,
574
+ cliffThresholdTokens: null,
575
+ inLongContextCliff: false,
576
+ cliffTriggered: false,
577
+ minCacheableTokens: 4096,
578
+ sharedPoolCeiling: null,
579
+ outputIncludesThinking: true,
580
+ scheduleId: 'unmapped',
581
+ upcomingChange: null
582
+ };
583
+ }
584
+
585
+ const tierKey = String(serviceTier || 'standard').toLowerCase().trim() === 'priority' ? 'priority' : 'standard';
586
+ const sched = entry.schedules.find((s) => isWithinSchedule(evalTsMs, s)) || entry.schedules[entry.schedules.length - 1];
587
+ const baseRates = sched[tierKey] || sched.standard;
588
+ const cliffActive = Boolean(entry.cliffThresholdTokens && prompt > entry.cliffThresholdTokens && sched.cliff);
589
+ const activeRates = cliffActive ? sched.cliff : baseRates;
590
+ const nextSchedIdx = entry.schedules.indexOf(sched) + 1;
591
+ const nextSched = nextSchedIdx > 0 && nextSchedIdx < entry.schedules.length ? entry.schedules[nextSchedIdx] : null;
592
+ const nextBase = nextSched ? (nextSched[tierKey] || nextSched.standard) : null;
593
+
594
+ const upcomingChange = nextSched && nextSched.effectiveFromUtc && nextBase
595
+ ? {
596
+ effectiveFromUtc: nextSched.effectiveFromUtc,
597
+ effectiveFromMs: Date.parse(nextSched.effectiveFromUtc),
598
+ multiplier: baseRates.inputPer1M > 0 ? Number((nextBase.inputPer1M / baseRates.inputPer1M).toFixed(4)) : null,
599
+ nextRates: nextBase
600
+ }
601
+ : null;
602
+
603
+ return {
604
+ modelId: entry.modelId,
605
+ rawModel,
606
+ label: entry.label,
607
+ unmappedModel: false,
608
+ unmapped_model: false,
609
+ cachedReadWeight: entry.cachedReadWeight,
610
+ inputPer1M: activeRates.inputPer1M,
611
+ cachedReadPer1M: activeRates.cachedReadPer1M,
612
+ write5mPer1M: activeRates.write5mPer1M,
613
+ write1hPer1M: activeRates.write1hPer1M,
614
+ outputPer1M: activeRates.outputPer1M,
615
+ baseInputPer1M: baseRates.inputPer1M,
616
+ baseCachedReadPer1M: baseRates.cachedReadPer1M,
617
+ baseWrite5mPer1M: baseRates.write5mPer1M,
618
+ baseWrite1hPer1M: baseRates.write1hPer1M,
619
+ baseOutputPer1M: baseRates.outputPer1M,
620
+ hasLongContextCliff: Boolean(entry.cliffThresholdTokens),
621
+ cliffThresholdTokens: entry.cliffThresholdTokens,
622
+ inLongContextCliff: cliffActive,
623
+ cliffTriggered: cliffActive,
624
+ minCacheableTokens: entry.minCacheableTokens,
625
+ sharedPoolCeiling: entry.sharedPoolCeiling,
626
+ outputIncludesThinking: entry.outputIncludesThinking,
627
+ scheduleId: sched.id,
628
+ upcomingChange
629
+ };
630
+ }
631
+
632
+ function readNum(obj, keys, fallback = 0) {
633
+ for (const k of keys) {
634
+ if (obj[k] !== undefined && obj[k] !== null) {
635
+ const n = Number(obj[k]);
636
+ if (Number.isFinite(n)) return Math.max(0, n);
637
+ }
638
+ }
639
+ return fallback;
640
+ }
641
+
642
+ /**
643
+ * Infers effort tier (`low`, `medium`, `high`, `xhigh`) from explicit effort fields, label, or model slug.
644
+ */
645
+ export function inferEffortTier({ effort = '', thinkingEffort = '', label = '', model = '' } = {}) {
646
+ const explicit = String(effort || thinkingEffort || '').trim().toLowerCase();
647
+ const haystack = explicit || `${String(label || '')} ${String(model || '')}`.toLowerCase();
648
+ if (/(?:^|[^a-z])(xhigh|extra)(?:$|[^a-z])/.test(haystack)) return 'xhigh';
649
+ if (/(?:^|[^a-z])high(?:$|[^a-z])/.test(haystack)) return 'high';
650
+ if (/(?:^|[^a-z])low(?:$|[^a-z])/.test(haystack)) return 'low';
651
+ if (/(?:^|[^a-z])(med|medium)(?:$|[^a-z])/.test(haystack)) return 'medium';
652
+ return 'medium';
653
+ }
654
+
655
+ /**
656
+ * Resolves subscription 5h/weekly quota multiplier weights per API dollar alongside catalog effort multipliers
657
+ * and headless/custom-agent invocation adjustments.
658
+ */
659
+ export function resolveSubscriptionQuotaWeight({
660
+ model = '',
661
+ label = '',
662
+ effort = '',
663
+ thinkingEffort = '',
664
+ entrypoint = null,
665
+ acpCustomAgent = false,
666
+ clientVersion = null
667
+ } = {}) {
668
+ const canonicalId = resolveCanonicalModelId(model, label) || String(model || label || 'unknown').trim() || 'unknown';
669
+ const effortTier = inferEffortTier({ effort, thinkingEffort, label, model });
670
+ const subscriptionQuotaWeightPerUsd =
671
+ canonicalId === 'gemini-4-carbon' || canonicalId === 'gemini-4-argon'
672
+ ? SUBSCRIPTION_QUOTA_CONSTANTS.ARGON_CARBON_PER_USD_WEIGHT
673
+ : SUBSCRIPTION_QUOTA_CONSTANTS.HYDROGEN_BASELINE_PER_USD_WEIGHT;
674
+
675
+ const catalogRow = CATALOG_QUOTA_MULTIPLIERS[canonicalId];
676
+ const catalogEffortMultiplier = catalogRow
677
+ ? Number(catalogRow[effortTier] ?? catalogRow.medium ?? 1.0)
678
+ : 1.0;
679
+
680
+ let invocationMultiplier = 1.0;
681
+ const invocationTags = [];
682
+ let isHeuristic = false;
683
+
684
+ const trimmedVer = clientVersion ? String(clientVersion).trim() : '';
685
+ const acpVersionAffected =
686
+ !trimmedVer || trimmedVer === SUBSCRIPTION_QUOTA_CONSTANTS.ACP_CUSTOM_AGENT_AFFECTED_VERSION || trimmedVer.startsWith(SUBSCRIPTION_QUOTA_CONSTANTS.ACP_CUSTOM_AGENT_AFFECTED_VERSION);
687
+ if (acpCustomAgent === true && acpVersionAffected) {
688
+ invocationMultiplier *= SUBSCRIPTION_QUOTA_CONSTANTS.ACP_CUSTOM_AGENT_MULTIPLIER;
689
+ invocationTags.push('acp_custom_agent_4x');
690
+ }
691
+
692
+ if (String(entrypoint || '').trim().toLowerCase() === 'sdk-cli') {
693
+ invocationMultiplier *= SUBSCRIPTION_QUOTA_CONSTANTS.SDK_CLI_HEADLESS_MULTIPLIER;
694
+ invocationTags.push('sdk_cli_1.8x_heuristic');
695
+ isHeuristic = true;
696
+ }
697
+
698
+ const combinedQuotaMultiplier = Number((subscriptionQuotaWeightPerUsd * invocationMultiplier).toFixed(4));
699
+ return {
700
+ modelId: canonicalId,
701
+ effort: effortTier,
702
+ subscriptionQuotaWeightPerUsd,
703
+ catalogEffortMultiplier,
704
+ invocationMultiplier: Number(invocationMultiplier.toFixed(4)),
705
+ combinedQuotaMultiplier,
706
+ invocationTags,
707
+ isHeuristic
708
+ };
709
+ }
710
+
711
+ /**
712
+ * Computes uncached-equivalent input units, estimated USD, and normalized quota burn for a single model call.
713
+ */
714
+ export function valuateCall(call = {}) {
715
+ const uncachedTokens = readNum(call, ['uncachedTokens', 'uncached', 'uncachedInputTokens', 'freshInputTokens', 'inputTokens', 'input_tokens']);
716
+ const cachedTokens = readNum(call, ['cachedTokens', 'cacheRead', 'cacheReadTokens', 'cacheReadInputTokens', 'cache_read_input_tokens']);
717
+ const write5mTokens = readNum(call, ['cacheWrite5mTokens', 'write5mTokens', 'cache_write_5m_tokens']);
718
+ const write1hTokens = readNum(call, ['cacheWrite1hTokens', 'write1hTokens', 'cache_write_1h_tokens']);
719
+ const genericWrite = readNum(call, ['cacheCreationTokens', 'cacheCreationInputTokens', 'cache_creation_input_tokens']);
720
+ const remainingWrite = Math.max(0, genericWrite - (write5mTokens + write1hTokens));
721
+ const effWrite5m = write5mTokens + (call.cacheTtlTier === '1h' ? 0 : remainingWrite);
722
+ const effWrite1h = write1hTokens + (call.cacheTtlTier === '1h' ? remainingWrite : 0);
723
+ const rawOutputTokens = readNum(call, ['outputTokens', 'output', 'output_tokens']);
724
+ const thinkingTokens = readNum(call, ['thinkingTokens', 'thinking_tokens']);
725
+ const promptTokens = Math.max(
726
+ readNum(call, ['promptTokens', 'totalPromptTokens']),
727
+ uncachedTokens + cachedTokens + effWrite5m + effWrite1h
728
+ );
729
+ const tsRaw = call.timestampMs ?? call.timestampSec ?? call.start ?? call.createdAt ?? call.t ?? null;
730
+ const timestampMs = tsRaw !== null && tsRaw !== undefined ? toEpochMs(tsRaw, Date.now()) : Date.now();
731
+
732
+ const card = resolveModelRateCard({
733
+ model: call.model || call.modelId || call.rawModel || '',
734
+ label: call.label || '',
735
+ timestampMs,
736
+ promptTokens,
737
+ serviceTier: call.serviceTier || call.service_tier || 'standard'
738
+ });
739
+
740
+ const includesThinking =
741
+ call.outputIncludesThinking !== undefined
742
+ ? Boolean(call.outputIncludesThinking)
743
+ : card.outputIncludesThinking !== false;
744
+ const outputTokens = includesThinking ? rawOutputTokens : rawOutputTokens + thinkingTokens;
745
+
746
+ const quotaWeight = resolveSubscriptionQuotaWeight({
747
+ model: call.model || call.modelId || call.rawModel || '',
748
+ label: call.label || '',
749
+ effort: call.effort || '',
750
+ thinkingEffort: call.thinkingEffort || '',
751
+ entrypoint: call.entrypoint || null,
752
+ acpCustomAgent: Boolean(call.acpCustomAgent || call.acpAgent),
753
+ clientVersion: call.clientVersion || null
754
+ });
755
+
756
+ const baseUncachedUnits = uncachedTokens;
757
+ const cachedEquivalentUnits = cachedTokens * card.cachedReadWeight;
758
+ const writeSurchargeUnits = card.unmappedModel || !card.inputPer1M
759
+ ? effWrite5m * 0.25 + effWrite1h * 1.0
760
+ : effWrite5m * Math.max(0, (card.write5mPer1M / card.inputPer1M) - 1) +
761
+ effWrite1h * Math.max(0, (card.write1hPer1M / card.inputPer1M) - 1);
762
+ const uncachedEquivalentInputUnits = baseUncachedUnits + cachedEquivalentUnits + writeSurchargeUnits;
763
+ const catalogWeightedUnits = Number(
764
+ ((uncachedEquivalentInputUnits / 1_000_000) * quotaWeight.catalogEffortMultiplier * quotaWeight.invocationMultiplier).toFixed(6)
765
+ );
766
+
767
+ if (card.unmappedModel || card.inputPer1M === null) {
768
+ return {
769
+ card,
770
+ timestampMs,
771
+ uncachedTokens,
772
+ cachedTokens,
773
+ write5mTokens: effWrite5m,
774
+ write1hTokens: effWrite1h,
775
+ outputTokens,
776
+ thinkingTokens,
777
+ outputIncludesThinking: includesThinking,
778
+ promptTokens,
779
+ uncachedEquivalentInputUnits,
780
+ cachedEquivalentUnits,
781
+ inputUncachedUsd: null,
782
+ inputCachedReadUsd: null,
783
+ cacheWriteSurchargeUsd: null,
784
+ outputUsd: null,
785
+ totalEstimatedUsd: null,
786
+ cliffSurchargeUsd: 0,
787
+ quotaWeight,
788
+ normalizedQuotaBurnUnits: null,
789
+ catalogWeightedUnits
790
+ };
791
+ }
792
+
793
+ const inputUncachedUsd = (uncachedTokens / 1_000_000) * card.inputPer1M;
794
+ const inputCachedReadUsd = (cachedTokens / 1_000_000) * card.cachedReadPer1M;
795
+ const cacheWriteSurchargeUsd =
796
+ (effWrite5m / 1_000_000) * Math.max(0, card.write5mPer1M - card.inputPer1M) +
797
+ (effWrite1h / 1_000_000) * Math.max(0, card.write1hPer1M - card.inputPer1M) +
798
+ ((effWrite5m + effWrite1h) / 1_000_000) * card.inputPer1M;
799
+ const outputUsd = (outputTokens / 1_000_000) * card.outputPer1M;
800
+ const totalEstimatedUsd = inputUncachedUsd + inputCachedReadUsd + cacheWriteSurchargeUsd + outputUsd;
801
+ const normalizedQuotaBurnUnits = Number((totalEstimatedUsd * quotaWeight.combinedQuotaMultiplier).toFixed(6));
802
+
803
+ let cliffSurchargeUsd = 0;
804
+ if (card.inLongContextCliff) {
805
+ const baseTotal =
806
+ (uncachedTokens / 1_000_000) * card.baseInputPer1M +
807
+ (cachedTokens / 1_000_000) * card.baseCachedReadPer1M +
808
+ (effWrite5m / 1_000_000) * card.baseWrite5mPer1M +
809
+ (effWrite1h / 1_000_000) * card.baseWrite1hPer1M +
810
+ (outputTokens / 1_000_000) * card.baseOutputPer1M;
811
+ cliffSurchargeUsd = Math.max(0, totalEstimatedUsd - baseTotal);
812
+ }
813
+
814
+ return {
815
+ card,
816
+ timestampMs,
817
+ uncachedTokens,
818
+ cachedTokens,
819
+ write5mTokens: effWrite5m,
820
+ write1hTokens: effWrite1h,
821
+ outputTokens,
822
+ thinkingTokens,
823
+ outputIncludesThinking: includesThinking,
824
+ promptTokens,
825
+ uncachedEquivalentInputUnits,
826
+ cachedEquivalentUnits,
827
+ inputUncachedUsd,
828
+ inputCachedReadUsd,
829
+ cacheWriteSurchargeUsd,
830
+ outputUsd,
831
+ totalEstimatedUsd,
832
+ cliffSurchargeUsd,
833
+ quotaWeight,
834
+ normalizedQuotaBurnUnits,
835
+ catalogWeightedUnits
836
+ };
837
+ }
838
+
839
+ /**
840
+ * Aggregates valuation, model breakdown, quota-weighted burn, unmapped counts, and upcoming 14-day rate step-up alerts across a batch of calls.
841
+ */
842
+ export function valuateBatch(calls = [], { nowMs = Date.now(), days = 7, entrypoint = null, acpCustomAgent = false, clientVersion = null } = {}) {
843
+ const byModelMap = new Map();
844
+ const unmappedModels = new Set();
845
+ const futureDeltaMap = new Map();
846
+ const windowDays = Math.max(1, Number(days || 7));
847
+
848
+ let inputUncachedUsd = 0;
849
+ let inputCachedReadUsd = 0;
850
+ let cacheWriteSurchargeUsd = 0;
851
+ let outputUsd = 0;
852
+ let uncachedEquivalentInputUnits = 0;
853
+ let cachedEquivalentInputUnits = 0;
854
+ let unmappedModelCalls = 0;
855
+ let totalNormalizedQuotaBurnUnitsRaw = 0;
856
+ let totalCatalogWeightedUnits = 0;
857
+ let sdkCliCalls = 0;
858
+ let acpCustomAgentCalls = 0;
859
+
860
+ for (const rawCall of calls) {
861
+ const hydratedCall = rawCall && typeof rawCall === 'object'
862
+ ? {
863
+ ...rawCall,
864
+ ...(rawCall.entrypoint === undefined && entrypoint !== null ? { entrypoint } : {}),
865
+ ...(rawCall.acpCustomAgent === undefined && rawCall.acpAgent === undefined && acpCustomAgent ? { acpCustomAgent: true } : {}),
866
+ ...(rawCall.clientVersion === undefined && clientVersion !== null ? { clientVersion } : {})
867
+ }
868
+ : {};
869
+ const val = valuateCall(hydratedCall);
870
+ const { card, quotaWeight } = val;
871
+ uncachedEquivalentInputUnits += val.uncachedEquivalentInputUnits;
872
+ cachedEquivalentInputUnits += val.cachedEquivalentUnits;
873
+ totalCatalogWeightedUnits += val.catalogWeightedUnits || 0;
874
+ if (quotaWeight.invocationTags.includes('sdk_cli_1.8x_heuristic')) sdkCliCalls += 1;
875
+ if (quotaWeight.invocationTags.includes('acp_custom_agent_4x')) acpCustomAgentCalls += 1;
876
+
877
+ if (card.unmappedModel) {
878
+ unmappedModelCalls += 1;
879
+ unmappedModels.add(card.rawModel);
880
+ } else {
881
+ inputUncachedUsd += val.inputUncachedUsd;
882
+ inputCachedReadUsd += val.inputCachedReadUsd;
883
+ cacheWriteSurchargeUsd += val.cacheWriteSurchargeUsd;
884
+ outputUsd += val.outputUsd;
885
+ if (val.normalizedQuotaBurnUnits !== null) {
886
+ totalNormalizedQuotaBurnUnitsRaw += val.normalizedQuotaBurnUnits;
887
+ }
888
+ }
889
+
890
+ const row = byModelMap.get(card.modelId) || {
891
+ modelId: card.modelId,
892
+ rawModels: new Set(),
893
+ calls: 0,
894
+ cachedReadWeight: card.cachedReadWeight,
895
+ subscriptionQuotaWeightPerUsd: quotaWeight.subscriptionQuotaWeightPerUsd,
896
+ catalogEffortMultiplier: quotaWeight.catalogEffortMultiplier,
897
+ uncachedTokens: 0,
898
+ cachedTokens: 0,
899
+ outputTokens: 0,
900
+ estimatedUsd: card.unmappedModel ? null : 0,
901
+ normalizedQuotaBurnUnits: card.unmappedModel ? null : 0,
902
+ unmappedModel: card.unmappedModel,
903
+ hasLongContextCliff: card.hasLongContextCliff
904
+ };
905
+ if (card.rawModel) row.rawModels.add(card.rawModel);
906
+ row.calls += 1;
907
+ row.uncachedTokens += val.uncachedTokens;
908
+ row.cachedTokens += val.cachedTokens;
909
+ row.outputTokens += val.outputTokens;
910
+ if (!card.unmappedModel && row.estimatedUsd !== null && val.totalEstimatedUsd !== null) {
911
+ row.estimatedUsd += val.totalEstimatedUsd;
912
+ if (row.normalizedQuotaBurnUnits !== null && val.normalizedQuotaBurnUnits !== null) {
913
+ row.normalizedQuotaBurnUnits += val.normalizedQuotaBurnUnits;
914
+ }
915
+ }
916
+ byModelMap.set(card.modelId, row);
917
+
918
+ if (
919
+ !card.unmappedModel &&
920
+ card.upcomingChange &&
921
+ Number.isFinite(card.upcomingChange.effectiveFromMs) &&
922
+ card.upcomingChange.effectiveFromMs > nowMs &&
923
+ card.upcomingChange.effectiveFromMs - nowMs <= UPCOMING_NOTICE_WINDOW_MS
924
+ ) {
925
+ const next = card.upcomingChange.nextRates;
926
+ const postTotal =
927
+ (val.uncachedTokens / 1_000_000) * next.inputPer1M +
928
+ (val.cachedTokens / 1_000_000) * next.cachedReadPer1M +
929
+ (val.outputTokens / 1_000_000) * next.outputPer1M;
930
+ const deltaUsd = Math.max(0, postTotal - (val.totalEstimatedUsd || 0));
931
+ const key = `${card.modelId}|${card.upcomingChange.effectiveFromUtc}`;
932
+ const agg = futureDeltaMap.get(key) || {
933
+ modelId: card.modelId,
934
+ effectiveFromUtc: card.upcomingChange.effectiveFromUtc,
935
+ multiplier: card.upcomingChange.multiplier,
936
+ rawDeltaUsd: 0
937
+ };
938
+ agg.rawDeltaUsd += deltaUsd;
939
+ futureDeltaMap.set(key, agg);
940
+ }
941
+ }
942
+
943
+ const totalEstimatedUsd = Number((inputUncachedUsd + inputCachedReadUsd + cacheWriteSurchargeUsd + outputUsd).toFixed(2));
944
+ const cachedShareOfInputSpendPct = uncachedEquivalentInputUnits > 0
945
+ ? Number(((cachedEquivalentInputUnits / uncachedEquivalentInputUnits) * 100).toFixed(1))
946
+ : 0;
947
+ const uncachedShareOfInputSpendPct = uncachedEquivalentInputUnits > 0
948
+ ? Number((100 - cachedShareOfInputSpendPct).toFixed(1))
949
+ : 0;
950
+
951
+ const byModel = [...byModelMap.values()]
952
+ .map((m) => ({
953
+ ...m,
954
+ rawModels: [...m.rawModels].sort(),
955
+ estimatedUsd: m.estimatedUsd === null ? null : Number(m.estimatedUsd.toFixed(2)),
956
+ normalizedQuotaBurnUnits: m.normalizedQuotaBurnUnits === null ? null : Number(m.normalizedQuotaBurnUnits.toFixed(2))
957
+ }))
958
+ .sort((a, b) => (b.estimatedUsd ?? -1) - (a.estimatedUsd ?? -1) || b.calls - a.calls);
959
+
960
+ const upcomingRateChanges = [...futureDeltaMap.values()]
961
+ .filter((u) => u.rawDeltaUsd > 0)
962
+ .map((u) => ({
963
+ modelId: u.modelId,
964
+ effectiveFromUtc: u.effectiveFromUtc,
965
+ multiplier: u.multiplier,
966
+ projectedWeeklyDeltaUsd: Number(((u.rawDeltaUsd / windowDays) * 7).toFixed(2))
967
+ }))
968
+ .sort((a, b) => b.projectedWeeklyDeltaUsd - a.projectedWeeklyDeltaUsd);
969
+
970
+ const totalNormalizedQuotaBurnUnits = Number(totalNormalizedQuotaBurnUnitsRaw.toFixed(2));
971
+ const effectiveQuotaMultiplier = totalEstimatedUsd > 0
972
+ ? Number((totalNormalizedQuotaBurnUnitsRaw / totalEstimatedUsd).toFixed(2))
973
+ : 1;
974
+ const elevatedModels = byModel
975
+ .filter((m) => (m.subscriptionQuotaWeightPerUsd || 1) > 1)
976
+ .map((m) => m.modelId);
977
+ const noteParts = [];
978
+ if (elevatedModels.length > 0) {
979
+ noteParts.push(`${elevatedModels.join(', ')} draw 3.0x shared 5h/weekly quota per API dollar vs Hydrogen 1.0x (#196351)`);
980
+ }
981
+ if (sdkCliCalls > 0) {
982
+ noteParts.push(`headless sdk-cli (${sdkCliCalls} calls) applies ~1.8x 5h quota burn heuristic (#97074)`);
983
+ }
984
+ if (acpCustomAgentCalls > 0) {
985
+ noteParts.push(`custom ACP --agent (${acpCustomAgentCalls} calls) applies 4.0x quota weight (#1890)`);
986
+ }
987
+
988
+ return {
989
+ currency: 'USD',
990
+ rateCardVersion: RATE_CARD_VERSION,
991
+ totalEstimatedUsd,
992
+ totalNormalizedQuotaBurnUnits,
993
+ effectiveQuotaMultiplier,
994
+ totalCatalogWeightedUnits: Number(totalCatalogWeightedUnits.toFixed(4)),
995
+ inputUncachedUsd: Number(inputUncachedUsd.toFixed(2)),
996
+ inputCachedReadUsd: Number(inputCachedReadUsd.toFixed(2)),
997
+ cacheWriteSurchargeUsd: Number(cacheWriteSurchargeUsd.toFixed(2)),
998
+ outputUsd: Number(outputUsd.toFixed(2)),
999
+ uncachedEquivalentInputUnits: Math.round(uncachedEquivalentInputUnits),
1000
+ cachedEquivalentInputUnits: Math.round(cachedEquivalentInputUnits),
1001
+ cachedShareOfInputSpendPct,
1002
+ uncachedShareOfInputSpendPct,
1003
+ unmappedModelCalls,
1004
+ unmappedModels: [...unmappedModels].sort(),
1005
+ upcomingRateChanges,
1006
+ quotaBurnSummary: {
1007
+ unit: 'quota-usd-equiv',
1008
+ totalNormalizedQuotaBurnUnits,
1009
+ effectiveQuotaMultiplier,
1010
+ hasElevatedMultiplier: elevatedModels.length > 0 || sdkCliCalls > 0 || acpCustomAgentCalls > 0,
1011
+ elevatedModels,
1012
+ sdkCliCalls,
1013
+ sdkCliHeuristicApplied: sdkCliCalls > 0,
1014
+ acpCustomAgentCalls,
1015
+ acpCustomAgentApplied: acpCustomAgentCalls > 0,
1016
+ coachingNote: noteParts.length > 0 ? noteParts.join('; ') : null
1017
+ },
1018
+ byModel
1019
+ };
1020
+ }
1021
+
1022
+ export default {
1023
+ RATE_CARD_VERSION,
1024
+ DEFAULT_UNMAPPED_CACHED_WEIGHT,
1025
+ SUBSCRIPTION_QUOTA_CONSTANTS,
1026
+ CATALOG_QUOTA_MULTIPLIERS,
1027
+ RATE_CARD_MODELS,
1028
+ inferEffortTier,
1029
+ resolveSubscriptionQuotaWeight,
1030
+ resolveModelRateCard,
1031
+ valuateCall,
1032
+ valuateBatch
1033
+ };