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