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