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