vibezcheck 0.4.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +249 -273
  3. package/bin/vibezcheck.js +4 -4
  4. package/dist/ai-sdk/index.d.mts +28 -59
  5. package/dist/ai-sdk/index.d.ts +28 -59
  6. package/dist/ai-sdk/index.js +307 -69
  7. package/dist/ai-sdk/index.js.map +1 -1
  8. package/dist/ai-sdk/index.mjs +307 -69
  9. package/dist/ai-sdk/index.mjs.map +1 -1
  10. package/dist/ai-sdk/middleware.d.mts +15 -0
  11. package/dist/ai-sdk/middleware.d.ts +15 -0
  12. package/dist/ai-sdk/middleware.js +1433 -0
  13. package/dist/ai-sdk/middleware.js.map +1 -0
  14. package/dist/ai-sdk/middleware.mjs +1396 -0
  15. package/dist/ai-sdk/middleware.mjs.map +1 -0
  16. package/dist/auth/index.js.map +1 -1
  17. package/dist/auth/index.mjs.map +1 -1
  18. package/dist/billing/index.d.mts +90 -1
  19. package/dist/billing/index.d.ts +90 -1
  20. package/dist/billing/index.js +1542 -2
  21. package/dist/billing/index.js.map +1 -1
  22. package/dist/billing/index.mjs +1537 -1
  23. package/dist/billing/index.mjs.map +1 -1
  24. package/dist/cli/index.js +59 -7
  25. package/dist/cli/index.js.map +1 -1
  26. package/dist/cli/index.mjs +59 -7
  27. package/dist/cli/index.mjs.map +1 -1
  28. package/dist/{client-ynfWcHX6.d.ts → client-BORmJy8s.d.ts} +1 -1
  29. package/dist/{client-w_hWhQ6g.d.mts → client-CbuXmoXz.d.mts} +1 -1
  30. package/dist/compat/stripe-meter.d.mts +21 -0
  31. package/dist/compat/stripe-meter.d.ts +21 -0
  32. package/dist/compat/stripe-meter.js +1451 -0
  33. package/dist/compat/stripe-meter.js.map +1 -0
  34. package/dist/compat/stripe-meter.mjs +1414 -0
  35. package/dist/compat/stripe-meter.mjs.map +1 -0
  36. package/dist/compat/stripe-provider.d.mts +34 -0
  37. package/dist/compat/stripe-provider.d.ts +34 -0
  38. package/dist/compat/stripe-provider.js +1620 -0
  39. package/dist/compat/stripe-provider.js.map +1 -0
  40. package/dist/compat/stripe-provider.mjs +1587 -0
  41. package/dist/compat/stripe-provider.mjs.map +1 -0
  42. package/dist/compat/token-meter.d.mts +28 -0
  43. package/dist/compat/token-meter.d.ts +28 -0
  44. package/dist/compat/token-meter.js +1320 -0
  45. package/dist/compat/token-meter.js.map +1 -0
  46. package/dist/compat/token-meter.mjs +1283 -0
  47. package/dist/compat/token-meter.mjs.map +1 -0
  48. package/dist/customers/index.d.mts +1 -1
  49. package/dist/customers/index.d.ts +1 -1
  50. package/dist/customers/index.js.map +1 -1
  51. package/dist/customers/index.mjs.map +1 -1
  52. package/dist/index.d.mts +25 -11
  53. package/dist/index.d.ts +25 -11
  54. package/dist/index.js +810 -72
  55. package/dist/index.js.map +1 -1
  56. package/dist/index.mjs +798 -72
  57. package/dist/index.mjs.map +1 -1
  58. package/dist/meter/index.d.mts +2 -2
  59. package/dist/meter/index.d.ts +2 -2
  60. package/dist/meter/index.js +176 -42
  61. package/dist/meter/index.js.map +1 -1
  62. package/dist/meter/index.mjs +176 -42
  63. package/dist/meter/index.mjs.map +1 -1
  64. package/dist/pricing/index.d.mts +15 -4
  65. package/dist/pricing/index.d.ts +15 -4
  66. package/dist/pricing/index.js +165 -29
  67. package/dist/pricing/index.js.map +1 -1
  68. package/dist/pricing/index.mjs +164 -29
  69. package/dist/pricing/index.mjs.map +1 -1
  70. package/dist/react/index.d.mts +46 -2
  71. package/dist/react/index.d.ts +46 -2
  72. package/dist/react/index.js +471 -29
  73. package/dist/react/index.js.map +1 -1
  74. package/dist/react/index.mjs +469 -29
  75. package/dist/react/index.mjs.map +1 -1
  76. package/dist/{types-Mozk4-Mr.d.mts → types-6P71CXAD.d.mts} +16 -6
  77. package/dist/{types-Mozk4-Mr.d.ts → types-6P71CXAD.d.ts} +16 -6
  78. package/dist/with-billing-Bj6Ya_Iy.d.ts +49 -0
  79. package/dist/with-billing-DndWGxL8.d.mts +49 -0
  80. package/package.json +35 -10
package/dist/index.mjs CHANGED
@@ -269,12 +269,12 @@ function extractOpenAIResponseUsage(response) {
269
269
  function inspectOpenAIStreamChunk(chunk) {
270
270
  if (!chunk || typeof chunk !== "object") return {};
271
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;
272
+ const rawUsage = chunk.usage || chunk.token_usage || chunk.x_groq?.usage || chunk.usageMetadata;
273
+ if (rawUsage) {
274
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? rawUsage.promptTokens ?? rawUsage.inputTokens ?? rawUsage.promptTokenCount ?? 0;
275
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? rawUsage.completionTokens ?? rawUsage.outputTokens ?? rawUsage.candidatesTokenCount ?? 0;
276
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.reasoning_tokens ?? rawUsage.reasoningTokens ?? rawUsage.thoughtsTokenCount ?? 0;
277
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? rawUsage.cached_tokens ?? rawUsage.cachedTokens ?? rawUsage.cachedContentTokenCount ?? 0;
278
278
  return {
279
279
  model,
280
280
  usage: {
@@ -289,11 +289,11 @@ function inspectOpenAIStreamChunk(chunk) {
289
289
  }
290
290
  if (chunk.type === "response.completed" || chunk.type === "response.done") {
291
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;
292
+ const rawUsage2 = chunk.response.usage;
293
+ const inputTokens = rawUsage2.input_tokens ?? 0;
294
+ const outputTokens = rawUsage2.output_tokens ?? 0;
295
+ const reasoningTokens = rawUsage2.output_token_details?.reasoning_tokens ?? 0;
296
+ const cachedTokens = rawUsage2.input_token_details?.cached_tokens ?? 0;
297
297
  return {
298
298
  model: chunk.response.model || model,
299
299
  usage: {
@@ -458,7 +458,7 @@ function detectAndExtractUsage(response, fallbackModel, fallbackProvider) {
458
458
 
459
459
  // src/pricing/table.ts
460
460
  var MODEL_PRICING_TABLE = {
461
- // --- OpenAI ---
461
+ // --- OpenAI (Modern & Reasoning) ---
462
462
  "gpt-5.6-sol": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
463
463
  "gpt-5.6-terra": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.2 },
464
464
  "gpt-5.6-luna": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
@@ -470,11 +470,22 @@ var MODEL_PRICING_TABLE = {
470
470
  "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
471
471
  "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10, cachedInputPer1M: 1.25 },
472
472
  "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.075 },
473
+ "gpt-4.5": { inputPer1M: 75, outputPer1M: 150, cachedInputPer1M: 37.5 },
474
+ "gpt-4.5-preview": { inputPer1M: 75, outputPer1M: 150, cachedInputPer1M: 37.5 },
475
+ "chatgpt-4o-latest": { inputPer1M: 5, outputPer1M: 15 },
473
476
  "gpt-4.1": { inputPer1M: 2, outputPer1M: 8, cachedInputPer1M: 1 },
474
477
  "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.05 },
478
+ // --- OpenAI (Legacy & Backward Compatibility) ---
479
+ "gpt-4-turbo": { inputPer1M: 10, outputPer1M: 30, cachedInputPer1M: 5 },
480
+ "gpt-4-turbo-preview": { inputPer1M: 10, outputPer1M: 30, cachedInputPer1M: 5 },
481
+ "gpt-4": { inputPer1M: 30, outputPer1M: 60 },
482
+ "gpt-4-32k": { inputPer1M: 60, outputPer1M: 120 },
483
+ "gpt-3.5-turbo": { inputPer1M: 0.5, outputPer1M: 1.5 },
484
+ "gpt-3.5-turbo-16k": { inputPer1M: 3, outputPer1M: 4 },
475
485
  "text-embedding-3-small": { inputPer1M: 0.02, outputPer1M: 0 },
476
486
  "text-embedding-3-large": { inputPer1M: 0.13, outputPer1M: 0 },
477
- // --- Anthropic ---
487
+ "text-embedding-ada-002": { inputPer1M: 0.1, outputPer1M: 0 },
488
+ // --- Anthropic (Modern & Extended Thinking) ---
478
489
  "claude-3-7-sonnet": { inputPer1M: 0.59, outputPer1M: 2.93, cachedInputPer1M: 0.3 },
479
490
  "claude-sonnet-5": { inputPer1M: 2, outputPer1M: 10, cachedInputPer1M: 0.3 },
480
491
  "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
@@ -482,48 +493,145 @@ var MODEL_PRICING_TABLE = {
482
493
  "haiku-4.5": { inputPer1M: 1, outputPer1M: 5, cachedInputPer1M: 0.1 },
483
494
  "claude-opus-5": { inputPer1M: 5, outputPer1M: 25, cachedInputPer1M: 1.5 },
484
495
  "claude-3-opus": { inputPer1M: 15, outputPer1M: 75, cachedInputPer1M: 1.5 },
485
- // --- Google Gemini ---
496
+ // --- Anthropic (Legacy & Backward Compatibility) ---
497
+ "claude-3-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
498
+ "claude-3-haiku": { inputPer1M: 0.25, outputPer1M: 1.25, cachedInputPer1M: 0.025 },
499
+ "claude-2.1": { inputPer1M: 8, outputPer1M: 24 },
500
+ "claude-2.0": { inputPer1M: 8, outputPer1M: 24 },
501
+ "claude-instant-1.2": { inputPer1M: 1.63, outputPer1M: 5.51 },
502
+ // --- Google Gemini (Modern & Thoughts) ---
486
503
  "gemini-3.7-flash": { inputPer1M: 0.75, outputPer1M: 3.75, cachedInputPer1M: 0.18 },
487
504
  "gemini-3.1-pro": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.5 },
488
505
  "gemini-3.5-flash": { inputPer1M: 1.5, outputPer1M: 9, cachedInputPer1M: 0.38 },
489
506
  "gemini-3.1-flash-lite": { inputPer1M: 0.25, outputPer1M: 1.5, cachedInputPer1M: 0.06 },
507
+ "gemini-2.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
508
+ "gemini-2.5-flash": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.0375 },
490
509
  "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.025 },
510
+ "gemini-2.0-flash-lite": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
511
+ "gemini-2.0-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
512
+ // --- Google Gemini (Legacy & Backward Compatibility) ---
491
513
  "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
492
514
  "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
515
+ "gemini-1.5-flash-8b": { inputPer1M: 0.0375, outputPer1M: 0.15, cachedInputPer1M: 9375e-6 },
516
+ "gemini-1.0-pro": { inputPer1M: 0.5, outputPer1M: 1.5 },
493
517
  // --- xAI Grok ---
494
518
  "grok-4.6": { inputPer1M: 3, outputPer1M: 15 },
519
+ "grok-3": { inputPer1M: 3, outputPer1M: 15 },
520
+ "grok-3-mini": { inputPer1M: 0.3, outputPer1M: 1.5 },
495
521
  "grok-2": { inputPer1M: 2, outputPer1M: 10 },
496
522
  "grok-2-vision": { inputPer1M: 2, outputPer1M: 10 },
497
523
  "grok-beta": { inputPer1M: 5, outputPer1M: 15 },
498
524
  // --- Mistral ---
499
525
  "mistral-large-3": { inputPer1M: 2, outputPer1M: 6 },
500
526
  "mistral-large-latest": { inputPer1M: 2, outputPer1M: 6 },
527
+ "mistral-large-2411": { inputPer1M: 2, outputPer1M: 6 },
501
528
  "codestral-latest": { inputPer1M: 0.3, outputPer1M: 0.9 },
529
+ "mistral-medium-latest": { inputPer1M: 2.7, outputPer1M: 8.1 },
502
530
  "mistral-small-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
503
531
  "ministral-8b-latest": { inputPer1M: 0.1, outputPer1M: 0.1 },
504
- // --- Groq LPUs ---
532
+ "ministral-3b-latest": { inputPer1M: 0.04, outputPer1M: 0.04 },
533
+ "open-mistral-7b": { inputPer1M: 0.2, outputPer1M: 0.2 },
534
+ "open-mixtral-8x7b": { inputPer1M: 0.7, outputPer1M: 0.7 },
535
+ "open-mixtral-8x22b": { inputPer1M: 2, outputPer1M: 6 },
536
+ // --- Groq & Meta Llama LPUs ---
505
537
  "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
538
+ "llama-3.1-405b": { inputPer1M: 3, outputPer1M: 3 },
539
+ "llama-3.1-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
506
540
  "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
541
+ "llama-3.2-1b-preview": { inputPer1M: 0.04, outputPer1M: 0.04 },
542
+ "llama-3.2-3b-preview": { inputPer1M: 0.06, outputPer1M: 0.06 },
543
+ "llama-3.2-11b-vision": { inputPer1M: 0.18, outputPer1M: 0.18 },
544
+ "llama-3.2-90b-vision": { inputPer1M: 0.9, outputPer1M: 0.9 },
507
545
  "deepseek-r1-distill-llama-70b": { inputPer1M: 0.75, outputPer1M: 0.99 },
546
+ "deepseek-r1-distill-qwen-32b": { inputPer1M: 0.49, outputPer1M: 0.49 },
508
547
  "qwen-2.5-32b": { inputPer1M: 0.29, outputPer1M: 0.39 },
548
+ "qwen-2.5-72b": { inputPer1M: 0.35, outputPer1M: 0.4 },
549
+ "mixtral-8x7b-32768": { inputPer1M: 0.24, outputPer1M: 0.24 },
550
+ "gemma2-9b-it": { inputPer1M: 0.2, outputPer1M: 0.2 },
509
551
  // --- DeepSeek ---
510
552
  "deepseek-v4-pro": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
511
553
  "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 },
554
+ "deepseek-v3": { inputPer1M: 0.14, outputPer1M: 0.28, cachedInputPer1M: 0.014 },
555
+ "deepseek-chat": { inputPer1M: 0.14, outputPer1M: 0.28, cachedInputPer1M: 0.014 },
556
+ "deepseek-r1": { inputPer1M: 0.55, outputPer1M: 2.19, cachedInputPer1M: 0.14 },
557
+ "deepseek-reasoner": { inputPer1M: 0.55, outputPer1M: 2.19, cachedInputPer1M: 0.14 },
514
558
  // --- Cohere ---
515
559
  "command-r-plus": { inputPer1M: 2.5, outputPer1M: 10 },
516
- "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 }
560
+ "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 },
561
+ "command": { inputPer1M: 1, outputPer1M: 2 },
562
+ "command-light": { inputPer1M: 0.3, outputPer1M: 0.6 },
563
+ "embed-english-v3.0": { inputPer1M: 0.1, outputPer1M: 0 },
564
+ // --- Perplexity ---
565
+ "sonar": { inputPer1M: 1, outputPer1M: 1 },
566
+ "sonar-pro": { inputPer1M: 3, outputPer1M: 15 },
567
+ "sonar-reasoning": { inputPer1M: 1, outputPer1M: 5 },
568
+ "sonar-reasoning-pro": { inputPer1M: 2, outputPer1M: 8 }
569
+ };
570
+ var MODEL_ALIASES = {
571
+ // OpenAI Shorthands & Aliases
572
+ "gpt4": "gpt-4",
573
+ "gpt4o": "gpt-4o",
574
+ "gpt-4-preview": "gpt-4-turbo",
575
+ "gpt-4-0125-preview": "gpt-4-turbo",
576
+ "gpt-4-1106-preview": "gpt-4-turbo",
577
+ "gpt-3.5": "gpt-3.5-turbo",
578
+ "gpt-3.5-turbo-0125": "gpt-3.5-turbo",
579
+ "gpt-3.5-turbo-1106": "gpt-3.5-turbo",
580
+ "gpt-3.5-turbo-16k-0613": "gpt-3.5-turbo-16k",
581
+ // Anthropic Shorthands
582
+ "sonnet": "claude-3-5-sonnet",
583
+ "sonnet-3.7": "claude-3-7-sonnet",
584
+ "sonnet-3.5": "claude-3-5-sonnet",
585
+ "haiku": "claude-3-5-haiku",
586
+ "haiku-3.5": "claude-3-5-haiku",
587
+ "opus": "claude-3-opus",
588
+ "claude-2": "claude-2.0",
589
+ "claude-instant": "claude-instant-1.2",
590
+ // DeepSeek Shorthands
591
+ "r1": "deepseek-r1",
592
+ "v3": "deepseek-v3",
593
+ // Gemini Shorthands
594
+ "flash": "gemini-2.0-flash",
595
+ "pro": "gemini-1.5-pro",
596
+ // Meta / Groq Shorthands
597
+ "llama-3.3-70b": "llama-3.3-70b-versatile",
598
+ "llama-3.1-70b": "llama-3.1-70b-versatile",
599
+ "llama-3.1-8b": "llama-3.1-8b-instant",
600
+ "llama-3-70b": "llama-3.1-70b-versatile",
601
+ "llama-3-8b": "llama-3.1-8b-instant",
602
+ // Mistral Shorthands
603
+ "codestral": "codestral-latest",
604
+ "mistral-large": "mistral-large-latest",
605
+ "mistral-small": "mistral-small-latest"
517
606
  };
518
607
  var customPricingRegistry = {};
519
608
  function normalizeModelKey(rawModel) {
520
609
  if (!rawModel) return "unknown";
521
610
  let model = rawModel.toLowerCase().trim();
611
+ model = model.replace(/^[a-z0-9_-]+\.(anthropic|meta|amazon|cohere|mistral|ai21)\./i, "");
612
+ model = model.replace(/^(anthropic|meta|amazon|cohere|mistral|ai21)\./i, "");
613
+ model = model.replace(/-v\d+(:\d+)?$/, "");
614
+ model = model.replace(/:\d+$/, "");
522
615
  if (model.includes("/")) {
523
- model = model.split("/")[1] || model;
616
+ model = model.split("/").slice(1).join("/");
524
617
  }
618
+ model = model.replace(/:(latest|free|beta)$/, "");
525
619
  model = model.replace(/-\d{8}$/, "");
526
620
  model = model.replace(/-\d{4}-\d{2}-\d{2}$/, "");
621
+ model = model.replace(/llama(\d+)-(\d+)-/g, "llama-$1.$2-");
622
+ model = model.replace(/llama(\d+)\.(\d+)-/g, "llama-$1.$2-");
623
+ if (MODEL_ALIASES[model]) {
624
+ return MODEL_ALIASES[model];
625
+ }
626
+ if (!MODEL_PRICING_TABLE[model]) {
627
+ const withoutInstruct = model.replace(/-(instruct|chat|preview)$/, "");
628
+ if (MODEL_PRICING_TABLE[withoutInstruct]) {
629
+ return withoutInstruct;
630
+ }
631
+ if (MODEL_ALIASES[withoutInstruct]) {
632
+ return MODEL_ALIASES[withoutInstruct];
633
+ }
634
+ }
527
635
  return model;
528
636
  }
529
637
  function getModelPricing(modelName) {
@@ -540,6 +648,10 @@ function getModelPricing(modelName) {
540
648
  if (MODEL_PRICING_TABLE[modelName]) {
541
649
  return MODEL_PRICING_TABLE[modelName];
542
650
  }
651
+ const alias = MODEL_ALIASES[modelName.toLowerCase().trim()];
652
+ if (alias && MODEL_PRICING_TABLE[alias]) {
653
+ return MODEL_PRICING_TABLE[alias];
654
+ }
543
655
  return {
544
656
  inputPer1M: 1,
545
657
  outputPer1M: 3,
@@ -567,35 +679,57 @@ function calculateCost(params) {
567
679
  } else {
568
680
  rates = getModelPricing(params.model);
569
681
  }
570
- const inputTokens = params.inputTokens ?? 0;
571
- const outputTokens = params.outputTokens ?? 0;
572
- const reasoningTokens = params.reasoningTokens ?? 0;
573
- const cachedTokens = params.cachedTokens ?? 0;
574
- const regularInputTokens = Math.max(0, inputTokens - cachedTokens);
575
- const regularInputCost = regularInputTokens / 1e6 * rates.inputPer1M;
576
- const cachedRate = rates.cachedInputPer1M ?? rates.inputPer1M * 0.15;
577
- const cachedInputCost = cachedTokens / 1e6 * cachedRate;
578
- const inputCostUSD = regularInputCost + cachedInputCost;
579
- const outputCostUSD = outputTokens / 1e6 * rates.outputPer1M;
580
- const reasoningRate = rates.reasoningPer1M ?? rates.outputPer1M;
581
- const reasoningCostUSD = reasoningTokens / 1e6 * reasoningRate;
582
- const standardCacheCost = cachedTokens / 1e6 * rates.inputPer1M;
583
- const cachedDiscountUSD = Math.max(0, standardCacheCost - cachedInputCost);
584
- let totalUSD = inputCostUSD + outputCostUSD;
682
+ const inputTokens = BigInt(Math.max(0, params.inputTokens ?? 0));
683
+ const outputTokens = BigInt(Math.max(0, params.outputTokens ?? 0));
684
+ const reasoningTokens = BigInt(Math.max(0, params.reasoningTokens ?? 0));
685
+ const cachedTokens = BigInt(Math.max(0, params.cachedTokens ?? 0));
686
+ const regularInputTokens = inputTokens > cachedTokens ? inputTokens - cachedTokens : 0n;
687
+ const rateInputNano = BigInt(Math.round(rates.inputPer1M * 1e3));
688
+ const cachedPer1M = rates.cachedInputPer1M ?? rates.inputPer1M * 0.15;
689
+ const rateCachedNano = BigInt(Math.round(cachedPer1M * 1e3));
690
+ const rateOutputNano = BigInt(Math.round(rates.outputPer1M * 1e3));
691
+ const reasoningPer1M = rates.reasoningPer1M ?? rates.outputPer1M;
692
+ const rateReasoningNano = BigInt(Math.round(reasoningPer1M * 1e3));
693
+ const regularInputCostNano = regularInputTokens * rateInputNano;
694
+ const cachedInputCostNano = cachedTokens * rateCachedNano;
695
+ const inputCostNano = regularInputCostNano + cachedInputCostNano;
696
+ const outputCostNano = outputTokens * rateOutputNano;
697
+ const reasoningCostNano = reasoningTokens * rateReasoningNano;
698
+ const standardCacheCostNano = cachedTokens * rateInputNano;
699
+ const cachedDiscountNano = standardCacheCostNano > cachedInputCostNano ? standardCacheCostNano - cachedInputCostNano : 0n;
700
+ const wholesaleNano = inputCostNano + outputCostNano;
585
701
  const markup = params.markupMultiplier ?? 1;
586
- let retailUSD = void 0;
702
+ let billedNano = wholesaleNano;
703
+ let hasRetail = false;
587
704
  if (markup !== 1 || params.minimumChargeUSD !== void 0) {
588
- retailUSD = totalUSD * markup;
589
- if (params.minimumChargeUSD !== void 0 && retailUSD < params.minimumChargeUSD) {
590
- retailUSD = params.minimumChargeUSD;
705
+ hasRetail = true;
706
+ const markupMultiplierNano = BigInt(Math.round(markup * 1e3));
707
+ billedNano = wholesaleNano * markupMultiplierNano / 1000n;
708
+ if (params.minimumChargeUSD !== void 0 && params.minimumChargeUSD > 0) {
709
+ const minChargeNano = BigInt(Math.round(params.minimumChargeUSD * 1e9));
710
+ if (billedNano < minChargeNano) {
711
+ billedNano = minChargeNano;
712
+ }
591
713
  }
592
714
  }
715
+ const inputCostUSD = Number(inputCostNano) / 1e9;
716
+ const outputCostUSD = Number(outputCostNano) / 1e9;
717
+ const reasoningCostUSD = Number(reasoningCostNano) / 1e9;
718
+ const cachedDiscountUSD = Number(cachedDiscountNano) / 1e9;
719
+ const totalUSD = Number(wholesaleNano) / 1e9;
720
+ const wholesaleTotalUSD = totalUSD;
721
+ const billedUSD = Number(billedNano) / 1e9;
722
+ const profitUSD = Math.max(0, billedUSD - wholesaleTotalUSD);
723
+ const retailUSD = hasRetail ? billedUSD : void 0;
593
724
  return {
594
725
  inputCostUSD: Number(inputCostUSD.toFixed(8)),
595
726
  outputCostUSD: Number(outputCostUSD.toFixed(8)),
596
- reasoningCostUSD: reasoningTokens > 0 ? Number(reasoningCostUSD.toFixed(8)) : void 0,
597
- cachedDiscountUSD: cachedTokens > 0 ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
727
+ reasoningCostUSD: reasoningTokens > 0n ? Number(reasoningCostUSD.toFixed(8)) : void 0,
728
+ cachedDiscountUSD: cachedTokens > 0n ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
598
729
  totalUSD: Number(totalUSD.toFixed(8)),
730
+ wholesaleTotalUSD: Number(wholesaleTotalUSD.toFixed(8)),
731
+ billedUSD: Number(billedUSD.toFixed(8)),
732
+ profitUSD: Number(profitUSD.toFixed(8)),
599
733
  retailUSD: retailUSD !== void 0 ? Number(retailUSD.toFixed(8)) : void 0,
600
734
  currency: rates.currency || "USD"
601
735
  };
@@ -801,7 +935,7 @@ function wrapUniversalStream(stream, options = {}, onComplete) {
801
935
  return wrapGeminiStream(stream, options, onComplete);
802
936
  }
803
937
  if (Symbol.asyncIterator in stream) {
804
- if (options.provider === "anthropic") {
938
+ if (options.provider === "anthropic" || options.model?.toLowerCase().includes("claude")) {
805
939
  return wrapAnthropicStream(stream, options, onComplete);
806
940
  }
807
941
  return wrapOpenAIStream(stream, options, onComplete);
@@ -823,7 +957,7 @@ var VibezMeter = class {
823
957
  this.stripeClient = new Stripe(key, {
824
958
  appInfo: {
825
959
  name: "vibezcheck",
826
- version: "0.4.2",
960
+ version: "0.5.3",
827
961
  url: "https://vibezcheck.xyz"
828
962
  }
829
963
  });
@@ -940,10 +1074,20 @@ var VibezCircuitBreakerError = class extends Error {
940
1074
  };
941
1075
 
942
1076
  // src/ai-sdk/with-billing.ts
943
- function withBilling(model, options = {}) {
1077
+ function withBilling(model, optionsOrCustomer, extraOptions = {}) {
944
1078
  if (!model || typeof model !== "object") {
945
1079
  return model;
946
1080
  }
1081
+ let options = {};
1082
+ if (typeof optionsOrCustomer === "string") {
1083
+ options = { ...extraOptions, customer: optionsOrCustomer };
1084
+ } else if (typeof optionsOrCustomer === "object" && optionsOrCustomer !== null) {
1085
+ if ("userId" in optionsOrCustomer || "email" in optionsOrCustomer || "id" in optionsOrCustomer) {
1086
+ options = { ...extraOptions, customer: optionsOrCustomer };
1087
+ } else {
1088
+ options = { ...optionsOrCustomer, ...extraOptions };
1089
+ }
1090
+ }
947
1091
  const meter = options.meter || createMeter({
948
1092
  apiKey: options.stripeApiKey,
949
1093
  eventName: options.eventName
@@ -972,17 +1116,19 @@ function withBilling(model, options = {}) {
972
1116
  };
973
1117
  const handleUsage = (rawUsage, extraMeta) => {
974
1118
  if (!rawUsage) return;
975
- const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? 0;
976
- const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? 0;
977
- const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? 0;
978
- const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? 0;
1119
+ const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? rawUsage.promptTokenCount ?? 0;
1120
+ const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? rawUsage.completion_tokens ?? rawUsage.output_tokens ?? rawUsage.candidatesTokenCount ?? 0;
1121
+ const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? rawUsage.reasoning_tokens ?? rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.thoughtsTokenCount ?? 0;
1122
+ const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? rawUsage.cachedTokens ?? rawUsage.cached_tokens ?? rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? rawUsage.cachedContentTokenCount ?? rawUsage.cache_read_input_tokens ?? 0;
1123
+ const cacheWriteTokens = rawUsage.cacheWriteTokens ?? rawUsage.cache_creation_input_tokens ?? rawUsage.cacheCreationTokens ?? 0;
979
1124
  const usage = {
980
1125
  inputTokens,
981
1126
  outputTokens,
982
1127
  totalTokens: inputTokens + outputTokens,
983
1128
  reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
984
1129
  visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
985
- cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
1130
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0,
1131
+ cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : void 0
986
1132
  };
987
1133
  const cost = calculateUsageCost(modelId, usage, {
988
1134
  markupMultiplier: options.pricing?.margin,
@@ -1083,7 +1229,9 @@ function withBilling(model, options = {}) {
1083
1229
  return;
1084
1230
  }
1085
1231
  } catch (err) {
1086
- console.warn(`[vibezcheck] Database record failed safely:`, err?.message || err);
1232
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1233
+ console.warn(`[vibezcheck] Database record failed safely:`, err?.message || err);
1234
+ }
1087
1235
  }
1088
1236
  };
1089
1237
  if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
@@ -1099,7 +1247,9 @@ function withBilling(model, options = {}) {
1099
1247
  try {
1100
1248
  await chargeFn(cost.totalUSD, event);
1101
1249
  } catch (err) {
1102
- console.warn(`[vibezcheck] Custom charge handler failed safely:`, err?.message || err);
1250
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1251
+ console.warn(`[vibezcheck] Custom charge handler failed safely:`, err?.message || err);
1252
+ }
1103
1253
  }
1104
1254
  };
1105
1255
  if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
@@ -1114,7 +1264,9 @@ function withBilling(model, options = {}) {
1114
1264
  try {
1115
1265
  await providerCharge(cost.totalUSD, event);
1116
1266
  } catch (err) {
1117
- console.warn(`[vibezcheck] Payment provider charge failed safely:`, err?.message || err);
1267
+ if (process.env.NODE_ENV !== "test" && !options.silent) {
1268
+ console.warn(`[vibezcheck] Payment provider charge failed safely:`, err?.message || err);
1269
+ }
1118
1270
  }
1119
1271
  };
1120
1272
  if (typeof globalThis !== "undefined" && typeof globalThis.after === "function") {
@@ -1169,14 +1321,19 @@ function withBilling(model, options = {}) {
1169
1321
  const transformStream = new TransformStream({
1170
1322
  transform(chunk, controller) {
1171
1323
  controller.enqueue(chunk);
1172
- if (chunk.type === "text-delta" && chunk.textDelta) {
1173
- accumulatedChars += chunk.textDelta.length;
1174
- } else if (chunk.type === "reasoning" && (chunk.textDelta || chunk.reasoning)) {
1175
- accumulatedChars += (chunk.textDelta || chunk.reasoning || "").length;
1324
+ const delta = chunk.textDelta || chunk.text || chunk.delta;
1325
+ if (delta && typeof delta === "string") {
1326
+ accumulatedChars += delta.length;
1327
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1328
+ const reasoning = chunk.reasoning || chunk.textDelta || chunk.text || chunk.delta || "";
1329
+ if (typeof reasoning === "string") {
1330
+ accumulatedChars += reasoning.length;
1331
+ }
1176
1332
  }
1177
- if (chunk.type === "finish" && chunk.usage) {
1333
+ const chunkUsage = chunk.usage || chunk.token_usage || chunk.usageMetadata;
1334
+ if (chunkUsage) {
1178
1335
  streamCompleted = true;
1179
- handleUsage(chunk.usage);
1336
+ handleUsage(chunkUsage);
1180
1337
  }
1181
1338
  },
1182
1339
  flush() {
@@ -1202,13 +1359,29 @@ function withBilling(model, options = {}) {
1202
1359
  if (prop === "doGenerate" && typeof originalValue === "function") {
1203
1360
  return async function(...args) {
1204
1361
  const result = await originalValue.apply(target, args);
1205
- if (result && result.usage) {
1206
- handleUsage(result.usage);
1362
+ const usage = result?.usage || result?.tokenUsage || result?.usageMetadata;
1363
+ if (usage) {
1364
+ handleUsage(usage);
1207
1365
  }
1208
1366
  return result;
1209
1367
  };
1210
1368
  }
1211
1369
  return originalValue;
1370
+ },
1371
+ apply(target, thisArg, argArray) {
1372
+ if (typeof target === "function") {
1373
+ return Reflect.apply(target, thisArg, argArray);
1374
+ }
1375
+ return target;
1376
+ },
1377
+ has(target, prop) {
1378
+ return Reflect.has(target, prop);
1379
+ },
1380
+ ownKeys(target) {
1381
+ return Reflect.ownKeys(target);
1382
+ },
1383
+ getPrototypeOf(target) {
1384
+ return Reflect.getPrototypeOf(target);
1212
1385
  }
1213
1386
  };
1214
1387
  return new Proxy(model, handler);
@@ -1228,23 +1401,88 @@ function createVibezModel(modelOrId, options = {}) {
1228
1401
  const parts = rawId.split("/");
1229
1402
  providerName = parts[0].toLowerCase();
1230
1403
  cleanModelId = parts.slice(1).join("/");
1404
+ } else if (rawId.startsWith("claude-")) {
1405
+ providerName = "anthropic";
1406
+ } else if (rawId.startsWith("gemini-")) {
1407
+ providerName = "google";
1408
+ } else if (rawId.startsWith("deepseek-")) {
1409
+ providerName = "deepseek";
1410
+ } else if (rawId.startsWith("grok-")) {
1411
+ providerName = "xai";
1412
+ } else if (rawId.startsWith("mistral-") || rawId.startsWith("codestral-") || rawId.startsWith("ministral-") || rawId.startsWith("open-mistral") || rawId.startsWith("open-mixtral")) {
1413
+ providerName = "mistral";
1414
+ } else if (rawId.startsWith("llama-") || rawId.startsWith("mixtral-") || rawId.startsWith("gemma") || rawId.startsWith("qwen-")) {
1415
+ providerName = "groq";
1416
+ } else if (rawId.startsWith("command-")) {
1417
+ providerName = "cohere";
1231
1418
  }
1232
- const apiKey = options.apiKey || process.env.AI_GATEWAY_API_KEY || process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.GOOGLE_GENERATIVE_AI_API_KEY;
1419
+ const apiKey = options.apiKey || process.env.AI_GATEWAY_API_KEY || (providerName === "anthropic" ? process.env.ANTHROPIC_API_KEY : void 0) || (providerName === "google" ? process.env.GOOGLE_GENERATIVE_AI_API_KEY : void 0) || (providerName === "mistral" ? process.env.MISTRAL_API_KEY : void 0) || (providerName === "groq" ? process.env.GROQ_API_KEY : void 0) || (providerName === "deepseek" ? process.env.DEEPSEEK_API_KEY : void 0) || (providerName === "xai" ? process.env.XAI_API_KEY : void 0) || (providerName === "cohere" ? process.env.COHERE_API_KEY : void 0) || process.env.OPENAI_API_KEY;
1233
1420
  const baseURL = options.baseURL || process.env.AI_GATEWAY_BASE_URL || (providerName === "openai" ? "https://api.openai.com/v1" : void 0);
1234
1421
  let baseModelInstance = null;
1235
1422
  try {
1236
1423
  if (providerName === "openai" || providerName === "gateway" || !providerName) {
1237
- const { createOpenAI } = __require("@ai-sdk/openai");
1238
- const openaiProvider = createOpenAI({ apiKey, baseURL });
1239
- baseModelInstance = openaiProvider(cleanModelId);
1424
+ const mod = __require("@ai-sdk/openai");
1425
+ const factory = mod.createOpenAI || mod.openai || mod.default?.createOpenAI || mod.default?.openai;
1426
+ if (typeof factory === "function") {
1427
+ if (mod.createOpenAI) {
1428
+ const provider = factory({ apiKey, baseURL });
1429
+ baseModelInstance = provider(cleanModelId);
1430
+ } else {
1431
+ baseModelInstance = factory(cleanModelId);
1432
+ }
1433
+ }
1240
1434
  } else if (providerName === "anthropic") {
1241
- const { createAnthropic } = __require("@ai-sdk/anthropic");
1242
- const anthropicProvider = createAnthropic({ apiKey, baseURL });
1243
- baseModelInstance = anthropicProvider(cleanModelId);
1435
+ const mod = __require("@ai-sdk/anthropic");
1436
+ const factory = mod.createAnthropic || mod.anthropic || mod.default?.createAnthropic || mod.default?.anthropic;
1437
+ if (typeof factory === "function") {
1438
+ if (mod.createAnthropic) {
1439
+ const provider = factory({ apiKey, baseURL });
1440
+ baseModelInstance = provider(cleanModelId);
1441
+ } else {
1442
+ baseModelInstance = factory(cleanModelId);
1443
+ }
1444
+ }
1244
1445
  } else if (providerName === "google") {
1245
- const { createGoogleGenerativeAI } = __require("@ai-sdk/google");
1246
- const googleProvider = createGoogleGenerativeAI({ apiKey, baseURL });
1247
- baseModelInstance = googleProvider(cleanModelId);
1446
+ const mod = __require("@ai-sdk/google");
1447
+ const factory = mod.createGoogleGenerativeAI || mod.google || mod.default?.createGoogleGenerativeAI || mod.default?.google;
1448
+ if (typeof factory === "function") {
1449
+ if (mod.createGoogleGenerativeAI) {
1450
+ const provider = factory({ apiKey, baseURL });
1451
+ baseModelInstance = provider(cleanModelId);
1452
+ } else {
1453
+ baseModelInstance = factory(cleanModelId);
1454
+ }
1455
+ }
1456
+ } else if (providerName === "mistral") {
1457
+ const mod = __require("@ai-sdk/mistral");
1458
+ const factory = mod.createMistral || mod.mistral || mod.default?.createMistral || mod.default?.mistral;
1459
+ if (typeof factory === "function") {
1460
+ baseModelInstance = mod.createMistral ? factory({ apiKey, baseURL })(cleanModelId) : factory(cleanModelId);
1461
+ }
1462
+ } else if (providerName === "groq") {
1463
+ const mod = __require("@ai-sdk/groq");
1464
+ const factory = mod.createGroq || mod.groq || mod.default?.createGroq || mod.default?.groq;
1465
+ if (typeof factory === "function") {
1466
+ baseModelInstance = mod.createGroq ? factory({ apiKey, baseURL })(cleanModelId) : factory(cleanModelId);
1467
+ }
1468
+ } else if (providerName === "deepseek") {
1469
+ const mod = __require("@ai-sdk/deepseek");
1470
+ const factory = mod.createDeepSeek || mod.deepseek || mod.default?.createDeepSeek || mod.default?.deepseek;
1471
+ if (typeof factory === "function") {
1472
+ baseModelInstance = mod.createDeepSeek ? factory({ apiKey, baseURL })(cleanModelId) : factory(cleanModelId);
1473
+ }
1474
+ } else if (providerName === "xai") {
1475
+ const mod = __require("@ai-sdk/xai");
1476
+ const factory = mod.createXai || mod.xai || mod.default?.createXai || mod.default?.xai;
1477
+ if (typeof factory === "function") {
1478
+ baseModelInstance = mod.createXai ? factory({ apiKey, baseURL })(cleanModelId) : factory(cleanModelId);
1479
+ }
1480
+ } else if (providerName === "cohere") {
1481
+ const mod = __require("@ai-sdk/cohere");
1482
+ const factory = mod.createCohere || mod.cohere || mod.default?.createCohere || mod.default?.cohere;
1483
+ if (typeof factory === "function") {
1484
+ baseModelInstance = mod.createCohere ? factory({ apiKey, baseURL })(cleanModelId) : factory(cleanModelId);
1485
+ }
1248
1486
  }
1249
1487
  } catch {
1250
1488
  baseModelInstance = {
@@ -1323,6 +1561,23 @@ var vibezcheck = Object.assign(createVibezModel, {
1323
1561
  session: createVibezSession
1324
1562
  });
1325
1563
 
1564
+ // src/ai-sdk/middleware.ts
1565
+ function vibezcheckMiddleware(options = {}) {
1566
+ return {
1567
+ specificationVersion: "v1",
1568
+ wrapGenerate: async ({ doGenerate, params, model }) => {
1569
+ const target = { ...model, doGenerate };
1570
+ const metered = withBilling(target, options);
1571
+ return metered.doGenerate(params);
1572
+ },
1573
+ wrapStream: async ({ doStream, params, model }) => {
1574
+ const target = { ...model, doStream };
1575
+ const metered = withBilling(target, options);
1576
+ return metered.doStream(params);
1577
+ }
1578
+ };
1579
+ }
1580
+
1326
1581
  // src/customers/manager.ts
1327
1582
  import Stripe2 from "stripe";
1328
1583
 
@@ -1488,8 +1743,8 @@ import * as crypto from "crypto";
1488
1743
  import Stripe3 from "stripe";
1489
1744
  var ApiKeyAuth = class {
1490
1745
  stripe;
1491
- constructor(stripe) {
1492
- this.stripe = stripe;
1746
+ constructor(stripe2) {
1747
+ this.stripe = stripe2;
1493
1748
  }
1494
1749
  /**
1495
1750
  * Hashes a raw API key using SHA-256
@@ -1654,6 +1909,164 @@ function createBillingHelper(options = {}) {
1654
1909
  return new BillingHelper(options);
1655
1910
  }
1656
1911
 
1912
+ // src/billing/session.ts
1913
+ var AgentSession = class {
1914
+ sessionId;
1915
+ customer;
1916
+ maxCostUSD;
1917
+ totalCostUSD = 0;
1918
+ totalTokens = 0;
1919
+ toolCalls = [];
1920
+ options;
1921
+ constructor(options = {}) {
1922
+ this.sessionId = `vibez_sess_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1923
+ this.customer = options.customer;
1924
+ this.maxCostUSD = options.sessionBudgetUSD ?? options.maxCostUSD ?? 1;
1925
+ this.options = options;
1926
+ }
1927
+ /**
1928
+ * Returns an AI model instance bound to this agent session with cumulative budget enforcement
1929
+ */
1930
+ model(modelOrId, modelOptions = {}) {
1931
+ const session = this;
1932
+ return withBilling(modelOrId, {
1933
+ ...modelOptions,
1934
+ customer: this.customer,
1935
+ pricing: modelOptions.pricing || this.options.pricing,
1936
+ billing: modelOptions.billing || this.options.billing,
1937
+ onUsage: async (event) => {
1938
+ const callCost = event.cost.retailUSD ?? event.cost.billedUSD ?? event.cost.totalUSD;
1939
+ session.totalCostUSD = Number((session.totalCostUSD + callCost).toFixed(8));
1940
+ session.totalTokens += event.usage.totalTokens;
1941
+ if (session.totalCostUSD > session.maxCostUSD) {
1942
+ throw new VibezCircuitBreakerError({
1943
+ reason: "cost_per_call_exceeded",
1944
+ limit: session.maxCostUSD,
1945
+ current: session.totalCostUSD,
1946
+ model: event.model,
1947
+ customerId: event.customerId,
1948
+ message: `[vibezcheck] Agent Session Budget exceeded: Cumulative cost ($${session.totalCostUSD.toFixed(4)}) exceeded limit ($${session.maxCostUSD.toFixed(4)}).`
1949
+ });
1950
+ }
1951
+ if (session.options.onUsage) {
1952
+ await session.options.onUsage(event);
1953
+ }
1954
+ }
1955
+ });
1956
+ }
1957
+ /**
1958
+ * Tracks an external tool invocation (e.g. web search, Python code sandbox, vector query, API call)
1959
+ */
1960
+ async trackTool(toolName, costOrOptions, fn) {
1961
+ const costUSD = typeof costOrOptions === "number" ? costOrOptions : costOrOptions.costUSD;
1962
+ const latencyMs = typeof costOrOptions === "object" ? costOrOptions.latencyMs : void 0;
1963
+ const metadata = typeof costOrOptions === "object" ? costOrOptions.metadata : void 0;
1964
+ if (this.totalCostUSD + costUSD > this.maxCostUSD) {
1965
+ throw new VibezCircuitBreakerError({
1966
+ reason: "cost_per_call_exceeded",
1967
+ limit: this.maxCostUSD,
1968
+ current: this.totalCostUSD + costUSD,
1969
+ model: `tool:${toolName}`,
1970
+ message: `[vibezcheck] Agent Session Budget exceeded on tool '${toolName}': ($${(this.totalCostUSD + costUSD).toFixed(4)}) exceeded limit ($${this.maxCostUSD.toFixed(4)}).`
1971
+ });
1972
+ }
1973
+ let result = void 0;
1974
+ const start = performance.now();
1975
+ if (fn) {
1976
+ result = await fn();
1977
+ }
1978
+ const elapsed = latencyMs ?? Math.round(performance.now() - start);
1979
+ this.totalCostUSD = Number((this.totalCostUSD + costUSD).toFixed(8));
1980
+ this.toolCalls.push({
1981
+ name: toolName,
1982
+ costUSD,
1983
+ latencyMs: elapsed,
1984
+ metadata
1985
+ });
1986
+ return result;
1987
+ }
1988
+ getCurrentCostUSD() {
1989
+ return this.totalCostUSD;
1990
+ }
1991
+ getTotalTokens() {
1992
+ return this.totalTokens;
1993
+ }
1994
+ /**
1995
+ * Concludes session and returns final financial summary
1996
+ */
1997
+ async conclude() {
1998
+ return this.getSummary();
1999
+ }
2000
+ /**
2001
+ * Returns current session summary
2002
+ */
2003
+ getSummary() {
2004
+ return {
2005
+ sessionId: this.sessionId,
2006
+ customer: this.customer,
2007
+ totalCostUSD: this.totalCostUSD,
2008
+ totalTokens: this.totalTokens,
2009
+ toolCallCount: this.toolCalls.length,
2010
+ toolCalls: [...this.toolCalls]
2011
+ };
2012
+ }
2013
+ };
2014
+ function createAgentSession(options = {}) {
2015
+ return new AgentSession(options);
2016
+ }
2017
+
2018
+ // src/billing/tools.ts
2019
+ function wrapTool(options) {
2020
+ const { name, costUSD, tool, execute } = options;
2021
+ const targetFn = execute || tool?.execute;
2022
+ if (!targetFn && !tool) {
2023
+ return options;
2024
+ }
2025
+ const base = tool || {};
2026
+ return {
2027
+ ...base,
2028
+ name,
2029
+ costUSD,
2030
+ execute: async (...args) => {
2031
+ const startTime = performance.now();
2032
+ try {
2033
+ const result = await targetFn(...args);
2034
+ const latencyMs = Math.round(performance.now() - startTime);
2035
+ if (typeof globalThis.__vibezCurrentSession?.trackTool === "function") {
2036
+ await globalThis.__vibezCurrentSession.trackTool(name, {
2037
+ costUSD,
2038
+ latencyMs,
2039
+ metadata: { args: args[0] }
2040
+ });
2041
+ }
2042
+ return result;
2043
+ } catch (error) {
2044
+ const latencyMs = Math.round(performance.now() - startTime);
2045
+ if (typeof globalThis.__vibezCurrentSession?.trackTool === "function") {
2046
+ await globalThis.__vibezCurrentSession.trackTool(name, {
2047
+ costUSD,
2048
+ latencyMs,
2049
+ metadata: { error: String(error) }
2050
+ });
2051
+ }
2052
+ throw error;
2053
+ }
2054
+ }
2055
+ };
2056
+ }
2057
+ function instrumentToolKit(tools, options = {}) {
2058
+ const instrumented = {};
2059
+ const cost = options.costPerActionUSD ?? 5e-3;
2060
+ for (const [toolName, toolDef] of Object.entries(tools)) {
2061
+ instrumented[toolName] = wrapTool({
2062
+ name: toolName,
2063
+ costUSD: cost,
2064
+ tool: toolDef
2065
+ });
2066
+ }
2067
+ return instrumented;
2068
+ }
2069
+
1657
2070
  // src/meter/index.ts
1658
2071
  var defaultMeter = createMeter();
1659
2072
  function wrapStream(stream, options) {
@@ -1663,6 +2076,299 @@ function trackTokens(response, options) {
1663
2076
  return defaultMeter.trackUsage(response, options);
1664
2077
  }
1665
2078
 
2079
+ // src/compat/token-meter.ts
2080
+ function createTokenMeter(stripeApiKey, config = {}) {
2081
+ const apiKey = stripeApiKey || (typeof process !== "undefined" ? process.env?.STRIPE_SECRET_KEY || process.env?.STRIPE_API_KEY : void 0);
2082
+ const meter = new VibezMeter({
2083
+ apiKey,
2084
+ eventName: config.eventName
2085
+ });
2086
+ const resolveCustomer = (cust) => {
2087
+ if (typeof cust === "string") return cust;
2088
+ return cust.customerId || cust.customer || "unknown-customer";
2089
+ };
2090
+ return {
2091
+ trackUsage(response, customer) {
2092
+ if (!response) return;
2093
+ const customerId = resolveCustomer(customer);
2094
+ meter.trackUsage(response, { customer: customerId });
2095
+ },
2096
+ track(response, customer) {
2097
+ if (!response) return;
2098
+ const customerId = resolveCustomer(customer);
2099
+ meter.trackUsage(response, { customer: customerId });
2100
+ },
2101
+ trackUsageStreamOpenAI(stream, customer) {
2102
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
2103
+ return stream;
2104
+ }
2105
+ const stripeCustomerId = resolveCustomer(customer);
2106
+ const originalIterator = stream[Symbol.asyncIterator].bind(stream);
2107
+ let capturedUsage = null;
2108
+ let capturedModel = "gpt-4o";
2109
+ const wrappedAsyncGenerator = async function* () {
2110
+ try {
2111
+ for await (const chunk of originalIterator()) {
2112
+ if (chunk.model) {
2113
+ capturedModel = chunk.model;
2114
+ }
2115
+ if (chunk.usage || chunk.token_usage) {
2116
+ capturedUsage = chunk.usage || chunk.token_usage;
2117
+ }
2118
+ yield chunk;
2119
+ }
2120
+ } finally {
2121
+ if (capturedUsage) {
2122
+ meter.recordUsage({
2123
+ model: capturedModel,
2124
+ provider: "openai",
2125
+ inputTokens: capturedUsage.prompt_tokens ?? capturedUsage.inputTokens ?? 0,
2126
+ outputTokens: capturedUsage.completion_tokens ?? capturedUsage.outputTokens ?? 0,
2127
+ reasoningTokens: capturedUsage.completion_tokens_details?.reasoning_tokens ?? capturedUsage.output_token_details?.reasoning_tokens ?? 0,
2128
+ cachedTokens: capturedUsage.prompt_tokens_details?.cached_tokens ?? capturedUsage.input_token_details?.cached_tokens ?? 0,
2129
+ customer: stripeCustomerId
2130
+ });
2131
+ }
2132
+ }
2133
+ };
2134
+ return wrappedAsyncGenerator();
2135
+ },
2136
+ trackUsageStreamAnthropic(stream, customer) {
2137
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
2138
+ return stream;
2139
+ }
2140
+ const stripeCustomerId = resolveCustomer(customer);
2141
+ const originalIterator = stream[Symbol.asyncIterator].bind(stream);
2142
+ let capturedUsage = null;
2143
+ let capturedModel = "claude-3-5-sonnet";
2144
+ const wrappedAsyncGenerator = async function* () {
2145
+ try {
2146
+ for await (const chunk of originalIterator()) {
2147
+ if (chunk.type === "message_start" && chunk.message?.model) {
2148
+ capturedModel = chunk.message.model;
2149
+ if (chunk.message.usage) {
2150
+ capturedUsage = { ...capturedUsage, ...chunk.message.usage };
2151
+ }
2152
+ } else if (chunk.type === "message_delta" && chunk.usage) {
2153
+ capturedUsage = { ...capturedUsage, ...chunk.usage };
2154
+ }
2155
+ yield chunk;
2156
+ }
2157
+ } finally {
2158
+ if (capturedUsage) {
2159
+ meter.recordUsage({
2160
+ model: capturedModel,
2161
+ provider: "anthropic",
2162
+ inputTokens: capturedUsage.input_tokens ?? 0,
2163
+ outputTokens: capturedUsage.output_tokens ?? 0,
2164
+ cachedTokens: capturedUsage.cache_read_input_tokens ?? 0,
2165
+ customer: stripeCustomerId
2166
+ });
2167
+ }
2168
+ }
2169
+ };
2170
+ return wrappedAsyncGenerator();
2171
+ },
2172
+ trackUsageStreamGemini(streamResult, customer, modelName = "gemini-2.0-flash") {
2173
+ const stripeCustomerId = resolveCustomer(customer);
2174
+ const originalStream = streamResult?.stream || streamResult;
2175
+ if (!originalStream || typeof originalStream[Symbol.asyncIterator] !== "function") {
2176
+ return streamResult;
2177
+ }
2178
+ const wrappedAsyncGenerator = async function* () {
2179
+ let lastUsageMetadata = null;
2180
+ try {
2181
+ for await (const chunk of originalStream) {
2182
+ if (chunk.usageMetadata) {
2183
+ lastUsageMetadata = chunk.usageMetadata;
2184
+ }
2185
+ yield chunk;
2186
+ }
2187
+ } finally {
2188
+ if (lastUsageMetadata) {
2189
+ meter.recordUsage({
2190
+ model: modelName,
2191
+ provider: "google",
2192
+ inputTokens: lastUsageMetadata.promptTokenCount ?? 0,
2193
+ outputTokens: (lastUsageMetadata.candidatesTokenCount ?? 0) + (lastUsageMetadata.thoughtsTokenCount ?? 0),
2194
+ reasoningTokens: lastUsageMetadata.thoughtsTokenCount ?? 0,
2195
+ customer: stripeCustomerId
2196
+ });
2197
+ }
2198
+ }
2199
+ };
2200
+ if (streamResult && streamResult.stream) {
2201
+ return {
2202
+ ...streamResult,
2203
+ stream: wrappedAsyncGenerator()
2204
+ };
2205
+ }
2206
+ return wrappedAsyncGenerator();
2207
+ },
2208
+ trackUsageStreamDeepSeek(stream, customer, modelName = "deepseek-chat") {
2209
+ const stripeCustomerId = resolveCustomer(customer);
2210
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
2211
+ return stream;
2212
+ }
2213
+ const originalIterator = stream[Symbol.asyncIterator].bind(stream);
2214
+ let capturedUsage = null;
2215
+ let capturedModel = modelName;
2216
+ const wrappedAsyncGenerator = async function* () {
2217
+ try {
2218
+ for await (const chunk of originalIterator()) {
2219
+ if (chunk.model) capturedModel = chunk.model;
2220
+ if (chunk.usage) capturedUsage = chunk.usage;
2221
+ yield chunk;
2222
+ }
2223
+ } finally {
2224
+ if (capturedUsage) {
2225
+ meter.recordUsage({
2226
+ model: capturedModel,
2227
+ provider: "deepseek",
2228
+ inputTokens: capturedUsage.prompt_tokens ?? capturedUsage.inputTokens ?? 0,
2229
+ outputTokens: capturedUsage.completion_tokens ?? capturedUsage.outputTokens ?? 0,
2230
+ reasoningTokens: capturedUsage.completion_tokens_details?.reasoning_tokens ?? 0,
2231
+ cachedTokens: capturedUsage.prompt_cache_hit_tokens ?? capturedUsage.prompt_tokens_details?.cached_tokens ?? 0,
2232
+ customer: stripeCustomerId
2233
+ });
2234
+ }
2235
+ }
2236
+ };
2237
+ return wrappedAsyncGenerator();
2238
+ },
2239
+ trackUsageStreamGroq(stream, customer, modelName = "llama-3.3-70b-versatile") {
2240
+ const stripeCustomerId = resolveCustomer(customer);
2241
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
2242
+ return stream;
2243
+ }
2244
+ const originalIterator = stream[Symbol.asyncIterator].bind(stream);
2245
+ let capturedUsage = null;
2246
+ let capturedModel = modelName;
2247
+ const wrappedAsyncGenerator = async function* () {
2248
+ try {
2249
+ for await (const chunk of originalIterator()) {
2250
+ if (chunk.model) capturedModel = chunk.model;
2251
+ if (chunk.usage || chunk.x_groq?.usage) {
2252
+ capturedUsage = chunk.usage || chunk.x_groq?.usage;
2253
+ }
2254
+ yield chunk;
2255
+ }
2256
+ } finally {
2257
+ if (capturedUsage) {
2258
+ meter.recordUsage({
2259
+ model: capturedModel,
2260
+ provider: "groq",
2261
+ inputTokens: capturedUsage.prompt_tokens ?? 0,
2262
+ outputTokens: capturedUsage.completion_tokens ?? 0,
2263
+ customer: stripeCustomerId
2264
+ });
2265
+ }
2266
+ }
2267
+ };
2268
+ return wrappedAsyncGenerator();
2269
+ },
2270
+ trackUsageStreamMistral(stream, customer, modelName = "mistral-large-latest") {
2271
+ const stripeCustomerId = resolveCustomer(customer);
2272
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
2273
+ return stream;
2274
+ }
2275
+ const originalIterator = stream[Symbol.asyncIterator].bind(stream);
2276
+ let capturedUsage = null;
2277
+ let capturedModel = modelName;
2278
+ const wrappedAsyncGenerator = async function* () {
2279
+ try {
2280
+ for await (const chunk of originalIterator()) {
2281
+ if (chunk.model) capturedModel = chunk.model;
2282
+ if (chunk.usage) capturedUsage = chunk.usage;
2283
+ yield chunk;
2284
+ }
2285
+ } finally {
2286
+ if (capturedUsage) {
2287
+ meter.recordUsage({
2288
+ model: capturedModel,
2289
+ provider: "mistral",
2290
+ inputTokens: capturedUsage.prompt_tokens ?? 0,
2291
+ outputTokens: capturedUsage.completion_tokens ?? 0,
2292
+ customer: stripeCustomerId
2293
+ });
2294
+ }
2295
+ }
2296
+ };
2297
+ return wrappedAsyncGenerator();
2298
+ },
2299
+ trackUsageStream(stream, customer, options = {}) {
2300
+ const stripeCustomerId = resolveCustomer(customer);
2301
+ return meter.wrapStream(stream, {
2302
+ customer: stripeCustomerId,
2303
+ model: options.model,
2304
+ provider: options.provider
2305
+ });
2306
+ }
2307
+ };
2308
+ }
2309
+
2310
+ // src/compat/stripe-provider.ts
2311
+ function createStripe(config = {}) {
2312
+ const apiKey = config.apiKey || (typeof process !== "undefined" ? process.env?.STRIPE_API_KEY || process.env?.STRIPE_SECRET_KEY : void 0);
2313
+ const provider = function(modelId, settings = {}) {
2314
+ const customerId = settings.customerId || config.customerId || "anonymous";
2315
+ const options = {
2316
+ customer: customerId,
2317
+ stripeApiKey: apiKey
2318
+ };
2319
+ if (settings.model && typeof settings.model === "object") {
2320
+ return withBilling(settings.model, options);
2321
+ }
2322
+ return createVibezModel(modelId, {
2323
+ ...settings,
2324
+ customer: customerId,
2325
+ stripeApiKey: apiKey,
2326
+ baseURL: config.baseURL
2327
+ });
2328
+ };
2329
+ provider.languageModel = provider;
2330
+ provider.specificationVersion = "v3";
2331
+ return provider;
2332
+ }
2333
+ var stripe = createStripe();
2334
+ var createStripeV3 = createStripe;
2335
+ var stripeV3 = stripe;
2336
+
2337
+ // src/compat/stripe-meter.ts
2338
+ function meteredModel2(model, arg2, arg3, arg4) {
2339
+ if (!model || typeof model !== "object") {
2340
+ throw new Error("[vibezcheck / Stripe AI] Invalid model provided to meteredModel().");
2341
+ }
2342
+ let stripeApiKey;
2343
+ let stripeCustomerId;
2344
+ let options = {};
2345
+ if (typeof arg2 === "object" && arg2 !== null) {
2346
+ options = { ...arg2 };
2347
+ stripeCustomerId = options.customerId || (typeof options.customer === "string" ? options.customer : options.customer?.id);
2348
+ stripeApiKey = options.stripeApiKey;
2349
+ } else if (typeof arg2 === "string") {
2350
+ if (typeof arg3 === "string") {
2351
+ stripeApiKey = arg2;
2352
+ stripeCustomerId = arg3;
2353
+ options = { ...arg4 || {} };
2354
+ } else {
2355
+ stripeCustomerId = arg2;
2356
+ options = { ...typeof arg3 === "object" ? arg3 : {} };
2357
+ }
2358
+ }
2359
+ stripeApiKey = stripeApiKey || options.stripeApiKey || (typeof process !== "undefined" ? process.env?.STRIPE_API_KEY || process.env?.STRIPE_SECRET_KEY : void 0);
2360
+ if (typeof process !== "undefined" && stripeApiKey && !process.env.STRIPE_API_KEY && !process.env.STRIPE_SECRET_KEY) {
2361
+ process.env.STRIPE_API_KEY = stripeApiKey;
2362
+ }
2363
+ const mergedOptions = {
2364
+ ...options,
2365
+ customer: stripeCustomerId || options.customer,
2366
+ customerId: stripeCustomerId,
2367
+ stripeApiKey
2368
+ };
2369
+ return withBilling(model, mergedOptions);
2370
+ }
2371
+
1666
2372
  // src/index.ts
1667
2373
  var VibezCheckClient = class {
1668
2374
  meter;
@@ -1738,21 +2444,31 @@ function vibezcheck2(firstArg, secondArg) {
1738
2444
  return new VibezCheckClient(firstArg || {});
1739
2445
  }
1740
2446
  vibezcheck2.calculateCost = calculateCost;
2447
+ vibezcheck2.calculateUsageCost = calculateUsageCost;
1741
2448
  vibezcheck2.getModelPricing = getModelPricing;
1742
2449
  vibezcheck2.registerModelPricing = registerModelPricing;
1743
2450
  vibezcheck2.create = createVibezCheck;
1744
2451
  vibezcheck2.withBilling = withBilling;
1745
2452
  vibezcheck2.createMeter = createMeter;
1746
- vibezcheck2.session = createVibezSession;
2453
+ vibezcheck2.session = createAgentSession;
2454
+ vibezcheck2.Session = AgentSession;
2455
+ vibezcheck2.wrapTool = wrapTool;
2456
+ vibezcheck2.instrumentToolKit = instrumentToolKit;
2457
+ vibezcheck2.middleware = vibezcheckMiddleware;
2458
+ vibezcheck2.Billing = BillingHelper;
2459
+ vibezcheck2.Auth = ApiKeyAuth;
2460
+ vibezcheck2.Customers = CustomerManager;
1747
2461
  var vibez = new VibezCheckClient();
1748
2462
  var vibescheck = vibezcheck2;
1749
2463
  var vibes = vibez;
1750
2464
  export {
2465
+ AgentSession,
1751
2466
  AnthropicStreamAccumulator,
1752
2467
  ApiKeyAuth,
1753
2468
  BillingHelper,
1754
2469
  CustomerCache,
1755
2470
  CustomerManager,
2471
+ MODEL_ALIASES,
1756
2472
  MODEL_PRICING_TABLE,
1757
2473
  MeterBatcher,
1758
2474
  VibezCheckClient,
@@ -1760,10 +2476,14 @@ export {
1760
2476
  VibezMeter,
1761
2477
  calculateCost,
1762
2478
  calculateUsageCost,
2479
+ createAgentSession,
1763
2480
  createApiKeyAuth,
1764
2481
  createBillingHelper,
1765
2482
  createCustomerManager,
1766
2483
  createMeter,
2484
+ createStripe,
2485
+ createStripeV3,
2486
+ createTokenMeter,
1767
2487
  createVibezCheck,
1768
2488
  createVibezModel,
1769
2489
  createVibezSession,
@@ -1775,20 +2495,26 @@ export {
1775
2495
  extractOpenAIResponseUsage,
1776
2496
  getModelPricing,
1777
2497
  inspectOpenAIStreamChunk,
2498
+ instrumentToolKit,
1778
2499
  meteredModel,
1779
2500
  normalizeCustomer,
1780
2501
  normalizeModelKey,
1781
2502
  registerModelPricing,
2503
+ stripe,
2504
+ meteredModel2 as stripeMeteredModel,
2505
+ stripeV3,
1782
2506
  trackTokens,
1783
2507
  vibes,
1784
2508
  vibescheck,
1785
2509
  vibez,
1786
2510
  vibezcheck2 as vibezcheck,
2511
+ vibezcheckMiddleware,
1787
2512
  withBilling,
1788
2513
  wrapAnthropicStream,
1789
2514
  wrapGeminiStream,
1790
2515
  wrapOpenAIStream,
1791
2516
  wrapStream,
2517
+ wrapTool,
1792
2518
  wrapUniversalStream
1793
2519
  };
1794
2520
  //# sourceMappingURL=index.mjs.map