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