vibezcheck 0.4.2 → 0.5.3

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 (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +249 -273
  3. package/bin/vibezcheck.js +4 -4
  4. package/dist/ai-sdk/index.d.mts +28 -59
  5. package/dist/ai-sdk/index.d.ts +28 -59
  6. package/dist/ai-sdk/index.js +307 -69
  7. package/dist/ai-sdk/index.js.map +1 -1
  8. package/dist/ai-sdk/index.mjs +307 -69
  9. package/dist/ai-sdk/index.mjs.map +1 -1
  10. package/dist/ai-sdk/middleware.d.mts +15 -0
  11. package/dist/ai-sdk/middleware.d.ts +15 -0
  12. package/dist/ai-sdk/middleware.js +1433 -0
  13. package/dist/ai-sdk/middleware.js.map +1 -0
  14. package/dist/ai-sdk/middleware.mjs +1396 -0
  15. package/dist/ai-sdk/middleware.mjs.map +1 -0
  16. package/dist/auth/index.js.map +1 -1
  17. package/dist/auth/index.mjs.map +1 -1
  18. package/dist/billing/index.d.mts +90 -1
  19. package/dist/billing/index.d.ts +90 -1
  20. package/dist/billing/index.js +1542 -2
  21. package/dist/billing/index.js.map +1 -1
  22. package/dist/billing/index.mjs +1537 -1
  23. package/dist/billing/index.mjs.map +1 -1
  24. package/dist/cli/index.js +59 -7
  25. package/dist/cli/index.js.map +1 -1
  26. package/dist/cli/index.mjs +59 -7
  27. package/dist/cli/index.mjs.map +1 -1
  28. package/dist/{client-ynfWcHX6.d.ts → client-BORmJy8s.d.ts} +1 -1
  29. package/dist/{client-w_hWhQ6g.d.mts → client-CbuXmoXz.d.mts} +1 -1
  30. package/dist/compat/stripe-meter.d.mts +21 -0
  31. package/dist/compat/stripe-meter.d.ts +21 -0
  32. package/dist/compat/stripe-meter.js +1451 -0
  33. package/dist/compat/stripe-meter.js.map +1 -0
  34. package/dist/compat/stripe-meter.mjs +1414 -0
  35. package/dist/compat/stripe-meter.mjs.map +1 -0
  36. package/dist/compat/stripe-provider.d.mts +34 -0
  37. package/dist/compat/stripe-provider.d.ts +34 -0
  38. package/dist/compat/stripe-provider.js +1620 -0
  39. package/dist/compat/stripe-provider.js.map +1 -0
  40. package/dist/compat/stripe-provider.mjs +1587 -0
  41. package/dist/compat/stripe-provider.mjs.map +1 -0
  42. package/dist/compat/token-meter.d.mts +28 -0
  43. package/dist/compat/token-meter.d.ts +28 -0
  44. package/dist/compat/token-meter.js +1320 -0
  45. package/dist/compat/token-meter.js.map +1 -0
  46. package/dist/compat/token-meter.mjs +1283 -0
  47. package/dist/compat/token-meter.mjs.map +1 -0
  48. package/dist/customers/index.d.mts +1 -1
  49. package/dist/customers/index.d.ts +1 -1
  50. package/dist/customers/index.js.map +1 -1
  51. package/dist/customers/index.mjs.map +1 -1
  52. package/dist/index.d.mts +25 -11
  53. package/dist/index.d.ts +25 -11
  54. package/dist/index.js +810 -72
  55. package/dist/index.js.map +1 -1
  56. package/dist/index.mjs +798 -72
  57. package/dist/index.mjs.map +1 -1
  58. package/dist/meter/index.d.mts +2 -2
  59. package/dist/meter/index.d.ts +2 -2
  60. package/dist/meter/index.js +176 -42
  61. package/dist/meter/index.js.map +1 -1
  62. package/dist/meter/index.mjs +176 -42
  63. package/dist/meter/index.mjs.map +1 -1
  64. package/dist/pricing/index.d.mts +15 -4
  65. package/dist/pricing/index.d.ts +15 -4
  66. package/dist/pricing/index.js +165 -29
  67. package/dist/pricing/index.js.map +1 -1
  68. package/dist/pricing/index.mjs +164 -29
  69. package/dist/pricing/index.mjs.map +1 -1
  70. package/dist/react/index.d.mts +46 -2
  71. package/dist/react/index.d.ts +46 -2
  72. package/dist/react/index.js +471 -29
  73. package/dist/react/index.js.map +1 -1
  74. package/dist/react/index.mjs +469 -29
  75. package/dist/react/index.mjs.map +1 -1
  76. package/dist/{types-Mozk4-Mr.d.mts → types-6P71CXAD.d.mts} +16 -6
  77. package/dist/{types-Mozk4-Mr.d.ts → types-6P71CXAD.d.ts} +16 -6
  78. package/dist/with-billing-Bj6Ya_Iy.d.ts +49 -0
  79. package/dist/with-billing-DndWGxL8.d.mts +49 -0
  80. package/package.json +35 -10
@@ -30,8 +30,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/billing/index.ts
31
31
  var billing_exports = {};
32
32
  __export(billing_exports, {
33
+ AgentSession: () => AgentSession,
33
34
  BillingHelper: () => BillingHelper,
34
- createBillingHelper: () => createBillingHelper
35
+ createAgentSession: () => createAgentSession,
36
+ createBillingHelper: () => createBillingHelper,
37
+ instrumentToolKit: () => instrumentToolKit,
38
+ wrapTool: () => wrapTool
35
39
  });
36
40
  module.exports = __toCommonJS(billing_exports);
37
41
 
@@ -120,9 +124,1545 @@ var BillingHelper = class {
120
124
  function createBillingHelper(options = {}) {
121
125
  return new BillingHelper(options);
122
126
  }
127
+
128
+ // src/types.ts
129
+ var VibezCircuitBreakerError = class extends Error {
130
+ event;
131
+ constructor(event) {
132
+ super(event.message);
133
+ this.name = "VibezCircuitBreakerError";
134
+ this.event = event;
135
+ }
136
+ };
137
+
138
+ // src/meter/client.ts
139
+ var import_stripe2 = __toESM(require("stripe"));
140
+
141
+ // src/meter/batcher.ts
142
+ var MeterBatcher = class {
143
+ queue = [];
144
+ timer = null;
145
+ isFlushing = false;
146
+ maxBatchSize;
147
+ flushIntervalMs;
148
+ stripeClient;
149
+ eventName;
150
+ onUsageCallback;
151
+ onErrorCallback;
152
+ debug;
153
+ // In-memory ledger for local stats
154
+ totalRequests = 0;
155
+ totalTokens = 0;
156
+ totalInputTokens = 0;
157
+ totalOutputTokens = 0;
158
+ totalReasoningTokens = 0;
159
+ totalCostUSD = 0;
160
+ byModel = {};
161
+ constructor(options = {}) {
162
+ this.stripeClient = options.stripe;
163
+ this.eventName = options.eventName || "token-billing-tokens";
164
+ this.maxBatchSize = options.batching?.maxBatchSize ?? 50;
165
+ this.flushIntervalMs = options.batching?.flushIntervalMs ?? 50;
166
+ this.onUsageCallback = options.onUsage;
167
+ this.onErrorCallback = options.onError;
168
+ this.debug = options.debug ?? false;
169
+ }
170
+ /**
171
+ * Enqueue a usage event for batch dispatching
172
+ */
173
+ enqueue(event) {
174
+ this.recordInLedger(event);
175
+ if (this.onUsageCallback) {
176
+ try {
177
+ const res = this.onUsageCallback(event);
178
+ if (res instanceof Promise) {
179
+ res.catch((err) => {
180
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
181
+ });
182
+ }
183
+ } catch (err) {
184
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
185
+ }
186
+ }
187
+ if (!this.stripeClient) {
188
+ if (this.debug) {
189
+ console.log(
190
+ `[vibezcheck:local] \u{1F4CA} ${event.model} | Tokens: ${event.usage.totalTokens} | Cost: $${event.cost.totalUSD.toFixed(6)}`
191
+ );
192
+ }
193
+ return;
194
+ }
195
+ this.queue.push(event);
196
+ if (this.queue.length >= this.maxBatchSize) {
197
+ this.flush().catch((err) => {
198
+ if (this.debug) console.error("[vibezcheck] Batch flush error:", err);
199
+ });
200
+ } else if (!this.timer) {
201
+ this.timer = setTimeout(() => {
202
+ this.timer = null;
203
+ this.flush().catch((err) => {
204
+ if (this.debug) console.error("[vibezcheck] Debounce flush error:", err);
205
+ });
206
+ }, this.flushIntervalMs);
207
+ }
208
+ }
209
+ /**
210
+ * Immediately flush all queued events to Stripe
211
+ */
212
+ async flush() {
213
+ if (this.timer) {
214
+ clearTimeout(this.timer);
215
+ this.timer = null;
216
+ }
217
+ if (this.queue.length === 0 || !this.stripeClient || this.isFlushing) {
218
+ return;
219
+ }
220
+ this.isFlushing = true;
221
+ const eventsToSend = [...this.queue];
222
+ this.queue = [];
223
+ try {
224
+ await this.sendEventsToStripe(eventsToSend);
225
+ } catch (error) {
226
+ const err = error instanceof Error ? error : new Error(String(error));
227
+ if (this.debug) {
228
+ console.error("[vibezcheck] Failed to send meter events to Stripe:", err);
229
+ }
230
+ if (this.onErrorCallback) {
231
+ this.onErrorCallback(err, eventsToSend);
232
+ }
233
+ } finally {
234
+ this.isFlushing = false;
235
+ if (this.queue.length > 0) {
236
+ this.flush().catch(() => {
237
+ });
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Sends events to Stripe Billing Meter Events API
243
+ */
244
+ async sendEventsToStripe(events) {
245
+ if (!this.stripeClient) return;
246
+ for (const event of events) {
247
+ const customerId = event.customerId;
248
+ if (!customerId) {
249
+ continue;
250
+ }
251
+ const timestamp = event.timestamp || (/* @__PURE__ */ new Date()).toISOString();
252
+ const model = `${event.provider}/${event.model}`;
253
+ if (event.usage.inputTokens > 0) {
254
+ try {
255
+ await this.stripeClient.v2.billing.meterEvents.create({
256
+ event_name: this.eventName,
257
+ timestamp,
258
+ payload: {
259
+ stripe_customer_id: customerId,
260
+ value: event.usage.inputTokens.toString(),
261
+ model,
262
+ token_type: "input",
263
+ cached_tokens: (event.usage.cachedTokens ?? 0).toString(),
264
+ ...event.metadata ? event.metadata : {}
265
+ }
266
+ });
267
+ } catch (e) {
268
+ if (this.debug) console.warn("[vibezcheck] Input meter event error:", e);
269
+ }
270
+ }
271
+ if (event.usage.outputTokens > 0) {
272
+ try {
273
+ await this.stripeClient.v2.billing.meterEvents.create({
274
+ event_name: this.eventName,
275
+ timestamp,
276
+ payload: {
277
+ stripe_customer_id: customerId,
278
+ value: event.usage.outputTokens.toString(),
279
+ model,
280
+ token_type: "output",
281
+ reasoning_tokens: (event.usage.reasoningTokens ?? 0).toString(),
282
+ visible_tokens: (event.usage.visibleOutputTokens ?? event.usage.outputTokens).toString(),
283
+ ...event.metadata ? event.metadata : {}
284
+ }
285
+ });
286
+ } catch (e) {
287
+ if (this.debug) console.warn("[vibezcheck] Output meter event error:", e);
288
+ }
289
+ }
290
+ }
291
+ }
292
+ /**
293
+ * Updates internal in-memory ledger
294
+ */
295
+ recordInLedger(event) {
296
+ this.totalRequests += 1;
297
+ this.totalTokens += event.usage.totalTokens;
298
+ this.totalInputTokens += event.usage.inputTokens;
299
+ this.totalOutputTokens += event.usage.outputTokens;
300
+ this.totalReasoningTokens += event.usage.reasoningTokens ?? 0;
301
+ this.totalCostUSD += event.cost.totalUSD;
302
+ const modelKey = event.model;
303
+ if (!this.byModel[modelKey]) {
304
+ this.byModel[modelKey] = { requests: 0, tokens: 0, costUSD: 0 };
305
+ }
306
+ this.byModel[modelKey].requests += 1;
307
+ this.byModel[modelKey].tokens += event.usage.totalTokens;
308
+ this.byModel[modelKey].costUSD += event.cost.totalUSD;
309
+ }
310
+ /**
311
+ * Get in-memory usage summary
312
+ */
313
+ getSummary() {
314
+ return {
315
+ totalRequests: this.totalRequests,
316
+ totalTokens: this.totalTokens,
317
+ totalInputTokens: this.totalInputTokens,
318
+ totalOutputTokens: this.totalOutputTokens,
319
+ totalReasoningTokens: this.totalReasoningTokens,
320
+ totalCostUSD: Number(this.totalCostUSD.toFixed(6)),
321
+ byModel: { ...this.byModel }
322
+ };
323
+ }
324
+ /**
325
+ * Reset in-memory ledger
326
+ */
327
+ resetLedger() {
328
+ this.totalRequests = 0;
329
+ this.totalTokens = 0;
330
+ this.totalInputTokens = 0;
331
+ this.totalOutputTokens = 0;
332
+ this.totalReasoningTokens = 0;
333
+ this.totalCostUSD = 0;
334
+ this.byModel = {};
335
+ }
336
+ };
337
+
338
+ // src/meter/extractors/openai.ts
339
+ function extractOpenAIResponseUsage(response) {
340
+ if (!response || typeof response !== "object") return null;
341
+ if ("choices" in response && "usage" in response && response.usage) {
342
+ const rawUsage = response.usage;
343
+ const model = response.model || "gpt-4o";
344
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
345
+ const outputTokens = rawUsage.completion_tokens ?? 0;
346
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
347
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
348
+ return {
349
+ model,
350
+ provider: "openai",
351
+ usage: {
352
+ inputTokens,
353
+ outputTokens,
354
+ totalTokens: inputTokens + outputTokens,
355
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
356
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
357
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
358
+ }
359
+ };
360
+ }
361
+ if ("data" in response && "usage" in response && response.usage && "model" in response) {
362
+ const rawUsage = response.usage;
363
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
364
+ return {
365
+ model: response.model || "text-embedding-3-small",
366
+ provider: "openai",
367
+ usage: {
368
+ inputTokens,
369
+ outputTokens: 0,
370
+ totalTokens: inputTokens
371
+ }
372
+ };
373
+ }
374
+ if ("status" in response && "usage" in response && response.usage) {
375
+ const rawUsage = response.usage;
376
+ const model = response.model || "gpt-5.6-sol";
377
+ const inputTokens = rawUsage.input_tokens ?? rawUsage.prompt_tokens ?? 0;
378
+ const outputTokens = rawUsage.output_tokens ?? rawUsage.completion_tokens ?? 0;
379
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
380
+ const cachedTokens = rawUsage.input_token_details?.cached_tokens ?? rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
381
+ return {
382
+ model,
383
+ provider: "openai",
384
+ usage: {
385
+ inputTokens,
386
+ outputTokens,
387
+ totalTokens: inputTokens + outputTokens,
388
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
389
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
390
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
391
+ }
392
+ };
393
+ }
394
+ return null;
395
+ }
396
+ function inspectOpenAIStreamChunk(chunk) {
397
+ if (!chunk || typeof chunk !== "object") return {};
398
+ const model = chunk.model;
399
+ const rawUsage = chunk.usage || chunk.token_usage || chunk.x_groq?.usage || chunk.usageMetadata;
400
+ if (rawUsage) {
401
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? rawUsage.promptTokens ?? rawUsage.inputTokens ?? rawUsage.promptTokenCount ?? 0;
402
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? rawUsage.completionTokens ?? rawUsage.outputTokens ?? rawUsage.candidatesTokenCount ?? 0;
403
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.reasoning_tokens ?? rawUsage.reasoningTokens ?? rawUsage.thoughtsTokenCount ?? 0;
404
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? rawUsage.cached_tokens ?? rawUsage.cachedTokens ?? rawUsage.cachedContentTokenCount ?? 0;
405
+ return {
406
+ model,
407
+ usage: {
408
+ inputTokens,
409
+ outputTokens,
410
+ totalTokens: inputTokens + outputTokens,
411
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
412
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
413
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
414
+ }
415
+ };
416
+ }
417
+ if (chunk.type === "response.completed" || chunk.type === "response.done") {
418
+ if (chunk.response?.usage) {
419
+ const rawUsage2 = chunk.response.usage;
420
+ const inputTokens = rawUsage2.input_tokens ?? 0;
421
+ const outputTokens = rawUsage2.output_tokens ?? 0;
422
+ const reasoningTokens = rawUsage2.output_token_details?.reasoning_tokens ?? 0;
423
+ const cachedTokens = rawUsage2.input_token_details?.cached_tokens ?? 0;
424
+ return {
425
+ model: chunk.response.model || model,
426
+ usage: {
427
+ inputTokens,
428
+ outputTokens,
429
+ totalTokens: inputTokens + outputTokens,
430
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
431
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
432
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
433
+ }
434
+ };
435
+ }
436
+ }
437
+ return { model };
438
+ }
439
+
440
+ // src/meter/extractors/anthropic.ts
441
+ function extractAnthropicResponseUsage(response) {
442
+ if (!response || typeof response !== "object") return null;
443
+ if (response.type === "message" || "content" in response && "usage" in response) {
444
+ const rawUsage = response.usage || {};
445
+ const model = response.model || "claude-3-7-sonnet";
446
+ const inputTokens = rawUsage.input_tokens ?? 0;
447
+ const outputTokens = rawUsage.output_tokens ?? 0;
448
+ const cachedTokens = rawUsage.cache_read_input_tokens ?? 0;
449
+ const cacheWriteTokens = rawUsage.cache_creation_input_tokens ?? 0;
450
+ let reasoningTokens = void 0;
451
+ if (Array.isArray(response.content)) {
452
+ const thinkingBlocks = response.content.filter((b) => b.type === "thinking");
453
+ if (thinkingBlocks.length > 0) {
454
+ reasoningTokens = rawUsage.thinking_tokens ?? void 0;
455
+ }
456
+ }
457
+ return {
458
+ model,
459
+ provider: "anthropic",
460
+ usage: {
461
+ inputTokens,
462
+ outputTokens,
463
+ totalTokens: inputTokens + outputTokens,
464
+ reasoningTokens,
465
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
466
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0,
467
+ cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : void 0
468
+ }
469
+ };
470
+ }
471
+ return null;
472
+ }
473
+ var AnthropicStreamAccumulator = class {
474
+ model = "claude-3-7-sonnet";
475
+ inputTokens = 0;
476
+ outputTokens = 0;
477
+ cachedTokens = 0;
478
+ cacheWriteTokens = 0;
479
+ reasoningTokens = 0;
480
+ processEvent(event) {
481
+ if (!event || typeof event !== "object") return;
482
+ if (event.type === "message_start" && event.message) {
483
+ if (event.message.model) {
484
+ this.model = event.message.model;
485
+ }
486
+ if (event.message.usage) {
487
+ this.inputTokens = event.message.usage.input_tokens ?? 0;
488
+ this.cachedTokens = event.message.usage.cache_read_input_tokens ?? 0;
489
+ this.cacheWriteTokens = event.message.usage.cache_creation_input_tokens ?? 0;
490
+ }
491
+ }
492
+ if (event.type === "message_delta" && event.usage) {
493
+ this.outputTokens = event.usage.output_tokens ?? 0;
494
+ if (event.usage.thinking_tokens) {
495
+ this.reasoningTokens = event.usage.thinking_tokens;
496
+ }
497
+ }
498
+ if (event.type === "content_block_start" && event.content_block?.type === "thinking") {
499
+ }
500
+ }
501
+ getUsage() {
502
+ return {
503
+ model: this.model,
504
+ provider: "anthropic",
505
+ usage: {
506
+ inputTokens: this.inputTokens,
507
+ outputTokens: this.outputTokens,
508
+ totalTokens: this.inputTokens + this.outputTokens,
509
+ reasoningTokens: this.reasoningTokens > 0 ? this.reasoningTokens : void 0,
510
+ visibleOutputTokens: this.reasoningTokens > 0 ? Math.max(0, this.outputTokens - this.reasoningTokens) : this.outputTokens,
511
+ cachedTokens: this.cachedTokens > 0 ? this.cachedTokens : void 0,
512
+ cacheWriteTokens: this.cacheWriteTokens > 0 ? this.cacheWriteTokens : void 0
513
+ }
514
+ };
515
+ }
516
+ };
517
+
518
+ // src/meter/extractors/gemini.ts
519
+ function extractGeminiResponseUsage(response, fallbackModel = "gemini-3.7-flash") {
520
+ if (!response || typeof response !== "object") return null;
521
+ const usageMetadata = response.usageMetadata || response.response?.usageMetadata;
522
+ if (usageMetadata) {
523
+ const inputTokens = usageMetadata.promptTokenCount ?? 0;
524
+ const baseOutputTokens = usageMetadata.candidatesTokenCount ?? 0;
525
+ const thoughtsTokenCount = usageMetadata.thoughtsTokenCount ?? usageMetadata.reasoningTokenCount ?? 0;
526
+ const cachedTokens = usageMetadata.cachedContentTokenCount ?? 0;
527
+ const totalOutput = baseOutputTokens + thoughtsTokenCount;
528
+ const model = response.model || response.response?.model || fallbackModel;
529
+ return {
530
+ model,
531
+ provider: "google",
532
+ usage: {
533
+ inputTokens,
534
+ outputTokens: totalOutput,
535
+ totalTokens: inputTokens + totalOutput,
536
+ reasoningTokens: thoughtsTokenCount > 0 ? thoughtsTokenCount : void 0,
537
+ visibleOutputTokens: baseOutputTokens,
538
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
539
+ }
540
+ };
541
+ }
542
+ return null;
543
+ }
544
+
545
+ // src/meter/extractors/generic.ts
546
+ function extractGenericResponseUsage(response, fallbackModel = "generic-llm", fallbackProvider = "generic") {
547
+ if (!response || typeof response !== "object") return null;
548
+ const usage = response.usage || response.token_usage || response.usageMetadata;
549
+ if (usage) {
550
+ const inputTokens = usage.prompt_tokens ?? usage.input_tokens ?? usage.promptTokenCount ?? usage.prompt_eval_count ?? 0;
551
+ const outputTokens = usage.completion_tokens ?? usage.output_tokens ?? usage.candidatesTokenCount ?? usage.eval_count ?? 0;
552
+ const reasoningTokens = usage.reasoning_tokens ?? usage.thoughtsTokenCount ?? usage.completion_tokens_details?.reasoning_tokens ?? 0;
553
+ const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens ?? usage.cachedContentTokenCount ?? 0;
554
+ const model = response.model || fallbackModel;
555
+ const provider = response.provider || fallbackProvider;
556
+ return {
557
+ model,
558
+ provider,
559
+ usage: {
560
+ inputTokens,
561
+ outputTokens,
562
+ totalTokens: inputTokens + outputTokens,
563
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
564
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
565
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
566
+ }
567
+ };
568
+ }
569
+ return null;
570
+ }
571
+
572
+ // src/meter/extractors/index.ts
573
+ function detectAndExtractUsage(response, fallbackModel, fallbackProvider) {
574
+ if (!response || typeof response !== "object") return null;
575
+ const openaiResult = extractOpenAIResponseUsage(response);
576
+ if (openaiResult) return openaiResult;
577
+ const anthropicResult = extractAnthropicResponseUsage(response);
578
+ if (anthropicResult) return anthropicResult;
579
+ const geminiResult = extractGeminiResponseUsage(response, fallbackModel);
580
+ if (geminiResult) return geminiResult;
581
+ const genericResult = extractGenericResponseUsage(response, fallbackModel, fallbackProvider);
582
+ if (genericResult) return genericResult;
583
+ return null;
584
+ }
585
+
586
+ // src/pricing/table.ts
587
+ var MODEL_PRICING_TABLE = {
588
+ // --- OpenAI (Modern & Reasoning) ---
589
+ "gpt-5.6-sol": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
590
+ "gpt-5.6-terra": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.2 },
591
+ "gpt-5.6-luna": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
592
+ "gpt-5": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
593
+ "gpt-5-mini": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
594
+ "o1": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
595
+ "o1-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
596
+ "o3": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
597
+ "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
598
+ "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10, cachedInputPer1M: 1.25 },
599
+ "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.075 },
600
+ "gpt-4.5": { inputPer1M: 75, outputPer1M: 150, cachedInputPer1M: 37.5 },
601
+ "gpt-4.5-preview": { inputPer1M: 75, outputPer1M: 150, cachedInputPer1M: 37.5 },
602
+ "chatgpt-4o-latest": { inputPer1M: 5, outputPer1M: 15 },
603
+ "gpt-4.1": { inputPer1M: 2, outputPer1M: 8, cachedInputPer1M: 1 },
604
+ "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.05 },
605
+ // --- OpenAI (Legacy & Backward Compatibility) ---
606
+ "gpt-4-turbo": { inputPer1M: 10, outputPer1M: 30, cachedInputPer1M: 5 },
607
+ "gpt-4-turbo-preview": { inputPer1M: 10, outputPer1M: 30, cachedInputPer1M: 5 },
608
+ "gpt-4": { inputPer1M: 30, outputPer1M: 60 },
609
+ "gpt-4-32k": { inputPer1M: 60, outputPer1M: 120 },
610
+ "gpt-3.5-turbo": { inputPer1M: 0.5, outputPer1M: 1.5 },
611
+ "gpt-3.5-turbo-16k": { inputPer1M: 3, outputPer1M: 4 },
612
+ "text-embedding-3-small": { inputPer1M: 0.02, outputPer1M: 0 },
613
+ "text-embedding-3-large": { inputPer1M: 0.13, outputPer1M: 0 },
614
+ "text-embedding-ada-002": { inputPer1M: 0.1, outputPer1M: 0 },
615
+ // --- Anthropic (Modern & Extended Thinking) ---
616
+ "claude-3-7-sonnet": { inputPer1M: 0.59, outputPer1M: 2.93, cachedInputPer1M: 0.3 },
617
+ "claude-sonnet-5": { inputPer1M: 2, outputPer1M: 10, cachedInputPer1M: 0.3 },
618
+ "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
619
+ "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4, cachedInputPer1M: 0.08 },
620
+ "haiku-4.5": { inputPer1M: 1, outputPer1M: 5, cachedInputPer1M: 0.1 },
621
+ "claude-opus-5": { inputPer1M: 5, outputPer1M: 25, cachedInputPer1M: 1.5 },
622
+ "claude-3-opus": { inputPer1M: 15, outputPer1M: 75, cachedInputPer1M: 1.5 },
623
+ // --- Anthropic (Legacy & Backward Compatibility) ---
624
+ "claude-3-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
625
+ "claude-3-haiku": { inputPer1M: 0.25, outputPer1M: 1.25, cachedInputPer1M: 0.025 },
626
+ "claude-2.1": { inputPer1M: 8, outputPer1M: 24 },
627
+ "claude-2.0": { inputPer1M: 8, outputPer1M: 24 },
628
+ "claude-instant-1.2": { inputPer1M: 1.63, outputPer1M: 5.51 },
629
+ // --- Google Gemini (Modern & Thoughts) ---
630
+ "gemini-3.7-flash": { inputPer1M: 0.75, outputPer1M: 3.75, cachedInputPer1M: 0.18 },
631
+ "gemini-3.1-pro": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.5 },
632
+ "gemini-3.5-flash": { inputPer1M: 1.5, outputPer1M: 9, cachedInputPer1M: 0.38 },
633
+ "gemini-3.1-flash-lite": { inputPer1M: 0.25, outputPer1M: 1.5, cachedInputPer1M: 0.06 },
634
+ "gemini-2.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
635
+ "gemini-2.5-flash": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.0375 },
636
+ "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.025 },
637
+ "gemini-2.0-flash-lite": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
638
+ "gemini-2.0-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
639
+ // --- Google Gemini (Legacy & Backward Compatibility) ---
640
+ "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
641
+ "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
642
+ "gemini-1.5-flash-8b": { inputPer1M: 0.0375, outputPer1M: 0.15, cachedInputPer1M: 9375e-6 },
643
+ "gemini-1.0-pro": { inputPer1M: 0.5, outputPer1M: 1.5 },
644
+ // --- xAI Grok ---
645
+ "grok-4.6": { inputPer1M: 3, outputPer1M: 15 },
646
+ "grok-3": { inputPer1M: 3, outputPer1M: 15 },
647
+ "grok-3-mini": { inputPer1M: 0.3, outputPer1M: 1.5 },
648
+ "grok-2": { inputPer1M: 2, outputPer1M: 10 },
649
+ "grok-2-vision": { inputPer1M: 2, outputPer1M: 10 },
650
+ "grok-beta": { inputPer1M: 5, outputPer1M: 15 },
651
+ // --- Mistral ---
652
+ "mistral-large-3": { inputPer1M: 2, outputPer1M: 6 },
653
+ "mistral-large-latest": { inputPer1M: 2, outputPer1M: 6 },
654
+ "mistral-large-2411": { inputPer1M: 2, outputPer1M: 6 },
655
+ "codestral-latest": { inputPer1M: 0.3, outputPer1M: 0.9 },
656
+ "mistral-medium-latest": { inputPer1M: 2.7, outputPer1M: 8.1 },
657
+ "mistral-small-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
658
+ "ministral-8b-latest": { inputPer1M: 0.1, outputPer1M: 0.1 },
659
+ "ministral-3b-latest": { inputPer1M: 0.04, outputPer1M: 0.04 },
660
+ "open-mistral-7b": { inputPer1M: 0.2, outputPer1M: 0.2 },
661
+ "open-mixtral-8x7b": { inputPer1M: 0.7, outputPer1M: 0.7 },
662
+ "open-mixtral-8x22b": { inputPer1M: 2, outputPer1M: 6 },
663
+ // --- Groq & Meta Llama LPUs ---
664
+ "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
665
+ "llama-3.1-405b": { inputPer1M: 3, outputPer1M: 3 },
666
+ "llama-3.1-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
667
+ "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
668
+ "llama-3.2-1b-preview": { inputPer1M: 0.04, outputPer1M: 0.04 },
669
+ "llama-3.2-3b-preview": { inputPer1M: 0.06, outputPer1M: 0.06 },
670
+ "llama-3.2-11b-vision": { inputPer1M: 0.18, outputPer1M: 0.18 },
671
+ "llama-3.2-90b-vision": { inputPer1M: 0.9, outputPer1M: 0.9 },
672
+ "deepseek-r1-distill-llama-70b": { inputPer1M: 0.75, outputPer1M: 0.99 },
673
+ "deepseek-r1-distill-qwen-32b": { inputPer1M: 0.49, outputPer1M: 0.49 },
674
+ "qwen-2.5-32b": { inputPer1M: 0.29, outputPer1M: 0.39 },
675
+ "qwen-2.5-72b": { inputPer1M: 0.35, outputPer1M: 0.4 },
676
+ "mixtral-8x7b-32768": { inputPer1M: 0.24, outputPer1M: 0.24 },
677
+ "gemma2-9b-it": { inputPer1M: 0.2, outputPer1M: 0.2 },
678
+ // --- DeepSeek ---
679
+ "deepseek-v4-pro": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
680
+ "deepseek-v4-flash": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
681
+ "deepseek-v3": { inputPer1M: 0.14, outputPer1M: 0.28, cachedInputPer1M: 0.014 },
682
+ "deepseek-chat": { inputPer1M: 0.14, outputPer1M: 0.28, cachedInputPer1M: 0.014 },
683
+ "deepseek-r1": { inputPer1M: 0.55, outputPer1M: 2.19, cachedInputPer1M: 0.14 },
684
+ "deepseek-reasoner": { inputPer1M: 0.55, outputPer1M: 2.19, cachedInputPer1M: 0.14 },
685
+ // --- Cohere ---
686
+ "command-r-plus": { inputPer1M: 2.5, outputPer1M: 10 },
687
+ "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 },
688
+ "command": { inputPer1M: 1, outputPer1M: 2 },
689
+ "command-light": { inputPer1M: 0.3, outputPer1M: 0.6 },
690
+ "embed-english-v3.0": { inputPer1M: 0.1, outputPer1M: 0 },
691
+ // --- Perplexity ---
692
+ "sonar": { inputPer1M: 1, outputPer1M: 1 },
693
+ "sonar-pro": { inputPer1M: 3, outputPer1M: 15 },
694
+ "sonar-reasoning": { inputPer1M: 1, outputPer1M: 5 },
695
+ "sonar-reasoning-pro": { inputPer1M: 2, outputPer1M: 8 }
696
+ };
697
+ var MODEL_ALIASES = {
698
+ // OpenAI Shorthands & Aliases
699
+ "gpt4": "gpt-4",
700
+ "gpt4o": "gpt-4o",
701
+ "gpt-4-preview": "gpt-4-turbo",
702
+ "gpt-4-0125-preview": "gpt-4-turbo",
703
+ "gpt-4-1106-preview": "gpt-4-turbo",
704
+ "gpt-3.5": "gpt-3.5-turbo",
705
+ "gpt-3.5-turbo-0125": "gpt-3.5-turbo",
706
+ "gpt-3.5-turbo-1106": "gpt-3.5-turbo",
707
+ "gpt-3.5-turbo-16k-0613": "gpt-3.5-turbo-16k",
708
+ // Anthropic Shorthands
709
+ "sonnet": "claude-3-5-sonnet",
710
+ "sonnet-3.7": "claude-3-7-sonnet",
711
+ "sonnet-3.5": "claude-3-5-sonnet",
712
+ "haiku": "claude-3-5-haiku",
713
+ "haiku-3.5": "claude-3-5-haiku",
714
+ "opus": "claude-3-opus",
715
+ "claude-2": "claude-2.0",
716
+ "claude-instant": "claude-instant-1.2",
717
+ // DeepSeek Shorthands
718
+ "r1": "deepseek-r1",
719
+ "v3": "deepseek-v3",
720
+ // Gemini Shorthands
721
+ "flash": "gemini-2.0-flash",
722
+ "pro": "gemini-1.5-pro",
723
+ // Meta / Groq Shorthands
724
+ "llama-3.3-70b": "llama-3.3-70b-versatile",
725
+ "llama-3.1-70b": "llama-3.1-70b-versatile",
726
+ "llama-3.1-8b": "llama-3.1-8b-instant",
727
+ "llama-3-70b": "llama-3.1-70b-versatile",
728
+ "llama-3-8b": "llama-3.1-8b-instant",
729
+ // Mistral Shorthands
730
+ "codestral": "codestral-latest",
731
+ "mistral-large": "mistral-large-latest",
732
+ "mistral-small": "mistral-small-latest"
733
+ };
734
+ var customPricingRegistry = {};
735
+ function normalizeModelKey(rawModel) {
736
+ if (!rawModel) return "unknown";
737
+ let model = rawModel.toLowerCase().trim();
738
+ model = model.replace(/^[a-z0-9_-]+\.(anthropic|meta|amazon|cohere|mistral|ai21)\./i, "");
739
+ model = model.replace(/^(anthropic|meta|amazon|cohere|mistral|ai21)\./i, "");
740
+ model = model.replace(/-v\d+(:\d+)?$/, "");
741
+ model = model.replace(/:\d+$/, "");
742
+ if (model.includes("/")) {
743
+ model = model.split("/").slice(1).join("/");
744
+ }
745
+ model = model.replace(/:(latest|free|beta)$/, "");
746
+ model = model.replace(/-\d{8}$/, "");
747
+ model = model.replace(/-\d{4}-\d{2}-\d{2}$/, "");
748
+ model = model.replace(/llama(\d+)-(\d+)-/g, "llama-$1.$2-");
749
+ model = model.replace(/llama(\d+)\.(\d+)-/g, "llama-$1.$2-");
750
+ if (MODEL_ALIASES[model]) {
751
+ return MODEL_ALIASES[model];
752
+ }
753
+ if (!MODEL_PRICING_TABLE[model]) {
754
+ const withoutInstruct = model.replace(/-(instruct|chat|preview)$/, "");
755
+ if (MODEL_PRICING_TABLE[withoutInstruct]) {
756
+ return withoutInstruct;
757
+ }
758
+ if (MODEL_ALIASES[withoutInstruct]) {
759
+ return MODEL_ALIASES[withoutInstruct];
760
+ }
761
+ }
762
+ return model;
763
+ }
764
+ function getModelPricing(modelName) {
765
+ const normalized = normalizeModelKey(modelName);
766
+ if (customPricingRegistry[normalized]) {
767
+ return customPricingRegistry[normalized];
768
+ }
769
+ if (customPricingRegistry[modelName]) {
770
+ return customPricingRegistry[modelName];
771
+ }
772
+ if (MODEL_PRICING_TABLE[normalized]) {
773
+ return MODEL_PRICING_TABLE[normalized];
774
+ }
775
+ if (MODEL_PRICING_TABLE[modelName]) {
776
+ return MODEL_PRICING_TABLE[modelName];
777
+ }
778
+ const alias = MODEL_ALIASES[modelName.toLowerCase().trim()];
779
+ if (alias && MODEL_PRICING_TABLE[alias]) {
780
+ return MODEL_PRICING_TABLE[alias];
781
+ }
782
+ return {
783
+ inputPer1M: 1,
784
+ outputPer1M: 3,
785
+ cachedInputPer1M: 0.5
786
+ };
787
+ }
788
+
789
+ // src/pricing/calculator.ts
790
+ function calculateCost(params) {
791
+ let rates;
792
+ if (params.customRate) {
793
+ const outRate = params.customRate.out ?? params.customRate.output ?? 0;
794
+ rates = {
795
+ inputPer1M: params.customRate.in,
796
+ outputPer1M: outRate,
797
+ reasoningPer1M: params.customRate.reasoning ?? outRate,
798
+ cachedInputPer1M: params.customRate.cached ?? params.customRate.in * 0.15,
799
+ currency: "USD"
800
+ };
801
+ } else {
802
+ rates = getModelPricing(params.model);
803
+ }
804
+ const inputTokens = BigInt(Math.max(0, params.inputTokens ?? 0));
805
+ const outputTokens = BigInt(Math.max(0, params.outputTokens ?? 0));
806
+ const reasoningTokens = BigInt(Math.max(0, params.reasoningTokens ?? 0));
807
+ const cachedTokens = BigInt(Math.max(0, params.cachedTokens ?? 0));
808
+ const regularInputTokens = inputTokens > cachedTokens ? inputTokens - cachedTokens : 0n;
809
+ const rateInputNano = BigInt(Math.round(rates.inputPer1M * 1e3));
810
+ const cachedPer1M = rates.cachedInputPer1M ?? rates.inputPer1M * 0.15;
811
+ const rateCachedNano = BigInt(Math.round(cachedPer1M * 1e3));
812
+ const rateOutputNano = BigInt(Math.round(rates.outputPer1M * 1e3));
813
+ const reasoningPer1M = rates.reasoningPer1M ?? rates.outputPer1M;
814
+ const rateReasoningNano = BigInt(Math.round(reasoningPer1M * 1e3));
815
+ const regularInputCostNano = regularInputTokens * rateInputNano;
816
+ const cachedInputCostNano = cachedTokens * rateCachedNano;
817
+ const inputCostNano = regularInputCostNano + cachedInputCostNano;
818
+ const outputCostNano = outputTokens * rateOutputNano;
819
+ const reasoningCostNano = reasoningTokens * rateReasoningNano;
820
+ const standardCacheCostNano = cachedTokens * rateInputNano;
821
+ const cachedDiscountNano = standardCacheCostNano > cachedInputCostNano ? standardCacheCostNano - cachedInputCostNano : 0n;
822
+ const wholesaleNano = inputCostNano + outputCostNano;
823
+ const markup = params.markupMultiplier ?? 1;
824
+ let billedNano = wholesaleNano;
825
+ let hasRetail = false;
826
+ if (markup !== 1 || params.minimumChargeUSD !== void 0) {
827
+ hasRetail = true;
828
+ const markupMultiplierNano = BigInt(Math.round(markup * 1e3));
829
+ billedNano = wholesaleNano * markupMultiplierNano / 1000n;
830
+ if (params.minimumChargeUSD !== void 0 && params.minimumChargeUSD > 0) {
831
+ const minChargeNano = BigInt(Math.round(params.minimumChargeUSD * 1e9));
832
+ if (billedNano < minChargeNano) {
833
+ billedNano = minChargeNano;
834
+ }
835
+ }
836
+ }
837
+ const inputCostUSD = Number(inputCostNano) / 1e9;
838
+ const outputCostUSD = Number(outputCostNano) / 1e9;
839
+ const reasoningCostUSD = Number(reasoningCostNano) / 1e9;
840
+ const cachedDiscountUSD = Number(cachedDiscountNano) / 1e9;
841
+ const totalUSD = Number(wholesaleNano) / 1e9;
842
+ const wholesaleTotalUSD = totalUSD;
843
+ const billedUSD = Number(billedNano) / 1e9;
844
+ const profitUSD = Math.max(0, billedUSD - wholesaleTotalUSD);
845
+ const retailUSD = hasRetail ? billedUSD : void 0;
846
+ return {
847
+ inputCostUSD: Number(inputCostUSD.toFixed(8)),
848
+ outputCostUSD: Number(outputCostUSD.toFixed(8)),
849
+ reasoningCostUSD: reasoningTokens > 0n ? Number(reasoningCostUSD.toFixed(8)) : void 0,
850
+ cachedDiscountUSD: cachedTokens > 0n ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
851
+ totalUSD: Number(totalUSD.toFixed(8)),
852
+ wholesaleTotalUSD: Number(wholesaleTotalUSD.toFixed(8)),
853
+ billedUSD: Number(billedUSD.toFixed(8)),
854
+ profitUSD: Number(profitUSD.toFixed(8)),
855
+ retailUSD: retailUSD !== void 0 ? Number(retailUSD.toFixed(8)) : void 0,
856
+ currency: rates.currency || "USD"
857
+ };
858
+ }
859
+ function calculateUsageCost(model, usage, optionsOrMarkup) {
860
+ const options = typeof optionsOrMarkup === "number" ? { markupMultiplier: optionsOrMarkup } : optionsOrMarkup || {};
861
+ return calculateCost({
862
+ model,
863
+ inputTokens: usage.inputTokens,
864
+ outputTokens: usage.outputTokens,
865
+ reasoningTokens: usage.reasoningTokens,
866
+ cachedTokens: usage.cachedTokens,
867
+ cacheWriteTokens: usage.cacheWriteTokens,
868
+ markupMultiplier: options.markupMultiplier,
869
+ minimumChargeUSD: options.minimumChargeUSD,
870
+ customRate: options.customRate
871
+ });
872
+ }
873
+
874
+ // src/customers/helpers.ts
875
+ function normalizeCustomer(customer, extraCustomerId) {
876
+ if (!customer && !extraCustomerId) {
877
+ return {
878
+ customerId: void 0,
879
+ customerEmail: void 0,
880
+ customerObj: void 0,
881
+ customerMetadata: {}
882
+ };
883
+ }
884
+ if (typeof customer === "string") {
885
+ const isEmail = customer.includes("@");
886
+ const customerObj2 = {
887
+ id: customer,
888
+ email: isEmail ? customer : void 0
889
+ };
890
+ return {
891
+ customerId: customer,
892
+ customerEmail: isEmail ? customer : void 0,
893
+ customerObj: customerObj2,
894
+ customerMetadata: {}
895
+ };
896
+ }
897
+ const customerObj = customer || (extraCustomerId ? { id: extraCustomerId } : void 0);
898
+ const customerId = customerObj?.id || customerObj?.userId || extraCustomerId;
899
+ const customerEmail = customerObj?.email;
900
+ const customerMetadata = {};
901
+ if (customerObj) {
902
+ const orgId = customerObj.orgId || customerObj.organizationId;
903
+ if (orgId) customerMetadata.org_id = String(orgId);
904
+ const teamId = customerObj.teamId || customerObj.workspaceId;
905
+ if (teamId) customerMetadata.team_id = String(teamId);
906
+ if (customerObj.plan) customerMetadata.plan = String(customerObj.plan);
907
+ if (customerObj.tier) customerMetadata.tier = String(customerObj.tier);
908
+ if (customerObj.role) customerMetadata.role = String(customerObj.role);
909
+ if (customerObj.orgName) customerMetadata.org_name = String(customerObj.orgName);
910
+ if (customerObj.metadata) {
911
+ for (const [key, val] of Object.entries(customerObj.metadata)) {
912
+ if (val !== null && val !== void 0) {
913
+ customerMetadata[key] = val;
914
+ }
915
+ }
916
+ }
917
+ }
918
+ return {
919
+ customerId,
920
+ customerEmail,
921
+ customerObj,
922
+ customerMetadata
923
+ };
924
+ }
925
+
926
+ // src/meter/stream.ts
927
+ function wrapOpenAIStream(stream, options, onComplete) {
928
+ let detectedModel = options.model || "gpt-4o";
929
+ let finalUsage = null;
930
+ const wrappedAsyncIterable = {
931
+ async *[Symbol.asyncIterator]() {
932
+ try {
933
+ for await (const chunk of stream) {
934
+ const inspected = inspectOpenAIStreamChunk(chunk);
935
+ if (inspected.model) {
936
+ detectedModel = inspected.model;
937
+ }
938
+ if (inspected.usage) {
939
+ finalUsage = inspected.usage;
940
+ }
941
+ yield chunk;
942
+ }
943
+ } finally {
944
+ if (finalUsage) {
945
+ const cost = calculateUsageCost(detectedModel, finalUsage);
946
+ const normalized = normalizeCustomer(options.customer, options.customerId);
947
+ const event = {
948
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
949
+ model: detectedModel,
950
+ provider: "openai",
951
+ usage: finalUsage,
952
+ cost,
953
+ customerId: normalized.customerId,
954
+ customerEmail: normalized.customerEmail,
955
+ customer: normalized.customerObj,
956
+ metadata: {
957
+ ...normalized.customerMetadata,
958
+ ...options.metadata
959
+ }
960
+ };
961
+ onComplete(event);
962
+ if (options.onUsage) {
963
+ options.onUsage(event);
964
+ }
965
+ }
966
+ }
967
+ }
968
+ };
969
+ return wrappedAsyncIterable;
970
+ }
971
+ function wrapAnthropicStream(stream, options, onComplete) {
972
+ const accumulator = new AnthropicStreamAccumulator();
973
+ const wrappedAsyncIterable = {
974
+ async *[Symbol.asyncIterator]() {
975
+ try {
976
+ for await (const event of stream) {
977
+ accumulator.processEvent(event);
978
+ yield event;
979
+ }
980
+ } finally {
981
+ const extracted = accumulator.getUsage();
982
+ const model = options.model || extracted.model;
983
+ const cost = calculateUsageCost(model, extracted.usage);
984
+ const normalized = normalizeCustomer(options.customer, options.customerId);
985
+ const usageEvent = {
986
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
987
+ model,
988
+ provider: "anthropic",
989
+ usage: extracted.usage,
990
+ cost,
991
+ customerId: normalized.customerId,
992
+ customerEmail: normalized.customerEmail,
993
+ customer: normalized.customerObj,
994
+ metadata: {
995
+ ...normalized.customerMetadata,
996
+ ...options.metadata
997
+ }
998
+ };
999
+ onComplete(usageEvent);
1000
+ if (options.onUsage) {
1001
+ options.onUsage(usageEvent);
1002
+ }
1003
+ }
1004
+ }
1005
+ };
1006
+ return wrappedAsyncIterable;
1007
+ }
1008
+ function wrapGeminiStream(result, options, onComplete) {
1009
+ if (!result || !result.stream) return result;
1010
+ const originalStream = result.stream;
1011
+ const model = options.model || "gemini-3.7-flash";
1012
+ let lastChunkWithUsage = null;
1013
+ const wrappedStream = (async function* () {
1014
+ try {
1015
+ for await (const chunk of originalStream) {
1016
+ if (chunk.usageMetadata) {
1017
+ lastChunkWithUsage = chunk;
1018
+ }
1019
+ yield chunk;
1020
+ }
1021
+ } finally {
1022
+ if (lastChunkWithUsage) {
1023
+ const extracted = extractGeminiResponseUsage(lastChunkWithUsage, model);
1024
+ if (extracted) {
1025
+ const cost = calculateUsageCost(extracted.model, extracted.usage);
1026
+ const normalized = normalizeCustomer(options.customer, options.customerId);
1027
+ const event = {
1028
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1029
+ model: extracted.model,
1030
+ provider: "google",
1031
+ usage: extracted.usage,
1032
+ cost,
1033
+ customerId: normalized.customerId,
1034
+ customerEmail: normalized.customerEmail,
1035
+ customer: normalized.customerObj,
1036
+ metadata: {
1037
+ ...normalized.customerMetadata,
1038
+ ...options.metadata
1039
+ }
1040
+ };
1041
+ onComplete(event);
1042
+ if (options.onUsage) {
1043
+ options.onUsage(event);
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+ })();
1049
+ return {
1050
+ ...result,
1051
+ stream: wrappedStream
1052
+ };
1053
+ }
1054
+ function wrapUniversalStream(stream, options = {}, onComplete) {
1055
+ if (!stream || typeof stream !== "object") return stream;
1056
+ if ("stream" in stream && "response" in stream) {
1057
+ return wrapGeminiStream(stream, options, onComplete);
1058
+ }
1059
+ if (Symbol.asyncIterator in stream) {
1060
+ if (options.provider === "anthropic" || options.model?.toLowerCase().includes("claude")) {
1061
+ return wrapAnthropicStream(stream, options, onComplete);
1062
+ }
1063
+ return wrapOpenAIStream(stream, options, onComplete);
1064
+ }
1065
+ return stream;
1066
+ }
1067
+
1068
+ // src/meter/client.ts
1069
+ var VibezMeter = class {
1070
+ batcher;
1071
+ stripeClient;
1072
+ markupMultiplier;
1073
+ constructor(options = {}) {
1074
+ this.markupMultiplier = options.markupMultiplier;
1075
+ if (options.stripe) {
1076
+ this.stripeClient = options.stripe;
1077
+ } else if (options.apiKey || process.env.STRIPE_SECRET_KEY) {
1078
+ const key = options.apiKey || process.env.STRIPE_SECRET_KEY;
1079
+ this.stripeClient = new import_stripe2.default(key, {
1080
+ appInfo: {
1081
+ name: "vibezcheck",
1082
+ version: "0.5.3",
1083
+ url: "https://vibezcheck.xyz"
1084
+ }
1085
+ });
1086
+ }
1087
+ this.batcher = new MeterBatcher({
1088
+ ...options,
1089
+ stripe: this.stripeClient
1090
+ });
1091
+ }
1092
+ /**
1093
+ * Track token usage from a non-streaming response object (OpenAI, Anthropic, Gemini, etc.)
1094
+ */
1095
+ trackUsage(response, options = {}) {
1096
+ const extracted = detectAndExtractUsage(response, options.model, options.provider);
1097
+ if (!extracted) {
1098
+ return null;
1099
+ }
1100
+ const model = options.model || extracted.model;
1101
+ const cost = calculateUsageCost(model, extracted.usage, this.markupMultiplier);
1102
+ const normalized = normalizeCustomer(options.customer, options.customerId);
1103
+ const mergedMeta = {
1104
+ ...normalized.customerMetadata,
1105
+ ...options.metadata
1106
+ };
1107
+ const event = {
1108
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1109
+ model,
1110
+ provider: extracted.provider,
1111
+ usage: extracted.usage,
1112
+ cost,
1113
+ customerId: normalized.customerId,
1114
+ customerEmail: normalized.customerEmail,
1115
+ customer: normalized.customerObj,
1116
+ metadata: mergedMeta
1117
+ };
1118
+ this.batcher.enqueue(event);
1119
+ return event;
1120
+ }
1121
+ /**
1122
+ * Wrap any LLM stream (OpenAI, Anthropic, Gemini) with zero added latency
1123
+ */
1124
+ wrapStream(stream, options = {}) {
1125
+ return wrapUniversalStream(stream, options, (event) => {
1126
+ this.batcher.enqueue(event);
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Directly record token usage manually
1131
+ */
1132
+ recordUsage(options) {
1133
+ const inputTokens = options.inputTokens ?? 0;
1134
+ const outputTokens = options.outputTokens ?? 0;
1135
+ const reasoningTokens = options.reasoningTokens;
1136
+ const cachedTokens = options.cachedTokens;
1137
+ const usage = {
1138
+ inputTokens,
1139
+ outputTokens,
1140
+ totalTokens: inputTokens + outputTokens,
1141
+ reasoningTokens,
1142
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
1143
+ cachedTokens
1144
+ };
1145
+ const cost = calculateUsageCost(options.model, usage, this.markupMultiplier);
1146
+ const normalized = normalizeCustomer(options.customer, options.customerId);
1147
+ const mergedMeta = {
1148
+ ...normalized.customerMetadata,
1149
+ ...options.metadata
1150
+ };
1151
+ const event = {
1152
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1153
+ model: options.model,
1154
+ provider: options.provider || "custom",
1155
+ usage,
1156
+ cost,
1157
+ customerId: normalized.customerId,
1158
+ customerEmail: normalized.customerEmail,
1159
+ customer: normalized.customerObj,
1160
+ metadata: mergedMeta
1161
+ };
1162
+ this.batcher.enqueue(event);
1163
+ return event;
1164
+ }
1165
+ /**
1166
+ * Flush pending events to Stripe (vital for Serverless & Edge environments)
1167
+ */
1168
+ async flush() {
1169
+ await this.batcher.flush();
1170
+ }
1171
+ /**
1172
+ * Get in-memory aggregated usage statistics
1173
+ */
1174
+ getUsageSummary() {
1175
+ return this.batcher.getSummary();
1176
+ }
1177
+ /**
1178
+ * Reset in-memory ledger
1179
+ */
1180
+ resetSummary() {
1181
+ this.batcher.resetLedger();
1182
+ }
1183
+ };
1184
+ function createMeter(options = {}) {
1185
+ return new VibezMeter(options);
1186
+ }
1187
+
1188
+ // src/ai-sdk/with-billing.ts
1189
+ function withBilling(model, optionsOrCustomer, extraOptions = {}) {
1190
+ if (!model || typeof model !== "object") {
1191
+ return model;
1192
+ }
1193
+ let options = {};
1194
+ if (typeof optionsOrCustomer === "string") {
1195
+ options = { ...extraOptions, customer: optionsOrCustomer };
1196
+ } else if (typeof optionsOrCustomer === "object" && optionsOrCustomer !== null) {
1197
+ if ("userId" in optionsOrCustomer || "email" in optionsOrCustomer || "id" in optionsOrCustomer) {
1198
+ options = { ...extraOptions, customer: optionsOrCustomer };
1199
+ } else {
1200
+ options = { ...optionsOrCustomer, ...extraOptions };
1201
+ }
1202
+ }
1203
+ const meter = options.meter || createMeter({
1204
+ apiKey: options.stripeApiKey,
1205
+ eventName: options.eventName
1206
+ });
1207
+ const normalized = normalizeCustomer(options.customer, options.customerId);
1208
+ const customerId = normalized.customerId;
1209
+ const customerEmail = normalized.customerEmail;
1210
+ const customerObj = normalized.customerObj;
1211
+ const customerMetadata = normalized.customerMetadata;
1212
+ const modelId = model.modelId || "unknown-model";
1213
+ const provider = model.provider?.replace(/^@ai-sdk\//, "") || "ai-sdk";
1214
+ const maxCostPerCall = options.maxCostPerCallUSD !== void 0 ? options.maxCostPerCallUSD : 0.5;
1215
+ const captureOnAbort = options.captureOnAbort !== false;
1216
+ const scheduleFlush = () => {
1217
+ try {
1218
+ const flushPromise = meter.flush();
1219
+ if (typeof globalThis !== "undefined") {
1220
+ const g = globalThis;
1221
+ if (typeof g.after === "function") {
1222
+ g.after(() => flushPromise);
1223
+ return;
1224
+ }
1225
+ }
1226
+ } catch {
1227
+ }
1228
+ };
1229
+ const handleUsage = (rawUsage, extraMeta) => {
1230
+ if (!rawUsage) return;
1231
+ const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? rawUsage.promptTokenCount ?? 0;
1232
+ const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? rawUsage.completion_tokens ?? rawUsage.output_tokens ?? rawUsage.candidatesTokenCount ?? 0;
1233
+ const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? rawUsage.reasoning_tokens ?? rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.thoughtsTokenCount ?? 0;
1234
+ const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? rawUsage.cachedTokens ?? rawUsage.cached_tokens ?? rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? rawUsage.cachedContentTokenCount ?? rawUsage.cache_read_input_tokens ?? 0;
1235
+ const cacheWriteTokens = rawUsage.cacheWriteTokens ?? rawUsage.cache_creation_input_tokens ?? rawUsage.cacheCreationTokens ?? 0;
1236
+ const usage = {
1237
+ inputTokens,
1238
+ outputTokens,
1239
+ totalTokens: inputTokens + outputTokens,
1240
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
1241
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
1242
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0,
1243
+ cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : void 0
1244
+ };
1245
+ const cost = calculateUsageCost(modelId, usage, {
1246
+ markupMultiplier: options.pricing?.margin,
1247
+ minimumChargeUSD: options.pricing?.minimumChargeUSD,
1248
+ customRate: options.rate
1249
+ });
1250
+ if (maxCostPerCall > 0 && maxCostPerCall !== Infinity && cost.totalUSD > maxCostPerCall) {
1251
+ const budgetEvent = {
1252
+ reason: "cost_per_call_exceeded",
1253
+ limit: maxCostPerCall,
1254
+ current: cost.totalUSD,
1255
+ model: modelId,
1256
+ customerId,
1257
+ message: `[vibezcheck] Circuit Breaker tripped: Call cost ($${cost.totalUSD.toFixed(4)}) exceeded budget ceiling ($${maxCostPerCall.toFixed(4)}).`
1258
+ };
1259
+ if (options.onBudgetExceeded) {
1260
+ options.onBudgetExceeded(budgetEvent);
1261
+ }
1262
+ if (options.throwOnBudgetExceeded) {
1263
+ throw new VibezCircuitBreakerError(budgetEvent);
1264
+ }
1265
+ }
1266
+ if (options.maxTokensPerCall && usage.totalTokens > options.maxTokensPerCall) {
1267
+ const budgetEvent = {
1268
+ reason: "max_tokens_exceeded",
1269
+ limit: options.maxTokensPerCall,
1270
+ current: usage.totalTokens,
1271
+ model: modelId,
1272
+ customerId,
1273
+ message: `[vibezcheck] Circuit Breaker tripped: Token count (${usage.totalTokens}) exceeded maxTokensPerCall limit (${options.maxTokensPerCall}).`
1274
+ };
1275
+ if (options.onBudgetExceeded) {
1276
+ options.onBudgetExceeded(budgetEvent);
1277
+ }
1278
+ if (options.throwOnBudgetExceeded) {
1279
+ throw new VibezCircuitBreakerError(budgetEvent);
1280
+ }
1281
+ }
1282
+ const mergedMetadata = {
1283
+ ...customerMetadata,
1284
+ ...options.metadata,
1285
+ ...extraMeta,
1286
+ billingMode: options.billing?.mode || "postpaid"
1287
+ };
1288
+ const event = {
1289
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1290
+ model: modelId,
1291
+ provider,
1292
+ usage,
1293
+ cost,
1294
+ customerId,
1295
+ customerEmail,
1296
+ customer: customerObj,
1297
+ metadata: mergedMetadata
1298
+ };
1299
+ meter.recordUsage({
1300
+ model: modelId,
1301
+ provider,
1302
+ inputTokens,
1303
+ outputTokens,
1304
+ reasoningTokens: usage.reasoningTokens,
1305
+ cachedTokens: usage.cachedTokens,
1306
+ customerId,
1307
+ customer: customerObj,
1308
+ metadata: event.metadata
1309
+ });
1310
+ if (options.onUsage) {
1311
+ options.onUsage(event);
1312
+ }
1313
+ if (options.database) {
1314
+ const dbTarget = options.database;
1315
+ const executeDbWrite = async () => {
1316
+ try {
1317
+ const supabaseClient = typeof dbTarget === "object" && dbTarget !== null && typeof dbTarget.from === "function" ? dbTarget : typeof dbTarget === "object" && dbTarget !== null && typeof dbTarget.client?.from === "function" ? dbTarget.client : null;
1318
+ if (supabaseClient) {
1319
+ const tableName = dbTarget?.table || "vibez_usage";
1320
+ await supabaseClient.from(tableName).insert({
1321
+ customer_id: customerId,
1322
+ user_id: customerObj?.userId || customerId,
1323
+ model: modelId,
1324
+ input_tokens: usage.inputTokens,
1325
+ output_tokens: usage.outputTokens,
1326
+ total_tokens: usage.totalTokens,
1327
+ cached_tokens: usage.cachedTokens,
1328
+ reasoning_tokens: usage.reasoningTokens,
1329
+ cost_usd: cost.totalUSD,
1330
+ created_at: event.timestamp,
1331
+ metadata: event.metadata
1332
+ });
1333
+ return;
1334
+ }
1335
+ if (typeof dbTarget === "object" && dbTarget !== null && typeof dbTarget.save === "function") {
1336
+ await dbTarget.save(event);
1337
+ return;
1338
+ }
1339
+ if (typeof dbTarget === "function") {
1340
+ await dbTarget(event);
1341
+ return;
1342
+ }
1343
+ } catch (err) {
1344
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1345
+ console.warn(`[vibezcheck] Database record failed safely:`, err?.message || err);
1346
+ }
1347
+ }
1348
+ };
1349
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1350
+ globalThis.after(() => executeDbWrite());
1351
+ } else {
1352
+ executeDbWrite().catch(() => {
1353
+ });
1354
+ }
1355
+ }
1356
+ if (options.billing?.charge && typeof options.billing.charge === "function") {
1357
+ const chargeFn = options.billing.charge;
1358
+ const executeCharge = async () => {
1359
+ try {
1360
+ await chargeFn(cost.totalUSD, event);
1361
+ } catch (err) {
1362
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1363
+ console.warn(`[vibezcheck] Custom charge handler failed safely:`, err?.message || err);
1364
+ }
1365
+ }
1366
+ };
1367
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1368
+ globalThis.after(() => executeCharge());
1369
+ } else {
1370
+ executeCharge().catch(() => {
1371
+ });
1372
+ }
1373
+ } else if (options.billing?.provider && typeof options.billing.provider === "object" && typeof options.billing.provider.charge === "function") {
1374
+ const providerCharge = options.billing.provider.charge;
1375
+ const executeCharge = async () => {
1376
+ try {
1377
+ await providerCharge(cost.totalUSD, event);
1378
+ } catch (err) {
1379
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1380
+ console.warn(`[vibezcheck] Payment provider charge failed safely:`, err?.message || err);
1381
+ }
1382
+ }
1383
+ };
1384
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1385
+ globalThis.after(() => executeCharge());
1386
+ } else {
1387
+ executeCharge().catch(() => {
1388
+ });
1389
+ }
1390
+ }
1391
+ scheduleFlush();
1392
+ };
1393
+ const handler = {
1394
+ get(target, prop, receiver) {
1395
+ const originalValue = Reflect.get(target, prop, receiver);
1396
+ if (prop === "doStream" && typeof originalValue === "function") {
1397
+ return async function(...args) {
1398
+ const result = await originalValue.apply(target, args);
1399
+ if (!result || !result.stream) {
1400
+ return result;
1401
+ }
1402
+ const originalStream = result.stream;
1403
+ let streamCompleted = false;
1404
+ let accumulatedChars = 0;
1405
+ let estimatedInputTokens = 0;
1406
+ try {
1407
+ if (args[0]?.prompt) {
1408
+ const str = typeof args[0].prompt === "string" ? args[0].prompt : JSON.stringify(args[0].prompt);
1409
+ estimatedInputTokens = Math.ceil(str.length / 4);
1410
+ }
1411
+ } catch {
1412
+ }
1413
+ const abortSignal = args[0]?.abortSignal;
1414
+ if (abortSignal && captureOnAbort) {
1415
+ abortSignal.addEventListener(
1416
+ "abort",
1417
+ () => {
1418
+ if (!streamCompleted && accumulatedChars > 0) {
1419
+ streamCompleted = true;
1420
+ const estimatedOutputTokens = Math.ceil(accumulatedChars / 3.8);
1421
+ handleUsage(
1422
+ {
1423
+ inputTokens: estimatedInputTokens,
1424
+ outputTokens: estimatedOutputTokens
1425
+ },
1426
+ { aborted: true, partial: true }
1427
+ );
1428
+ }
1429
+ },
1430
+ { once: true }
1431
+ );
1432
+ }
1433
+ const transformStream = new TransformStream({
1434
+ transform(chunk, controller) {
1435
+ controller.enqueue(chunk);
1436
+ const delta = chunk.textDelta || chunk.text || chunk.delta;
1437
+ if (delta && typeof delta === "string") {
1438
+ accumulatedChars += delta.length;
1439
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1440
+ const reasoning = chunk.reasoning || chunk.textDelta || chunk.text || chunk.delta || "";
1441
+ if (typeof reasoning === "string") {
1442
+ accumulatedChars += reasoning.length;
1443
+ }
1444
+ }
1445
+ const chunkUsage = chunk.usage || chunk.token_usage || chunk.usageMetadata;
1446
+ if (chunkUsage) {
1447
+ streamCompleted = true;
1448
+ handleUsage(chunkUsage);
1449
+ }
1450
+ },
1451
+ flush() {
1452
+ if (!streamCompleted && captureOnAbort && accumulatedChars > 0) {
1453
+ streamCompleted = true;
1454
+ const estimatedOutputTokens = Math.ceil(accumulatedChars / 3.8);
1455
+ handleUsage(
1456
+ {
1457
+ inputTokens: estimatedInputTokens,
1458
+ outputTokens: estimatedOutputTokens
1459
+ },
1460
+ { aborted: true, partial: true }
1461
+ );
1462
+ }
1463
+ }
1464
+ });
1465
+ return {
1466
+ ...result,
1467
+ stream: originalStream.pipeThrough(transformStream)
1468
+ };
1469
+ };
1470
+ }
1471
+ if (prop === "doGenerate" && typeof originalValue === "function") {
1472
+ return async function(...args) {
1473
+ const result = await originalValue.apply(target, args);
1474
+ const usage = result?.usage || result?.tokenUsage || result?.usageMetadata;
1475
+ if (usage) {
1476
+ handleUsage(usage);
1477
+ }
1478
+ return result;
1479
+ };
1480
+ }
1481
+ return originalValue;
1482
+ },
1483
+ apply(target, thisArg, argArray) {
1484
+ if (typeof target === "function") {
1485
+ return Reflect.apply(target, thisArg, argArray);
1486
+ }
1487
+ return target;
1488
+ },
1489
+ has(target, prop) {
1490
+ return Reflect.has(target, prop);
1491
+ },
1492
+ ownKeys(target) {
1493
+ return Reflect.ownKeys(target);
1494
+ },
1495
+ getPrototypeOf(target) {
1496
+ return Reflect.getPrototypeOf(target);
1497
+ }
1498
+ };
1499
+ return new Proxy(model, handler);
1500
+ }
1501
+
1502
+ // src/billing/session.ts
1503
+ var AgentSession = class {
1504
+ sessionId;
1505
+ customer;
1506
+ maxCostUSD;
1507
+ totalCostUSD = 0;
1508
+ totalTokens = 0;
1509
+ toolCalls = [];
1510
+ options;
1511
+ constructor(options = {}) {
1512
+ this.sessionId = `vibez_sess_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1513
+ this.customer = options.customer;
1514
+ this.maxCostUSD = options.sessionBudgetUSD ?? options.maxCostUSD ?? 1;
1515
+ this.options = options;
1516
+ }
1517
+ /**
1518
+ * Returns an AI model instance bound to this agent session with cumulative budget enforcement
1519
+ */
1520
+ model(modelOrId, modelOptions = {}) {
1521
+ const session = this;
1522
+ return withBilling(modelOrId, {
1523
+ ...modelOptions,
1524
+ customer: this.customer,
1525
+ pricing: modelOptions.pricing || this.options.pricing,
1526
+ billing: modelOptions.billing || this.options.billing,
1527
+ onUsage: async (event) => {
1528
+ const callCost = event.cost.retailUSD ?? event.cost.billedUSD ?? event.cost.totalUSD;
1529
+ session.totalCostUSD = Number((session.totalCostUSD + callCost).toFixed(8));
1530
+ session.totalTokens += event.usage.totalTokens;
1531
+ if (session.totalCostUSD > session.maxCostUSD) {
1532
+ throw new VibezCircuitBreakerError({
1533
+ reason: "cost_per_call_exceeded",
1534
+ limit: session.maxCostUSD,
1535
+ current: session.totalCostUSD,
1536
+ model: event.model,
1537
+ customerId: event.customerId,
1538
+ message: `[vibezcheck] Agent Session Budget exceeded: Cumulative cost ($${session.totalCostUSD.toFixed(4)}) exceeded limit ($${session.maxCostUSD.toFixed(4)}).`
1539
+ });
1540
+ }
1541
+ if (session.options.onUsage) {
1542
+ await session.options.onUsage(event);
1543
+ }
1544
+ }
1545
+ });
1546
+ }
1547
+ /**
1548
+ * Tracks an external tool invocation (e.g. web search, Python code sandbox, vector query, API call)
1549
+ */
1550
+ async trackTool(toolName, costOrOptions, fn) {
1551
+ const costUSD = typeof costOrOptions === "number" ? costOrOptions : costOrOptions.costUSD;
1552
+ const latencyMs = typeof costOrOptions === "object" ? costOrOptions.latencyMs : void 0;
1553
+ const metadata = typeof costOrOptions === "object" ? costOrOptions.metadata : void 0;
1554
+ if (this.totalCostUSD + costUSD > this.maxCostUSD) {
1555
+ throw new VibezCircuitBreakerError({
1556
+ reason: "cost_per_call_exceeded",
1557
+ limit: this.maxCostUSD,
1558
+ current: this.totalCostUSD + costUSD,
1559
+ model: `tool:${toolName}`,
1560
+ message: `[vibezcheck] Agent Session Budget exceeded on tool '${toolName}': ($${(this.totalCostUSD + costUSD).toFixed(4)}) exceeded limit ($${this.maxCostUSD.toFixed(4)}).`
1561
+ });
1562
+ }
1563
+ let result = void 0;
1564
+ const start = performance.now();
1565
+ if (fn) {
1566
+ result = await fn();
1567
+ }
1568
+ const elapsed = latencyMs ?? Math.round(performance.now() - start);
1569
+ this.totalCostUSD = Number((this.totalCostUSD + costUSD).toFixed(8));
1570
+ this.toolCalls.push({
1571
+ name: toolName,
1572
+ costUSD,
1573
+ latencyMs: elapsed,
1574
+ metadata
1575
+ });
1576
+ return result;
1577
+ }
1578
+ getCurrentCostUSD() {
1579
+ return this.totalCostUSD;
1580
+ }
1581
+ getTotalTokens() {
1582
+ return this.totalTokens;
1583
+ }
1584
+ /**
1585
+ * Concludes session and returns final financial summary
1586
+ */
1587
+ async conclude() {
1588
+ return this.getSummary();
1589
+ }
1590
+ /**
1591
+ * Returns current session summary
1592
+ */
1593
+ getSummary() {
1594
+ return {
1595
+ sessionId: this.sessionId,
1596
+ customer: this.customer,
1597
+ totalCostUSD: this.totalCostUSD,
1598
+ totalTokens: this.totalTokens,
1599
+ toolCallCount: this.toolCalls.length,
1600
+ toolCalls: [...this.toolCalls]
1601
+ };
1602
+ }
1603
+ };
1604
+ function createAgentSession(options = {}) {
1605
+ return new AgentSession(options);
1606
+ }
1607
+
1608
+ // src/billing/tools.ts
1609
+ function wrapTool(options) {
1610
+ const { name, costUSD, tool, execute } = options;
1611
+ const targetFn = execute || tool?.execute;
1612
+ if (!targetFn && !tool) {
1613
+ return options;
1614
+ }
1615
+ const base = tool || {};
1616
+ return {
1617
+ ...base,
1618
+ name,
1619
+ costUSD,
1620
+ execute: async (...args) => {
1621
+ const startTime = performance.now();
1622
+ try {
1623
+ const result = await targetFn(...args);
1624
+ const latencyMs = Math.round(performance.now() - startTime);
1625
+ if (typeof globalThis.__vibezCurrentSession?.trackTool === "function") {
1626
+ await globalThis.__vibezCurrentSession.trackTool(name, {
1627
+ costUSD,
1628
+ latencyMs,
1629
+ metadata: { args: args[0] }
1630
+ });
1631
+ }
1632
+ return result;
1633
+ } catch (error) {
1634
+ const latencyMs = Math.round(performance.now() - startTime);
1635
+ if (typeof globalThis.__vibezCurrentSession?.trackTool === "function") {
1636
+ await globalThis.__vibezCurrentSession.trackTool(name, {
1637
+ costUSD,
1638
+ latencyMs,
1639
+ metadata: { error: String(error) }
1640
+ });
1641
+ }
1642
+ throw error;
1643
+ }
1644
+ }
1645
+ };
1646
+ }
1647
+ function instrumentToolKit(tools, options = {}) {
1648
+ const instrumented = {};
1649
+ const cost = options.costPerActionUSD ?? 5e-3;
1650
+ for (const [toolName, toolDef] of Object.entries(tools)) {
1651
+ instrumented[toolName] = wrapTool({
1652
+ name: toolName,
1653
+ costUSD: cost,
1654
+ tool: toolDef
1655
+ });
1656
+ }
1657
+ return instrumented;
1658
+ }
123
1659
  // Annotate the CommonJS export names for ESM import in node:
124
1660
  0 && (module.exports = {
1661
+ AgentSession,
125
1662
  BillingHelper,
126
- createBillingHelper
1663
+ createAgentSession,
1664
+ createBillingHelper,
1665
+ instrumentToolKit,
1666
+ wrapTool
127
1667
  });
128
1668
  //# sourceMappingURL=index.js.map