vibezcheck 0.1.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/dist/ai-sdk/index.d.mts +34 -0
  4. package/dist/ai-sdk/index.d.ts +34 -0
  5. package/dist/ai-sdk/index.js +982 -0
  6. package/dist/ai-sdk/index.js.map +1 -0
  7. package/dist/ai-sdk/index.mjs +944 -0
  8. package/dist/ai-sdk/index.mjs.map +1 -0
  9. package/dist/auth/index.d.mts +59 -0
  10. package/dist/auth/index.d.ts +59 -0
  11. package/dist/auth/index.js +129 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/index.mjs +90 -0
  14. package/dist/auth/index.mjs.map +1 -0
  15. package/dist/billing/index.d.mts +48 -0
  16. package/dist/billing/index.d.ts +48 -0
  17. package/dist/billing/index.js +128 -0
  18. package/dist/billing/index.js.map +1 -0
  19. package/dist/billing/index.mjs +90 -0
  20. package/dist/billing/index.mjs.map +1 -0
  21. package/dist/client-MJ3tl7bz.d.mts +44 -0
  22. package/dist/client-txrE0D_D.d.ts +44 -0
  23. package/dist/customers/index.d.mts +49 -0
  24. package/dist/customers/index.d.ts +49 -0
  25. package/dist/customers/index.js +158 -0
  26. package/dist/customers/index.js.map +1 -0
  27. package/dist/customers/index.mjs +119 -0
  28. package/dist/customers/index.mjs.map +1 -0
  29. package/dist/index.d.mts +92 -0
  30. package/dist/index.d.ts +92 -0
  31. package/dist/index.js +1458 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/index.mjs +1386 -0
  34. package/dist/index.mjs.map +1 -0
  35. package/dist/meter/index.d.mts +131 -0
  36. package/dist/meter/index.d.ts +131 -0
  37. package/dist/meter/index.js +895 -0
  38. package/dist/meter/index.js.map +1 -0
  39. package/dist/meter/index.mjs +843 -0
  40. package/dist/meter/index.mjs.map +1 -0
  41. package/dist/pricing/index.d.mts +40 -0
  42. package/dist/pricing/index.d.ts +40 -0
  43. package/dist/pricing/index.js +178 -0
  44. package/dist/pricing/index.js.map +1 -0
  45. package/dist/pricing/index.mjs +146 -0
  46. package/dist/pricing/index.mjs.map +1 -0
  47. package/dist/types-CSrSmsd1.d.mts +159 -0
  48. package/dist/types-CSrSmsd1.d.ts +159 -0
  49. package/package.json +131 -0
@@ -0,0 +1,944 @@
1
+ // src/meter/client.ts
2
+ import Stripe from "stripe";
3
+
4
+ // src/meter/batcher.ts
5
+ var MeterBatcher = class {
6
+ queue = [];
7
+ timer = null;
8
+ isFlushing = false;
9
+ maxBatchSize;
10
+ flushIntervalMs;
11
+ stripeClient;
12
+ eventName;
13
+ onUsageCallback;
14
+ onErrorCallback;
15
+ debug;
16
+ // In-memory ledger for local stats
17
+ totalRequests = 0;
18
+ totalTokens = 0;
19
+ totalInputTokens = 0;
20
+ totalOutputTokens = 0;
21
+ totalReasoningTokens = 0;
22
+ totalCostUSD = 0;
23
+ byModel = {};
24
+ constructor(options = {}) {
25
+ this.stripeClient = options.stripe;
26
+ this.eventName = options.eventName || "token-billing-tokens";
27
+ this.maxBatchSize = options.batching?.maxBatchSize ?? 50;
28
+ this.flushIntervalMs = options.batching?.flushIntervalMs ?? 50;
29
+ this.onUsageCallback = options.onUsage;
30
+ this.onErrorCallback = options.onError;
31
+ this.debug = options.debug ?? false;
32
+ }
33
+ /**
34
+ * Enqueue a usage event for batch dispatching
35
+ */
36
+ enqueue(event) {
37
+ this.recordInLedger(event);
38
+ if (this.onUsageCallback) {
39
+ try {
40
+ const res = this.onUsageCallback(event);
41
+ if (res instanceof Promise) {
42
+ res.catch((err) => {
43
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
44
+ });
45
+ }
46
+ } catch (err) {
47
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
48
+ }
49
+ }
50
+ if (!this.stripeClient) {
51
+ if (this.debug) {
52
+ console.log(
53
+ `[vibezcheck:local] \u{1F4CA} ${event.model} | Tokens: ${event.usage.totalTokens} | Cost: $${event.cost.totalUSD.toFixed(6)}`
54
+ );
55
+ }
56
+ return;
57
+ }
58
+ this.queue.push(event);
59
+ if (this.queue.length >= this.maxBatchSize) {
60
+ this.flush().catch((err) => {
61
+ if (this.debug) console.error("[vibezcheck] Batch flush error:", err);
62
+ });
63
+ } else if (!this.timer) {
64
+ this.timer = setTimeout(() => {
65
+ this.timer = null;
66
+ this.flush().catch((err) => {
67
+ if (this.debug) console.error("[vibezcheck] Debounce flush error:", err);
68
+ });
69
+ }, this.flushIntervalMs);
70
+ }
71
+ }
72
+ /**
73
+ * Immediately flush all queued events to Stripe
74
+ */
75
+ async flush() {
76
+ if (this.timer) {
77
+ clearTimeout(this.timer);
78
+ this.timer = null;
79
+ }
80
+ if (this.queue.length === 0 || !this.stripeClient || this.isFlushing) {
81
+ return;
82
+ }
83
+ this.isFlushing = true;
84
+ const eventsToSend = [...this.queue];
85
+ this.queue = [];
86
+ try {
87
+ await this.sendEventsToStripe(eventsToSend);
88
+ } catch (error) {
89
+ const err = error instanceof Error ? error : new Error(String(error));
90
+ if (this.debug) {
91
+ console.error("[vibezcheck] Failed to send meter events to Stripe:", err);
92
+ }
93
+ if (this.onErrorCallback) {
94
+ this.onErrorCallback(err, eventsToSend);
95
+ }
96
+ } finally {
97
+ this.isFlushing = false;
98
+ if (this.queue.length > 0) {
99
+ this.flush().catch(() => {
100
+ });
101
+ }
102
+ }
103
+ }
104
+ /**
105
+ * Sends events to Stripe Billing Meter Events API
106
+ */
107
+ async sendEventsToStripe(events) {
108
+ if (!this.stripeClient) return;
109
+ for (const event of events) {
110
+ const customerId = event.customerId;
111
+ if (!customerId) {
112
+ continue;
113
+ }
114
+ const timestamp = event.timestamp || (/* @__PURE__ */ new Date()).toISOString();
115
+ const model = `${event.provider}/${event.model}`;
116
+ if (event.usage.inputTokens > 0) {
117
+ try {
118
+ await this.stripeClient.v2.billing.meterEvents.create({
119
+ event_name: this.eventName,
120
+ timestamp,
121
+ payload: {
122
+ stripe_customer_id: customerId,
123
+ value: event.usage.inputTokens.toString(),
124
+ model,
125
+ token_type: "input",
126
+ cached_tokens: (event.usage.cachedTokens ?? 0).toString(),
127
+ ...event.metadata ? event.metadata : {}
128
+ }
129
+ });
130
+ } catch (e) {
131
+ if (this.debug) console.warn("[vibezcheck] Input meter event error:", e);
132
+ }
133
+ }
134
+ if (event.usage.outputTokens > 0) {
135
+ try {
136
+ await this.stripeClient.v2.billing.meterEvents.create({
137
+ event_name: this.eventName,
138
+ timestamp,
139
+ payload: {
140
+ stripe_customer_id: customerId,
141
+ value: event.usage.outputTokens.toString(),
142
+ model,
143
+ token_type: "output",
144
+ reasoning_tokens: (event.usage.reasoningTokens ?? 0).toString(),
145
+ visible_tokens: (event.usage.visibleOutputTokens ?? event.usage.outputTokens).toString(),
146
+ ...event.metadata ? event.metadata : {}
147
+ }
148
+ });
149
+ } catch (e) {
150
+ if (this.debug) console.warn("[vibezcheck] Output meter event error:", e);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ /**
156
+ * Updates internal in-memory ledger
157
+ */
158
+ recordInLedger(event) {
159
+ this.totalRequests += 1;
160
+ this.totalTokens += event.usage.totalTokens;
161
+ this.totalInputTokens += event.usage.inputTokens;
162
+ this.totalOutputTokens += event.usage.outputTokens;
163
+ this.totalReasoningTokens += event.usage.reasoningTokens ?? 0;
164
+ this.totalCostUSD += event.cost.totalUSD;
165
+ const modelKey = event.model;
166
+ if (!this.byModel[modelKey]) {
167
+ this.byModel[modelKey] = { requests: 0, tokens: 0, costUSD: 0 };
168
+ }
169
+ this.byModel[modelKey].requests += 1;
170
+ this.byModel[modelKey].tokens += event.usage.totalTokens;
171
+ this.byModel[modelKey].costUSD += event.cost.totalUSD;
172
+ }
173
+ /**
174
+ * Get in-memory usage summary
175
+ */
176
+ getSummary() {
177
+ return {
178
+ totalRequests: this.totalRequests,
179
+ totalTokens: this.totalTokens,
180
+ totalInputTokens: this.totalInputTokens,
181
+ totalOutputTokens: this.totalOutputTokens,
182
+ totalReasoningTokens: this.totalReasoningTokens,
183
+ totalCostUSD: Number(this.totalCostUSD.toFixed(6)),
184
+ byModel: { ...this.byModel }
185
+ };
186
+ }
187
+ /**
188
+ * Reset in-memory ledger
189
+ */
190
+ resetLedger() {
191
+ this.totalRequests = 0;
192
+ this.totalTokens = 0;
193
+ this.totalInputTokens = 0;
194
+ this.totalOutputTokens = 0;
195
+ this.totalReasoningTokens = 0;
196
+ this.totalCostUSD = 0;
197
+ this.byModel = {};
198
+ }
199
+ };
200
+
201
+ // src/meter/extractors/openai.ts
202
+ function extractOpenAIResponseUsage(response) {
203
+ if (!response || typeof response !== "object") return null;
204
+ if ("choices" in response && "usage" in response && response.usage) {
205
+ const rawUsage = response.usage;
206
+ const model = response.model || "gpt-4o";
207
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
208
+ const outputTokens = rawUsage.completion_tokens ?? 0;
209
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
210
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
211
+ return {
212
+ model,
213
+ provider: "openai",
214
+ usage: {
215
+ inputTokens,
216
+ outputTokens,
217
+ totalTokens: inputTokens + outputTokens,
218
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
219
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
220
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
221
+ }
222
+ };
223
+ }
224
+ if ("data" in response && "usage" in response && response.usage && "model" in response) {
225
+ const rawUsage = response.usage;
226
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
227
+ return {
228
+ model: response.model || "text-embedding-3-small",
229
+ provider: "openai",
230
+ usage: {
231
+ inputTokens,
232
+ outputTokens: 0,
233
+ totalTokens: inputTokens
234
+ }
235
+ };
236
+ }
237
+ if ("status" in response && "usage" in response && response.usage) {
238
+ const rawUsage = response.usage;
239
+ const model = response.model || "gpt-5.6-sol";
240
+ const inputTokens = rawUsage.input_tokens ?? rawUsage.prompt_tokens ?? 0;
241
+ const outputTokens = rawUsage.output_tokens ?? rawUsage.completion_tokens ?? 0;
242
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
243
+ const cachedTokens = rawUsage.input_token_details?.cached_tokens ?? rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
244
+ return {
245
+ model,
246
+ provider: "openai",
247
+ usage: {
248
+ inputTokens,
249
+ outputTokens,
250
+ totalTokens: inputTokens + outputTokens,
251
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
252
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
253
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
254
+ }
255
+ };
256
+ }
257
+ return null;
258
+ }
259
+ function inspectOpenAIStreamChunk(chunk) {
260
+ if (!chunk || typeof chunk !== "object") return {};
261
+ const model = chunk.model;
262
+ if (chunk.usage) {
263
+ const rawUsage = chunk.usage;
264
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? 0;
265
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? 0;
266
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? 0;
267
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? 0;
268
+ return {
269
+ model,
270
+ usage: {
271
+ inputTokens,
272
+ outputTokens,
273
+ totalTokens: inputTokens + outputTokens,
274
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
275
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
276
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
277
+ }
278
+ };
279
+ }
280
+ if (chunk.type === "response.completed" || chunk.type === "response.done") {
281
+ if (chunk.response?.usage) {
282
+ const rawUsage = chunk.response.usage;
283
+ const inputTokens = rawUsage.input_tokens ?? 0;
284
+ const outputTokens = rawUsage.output_tokens ?? 0;
285
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? 0;
286
+ const cachedTokens = rawUsage.input_token_details?.cached_tokens ?? 0;
287
+ return {
288
+ model: chunk.response.model || model,
289
+ usage: {
290
+ inputTokens,
291
+ outputTokens,
292
+ totalTokens: inputTokens + outputTokens,
293
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
294
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
295
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
296
+ }
297
+ };
298
+ }
299
+ }
300
+ return { model };
301
+ }
302
+
303
+ // src/meter/extractors/anthropic.ts
304
+ function extractAnthropicResponseUsage(response) {
305
+ if (!response || typeof response !== "object") return null;
306
+ if (response.type === "message" || "content" in response && "usage" in response) {
307
+ const rawUsage = response.usage || {};
308
+ const model = response.model || "claude-3-7-sonnet";
309
+ const inputTokens = rawUsage.input_tokens ?? 0;
310
+ const outputTokens = rawUsage.output_tokens ?? 0;
311
+ const cachedTokens = rawUsage.cache_read_input_tokens ?? 0;
312
+ const cacheWriteTokens = rawUsage.cache_creation_input_tokens ?? 0;
313
+ let reasoningTokens = void 0;
314
+ if (Array.isArray(response.content)) {
315
+ const thinkingBlocks = response.content.filter((b) => b.type === "thinking");
316
+ if (thinkingBlocks.length > 0) {
317
+ reasoningTokens = rawUsage.thinking_tokens ?? void 0;
318
+ }
319
+ }
320
+ return {
321
+ model,
322
+ provider: "anthropic",
323
+ usage: {
324
+ inputTokens,
325
+ outputTokens,
326
+ totalTokens: inputTokens + outputTokens,
327
+ reasoningTokens,
328
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
329
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0,
330
+ cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : void 0
331
+ }
332
+ };
333
+ }
334
+ return null;
335
+ }
336
+ var AnthropicStreamAccumulator = class {
337
+ model = "claude-3-7-sonnet";
338
+ inputTokens = 0;
339
+ outputTokens = 0;
340
+ cachedTokens = 0;
341
+ cacheWriteTokens = 0;
342
+ reasoningTokens = 0;
343
+ processEvent(event) {
344
+ if (!event || typeof event !== "object") return;
345
+ if (event.type === "message_start" && event.message) {
346
+ if (event.message.model) {
347
+ this.model = event.message.model;
348
+ }
349
+ if (event.message.usage) {
350
+ this.inputTokens = event.message.usage.input_tokens ?? 0;
351
+ this.cachedTokens = event.message.usage.cache_read_input_tokens ?? 0;
352
+ this.cacheWriteTokens = event.message.usage.cache_creation_input_tokens ?? 0;
353
+ }
354
+ }
355
+ if (event.type === "message_delta" && event.usage) {
356
+ this.outputTokens = event.usage.output_tokens ?? 0;
357
+ if (event.usage.thinking_tokens) {
358
+ this.reasoningTokens = event.usage.thinking_tokens;
359
+ }
360
+ }
361
+ if (event.type === "content_block_start" && event.content_block?.type === "thinking") {
362
+ }
363
+ }
364
+ getUsage() {
365
+ return {
366
+ model: this.model,
367
+ provider: "anthropic",
368
+ usage: {
369
+ inputTokens: this.inputTokens,
370
+ outputTokens: this.outputTokens,
371
+ totalTokens: this.inputTokens + this.outputTokens,
372
+ reasoningTokens: this.reasoningTokens > 0 ? this.reasoningTokens : void 0,
373
+ visibleOutputTokens: this.reasoningTokens > 0 ? Math.max(0, this.outputTokens - this.reasoningTokens) : this.outputTokens,
374
+ cachedTokens: this.cachedTokens > 0 ? this.cachedTokens : void 0,
375
+ cacheWriteTokens: this.cacheWriteTokens > 0 ? this.cacheWriteTokens : void 0
376
+ }
377
+ };
378
+ }
379
+ };
380
+
381
+ // src/meter/extractors/gemini.ts
382
+ function extractGeminiResponseUsage(response, fallbackModel = "gemini-3.7-flash") {
383
+ if (!response || typeof response !== "object") return null;
384
+ const usageMetadata = response.usageMetadata || response.response?.usageMetadata;
385
+ if (usageMetadata) {
386
+ const inputTokens = usageMetadata.promptTokenCount ?? 0;
387
+ const baseOutputTokens = usageMetadata.candidatesTokenCount ?? 0;
388
+ const thoughtsTokenCount = usageMetadata.thoughtsTokenCount ?? usageMetadata.reasoningTokenCount ?? 0;
389
+ const cachedTokens = usageMetadata.cachedContentTokenCount ?? 0;
390
+ const totalOutput = baseOutputTokens + thoughtsTokenCount;
391
+ const model = response.model || response.response?.model || fallbackModel;
392
+ return {
393
+ model,
394
+ provider: "google",
395
+ usage: {
396
+ inputTokens,
397
+ outputTokens: totalOutput,
398
+ totalTokens: inputTokens + totalOutput,
399
+ reasoningTokens: thoughtsTokenCount > 0 ? thoughtsTokenCount : void 0,
400
+ visibleOutputTokens: baseOutputTokens,
401
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
402
+ }
403
+ };
404
+ }
405
+ return null;
406
+ }
407
+
408
+ // src/meter/extractors/generic.ts
409
+ function extractGenericResponseUsage(response, fallbackModel = "generic-llm", fallbackProvider = "generic") {
410
+ if (!response || typeof response !== "object") return null;
411
+ const usage = response.usage || response.token_usage || response.usageMetadata;
412
+ if (usage) {
413
+ const inputTokens = usage.prompt_tokens ?? usage.input_tokens ?? usage.promptTokenCount ?? usage.prompt_eval_count ?? 0;
414
+ const outputTokens = usage.completion_tokens ?? usage.output_tokens ?? usage.candidatesTokenCount ?? usage.eval_count ?? 0;
415
+ const reasoningTokens = usage.reasoning_tokens ?? usage.thoughtsTokenCount ?? usage.completion_tokens_details?.reasoning_tokens ?? 0;
416
+ const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens ?? usage.cachedContentTokenCount ?? 0;
417
+ const model = response.model || fallbackModel;
418
+ const provider = response.provider || fallbackProvider;
419
+ return {
420
+ model,
421
+ provider,
422
+ usage: {
423
+ inputTokens,
424
+ outputTokens,
425
+ totalTokens: inputTokens + outputTokens,
426
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
427
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
428
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
429
+ }
430
+ };
431
+ }
432
+ return null;
433
+ }
434
+
435
+ // src/meter/extractors/index.ts
436
+ function detectAndExtractUsage(response, fallbackModel, fallbackProvider) {
437
+ if (!response || typeof response !== "object") return null;
438
+ const openaiResult = extractOpenAIResponseUsage(response);
439
+ if (openaiResult) return openaiResult;
440
+ const anthropicResult = extractAnthropicResponseUsage(response);
441
+ if (anthropicResult) return anthropicResult;
442
+ const geminiResult = extractGeminiResponseUsage(response, fallbackModel);
443
+ if (geminiResult) return geminiResult;
444
+ const genericResult = extractGenericResponseUsage(response, fallbackModel, fallbackProvider);
445
+ if (genericResult) return genericResult;
446
+ return null;
447
+ }
448
+
449
+ // src/pricing/table.ts
450
+ var MODEL_PRICING_TABLE = {
451
+ // --- OpenAI ---
452
+ "gpt-5.6-sol": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
453
+ "gpt-5.6-terra": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.2 },
454
+ "gpt-5.6-luna": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
455
+ "gpt-5": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
456
+ "gpt-5-mini": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
457
+ "o1": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
458
+ "o1-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
459
+ "o3": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
460
+ "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
461
+ "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10, cachedInputPer1M: 1.25 },
462
+ "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.075 },
463
+ "gpt-4.1": { inputPer1M: 2, outputPer1M: 8, cachedInputPer1M: 1 },
464
+ "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.05 },
465
+ "text-embedding-3-small": { inputPer1M: 0.02, outputPer1M: 0 },
466
+ "text-embedding-3-large": { inputPer1M: 0.13, outputPer1M: 0 },
467
+ // --- Anthropic ---
468
+ "claude-3-7-sonnet": { inputPer1M: 0.59, outputPer1M: 2.93, cachedInputPer1M: 0.3 },
469
+ "claude-sonnet-5": { inputPer1M: 2, outputPer1M: 10, cachedInputPer1M: 0.3 },
470
+ "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
471
+ "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4, cachedInputPer1M: 0.08 },
472
+ "haiku-4.5": { inputPer1M: 1, outputPer1M: 5, cachedInputPer1M: 0.1 },
473
+ "claude-opus-5": { inputPer1M: 5, outputPer1M: 25, cachedInputPer1M: 1.5 },
474
+ "claude-3-opus": { inputPer1M: 15, outputPer1M: 75, cachedInputPer1M: 1.5 },
475
+ // --- Google Gemini ---
476
+ "gemini-3.7-flash": { inputPer1M: 0.75, outputPer1M: 3.75, cachedInputPer1M: 0.18 },
477
+ "gemini-3.1-pro": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.5 },
478
+ "gemini-3.5-flash": { inputPer1M: 1.5, outputPer1M: 9, cachedInputPer1M: 0.38 },
479
+ "gemini-3.1-flash-lite": { inputPer1M: 0.25, outputPer1M: 1.5, cachedInputPer1M: 0.06 },
480
+ "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.025 },
481
+ "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
482
+ "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
483
+ // --- xAI Grok ---
484
+ "grok-4.6": { inputPer1M: 3, outputPer1M: 15 },
485
+ "grok-2": { inputPer1M: 2, outputPer1M: 10 },
486
+ "grok-2-vision": { inputPer1M: 2, outputPer1M: 10 },
487
+ "grok-beta": { inputPer1M: 5, outputPer1M: 15 },
488
+ // --- Mistral ---
489
+ "mistral-large-3": { inputPer1M: 2, outputPer1M: 6 },
490
+ "mistral-large-latest": { inputPer1M: 2, outputPer1M: 6 },
491
+ "codestral-latest": { inputPer1M: 0.3, outputPer1M: 0.9 },
492
+ "mistral-small-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
493
+ "ministral-8b-latest": { inputPer1M: 0.1, outputPer1M: 0.1 },
494
+ // --- Groq LPUs ---
495
+ "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
496
+ "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
497
+ "deepseek-r1-distill-llama-70b": { inputPer1M: 0.75, outputPer1M: 0.99 },
498
+ "qwen-2.5-32b": { inputPer1M: 0.29, outputPer1M: 0.39 },
499
+ // --- DeepSeek ---
500
+ "deepseek-v4-pro": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
501
+ "deepseek-v4-flash": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
502
+ "deepseek-chat": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
503
+ "deepseek-reasoner": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
504
+ // --- Cohere ---
505
+ "command-r-plus": { inputPer1M: 2.5, outputPer1M: 10 },
506
+ "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 }
507
+ };
508
+ var customPricingRegistry = {};
509
+ function normalizeModelKey(rawModel) {
510
+ if (!rawModel) return "unknown";
511
+ let model = rawModel.toLowerCase().trim();
512
+ if (model.includes("/")) {
513
+ model = model.split("/")[1] || model;
514
+ }
515
+ model = model.replace(/-\d{8}$/, "");
516
+ model = model.replace(/-\d{4}-\d{2}-\d{2}$/, "");
517
+ return model;
518
+ }
519
+ function getModelPricing(modelName) {
520
+ const normalized = normalizeModelKey(modelName);
521
+ if (customPricingRegistry[normalized]) {
522
+ return customPricingRegistry[normalized];
523
+ }
524
+ if (customPricingRegistry[modelName]) {
525
+ return customPricingRegistry[modelName];
526
+ }
527
+ if (MODEL_PRICING_TABLE[normalized]) {
528
+ return MODEL_PRICING_TABLE[normalized];
529
+ }
530
+ if (MODEL_PRICING_TABLE[modelName]) {
531
+ return MODEL_PRICING_TABLE[modelName];
532
+ }
533
+ return {
534
+ inputPer1M: 1,
535
+ outputPer1M: 3,
536
+ cachedInputPer1M: 0.5
537
+ };
538
+ }
539
+
540
+ // src/pricing/calculator.ts
541
+ function calculateCost(params) {
542
+ const rates = getModelPricing(params.model);
543
+ const inputTokens = params.inputTokens ?? 0;
544
+ const outputTokens = params.outputTokens ?? 0;
545
+ const reasoningTokens = params.reasoningTokens ?? 0;
546
+ const cachedTokens = params.cachedTokens ?? 0;
547
+ const regularInputTokens = Math.max(0, inputTokens - cachedTokens);
548
+ const regularInputCost = regularInputTokens / 1e6 * rates.inputPer1M;
549
+ const cachedRate = rates.cachedInputPer1M ?? rates.inputPer1M * 0.5;
550
+ const cachedInputCost = cachedTokens / 1e6 * cachedRate;
551
+ const inputCostUSD = regularInputCost + cachedInputCost;
552
+ const outputCostUSD = outputTokens / 1e6 * rates.outputPer1M;
553
+ const reasoningRate = rates.reasoningPer1M ?? rates.outputPer1M;
554
+ const reasoningCostUSD = reasoningTokens / 1e6 * reasoningRate;
555
+ const standardCacheCost = cachedTokens / 1e6 * rates.inputPer1M;
556
+ const cachedDiscountUSD = Math.max(0, standardCacheCost - cachedInputCost);
557
+ const totalUSD = inputCostUSD + outputCostUSD;
558
+ const markup = params.markupMultiplier ?? 1;
559
+ const retailUSD = markup !== 1 ? totalUSD * markup : void 0;
560
+ return {
561
+ inputCostUSD: Number(inputCostUSD.toFixed(8)),
562
+ outputCostUSD: Number(outputCostUSD.toFixed(8)),
563
+ reasoningCostUSD: reasoningTokens > 0 ? Number(reasoningCostUSD.toFixed(8)) : void 0,
564
+ cachedDiscountUSD: cachedTokens > 0 ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
565
+ totalUSD: Number(totalUSD.toFixed(8)),
566
+ retailUSD: retailUSD ? Number(retailUSD.toFixed(8)) : void 0,
567
+ currency: rates.currency || "USD"
568
+ };
569
+ }
570
+ function calculateUsageCost(model, usage, markupMultiplier) {
571
+ return calculateCost({
572
+ model,
573
+ inputTokens: usage.inputTokens,
574
+ outputTokens: usage.outputTokens,
575
+ reasoningTokens: usage.reasoningTokens,
576
+ cachedTokens: usage.cachedTokens,
577
+ cacheWriteTokens: usage.cacheWriteTokens,
578
+ markupMultiplier
579
+ });
580
+ }
581
+
582
+ // src/meter/stream.ts
583
+ function wrapOpenAIStream(stream, options, onComplete) {
584
+ let detectedModel = options.model || "gpt-4o";
585
+ let finalUsage = null;
586
+ const wrappedAsyncIterable = {
587
+ async *[Symbol.asyncIterator]() {
588
+ try {
589
+ for await (const chunk of stream) {
590
+ const inspected = inspectOpenAIStreamChunk(chunk);
591
+ if (inspected.model) {
592
+ detectedModel = inspected.model;
593
+ }
594
+ if (inspected.usage) {
595
+ finalUsage = inspected.usage;
596
+ }
597
+ yield chunk;
598
+ }
599
+ } finally {
600
+ if (finalUsage) {
601
+ const cost = calculateUsageCost(detectedModel, finalUsage);
602
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
603
+ const event = {
604
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
605
+ model: detectedModel,
606
+ provider: "openai",
607
+ usage: finalUsage,
608
+ cost,
609
+ customerId,
610
+ metadata: options.metadata
611
+ };
612
+ onComplete(event);
613
+ if (options.onUsage) {
614
+ options.onUsage(event);
615
+ }
616
+ }
617
+ }
618
+ }
619
+ };
620
+ return wrappedAsyncIterable;
621
+ }
622
+ function wrapAnthropicStream(stream, options, onComplete) {
623
+ const accumulator = new AnthropicStreamAccumulator();
624
+ const wrappedAsyncIterable = {
625
+ async *[Symbol.asyncIterator]() {
626
+ try {
627
+ for await (const event of stream) {
628
+ accumulator.processEvent(event);
629
+ yield event;
630
+ }
631
+ } finally {
632
+ const extracted = accumulator.getUsage();
633
+ const model = options.model || extracted.model;
634
+ const cost = calculateUsageCost(model, extracted.usage);
635
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
636
+ const usageEvent = {
637
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
638
+ model,
639
+ provider: "anthropic",
640
+ usage: extracted.usage,
641
+ cost,
642
+ customerId,
643
+ metadata: options.metadata
644
+ };
645
+ onComplete(usageEvent);
646
+ if (options.onUsage) {
647
+ options.onUsage(usageEvent);
648
+ }
649
+ }
650
+ }
651
+ };
652
+ return wrappedAsyncIterable;
653
+ }
654
+ function wrapGeminiStream(result, options, onComplete) {
655
+ if (!result || !result.stream) return result;
656
+ const originalStream = result.stream;
657
+ const model = options.model || "gemini-3.7-flash";
658
+ let lastChunkWithUsage = null;
659
+ const wrappedStream = (async function* () {
660
+ try {
661
+ for await (const chunk of originalStream) {
662
+ if (chunk.usageMetadata) {
663
+ lastChunkWithUsage = chunk;
664
+ }
665
+ yield chunk;
666
+ }
667
+ } finally {
668
+ if (lastChunkWithUsage) {
669
+ const extracted = extractGeminiResponseUsage(lastChunkWithUsage, model);
670
+ if (extracted) {
671
+ const cost = calculateUsageCost(extracted.model, extracted.usage);
672
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
673
+ const event = {
674
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
675
+ model: extracted.model,
676
+ provider: "google",
677
+ usage: extracted.usage,
678
+ cost,
679
+ customerId,
680
+ metadata: options.metadata
681
+ };
682
+ onComplete(event);
683
+ if (options.onUsage) {
684
+ options.onUsage(event);
685
+ }
686
+ }
687
+ }
688
+ }
689
+ })();
690
+ return {
691
+ ...result,
692
+ stream: wrappedStream
693
+ };
694
+ }
695
+ function wrapUniversalStream(stream, options = {}, onComplete) {
696
+ if (!stream || typeof stream !== "object") return stream;
697
+ if ("stream" in stream && "response" in stream) {
698
+ return wrapGeminiStream(stream, options, onComplete);
699
+ }
700
+ if (Symbol.asyncIterator in stream) {
701
+ if (options.provider === "anthropic") {
702
+ return wrapAnthropicStream(stream, options, onComplete);
703
+ }
704
+ return wrapOpenAIStream(stream, options, onComplete);
705
+ }
706
+ return stream;
707
+ }
708
+
709
+ // src/meter/client.ts
710
+ var VibezMeter = class {
711
+ batcher;
712
+ stripeClient;
713
+ markupMultiplier;
714
+ constructor(options = {}) {
715
+ this.markupMultiplier = options.markupMultiplier;
716
+ if (options.stripe) {
717
+ this.stripeClient = options.stripe;
718
+ } else if (options.apiKey || process.env.STRIPE_SECRET_KEY) {
719
+ const key = options.apiKey || process.env.STRIPE_SECRET_KEY;
720
+ this.stripeClient = new Stripe(key, {
721
+ appInfo: {
722
+ name: "vibezcheck",
723
+ version: "0.1.0",
724
+ url: "https://vibezcheck.xyz"
725
+ }
726
+ });
727
+ }
728
+ this.batcher = new MeterBatcher({
729
+ ...options,
730
+ stripe: this.stripeClient
731
+ });
732
+ }
733
+ /**
734
+ * Track token usage from a non-streaming response object (OpenAI, Anthropic, Gemini, etc.)
735
+ */
736
+ trackUsage(response, options = {}) {
737
+ const extracted = detectAndExtractUsage(response, options.model, options.provider);
738
+ if (!extracted) {
739
+ return null;
740
+ }
741
+ const model = options.model || extracted.model;
742
+ const cost = calculateUsageCost(model, extracted.usage, this.markupMultiplier);
743
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
744
+ const event = {
745
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
746
+ model,
747
+ provider: extracted.provider,
748
+ usage: extracted.usage,
749
+ cost,
750
+ customerId,
751
+ metadata: options.metadata
752
+ };
753
+ this.batcher.enqueue(event);
754
+ return event;
755
+ }
756
+ /**
757
+ * Wrap any LLM stream (OpenAI, Anthropic, Gemini) with zero added latency
758
+ */
759
+ wrapStream(stream, options = {}) {
760
+ return wrapUniversalStream(stream, options, (event) => {
761
+ this.batcher.enqueue(event);
762
+ });
763
+ }
764
+ /**
765
+ * Directly record token usage manually
766
+ */
767
+ recordUsage(options) {
768
+ const inputTokens = options.inputTokens ?? 0;
769
+ const outputTokens = options.outputTokens ?? 0;
770
+ const reasoningTokens = options.reasoningTokens;
771
+ const cachedTokens = options.cachedTokens;
772
+ const usage = {
773
+ inputTokens,
774
+ outputTokens,
775
+ totalTokens: inputTokens + outputTokens,
776
+ reasoningTokens,
777
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
778
+ cachedTokens
779
+ };
780
+ const cost = calculateUsageCost(options.model, usage, this.markupMultiplier);
781
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
782
+ const event = {
783
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
784
+ model: options.model,
785
+ provider: options.provider || "custom",
786
+ usage,
787
+ cost,
788
+ customerId,
789
+ metadata: options.metadata
790
+ };
791
+ this.batcher.enqueue(event);
792
+ return event;
793
+ }
794
+ /**
795
+ * Flush pending events to Stripe (vital for Serverless & Edge environments)
796
+ */
797
+ async flush() {
798
+ await this.batcher.flush();
799
+ }
800
+ /**
801
+ * Get in-memory aggregated usage statistics
802
+ */
803
+ getUsageSummary() {
804
+ return this.batcher.getSummary();
805
+ }
806
+ /**
807
+ * Reset in-memory ledger
808
+ */
809
+ resetSummary() {
810
+ this.batcher.resetLedger();
811
+ }
812
+ };
813
+ function createMeter(options = {}) {
814
+ return new VibezMeter(options);
815
+ }
816
+
817
+ // src/ai-sdk/with-billing.ts
818
+ function withBilling(model, options = {}) {
819
+ if (!model || typeof model !== "object") {
820
+ return model;
821
+ }
822
+ const meter = options.meter || createMeter({
823
+ apiKey: options.stripeApiKey,
824
+ eventName: options.eventName
825
+ });
826
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
827
+ const modelId = model.modelId || "unknown-model";
828
+ const provider = model.provider?.replace(/^@ai-sdk\//, "") || "ai-sdk";
829
+ const handleUsage = (rawUsage) => {
830
+ if (!rawUsage) return;
831
+ const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? 0;
832
+ const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? 0;
833
+ const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? 0;
834
+ const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? 0;
835
+ const usage = {
836
+ inputTokens,
837
+ outputTokens,
838
+ totalTokens: inputTokens + outputTokens,
839
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
840
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
841
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
842
+ };
843
+ const cost = calculateUsageCost(modelId, usage);
844
+ const event = {
845
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
846
+ model: modelId,
847
+ provider,
848
+ usage,
849
+ cost,
850
+ customerId,
851
+ metadata: options.metadata
852
+ };
853
+ meter.recordUsage({
854
+ model: modelId,
855
+ provider,
856
+ inputTokens,
857
+ outputTokens,
858
+ reasoningTokens: usage.reasoningTokens,
859
+ cachedTokens: usage.cachedTokens,
860
+ customerId,
861
+ metadata: options.metadata
862
+ });
863
+ if (options.onUsage) {
864
+ options.onUsage(event);
865
+ }
866
+ };
867
+ return new Proxy(model, {
868
+ get(target, prop, receiver) {
869
+ const originalValue = Reflect.get(target, prop, receiver);
870
+ if (prop === "doGenerate" && typeof originalValue === "function") {
871
+ return async function(...args) {
872
+ const result = await originalValue.apply(target, args);
873
+ if (result && result.usage) {
874
+ handleUsage(result.usage);
875
+ }
876
+ return result;
877
+ };
878
+ }
879
+ if (prop === "doStream" && typeof originalValue === "function") {
880
+ return async function(...args) {
881
+ const result = await originalValue.apply(target, args);
882
+ if (!result || !result.stream) {
883
+ return result;
884
+ }
885
+ const originalStream = result.stream;
886
+ if (typeof originalStream.getReader === "function") {
887
+ const reader = originalStream.getReader();
888
+ const transformedStream = new ReadableStream({
889
+ async start(controller) {
890
+ try {
891
+ while (true) {
892
+ const { done, value } = await reader.read();
893
+ if (done) {
894
+ controller.close();
895
+ break;
896
+ }
897
+ if (value && typeof value === "object") {
898
+ if (value.type === "finish" && value.usage) {
899
+ handleUsage(value.usage);
900
+ }
901
+ }
902
+ controller.enqueue(value);
903
+ }
904
+ } catch (err) {
905
+ controller.error(err);
906
+ }
907
+ }
908
+ });
909
+ return {
910
+ ...result,
911
+ stream: transformedStream
912
+ };
913
+ }
914
+ if (Symbol.asyncIterator in originalStream) {
915
+ const wrappedAsyncIterable = {
916
+ async *[Symbol.asyncIterator]() {
917
+ for await (const chunk of originalStream) {
918
+ if (chunk && typeof chunk === "object") {
919
+ if (chunk.type === "finish" && chunk.usage) {
920
+ handleUsage(chunk.usage);
921
+ }
922
+ }
923
+ yield chunk;
924
+ }
925
+ }
926
+ };
927
+ return {
928
+ ...result,
929
+ stream: wrappedAsyncIterable
930
+ };
931
+ }
932
+ return result;
933
+ };
934
+ }
935
+ return originalValue;
936
+ }
937
+ });
938
+ }
939
+ var meteredModel = withBilling;
940
+ export {
941
+ meteredModel,
942
+ withBilling
943
+ };
944
+ //# sourceMappingURL=index.mjs.map