@omnicross/core 0.1.3 → 0.1.4

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 (114) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +57 -57
  3. package/README.md +15 -15
  4. package/dist/auth/GeminiCodeAssistProjectResolver.cjs +4 -4
  5. package/dist/auth/GeminiCodeAssistProjectResolver.js +3 -3
  6. package/dist/chunk-3QFXFCHG.js +33 -0
  7. package/dist/chunk-4YINUUKQ.cjs +33 -0
  8. package/dist/chunk-7Y47UCF2.js +142 -0
  9. package/dist/chunk-APYG5QD7.cjs +50 -0
  10. package/dist/{chunk-CWM2ZDU5.js → chunk-BPKCU575.js} +3 -10
  11. package/dist/{chunk-2FMI2B6V.cjs → chunk-DKPXN34V.cjs} +222 -448
  12. package/dist/chunk-E3UCVHLP.cjs +142 -0
  13. package/dist/chunk-FCR77GYM.cjs +33 -0
  14. package/dist/{chunk-N5QFKSDO.js → chunk-HRRYG2AX.js} +2 -1
  15. package/dist/{chunk-KUU2RNG6.cjs → chunk-HYN75H6G.cjs} +3 -0
  16. package/dist/{chunk-JO5NLTLY.js → chunk-IK3KE3AU.js} +3 -0
  17. package/dist/chunk-K5NM7VAH.js +33 -0
  18. package/dist/{chunk-Y6OM7EV7.cjs → chunk-KFI44N2R.cjs} +2 -1
  19. package/dist/{chunk-S6JGLF3G.cjs → chunk-OCEUVQHW.cjs} +27 -4
  20. package/dist/chunk-OE6TDIWW.js +22 -0
  21. package/dist/chunk-OZFM4X3S.js +18 -0
  22. package/dist/{chunk-4DECIFU7.js → chunk-QYTT6GE3.js} +62 -288
  23. package/dist/{chunk-FFALUUZZ.cjs → chunk-RGTR7CIO.cjs} +5 -5
  24. package/dist/{chunk-3QOSDDNI.cjs → chunk-SNYBEXLB.cjs} +6 -13
  25. package/dist/{chunk-2DCNB7DF.cjs → chunk-SU2GCLAC.cjs} +30 -10
  26. package/dist/{chunk-5HTVET6E.js → chunk-TIER4SUC.js} +24 -4
  27. package/dist/{chunk-CZHZGRU7.js → chunk-UHGVBFU3.js} +2 -0
  28. package/dist/chunk-UIBD2YY5.cjs +22 -0
  29. package/dist/{chunk-SVXC36MU.cjs → chunk-VACWOIRE.cjs} +2 -0
  30. package/dist/{chunk-MQNDWYPN.js → chunk-VPBAUQ2M.js} +4 -4
  31. package/dist/chunk-WLYIIEAF.js +50 -0
  32. package/dist/{chunk-BO4RFWBR.js → chunk-XK5CIRMQ.js} +24 -1
  33. package/dist/chunk-XSVNC2UD.cjs +18 -0
  34. package/dist/completion/CompletionService.cjs +22 -16
  35. package/dist/completion/CompletionService.js +21 -15
  36. package/dist/completion.cjs +24 -18
  37. package/dist/completion.js +23 -17
  38. package/dist/index.cjs +33 -24
  39. package/dist/index.d.cts +7 -3
  40. package/dist/index.d.ts +7 -3
  41. package/dist/index.js +42 -33
  42. package/dist/keyPolicy-Cp0FntZl.d.cts +90 -0
  43. package/dist/keyPolicy-Cp0FntZl.d.ts +90 -0
  44. package/dist/outbound-api/auditCapture.cjs +9 -0
  45. package/dist/outbound-api/auditCapture.d.cts +52 -0
  46. package/dist/outbound-api/auditCapture.d.ts +52 -0
  47. package/dist/outbound-api/auditCapture.js +9 -0
  48. package/dist/outbound-api/auditRedact.cjs +8 -0
  49. package/dist/outbound-api/auditRedact.d.cts +30 -0
  50. package/dist/outbound-api/auditRedact.d.ts +30 -0
  51. package/dist/outbound-api/auditRedact.js +8 -0
  52. package/dist/outbound-api/billingCapture.cjs +8 -0
  53. package/dist/outbound-api/billingCapture.d.cts +61 -0
  54. package/dist/outbound-api/billingCapture.d.ts +61 -0
  55. package/dist/outbound-api/billingCapture.js +8 -0
  56. package/dist/outbound-api/quotaWarn.cjs +12 -0
  57. package/dist/outbound-api/quotaWarn.d.cts +43 -0
  58. package/dist/outbound-api/quotaWarn.d.ts +43 -0
  59. package/dist/outbound-api/quotaWarn.js +12 -0
  60. package/dist/outbound-api/routeResolver.cjs +2 -2
  61. package/dist/outbound-api/routeResolver.d.cts +3 -2
  62. package/dist/outbound-api/routeResolver.d.ts +3 -2
  63. package/dist/outbound-api/routeResolver.js +1 -1
  64. package/dist/outbound-api/types.d.cts +2 -1
  65. package/dist/outbound-api/types.d.ts +2 -1
  66. package/dist/outbound-api.cjs +29 -20
  67. package/dist/outbound-api.d.cts +9 -140
  68. package/dist/outbound-api.d.ts +9 -140
  69. package/dist/outbound-api.js +28 -19
  70. package/dist/pipeline/AuthSource.d.cts +6 -0
  71. package/dist/pipeline/AuthSource.d.ts +6 -0
  72. package/dist/pipeline/SubscriptionAuthSource.cjs +2 -2
  73. package/dist/pipeline/SubscriptionAuthSource.js +1 -1
  74. package/dist/pipeline/SubscriptionAuthStrategy.d.cts +6 -0
  75. package/dist/pipeline/SubscriptionAuthStrategy.d.ts +6 -0
  76. package/dist/pipeline/auditUsageStash.cjs +10 -0
  77. package/dist/pipeline/auditUsageStash.d.cts +37 -0
  78. package/dist/pipeline/auditUsageStash.d.ts +37 -0
  79. package/dist/pipeline/auditUsageStash.js +10 -0
  80. package/dist/pipeline/executeProviderCall.cjs +2 -2
  81. package/dist/pipeline/executeProviderCall.js +1 -1
  82. package/dist/pipeline/upstreamFetch.cjs +14 -0
  83. package/dist/pipeline/upstreamFetch.d.cts +83 -0
  84. package/dist/pipeline/upstreamFetch.d.ts +83 -0
  85. package/dist/pipeline/upstreamFetch.js +14 -0
  86. package/dist/pipeline/webhookEmit.cjs +10 -0
  87. package/dist/pipeline/webhookEmit.d.cts +36 -0
  88. package/dist/pipeline/webhookEmit.d.ts +36 -0
  89. package/dist/pipeline/webhookEmit.js +10 -0
  90. package/dist/ports.d.cts +2 -1
  91. package/dist/ports.d.ts +2 -1
  92. package/dist/provider-proxy/ProviderProxy.cjs +22 -16
  93. package/dist/provider-proxy/ProviderProxy.js +21 -15
  94. package/dist/provider-proxy/ingress/providerProxyShared.cjs +22 -16
  95. package/dist/provider-proxy/ingress/providerProxyShared.js +21 -15
  96. package/dist/provider-proxy/types.d.cts +7 -0
  97. package/dist/provider-proxy/types.d.ts +7 -0
  98. package/dist/provider-proxy.cjs +22 -16
  99. package/dist/provider-proxy.js +21 -15
  100. package/dist/{routeResolver-B1NglTfe.d.ts → routeResolver-C4T7yClx.d.ts} +1 -1
  101. package/dist/{routeResolver-CbG5uBgm.d.cts → routeResolver-CB3tvJKy.d.cts} +1 -1
  102. package/dist/transformer/transformers/OpenAIResponseTransformer.cjs +2 -2
  103. package/dist/transformer/transformers/OpenAIResponseTransformer.js +1 -1
  104. package/dist/transformer/transformers.cjs +6 -6
  105. package/dist/transformer/transformers.js +5 -5
  106. package/dist/transformer.cjs +7 -7
  107. package/dist/transformer.js +6 -6
  108. package/dist/{types-aBFFXoBz.d.cts → types-B8Arpxn0.d.cts} +14 -90
  109. package/dist/{types-6OUY_xfA.d.ts → types-lgPYQuZS.d.ts} +14 -90
  110. package/dist/usage/usage-recorder.cjs +3 -2
  111. package/dist/usage/usage-recorder.js +2 -1
  112. package/dist/usage.cjs +3 -2
  113. package/dist/usage.js +2 -1
  114. package/package.json +64 -64
@@ -3,19 +3,16 @@
3
3
  var _chunkHQP3K7PUcjs = require('./chunk-HQP3K7PU.cjs');
4
4
 
5
5
 
6
- var _chunk46ZIFWYGcjs = require('./chunk-46ZIFWYG.cjs');
7
-
8
-
9
6
  var _chunk4VAVYUZScjs = require('./chunk-4VAVYUZS.cjs');
10
7
 
11
8
 
12
9
  var _chunk7YN22L2Hcjs = require('./chunk-7YN22L2H.cjs');
13
10
 
14
11
 
15
- var _chunk2DCNB7DFcjs = require('./chunk-2DCNB7DF.cjs');
12
+ var _chunkSU2GCLACcjs = require('./chunk-SU2GCLAC.cjs');
16
13
 
17
14
 
18
- var _chunk3QOSDDNIcjs = require('./chunk-3QOSDDNI.cjs');
15
+ var _chunk46ZIFWYGcjs = require('./chunk-46ZIFWYG.cjs');
19
16
 
20
17
 
21
18
  var _chunkGBHYAGX3cjs = require('./chunk-GBHYAGX3.cjs');
@@ -32,60 +29,65 @@ var _chunk6RPZADX3cjs = require('./chunk-6RPZADX3.cjs');
32
29
  var _chunkQWBWGODScjs = require('./chunk-QWBWGODS.cjs');
33
30
 
34
31
 
35
- var _chunkNYUNU75Acjs = require('./chunk-NYUNU75A.cjs');
32
+ var _chunkUIBD2YY5cjs = require('./chunk-UIBD2YY5.cjs');
36
33
 
37
34
 
35
+ var _chunkR3HK6R4Bcjs = require('./chunk-R3HK6R4B.cjs');
38
36
 
39
- var _chunkVQY5W4YWcjs = require('./chunk-VQY5W4YW.cjs');
40
37
 
38
+ var _chunkHYN75H6Gcjs = require('./chunk-HYN75H6G.cjs');
41
39
 
42
- var _chunkY6OM7EV7cjs = require('./chunk-Y6OM7EV7.cjs');
43
40
 
44
41
 
45
- var _chunkSVNDB62Dcjs = require('./chunk-SVNDB62D.cjs');
42
+ var _chunkQ27JY5RGcjs = require('./chunk-Q27JY5RG.cjs');
46
43
 
47
44
 
48
- var _chunkR3HK6R4Bcjs = require('./chunk-R3HK6R4B.cjs');
45
+ var _chunkQXD4MV2Xcjs = require('./chunk-QXD4MV2X.cjs');
49
46
 
50
47
 
48
+ var _chunkNYUNU75Acjs = require('./chunk-NYUNU75A.cjs');
51
49
 
52
- var _chunkAEOZIDEBcjs = require('./chunk-AEOZIDEB.cjs');
53
50
 
54
51
 
52
+ var _chunkVQY5W4YWcjs = require('./chunk-VQY5W4YW.cjs');
55
53
 
56
- var _chunkL74VDN4Acjs = require('./chunk-L74VDN4A.cjs');
57
54
 
55
+ var _chunkKFI44N2Rcjs = require('./chunk-KFI44N2R.cjs');
58
56
 
59
- var _chunkKUU2RNG6cjs = require('./chunk-KUU2RNG6.cjs');
60
57
 
58
+ var _chunkSVNDB62Dcjs = require('./chunk-SVNDB62D.cjs');
61
59
 
62
60
 
63
- var _chunkQ27JY5RGcjs = require('./chunk-Q27JY5RG.cjs');
61
+ var _chunkAPYG5QD7cjs = require('./chunk-APYG5QD7.cjs');
64
62
 
65
63
 
66
- var _chunkQXD4MV2Xcjs = require('./chunk-QXD4MV2X.cjs');
64
+
65
+ var _chunk4YINUUKQcjs = require('./chunk-4YINUUKQ.cjs');
66
+
67
67
 
68
68
 
69
69
 
70
70
 
71
- var _chunkA2YMUCBTcjs = require('./chunk-A2YMUCBT.cjs');
72
71
 
73
72
 
74
73
 
75
74
 
75
+ var _chunkVACWOIREcjs = require('./chunk-VACWOIRE.cjs');
76
76
 
77
77
 
78
78
 
79
79
 
80
+ var _chunkA2YMUCBTcjs = require('./chunk-A2YMUCBT.cjs');
81
+
80
82
 
81
- var _chunkSVXC36MUcjs = require('./chunk-SVXC36MU.cjs');
83
+ var _chunkE3UCVHLPcjs = require('./chunk-E3UCVHLP.cjs');
82
84
 
83
85
 
84
86
 
85
87
  var _chunkSUEGJ75Dcjs = require('./chunk-SUEGJ75D.cjs');
86
88
 
87
89
 
88
- var _chunkS6JGLF3Gcjs = require('./chunk-S6JGLF3G.cjs');
90
+ var _chunkOCEUVQHWcjs = require('./chunk-OCEUVQHW.cjs');
89
91
 
90
92
 
91
93
  var _chunkJMJBSACDcjs = require('./chunk-JMJBSACD.cjs');
@@ -515,7 +517,7 @@ function getSharedExecutor() {
515
517
  }
516
518
  var sharedResponses = null;
517
519
  function getResponsesEndpointTransformer() {
518
- if (!sharedResponses) sharedResponses = new (0, _chunk2DCNB7DFcjs.OpenAIResponseTransformer)();
520
+ if (!sharedResponses) sharedResponses = new (0, _chunkSU2GCLACcjs.OpenAIResponseTransformer)();
519
521
  return sharedResponses;
520
522
  }
521
523
  var sharedAnthropic = null;
@@ -695,7 +697,7 @@ async function buildSubscriptionPlan(res, route, deps, anthropicBody, routeModel
695
697
  function buildSubscriptionIterationPlan(profile, route, deps, resolvedModel, isStream, scenario, sessionKey) {
696
698
  const upstreamUrl = _optionalChain([profile, 'access', _8 => _8.resolveUpstreamUrl, 'optionalCall', _9 => _9(resolvedModel, route.subscriptionConfig)]);
697
699
  if (!upstreamUrl) return null;
698
- const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkY6OM7EV7cjs.SubscriptionAuthSource)(profile)));
700
+ const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkKFI44N2Rcjs.SubscriptionAuthSource)(profile)));
699
701
  const sameFormat = profile.mode === "pass-through" || upstreamUrl.endsWith("/v1/messages");
700
702
  const overrideNames = _optionalChain([profile, 'access', _10 => _10.resolveProviderTransformerNames, 'optionalCall', _11 => _11(
701
703
  resolvedModel,
@@ -715,6 +717,7 @@ function buildSubscriptionIterationPlan(profile, route, deps, resolvedModel, isS
715
717
  };
716
718
  return {
717
719
  auth,
720
+ preferredAccountId: route.preferredAccountId,
718
721
  chain,
719
722
  transformerProvider,
720
723
  resolvedModel,
@@ -788,13 +791,14 @@ async function runPipeline(anthropicBody, plan, reportSelection) {
788
791
  upstreamUrl,
789
792
  model: resolvedModel,
790
793
  sessionKey: plan.sessionKey,
794
+ preferredAccountId: plan.preferredAccountId,
791
795
  reportSelection: (accountId, isActive) => {
792
796
  proxyAccountId = accountId;
793
797
  _optionalChain([reportSelection, 'optionalCall', _12 => _12(accountId, isActive)]);
794
798
  }
795
799
  });
796
800
  let rawStatus = null;
797
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
801
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
798
802
  executor,
799
803
  request: anthropicBody,
800
804
  provider: transformerProvider,
@@ -812,7 +816,7 @@ async function runPipeline(anthropicBody, plan, reportSelection) {
812
816
  },
813
817
  fetchFn: (url, headers, body) => {
814
818
  console.info(`[ProviderProxy:anthropic] -> ${url} model=${resolvedModel} stream=${isStream}`);
815
- return _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
819
+ return _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
816
820
  url,
817
821
  { method: "POST", headers, body: JSON.stringify(body) },
818
822
  { providerId: proxyProviderId(plan), accountId: proxyAccountId }
@@ -833,6 +837,7 @@ async function runSubscriptionSameFormatFetch(rawBody, plan, reportSelection, op
833
837
  upstreamUrl: plan.upstreamUrl,
834
838
  model: plan.resolvedModel,
835
839
  sessionKey: plan.sessionKey,
840
+ preferredAccountId: plan.preferredAccountId,
836
841
  reportSelection: (accountId, isActive, remapped) => {
837
842
  proxyAccountId = accountId;
838
843
  remappedModel = remapped;
@@ -854,7 +859,7 @@ async function runSubscriptionSameFormatFetch(rawBody, plan, reportSelection, op
854
859
  console.info(
855
860
  `[ProviderProxy:anthropic] (subscription same-format) -> ${plan.upstreamUrl} model=${outboundModel} stream=${plan.isStream}`
856
861
  );
857
- const response = await _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
862
+ const response = await _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
858
863
  plan.upstreamUrl,
859
864
  { method: "POST", headers, body: outboundBody },
860
865
  { providerId: proxyProviderId(plan), accountId: proxyAccountId }
@@ -1106,7 +1111,7 @@ async function runSameFormatFetch(bodyToSend, plan, options, keyOverride) {
1106
1111
  _chunkGBHYAGX3cjs.injectExtendedContextBeta.call(void 0, headers, resolvedModel, _nullishCoalesce(extendedContextEnabled, () => ( false)));
1107
1112
  const url = _chunkA2YMUCBTcjs.buildProviderApiUrl.call(void 0, provider, { model: resolvedModel, stream: isStream });
1108
1113
  console.info(`[ProviderProxy:anthropic] (same-format) -> ${url} model=${resolvedModel} stream=${isStream}`);
1109
- const response = await _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
1114
+ const response = await _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
1110
1115
  url,
1111
1116
  { method: "POST", headers, body: bodyToSend },
1112
1117
  { providerId: "byo" }
@@ -1323,7 +1328,7 @@ async function runPipeline2(geminiBody, plan) {
1323
1328
  const authHeaders = {};
1324
1329
  await auth.applyHeaders(authHeaders, { upstreamUrl, model: resolvedModel });
1325
1330
  let rawStatus = null;
1326
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
1331
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
1327
1332
  executor,
1328
1333
  request: geminiBody,
1329
1334
  provider: transformerProvider,
@@ -1341,7 +1346,7 @@ async function runPipeline2(geminiBody, plan) {
1341
1346
  },
1342
1347
  fetchFn: (url, headers, body) => {
1343
1348
  console.log(`[ProviderProxy:gemini] -> ${url} model=${resolvedModel} stream=${isStream}`);
1344
- return _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
1349
+ return _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
1345
1350
  url,
1346
1351
  { method: "POST", headers, body: JSON.stringify(body) },
1347
1352
  { providerId: "byo" }
@@ -1510,7 +1515,7 @@ async function buildSubscriptionPlan2(res, route, deps, resolvedModel, isStream)
1510
1515
  writeError(res, 502, "Subscription profile is missing resolveUpstreamUrl");
1511
1516
  return null;
1512
1517
  }
1513
- const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkY6OM7EV7cjs.SubscriptionAuthSource)(profile)));
1518
+ const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkKFI44N2Rcjs.SubscriptionAuthSource)(profile)));
1514
1519
  const chain = _chunkNYUNU75Acjs.resolveSubscriptionChain.call(void 0,
1515
1520
  profile,
1516
1521
  deps.llmConfig.getTransformerService(),
@@ -1547,7 +1552,7 @@ async function runPipeline3(chatBody, plan) {
1547
1552
  }
1548
1553
  });
1549
1554
  let rawStatus = null;
1550
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
1555
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
1551
1556
  executor,
1552
1557
  request: chatBody,
1553
1558
  provider: transformerProvider,
@@ -1564,7 +1569,7 @@ async function runPipeline3(chatBody, plan) {
1564
1569
  },
1565
1570
  fetchFn: (url, headers, body) => {
1566
1571
  console.log(`[ProviderProxy:chat] -> ${url} model=${resolvedModel} stream=${isStream}`);
1567
- return _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
1572
+ return _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
1568
1573
  url,
1569
1574
  { method: "POST", headers, body: JSON.stringify(body) },
1570
1575
  { providerId: plan.proxyProviderId, accountId: proxyAccountId }
@@ -1732,7 +1737,7 @@ async function buildSubscriptionPlan3(res, route, deps, resolvedModel, isStream)
1732
1737
  writeError(res, 502, "Subscription profile is missing resolveUpstreamUrl");
1733
1738
  return null;
1734
1739
  }
1735
- const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkY6OM7EV7cjs.SubscriptionAuthSource)(profile)));
1740
+ const auth = _nullishCoalesce(route.auth, () => ( new (0, _chunkKFI44N2Rcjs.SubscriptionAuthSource)(profile)));
1736
1741
  const chain = _chunkNYUNU75Acjs.resolveSubscriptionChain.call(void 0,
1737
1742
  profile,
1738
1743
  deps.llmConfig.getTransformerService(),
@@ -1754,6 +1759,7 @@ async function buildSubscriptionPlan3(res, route, deps, resolvedModel, isStream)
1754
1759
  }
1755
1760
  return {
1756
1761
  auth,
1762
+ preferredAccountId: route.preferredAccountId,
1757
1763
  chain,
1758
1764
  transformerProvider,
1759
1765
  resolvedModel,
@@ -1785,12 +1791,13 @@ async function runPipeline4(responsesBody, plan) {
1785
1791
  await auth.applyHeaders(authHeaders, {
1786
1792
  upstreamUrl,
1787
1793
  model: resolvedModel,
1794
+ preferredAccountId: plan.preferredAccountId,
1788
1795
  reportSelection: (accountId) => {
1789
1796
  proxyAccountId = accountId;
1790
1797
  }
1791
1798
  });
1792
1799
  let rawStatus = null;
1793
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
1800
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
1794
1801
  executor,
1795
1802
  request: responsesBody,
1796
1803
  provider: transformerProvider,
@@ -1808,7 +1815,7 @@ async function runPipeline4(responsesBody, plan) {
1808
1815
  },
1809
1816
  fetchFn: (url, headers, body) => {
1810
1817
  console.log(`[ProviderProxy:responses] -> ${url} model=${resolvedModel} stream=${isStream}`);
1811
- return _chunkS6JGLF3Gcjs.fetchUpstream.call(void 0,
1818
+ return _chunkOCEUVQHWcjs.fetchUpstream.call(void 0,
1812
1819
  url,
1813
1820
  { method: "POST", headers, body: JSON.stringify(body) },
1814
1821
  { providerId: plan.proxyProviderId, accountId: proxyAccountId }
@@ -2044,17 +2051,6 @@ var KeyedMutex = (_class3 = class {constructor() { _class3.prototype.__init4.cal
2044
2051
  // src/outbound-api/outboundApiRouter.ts
2045
2052
  var _stream = require('stream');
2046
2053
 
2047
- // src/pipeline/webhookEmit.ts
2048
- var sink = null;
2049
- function emitWebhookEvent(event) {
2050
- const active = sink;
2051
- if (!active) return;
2052
- try {
2053
- active(event);
2054
- } catch (e17) {
2055
- }
2056
- }
2057
-
2058
2054
  // src/outbound-api/apiServerConfig.ts
2059
2055
  var _audittypes = require('@omnicross/contracts/audit-types');
2060
2056
  var _billingtypes = require('@omnicross/contracts/billing-types');
@@ -2261,11 +2257,11 @@ function normalizeQueueSegments(raw) {
2261
2257
  var ALL_ENDPOINTS = ["chat", "responses", "messages", "gemini"];
2262
2258
  function blankModelMap(endpoint) {
2263
2259
  const modelMap = {};
2264
- for (const kind of _chunkSVXC36MUcjs.modelKindsForEndpoint.call(void 0, endpoint)) modelMap[kind] = "";
2260
+ for (const kind of _chunkVACWOIREcjs.modelKindsForEndpoint.call(void 0, endpoint)) modelMap[kind] = "";
2265
2261
  return modelMap;
2266
2262
  }
2267
2263
  function defaultEndpointConfig(endpoint) {
2268
- if (_chunkSVXC36MUcjs.isKindMappedEndpoint.call(void 0, endpoint)) {
2264
+ if (_chunkVACWOIREcjs.isKindMappedEndpoint.call(void 0, endpoint)) {
2269
2265
  return { endpoint, modelMap: blankModelMap(endpoint), useSubscription: false };
2270
2266
  }
2271
2267
  if (endpoint === "chat") {
@@ -2291,34 +2287,38 @@ function normalizePrefixTargets(raw) {
2291
2287
  function normalizeEndpointConfig(e) {
2292
2288
  const endpoint = e.endpoint;
2293
2289
  const useSubscription = e.useSubscription === true;
2294
- if (_chunkSVXC36MUcjs.isKindMappedEndpoint.call(void 0, endpoint)) {
2290
+ const boundAccountId = typeof e.boundAccountId === "string" && e.boundAccountId.trim() !== "" ? e.boundAccountId : void 0;
2291
+ const boundKeyId = typeof e.boundKeyId === "string" && e.boundKeyId.trim() !== "" ? e.boundKeyId : void 0;
2292
+ let config;
2293
+ if (_chunkVACWOIREcjs.isKindMappedEndpoint.call(void 0, endpoint)) {
2295
2294
  const rawMap = e.modelMap && typeof e.modelMap === "object" ? e.modelMap : {};
2296
2295
  const modelMap = {};
2297
- for (const kind of _chunkSVXC36MUcjs.modelKindsForEndpoint.call(void 0, endpoint)) {
2296
+ for (const kind of _chunkVACWOIREcjs.modelKindsForEndpoint.call(void 0, endpoint)) {
2298
2297
  const v = rawMap[kind];
2299
2298
  modelMap[kind] = typeof v === "string" ? v : "";
2300
2299
  }
2301
- return { endpoint, modelMap, useSubscription };
2302
- }
2303
- if (endpoint === "chat") {
2300
+ config = { endpoint, modelMap, useSubscription };
2301
+ } else if (endpoint === "chat") {
2304
2302
  const models = Array.isArray(e.models) ? e.models.filter((m) => typeof m === "string" && m.trim() !== "") : [];
2305
- const config2 = { endpoint, models, useSubscription };
2303
+ config = { endpoint, models, useSubscription };
2306
2304
  if (e.dispatchMode === "prefix") {
2307
- config2.dispatchMode = "prefix";
2305
+ config.dispatchMode = "prefix";
2308
2306
  const targets = normalizePrefixTargets(e.prefixTargets);
2309
- if (targets) config2.prefixTargets = targets;
2307
+ if (targets) config.prefixTargets = targets;
2308
+ }
2309
+ } else {
2310
+ config = {
2311
+ endpoint,
2312
+ defaultModel: typeof e.defaultModel === "string" ? e.defaultModel : "",
2313
+ backgroundModel: typeof e.backgroundModel === "string" ? e.backgroundModel : "",
2314
+ useSubscription
2315
+ };
2316
+ if (Array.isArray(e.backgroundModelIds)) {
2317
+ config.backgroundModelIds = e.backgroundModelIds;
2310
2318
  }
2311
- return config2;
2312
- }
2313
- const config = {
2314
- endpoint,
2315
- defaultModel: typeof e.defaultModel === "string" ? e.defaultModel : "",
2316
- backgroundModel: typeof e.backgroundModel === "string" ? e.backgroundModel : "",
2317
- useSubscription
2318
- };
2319
- if (Array.isArray(e.backgroundModelIds)) {
2320
- config.backgroundModelIds = e.backgroundModelIds;
2321
2319
  }
2320
+ if (boundAccountId) config.boundAccountId = boundAccountId;
2321
+ if (boundKeyId) config.boundKeyId = boundKeyId;
2322
2322
  return config;
2323
2323
  }
2324
2324
  function defaultServerConfig() {
@@ -2406,204 +2406,6 @@ function mergeServerConfig(current, patch) {
2406
2406
  });
2407
2407
  }
2408
2408
 
2409
- // src/outbound-api/auditCapture.ts
2410
-
2411
-
2412
- // src/outbound-api/auditRedact.ts
2413
- var AUDIT_REDACTED = "***REDACTED***";
2414
- var RULES = [
2415
- // `sk-…` family (Anthropic sk-ant-, omnicross sk-omnicross-, OpenAI sk-proj-/sk-).
2416
- { re: /\bsk-[A-Za-z0-9_-]{6,}/g, replace: AUDIT_REDACTED },
2417
- // Google API keys.
2418
- { re: /\bAIza[A-Za-z0-9_-]{10,}/g, replace: AUDIT_REDACTED },
2419
- // `Bearer <token>` (auth headers echoed into a body / SSE error).
2420
- { re: /\bBearer\s+[A-Za-z0-9._~+/=-]{6,}/gi, replace: `Bearer ${AUDIT_REDACTED}` },
2421
- // Inline `x-api-key` / `api-key` / `authorization` label followed by a value.
2422
- {
2423
- re: /\b(x-api-key|api[_-]?key|authorization)(["']?\s*[:=]\s*["']?)[A-Za-z0-9._~+/=-]{6,}/gi,
2424
- replace: `$1$2${AUDIT_REDACTED}`
2425
- },
2426
- // `x-goog-api-key` header echoed inline.
2427
- {
2428
- re: /\b(x-goog-api-key)(["']?\s*[:=]\s*["']?)[A-Za-z0-9._~+/=-]{6,}/gi,
2429
- replace: `$1$2${AUDIT_REDACTED}`
2430
- }
2431
- ];
2432
- function redactAuditText(text) {
2433
- if (typeof text !== "string" || text.length === 0) return _nullishCoalesce(text, () => ( ""));
2434
- let out = text;
2435
- for (const { re, replace } of RULES) {
2436
- out = out.replace(re, replace);
2437
- }
2438
- return out;
2439
- }
2440
-
2441
- // src/outbound-api/auditCapture.ts
2442
- function isStreamingContentType(res) {
2443
- const ct = res.getHeader("content-type");
2444
- const value = Array.isArray(ct) ? ct.join(";") : String(_nullishCoalesce(ct, () => ( "")));
2445
- return value.toLowerCase().includes("text/event-stream");
2446
- }
2447
- function resolveClientIp(req, trustForwardedFor) {
2448
- if (trustForwardedFor) {
2449
- const xff = req.headers["x-forwarded-for"];
2450
- const raw = Array.isArray(xff) ? xff[0] : xff;
2451
- if (typeof raw === "string" && raw.trim()) {
2452
- const first = _optionalChain([raw, 'access', _105 => _105.split, 'call', _106 => _106(","), 'access', _107 => _107[0], 'optionalAccess', _108 => _108.trim, 'call', _109 => _109()]);
2453
- if (first) return first;
2454
- }
2455
- }
2456
- return _nullishCoalesce(_optionalChain([req, 'access', _110 => _110.socket, 'optionalAccess', _111 => _111.remoteAddress]), () => ( void 0));
2457
- }
2458
- function truncateToBytes(text, maxBytes) {
2459
- const buf = Buffer.from(text, "utf8");
2460
- if (buf.length <= maxBytes) return text;
2461
- return buf.subarray(0, maxBytes).toString("utf8");
2462
- }
2463
- function beginAuditCapture(req, res, now) {
2464
- const config = _chunkAEOZIDEBcjs.getAuditCaptureConfig.call(void 0, );
2465
- if (!config) return null;
2466
- let rawRequestBody;
2467
- const responseChunks = [];
2468
- let responseBytes = 0;
2469
- let streamDetected = false;
2470
- let finished = false;
2471
- const ctx = {
2472
- setRequestBody(raw) {
2473
- if (config.captureBodies) rawRequestBody = raw;
2474
- }
2475
- };
2476
- if (config.captureBodies) {
2477
- installResponseCapture(res, config.maxBodyBytes, {
2478
- push(chunk) {
2479
- responseBytes += chunk.length;
2480
- responseChunks.push(chunk);
2481
- },
2482
- get bytes() {
2483
- return responseBytes;
2484
- },
2485
- markStream() {
2486
- streamDetected = true;
2487
- },
2488
- get isStream() {
2489
- return streamDetected;
2490
- }
2491
- });
2492
- }
2493
- const finalize = () => {
2494
- if (finished) return;
2495
- finished = true;
2496
- try {
2497
- const record = {
2498
- id: _crypto.randomUUID.call(void 0, ),
2499
- ts: now,
2500
- method: _nullishCoalesce(req.method, () => ( "")),
2501
- path: _nullishCoalesce((_nullishCoalesce(req.url, () => ( ""))).split("?")[0], () => ( "")),
2502
- status: res.statusCode,
2503
- latencyMs: Math.max(0, Date.now() - now)
2504
- };
2505
- if (ctx.keyId != null) record.keyId = ctx.keyId;
2506
- const ip = resolveClientIp(req, config.trustForwardedFor);
2507
- if (ip) record.ip = ip;
2508
- const ua = req.headers["user-agent"];
2509
- if (typeof ua === "string" && ua) record.ua = ua;
2510
- if (ctx.model) record.model = ctx.model;
2511
- if (ctx.provider) record.provider = ctx.provider;
2512
- const usage = _chunk3QOSDDNIcjs.readAuditUsage.call(void 0, res);
2513
- if (usage) {
2514
- if (typeof usage.inputTokens === "number") record.inputTokens = usage.inputTokens;
2515
- if (typeof usage.outputTokens === "number") record.outputTokens = usage.outputTokens;
2516
- if (typeof usage.costUsd === "number") record.costUsd = usage.costUsd;
2517
- if (!record.model && usage.model) record.model = usage.model;
2518
- if (!record.provider && usage.provider) record.provider = usage.provider;
2519
- }
2520
- if (ctx.error) record.error = redactAuditText(ctx.error);
2521
- if (config.captureBodies) {
2522
- if (rawRequestBody != null && rawRequestBody.length > 0) {
2523
- record.requestBody = redactAuditText(truncateToBytes(rawRequestBody, config.maxBodyBytes));
2524
- }
2525
- if (!streamDetected && responseChunks.length > 0) {
2526
- const body = Buffer.concat(responseChunks).toString("utf8");
2527
- record.responseBody = redactAuditText(body);
2528
- }
2529
- }
2530
- _chunkAEOZIDEBcjs.recordAudit.call(void 0, record);
2531
- } catch (e18) {
2532
- }
2533
- };
2534
- res.once("close", finalize);
2535
- return ctx;
2536
- }
2537
- function installResponseCapture(res, maxBodyBytes, sink2) {
2538
- let contentTypeChecked = false;
2539
- const capture = (chunk) => {
2540
- if (sink2.isStream) return;
2541
- if (!contentTypeChecked) {
2542
- contentTypeChecked = true;
2543
- if (isStreamingContentType(res)) {
2544
- sink2.markStream();
2545
- return;
2546
- }
2547
- }
2548
- if (sink2.bytes >= maxBodyBytes) return;
2549
- let buf = null;
2550
- if (Buffer.isBuffer(chunk)) buf = chunk;
2551
- else if (typeof chunk === "string") buf = Buffer.from(chunk, "utf8");
2552
- if (!buf || buf.length === 0) return;
2553
- const remaining = maxBodyBytes - sink2.bytes;
2554
- sink2.push(buf.length > remaining ? buf.subarray(0, remaining) : buf);
2555
- };
2556
- const originalWrite = res.write.bind(res);
2557
- const originalEnd = res.end.bind(res);
2558
- res.write = ((chunk, ...args) => {
2559
- if (chunk != null) capture(chunk);
2560
- return originalWrite(chunk, ...args);
2561
- });
2562
- res.end = ((chunk, ...args) => {
2563
- if (chunk != null && typeof chunk !== "function") capture(chunk);
2564
- return originalEnd(chunk, ...args);
2565
- });
2566
- }
2567
-
2568
- // src/outbound-api/billingCapture.ts
2569
-
2570
- var defaultDefer = (fn) => {
2571
- setTimeout(fn, 0);
2572
- };
2573
- function beginBillingCapture(_req, res, now, defer = defaultDefer) {
2574
- if (!_chunkL74VDN4Acjs.getBillingCaptureConfig.call(void 0, )) return null;
2575
- const ctx = {};
2576
- let finished = false;
2577
- const finalize = () => {
2578
- if (finished) return;
2579
- finished = true;
2580
- const status = res.statusCode;
2581
- defer(() => {
2582
- try {
2583
- const usage = _chunk3QOSDDNIcjs.readAuditUsage.call(void 0, res);
2584
- if (!usage) return;
2585
- const event = {
2586
- id: _crypto.randomUUID.call(void 0, ),
2587
- ts: now,
2588
- model: _nullishCoalesce(_nullishCoalesce(ctx.model, () => ( usage.model)), () => ( "")),
2589
- authMode: _nullishCoalesce(ctx.authMode, () => ( "byo")),
2590
- inputTokens: _nullishCoalesce(usage.inputTokens, () => ( 0)),
2591
- outputTokens: _nullishCoalesce(usage.outputTokens, () => ( 0)),
2592
- costUsd: _nullishCoalesce(usage.costUsd, () => ( 0)),
2593
- status
2594
- };
2595
- if (ctx.keyId != null) event.keyId = ctx.keyId;
2596
- const provider = _nullishCoalesce(ctx.provider, () => ( usage.provider));
2597
- if (provider) event.provider = provider;
2598
- _chunkL74VDN4Acjs.publishBillingEvent.call(void 0, event);
2599
- } catch (e19) {
2600
- }
2601
- });
2602
- };
2603
- res.once("close", finalize);
2604
- return ctx;
2605
- }
2606
-
2607
2409
  // src/outbound-api/outboundApiKeyAuth.ts
2608
2410
 
2609
2411
 
@@ -2752,30 +2554,6 @@ async function verifyPresentedKey(db, presentedKey) {
2752
2554
  return result.status === "ok" ? result.key : null;
2753
2555
  }
2754
2556
 
2755
- // src/outbound-api/quotaWarn.ts
2756
- var WEBHOOK_QUOTA_WARN_RATIO = 0.8;
2757
- function computeQuotaWarnings(limits, spend, ratio = WEBHOOK_QUOTA_WARN_RATIO) {
2758
- const out = [];
2759
- const consider = (scope, limit, spent, windowStart) => {
2760
- if (limit == null || limit <= 0) return;
2761
- if (spent >= limit) return;
2762
- if (spent >= ratio * limit) out.push({ scope, limitUsd: limit, spentUsd: spent, windowStart });
2763
- };
2764
- consider("daily", limits.dailyUsd, spend.dailyUsd, spend.dailyWindowStart);
2765
- consider("weekly", limits.weeklyUsd, spend.weeklyUsd, spend.weeklyWindowStart);
2766
- consider("total", limits.totalUsd, spend.totalUsd, 0);
2767
- return out;
2768
- }
2769
- var WARN_GUARD_MAX = 1e4;
2770
- var warned = /* @__PURE__ */ new Set();
2771
- function markQuotaWarnedOnce(keyId, scope, windowStart) {
2772
- const key = `${keyId}\0${scope}\0${windowStart}`;
2773
- if (warned.has(key)) return false;
2774
- if (warned.size >= WARN_GUARD_MAX) warned.clear();
2775
- warned.add(key);
2776
- return true;
2777
- }
2778
-
2779
2557
  // src/outbound-api/outboundConcurrencyGate.ts
2780
2558
  var ConcurrencyQueueFullError = (_class4 = class extends Error {
2781
2559
  constructor(apiKeyId, maxQueueSize) {
@@ -2962,8 +2740,8 @@ var OutboundRateLimiter = (_class8 = class {
2962
2740
  * recorded (no bucket growth).
2963
2741
  */
2964
2742
  check(apiKeyId, now = Date.now(), override) {
2965
- const maxRequests = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _112 => _112.maxRequests]), () => ( this.maxRequests));
2966
- const windowMs = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _113 => _113.windowMs]), () => ( this.windowMs));
2743
+ const maxRequests = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _105 => _105.maxRequests]), () => ( this.maxRequests));
2744
+ const windowMs = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _106 => _106.windowMs]), () => ( this.windowMs));
2967
2745
  if (maxRequests === 0) return { allowed: true, retryAfterSeconds: 0 };
2968
2746
  const cutoff = now - windowMs;
2969
2747
  const timestamps = (_nullishCoalesce(this.hits.get(apiKeyId), () => ( []))).filter((ts) => ts > cutoff);
@@ -3008,7 +2786,7 @@ function isUserMessageAnthropic(body) {
3008
2786
  if (typeof content === "string") return true;
3009
2787
  if (Array.isArray(content)) {
3010
2788
  const hasToolResult = content.some(
3011
- (block) => _optionalChain([asObject, 'call', _114 => _114(block), 'optionalAccess', _115 => _115["type"]]) === "tool_result"
2789
+ (block) => _optionalChain([asObject, 'call', _107 => _107(block), 'optionalAccess', _108 => _108["type"]]) === "tool_result"
3012
2790
  );
3013
2791
  return !hasToolResult;
3014
2792
  }
@@ -3037,7 +2815,7 @@ function isUserMessageGemini(body) {
3037
2815
  if (!lastContent || lastContent["role"] !== "user") return false;
3038
2816
  const parts = asArray(lastContent["parts"]);
3039
2817
  const hasFunctionResponse = parts.some(
3040
- (part) => _optionalChain([asObject, 'call', _116 => _116(part), 'optionalAccess', _117 => _117["functionResponse"]]) !== void 0
2818
+ (part) => _optionalChain([asObject, 'call', _109 => _109(part), 'optionalAccess', _110 => _110["functionResponse"]]) !== void 0
3041
2819
  );
3042
2820
  return !hasFunctionResponse;
3043
2821
  }
@@ -3211,14 +2989,14 @@ function newVoucherId() {
3211
2989
  }
3212
2990
  function computeVoucherGrant(voucher, currentKey, now) {
3213
2991
  if (voucher.type === "credit") {
3214
- const current = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _118 => _118.totalCostLimitUsd]), () => ( 0));
2992
+ const current = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _111 => _111.totalCostLimitUsd]), () => ( 0));
3215
2993
  let granted2 = current + (_nullishCoalesce(voucher.creditUsd, () => ( 0)));
3216
2994
  if (voucher.maxTotalCostLimitUsd != null) {
3217
2995
  granted2 = Math.min(granted2, voucher.maxTotalCostLimitUsd);
3218
2996
  }
3219
2997
  return { totalCostLimitUsd: granted2 };
3220
2998
  }
3221
- const currentExpiry = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _119 => _119.expiresAt]), () => ( now));
2999
+ const currentExpiry = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _112 => _112.expiresAt]), () => ( now));
3222
3000
  let granted = currentExpiry + (_nullishCoalesce(voucher.renewalDays, () => ( 0))) * DAY_MS2;
3223
3001
  if (voucher.maxExpiryDays != null) {
3224
3002
  granted = Math.min(granted, now + voucher.maxExpiryDays * DAY_MS2);
@@ -3249,7 +3027,7 @@ function toVoucherInfo(v) {
3249
3027
  // src/outbound-api/voucherRedeem.ts
3250
3028
  function isRedeemRequest(method, url) {
3251
3029
  if (method !== "POST" || !url) return false;
3252
- const path = _nullishCoalesce(_optionalChain([url, 'access', _120 => _120.split, 'call', _121 => _121("?"), 'access', _122 => _122[0], 'optionalAccess', _123 => _123.replace, 'call', _124 => _124(/\/+$/, "")]), () => ( ""));
3030
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _113 => _113.split, 'call', _114 => _114("?"), 'access', _115 => _115[0], 'optionalAccess', _116 => _116.replace, 'call', _117 => _117(/\/+$/, "")]), () => ( ""));
3253
3031
  return path.endsWith("/redeem");
3254
3032
  }
3255
3033
  function writeErr(res, status, message, headers = {}) {
@@ -3279,8 +3057,8 @@ function grantToResult(type, granted) {
3279
3057
  function currentResult(type, keyRow) {
3280
3058
  const result = { type };
3281
3059
  if (type === "credit") {
3282
- if (_optionalChain([keyRow, 'optionalAccess', _125 => _125.totalCostLimitUsd]) != null) result.totalCostLimitUsd = keyRow.totalCostLimitUsd;
3283
- } else if (_optionalChain([keyRow, 'optionalAccess', _126 => _126.expiresAt]) != null) {
3060
+ if (_optionalChain([keyRow, 'optionalAccess', _118 => _118.totalCostLimitUsd]) != null) result.totalCostLimitUsd = keyRow.totalCostLimitUsd;
3061
+ } else if (_optionalChain([keyRow, 'optionalAccess', _119 => _119.expiresAt]) != null) {
3284
3062
  result.expiresAt = keyRow.expiresAt;
3285
3063
  }
3286
3064
  return result;
@@ -3318,7 +3096,7 @@ async function handleVoucherRedeem(req, res, deps, voucherEnabled, redeemLimiter
3318
3096
  let code;
3319
3097
  try {
3320
3098
  code = raw ? JSON.parse(raw)["code"] : void 0;
3321
- } catch (e20) {
3099
+ } catch (e17) {
3322
3100
  writeErr(res, 400, "Invalid JSON in request body");
3323
3101
  return;
3324
3102
  }
@@ -3367,7 +3145,7 @@ async function handleVoucherRedeem(req, res, deps, voucherEnabled, redeemLimiter
3367
3145
  const won = await voucherDb.voucherRedeemCas(voucher.id, verifiedKeyId, absolute, now);
3368
3146
  if (!won) {
3369
3147
  const after = await voucherDb.voucherGetByHash(codeHash);
3370
- if (_optionalChain([after, 'optionalAccess', _127 => _127.status]) === "redeemed" && after.redeemedByKeyId === verifiedKeyId) {
3148
+ if (_optionalChain([after, 'optionalAccess', _120 => _120.status]) === "redeemed" && after.redeemedByKeyId === verifiedKeyId) {
3371
3149
  return after.grantApplied === true ? { ok: true, result: currentResult(after.type, await deps.db.outboundApiKeysGetByHash(keyHash)) } : await applyFirstPass(after, recordedAbsolute(after));
3372
3150
  }
3373
3151
  return { ok: false, status: 409, message: "Code was already redeemed" };
@@ -3428,14 +3206,14 @@ function extractPresentedKey(req) {
3428
3206
  }
3429
3207
  const xApiKey = req.headers["x-api-key"];
3430
3208
  const xApi = Array.isArray(xApiKey) ? xApiKey[0] : xApiKey;
3431
- if (_optionalChain([xApi, 'optionalAccess', _128 => _128.trim, 'call', _129 => _129()])) return xApi.trim();
3209
+ if (_optionalChain([xApi, 'optionalAccess', _121 => _121.trim, 'call', _122 => _122()])) return xApi.trim();
3432
3210
  const goog = req.headers["x-goog-api-key"];
3433
3211
  const g = Array.isArray(goog) ? goog[0] : goog;
3434
- return _optionalChain([g, 'optionalAccess', _130 => _130.trim, 'call', _131 => _131()]) || void 0;
3212
+ return _optionalChain([g, 'optionalAccess', _123 => _123.trim, 'call', _124 => _124()]) || void 0;
3435
3213
  }
3436
3214
  function selectEndpoint(method, url) {
3437
3215
  if (method !== "POST" || !url) return null;
3438
- const path = _nullishCoalesce(_optionalChain([url, 'access', _132 => _132.split, 'call', _133 => _133("?"), 'access', _134 => _134[0], 'optionalAccess', _135 => _135.replace, 'call', _136 => _136(/\/+$/, "")]), () => ( ""));
3216
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _125 => _125.split, 'call', _126 => _126("?"), 'access', _127 => _127[0], 'optionalAccess', _128 => _128.replace, 'call', _129 => _129(/\/+$/, "")]), () => ( ""));
3439
3217
  if (path.endsWith("/chat/completions")) return "chat";
3440
3218
  if (path.endsWith("/responses")) return "responses";
3441
3219
  if (path.includes("/v1/messages")) return "messages";
@@ -3453,12 +3231,12 @@ function extractGeminiModelFromUrl(url) {
3453
3231
  }
3454
3232
  function isModelsListRequest(url) {
3455
3233
  if (!url) return false;
3456
- const path = _nullishCoalesce(_optionalChain([url, 'access', _137 => _137.split, 'call', _138 => _138("?"), 'access', _139 => _139[0], 'optionalAccess', _140 => _140.replace, 'call', _141 => _141(/\/+$/, "")]), () => ( ""));
3234
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _130 => _130.split, 'call', _131 => _131("?"), 'access', _132 => _132[0], 'optionalAccess', _133 => _133.replace, 'call', _134 => _134(/\/+$/, "")]), () => ( ""));
3457
3235
  return path.endsWith("/models");
3458
3236
  }
3459
3237
  function writeChatModelsList(res, config) {
3460
3238
  const chat = config.endpoints.find((e) => e.endpoint === "chat");
3461
- const data = (_nullishCoalesce(_optionalChain([chat, 'optionalAccess', _142 => _142.models]), () => ( []))).map((ref) => _chunkSVXC36MUcjs.parseModelRef.call(void 0, ref)).filter((p) => p !== null).map((p) => ({ id: p.modelId, object: "model", owned_by: "omnicross" }));
3239
+ const data = (_nullishCoalesce(_optionalChain([chat, 'optionalAccess', _135 => _135.models]), () => ( []))).map((ref) => _chunkVACWOIREcjs.parseModelRef.call(void 0, ref)).filter((p) => p !== null).map((p) => ({ id: p.modelId, object: "model", owned_by: "omnicross" }));
3462
3240
  res.writeHead(200, { "Content-Type": "application/json" });
3463
3241
  res.end(JSON.stringify({ object: "list", data }));
3464
3242
  }
@@ -3477,8 +3255,8 @@ function shimAuthHeader(req, routeToken) {
3477
3255
  }
3478
3256
  async function handleOutboundRequest(req, res, deps, config, rateLimiter, serialQueue, concurrencyGate, redeemLimiter, redeemMutex) {
3479
3257
  const now = Date.now();
3480
- const audit = beginAuditCapture(req, res, now);
3481
- const billing = beginBillingCapture(req, res, now);
3258
+ const audit = _chunkE3UCVHLPcjs.beginAuditCapture.call(void 0, req, res, now);
3259
+ const billing = _chunkAPYG5QD7cjs.beginBillingCapture.call(void 0, req, res, now);
3482
3260
  const presented = extractPresentedKey(req);
3483
3261
  const verification = await verifyKey(deps.db, presented, now);
3484
3262
  if (verification.status !== "ok") {
@@ -3497,7 +3275,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3497
3275
  req,
3498
3276
  res,
3499
3277
  deps,
3500
- _optionalChain([config, 'access', _143 => _143.voucher, 'optionalAccess', _144 => _144.enabled]) === true,
3278
+ _optionalChain([config, 'access', _136 => _136.voucher, 'optionalAccess', _137 => _137.enabled]) === true,
3501
3279
  _nullishCoalesce(redeemLimiter, () => ( getFallbackRedeemLimiter())),
3502
3280
  verified.id,
3503
3281
  _nullishCoalesce(presented, () => ( "")),
@@ -3531,7 +3309,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3531
3309
  const spend = await deps.keySpendTracker.getSpend(verified.id, now);
3532
3310
  const quota = checkKeyQuota(verified.costLimits, spend);
3533
3311
  if (!quota.allowed) {
3534
- emitWebhookEvent({
3312
+ _chunkUIBD2YY5cjs.emitWebhookEvent.call(void 0, {
3535
3313
  kind: "key.quotaExceeded",
3536
3314
  at: now,
3537
3315
  keyId: verified.id,
@@ -3542,9 +3320,9 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3542
3320
  writeCostLimitError(res, quota.scope, quota.limitUsd, quota.spentUsd);
3543
3321
  return;
3544
3322
  }
3545
- for (const warn of computeQuotaWarnings(verified.costLimits, spend)) {
3546
- if (markQuotaWarnedOnce(verified.id, warn.scope, warn.windowStart)) {
3547
- emitWebhookEvent({
3323
+ for (const warn of _chunk4YINUUKQcjs.computeQuotaWarnings.call(void 0, verified.costLimits, spend)) {
3324
+ if (_chunk4YINUUKQcjs.markQuotaWarnedOnce.call(void 0, verified.id, warn.scope, warn.windowStart)) {
3325
+ _chunkUIBD2YY5cjs.emitWebhookEvent.call(void 0, {
3548
3326
  kind: "key.quotaWarning",
3549
3327
  at: now,
3550
3328
  keyId: verified.id,
@@ -3583,12 +3361,12 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3583
3361
  res.once("close", release2);
3584
3362
  }
3585
3363
  try {
3586
- const ingressFormat = _chunkSVXC36MUcjs.endpointToIngressFormat.call(void 0, endpoint);
3364
+ const ingressFormat = _chunkVACWOIREcjs.endpointToIngressFormat.call(void 0, endpoint);
3587
3365
  const rawBody = await readBody3(req);
3588
3366
  let parsedBody = {};
3589
3367
  try {
3590
3368
  parsedBody = rawBody ? JSON.parse(rawBody) : {};
3591
- } catch (e21) {
3369
+ } catch (e18) {
3592
3370
  writeJsonError(res, 400, "Invalid JSON in request body");
3593
3371
  return;
3594
3372
  }
@@ -3598,7 +3376,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3598
3376
  if (urlModel) parsedBody["model"] = urlModel;
3599
3377
  }
3600
3378
  const sessionId = deps.proxyDeps.apiKeyPool ? `outbound:${verified.id}` : null;
3601
- const resolved = _chunkSVXC36MUcjs.isKindMappedEndpoint.call(void 0, endpoint) || endpoint === "chat" ? await _chunkSVXC36MUcjs.resolveRoute.call(void 0, {
3379
+ const resolved = _chunkVACWOIREcjs.isKindMappedEndpoint.call(void 0, endpoint) || endpoint === "chat" ? await _chunkVACWOIREcjs.resolveRoute.call(void 0, {
3602
3380
  config: endpointConfig,
3603
3381
  ingressFormat,
3604
3382
  llmConfig: deps.llmConfig,
@@ -3606,12 +3384,12 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3606
3384
  // Capture the ORIGINAL requested id BEFORE any downstream swap; for
3607
3385
  // kind-mapped endpoints it selects the kind AND is stamped onto
3608
3386
  // `route.requestedModel`; for chat it is matched against the list.
3609
- requestedModel: _chunkSVXC36MUcjs.extractRequestedModel.call(void 0, ingressFormat, parsedBody),
3387
+ requestedModel: _chunkVACWOIREcjs.extractRequestedModel.call(void 0, ingressFormat, parsedBody),
3610
3388
  // Attribution: stamp the verified named-key id onto the route.
3611
3389
  apiKeyId: verified.id
3612
- }) : await _chunkSVXC36MUcjs.resolveRoute.call(void 0, {
3390
+ }) : await _chunkVACWOIREcjs.resolveRoute.call(void 0, {
3613
3391
  config: endpointConfig,
3614
- role: _chunkSVXC36MUcjs.detectRequestRole.call(void 0, ingressFormat, parsedBody, {
3392
+ role: _chunkVACWOIREcjs.detectRequestRole.call(void 0, ingressFormat, parsedBody, {
3615
3393
  backgroundModelIds: endpointConfig.backgroundModelIds
3616
3394
  }),
3617
3395
  ingressFormat,
@@ -3642,7 +3420,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3642
3420
  }
3643
3421
  let releaseSerial = null;
3644
3422
  const providerKey = resolved.route.providerId;
3645
- if (_optionalChain([config, 'access', _145 => _145.userMessageQueue, 'optionalAccess', _146 => _146.enabled]) && providerKey && isUserMessageRequest(endpoint, parsedBody)) {
3423
+ if (_optionalChain([config, 'access', _138 => _138.userMessageQueue, 'optionalAccess', _139 => _139.enabled]) && providerKey && isUserMessageRequest(endpoint, parsedBody)) {
3646
3424
  const umq = config.userMessageQueue;
3647
3425
  try {
3648
3426
  const serialSlot = await serialQueue.acquire(providerKey, {
@@ -3677,7 +3455,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
3677
3455
  const message = _chunkSVNDB62Dcjs.serializeError.call(void 0, err);
3678
3456
  if (deps.logger) deps.logger.error("[OutboundApi] dispatch error:", message);
3679
3457
  else console.error("[OutboundApi] dispatch error:", message);
3680
- emitWebhookEvent({ kind: "server.error", at: Date.now(), message });
3458
+ _chunkUIBD2YY5cjs.emitWebhookEvent.call(void 0, { kind: "server.error", at: Date.now(), message });
3681
3459
  if (audit) audit.error = message;
3682
3460
  writeJsonError(res, 502, message);
3683
3461
  } finally {
@@ -3759,7 +3537,7 @@ var OutboundApiServer = (_class11 = class {
3759
3537
  await this.stop();
3760
3538
  return;
3761
3539
  }
3762
- const missing = _chunkSVXC36MUcjs.validateServerModelConfig.call(void 0, {
3540
+ const missing = _chunkVACWOIREcjs.validateServerModelConfig.call(void 0, {
3763
3541
  enabled: true,
3764
3542
  networkBinding: input.networkBinding,
3765
3543
  endpoints: input.endpoints,
@@ -3783,7 +3561,7 @@ var OutboundApiServer = (_class11 = class {
3783
3561
  const actualPort = await this.listen(bindAddr, port);
3784
3562
  this.boundAddr = bindAddr;
3785
3563
  this.boundPort = actualPort;
3786
- if (actualPort !== port) _optionalChain([this, 'access', _147 => _147.onPortChange, 'optionalCall', _148 => _148(actualPort)]);
3564
+ if (actualPort !== port) _optionalChain([this, 'access', _140 => _140.onPortChange, 'optionalCall', _141 => _141(actualPort)]);
3787
3565
  this.logInfo(`[OutboundApiServer] Listening on ${bindAddr}:${actualPort}`);
3788
3566
  return actualPort;
3789
3567
  }
@@ -3850,7 +3628,7 @@ var OutboundApiServer = (_class11 = class {
3850
3628
  const provider = this.deps.healthReportProvider;
3851
3629
  if (!provider) return false;
3852
3630
  if (req.method !== "GET" && req.method !== "HEAD") return false;
3853
- const path = _optionalChain([(_nullishCoalesce(req.url, () => ( "/"))), 'access', _149 => _149.split, 'call', _150 => _150("?"), 'access', _151 => _151[0], 'optionalAccess', _152 => _152.replace, 'call', _153 => _153(/\/+$/, "")]) || "/";
3631
+ const path = _optionalChain([(_nullishCoalesce(req.url, () => ( "/"))), 'access', _142 => _142.split, 'call', _143 => _143("?"), 'access', _144 => _144[0], 'optionalAccess', _145 => _145.replace, 'call', _146 => _146(/\/+$/, "")]) || "/";
3854
3632
  if (path !== "/health" && path !== "/healthz") return false;
3855
3633
  const report = provider();
3856
3634
  res.writeHead(_healthloggingtypes.healthHttpStatus.call(void 0, report.status), { "Content-Type": "application/json" });
@@ -4125,7 +3903,7 @@ async function callAnthropicCompletion(provider, apiKey, options, logger) {
4125
3903
  message: {
4126
3904
  id: `assistant-${Date.now()}`,
4127
3905
  role: "assistant",
4128
- content: _optionalChain([choice2, 'access', _154 => _154.message, 'optionalAccess', _155 => _155.content]) || "",
3906
+ content: _optionalChain([choice2, 'access', _147 => _147.message, 'optionalAccess', _148 => _148.content]) || "",
4129
3907
  timestamp: Date.now()
4130
3908
  },
4131
3909
  usage: openaiResponse2.usage ? {
@@ -4230,7 +4008,7 @@ async function callGeminiCompletion(provider, apiKey, options, logger) {
4230
4008
  const candidate = candidates[0];
4231
4009
  const content = candidate.content;
4232
4010
  let textContent = "";
4233
- if (_optionalChain([content, 'optionalAccess', _156 => _156.parts])) {
4011
+ if (_optionalChain([content, 'optionalAccess', _149 => _149.parts])) {
4234
4012
  for (const part of content.parts) {
4235
4013
  if (part.text) {
4236
4014
  textContent += part.text;
@@ -4363,7 +4141,7 @@ async function streamOpenAICompletion(provider, apiKey, options, messageId, call
4363
4141
  });
4364
4142
  if (!response.ok) {
4365
4143
  const errorText = await response.text();
4366
- _optionalChain([callbacks, 'access', _157 => _157.onError, 'optionalCall', _158 => _158(`API error (${response.status}): ${errorText}`)]);
4144
+ _optionalChain([callbacks, 'access', _150 => _150.onError, 'optionalCall', _151 => _151(`API error (${response.status}): ${errorText}`)]);
4367
4145
  return;
4368
4146
  }
4369
4147
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "openai", {
@@ -4373,7 +4151,7 @@ async function streamOpenAICompletion(provider, apiKey, options, messageId, call
4373
4151
  onVideo: callbacks.onVideo,
4374
4152
  onError: callbacks.onError
4375
4153
  });
4376
- _optionalChain([callbacks, 'access', _159 => _159.onDone, 'optionalCall', _160 => _160(
4154
+ _optionalChain([callbacks, 'access', _152 => _152.onDone, 'optionalCall', _153 => _153(
4377
4155
  {
4378
4156
  id: messageId,
4379
4157
  role: "assistant",
@@ -4445,7 +4223,7 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
4445
4223
  logger.info("Streaming Anthropic completion request", {
4446
4224
  url: apiUrl,
4447
4225
  model: anthropicRequest.model,
4448
- messagesCount: _optionalChain([anthropicRequest, 'access', _161 => _161.messages, 'optionalAccess', _162 => _162.length]),
4226
+ messagesCount: _optionalChain([anthropicRequest, 'access', _154 => _154.messages, 'optionalAccess', _155 => _155.length]),
4449
4227
  max_tokens: anthropicRequest.max_tokens,
4450
4228
  temperature: anthropicRequest.temperature,
4451
4229
  stream: anthropicRequest.stream,
@@ -4462,7 +4240,7 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
4462
4240
  if (!response.ok) {
4463
4241
  const errorText = await response.text();
4464
4242
  logger.error("Anthropic API error", void 0, { status: response.status, errorText });
4465
- _optionalChain([callbacks, 'access', _163 => _163.onError, 'optionalCall', _164 => _164(`API error (${response.status}): ${errorText}`)]);
4243
+ _optionalChain([callbacks, 'access', _156 => _156.onError, 'optionalCall', _157 => _157(`API error (${response.status}): ${errorText}`)]);
4466
4244
  return;
4467
4245
  }
4468
4246
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "anthropic", {
@@ -4473,10 +4251,10 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
4473
4251
  });
4474
4252
  logger.info("Anthropic stream complete", {
4475
4253
  contentLength: result.content.length,
4476
- reasoningLength: _optionalChain([result, 'access', _165 => _165.reasoning, 'optionalAccess', _166 => _166.length]) || 0,
4254
+ reasoningLength: _optionalChain([result, 'access', _158 => _158.reasoning, 'optionalAccess', _159 => _159.length]) || 0,
4477
4255
  blocksCount: result.blocks.length
4478
4256
  });
4479
- _optionalChain([callbacks, 'access', _167 => _167.onDone, 'optionalCall', _168 => _168(
4257
+ _optionalChain([callbacks, 'access', _160 => _160.onDone, 'optionalCall', _161 => _161(
4480
4258
  {
4481
4259
  id: messageId,
4482
4260
  role: "assistant",
@@ -4532,7 +4310,7 @@ async function streamGeminiCompletion(provider, apiKey, options, messageId, call
4532
4310
  if (!response.ok) {
4533
4311
  const errorText = await response.text();
4534
4312
  logger.error("Gemini API error", void 0, { status: response.status, errorText });
4535
- _optionalChain([callbacks, 'access', _169 => _169.onError, 'optionalCall', _170 => _170(`API error (${response.status}): ${errorText}`)]);
4313
+ _optionalChain([callbacks, 'access', _162 => _162.onError, 'optionalCall', _163 => _163(`API error (${response.status}): ${errorText}`)]);
4536
4314
  return;
4537
4315
  }
4538
4316
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "gemini", {
@@ -4541,7 +4319,7 @@ async function streamGeminiCompletion(provider, apiKey, options, messageId, call
4541
4319
  onError: callbacks.onError
4542
4320
  });
4543
4321
  logger.info("Gemini stream complete", { contentLength: result.content.length });
4544
- _optionalChain([callbacks, 'access', _171 => _171.onDone, 'optionalCall', _172 => _172(
4322
+ _optionalChain([callbacks, 'access', _164 => _164.onDone, 'optionalCall', _165 => _165(
4545
4323
  {
4546
4324
  id: messageId,
4547
4325
  role: "assistant",
@@ -4593,7 +4371,7 @@ async function streamOpenAIResponseCompletion(provider, apiKey, options, message
4593
4371
  });
4594
4372
  if (!response.ok) {
4595
4373
  const errorText = await response.text();
4596
- _optionalChain([callbacks, 'access', _173 => _173.onError, 'optionalCall', _174 => _174(`API error (${response.status}): ${errorText}`)]);
4374
+ _optionalChain([callbacks, 'access', _166 => _166.onError, 'optionalCall', _167 => _167(`API error (${response.status}): ${errorText}`)]);
4597
4375
  return;
4598
4376
  }
4599
4377
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "openai-response", {
@@ -4602,7 +4380,7 @@ async function streamOpenAIResponseCompletion(provider, apiKey, options, message
4602
4380
  onError: callbacks.onError
4603
4381
  });
4604
4382
  logger.info("OpenAI Response API stream complete", { contentLength: result.content.length });
4605
- _optionalChain([callbacks, 'access', _175 => _175.onDone, 'optionalCall', _176 => _176(
4383
+ _optionalChain([callbacks, 'access', _168 => _168.onDone, 'optionalCall', _169 => _169(
4606
4384
  {
4607
4385
  id: messageId,
4608
4386
  role: "assistant",
@@ -4630,7 +4408,7 @@ async function resolveEffectiveMaxTokens(llmConfig, getProvider, logger, provide
4630
4408
  }
4631
4409
  try {
4632
4410
  const globalParams = await llmConfig.getGlobalModelParameters();
4633
- if (_optionalChain([globalParams, 'optionalAccess', _177 => _177.maxTokens, 'optionalAccess', _178 => _178.enabled]) && globalParams.maxTokens.value > 0) {
4411
+ if (_optionalChain([globalParams, 'optionalAccess', _170 => _170.maxTokens, 'optionalAccess', _171 => _171.enabled]) && globalParams.maxTokens.value > 0) {
4634
4412
  logger.debug("Using global maxTokens", { maxTokens: globalParams.maxTokens.value });
4635
4413
  return globalParams.maxTokens.value;
4636
4414
  }
@@ -4640,8 +4418,8 @@ async function resolveEffectiveMaxTokens(llmConfig, getProvider, logger, provide
4640
4418
  const MAX_TOKENS_CAP = 131072;
4641
4419
  const provider = await getProvider(providerId);
4642
4420
  if (provider) {
4643
- const modelConfig = _optionalChain([provider, 'access', _179 => _179.modelConfigs, 'optionalAccess', _180 => _180.find, 'call', _181 => _181((m) => m.id === modelId)]);
4644
- if (_optionalChain([modelConfig, 'optionalAccess', _182 => _182.maxTokens]) && modelConfig.maxTokens > 0) {
4421
+ const modelConfig = _optionalChain([provider, 'access', _172 => _172.modelConfigs, 'optionalAccess', _173 => _173.find, 'call', _174 => _174((m) => m.id === modelId)]);
4422
+ if (_optionalChain([modelConfig, 'optionalAccess', _175 => _175.maxTokens]) && modelConfig.maxTokens > 0) {
4645
4423
  const cappedMaxTokens = Math.min(modelConfig.maxTokens, MAX_TOKENS_CAP);
4646
4424
  logger.debug("Using model config maxTokens", {
4647
4425
  maxTokens: modelConfig.maxTokens,
@@ -4651,8 +4429,8 @@ async function resolveEffectiveMaxTokens(llmConfig, getProvider, logger, provide
4651
4429
  }
4652
4430
  if (provider.modelGroups) {
4653
4431
  for (const group of provider.modelGroups) {
4654
- const model = _optionalChain([group, 'access', _183 => _183.models, 'optionalAccess', _184 => _184.find, 'call', _185 => _185((m) => m.id === modelId)]);
4655
- if (_optionalChain([model, 'optionalAccess', _186 => _186.maxTokens]) && model.maxTokens > 0) {
4432
+ const model = _optionalChain([group, 'access', _176 => _176.models, 'optionalAccess', _177 => _177.find, 'call', _178 => _178((m) => m.id === modelId)]);
4433
+ if (_optionalChain([model, 'optionalAccess', _179 => _179.maxTokens]) && model.maxTokens > 0) {
4656
4434
  const cappedMaxTokens = Math.min(model.maxTokens, MAX_TOKENS_CAP);
4657
4435
  logger.debug("Using modelGroup model maxTokens", {
4658
4436
  maxTokens: model.maxTokens,
@@ -4697,7 +4475,7 @@ async function resolveThinkingBudget(getProvider, logger, providerId, modelId, m
4697
4475
  }
4698
4476
  const thinkingBudget = _thinkingconfig.calculateThinkingBudget.call(void 0, modelId, thinkLevel, maxTokens);
4699
4477
  const provider = await getProvider(providerId);
4700
- const providerName = _optionalChain([provider, 'optionalAccess', _187 => _187.name, 'optionalAccess', _188 => _188.toLowerCase, 'call', _189 => _189()]) || "";
4478
+ const providerName = _optionalChain([provider, 'optionalAccess', _180 => _180.name, 'optionalAccess', _181 => _181.toLowerCase, 'call', _182 => _182()]) || "";
4701
4479
  const apiFormat = provider ? _chunkA2YMUCBTcjs.resolveApiFormat.call(void 0, provider) : "openai";
4702
4480
  if (apiFormat === "anthropic" || providerName === "anthropic" || providerName.includes("claude")) {
4703
4481
  const thinkingConfig = _thinkingconfig.buildAnthropicThinking.call(void 0, modelId, thinkLevel, maxTokens);
@@ -4734,7 +4512,7 @@ function logToolFormat(tools, logger) {
4734
4512
  tools: openaiTools.map((t) => t.function.name),
4735
4513
  firstTool: {
4736
4514
  name: firstTool.function.name,
4737
- description: _optionalChain([firstTool, 'access', _190 => _190.function, 'access', _191 => _191.description, 'optionalAccess', _192 => _192.slice, 'call', _193 => _193(0, 100)]),
4515
+ description: _optionalChain([firstTool, 'access', _183 => _183.function, 'access', _184 => _184.description, 'optionalAccess', _185 => _185.slice, 'call', _186 => _186(0, 100)]),
4738
4516
  parameters: firstTool.function.parameters
4739
4517
  }
4740
4518
  });
@@ -4745,7 +4523,7 @@ function logToolFormat(tools, logger) {
4745
4523
  tools: anthropicTools.map((t) => t.name),
4746
4524
  firstTool: {
4747
4525
  name: firstTool.name,
4748
- description: _optionalChain([firstTool, 'access', _194 => _194.description, 'optionalAccess', _195 => _195.slice, 'call', _196 => _196(0, 100)]),
4526
+ description: _optionalChain([firstTool, 'access', _187 => _187.description, 'optionalAccess', _188 => _188.slice, 'call', _189 => _189(0, 100)]),
4749
4527
  input_schema: firstTool.input_schema
4750
4528
  }
4751
4529
  });
@@ -4756,9 +4534,9 @@ function logToolFormat(tools, logger) {
4756
4534
  count: allDeclarations.length,
4757
4535
  tools: allDeclarations.map((t) => t.name),
4758
4536
  firstTool: {
4759
- name: _optionalChain([allDeclarations, 'access', _197 => _197[0], 'optionalAccess', _198 => _198.name]),
4760
- description: _optionalChain([allDeclarations, 'access', _199 => _199[0], 'optionalAccess', _200 => _200.description, 'optionalAccess', _201 => _201.slice, 'call', _202 => _202(0, 100)]),
4761
- parameters: _optionalChain([allDeclarations, 'access', _203 => _203[0], 'optionalAccess', _204 => _204.parameters])
4537
+ name: _optionalChain([allDeclarations, 'access', _190 => _190[0], 'optionalAccess', _191 => _191.name]),
4538
+ description: _optionalChain([allDeclarations, 'access', _192 => _192[0], 'optionalAccess', _193 => _193.description, 'optionalAccess', _194 => _194.slice, 'call', _195 => _195(0, 100)]),
4539
+ parameters: _optionalChain([allDeclarations, 'access', _196 => _196[0], 'optionalAccess', _197 => _197.parameters])
4762
4540
  }
4763
4541
  });
4764
4542
  }
@@ -4817,7 +4595,7 @@ function buildToolRequest(apiFormat, conversationMessages, actualModel, options,
4817
4595
  function extractDeltaContent(rawJson, apiFormat) {
4818
4596
  const json = rawJson;
4819
4597
  if (apiFormat === "google") {
4820
- const parts = _optionalChain([json, 'access', _205 => _205.candidates, 'optionalAccess', _206 => _206[0], 'optionalAccess', _207 => _207.content, 'optionalAccess', _208 => _208.parts]) || [];
4598
+ const parts = _optionalChain([json, 'access', _198 => _198.candidates, 'optionalAccess', _199 => _199[0], 'optionalAccess', _200 => _200.content, 'optionalAccess', _201 => _201.parts]) || [];
4821
4599
  let text = "";
4822
4600
  for (const part of parts) {
4823
4601
  if (part.thought === true) continue;
@@ -4825,15 +4603,15 @@ function extractDeltaContent(rawJson, apiFormat) {
4825
4603
  }
4826
4604
  return text;
4827
4605
  } else if (apiFormat === "anthropic") {
4828
- return _optionalChain([json, 'access', _209 => _209.delta, 'optionalAccess', _210 => _210.text]) || "";
4606
+ return _optionalChain([json, 'access', _202 => _202.delta, 'optionalAccess', _203 => _203.text]) || "";
4829
4607
  } else {
4830
- return _optionalChain([json, 'access', _211 => _211.choices, 'optionalAccess', _212 => _212[0], 'optionalAccess', _213 => _213.delta, 'optionalAccess', _214 => _214.content]) || "";
4608
+ return _optionalChain([json, 'access', _204 => _204.choices, 'optionalAccess', _205 => _205[0], 'optionalAccess', _206 => _206.delta, 'optionalAccess', _207 => _207.content]) || "";
4831
4609
  }
4832
4610
  }
4833
4611
  function extractDeltaReasoning(rawJson, apiFormat) {
4834
4612
  const json = rawJson;
4835
4613
  if (apiFormat === "google") {
4836
- const parts = _optionalChain([json, 'access', _215 => _215.candidates, 'optionalAccess', _216 => _216[0], 'optionalAccess', _217 => _217.content, 'optionalAccess', _218 => _218.parts]) || [];
4614
+ const parts = _optionalChain([json, 'access', _208 => _208.candidates, 'optionalAccess', _209 => _209[0], 'optionalAccess', _210 => _210.content, 'optionalAccess', _211 => _211.parts]) || [];
4837
4615
  let reasoning = "";
4838
4616
  for (const part of parts) {
4839
4617
  if (part.thought === true && part.text) reasoning += part.text;
@@ -4842,14 +4620,14 @@ function extractDeltaReasoning(rawJson, apiFormat) {
4842
4620
  } else if (apiFormat === "anthropic") {
4843
4621
  return "";
4844
4622
  } else {
4845
- const delta = _optionalChain([json, 'access', _219 => _219.choices, 'optionalAccess', _220 => _220[0], 'optionalAccess', _221 => _221.delta]);
4846
- return (_optionalChain([delta, 'optionalAccess', _222 => _222.thinking, 'optionalAccess', _223 => _223.content]) || "") + (_optionalChain([delta, 'optionalAccess', _224 => _224.reasoning_content]) || "");
4623
+ const delta = _optionalChain([json, 'access', _212 => _212.choices, 'optionalAccess', _213 => _213[0], 'optionalAccess', _214 => _214.delta]);
4624
+ return (_optionalChain([delta, 'optionalAccess', _215 => _215.thinking, 'optionalAccess', _216 => _216.content]) || "") + (_optionalChain([delta, 'optionalAccess', _217 => _217.reasoning_content]) || "");
4847
4625
  }
4848
4626
  }
4849
4627
  function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pendingOpenAIToolCalls) {
4850
4628
  const json = rawJson;
4851
4629
  if (apiFormat === "google") {
4852
- const parts = _optionalChain([json, 'access', _225 => _225.candidates, 'optionalAccess', _226 => _226[0], 'optionalAccess', _227 => _227.content, 'optionalAccess', _228 => _228.parts]) || [];
4630
+ const parts = _optionalChain([json, 'access', _218 => _218.candidates, 'optionalAccess', _219 => _219[0], 'optionalAccess', _220 => _220.content, 'optionalAccess', _221 => _221.parts]) || [];
4853
4631
  for (const part of parts) {
4854
4632
  if (part.functionCall) {
4855
4633
  logger.info("Function call detected", { functionCall: part.functionCall });
@@ -4859,13 +4637,13 @@ function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pend
4859
4637
  args: part.functionCall.args || {}
4860
4638
  };
4861
4639
  toolCalls.push(toolCall);
4862
- _optionalChain([callbacks, 'access', _229 => _229.onToolCall, 'optionalCall', _230 => _230(toolCall)]);
4640
+ _optionalChain([callbacks, 'access', _222 => _222.onToolCall, 'optionalCall', _223 => _223(toolCall)]);
4863
4641
  logger.info("Tool called", { toolName: toolCall.name });
4864
4642
  }
4865
4643
  }
4866
4644
  } else if (apiFormat !== "anthropic") {
4867
- const delta = _optionalChain([json, 'access', _231 => _231.choices, 'optionalAccess', _232 => _232[0], 'optionalAccess', _233 => _233.delta]);
4868
- if (_optionalChain([delta, 'optionalAccess', _234 => _234.tool_calls]) && pendingOpenAIToolCalls) {
4645
+ const delta = _optionalChain([json, 'access', _224 => _224.choices, 'optionalAccess', _225 => _225[0], 'optionalAccess', _226 => _226.delta]);
4646
+ if (_optionalChain([delta, 'optionalAccess', _227 => _227.tool_calls]) && pendingOpenAIToolCalls) {
4869
4647
  for (const tc of delta.tool_calls) {
4870
4648
  const index = _nullishCoalesce(tc.index, () => ( 0));
4871
4649
  let pending = pendingOpenAIToolCalls.get(index);
@@ -4874,8 +4652,8 @@ function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pend
4874
4652
  pendingOpenAIToolCalls.set(index, pending);
4875
4653
  }
4876
4654
  if (tc.id) pending.id = tc.id;
4877
- if (_optionalChain([tc, 'access', _235 => _235.function, 'optionalAccess', _236 => _236.name])) pending.name += tc.function.name;
4878
- if (_optionalChain([tc, 'access', _237 => _237.function, 'optionalAccess', _238 => _238.arguments])) pending.arguments += tc.function.arguments;
4655
+ if (_optionalChain([tc, 'access', _228 => _228.function, 'optionalAccess', _229 => _229.name])) pending.name += tc.function.name;
4656
+ if (_optionalChain([tc, 'access', _230 => _230.function, 'optionalAccess', _231 => _231.arguments])) pending.arguments += tc.function.arguments;
4879
4657
  }
4880
4658
  }
4881
4659
  }
@@ -4890,7 +4668,7 @@ function finalizeOpenAIToolCalls(pendingOpenAIToolCalls, toolCalls, callbacks, l
4890
4668
  args: JSON.parse(pending.arguments || "{}")
4891
4669
  };
4892
4670
  toolCalls.push(toolCall);
4893
- _optionalChain([callbacks, 'access', _239 => _239.onToolCall, 'optionalCall', _240 => _240(toolCall)]);
4671
+ _optionalChain([callbacks, 'access', _232 => _232.onToolCall, 'optionalCall', _233 => _233(toolCall)]);
4894
4672
  logger.info("Tool called (OpenAI)", { toolName: toolCall.name, args: toolCall.args });
4895
4673
  } catch (e) {
4896
4674
  logger.error("Failed to parse OpenAI tool call arguments", e instanceof Error ? e : void 0, {
@@ -4904,38 +4682,38 @@ function finalizeOpenAIToolCalls(pendingOpenAIToolCalls, toolCalls, callbacks, l
4904
4682
  function parseStreamChunk(rawJson, apiFormat, callbacks, logger) {
4905
4683
  const json = rawJson;
4906
4684
  if (apiFormat === "google") {
4907
- const candidate = _optionalChain([json, 'access', _241 => _241.candidates, 'optionalAccess', _242 => _242[0]]);
4685
+ const candidate = _optionalChain([json, 'access', _234 => _234.candidates, 'optionalAccess', _235 => _235[0]]);
4908
4686
  if (!candidate) {
4909
4687
  logger.warn("No candidate found in Gemini response");
4910
4688
  return;
4911
4689
  }
4912
- const parts = _optionalChain([candidate, 'access', _243 => _243.content, 'optionalAccess', _244 => _244.parts]) || [];
4690
+ const parts = _optionalChain([candidate, 'access', _236 => _236.content, 'optionalAccess', _237 => _237.parts]) || [];
4913
4691
  for (const part of parts) {
4914
4692
  if (part.thought === true && part.text) {
4915
- _optionalChain([callbacks, 'access', _245 => _245.onReasoning, 'optionalCall', _246 => _246(part.text)]);
4693
+ _optionalChain([callbacks, 'access', _238 => _238.onReasoning, 'optionalCall', _239 => _239(part.text)]);
4916
4694
  continue;
4917
4695
  } else if (part.thoughtSignature && !part.thought) {
4918
4696
  logger.debug("Gemini returned thoughtSignature without thought content");
4919
4697
  }
4920
4698
  if (part.text) {
4921
- _optionalChain([callbacks, 'access', _247 => _247.onDelta, 'optionalCall', _248 => _248(part.text)]);
4699
+ _optionalChain([callbacks, 'access', _240 => _240.onDelta, 'optionalCall', _241 => _241(part.text)]);
4922
4700
  }
4923
4701
  }
4924
4702
  } else if (apiFormat === "anthropic") {
4925
4703
  const delta = json.delta;
4926
- if (_optionalChain([delta, 'optionalAccess', _249 => _249.text])) {
4927
- _optionalChain([callbacks, 'access', _250 => _250.onDelta, 'optionalCall', _251 => _251(delta.text)]);
4704
+ if (_optionalChain([delta, 'optionalAccess', _242 => _242.text])) {
4705
+ _optionalChain([callbacks, 'access', _243 => _243.onDelta, 'optionalCall', _244 => _244(delta.text)]);
4928
4706
  }
4929
4707
  } else {
4930
- const delta = _optionalChain([json, 'access', _252 => _252.choices, 'optionalAccess', _253 => _253[0], 'optionalAccess', _254 => _254.delta]);
4931
- if (_optionalChain([delta, 'optionalAccess', _255 => _255.content])) {
4932
- _optionalChain([callbacks, 'access', _256 => _256.onDelta, 'optionalCall', _257 => _257(delta.content)]);
4708
+ const delta = _optionalChain([json, 'access', _245 => _245.choices, 'optionalAccess', _246 => _246[0], 'optionalAccess', _247 => _247.delta]);
4709
+ if (_optionalChain([delta, 'optionalAccess', _248 => _248.content])) {
4710
+ _optionalChain([callbacks, 'access', _249 => _249.onDelta, 'optionalCall', _250 => _250(delta.content)]);
4933
4711
  }
4934
- if (_optionalChain([delta, 'optionalAccess', _258 => _258.thinking, 'optionalAccess', _259 => _259.content])) {
4935
- _optionalChain([callbacks, 'access', _260 => _260.onReasoning, 'optionalCall', _261 => _261(delta.thinking.content)]);
4712
+ if (_optionalChain([delta, 'optionalAccess', _251 => _251.thinking, 'optionalAccess', _252 => _252.content])) {
4713
+ _optionalChain([callbacks, 'access', _253 => _253.onReasoning, 'optionalCall', _254 => _254(delta.thinking.content)]);
4936
4714
  }
4937
- if (_optionalChain([delta, 'optionalAccess', _262 => _262.reasoning_content])) {
4938
- _optionalChain([callbacks, 'access', _263 => _263.onReasoning, 'optionalCall', _264 => _264(delta.reasoning_content)]);
4715
+ if (_optionalChain([delta, 'optionalAccess', _255 => _255.reasoning_content])) {
4716
+ _optionalChain([callbacks, 'access', _256 => _256.onReasoning, 'optionalCall', _257 => _257(delta.reasoning_content)]);
4939
4717
  }
4940
4718
  }
4941
4719
  }
@@ -4948,7 +4726,7 @@ function buildIterationBlocks(iteration, content, reasoning, blocks, callbacks)
4948
4726
  content: reasoning
4949
4727
  };
4950
4728
  blocks.push(thinkingBlock);
4951
- _optionalChain([callbacks, 'access', _265 => _265.onBlock, 'optionalCall', _266 => _266(thinkingBlock)]);
4729
+ _optionalChain([callbacks, 'access', _258 => _258.onBlock, 'optionalCall', _259 => _259(thinkingBlock)]);
4952
4730
  }
4953
4731
  if (content && content.trim()) {
4954
4732
  const textBlock = {
@@ -4957,7 +4735,7 @@ function buildIterationBlocks(iteration, content, reasoning, blocks, callbacks)
4957
4735
  content
4958
4736
  };
4959
4737
  blocks.push(textBlock);
4960
- _optionalChain([callbacks, 'access', _267 => _267.onBlock, 'optionalCall', _268 => _268(textBlock)]);
4738
+ _optionalChain([callbacks, 'access', _260 => _260.onBlock, 'optionalCall', _261 => _261(textBlock)]);
4961
4739
  }
4962
4740
  }
4963
4741
  async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbacks, logger, builtinExecutor) {
@@ -4972,7 +4750,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
4972
4750
  status: "running"
4973
4751
  };
4974
4752
  blocks.push(toolUseBlock);
4975
- _optionalChain([callbacks, 'access', _269 => _269.onBlock, 'optionalCall', _270 => _270(toolUseBlock)]);
4753
+ _optionalChain([callbacks, 'access', _262 => _262.onBlock, 'optionalCall', _263 => _263(toolUseBlock)]);
4976
4754
  try {
4977
4755
  logger.info("Executing tool", { toolName: toolCall.name });
4978
4756
  const mcpTool = mcpTools.find((t) => t.id === toolCall.name);
@@ -4995,8 +4773,8 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
4995
4773
  result = { isError: true, content: [{ type: "text", text: "MCP service not available" }] };
4996
4774
  }
4997
4775
  logger.info("Tool result received", { result });
4998
- _optionalChain([callbacks, 'access', _271 => _271.onToolResult, 'optionalCall', _272 => _272(toolCall.id, result)]);
4999
- const resultText = _optionalChain([result, 'access', _273 => _273.content, 'optionalAccess', _274 => _274[0], 'optionalAccess', _275 => _275.text]) || JSON.stringify(result);
4776
+ _optionalChain([callbacks, 'access', _264 => _264.onToolResult, 'optionalCall', _265 => _265(toolCall.id, result)]);
4777
+ const resultText = _optionalChain([result, 'access', _266 => _266.content, 'optionalAccess', _267 => _267[0], 'optionalAccess', _268 => _268.text]) || JSON.stringify(result);
5000
4778
  const toolResultBlock = {
5001
4779
  id: `${toolCall.id}_result`,
5002
4780
  type: "tool_result",
@@ -5006,11 +4784,11 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
5006
4784
  isError: result.isError
5007
4785
  };
5008
4786
  blocks.push(toolResultBlock);
5009
- _optionalChain([callbacks, 'access', _276 => _276.onBlock, 'optionalCall', _277 => _277(toolResultBlock)]);
4787
+ _optionalChain([callbacks, 'access', _269 => _269.onBlock, 'optionalCall', _270 => _270(toolResultBlock)]);
5010
4788
  const toolUseBlockRef = blocks.find((b) => b.id === `${toolCall.id}_use`);
5011
4789
  if (toolUseBlockRef && toolUseBlockRef.type === "tool_use") {
5012
4790
  toolUseBlockRef.status = result.isError ? "error" : "completed";
5013
- _optionalChain([callbacks, 'access', _278 => _278.onBlock, 'optionalCall', _279 => _279({ ...toolUseBlockRef })]);
4791
+ _optionalChain([callbacks, 'access', _271 => _271.onBlock, 'optionalCall', _272 => _272({ ...toolUseBlockRef })]);
5014
4792
  }
5015
4793
  toolResults.push({ toolCall, result });
5016
4794
  } catch (error) {
@@ -5020,7 +4798,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
5020
4798
  isError: true,
5021
4799
  content: [{ type: "text", text: `Error: ${errorMessage}` }]
5022
4800
  };
5023
- _optionalChain([callbacks, 'access', _280 => _280.onToolResult, 'optionalCall', _281 => _281(toolCall.id, errorResult)]);
4801
+ _optionalChain([callbacks, 'access', _273 => _273.onToolResult, 'optionalCall', _274 => _274(toolCall.id, errorResult)]);
5024
4802
  const errorToolResultBlock = {
5025
4803
  id: `${toolCall.id}_result`,
5026
4804
  type: "tool_result",
@@ -5030,11 +4808,11 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
5030
4808
  isError: true
5031
4809
  };
5032
4810
  blocks.push(errorToolResultBlock);
5033
- _optionalChain([callbacks, 'access', _282 => _282.onBlock, 'optionalCall', _283 => _283(errorToolResultBlock)]);
4811
+ _optionalChain([callbacks, 'access', _275 => _275.onBlock, 'optionalCall', _276 => _276(errorToolResultBlock)]);
5034
4812
  const errorToolUseBlockRef = blocks.find((b) => b.id === `${toolCall.id}_use`);
5035
4813
  if (errorToolUseBlockRef && errorToolUseBlockRef.type === "tool_use") {
5036
4814
  errorToolUseBlockRef.status = "error";
5037
- _optionalChain([callbacks, 'access', _284 => _284.onBlock, 'optionalCall', _285 => _285({ ...errorToolUseBlockRef })]);
4815
+ _optionalChain([callbacks, 'access', _277 => _277.onBlock, 'optionalCall', _278 => _278({ ...errorToolUseBlockRef })]);
5038
4816
  }
5039
4817
  toolResults.push({ toolCall, result: errorResult });
5040
4818
  }
@@ -5044,7 +4822,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
5044
4822
  function mapToolArguments(args, mcpTool, logger) {
5045
4823
  const mappedArgs = { ...args };
5046
4824
  const toolSchema = mcpTool.inputSchema;
5047
- if (_optionalChain([toolSchema, 'optionalAccess', _286 => _286.properties])) {
4825
+ if (_optionalChain([toolSchema, 'optionalAccess', _279 => _279.properties])) {
5048
4826
  const expectedParams = Object.keys(toolSchema.properties);
5049
4827
  const paramMappings = {
5050
4828
  "search_query": ["query", "q", "searchQuery", "search"],
@@ -5078,25 +4856,25 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
5078
4856
  options.providerId,
5079
4857
  options.model
5080
4858
  );
5081
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _287 => _287.actualProviderId]) || options.providerId;
5082
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _288 => _288.actualModelId]) || options.model;
4859
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _280 => _280.actualProviderId]) || options.providerId;
4860
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _281 => _281.actualModelId]) || options.model;
5083
4861
  const provider = await getProvider(actualProviderId);
5084
4862
  if (!provider) {
5085
- _optionalChain([callbacks, 'access', _289 => _289.onError, 'optionalCall', _290 => _290(`Provider not found: ${actualProviderId}`)]);
4863
+ _optionalChain([callbacks, 'access', _282 => _282.onError, 'optionalCall', _283 => _283(`Provider not found: ${actualProviderId}`)]);
5086
4864
  return;
5087
4865
  }
5088
4866
  if (!provider.enabled) {
5089
- _optionalChain([callbacks, 'access', _291 => _291.onError, 'optionalCall', _292 => _292(`Provider is disabled: ${provider.name}`)]);
4867
+ _optionalChain([callbacks, 'access', _284 => _284.onError, 'optionalCall', _285 => _285(`Provider is disabled: ${provider.name}`)]);
5090
4868
  return;
5091
4869
  }
5092
4870
  const { apiKey: effectiveKey } = _chunkA2YMUCBTcjs.resolveProviderEndpoint.call(void 0, provider);
5093
4871
  const apiKey = resolveApiKey2(effectiveKey);
5094
4872
  if (!apiKey) {
5095
- _optionalChain([callbacks, 'access', _293 => _293.onError, 'optionalCall', _294 => _294("API key not configured")]);
4873
+ _optionalChain([callbacks, 'access', _286 => _286.onError, 'optionalCall', _287 => _287("API key not configured")]);
5096
4874
  return;
5097
4875
  }
5098
4876
  const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
5099
- _optionalChain([callbacks, 'access', _295 => _295.onStart, 'optionalCall', _296 => _296(messageId)]);
4877
+ _optionalChain([callbacks, 'access', _288 => _288.onStart, 'optionalCall', _289 => _289(messageId)]);
5100
4878
  const globalParams = await llmConfig.getGlobalModelParameters();
5101
4879
  const MAX_ITERATIONS = _nullishCoalesce(globalParams.toolMaxTurns, () => ( 100));
5102
4880
  let iteration = 0;
@@ -5143,12 +4921,12 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
5143
4921
  });
5144
4922
  if (!response.ok) {
5145
4923
  const errorText = await response.text();
5146
- _optionalChain([callbacks, 'access', _297 => _297.onError, 'optionalCall', _298 => _298(`API error (${response.status}): ${errorText}`)]);
4924
+ _optionalChain([callbacks, 'access', _290 => _290.onError, 'optionalCall', _291 => _291(`API error (${response.status}): ${errorText}`)]);
5147
4925
  return;
5148
4926
  }
5149
- const reader = _optionalChain([response, 'access', _299 => _299.body, 'optionalAccess', _300 => _300.getReader, 'call', _301 => _301()]);
4927
+ const reader = _optionalChain([response, 'access', _292 => _292.body, 'optionalAccess', _293 => _293.getReader, 'call', _294 => _294()]);
5150
4928
  if (!reader) {
5151
- _optionalChain([callbacks, 'access', _302 => _302.onError, 'optionalCall', _303 => _303("No response body")]);
4929
+ _optionalChain([callbacks, 'access', _295 => _295.onError, 'optionalCall', _296 => _296("No response body")]);
5152
4930
  return;
5153
4931
  }
5154
4932
  const decoder = new TextDecoder();
@@ -5181,7 +4959,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
5181
4959
  logger.debug("Parsed JSON", { json });
5182
4960
  if (json.error) {
5183
4961
  logger.error("API Error", void 0, { error: json.error });
5184
- _optionalChain([callbacks, 'access', _304 => _304.onError, 'optionalCall', _305 => _305(`API Error: ${json.error.message || JSON.stringify(json.error)}`)]);
4962
+ _optionalChain([callbacks, 'access', _297 => _297.onError, 'optionalCall', _298 => _298(`API Error: ${json.error.message || JSON.stringify(json.error)}`)]);
5185
4963
  return;
5186
4964
  }
5187
4965
  parseStreamChunk(json, apiFormat, callbacks, logger);
@@ -5214,7 +4992,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
5214
4992
  toolCallsLength: toolCalls.length,
5215
4993
  executableToolCallsLength: executableToolCalls.length,
5216
4994
  hasMcpTools: !!options.mcpTools,
5217
- mcpToolsLength: _optionalChain([options, 'access', _306 => _306.mcpTools, 'optionalAccess', _307 => _307.length]),
4995
+ mcpToolsLength: _optionalChain([options, 'access', _299 => _299.mcpTools, 'optionalAccess', _300 => _300.length]),
5218
4996
  hasMcpService: !!mcpService
5219
4997
  });
5220
4998
  if (executableToolCalls.length > 0 && options.mcpTools && (mcpService || builtinExecutor)) {
@@ -5235,7 +5013,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
5235
5013
  builtinExecutor
5236
5014
  );
5237
5015
  const toolResultsText = toolResults.map(({ toolCall, result }) => {
5238
- const resultText = typeof result === "string" ? result : _optionalChain([result, 'access', _308 => _308.content, 'optionalAccess', _309 => _309[0], 'optionalAccess', _310 => _310.text]) || JSON.stringify(result);
5016
+ const resultText = typeof result === "string" ? result : _optionalChain([result, 'access', _301 => _301.content, 'optionalAccess', _302 => _302[0], 'optionalAccess', _303 => _303.text]) || JSON.stringify(result);
5239
5017
  return `Tool ${toolCall.name} result:
5240
5018
  ${resultText}`;
5241
5019
  }).join("\n\n");
@@ -5253,12 +5031,12 @@ ${resultText}`;
5253
5031
  }
5254
5032
  } catch (streamError) {
5255
5033
  logger.error("Stream processing error", streamError instanceof Error ? streamError : void 0);
5256
- _optionalChain([callbacks, 'access', _311 => _311.onError, 'optionalCall', _312 => _312(`Stream error: ${streamError instanceof Error ? streamError.message : "Unknown error"}`)]);
5034
+ _optionalChain([callbacks, 'access', _304 => _304.onError, 'optionalCall', _305 => _305(`Stream error: ${streamError instanceof Error ? streamError.message : "Unknown error"}`)]);
5257
5035
  return;
5258
5036
  }
5259
5037
  }
5260
5038
  logger.info("Sending final callback", { blocksCount: blocks.length });
5261
- _optionalChain([callbacks, 'access', _313 => _313.onDone, 'optionalCall', _314 => _314({
5039
+ _optionalChain([callbacks, 'access', _306 => _306.onDone, 'optionalCall', _307 => _307({
5262
5040
  id: messageId,
5263
5041
  role: "assistant",
5264
5042
  content: finalContent,
@@ -5269,7 +5047,7 @@ ${resultText}`;
5269
5047
  } catch (error) {
5270
5048
  logger.error("Error in streamWithTools", error instanceof Error ? error : void 0);
5271
5049
  const message = error instanceof Error ? error.message : "Unknown error";
5272
- _optionalChain([callbacks, 'access', _315 => _315.onError, 'optionalCall', _316 => _316(message)]);
5050
+ _optionalChain([callbacks, 'access', _308 => _308.onError, 'optionalCall', _309 => _309(message)]);
5273
5051
  }
5274
5052
  }
5275
5053
 
@@ -5308,8 +5086,8 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
5308
5086
  options.providerId,
5309
5087
  options.model
5310
5088
  );
5311
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _317 => _317.actualProviderId]) || options.providerId;
5312
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _318 => _318.actualModelId]) || options.model;
5089
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _310 => _310.actualProviderId]) || options.providerId;
5090
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _311 => _311.actualModelId]) || options.model;
5313
5091
  const provider = await getProvider(actualProviderId);
5314
5092
  if (!provider) {
5315
5093
  return { success: false, error: `Provider not found: ${actualProviderId}` };
@@ -5347,7 +5125,7 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
5347
5125
  models: provider.models || []
5348
5126
  };
5349
5127
  const executor = getSharedExecutor2();
5350
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
5128
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
5351
5129
  executor,
5352
5130
  request: unifiedRequest,
5353
5131
  provider: transformerProvider,
@@ -5390,18 +5168,18 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
5390
5168
  { endpointTransformer: void 0 }
5391
5169
  );
5392
5170
  const data = await transformedResponse.json();
5393
- const choice = _optionalChain([data, 'access', _319 => _319.choices, 'optionalAccess', _320 => _320[0]]);
5171
+ const choice = _optionalChain([data, 'access', _312 => _312.choices, 'optionalAccess', _313 => _313[0]]);
5394
5172
  if (!choice) {
5395
5173
  return { success: false, error: "No choices in response" };
5396
5174
  }
5397
- const rawToolCalls = _optionalChain([choice, 'access', _321 => _321.message, 'optionalAccess', _322 => _322.tool_calls]);
5398
- const toolCalls = _optionalChain([rawToolCalls, 'optionalAccess', _323 => _323.map, 'call', _324 => _324((tc) => ({
5175
+ const rawToolCalls = _optionalChain([choice, 'access', _314 => _314.message, 'optionalAccess', _315 => _315.tool_calls]);
5176
+ const toolCalls = _optionalChain([rawToolCalls, 'optionalAccess', _316 => _316.map, 'call', _317 => _317((tc) => ({
5399
5177
  id: tc.id,
5400
5178
  name: tc.function.name,
5401
5179
  args: typeof tc.function.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function.arguments
5402
5180
  }))]);
5403
5181
  const tapped = readUsageFromOpenAIResponse(data.usage);
5404
- if (_optionalChain([recording, 'optionalAccess', _325 => _325.recorder]) && tapped) {
5182
+ if (_optionalChain([recording, 'optionalAccess', _318 => _318.recorder]) && tapped) {
5405
5183
  recording.recorder.record({
5406
5184
  messageId: _nullishCoalesce(options.messageId, () => ( null)),
5407
5185
  parentMessageId: _nullishCoalesce(options.parentMessageId, () => ( null)),
@@ -5419,9 +5197,9 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
5419
5197
  message: {
5420
5198
  id: `msg_${Date.now()}`,
5421
5199
  role: "assistant",
5422
- content: _optionalChain([choice, 'access', _326 => _326.message, 'optionalAccess', _327 => _327.content]) || "",
5200
+ content: _optionalChain([choice, 'access', _319 => _319.message, 'optionalAccess', _320 => _320.content]) || "",
5423
5201
  timestamp: Date.now(),
5424
- thinking: data.reasoning_content || _optionalChain([choice, 'access', _328 => _328.message, 'optionalAccess', _329 => _329.thinking, 'optionalAccess', _330 => _330.content]) ? { content: data.reasoning_content || _optionalChain([choice, 'access', _331 => _331.message, 'optionalAccess', _332 => _332.thinking, 'optionalAccess', _333 => _333.content]) || "", signature: _optionalChain([choice, 'access', _334 => _334.message, 'optionalAccess', _335 => _335.thinking, 'optionalAccess', _336 => _336.signature]) } : void 0,
5202
+ thinking: data.reasoning_content || _optionalChain([choice, 'access', _321 => _321.message, 'optionalAccess', _322 => _322.thinking, 'optionalAccess', _323 => _323.content]) ? { content: data.reasoning_content || _optionalChain([choice, 'access', _324 => _324.message, 'optionalAccess', _325 => _325.thinking, 'optionalAccess', _326 => _326.content]) || "", signature: _optionalChain([choice, 'access', _327 => _327.message, 'optionalAccess', _328 => _328.thinking, 'optionalAccess', _329 => _329.signature]) } : void 0,
5425
5203
  toolCalls
5426
5204
  },
5427
5205
  usage: data.usage ? {
@@ -5442,21 +5220,21 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5442
5220
  options.providerId,
5443
5221
  options.model
5444
5222
  );
5445
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _337 => _337.actualProviderId]) || options.providerId;
5446
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _338 => _338.actualModelId]) || options.model;
5223
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _330 => _330.actualProviderId]) || options.providerId;
5224
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _331 => _331.actualModelId]) || options.model;
5447
5225
  const provider = await getProvider(actualProviderId);
5448
5226
  if (!provider) {
5449
- _optionalChain([callbacks, 'access', _339 => _339.onError, 'optionalCall', _340 => _340(`Provider not found: ${actualProviderId}`)]);
5227
+ _optionalChain([callbacks, 'access', _332 => _332.onError, 'optionalCall', _333 => _333(`Provider not found: ${actualProviderId}`)]);
5450
5228
  return;
5451
5229
  }
5452
5230
  if (!provider.enabled) {
5453
- _optionalChain([callbacks, 'access', _341 => _341.onError, 'optionalCall', _342 => _342(`Provider is disabled: ${provider.name}`)]);
5231
+ _optionalChain([callbacks, 'access', _334 => _334.onError, 'optionalCall', _335 => _335(`Provider is disabled: ${provider.name}`)]);
5454
5232
  return;
5455
5233
  }
5456
5234
  const { apiKey: effectiveKey } = _chunkA2YMUCBTcjs.resolveProviderEndpoint.call(void 0, provider);
5457
5235
  const apiKey = resolveApiKey2(effectiveKey);
5458
5236
  if (!apiKey) {
5459
- _optionalChain([callbacks, 'access', _343 => _343.onError, 'optionalCall', _344 => _344("API key not configured")]);
5237
+ _optionalChain([callbacks, 'access', _336 => _336.onError, 'optionalCall', _337 => _337("API key not configured")]);
5460
5238
  return;
5461
5239
  }
5462
5240
  const { chain, hasTransformers } = await resolveChainWithMain(
@@ -5468,7 +5246,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5468
5246
  return completeStreamFallback(options, callbacks);
5469
5247
  }
5470
5248
  const messageId = `msg_${Date.now()}`;
5471
- _optionalChain([callbacks, 'access', _345 => _345.onStart, 'optionalCall', _346 => _346(messageId)]);
5249
+ _optionalChain([callbacks, 'access', _338 => _338.onStart, 'optionalCall', _339 => _339(messageId)]);
5472
5250
  const unifiedRequest = {
5473
5251
  model: actualModel,
5474
5252
  messages: options.messages.map((m) => ({
@@ -5486,7 +5264,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5486
5264
  models: provider.models || []
5487
5265
  };
5488
5266
  const executor = getSharedExecutor2();
5489
- const { response } = await _chunkKUU2RNG6cjs.executeProviderCall.call(void 0, {
5267
+ const { response } = await _chunkHYN75H6Gcjs.executeProviderCall.call(void 0, {
5490
5268
  executor,
5491
5269
  request: unifiedRequest,
5492
5270
  provider: transformerProvider,
@@ -5516,7 +5294,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5516
5294
  });
5517
5295
  if (!response.ok) {
5518
5296
  const errorText = await response.text();
5519
- _optionalChain([callbacks, 'access', _347 => _347.onError, 'optionalCall', _348 => _348(`API error (${response.status}): ${errorText}`)]);
5297
+ _optionalChain([callbacks, 'access', _340 => _340.onError, 'optionalCall', _341 => _341(`API error (${response.status}): ${errorText}`)]);
5520
5298
  return;
5521
5299
  }
5522
5300
  const transformedResponse = await executor.executeResponseChain(
@@ -5526,9 +5304,9 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5526
5304
  chain,
5527
5305
  { endpointTransformer: void 0 }
5528
5306
  );
5529
- const reader = _optionalChain([transformedResponse, 'access', _349 => _349.body, 'optionalAccess', _350 => _350.getReader, 'call', _351 => _351()]);
5307
+ const reader = _optionalChain([transformedResponse, 'access', _342 => _342.body, 'optionalAccess', _343 => _343.getReader, 'call', _344 => _344()]);
5530
5308
  if (!reader) {
5531
- _optionalChain([callbacks, 'access', _352 => _352.onError, 'optionalCall', _353 => _353("No response body")]);
5309
+ _optionalChain([callbacks, 'access', _345 => _345.onError, 'optionalCall', _346 => _346("No response body")]);
5532
5310
  return;
5533
5311
  }
5534
5312
  const decoder = new TextDecoder();
@@ -5546,22 +5324,22 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5546
5324
  if (data === "[DONE]") continue;
5547
5325
  try {
5548
5326
  const json = JSON.parse(data);
5549
- const delta = _optionalChain([json, 'access', _354 => _354.choices, 'optionalAccess', _355 => _355[0], 'optionalAccess', _356 => _356.delta]);
5550
- if (_optionalChain([delta, 'optionalAccess', _357 => _357.content])) {
5327
+ const delta = _optionalChain([json, 'access', _347 => _347.choices, 'optionalAccess', _348 => _348[0], 'optionalAccess', _349 => _349.delta]);
5328
+ if (_optionalChain([delta, 'optionalAccess', _350 => _350.content])) {
5551
5329
  content += delta.content;
5552
- _optionalChain([callbacks, 'access', _358 => _358.onDelta, 'optionalCall', _359 => _359(delta.content)]);
5330
+ _optionalChain([callbacks, 'access', _351 => _351.onDelta, 'optionalCall', _352 => _352(delta.content)]);
5553
5331
  }
5554
- if (_optionalChain([delta, 'optionalAccess', _360 => _360.thinking, 'optionalAccess', _361 => _361.content])) {
5332
+ if (_optionalChain([delta, 'optionalAccess', _353 => _353.thinking, 'optionalAccess', _354 => _354.content])) {
5555
5333
  reasoning += delta.thinking.content;
5556
- _optionalChain([callbacks, 'access', _362 => _362.onReasoning, 'optionalCall', _363 => _363(delta.thinking.content)]);
5334
+ _optionalChain([callbacks, 'access', _355 => _355.onReasoning, 'optionalCall', _356 => _356(delta.thinking.content)]);
5557
5335
  }
5558
- if (_optionalChain([delta, 'optionalAccess', _364 => _364.reasoning_content])) {
5336
+ if (_optionalChain([delta, 'optionalAccess', _357 => _357.reasoning_content])) {
5559
5337
  reasoning += delta.reasoning_content;
5560
- _optionalChain([callbacks, 'access', _365 => _365.onReasoning, 'optionalCall', _366 => _366(delta.reasoning_content)]);
5338
+ _optionalChain([callbacks, 'access', _358 => _358.onReasoning, 'optionalCall', _359 => _359(delta.reasoning_content)]);
5561
5339
  }
5562
5340
  if (json.usage) {
5563
5341
  const tapped = readUsageFromOpenAIResponse(json.usage);
5564
- if (_optionalChain([recording, 'optionalAccess', _367 => _367.recorder]) && tapped) {
5342
+ if (_optionalChain([recording, 'optionalAccess', _360 => _360.recorder]) && tapped) {
5565
5343
  recording.recorder.record({
5566
5344
  messageId: _nullishCoalesce(options.messageId, () => ( null)),
5567
5345
  parentMessageId: _nullishCoalesce(options.parentMessageId, () => ( null)),
@@ -5574,7 +5352,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5574
5352
  rawUsage: json.usage
5575
5353
  });
5576
5354
  }
5577
- _optionalChain([callbacks, 'access', _368 => _368.onDone, 'optionalCall', _369 => _369(
5355
+ _optionalChain([callbacks, 'access', _361 => _361.onDone, 'optionalCall', _362 => _362(
5578
5356
  {
5579
5357
  id: messageId,
5580
5358
  role: "assistant",
@@ -5595,7 +5373,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5595
5373
  }
5596
5374
  }
5597
5375
  }
5598
- _optionalChain([callbacks, 'access', _370 => _370.onDone, 'optionalCall', _371 => _371({
5376
+ _optionalChain([callbacks, 'access', _363 => _363.onDone, 'optionalCall', _364 => _364({
5599
5377
  id: messageId,
5600
5378
  role: "assistant",
5601
5379
  content,
@@ -5607,7 +5385,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
5607
5385
  }
5608
5386
  } catch (error) {
5609
5387
  const message = error instanceof Error ? error.message : "Unknown error";
5610
- _optionalChain([callbacks, 'access', _372 => _372.onError, 'optionalCall', _373 => _373(message)]);
5388
+ _optionalChain([callbacks, 'access', _365 => _365.onError, 'optionalCall', _366 => _366(message)]);
5611
5389
  }
5612
5390
  }
5613
5391
 
@@ -5646,8 +5424,8 @@ var CompletionService = (_class13 = class {
5646
5424
  * emission is unconditional in production. Optional — when unset (unit-test
5647
5425
  * constructors), the emit calls no-op, identical to `usageRecorder`.
5648
5426
  */
5649
- setUsageEventSink(sink2) {
5650
- this.usageEventSink = sink2;
5427
+ setUsageEventSink(sink) {
5428
+ this.usageEventSink = sink;
5651
5429
  }
5652
5430
  /**
5653
5431
  * Set the vision-fallback provider used by `applyVisionFallback` to describe
@@ -5674,8 +5452,8 @@ var CompletionService = (_class13 = class {
5674
5452
  options.providerId,
5675
5453
  options.model
5676
5454
  );
5677
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _374 => _374.actualProviderId]) || options.providerId;
5678
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _375 => _375.actualModelId]) || options.model;
5455
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _367 => _367.actualProviderId]) || options.providerId;
5456
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _368 => _368.actualModelId]) || options.model;
5679
5457
  const provider = await this.getProvider(actualProviderId);
5680
5458
  if (!provider) {
5681
5459
  return { success: false, error: `Provider not found: ${actualProviderId}` };
@@ -5708,7 +5486,7 @@ var CompletionService = (_class13 = class {
5708
5486
  this.apiKeyPool.reportSuccess(options.sessionId);
5709
5487
  }
5710
5488
  if (result.success && result.usage && options.sessionId) {
5711
- _optionalChain([this, 'access', _376 => _376.usageEventSink, 'optionalAccess', _377 => _377.emit, 'call', _378 => _378({
5489
+ _optionalChain([this, 'access', _369 => _369.usageEventSink, 'optionalAccess', _370 => _370.emit, 'call', _371 => _371({
5712
5490
  sessionId: options.sessionId,
5713
5491
  modelId: actualModel,
5714
5492
  usage: result.usage,
@@ -5737,8 +5515,8 @@ var CompletionService = (_class13 = class {
5737
5515
  options.model
5738
5516
  );
5739
5517
  this.logger.debug("Resolved routed model", { routedInfo });
5740
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _379 => _379.actualProviderId]) || options.providerId;
5741
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _380 => _380.actualModelId]) || options.model;
5518
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _372 => _372.actualProviderId]) || options.providerId;
5519
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _373 => _373.actualModelId]) || options.model;
5742
5520
  this.logger.debug("Resolved provider and model", { actualProviderId, actualModel });
5743
5521
  const provider = await this.getProvider(actualProviderId);
5744
5522
  this.logger.debug("Retrieved provider", provider ? {
@@ -5750,22 +5528,22 @@ var CompletionService = (_class13 = class {
5750
5528
  enabled: provider.enabled
5751
5529
  } : { error: "Provider not found" });
5752
5530
  if (!provider) {
5753
- _optionalChain([callbacks, 'access', _381 => _381.onError, 'optionalCall', _382 => _382(`Provider not found: ${actualProviderId}`)]);
5531
+ _optionalChain([callbacks, 'access', _374 => _374.onError, 'optionalCall', _375 => _375(`Provider not found: ${actualProviderId}`)]);
5754
5532
  return;
5755
5533
  }
5756
5534
  if (!provider.enabled) {
5757
- _optionalChain([callbacks, 'access', _383 => _383.onError, 'optionalCall', _384 => _384(`Provider is disabled: ${provider.name}`)]);
5535
+ _optionalChain([callbacks, 'access', _376 => _376.onError, 'optionalCall', _377 => _377(`Provider is disabled: ${provider.name}`)]);
5758
5536
  return;
5759
5537
  }
5760
5538
  const apiKey = await this.resolveApiKeyForRequest(provider, actualProviderId, options.sessionId);
5761
5539
  if (!apiKey) {
5762
- _optionalChain([callbacks, 'access', _385 => _385.onError, 'optionalCall', _386 => _386("API key not configured")]);
5540
+ _optionalChain([callbacks, 'access', _378 => _378.onError, 'optionalCall', _379 => _379("API key not configured")]);
5763
5541
  return;
5764
5542
  }
5765
5543
  const apiFormat = _chunkA2YMUCBTcjs.resolveApiFormat.call(void 0, provider);
5766
5544
  this.logger.info("Using API format for stream", { apiFormat });
5767
5545
  const messageId = `msg_${Date.now()}`;
5768
- _optionalChain([callbacks, 'access', _387 => _387.onStart, 'optionalCall', _388 => _388(messageId)]);
5546
+ _optionalChain([callbacks, 'access', _380 => _380.onStart, 'optionalCall', _381 => _381(messageId)]);
5769
5547
  const resolvedOptions = { ...options, model: actualModel };
5770
5548
  if (options.sessionId) {
5771
5549
  const sid = options.sessionId;
@@ -5774,14 +5552,14 @@ var CompletionService = (_class13 = class {
5774
5552
  ...callbacks,
5775
5553
  onDone: (message, usage, metrics) => {
5776
5554
  if (usage) {
5777
- _optionalChain([this, 'access', _389 => _389.usageEventSink, 'optionalAccess', _390 => _390.emit, 'call', _391 => _391({
5555
+ _optionalChain([this, 'access', _382 => _382.usageEventSink, 'optionalAccess', _383 => _383.emit, 'call', _384 => _384({
5778
5556
  sessionId: sid,
5779
5557
  modelId: actualModel,
5780
5558
  usage,
5781
5559
  engineOrigin: "completion"
5782
5560
  })]);
5783
5561
  }
5784
- _optionalChain([userOnDone, 'optionalCall', _392 => _392(message, usage, metrics)]);
5562
+ _optionalChain([userOnDone, 'optionalCall', _385 => _385(message, usage, metrics)]);
5785
5563
  }
5786
5564
  };
5787
5565
  }
@@ -5797,11 +5575,11 @@ var CompletionService = (_class13 = class {
5797
5575
  retryState.error = { status, message: error };
5798
5576
  return;
5799
5577
  }
5800
- _optionalChain([callbacks, 'access', _393 => _393.onError, 'optionalCall', _394 => _394(error)]);
5578
+ _optionalChain([callbacks, 'access', _386 => _386.onError, 'optionalCall', _387 => _387(error)]);
5801
5579
  },
5802
5580
  onDone: (message, usage, metrics) => {
5803
5581
  this.apiKeyPool.reportSuccess(options.sessionId);
5804
- _optionalChain([callbacks, 'access', _395 => _395.onDone, 'optionalCall', _396 => _396(message, usage, metrics)]);
5582
+ _optionalChain([callbacks, 'access', _388 => _388.onDone, 'optionalCall', _389 => _389(message, usage, metrics)]);
5805
5583
  }
5806
5584
  };
5807
5585
  await this.callStreamHandler(apiFormat, provider, apiKey, resolvedOptions, messageId, interceptCallbacks);
@@ -5822,7 +5600,7 @@ var CompletionService = (_class13 = class {
5822
5600
  // don't fire onStart again
5823
5601
  });
5824
5602
  } else {
5825
- _optionalChain([callbacks, 'access', _397 => _397.onError, 'optionalCall', _398 => _398(retryState.error.message)]);
5603
+ _optionalChain([callbacks, 'access', _390 => _390.onError, 'optionalCall', _391 => _391(retryState.error.message)]);
5826
5604
  }
5827
5605
  }
5828
5606
  } else {
@@ -5835,7 +5613,7 @@ var CompletionService = (_class13 = class {
5835
5613
  } catch (error) {
5836
5614
  const message = error instanceof Error ? error.message : "Unknown error";
5837
5615
  this.logger.error("Stream completion error", error instanceof Error ? error : void 0, { message });
5838
- _optionalChain([callbacks, 'access', _399 => _399.onError, 'optionalCall', _400 => _400(message)]);
5616
+ _optionalChain([callbacks, 'access', _392 => _392.onError, 'optionalCall', _393 => _393(message)]);
5839
5617
  }
5840
5618
  }
5841
5619
  /**
@@ -5875,7 +5653,7 @@ var CompletionService = (_class13 = class {
5875
5653
  return {
5876
5654
  success: true,
5877
5655
  message: "Connection successful",
5878
- response: _optionalChain([result, 'access', _401 => _401.message, 'optionalAccess', _402 => _402.content]) || "",
5656
+ response: _optionalChain([result, 'access', _394 => _394.message, 'optionalAccess', _395 => _395.content]) || "",
5879
5657
  model: modelId,
5880
5658
  durationMs
5881
5659
  };
@@ -5940,7 +5718,7 @@ ${description}`;
5940
5718
  * 3. Legacy single key from provider config
5941
5719
  */
5942
5720
  async resolveApiKeyForRequest(provider, providerId, sessionId) {
5943
- if (_optionalChain([provider, 'access', _403 => _403.codingPlan, 'optionalAccess', _404 => _404.enabled]) && provider.codingPlan.apiKey) {
5721
+ if (_optionalChain([provider, 'access', _396 => _396.codingPlan, 'optionalAccess', _397 => _397.enabled]) && provider.codingPlan.apiKey) {
5944
5722
  return this.resolveApiKey(provider.codingPlan.apiKey);
5945
5723
  }
5946
5724
  if (this.apiKeyPool) {
@@ -6189,8 +5967,4 @@ ${description}`;
6189
5967
 
6190
5968
 
6191
5969
 
6192
-
6193
-
6194
-
6195
-
6196
- exports.CompletionService = CompletionService; exports.register = register; exports.emit = emit; exports.attach = attach; exports.release = release; exports.convertMessageToOpenAI = convertMessageToOpenAI; exports.convertMessageToAnthropic = convertMessageToAnthropic; exports.convertMessageToGemini = convertMessageToGemini; exports.getOpenRouterProviderConfig = getOpenRouterProviderConfig; exports.addOpenRouterProviderToRequest = addOpenRouterProviderToRequest; exports.DEFAULT_ROUTE_IDLE_MS = DEFAULT_ROUTE_IDLE_MS; exports.ProviderProxyRouteMap = ProviderProxyRouteMap; exports.getSharedExecutor = getSharedExecutor; exports.getResponsesEndpointTransformer = getResponsesEndpointTransformer; exports.getAnthropicEndpointTransformer = getAnthropicEndpointTransformer; exports.getGeminiEndpointTransformer = getGeminiEndpointTransformer; exports.readBody = readBody; exports.relayResponse = relayResponse; exports.writeError = writeError; exports.resolvePoolBoundKey = resolvePoolBoundKey; exports.extractRouteToken = extractRouteToken; exports.isLoopbackAddress = isLoopbackAddress; exports.ProviderProxy = ProviderProxy; exports.getProviderProxy = getProviderProxy; exports.__resetProviderProxyForTests = __resetProviderProxyForTests; exports.KeyedMutex = KeyedMutex; exports.OUTBOUND_API_SERVER_CONFIG_KEY = OUTBOUND_API_SERVER_CONFIG_KEY; exports.DEFAULT_USER_MESSAGE_QUEUE = DEFAULT_USER_MESSAGE_QUEUE; exports.DEFAULT_CONCURRENCY_QUEUE = DEFAULT_CONCURRENCY_QUEUE; exports.DEFAULT_ACCOUNT_PROBE = DEFAULT_ACCOUNT_PROBE; exports.normalizeAccountProbe = normalizeAccountProbe; exports.normalizeAudit = normalizeAudit; exports.normalizeBilling = normalizeBilling; exports.DEFAULT_FINGERPRINT = DEFAULT_FINGERPRINT; exports.normalizeFingerprint = normalizeFingerprint; exports.normalizeVoucher = normalizeVoucher; exports.normalizeProxyConfig = normalizeProxyConfig; exports.normalizeProxySegment = normalizeProxySegment; exports.normalizeWebhookDestination = normalizeWebhookDestination; exports.normalizeWebhookSegment = normalizeWebhookSegment; exports.normalizeQueueSegments = normalizeQueueSegments; exports.normalizePrefixTargets = normalizePrefixTargets; exports.defaultServerConfig = defaultServerConfig; exports.normalizeServerConfig = normalizeServerConfig; exports.loadServerConfig = loadServerConfig; exports.saveServerConfig = saveServerConfig; exports.mergeServerConfig = mergeServerConfig; exports.AUDIT_REDACTED = AUDIT_REDACTED; exports.redactAuditText = redactAuditText; exports.beginAuditCapture = beginAuditCapture; exports.beginBillingCapture = beginBillingCapture; exports.computeKeyExpiry = computeKeyExpiry; exports.checkKeyQuota = checkKeyQuota; exports.randomBase62 = randomBase62; exports.hashKey = hashKey; exports.createNamedKey = createNamedKey; exports.verifyKey = verifyKey; exports.verifyPresentedKey = verifyPresentedKey; exports.ConcurrencyQueueFullError = ConcurrencyQueueFullError; exports.ConcurrencyWaitTimeoutError = ConcurrencyWaitTimeoutError; exports.ConcurrencyWaitCancelledError = ConcurrencyWaitCancelledError; exports.isConcurrencyRejection = isConcurrencyRejection; exports.OutboundConcurrencyGate = OutboundConcurrencyGate; exports.OutboundRateLimiter = OutboundRateLimiter; exports.isUserMessageRequest = isUserMessageRequest; exports.SerialQueueTimeoutError = SerialQueueTimeoutError; exports.isSerialQueueTimeout = isSerialQueueTimeout; exports.UserMessageSerialQueue = UserMessageSerialQueue; exports.generateVoucherCode = generateVoucherCode; exports.hashVoucherCode = hashVoucherCode; exports.voucherCodePrefix = voucherCodePrefix; exports.newVoucherId = newVoucherId; exports.computeVoucherGrant = computeVoucherGrant; exports.toVoucherInfo = toVoucherInfo; exports.isRedeemRequest = isRedeemRequest; exports.handleVoucherRedeem = handleVoucherRedeem; exports.DEFAULT_OUTBOUND_PORT = DEFAULT_OUTBOUND_PORT; exports.OutboundApiConfigError = OutboundApiConfigError; exports.OutboundApiServer = OutboundApiServer; exports.formatUrls = formatUrls; exports.startOfLocalDay = startOfLocalDay; exports.startOfLocalWeek = startOfLocalWeek; exports.KeySpendTracker = KeySpendTracker; exports.getOutboundApiServer = getOutboundApiServer; exports.__resetOutboundApiServerForTests = __resetOutboundApiServerForTests;
5970
+ exports.CompletionService = CompletionService; exports.register = register; exports.emit = emit; exports.attach = attach; exports.release = release; exports.convertMessageToOpenAI = convertMessageToOpenAI; exports.convertMessageToAnthropic = convertMessageToAnthropic; exports.convertMessageToGemini = convertMessageToGemini; exports.getOpenRouterProviderConfig = getOpenRouterProviderConfig; exports.addOpenRouterProviderToRequest = addOpenRouterProviderToRequest; exports.DEFAULT_ROUTE_IDLE_MS = DEFAULT_ROUTE_IDLE_MS; exports.ProviderProxyRouteMap = ProviderProxyRouteMap; exports.getSharedExecutor = getSharedExecutor; exports.getResponsesEndpointTransformer = getResponsesEndpointTransformer; exports.getAnthropicEndpointTransformer = getAnthropicEndpointTransformer; exports.getGeminiEndpointTransformer = getGeminiEndpointTransformer; exports.readBody = readBody; exports.relayResponse = relayResponse; exports.writeError = writeError; exports.resolvePoolBoundKey = resolvePoolBoundKey; exports.extractRouteToken = extractRouteToken; exports.isLoopbackAddress = isLoopbackAddress; exports.ProviderProxy = ProviderProxy; exports.getProviderProxy = getProviderProxy; exports.__resetProviderProxyForTests = __resetProviderProxyForTests; exports.KeyedMutex = KeyedMutex; exports.OUTBOUND_API_SERVER_CONFIG_KEY = OUTBOUND_API_SERVER_CONFIG_KEY; exports.DEFAULT_USER_MESSAGE_QUEUE = DEFAULT_USER_MESSAGE_QUEUE; exports.DEFAULT_CONCURRENCY_QUEUE = DEFAULT_CONCURRENCY_QUEUE; exports.DEFAULT_ACCOUNT_PROBE = DEFAULT_ACCOUNT_PROBE; exports.normalizeAccountProbe = normalizeAccountProbe; exports.normalizeAudit = normalizeAudit; exports.normalizeBilling = normalizeBilling; exports.DEFAULT_FINGERPRINT = DEFAULT_FINGERPRINT; exports.normalizeFingerprint = normalizeFingerprint; exports.normalizeVoucher = normalizeVoucher; exports.normalizeProxyConfig = normalizeProxyConfig; exports.normalizeProxySegment = normalizeProxySegment; exports.normalizeWebhookDestination = normalizeWebhookDestination; exports.normalizeWebhookSegment = normalizeWebhookSegment; exports.normalizeQueueSegments = normalizeQueueSegments; exports.normalizePrefixTargets = normalizePrefixTargets; exports.defaultServerConfig = defaultServerConfig; exports.normalizeServerConfig = normalizeServerConfig; exports.loadServerConfig = loadServerConfig; exports.saveServerConfig = saveServerConfig; exports.mergeServerConfig = mergeServerConfig; exports.computeKeyExpiry = computeKeyExpiry; exports.checkKeyQuota = checkKeyQuota; exports.randomBase62 = randomBase62; exports.hashKey = hashKey; exports.createNamedKey = createNamedKey; exports.verifyKey = verifyKey; exports.verifyPresentedKey = verifyPresentedKey; exports.ConcurrencyQueueFullError = ConcurrencyQueueFullError; exports.ConcurrencyWaitTimeoutError = ConcurrencyWaitTimeoutError; exports.ConcurrencyWaitCancelledError = ConcurrencyWaitCancelledError; exports.isConcurrencyRejection = isConcurrencyRejection; exports.OutboundConcurrencyGate = OutboundConcurrencyGate; exports.OutboundRateLimiter = OutboundRateLimiter; exports.isUserMessageRequest = isUserMessageRequest; exports.SerialQueueTimeoutError = SerialQueueTimeoutError; exports.isSerialQueueTimeout = isSerialQueueTimeout; exports.UserMessageSerialQueue = UserMessageSerialQueue; exports.generateVoucherCode = generateVoucherCode; exports.hashVoucherCode = hashVoucherCode; exports.voucherCodePrefix = voucherCodePrefix; exports.newVoucherId = newVoucherId; exports.computeVoucherGrant = computeVoucherGrant; exports.toVoucherInfo = toVoucherInfo; exports.isRedeemRequest = isRedeemRequest; exports.handleVoucherRedeem = handleVoucherRedeem; exports.DEFAULT_OUTBOUND_PORT = DEFAULT_OUTBOUND_PORT; exports.OutboundApiConfigError = OutboundApiConfigError; exports.OutboundApiServer = OutboundApiServer; exports.formatUrls = formatUrls; exports.startOfLocalDay = startOfLocalDay; exports.startOfLocalWeek = startOfLocalWeek; exports.KeySpendTracker = KeySpendTracker; exports.getOutboundApiServer = getOutboundApiServer; exports.__resetOutboundApiServerForTests = __resetOutboundApiServerForTests;