@jeffusion/bungee-core 6.16.1 → 6.17.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 (37) hide show
  1. package/dist/main.js +5700 -2198
  2. package/dist/observability-worker.js +3245 -1495
  3. package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
  4. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
  5. package/dist/plugins/chatgpt-oauth/index.js +37 -15
  6. package/dist/plugins/chatgpt-oauth/index.js.map +5 -5
  7. package/dist/plugins/codex-router/index.js +21 -3
  8. package/dist/plugins/codex-router/index.js.map +5 -5
  9. package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
  10. package/dist/plugins/key-access/index.js +1 -1
  11. package/dist/plugins/key-access/index.js.map +4 -4
  12. package/dist/plugins/key-access/ingress.js +1 -1
  13. package/dist/plugins/key-access/ingress.js.map +3 -3
  14. package/dist/plugins/key-rate-limit/index.js.map +2 -2
  15. package/dist/plugins/llm-protocol-adapter/control.js +1 -1
  16. package/dist/plugins/llm-protocol-adapter/control.js.map +3 -3
  17. package/dist/plugins/llm-protocol-adapter/index.js +1 -1
  18. package/dist/plugins/llm-protocol-adapter/index.js.map +5 -5
  19. package/dist/plugins/llm-tps/index.js.map +2 -2
  20. package/dist/plugins/model-mapping/index.js +1 -1
  21. package/dist/plugins/model-mapping/index.js.map +4 -4
  22. package/dist/plugins/models-dev/index.js.map +2 -2
  23. package/dist/plugins/request-logs/index.js +505 -118
  24. package/dist/plugins/request-logs/index.js.map +11 -10
  25. package/dist/plugins/request-logs/ingress.js +3 -23
  26. package/dist/plugins/request-logs/ingress.js.map +3 -3
  27. package/dist/plugins/request-logs/ui/RequestLogsPage.svelte +215 -130
  28. package/dist/plugins/signature-repair/index.js.map +2 -2
  29. package/dist/plugins/token-budget/index.js.map +2 -2
  30. package/dist/plugins/token-metering/index.js.map +2 -2
  31. package/dist/plugins/token-stats/control.js +257 -61
  32. package/dist/plugins/token-stats/control.js.map +7 -6
  33. package/dist/plugins/token-stats/index.js +271 -127
  34. package/dist/plugins/token-stats/index.js.map +8 -8
  35. package/dist/plugins/token-stats/manifest.json +2 -2
  36. package/dist/plugins/user-auth/index.js.map +2 -2
  37. package/package.json +3 -2
@@ -187,6 +187,78 @@ function tokenStatsWindow(range, asOfMs, timeZone = "UTC") {
187
187
  const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));
188
188
  return { startMs: bucketStarts[0], endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };
189
189
  }
190
+ // plugins/token-stats/server/pricing.ts
191
+ var TOKENS_PER_UNIT = 1e6;
192
+ function isNonNegativeInteger(value) {
193
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
194
+ }
195
+ function costOf(match, input) {
196
+ const inputTokens = input.inputTokens;
197
+ const outputTokens = input.outputTokens;
198
+ if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens))
199
+ return null;
200
+ const cacheReads = input.cacheReadTokens ?? 0;
201
+ const cacheWrites = input.cacheWriteTokens ?? 0;
202
+ if (!isNonNegativeInteger(cacheReads) || !isNonNegativeInteger(cacheWrites) || cacheReads + cacheWrites > inputTokens)
203
+ return null;
204
+ let rates = match;
205
+ for (const tier of match.contextTiers ?? []) {
206
+ if (inputTokens < tier.minimumInputTokens)
207
+ break;
208
+ rates = tier;
209
+ }
210
+ const cacheRead = rates.cacheRead ?? match.cacheRead ?? rates.input;
211
+ const cacheWrite = rates.cacheWrite ?? match.cacheWrite ?? rates.input;
212
+ const baseInput = inputTokens - cacheReads - cacheWrites;
213
+ const total = baseInput * rates.input + outputTokens * rates.output + cacheReads * cacheRead + cacheWrites * cacheWrite;
214
+ const cost = total / TOKENS_PER_UNIT;
215
+ return Number.isFinite(cost) && cost >= 0 ? cost : null;
216
+ }
217
+ function costNanoUsdOf(cost) {
218
+ if (cost === null || !Number.isFinite(cost) || cost < 0)
219
+ return null;
220
+ const nano = Math.round(cost * 1e9);
221
+ return Number.isSafeInteger(nano) ? nano : null;
222
+ }
223
+ function calculateTokenStatsCost(catalog, input, mappings = []) {
224
+ if (catalog === null || typeof input.model !== "string" || input.model.length === 0)
225
+ return null;
226
+ const mapping = mappings.find((item) => item.source === input.model);
227
+ if (mapping !== undefined) {
228
+ const target = catalog.resolveModel({ model: mapping.model, pricingProvider: mapping.provider });
229
+ return target === null ? null : costOf(target, input);
230
+ }
231
+ const match = catalog.resolveModel({
232
+ model: input.model,
233
+ mode: "estimate",
234
+ ...input.provider === undefined ? {} : { pricingProvider: input.provider },
235
+ ...input.url === undefined ? {} : { url: input.url }
236
+ });
237
+ return match === null ? null : costOf(match, input);
238
+ }
239
+
240
+ class TokenStatsPricing {
241
+ catalog;
242
+ mappings = [];
243
+ constructor(catalog) {
244
+ this.catalog = catalog;
245
+ }
246
+ setMappings(mappings) {
247
+ this.mappings = mappings;
248
+ }
249
+ hasMappings() {
250
+ return this.mappings !== undefined;
251
+ }
252
+ estimate(input) {
253
+ if (this.mappings === undefined)
254
+ return null;
255
+ return calculateTokenStatsCost(this.catalog, input, this.mappings);
256
+ }
257
+ ready() {
258
+ return Promise.resolve();
259
+ }
260
+ }
261
+
190
262
  // plugins/token-stats/server/storage.ts
191
263
  var TOKEN_STATS_METRICS = [
192
264
  "inputTokens",
@@ -215,47 +287,122 @@ var TOKEN_STATS_METRICS = [
215
287
  var TOKEN_STATS_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
216
288
  var TOKEN_STATS_BUSY_TIMEOUT_MS = 5;
217
289
  var EMPTY_METRICS = Object.fromEntries(TOKEN_STATS_METRICS.map((name) => [name, 0]));
290
+ var PRICEABLE_USAGE = `cost_usd IS NULL AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL AND model <> 'unknown'`;
218
291
 
219
292
  class SQLiteTokenStatsMetering {
220
293
  observation;
221
294
  constructor(observation) {
222
295
  this.observation = observation;
223
296
  }
224
- async recordAttempt(row) {
225
- return this.observation.withDatabase((db) => {
226
- validateTokenStatsAttempt(row);
227
- const transaction = db.transaction(() => {
228
- db.query(`
229
- INSERT OR IGNORE INTO token_stats_attempts (
230
- attempt_id, request_id, finished_at_ms, route_id, upstream_id, provider, outcome, model, key_id,
231
- input_tokens, output_tokens, input_source, output_source,
232
- cache_read_tokens, cache_write_tokens, cost_usd, observation_incomplete
233
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
234
- `).run(row.attempt_id, row.request_id, row.finished_at_ms, row.route_id, row.upstream_id, row.provider, row.outcome, row.model, row.key_id ?? null, row.input_tokens, row.output_tokens, row.input_source, row.output_source, row.cache_read_tokens, row.cache_write_tokens, row.cost_usd, row.observation_incomplete ? 1 : 0);
235
- db.query(`
236
- DELETE FROM token_stats_attempts WHERE attempt_id IN (
237
- SELECT attempt_id FROM token_stats_attempts INDEXED BY idx_token_stats_attempts_finished
238
- WHERE finished_at_ms < ? ORDER BY finished_at_ms LIMIT 500
239
- )
240
- `).run(Date.now() - TOKEN_STATS_RETENTION_MS);
297
+ async recordAttempt(row, deadlineAt) {
298
+ row = { ...row };
299
+ let remainingMs;
300
+ if (deadlineAt === undefined) {
301
+ const directDeadline = performance.now() + 50;
302
+ remainingMs = () => directDeadline - performance.now();
303
+ } else {
304
+ if (!Number.isSafeInteger(deadlineAt))
305
+ throw new Error("invalid token-stats write deadline");
306
+ const budget = this.observation.writeBudgetMs?.(deadlineAt);
307
+ if (!budget)
308
+ throw new Error("token-stats write deadline clock unavailable");
309
+ remainingMs = budget;
310
+ }
311
+ const requireWriteBudget = () => {
312
+ if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
313
+ throw new Error("token-stats write deadline expired");
314
+ };
315
+ requireWriteBudget();
316
+ const maxAttempts = deadlineAt === undefined ? 8 : Infinity;
317
+ for (let attempt = 1;; attempt++) {
318
+ const busy = await this.observation.withDatabase((db) => {
319
+ validateTokenStatsAttempt(row);
320
+ const transaction = db.transaction(() => {
321
+ if (deadlineAt !== undefined)
322
+ requireWriteBudget();
323
+ db.query(`
324
+ INSERT OR IGNORE INTO token_stats_attempts (
325
+ attempt_id, request_id, finished_at_ms, route_id, upstream_id, provider, outcome, model, key_id,
326
+ input_tokens, output_tokens, input_source, output_source,
327
+ cache_read_tokens, cache_write_tokens, cost_usd, observation_incomplete
328
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
329
+ `).run(row.attempt_id, row.request_id, row.finished_at_ms, row.route_id, row.upstream_id, row.provider, row.outcome, row.model, row.key_id ?? null, row.input_tokens, row.output_tokens, row.input_source, row.output_source, row.cache_read_tokens, row.cache_write_tokens, row.cost_usd, row.observation_incomplete ? 1 : 0);
330
+ db.query(`
331
+ DELETE FROM token_stats_attempts WHERE attempt_id IN (
332
+ SELECT attempt_id FROM token_stats_attempts INDEXED BY idx_token_stats_attempts_finished
333
+ WHERE finished_at_ms < ? ORDER BY finished_at_ms LIMIT 500
334
+ )
335
+ `).run(Date.now() - TOKEN_STATS_RETENTION_MS);
336
+ if (deadlineAt !== undefined)
337
+ requireWriteBudget();
338
+ });
339
+ return withReportingWriteTimeout(db, () => {
340
+ try {
341
+ transaction.immediate();
342
+ } catch (error) {
343
+ if (error instanceof Error && error.name === "SQLiteError" && "code" in error && error.code === "SQLITE_BUSY" && db.inTransaction === false)
344
+ return error;
345
+ throw error;
346
+ }
347
+ });
241
348
  });
242
- withReportingWriteTimeout(db, () => transaction.immediate());
243
- });
349
+ if (!busy)
350
+ return;
351
+ if (attempt === maxAttempts || remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
352
+ throw busy;
353
+ await new Promise((resolve) => setTimeout(resolve, 0));
354
+ if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS)
355
+ throw busy;
356
+ }
357
+ }
358
+ async queryPricingModels(input) {
359
+ const window = queryBounds(input);
360
+ return this.observation.withDatabase((db) => db.transaction(() => {
361
+ const { throughRow } = db.query("SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts").get();
362
+ const { index, where, params } = attemptWindow({ ...window, throughRow });
363
+ const rows = db.query(`
364
+ SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}
365
+ WHERE ${where} AND ${PRICEABLE_USAGE}
366
+ `).all(...params);
367
+ return { models: rows.map((row) => row.model), throughRow };
368
+ }).deferred());
244
369
  }
245
370
  async queryWindowSnapshot(input) {
371
+ const window = queryBounds(input);
372
+ const { bucketMs, bucketStarts, bucketEndMs } = window;
373
+ const pricing = input.pricing;
374
+ const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });
246
375
  return this.observation.withDatabase((db) => {
247
- validateTokenStatsTimestamp(input.asOfMs, "asOfMs");
248
- if (!TOKEN_STATS_RANGES.includes(input.range))
249
- throw new Error("invalid token-stats range");
250
- if (!["model", "time"].includes(input.groupBy))
251
- throw new Error("invalid token-stats groupBy");
252
- const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);
253
- const startMs = Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS);
254
- const bucketMs = input.groupBy === "time" ? window.bucketMs : undefined;
255
- const bucketStarts = input.groupBy === "time" ? window.bucketStarts : undefined;
256
- const bucketEndMs = input.groupBy === "time" ? window.bucketEndMs : undefined;
257
- const { sql, params } = buildTokenStatsWindowSnapshotQuery({ ...window, startMs, groupBy: input.groupBy, bucketMs, bucketStarts, keyId: input.keyId });
258
- const rows = db.query(sql).all(...params);
376
+ const read = () => {
377
+ const rows = db.query(sql).all(...params);
378
+ if (!pricing?.prices.length)
379
+ return rows;
380
+ const prices = new Map(pricing.prices);
381
+ const missing = db.query(missingSql).iterate(...params, JSON.stringify([...prices.keys()]));
382
+ const byGroup = new Map;
383
+ let total;
384
+ for (const row of missing) {
385
+ const nano = costNanoUsdOf(costOf(prices.get(row.model), {
386
+ inputTokens: row.input_tokens ?? undefined,
387
+ outputTokens: row.output_tokens ?? undefined,
388
+ cacheReadTokens: row.cache_read_tokens ?? undefined,
389
+ cacheWriteTokens: row.cache_write_tokens ?? undefined
390
+ }));
391
+ if (nano === null)
392
+ continue;
393
+ const cost = nano / 1e9;
394
+ total = (total ?? 0) + cost;
395
+ const key = JSON.stringify([row.model, row.bucketStartMs]);
396
+ byGroup.set(key, (byGroup.get(key) ?? 0) + cost);
397
+ }
398
+ for (const row of rows) {
399
+ const extra = row.kind === "all" ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));
400
+ if (extra !== undefined)
401
+ row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;
402
+ }
403
+ return rows;
404
+ };
405
+ const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();
259
406
  const allRow = rows.find((row) => row.kind === "all");
260
407
  const dataRows = rows.filter((row) => row.kind === "data");
261
408
  const metrics = (row) => {
@@ -301,6 +448,36 @@ class SQLiteTokenStatsMetering {
301
448
  });
302
449
  }
303
450
  }
451
+ function queryBounds(input) {
452
+ validateTokenStatsTimestamp(input.asOfMs, "asOfMs");
453
+ if (!TOKEN_STATS_RANGES.includes(input.range))
454
+ throw new Error("invalid token-stats range");
455
+ if (!["model", "time"].includes(input.groupBy))
456
+ throw new Error("invalid token-stats groupBy");
457
+ const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);
458
+ return {
459
+ ...window,
460
+ startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),
461
+ groupBy: input.groupBy,
462
+ bucketMs: input.groupBy === "time" ? window.bucketMs : undefined,
463
+ bucketStarts: input.groupBy === "time" ? window.bucketStarts : undefined,
464
+ bucketEndMs: input.groupBy === "time" ? window.bucketEndMs : undefined,
465
+ keyId: input.keyId
466
+ };
467
+ }
468
+ function attemptWindow(input) {
469
+ const { startMs, endMs, keyId, throughRow } = input;
470
+ if (keyId !== undefined && (typeof keyId !== "string" || !keyId || keyId.length > 128))
471
+ throw new Error("invalid token-stats keyId");
472
+ if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0))
473
+ throw new Error("invalid token-stats row boundary");
474
+ const keyFilter = keyId === undefined ? "" : keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
475
+ return {
476
+ index: keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished",
477
+ where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? "" : " AND rowid <= ?"}`,
478
+ params: [startMs, endMs, ...keyId !== undefined && keyId !== "__unattributed__" ? [keyId] : [], ...throughRow === undefined ? [] : [throughRow]]
479
+ };
480
+ }
304
481
  function buildTokenStatsWindowSnapshotQuery(input) {
305
482
  const metrics = (alias) => `
306
483
  COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,
@@ -328,10 +505,7 @@ function buildTokenStatsWindowSnapshotQuery(input) {
328
505
  if (input.bucketStarts && (!input.bucketStarts.length || input.bucketStarts.length > 31 || input.bucketStarts.some((start, i, starts) => !Number.isSafeInteger(start) || start < 0 || i > 0 && start <= starts[i - 1]))) {
329
506
  throw new Error("invalid token-stats bucketStarts");
330
507
  }
331
- if (input.keyId !== undefined && (typeof input.keyId !== "string" || !input.keyId || input.keyId.length > 128))
332
- throw new Error("invalid token-stats keyId");
333
- const keyFilter = input.keyId === undefined ? "" : input.keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
334
- const index = input.keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished";
508
+ const { index, where, params } = attemptWindow(input);
335
509
  const origin = input.bucketStarts?.[0] ?? 0;
336
510
  const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs);
337
511
  const bucketStart = input.groupBy !== "time" ? "NULL" : uniform ? `CAST((attempt.finished_at_ms - ${origin}) / ${input.bucketMs} AS INTEGER) * ${input.bucketMs} + ${origin}` : `CASE ${[...input.bucketStarts].reverse().map((start) => `WHEN attempt.finished_at_ms >= ${start} THEN ${start}`).join(" ")} END`;
@@ -344,14 +518,19 @@ function buildTokenStatsWindowSnapshotQuery(input) {
344
518
  sql: `
345
519
  WITH window_rows AS MATERIALIZED (
346
520
  SELECT * FROM token_stats_attempts INDEXED BY ${index}
347
- WHERE finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}
521
+ WHERE ${where}
348
522
  )
349
523
  SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics("attempt")}, (COUNT(*) > 0) AS present
350
524
  FROM window_rows AS attempt
351
525
  ${grouped}
352
526
  ORDER BY kind, bucketStartMs, dimension
353
527
  `,
354
- params: [input.startMs, input.endMs, ...input.keyId !== undefined && input.keyId !== "__unattributed__" ? [input.keyId] : []]
528
+ missingSql: `
529
+ SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs
530
+ FROM token_stats_attempts AS attempt INDEXED BY ${index}
531
+ WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))
532
+ `,
533
+ params
355
534
  };
356
535
  }
357
536
  function validateTokenStatsAttempt(row) {
@@ -454,13 +633,29 @@ var pendingCount = 0;
454
633
  var drainTimer;
455
634
  var draining = false;
456
635
  var lastDropLogAt = 0;
457
- var lastFailureLogAt = 0;
458
- function logRateLimited(logger, kind, error) {
636
+ var lastFailureLogAt = new Map;
637
+ function failureCode(error) {
638
+ if (error instanceof DOMException && error.name === "TimeoutError")
639
+ return "rpc_timeout";
640
+ if (error instanceof Error && error.name === "DataAdmissionError" && "code" in error) {
641
+ switch (error.code) {
642
+ case "invalid_worker_rpc":
643
+ case "worker_not_admitted":
644
+ case "rpc_busy":
645
+ case "rpc_capacity":
646
+ return error.code;
647
+ default:
648
+ return "rpc_rejected";
649
+ }
650
+ }
651
+ return "unclassified";
652
+ }
653
+ function logRateLimited(logger, stage, error) {
459
654
  try {
460
655
  logger.onFailure?.();
461
656
  } catch {}
462
657
  const now = Date.now();
463
- if (kind === "drop") {
658
+ if (stage === "drop") {
464
659
  if (now - lastDropLogAt < LOG_INTERVAL_MS)
465
660
  return;
466
661
  lastDropLogAt = now;
@@ -469,13 +664,12 @@ function logRateLimited(logger, kind, error) {
469
664
  } catch {}
470
665
  return;
471
666
  }
472
- if (now - lastFailureLogAt < LOG_INTERVAL_MS)
473
- return;
474
- lastFailureLogAt = now;
475
667
  try {
476
- logger.error("Token stats attempt processing failed; dropping metering row", {
477
- error: error instanceof Error ? error.message : error === undefined ? "attempt task returned no row" : String(error)
478
- });
668
+ const failure = `${stage}/${failureCode(error)}`;
669
+ if (now - (lastFailureLogAt.get(failure) ?? 0) < LOG_INTERVAL_MS)
670
+ return;
671
+ lastFailureLogAt.set(failure, now);
672
+ logger.error(`Token stats attempt processing failed; dropping metering row [${failure}]`);
479
673
  } catch {}
480
674
  }
481
675
  function scheduleDrain() {
@@ -493,17 +687,15 @@ async function drainOneAttempt() {
493
687
  if (!item)
494
688
  return;
495
689
  draining = true;
690
+ let stage = "prepare";
496
691
  try {
497
- try {
498
- const row = await item.task();
499
- if (row === undefined) {
500
- logRateLimited(item.logger, "failure");
501
- } else {
502
- await item.metering.recordAttempt(row);
503
- }
504
- } catch (error) {
505
- logRateLimited(item.logger, "failure", error);
506
- }
692
+ const row = await item.task();
693
+ if (row === undefined)
694
+ return logRateLimited(item.logger, "missing_row");
695
+ stage = "write";
696
+ await item.metering.recordAttempt(row);
697
+ } catch (error) {
698
+ logRateLimited(item.logger, stage, error);
507
699
  } finally {
508
700
  pendingCount--;
509
701
  draining = false;
@@ -557,7 +749,7 @@ class TokenStatsRepository {
557
749
  scheduleDrain();
558
750
  return true;
559
751
  }
560
- async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId) {
752
+ async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId, catalog) {
561
753
  if (!TOKEN_STATS_RANGES.includes(range))
562
754
  throw new TokenStatsRepositoryError("invalid token-stats range");
563
755
  if (groupBy !== "model" && groupBy !== "time") {
@@ -565,7 +757,26 @@ class TokenStatsRepository {
565
757
  }
566
758
  if (!Number.isSafeInteger(asOfMs) || asOfMs < 0)
567
759
  throw new TokenStatsRepositoryError("invalid token-stats asOfMs");
568
- const snapshot = await this.metering.queryWindowSnapshot({ asOfMs, range, groupBy, timeZone, keyId });
760
+ const window = { asOfMs, range, groupBy, timeZone, keyId };
761
+ let input = window;
762
+ if (catalog && this.metering.queryPricingModels) {
763
+ const mappings = await this.mappings().catch(() => {
764
+ return;
765
+ });
766
+ if (mappings) {
767
+ const { models, throughRow } = await this.metering.queryPricingModels(window);
768
+ const bySource = new Map(mappings.map((mapping) => [mapping.source, mapping]));
769
+ const prices = [];
770
+ for (const model of models) {
771
+ const mapped = bySource.get(model);
772
+ const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });
773
+ if (price !== null)
774
+ prices.push([model, price]);
775
+ }
776
+ input = { ...window, pricing: { throughRow, prices } };
777
+ }
778
+ }
779
+ const snapshot = await this.metering.queryWindowSnapshot(input);
569
780
  const total = metricsToDto(snapshot.all);
570
781
  const { inputTokens, outputTokens, ...summary } = total;
571
782
  return {
@@ -606,72 +817,6 @@ class TokenStatsRepository {
606
817
  }
607
818
  }
608
819
 
609
- // plugins/token-stats/server/pricing.ts
610
- var TOKENS_PER_UNIT = 1e6;
611
- function isNonNegativeInteger(value) {
612
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
613
- }
614
- function costOf(match, input) {
615
- const inputTokens = input.inputTokens;
616
- const outputTokens = input.outputTokens;
617
- if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens))
618
- return null;
619
- const cacheReads = input.cacheReadTokens ?? 0;
620
- const cacheWrites = input.cacheWriteTokens ?? 0;
621
- if (!isNonNegativeInteger(cacheReads) || !isNonNegativeInteger(cacheWrites) || cacheReads + cacheWrites > inputTokens)
622
- return null;
623
- let rates = match;
624
- for (const tier of match.contextTiers ?? []) {
625
- if (inputTokens < tier.minimumInputTokens)
626
- break;
627
- rates = tier;
628
- }
629
- const cacheRead = rates.cacheRead ?? match.cacheRead ?? rates.input;
630
- const cacheWrite = rates.cacheWrite ?? match.cacheWrite ?? rates.input;
631
- const baseInput = inputTokens - cacheReads - cacheWrites;
632
- const total = baseInput * rates.input + outputTokens * rates.output + cacheReads * cacheRead + cacheWrites * cacheWrite;
633
- const cost = total / TOKENS_PER_UNIT;
634
- return Number.isFinite(cost) && cost >= 0 ? cost : null;
635
- }
636
- function calculateTokenStatsCost(catalog, input, mappings = []) {
637
- if (catalog === null || typeof input.model !== "string" || input.model.length === 0)
638
- return null;
639
- const mapping = mappings.find((item) => item.source === input.model);
640
- if (mapping !== undefined) {
641
- const target = catalog.resolveModel({ model: mapping.model, pricingProvider: mapping.provider });
642
- return target === null ? null : costOf(target, input);
643
- }
644
- const match = catalog.resolveModel({
645
- model: input.model,
646
- mode: "estimate",
647
- ...input.provider === undefined ? {} : { pricingProvider: input.provider },
648
- ...input.url === undefined ? {} : { url: input.url }
649
- });
650
- return match === null ? null : costOf(match, input);
651
- }
652
-
653
- class TokenStatsPricing {
654
- catalog;
655
- mappings = [];
656
- constructor(catalog) {
657
- this.catalog = catalog;
658
- }
659
- setMappings(mappings) {
660
- this.mappings = mappings;
661
- }
662
- hasMappings() {
663
- return this.mappings !== undefined;
664
- }
665
- estimate(input) {
666
- if (this.mappings === undefined)
667
- return null;
668
- return calculateTokenStatsCost(this.catalog, input, this.mappings);
669
- }
670
- ready() {
671
- return Promise.resolve();
672
- }
673
- }
674
-
675
820
  // plugins/models-dev/contract.ts
676
821
  var MODELS_DEV_CATALOG_SERVICE_ID = "models-dev.catalog.v1";
677
822
  var MODELS_DEV_CATALOG_CONTRACT_VERSION = 1;
@@ -752,8 +897,7 @@ class TokenStatsPricingService {
752
897
  cacheReadTokens: result.cacheReadTokens,
753
898
  cacheWriteTokens: result.cacheWriteTokens
754
899
  });
755
- const nano = raw === null || !Number.isFinite(raw) || raw < 0 ? null : Math.round(raw * 1e9);
756
- const costNanoUsd = nano !== null && Number.isSafeInteger(nano) && nano >= 0 ? nano : null;
900
+ const costNanoUsd = costNanoUsdOf(raw);
757
901
  return Object.freeze({ costNanoUsd, costUsd: costNanoUsd === null ? null : costNanoUsd / 1e9 });
758
902
  });
759
903
  this.results.set(key, pending);
@@ -912,4 +1056,4 @@ export {
912
1056
  server_default as default
913
1057
  };
914
1058
 
915
- //# debugId=5AF5B1588AE8435764756E2164756E21
1059
+ //# debugId=E5DE987FFE6B7D0064756E2164756E21