@jeffusion/bungee-core 6.16.0 → 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 +43 -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
|
@@ -199,6 +199,40 @@ function tokenStatsWindow(range, asOfMs, timeZone = "UTC") {
|
|
|
199
199
|
const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));
|
|
200
200
|
return { startMs: bucketStarts[0], endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };
|
|
201
201
|
}
|
|
202
|
+
// plugins/token-stats/server/pricing.ts
|
|
203
|
+
var TOKENS_PER_UNIT = 1e6;
|
|
204
|
+
function isNonNegativeInteger(value) {
|
|
205
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
206
|
+
}
|
|
207
|
+
function costOf(match, input) {
|
|
208
|
+
const inputTokens = input.inputTokens;
|
|
209
|
+
const outputTokens = input.outputTokens;
|
|
210
|
+
if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens))
|
|
211
|
+
return null;
|
|
212
|
+
const cacheReads = input.cacheReadTokens ?? 0;
|
|
213
|
+
const cacheWrites = input.cacheWriteTokens ?? 0;
|
|
214
|
+
if (!isNonNegativeInteger(cacheReads) || !isNonNegativeInteger(cacheWrites) || cacheReads + cacheWrites > inputTokens)
|
|
215
|
+
return null;
|
|
216
|
+
let rates = match;
|
|
217
|
+
for (const tier of match.contextTiers ?? []) {
|
|
218
|
+
if (inputTokens < tier.minimumInputTokens)
|
|
219
|
+
break;
|
|
220
|
+
rates = tier;
|
|
221
|
+
}
|
|
222
|
+
const cacheRead = rates.cacheRead ?? match.cacheRead ?? rates.input;
|
|
223
|
+
const cacheWrite = rates.cacheWrite ?? match.cacheWrite ?? rates.input;
|
|
224
|
+
const baseInput = inputTokens - cacheReads - cacheWrites;
|
|
225
|
+
const total = baseInput * rates.input + outputTokens * rates.output + cacheReads * cacheRead + cacheWrites * cacheWrite;
|
|
226
|
+
const cost = total / TOKENS_PER_UNIT;
|
|
227
|
+
return Number.isFinite(cost) && cost >= 0 ? cost : null;
|
|
228
|
+
}
|
|
229
|
+
function costNanoUsdOf(cost) {
|
|
230
|
+
if (cost === null || !Number.isFinite(cost) || cost < 0)
|
|
231
|
+
return null;
|
|
232
|
+
const nano = Math.round(cost * 1e9);
|
|
233
|
+
return Number.isSafeInteger(nano) ? nano : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
202
236
|
// plugins/token-stats/server/storage.ts
|
|
203
237
|
var TOKEN_STATS_METRICS = [
|
|
204
238
|
"inputTokens",
|
|
@@ -227,6 +261,7 @@ var TOKEN_STATS_METRICS = [
|
|
|
227
261
|
var TOKEN_STATS_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
|
|
228
262
|
var TOKEN_STATS_BUSY_TIMEOUT_MS = 5;
|
|
229
263
|
var EMPTY_METRICS = Object.fromEntries(TOKEN_STATS_METRICS.map((name) => [name, 0]));
|
|
264
|
+
var PRICEABLE_USAGE = `cost_usd IS NULL AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL AND model <> 'unknown'`;
|
|
230
265
|
|
|
231
266
|
class SQLiteTokenStatsMetering {
|
|
232
267
|
observation;
|
|
@@ -254,20 +289,54 @@ class SQLiteTokenStatsMetering {
|
|
|
254
289
|
withReportingWriteTimeout(db, () => transaction.immediate());
|
|
255
290
|
});
|
|
256
291
|
}
|
|
292
|
+
async queryPricingModels(input) {
|
|
293
|
+
const window = queryBounds(input);
|
|
294
|
+
return this.observation.withDatabase((db) => db.transaction(() => {
|
|
295
|
+
const { throughRow } = db.query("SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts").get();
|
|
296
|
+
const { index, where, params } = attemptWindow({ ...window, throughRow });
|
|
297
|
+
const rows = db.query(`
|
|
298
|
+
SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}
|
|
299
|
+
WHERE ${where} AND ${PRICEABLE_USAGE}
|
|
300
|
+
`).all(...params);
|
|
301
|
+
return { models: rows.map((row) => row.model), throughRow };
|
|
302
|
+
}).deferred());
|
|
303
|
+
}
|
|
257
304
|
async queryWindowSnapshot(input) {
|
|
305
|
+
const window = queryBounds(input);
|
|
306
|
+
const { bucketMs, bucketStarts, bucketEndMs } = window;
|
|
307
|
+
const pricing = input.pricing;
|
|
308
|
+
const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });
|
|
258
309
|
return this.observation.withDatabase((db) => {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
310
|
+
const read = () => {
|
|
311
|
+
const rows = db.query(sql).all(...params);
|
|
312
|
+
if (!pricing?.prices.length)
|
|
313
|
+
return rows;
|
|
314
|
+
const prices = new Map(pricing.prices);
|
|
315
|
+
const missing = db.query(missingSql).iterate(...params, JSON.stringify([...prices.keys()]));
|
|
316
|
+
const byGroup = new Map;
|
|
317
|
+
let total;
|
|
318
|
+
for (const row of missing) {
|
|
319
|
+
const nano = costNanoUsdOf(costOf(prices.get(row.model), {
|
|
320
|
+
inputTokens: row.input_tokens ?? undefined,
|
|
321
|
+
outputTokens: row.output_tokens ?? undefined,
|
|
322
|
+
cacheReadTokens: row.cache_read_tokens ?? undefined,
|
|
323
|
+
cacheWriteTokens: row.cache_write_tokens ?? undefined
|
|
324
|
+
}));
|
|
325
|
+
if (nano === null)
|
|
326
|
+
continue;
|
|
327
|
+
const cost = nano / 1e9;
|
|
328
|
+
total = (total ?? 0) + cost;
|
|
329
|
+
const key = JSON.stringify([row.model, row.bucketStartMs]);
|
|
330
|
+
byGroup.set(key, (byGroup.get(key) ?? 0) + cost);
|
|
331
|
+
}
|
|
332
|
+
for (const row of rows) {
|
|
333
|
+
const extra = row.kind === "all" ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));
|
|
334
|
+
if (extra !== undefined)
|
|
335
|
+
row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;
|
|
336
|
+
}
|
|
337
|
+
return rows;
|
|
338
|
+
};
|
|
339
|
+
const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();
|
|
271
340
|
const allRow = rows.find((row) => row.kind === "all");
|
|
272
341
|
const dataRows = rows.filter((row) => row.kind === "data");
|
|
273
342
|
const metrics = (row) => {
|
|
@@ -313,6 +382,36 @@ class SQLiteTokenStatsMetering {
|
|
|
313
382
|
});
|
|
314
383
|
}
|
|
315
384
|
}
|
|
385
|
+
function queryBounds(input) {
|
|
386
|
+
validateTokenStatsTimestamp(input.asOfMs, "asOfMs");
|
|
387
|
+
if (!TOKEN_STATS_RANGES.includes(input.range))
|
|
388
|
+
throw new Error("invalid token-stats range");
|
|
389
|
+
if (!["model", "time"].includes(input.groupBy))
|
|
390
|
+
throw new Error("invalid token-stats groupBy");
|
|
391
|
+
const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);
|
|
392
|
+
return {
|
|
393
|
+
...window,
|
|
394
|
+
startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),
|
|
395
|
+
groupBy: input.groupBy,
|
|
396
|
+
bucketMs: input.groupBy === "time" ? window.bucketMs : undefined,
|
|
397
|
+
bucketStarts: input.groupBy === "time" ? window.bucketStarts : undefined,
|
|
398
|
+
bucketEndMs: input.groupBy === "time" ? window.bucketEndMs : undefined,
|
|
399
|
+
keyId: input.keyId
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
function attemptWindow(input) {
|
|
403
|
+
const { startMs, endMs, keyId, throughRow } = input;
|
|
404
|
+
if (keyId !== undefined && (typeof keyId !== "string" || !keyId || keyId.length > 128))
|
|
405
|
+
throw new Error("invalid token-stats keyId");
|
|
406
|
+
if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0))
|
|
407
|
+
throw new Error("invalid token-stats row boundary");
|
|
408
|
+
const keyFilter = keyId === undefined ? "" : keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
|
|
409
|
+
return {
|
|
410
|
+
index: keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished",
|
|
411
|
+
where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? "" : " AND rowid <= ?"}`,
|
|
412
|
+
params: [startMs, endMs, ...keyId !== undefined && keyId !== "__unattributed__" ? [keyId] : [], ...throughRow === undefined ? [] : [throughRow]]
|
|
413
|
+
};
|
|
414
|
+
}
|
|
316
415
|
function buildTokenStatsWindowSnapshotQuery(input) {
|
|
317
416
|
const metrics = (alias) => `
|
|
318
417
|
COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,
|
|
@@ -340,10 +439,7 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
340
439
|
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]))) {
|
|
341
440
|
throw new Error("invalid token-stats bucketStarts");
|
|
342
441
|
}
|
|
343
|
-
|
|
344
|
-
throw new Error("invalid token-stats keyId");
|
|
345
|
-
const keyFilter = input.keyId === undefined ? "" : input.keyId === "__unattributed__" ? " AND key_id IS NULL" : " AND key_id = ?";
|
|
346
|
-
const index = input.keyId === undefined ? "idx_token_stats_attempts_finished" : "idx_token_stats_attempts_key_finished";
|
|
442
|
+
const { index, where, params } = attemptWindow(input);
|
|
347
443
|
const origin = input.bucketStarts?.[0] ?? 0;
|
|
348
444
|
const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs);
|
|
349
445
|
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`;
|
|
@@ -356,14 +452,19 @@ function buildTokenStatsWindowSnapshotQuery(input) {
|
|
|
356
452
|
sql: `
|
|
357
453
|
WITH window_rows AS MATERIALIZED (
|
|
358
454
|
SELECT * FROM token_stats_attempts INDEXED BY ${index}
|
|
359
|
-
WHERE
|
|
455
|
+
WHERE ${where}
|
|
360
456
|
)
|
|
361
457
|
SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics("attempt")}, (COUNT(*) > 0) AS present
|
|
362
458
|
FROM window_rows AS attempt
|
|
363
459
|
${grouped}
|
|
364
460
|
ORDER BY kind, bucketStartMs, dimension
|
|
365
461
|
`,
|
|
366
|
-
|
|
462
|
+
missingSql: `
|
|
463
|
+
SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs
|
|
464
|
+
FROM token_stats_attempts AS attempt INDEXED BY ${index}
|
|
465
|
+
WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))
|
|
466
|
+
`,
|
|
467
|
+
params
|
|
367
468
|
};
|
|
368
469
|
}
|
|
369
470
|
function validateTokenStatsAttempt(row) {
|
|
@@ -575,7 +676,7 @@ class TokenStatsRepository {
|
|
|
575
676
|
scheduleDrain();
|
|
576
677
|
return true;
|
|
577
678
|
}
|
|
578
|
-
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId) {
|
|
679
|
+
async query(range, groupBy, asOfMs = Date.now(), timeZone, keyId, catalog) {
|
|
579
680
|
if (!TOKEN_STATS_RANGES.includes(range))
|
|
580
681
|
throw new TokenStatsRepositoryError("invalid token-stats range");
|
|
581
682
|
if (groupBy !== "model" && groupBy !== "time") {
|
|
@@ -583,7 +684,26 @@ class TokenStatsRepository {
|
|
|
583
684
|
}
|
|
584
685
|
if (!Number.isSafeInteger(asOfMs) || asOfMs < 0)
|
|
585
686
|
throw new TokenStatsRepositoryError("invalid token-stats asOfMs");
|
|
586
|
-
const
|
|
687
|
+
const window = { asOfMs, range, groupBy, timeZone, keyId };
|
|
688
|
+
let input = window;
|
|
689
|
+
if (catalog && this.metering.queryPricingModels) {
|
|
690
|
+
const mappings = await this.mappings().catch(() => {
|
|
691
|
+
return;
|
|
692
|
+
});
|
|
693
|
+
if (mappings) {
|
|
694
|
+
const { models, throughRow } = await this.metering.queryPricingModels(window);
|
|
695
|
+
const bySource = new Map(mappings.map((mapping) => [mapping.source, mapping]));
|
|
696
|
+
const prices = [];
|
|
697
|
+
for (const model of models) {
|
|
698
|
+
const mapped = bySource.get(model);
|
|
699
|
+
const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });
|
|
700
|
+
if (price !== null)
|
|
701
|
+
prices.push([model, price]);
|
|
702
|
+
}
|
|
703
|
+
input = { ...window, pricing: { throughRow, prices } };
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const snapshot = await this.metering.queryWindowSnapshot(input);
|
|
587
707
|
const total = metricsToDto(snapshot.all);
|
|
588
708
|
const { inputTokens, outputTokens, ...summary } = total;
|
|
589
709
|
return {
|
|
@@ -815,7 +935,11 @@ class TokenStatsControl {
|
|
|
815
935
|
}
|
|
816
936
|
const range = rawRange ?? "24h";
|
|
817
937
|
const groupBy = rawGroupBy ?? "model";
|
|
818
|
-
|
|
938
|
+
let catalog;
|
|
939
|
+
try {
|
|
940
|
+
catalog = this.catalogService();
|
|
941
|
+
} catch {}
|
|
942
|
+
const payload = await abortable(this.repository.query(range, groupBy, Date.now(), timeZone, keyId, catalog), context.requestSignal, context.signal);
|
|
819
943
|
this.assertAlive(context.requestSignal);
|
|
820
944
|
const maxBytes = ["1h", "12h", "24h"].includes(range) ? MAX_RESPONSE_BYTES : MAX_PAGE_STATS_RESPONSE_BYTES;
|
|
821
945
|
return jsonResponse(payload, 200, maxBytes);
|
|
@@ -913,6 +1037,7 @@ function createObservationAdapter(observation) {
|
|
|
913
1037
|
return Object.freeze({
|
|
914
1038
|
recordAttempt: leaf.recordAttempt.bind(leaf),
|
|
915
1039
|
queryWindowSnapshot: leaf.queryWindowSnapshot.bind(leaf),
|
|
1040
|
+
queryPricingModels: leaf.queryPricingModels.bind(leaf),
|
|
916
1041
|
listClientModels: leaf.listClientModels.bind(leaf)
|
|
917
1042
|
});
|
|
918
1043
|
}
|
|
@@ -922,4 +1047,4 @@ export {
|
|
|
922
1047
|
control_default as default
|
|
923
1048
|
};
|
|
924
1049
|
|
|
925
|
-
//# debugId=
|
|
1050
|
+
//# debugId=965474093B0BDEB764756E2164756E21
|