@jeffusion/bungee-core 6.16.1 → 6.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +42 -42
- package/dist/plugins/token-stats/control.js +147 -22
- package/dist/plugins/token-stats/control.js.map +7 -6
- package/dist/plugins/token-stats/index.js +180 -89
- package/dist/plugins/token-stats/index.js.map +7 -7
- package/dist/plugins/token-stats/manifest.json +2 -2
- package/package.json +2 -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,6 +287,7 @@ 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;
|
|
@@ -242,20 +315,54 @@ class SQLiteTokenStatsMetering {
|
|
|
242
315
|
withReportingWriteTimeout(db, () => transaction.immediate());
|
|
243
316
|
});
|
|
244
317
|
}
|
|
318
|
+
async queryPricingModels(input) {
|
|
319
|
+
const window = queryBounds(input);
|
|
320
|
+
return this.observation.withDatabase((db) => db.transaction(() => {
|
|
321
|
+
const { throughRow } = db.query("SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts").get();
|
|
322
|
+
const { index, where, params } = attemptWindow({ ...window, throughRow });
|
|
323
|
+
const rows = db.query(`
|
|
324
|
+
SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}
|
|
325
|
+
WHERE ${where} AND ${PRICEABLE_USAGE}
|
|
326
|
+
`).all(...params);
|
|
327
|
+
return { models: rows.map((row) => row.model), throughRow };
|
|
328
|
+
}).deferred());
|
|
329
|
+
}
|
|
245
330
|
async queryWindowSnapshot(input) {
|
|
331
|
+
const window = queryBounds(input);
|
|
332
|
+
const { bucketMs, bucketStarts, bucketEndMs } = window;
|
|
333
|
+
const pricing = input.pricing;
|
|
334
|
+
const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });
|
|
246
335
|
return this.observation.withDatabase((db) => {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
336
|
+
const read = () => {
|
|
337
|
+
const rows = db.query(sql).all(...params);
|
|
338
|
+
if (!pricing?.prices.length)
|
|
339
|
+
return rows;
|
|
340
|
+
const prices = new Map(pricing.prices);
|
|
341
|
+
const missing = db.query(missingSql).iterate(...params, JSON.stringify([...prices.keys()]));
|
|
342
|
+
const byGroup = new Map;
|
|
343
|
+
let total;
|
|
344
|
+
for (const row of missing) {
|
|
345
|
+
const nano = costNanoUsdOf(costOf(prices.get(row.model), {
|
|
346
|
+
inputTokens: row.input_tokens ?? undefined,
|
|
347
|
+
outputTokens: row.output_tokens ?? undefined,
|
|
348
|
+
cacheReadTokens: row.cache_read_tokens ?? undefined,
|
|
349
|
+
cacheWriteTokens: row.cache_write_tokens ?? undefined
|
|
350
|
+
}));
|
|
351
|
+
if (nano === null)
|
|
352
|
+
continue;
|
|
353
|
+
const cost = nano / 1e9;
|
|
354
|
+
total = (total ?? 0) + cost;
|
|
355
|
+
const key = JSON.stringify([row.model, row.bucketStartMs]);
|
|
356
|
+
byGroup.set(key, (byGroup.get(key) ?? 0) + cost);
|
|
357
|
+
}
|
|
358
|
+
for (const row of rows) {
|
|
359
|
+
const extra = row.kind === "all" ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));
|
|
360
|
+
if (extra !== undefined)
|
|
361
|
+
row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;
|
|
362
|
+
}
|
|
363
|
+
return rows;
|
|
364
|
+
};
|
|
365
|
+
const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();
|
|
259
366
|
const allRow = rows.find((row) => row.kind === "all");
|
|
260
367
|
const dataRows = rows.filter((row) => row.kind === "data");
|
|
261
368
|
const metrics = (row) => {
|
|
@@ -301,6 +408,36 @@ class SQLiteTokenStatsMetering {
|
|
|
301
408
|
});
|
|
302
409
|
}
|
|
303
410
|
}
|
|
411
|
+
function queryBounds(input) {
|
|
412
|
+
validateTokenStatsTimestamp(input.asOfMs, "asOfMs");
|
|
413
|
+
if (!TOKEN_STATS_RANGES.includes(input.range))
|
|
414
|
+
throw new Error("invalid token-stats range");
|
|
415
|
+
if (!["model", "time"].includes(input.groupBy))
|
|
416
|
+
throw new Error("invalid token-stats groupBy");
|
|
417
|
+
const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);
|
|
418
|
+
return {
|
|
419
|
+
...window,
|
|
420
|
+
startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),
|
|
421
|
+
groupBy: input.groupBy,
|
|
422
|
+
bucketMs: input.groupBy === "time" ? window.bucketMs : undefined,
|
|
423
|
+
bucketStarts: input.groupBy === "time" ? window.bucketStarts : undefined,
|
|
424
|
+
bucketEndMs: input.groupBy === "time" ? window.bucketEndMs : undefined,
|
|
425
|
+
keyId: input.keyId
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function attemptWindow(input) {
|
|
429
|
+
const { startMs, endMs, keyId, throughRow } = input;
|
|
430
|
+
if (keyId !== undefined && (typeof keyId !== "string" || !keyId || keyId.length > 128))
|
|
431
|
+
throw new Error("invalid token-stats keyId");
|
|
432
|
+
if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0))
|
|
433
|
+
throw new Error("invalid token-stats row boundary");
|
|
434
|
+
const keyFilter = keyId === undefined ? "" : keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
|
|
435
|
+
return {
|
|
436
|
+
index: keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished",
|
|
437
|
+
where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? "" : " AND rowid <= ?"}`,
|
|
438
|
+
params: [startMs, endMs, ...keyId !== undefined && keyId !== "__unattributed__" ? [keyId] : [], ...throughRow === undefined ? [] : [throughRow]]
|
|
439
|
+
};
|
|
440
|
+
}
|
|
304
441
|
function buildTokenStatsWindowSnapshotQuery(input) {
|
|
305
442
|
const metrics = (alias) => `
|
|
306
443
|
COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,
|
|
@@ -328,10 +465,7 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
328
465
|
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
466
|
throw new Error("invalid token-stats bucketStarts");
|
|
330
467
|
}
|
|
331
|
-
|
|
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";
|
|
468
|
+
const { index, where, params } = attemptWindow(input);
|
|
335
469
|
const origin = input.bucketStarts?.[0] ?? 0;
|
|
336
470
|
const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs);
|
|
337
471
|
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 +478,19 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
344
478
|
sql: `
|
|
345
479
|
WITH window_rows AS MATERIALIZED (
|
|
346
480
|
SELECT * FROM token_stats_attempts INDEXED BY ${index}
|
|
347
|
-
WHERE
|
|
481
|
+
WHERE ${where}
|
|
348
482
|
)
|
|
349
483
|
SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics("attempt")}, (COUNT(*) > 0) AS present
|
|
350
484
|
FROM window_rows AS attempt
|
|
351
485
|
${grouped}
|
|
352
486
|
ORDER BY kind, bucketStartMs, dimension
|
|
353
487
|
`,
|
|
354
|
-
|
|
488
|
+
missingSql: `
|
|
489
|
+
SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs
|
|
490
|
+
FROM token_stats_attempts AS attempt INDEXED BY ${index}
|
|
491
|
+
WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))
|
|
492
|
+
`,
|
|
493
|
+
params
|
|
355
494
|
};
|
|
356
495
|
}
|
|
357
496
|
function validateTokenStatsAttempt(row) {
|
|
@@ -557,7 +696,7 @@ class TokenStatsRepository {
|
|
|
557
696
|
scheduleDrain();
|
|
558
697
|
return true;
|
|
559
698
|
}
|
|
560
|
-
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId) {
|
|
699
|
+
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId, catalog) {
|
|
561
700
|
if (!TOKEN_STATS_RANGES.includes(range))
|
|
562
701
|
throw new TokenStatsRepositoryError("invalid token-stats range");
|
|
563
702
|
if (groupBy !== "model" && groupBy !== "time") {
|
|
@@ -565,7 +704,26 @@ class TokenStatsRepository {
|
|
|
565
704
|
}
|
|
566
705
|
if (!Number.isSafeInteger(asOfMs) || asOfMs < 0)
|
|
567
706
|
throw new TokenStatsRepositoryError("invalid token-stats asOfMs");
|
|
568
|
-
const
|
|
707
|
+
const window = { asOfMs, range, groupBy, timeZone, keyId };
|
|
708
|
+
let input = window;
|
|
709
|
+
if (catalog && this.metering.queryPricingModels) {
|
|
710
|
+
const mappings = await this.mappings().catch(() => {
|
|
711
|
+
return;
|
|
712
|
+
});
|
|
713
|
+
if (mappings) {
|
|
714
|
+
const { models, throughRow } = await this.metering.queryPricingModels(window);
|
|
715
|
+
const bySource = new Map(mappings.map((mapping) => [mapping.source, mapping]));
|
|
716
|
+
const prices = [];
|
|
717
|
+
for (const model of models) {
|
|
718
|
+
const mapped = bySource.get(model);
|
|
719
|
+
const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });
|
|
720
|
+
if (price !== null)
|
|
721
|
+
prices.push([model, price]);
|
|
722
|
+
}
|
|
723
|
+
input = { ...window, pricing: { throughRow, prices } };
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const snapshot = await this.metering.queryWindowSnapshot(input);
|
|
569
727
|
const total = metricsToDto(snapshot.all);
|
|
570
728
|
const { inputTokens, outputTokens, ...summary } = total;
|
|
571
729
|
return {
|
|
@@ -606,72 +764,6 @@ class TokenStatsRepository {
|
|
|
606
764
|
}
|
|
607
765
|
}
|
|
608
766
|
|
|
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
767
|
// plugins/models-dev/contract.ts
|
|
676
768
|
var MODELS_DEV_CATALOG_SERVICE_ID = "models-dev.catalog.v1";
|
|
677
769
|
var MODELS_DEV_CATALOG_CONTRACT_VERSION = 1;
|
|
@@ -752,8 +844,7 @@ class TokenStatsPricingService {
|
|
|
752
844
|
cacheReadTokens: result.cacheReadTokens,
|
|
753
845
|
cacheWriteTokens: result.cacheWriteTokens
|
|
754
846
|
});
|
|
755
|
-
const
|
|
756
|
-
const costNanoUsd = nano !== null && Number.isSafeInteger(nano) && nano >= 0 ? nano : null;
|
|
847
|
+
const costNanoUsd = costNanoUsdOf(raw);
|
|
757
848
|
return Object.freeze({ costNanoUsd, costUsd: costNanoUsd === null ? null : costNanoUsd / 1e9 });
|
|
758
849
|
});
|
|
759
850
|
this.results.set(key, pending);
|
|
@@ -912,4 +1003,4 @@ export {
|
|
|
912
1003
|
server_default as default
|
|
913
1004
|
};
|
|
914
1005
|
|
|
915
|
-
//# debugId=
|
|
1006
|
+
//# debugId=8ABD8AA5768DF02364756E2164756E21
|