vibezcheck 0.4.2 → 0.5.0

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 (78) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +230 -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 +79 -32
  7. package/dist/ai-sdk/index.js.map +1 -1
  8. package/dist/ai-sdk/index.mjs +79 -32
  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 +1280 -0
  13. package/dist/ai-sdk/middleware.js.map +1 -0
  14. package/dist/ai-sdk/middleware.mjs +1243 -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 +1391 -2
  21. package/dist/billing/index.js.map +1 -1
  22. package/dist/billing/index.mjs +1386 -1
  23. package/dist/billing/index.mjs.map +1 -1
  24. package/dist/cli/index.js.map +1 -1
  25. package/dist/cli/index.mjs.map +1 -1
  26. package/dist/{client-ynfWcHX6.d.ts → client-CJ2Dj8ID.d.ts} +1 -1
  27. package/dist/{client-w_hWhQ6g.d.mts → client-Dmwb3hQt.d.mts} +1 -1
  28. package/dist/compat/stripe-meter.d.mts +21 -0
  29. package/dist/compat/stripe-meter.d.ts +21 -0
  30. package/dist/compat/stripe-meter.js +1281 -0
  31. package/dist/compat/stripe-meter.js.map +1 -0
  32. package/dist/compat/stripe-meter.mjs +1244 -0
  33. package/dist/compat/stripe-meter.mjs.map +1 -0
  34. package/dist/compat/stripe-provider.d.mts +54 -0
  35. package/dist/compat/stripe-provider.d.ts +54 -0
  36. package/dist/compat/stripe-provider.js +1304 -0
  37. package/dist/compat/stripe-provider.js.map +1 -0
  38. package/dist/compat/stripe-provider.mjs +1264 -0
  39. package/dist/compat/stripe-provider.mjs.map +1 -0
  40. package/dist/compat/token-meter.d.mts +16 -0
  41. package/dist/compat/token-meter.d.ts +16 -0
  42. package/dist/compat/token-meter.js +1095 -0
  43. package/dist/compat/token-meter.js.map +1 -0
  44. package/dist/compat/token-meter.mjs +1058 -0
  45. package/dist/compat/token-meter.mjs.map +1 -0
  46. package/dist/customers/index.d.mts +1 -1
  47. package/dist/customers/index.d.ts +1 -1
  48. package/dist/customers/index.js.map +1 -1
  49. package/dist/customers/index.mjs.map +1 -1
  50. package/dist/index.d.mts +22 -11
  51. package/dist/index.d.ts +22 -11
  52. package/dist/index.js +269 -33
  53. package/dist/index.js.map +1 -1
  54. package/dist/index.mjs +265 -33
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/meter/index.d.mts +2 -2
  57. package/dist/meter/index.d.ts +2 -2
  58. package/dist/meter/index.js +44 -22
  59. package/dist/meter/index.js.map +1 -1
  60. package/dist/meter/index.mjs +44 -22
  61. package/dist/meter/index.mjs.map +1 -1
  62. package/dist/pricing/index.d.mts +5 -2
  63. package/dist/pricing/index.d.ts +5 -2
  64. package/dist/pricing/index.js +43 -21
  65. package/dist/pricing/index.js.map +1 -1
  66. package/dist/pricing/index.mjs +43 -21
  67. package/dist/pricing/index.mjs.map +1 -1
  68. package/dist/react/index.d.mts +46 -2
  69. package/dist/react/index.d.ts +46 -2
  70. package/dist/react/index.js +351 -21
  71. package/dist/react/index.js.map +1 -1
  72. package/dist/react/index.mjs +349 -21
  73. package/dist/react/index.mjs.map +1 -1
  74. package/dist/{types-Mozk4-Mr.d.mts → types-BVGqbKnY.d.mts} +6 -0
  75. package/dist/{types-Mozk4-Mr.d.ts → types-BVGqbKnY.d.ts} +6 -0
  76. package/dist/with-billing-CDqKIAQ6.d.ts +47 -0
  77. package/dist/with-billing-mci2vtFS.d.mts +47 -0
  78. package/package.json +26 -1
@@ -0,0 +1,1280 @@
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
+ if (chunk.usage) {
310
+ const rawUsage = chunk.usage;
311
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? 0;
312
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? 0;
313
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? 0;
314
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? 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 rawUsage = chunk.response.usage;
330
+ const inputTokens = rawUsage.input_tokens ?? 0;
331
+ const outputTokens = rawUsage.output_tokens ?? 0;
332
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? 0;
333
+ const cachedTokens = rawUsage.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 ---
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.1": { inputPer1M: 2, outputPer1M: 8, cachedInputPer1M: 1 },
511
+ "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.05 },
512
+ "text-embedding-3-small": { inputPer1M: 0.02, outputPer1M: 0 },
513
+ "text-embedding-3-large": { inputPer1M: 0.13, outputPer1M: 0 },
514
+ // --- Anthropic ---
515
+ "claude-3-7-sonnet": { inputPer1M: 0.59, outputPer1M: 2.93, cachedInputPer1M: 0.3 },
516
+ "claude-sonnet-5": { inputPer1M: 2, outputPer1M: 10, cachedInputPer1M: 0.3 },
517
+ "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
518
+ "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4, cachedInputPer1M: 0.08 },
519
+ "haiku-4.5": { inputPer1M: 1, outputPer1M: 5, cachedInputPer1M: 0.1 },
520
+ "claude-opus-5": { inputPer1M: 5, outputPer1M: 25, cachedInputPer1M: 1.5 },
521
+ "claude-3-opus": { inputPer1M: 15, outputPer1M: 75, cachedInputPer1M: 1.5 },
522
+ // --- Google Gemini ---
523
+ "gemini-3.7-flash": { inputPer1M: 0.75, outputPer1M: 3.75, cachedInputPer1M: 0.18 },
524
+ "gemini-3.1-pro": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.5 },
525
+ "gemini-3.5-flash": { inputPer1M: 1.5, outputPer1M: 9, cachedInputPer1M: 0.38 },
526
+ "gemini-3.1-flash-lite": { inputPer1M: 0.25, outputPer1M: 1.5, cachedInputPer1M: 0.06 },
527
+ "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.025 },
528
+ "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
529
+ "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
530
+ // --- xAI Grok ---
531
+ "grok-4.6": { inputPer1M: 3, outputPer1M: 15 },
532
+ "grok-2": { inputPer1M: 2, outputPer1M: 10 },
533
+ "grok-2-vision": { inputPer1M: 2, outputPer1M: 10 },
534
+ "grok-beta": { inputPer1M: 5, outputPer1M: 15 },
535
+ // --- Mistral ---
536
+ "mistral-large-3": { inputPer1M: 2, outputPer1M: 6 },
537
+ "mistral-large-latest": { inputPer1M: 2, outputPer1M: 6 },
538
+ "codestral-latest": { inputPer1M: 0.3, outputPer1M: 0.9 },
539
+ "mistral-small-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
540
+ "ministral-8b-latest": { inputPer1M: 0.1, outputPer1M: 0.1 },
541
+ // --- Groq LPUs ---
542
+ "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
543
+ "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
544
+ "deepseek-r1-distill-llama-70b": { inputPer1M: 0.75, outputPer1M: 0.99 },
545
+ "qwen-2.5-32b": { inputPer1M: 0.29, outputPer1M: 0.39 },
546
+ // --- DeepSeek ---
547
+ "deepseek-v4-pro": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
548
+ "deepseek-v4-flash": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
549
+ "deepseek-chat": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
550
+ "deepseek-reasoner": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
551
+ // --- Cohere ---
552
+ "command-r-plus": { inputPer1M: 2.5, outputPer1M: 10 },
553
+ "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 }
554
+ };
555
+ var customPricingRegistry = {};
556
+ function normalizeModelKey(rawModel) {
557
+ if (!rawModel) return "unknown";
558
+ let model = rawModel.toLowerCase().trim();
559
+ if (model.includes("/")) {
560
+ model = model.split("/")[1] || model;
561
+ }
562
+ model = model.replace(/-\d{8}$/, "");
563
+ model = model.replace(/-\d{4}-\d{2}-\d{2}$/, "");
564
+ return model;
565
+ }
566
+ function getModelPricing(modelName) {
567
+ const normalized = normalizeModelKey(modelName);
568
+ if (customPricingRegistry[normalized]) {
569
+ return customPricingRegistry[normalized];
570
+ }
571
+ if (customPricingRegistry[modelName]) {
572
+ return customPricingRegistry[modelName];
573
+ }
574
+ if (MODEL_PRICING_TABLE[normalized]) {
575
+ return MODEL_PRICING_TABLE[normalized];
576
+ }
577
+ if (MODEL_PRICING_TABLE[modelName]) {
578
+ return MODEL_PRICING_TABLE[modelName];
579
+ }
580
+ return {
581
+ inputPer1M: 1,
582
+ outputPer1M: 3,
583
+ cachedInputPer1M: 0.5
584
+ };
585
+ }
586
+
587
+ // src/pricing/calculator.ts
588
+ function calculateCost(params) {
589
+ let rates;
590
+ if (params.customRate) {
591
+ const outRate = params.customRate.out ?? params.customRate.output ?? 0;
592
+ rates = {
593
+ inputPer1M: params.customRate.in,
594
+ outputPer1M: outRate,
595
+ reasoningPer1M: params.customRate.reasoning ?? outRate,
596
+ cachedInputPer1M: params.customRate.cached ?? params.customRate.in * 0.15,
597
+ currency: "USD"
598
+ };
599
+ } else {
600
+ rates = getModelPricing(params.model);
601
+ }
602
+ const inputTokens = BigInt(Math.max(0, params.inputTokens ?? 0));
603
+ const outputTokens = BigInt(Math.max(0, params.outputTokens ?? 0));
604
+ const reasoningTokens = BigInt(Math.max(0, params.reasoningTokens ?? 0));
605
+ const cachedTokens = BigInt(Math.max(0, params.cachedTokens ?? 0));
606
+ const regularInputTokens = inputTokens > cachedTokens ? inputTokens - cachedTokens : 0n;
607
+ const rateInputNano = BigInt(Math.round(rates.inputPer1M * 1e3));
608
+ const cachedPer1M = rates.cachedInputPer1M ?? rates.inputPer1M * 0.15;
609
+ const rateCachedNano = BigInt(Math.round(cachedPer1M * 1e3));
610
+ const rateOutputNano = BigInt(Math.round(rates.outputPer1M * 1e3));
611
+ const reasoningPer1M = rates.reasoningPer1M ?? rates.outputPer1M;
612
+ const rateReasoningNano = BigInt(Math.round(reasoningPer1M * 1e3));
613
+ const regularInputCostNano = regularInputTokens * rateInputNano;
614
+ const cachedInputCostNano = cachedTokens * rateCachedNano;
615
+ const inputCostNano = regularInputCostNano + cachedInputCostNano;
616
+ const outputCostNano = outputTokens * rateOutputNano;
617
+ const reasoningCostNano = reasoningTokens * rateReasoningNano;
618
+ const standardCacheCostNano = cachedTokens * rateInputNano;
619
+ const cachedDiscountNano = standardCacheCostNano > cachedInputCostNano ? standardCacheCostNano - cachedInputCostNano : 0n;
620
+ const wholesaleNano = inputCostNano + outputCostNano;
621
+ const markup = params.markupMultiplier ?? 1;
622
+ let billedNano = wholesaleNano;
623
+ let hasRetail = false;
624
+ if (markup !== 1 || params.minimumChargeUSD !== void 0) {
625
+ hasRetail = true;
626
+ const markupMultiplierNano = BigInt(Math.round(markup * 1e3));
627
+ billedNano = wholesaleNano * markupMultiplierNano / 1000n;
628
+ if (params.minimumChargeUSD !== void 0 && params.minimumChargeUSD > 0) {
629
+ const minChargeNano = BigInt(Math.round(params.minimumChargeUSD * 1e9));
630
+ if (billedNano < minChargeNano) {
631
+ billedNano = minChargeNano;
632
+ }
633
+ }
634
+ }
635
+ const inputCostUSD = Number(inputCostNano) / 1e9;
636
+ const outputCostUSD = Number(outputCostNano) / 1e9;
637
+ const reasoningCostUSD = Number(reasoningCostNano) / 1e9;
638
+ const cachedDiscountUSD = Number(cachedDiscountNano) / 1e9;
639
+ const totalUSD = Number(wholesaleNano) / 1e9;
640
+ const wholesaleTotalUSD = totalUSD;
641
+ const billedUSD = Number(billedNano) / 1e9;
642
+ const profitUSD = Math.max(0, billedUSD - wholesaleTotalUSD);
643
+ const retailUSD = hasRetail ? billedUSD : void 0;
644
+ return {
645
+ inputCostUSD: Number(inputCostUSD.toFixed(8)),
646
+ outputCostUSD: Number(outputCostUSD.toFixed(8)),
647
+ reasoningCostUSD: reasoningTokens > 0n ? Number(reasoningCostUSD.toFixed(8)) : void 0,
648
+ cachedDiscountUSD: cachedTokens > 0n ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
649
+ totalUSD: Number(totalUSD.toFixed(8)),
650
+ wholesaleTotalUSD: Number(wholesaleTotalUSD.toFixed(8)),
651
+ billedUSD: Number(billedUSD.toFixed(8)),
652
+ profitUSD: Number(profitUSD.toFixed(8)),
653
+ retailUSD: retailUSD !== void 0 ? Number(retailUSD.toFixed(8)) : void 0,
654
+ currency: rates.currency || "USD"
655
+ };
656
+ }
657
+ function calculateUsageCost(model, usage, optionsOrMarkup) {
658
+ const options = typeof optionsOrMarkup === "number" ? { markupMultiplier: optionsOrMarkup } : optionsOrMarkup || {};
659
+ return calculateCost({
660
+ model,
661
+ inputTokens: usage.inputTokens,
662
+ outputTokens: usage.outputTokens,
663
+ reasoningTokens: usage.reasoningTokens,
664
+ cachedTokens: usage.cachedTokens,
665
+ cacheWriteTokens: usage.cacheWriteTokens,
666
+ markupMultiplier: options.markupMultiplier,
667
+ minimumChargeUSD: options.minimumChargeUSD,
668
+ customRate: options.customRate
669
+ });
670
+ }
671
+
672
+ // src/customers/helpers.ts
673
+ function normalizeCustomer(customer, extraCustomerId) {
674
+ if (!customer && !extraCustomerId) {
675
+ return {
676
+ customerId: void 0,
677
+ customerEmail: void 0,
678
+ customerObj: void 0,
679
+ customerMetadata: {}
680
+ };
681
+ }
682
+ if (typeof customer === "string") {
683
+ const isEmail = customer.includes("@");
684
+ const customerObj2 = {
685
+ id: customer,
686
+ email: isEmail ? customer : void 0
687
+ };
688
+ return {
689
+ customerId: customer,
690
+ customerEmail: isEmail ? customer : void 0,
691
+ customerObj: customerObj2,
692
+ customerMetadata: {}
693
+ };
694
+ }
695
+ const customerObj = customer || (extraCustomerId ? { id: extraCustomerId } : void 0);
696
+ const customerId = customerObj?.id || customerObj?.userId || extraCustomerId;
697
+ const customerEmail = customerObj?.email;
698
+ const customerMetadata = {};
699
+ if (customerObj) {
700
+ const orgId = customerObj.orgId || customerObj.organizationId;
701
+ if (orgId) customerMetadata.org_id = String(orgId);
702
+ const teamId = customerObj.teamId || customerObj.workspaceId;
703
+ if (teamId) customerMetadata.team_id = String(teamId);
704
+ if (customerObj.plan) customerMetadata.plan = String(customerObj.plan);
705
+ if (customerObj.tier) customerMetadata.tier = String(customerObj.tier);
706
+ if (customerObj.role) customerMetadata.role = String(customerObj.role);
707
+ if (customerObj.orgName) customerMetadata.org_name = String(customerObj.orgName);
708
+ if (customerObj.metadata) {
709
+ for (const [key, val] of Object.entries(customerObj.metadata)) {
710
+ if (val !== null && val !== void 0) {
711
+ customerMetadata[key] = val;
712
+ }
713
+ }
714
+ }
715
+ }
716
+ return {
717
+ customerId,
718
+ customerEmail,
719
+ customerObj,
720
+ customerMetadata
721
+ };
722
+ }
723
+
724
+ // src/meter/stream.ts
725
+ function wrapOpenAIStream(stream, options, onComplete) {
726
+ let detectedModel = options.model || "gpt-4o";
727
+ let finalUsage = null;
728
+ const wrappedAsyncIterable = {
729
+ async *[Symbol.asyncIterator]() {
730
+ try {
731
+ for await (const chunk of stream) {
732
+ const inspected = inspectOpenAIStreamChunk(chunk);
733
+ if (inspected.model) {
734
+ detectedModel = inspected.model;
735
+ }
736
+ if (inspected.usage) {
737
+ finalUsage = inspected.usage;
738
+ }
739
+ yield chunk;
740
+ }
741
+ } finally {
742
+ if (finalUsage) {
743
+ const cost = calculateUsageCost(detectedModel, finalUsage);
744
+ const normalized = normalizeCustomer(options.customer, options.customerId);
745
+ const event = {
746
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
747
+ model: detectedModel,
748
+ provider: "openai",
749
+ usage: finalUsage,
750
+ cost,
751
+ customerId: normalized.customerId,
752
+ customerEmail: normalized.customerEmail,
753
+ customer: normalized.customerObj,
754
+ metadata: {
755
+ ...normalized.customerMetadata,
756
+ ...options.metadata
757
+ }
758
+ };
759
+ onComplete(event);
760
+ if (options.onUsage) {
761
+ options.onUsage(event);
762
+ }
763
+ }
764
+ }
765
+ }
766
+ };
767
+ return wrappedAsyncIterable;
768
+ }
769
+ function wrapAnthropicStream(stream, options, onComplete) {
770
+ const accumulator = new AnthropicStreamAccumulator();
771
+ const wrappedAsyncIterable = {
772
+ async *[Symbol.asyncIterator]() {
773
+ try {
774
+ for await (const event of stream) {
775
+ accumulator.processEvent(event);
776
+ yield event;
777
+ }
778
+ } finally {
779
+ const extracted = accumulator.getUsage();
780
+ const model = options.model || extracted.model;
781
+ const cost = calculateUsageCost(model, extracted.usage);
782
+ const normalized = normalizeCustomer(options.customer, options.customerId);
783
+ const usageEvent = {
784
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
785
+ model,
786
+ provider: "anthropic",
787
+ usage: extracted.usage,
788
+ cost,
789
+ customerId: normalized.customerId,
790
+ customerEmail: normalized.customerEmail,
791
+ customer: normalized.customerObj,
792
+ metadata: {
793
+ ...normalized.customerMetadata,
794
+ ...options.metadata
795
+ }
796
+ };
797
+ onComplete(usageEvent);
798
+ if (options.onUsage) {
799
+ options.onUsage(usageEvent);
800
+ }
801
+ }
802
+ }
803
+ };
804
+ return wrappedAsyncIterable;
805
+ }
806
+ function wrapGeminiStream(result, options, onComplete) {
807
+ if (!result || !result.stream) return result;
808
+ const originalStream = result.stream;
809
+ const model = options.model || "gemini-3.7-flash";
810
+ let lastChunkWithUsage = null;
811
+ const wrappedStream = (async function* () {
812
+ try {
813
+ for await (const chunk of originalStream) {
814
+ if (chunk.usageMetadata) {
815
+ lastChunkWithUsage = chunk;
816
+ }
817
+ yield chunk;
818
+ }
819
+ } finally {
820
+ if (lastChunkWithUsage) {
821
+ const extracted = extractGeminiResponseUsage(lastChunkWithUsage, model);
822
+ if (extracted) {
823
+ const cost = calculateUsageCost(extracted.model, extracted.usage);
824
+ const normalized = normalizeCustomer(options.customer, options.customerId);
825
+ const event = {
826
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
827
+ model: extracted.model,
828
+ provider: "google",
829
+ usage: extracted.usage,
830
+ cost,
831
+ customerId: normalized.customerId,
832
+ customerEmail: normalized.customerEmail,
833
+ customer: normalized.customerObj,
834
+ metadata: {
835
+ ...normalized.customerMetadata,
836
+ ...options.metadata
837
+ }
838
+ };
839
+ onComplete(event);
840
+ if (options.onUsage) {
841
+ options.onUsage(event);
842
+ }
843
+ }
844
+ }
845
+ }
846
+ })();
847
+ return {
848
+ ...result,
849
+ stream: wrappedStream
850
+ };
851
+ }
852
+ function wrapUniversalStream(stream, options = {}, onComplete) {
853
+ if (!stream || typeof stream !== "object") return stream;
854
+ if ("stream" in stream && "response" in stream) {
855
+ return wrapGeminiStream(stream, options, onComplete);
856
+ }
857
+ if (Symbol.asyncIterator in stream) {
858
+ if (options.provider === "anthropic") {
859
+ return wrapAnthropicStream(stream, options, onComplete);
860
+ }
861
+ return wrapOpenAIStream(stream, options, onComplete);
862
+ }
863
+ return stream;
864
+ }
865
+
866
+ // src/meter/client.ts
867
+ var VibezMeter = class {
868
+ batcher;
869
+ stripeClient;
870
+ markupMultiplier;
871
+ constructor(options = {}) {
872
+ this.markupMultiplier = options.markupMultiplier;
873
+ if (options.stripe) {
874
+ this.stripeClient = options.stripe;
875
+ } else if (options.apiKey || process.env.STRIPE_SECRET_KEY) {
876
+ const key = options.apiKey || process.env.STRIPE_SECRET_KEY;
877
+ this.stripeClient = new import_stripe.default(key, {
878
+ appInfo: {
879
+ name: "vibezcheck",
880
+ version: "0.5.0",
881
+ url: "https://vibezcheck.xyz"
882
+ }
883
+ });
884
+ }
885
+ this.batcher = new MeterBatcher({
886
+ ...options,
887
+ stripe: this.stripeClient
888
+ });
889
+ }
890
+ /**
891
+ * Track token usage from a non-streaming response object (OpenAI, Anthropic, Gemini, etc.)
892
+ */
893
+ trackUsage(response, options = {}) {
894
+ const extracted = detectAndExtractUsage(response, options.model, options.provider);
895
+ if (!extracted) {
896
+ return null;
897
+ }
898
+ const model = options.model || extracted.model;
899
+ const cost = calculateUsageCost(model, extracted.usage, this.markupMultiplier);
900
+ const normalized = normalizeCustomer(options.customer, options.customerId);
901
+ const mergedMeta = {
902
+ ...normalized.customerMetadata,
903
+ ...options.metadata
904
+ };
905
+ const event = {
906
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
907
+ model,
908
+ provider: extracted.provider,
909
+ usage: extracted.usage,
910
+ cost,
911
+ customerId: normalized.customerId,
912
+ customerEmail: normalized.customerEmail,
913
+ customer: normalized.customerObj,
914
+ metadata: mergedMeta
915
+ };
916
+ this.batcher.enqueue(event);
917
+ return event;
918
+ }
919
+ /**
920
+ * Wrap any LLM stream (OpenAI, Anthropic, Gemini) with zero added latency
921
+ */
922
+ wrapStream(stream, options = {}) {
923
+ return wrapUniversalStream(stream, options, (event) => {
924
+ this.batcher.enqueue(event);
925
+ });
926
+ }
927
+ /**
928
+ * Directly record token usage manually
929
+ */
930
+ recordUsage(options) {
931
+ const inputTokens = options.inputTokens ?? 0;
932
+ const outputTokens = options.outputTokens ?? 0;
933
+ const reasoningTokens = options.reasoningTokens;
934
+ const cachedTokens = options.cachedTokens;
935
+ const usage = {
936
+ inputTokens,
937
+ outputTokens,
938
+ totalTokens: inputTokens + outputTokens,
939
+ reasoningTokens,
940
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
941
+ cachedTokens
942
+ };
943
+ const cost = calculateUsageCost(options.model, usage, this.markupMultiplier);
944
+ const normalized = normalizeCustomer(options.customer, options.customerId);
945
+ const mergedMeta = {
946
+ ...normalized.customerMetadata,
947
+ ...options.metadata
948
+ };
949
+ const event = {
950
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
951
+ model: options.model,
952
+ provider: options.provider || "custom",
953
+ usage,
954
+ cost,
955
+ customerId: normalized.customerId,
956
+ customerEmail: normalized.customerEmail,
957
+ customer: normalized.customerObj,
958
+ metadata: mergedMeta
959
+ };
960
+ this.batcher.enqueue(event);
961
+ return event;
962
+ }
963
+ /**
964
+ * Flush pending events to Stripe (vital for Serverless & Edge environments)
965
+ */
966
+ async flush() {
967
+ await this.batcher.flush();
968
+ }
969
+ /**
970
+ * Get in-memory aggregated usage statistics
971
+ */
972
+ getUsageSummary() {
973
+ return this.batcher.getSummary();
974
+ }
975
+ /**
976
+ * Reset in-memory ledger
977
+ */
978
+ resetSummary() {
979
+ this.batcher.resetLedger();
980
+ }
981
+ };
982
+ function createMeter(options = {}) {
983
+ return new VibezMeter(options);
984
+ }
985
+
986
+ // src/ai-sdk/with-billing.ts
987
+ function withBilling(model, options = {}) {
988
+ if (!model || typeof model !== "object") {
989
+ return model;
990
+ }
991
+ const meter = options.meter || createMeter({
992
+ apiKey: options.stripeApiKey,
993
+ eventName: options.eventName
994
+ });
995
+ const normalized = normalizeCustomer(options.customer, options.customerId);
996
+ const customerId = normalized.customerId;
997
+ const customerEmail = normalized.customerEmail;
998
+ const customerObj = normalized.customerObj;
999
+ const customerMetadata = normalized.customerMetadata;
1000
+ const modelId = model.modelId || "unknown-model";
1001
+ const provider = model.provider?.replace(/^@ai-sdk\//, "") || "ai-sdk";
1002
+ const maxCostPerCall = options.maxCostPerCallUSD !== void 0 ? options.maxCostPerCallUSD : 0.5;
1003
+ const captureOnAbort = options.captureOnAbort !== false;
1004
+ const scheduleFlush = () => {
1005
+ try {
1006
+ const flushPromise = meter.flush();
1007
+ if (typeof globalThis !== "undefined") {
1008
+ const g = globalThis;
1009
+ if (typeof g.after === "function") {
1010
+ g.after(() => flushPromise);
1011
+ return;
1012
+ }
1013
+ }
1014
+ } catch {
1015
+ }
1016
+ };
1017
+ const handleUsage = (rawUsage, extraMeta) => {
1018
+ if (!rawUsage) return;
1019
+ const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? 0;
1020
+ const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? 0;
1021
+ const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? 0;
1022
+ const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? 0;
1023
+ const usage = {
1024
+ inputTokens,
1025
+ outputTokens,
1026
+ totalTokens: inputTokens + outputTokens,
1027
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
1028
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
1029
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
1030
+ };
1031
+ const cost = calculateUsageCost(modelId, usage, {
1032
+ markupMultiplier: options.pricing?.margin,
1033
+ minimumChargeUSD: options.pricing?.minimumChargeUSD,
1034
+ customRate: options.rate
1035
+ });
1036
+ if (maxCostPerCall > 0 && maxCostPerCall !== Infinity && cost.totalUSD > maxCostPerCall) {
1037
+ const budgetEvent = {
1038
+ reason: "cost_per_call_exceeded",
1039
+ limit: maxCostPerCall,
1040
+ current: cost.totalUSD,
1041
+ model: modelId,
1042
+ customerId,
1043
+ message: `[vibezcheck] Circuit Breaker tripped: Call cost ($${cost.totalUSD.toFixed(4)}) exceeded budget ceiling ($${maxCostPerCall.toFixed(4)}).`
1044
+ };
1045
+ if (options.onBudgetExceeded) {
1046
+ options.onBudgetExceeded(budgetEvent);
1047
+ }
1048
+ if (options.throwOnBudgetExceeded) {
1049
+ throw new VibezCircuitBreakerError(budgetEvent);
1050
+ }
1051
+ }
1052
+ if (options.maxTokensPerCall && usage.totalTokens > options.maxTokensPerCall) {
1053
+ const budgetEvent = {
1054
+ reason: "max_tokens_exceeded",
1055
+ limit: options.maxTokensPerCall,
1056
+ current: usage.totalTokens,
1057
+ model: modelId,
1058
+ customerId,
1059
+ message: `[vibezcheck] Circuit Breaker tripped: Token count (${usage.totalTokens}) exceeded maxTokensPerCall limit (${options.maxTokensPerCall}).`
1060
+ };
1061
+ if (options.onBudgetExceeded) {
1062
+ options.onBudgetExceeded(budgetEvent);
1063
+ }
1064
+ if (options.throwOnBudgetExceeded) {
1065
+ throw new VibezCircuitBreakerError(budgetEvent);
1066
+ }
1067
+ }
1068
+ const mergedMetadata = {
1069
+ ...customerMetadata,
1070
+ ...options.metadata,
1071
+ ...extraMeta,
1072
+ billingMode: options.billing?.mode || "postpaid"
1073
+ };
1074
+ const event = {
1075
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1076
+ model: modelId,
1077
+ provider,
1078
+ usage,
1079
+ cost,
1080
+ customerId,
1081
+ customerEmail,
1082
+ customer: customerObj,
1083
+ metadata: mergedMetadata
1084
+ };
1085
+ meter.recordUsage({
1086
+ model: modelId,
1087
+ provider,
1088
+ inputTokens,
1089
+ outputTokens,
1090
+ reasoningTokens: usage.reasoningTokens,
1091
+ cachedTokens: usage.cachedTokens,
1092
+ customerId,
1093
+ customer: customerObj,
1094
+ metadata: event.metadata
1095
+ });
1096
+ if (options.onUsage) {
1097
+ options.onUsage(event);
1098
+ }
1099
+ if (options.database) {
1100
+ const dbTarget = options.database;
1101
+ const executeDbWrite = async () => {
1102
+ try {
1103
+ 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;
1104
+ if (supabaseClient) {
1105
+ const tableName = dbTarget?.table || "vibez_usage";
1106
+ await supabaseClient.from(tableName).insert({
1107
+ customer_id: customerId,
1108
+ user_id: customerObj?.userId || customerId,
1109
+ model: modelId,
1110
+ input_tokens: usage.inputTokens,
1111
+ output_tokens: usage.outputTokens,
1112
+ total_tokens: usage.totalTokens,
1113
+ cached_tokens: usage.cachedTokens,
1114
+ reasoning_tokens: usage.reasoningTokens,
1115
+ cost_usd: cost.totalUSD,
1116
+ created_at: event.timestamp,
1117
+ metadata: event.metadata
1118
+ });
1119
+ return;
1120
+ }
1121
+ if (typeof dbTarget === "object" && dbTarget !== null && typeof dbTarget.save === "function") {
1122
+ await dbTarget.save(event);
1123
+ return;
1124
+ }
1125
+ if (typeof dbTarget === "function") {
1126
+ await dbTarget(event);
1127
+ return;
1128
+ }
1129
+ } catch (err) {
1130
+ console.warn(`[vibezcheck] Database record failed safely:`, err?.message || err);
1131
+ }
1132
+ };
1133
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1134
+ globalThis.after(() => executeDbWrite());
1135
+ } else {
1136
+ executeDbWrite().catch(() => {
1137
+ });
1138
+ }
1139
+ }
1140
+ if (options.billing?.charge && typeof options.billing.charge === "function") {
1141
+ const chargeFn = options.billing.charge;
1142
+ const executeCharge = async () => {
1143
+ try {
1144
+ await chargeFn(cost.totalUSD, event);
1145
+ } catch (err) {
1146
+ console.warn(`[vibezcheck] Custom charge handler failed safely:`, err?.message || err);
1147
+ }
1148
+ };
1149
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1150
+ globalThis.after(() => executeCharge());
1151
+ } else {
1152
+ executeCharge().catch(() => {
1153
+ });
1154
+ }
1155
+ } else if (options.billing?.provider && typeof options.billing.provider === "object" && typeof options.billing.provider.charge === "function") {
1156
+ const providerCharge = options.billing.provider.charge;
1157
+ const executeCharge = async () => {
1158
+ try {
1159
+ await providerCharge(cost.totalUSD, event);
1160
+ } catch (err) {
1161
+ console.warn(`[vibezcheck] Payment provider charge failed safely:`, err?.message || err);
1162
+ }
1163
+ };
1164
+ if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
1165
+ globalThis.after(() => executeCharge());
1166
+ } else {
1167
+ executeCharge().catch(() => {
1168
+ });
1169
+ }
1170
+ }
1171
+ scheduleFlush();
1172
+ };
1173
+ const handler = {
1174
+ get(target, prop, receiver) {
1175
+ const originalValue = Reflect.get(target, prop, receiver);
1176
+ if (prop === "doStream" && typeof originalValue === "function") {
1177
+ return async function(...args) {
1178
+ const result = await originalValue.apply(target, args);
1179
+ if (!result || !result.stream) {
1180
+ return result;
1181
+ }
1182
+ const originalStream = result.stream;
1183
+ let streamCompleted = false;
1184
+ let accumulatedChars = 0;
1185
+ let estimatedInputTokens = 0;
1186
+ try {
1187
+ if (args[0]?.prompt) {
1188
+ const str = typeof args[0].prompt === "string" ? args[0].prompt : JSON.stringify(args[0].prompt);
1189
+ estimatedInputTokens = Math.ceil(str.length / 4);
1190
+ }
1191
+ } catch {
1192
+ }
1193
+ const abortSignal = args[0]?.abortSignal;
1194
+ if (abortSignal && captureOnAbort) {
1195
+ abortSignal.addEventListener(
1196
+ "abort",
1197
+ () => {
1198
+ if (!streamCompleted && accumulatedChars > 0) {
1199
+ streamCompleted = true;
1200
+ const estimatedOutputTokens = Math.ceil(accumulatedChars / 3.8);
1201
+ handleUsage(
1202
+ {
1203
+ inputTokens: estimatedInputTokens,
1204
+ outputTokens: estimatedOutputTokens
1205
+ },
1206
+ { aborted: true, partial: true }
1207
+ );
1208
+ }
1209
+ },
1210
+ { once: true }
1211
+ );
1212
+ }
1213
+ const transformStream = new TransformStream({
1214
+ transform(chunk, controller) {
1215
+ controller.enqueue(chunk);
1216
+ if (chunk.type === "text-delta" && chunk.textDelta) {
1217
+ accumulatedChars += chunk.textDelta.length;
1218
+ } else if (chunk.type === "reasoning" && (chunk.textDelta || chunk.reasoning)) {
1219
+ accumulatedChars += (chunk.textDelta || chunk.reasoning || "").length;
1220
+ }
1221
+ if (chunk.type === "finish" && chunk.usage) {
1222
+ streamCompleted = true;
1223
+ handleUsage(chunk.usage);
1224
+ }
1225
+ },
1226
+ flush() {
1227
+ if (!streamCompleted && captureOnAbort && accumulatedChars > 0) {
1228
+ streamCompleted = true;
1229
+ const estimatedOutputTokens = Math.ceil(accumulatedChars / 3.8);
1230
+ handleUsage(
1231
+ {
1232
+ inputTokens: estimatedInputTokens,
1233
+ outputTokens: estimatedOutputTokens
1234
+ },
1235
+ { aborted: true, partial: true }
1236
+ );
1237
+ }
1238
+ }
1239
+ });
1240
+ return {
1241
+ ...result,
1242
+ stream: originalStream.pipeThrough(transformStream)
1243
+ };
1244
+ };
1245
+ }
1246
+ if (prop === "doGenerate" && typeof originalValue === "function") {
1247
+ return async function(...args) {
1248
+ const result = await originalValue.apply(target, args);
1249
+ if (result && result.usage) {
1250
+ handleUsage(result.usage);
1251
+ }
1252
+ return result;
1253
+ };
1254
+ }
1255
+ return originalValue;
1256
+ }
1257
+ };
1258
+ return new Proxy(model, handler);
1259
+ }
1260
+
1261
+ // src/ai-sdk/middleware.ts
1262
+ function vibezcheckMiddleware(options = {}) {
1263
+ return {
1264
+ specificationVersion: "v1",
1265
+ wrapGenerate: async ({ doGenerate, params, model }) => {
1266
+ const metered = withBilling(model, options);
1267
+ return metered.doGenerate(params);
1268
+ },
1269
+ wrapStream: async ({ doStream, params, model }) => {
1270
+ const metered = withBilling(model, options);
1271
+ return metered.doStream(params);
1272
+ }
1273
+ };
1274
+ }
1275
+ var middleware_default = vibezcheckMiddleware;
1276
+ // Annotate the CommonJS export names for ESM import in node:
1277
+ 0 && (module.exports = {
1278
+ vibezcheckMiddleware
1279
+ });
1280
+ //# sourceMappingURL=middleware.js.map