@omnicross/core 0.1.9 → 0.1.10

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 (39) hide show
  1. package/dist/{chunk-EPN67EGP.cjs → chunk-5UK3KLE2.cjs} +9 -1
  2. package/dist/chunk-6D4W22P4.js +150 -0
  3. package/dist/{chunk-UAPBLNN2.js → chunk-AQDON6MB.js} +8 -0
  4. package/dist/{chunk-CQIJCPMF.js → chunk-FEBAQI5A.js} +78 -15
  5. package/dist/{chunk-7C7DET6S.js → chunk-GXEZ2R3E.js} +156 -1
  6. package/dist/chunk-QUSEZNYS.cjs +150 -0
  7. package/dist/{chunk-XELFM7KL.cjs → chunk-TIT74RIL.cjs} +235 -172
  8. package/dist/{chunk-XPIOJQS2.cjs → chunk-UWDW6PN3.cjs} +159 -4
  9. package/dist/completion/CompletionService.cjs +5 -5
  10. package/dist/completion/CompletionService.js +4 -4
  11. package/dist/completion.cjs +5 -5
  12. package/dist/completion.js +4 -4
  13. package/dist/index.cjs +5 -5
  14. package/dist/index.js +4 -4
  15. package/dist/outbound-api/auditCapture.cjs +2 -2
  16. package/dist/outbound-api/auditCapture.d.cts +6 -0
  17. package/dist/outbound-api/auditCapture.d.ts +6 -0
  18. package/dist/outbound-api/auditCapture.js +1 -1
  19. package/dist/outbound-api.cjs +5 -5
  20. package/dist/outbound-api.d.cts +2 -1
  21. package/dist/outbound-api.d.ts +2 -1
  22. package/dist/outbound-api.js +4 -4
  23. package/dist/provider-proxy/ProviderProxy.cjs +5 -5
  24. package/dist/provider-proxy/ProviderProxy.js +4 -4
  25. package/dist/provider-proxy/ingress/providerProxyShared.cjs +5 -5
  26. package/dist/provider-proxy/ingress/providerProxyShared.js +4 -4
  27. package/dist/provider-proxy.cjs +5 -5
  28. package/dist/provider-proxy.js +4 -4
  29. package/dist/usage/usage-recorder.cjs +2 -2
  30. package/dist/usage/usage-recorder.d.cts +12 -2
  31. package/dist/usage/usage-recorder.d.ts +12 -2
  32. package/dist/usage/usage-recorder.js +1 -1
  33. package/dist/usage.cjs +20 -3
  34. package/dist/usage.d.cts +149 -0
  35. package/dist/usage.d.ts +149 -0
  36. package/dist/usage.js +20 -3
  37. package/package.json +2 -2
  38. package/dist/chunk-7VU7V2E4.js +0 -0
  39. package/dist/chunk-EYZYXJTJ.cjs +0 -1
@@ -36,6 +36,8 @@ var _chunk6RPZADX3cjs = require('./chunk-6RPZADX3.cjs');
36
36
 
37
37
 
38
38
 
39
+
40
+
39
41
  var _chunkJ3QQ6JS5cjs = require('./chunk-J3QQ6JS5.cjs');
40
42
 
41
43
 
@@ -104,7 +106,7 @@ var _chunkQBZJ7P2Tcjs = require('./chunk-QBZJ7P2T.cjs');
104
106
  var _chunkA2YMUCBTcjs = require('./chunk-A2YMUCBT.cjs');
105
107
 
106
108
 
107
- var _chunkXPIOJQS2cjs = require('./chunk-XPIOJQS2.cjs');
109
+ var _chunkUWDW6PN3cjs = require('./chunk-UWDW6PN3.cjs');
108
110
 
109
111
 
110
112
 
@@ -3664,7 +3666,8 @@ function normalizeAudit(raw) {
3664
3666
  retentionDays: Math.trunc(
3665
3667
  clampNumber(_optionalChain([a, 'optionalAccess', _195 => _195.retentionDays]), 1, 365, _audittypes.DEFAULT_AUDIT_CONFIG.retentionDays)
3666
3668
  ),
3667
- trustForwardedFor: _optionalChain([a, 'optionalAccess', _196 => _196.trustForwardedFor]) === true
3669
+ compactStreamingBodies: _optionalChain([a, 'optionalAccess', _196 => _196.compactStreamingBodies]) === true,
3670
+ trustForwardedFor: _optionalChain([a, 'optionalAccess', _197 => _197.trustForwardedFor]) === true
3668
3671
  };
3669
3672
  }
3670
3673
  function normalizeMaxBodyBytes(value) {
@@ -3675,26 +3678,26 @@ function normalizeMaxBodyBytes(value) {
3675
3678
  return Math.trunc(Math.min(1048576, value));
3676
3679
  }
3677
3680
  function normalizeBilling(raw) {
3678
- const b = _optionalChain([raw, 'optionalAccess', _197 => _197.billing]);
3681
+ const b = _optionalChain([raw, 'optionalAccess', _198 => _198.billing]);
3679
3682
  const config = {
3680
- enabled: _optionalChain([b, 'optionalAccess', _198 => _198.enabled]) === true,
3683
+ enabled: _optionalChain([b, 'optionalAccess', _199 => _199.enabled]) === true,
3681
3684
  maxRetryAgeMs: Math.trunc(
3682
- clampNumber(_optionalChain([b, 'optionalAccess', _199 => _199.maxRetryAgeMs]), 6e4, 2592e6, _billingtypes.DEFAULT_BILLING_CONFIG.maxRetryAgeMs)
3685
+ clampNumber(_optionalChain([b, 'optionalAccess', _200 => _200.maxRetryAgeMs]), 6e4, 2592e6, _billingtypes.DEFAULT_BILLING_CONFIG.maxRetryAgeMs)
3683
3686
  )
3684
3687
  };
3685
- if (typeof _optionalChain([b, 'optionalAccess', _200 => _200.endpoint]) === "string" && b.endpoint.trim()) config.endpoint = b.endpoint.trim();
3686
- if (typeof _optionalChain([b, 'optionalAccess', _201 => _201.secret]) === "string" && b.secret.length > 0) config.secret = b.secret;
3688
+ if (typeof _optionalChain([b, 'optionalAccess', _201 => _201.endpoint]) === "string" && b.endpoint.trim()) config.endpoint = b.endpoint.trim();
3689
+ if (typeof _optionalChain([b, 'optionalAccess', _202 => _202.secret]) === "string" && b.secret.length > 0) config.secret = b.secret;
3687
3690
  return config;
3688
3691
  }
3689
3692
  var DEFAULT_FINGERPRINT = { enabled: false };
3690
3693
  function normalizeFingerprint(raw) {
3691
- const f = _optionalChain([raw, 'optionalAccess', _202 => _202.fingerprint]);
3692
- const out = { enabled: _optionalChain([f, 'optionalAccess', _203 => _203.enabled]) === true };
3693
- if (typeof _optionalChain([f, 'optionalAccess', _204 => _204.ua]) === "string" && f.ua.trim().length > 0) out.ua = f.ua.trim();
3694
+ const f = _optionalChain([raw, 'optionalAccess', _203 => _203.fingerprint]);
3695
+ const out = { enabled: _optionalChain([f, 'optionalAccess', _204 => _204.enabled]) === true };
3696
+ if (typeof _optionalChain([f, 'optionalAccess', _205 => _205.ua]) === "string" && f.ua.trim().length > 0) out.ua = f.ua.trim();
3694
3697
  return out;
3695
3698
  }
3696
3699
  function normalizeVoucher(raw) {
3697
- return { enabled: _optionalChain([raw, 'optionalAccess', _205 => _205.voucher, 'optionalAccess', _206 => _206.enabled]) === true };
3700
+ return { enabled: _optionalChain([raw, 'optionalAccess', _206 => _206.voucher, 'optionalAccess', _207 => _207.enabled]) === true };
3698
3701
  }
3699
3702
  var PROXY_TYPES = ["http", "https", "socks5"];
3700
3703
  function normalizeProxyConfig(raw) {
@@ -3778,14 +3781,14 @@ function clampNumber(value, min, max, fallback) {
3778
3781
  return Math.min(max, Math.max(min, n));
3779
3782
  }
3780
3783
  function normalizeQueueSegments(raw) {
3781
- const umq = _optionalChain([raw, 'optionalAccess', _207 => _207.userMessageQueue]);
3782
- const cq = _optionalChain([raw, 'optionalAccess', _208 => _208.concurrencyQueue]);
3784
+ const umq = _optionalChain([raw, 'optionalAccess', _208 => _208.userMessageQueue]);
3785
+ const cq = _optionalChain([raw, 'optionalAccess', _209 => _209.concurrencyQueue]);
3783
3786
  return {
3784
3787
  userMessageQueue: {
3785
- enabled: _optionalChain([umq, 'optionalAccess', _209 => _209.enabled]) === true,
3786
- delayMs: clampNumber(_optionalChain([umq, 'optionalAccess', _210 => _210.delayMs]), 0, 1e4, DEFAULT_USER_MESSAGE_QUEUE.delayMs),
3788
+ enabled: _optionalChain([umq, 'optionalAccess', _210 => _210.enabled]) === true,
3789
+ delayMs: clampNumber(_optionalChain([umq, 'optionalAccess', _211 => _211.delayMs]), 0, 1e4, DEFAULT_USER_MESSAGE_QUEUE.delayMs),
3787
3790
  waitTimeoutMs: clampNumber(
3788
- _optionalChain([umq, 'optionalAccess', _211 => _211.waitTimeoutMs]),
3791
+ _optionalChain([umq, 'optionalAccess', _212 => _212.waitTimeoutMs]),
3789
3792
  1e3,
3790
3793
  3e5,
3791
3794
  DEFAULT_USER_MESSAGE_QUEUE.waitTimeoutMs
@@ -3793,14 +3796,14 @@ function normalizeQueueSegments(raw) {
3793
3796
  },
3794
3797
  concurrencyQueue: {
3795
3798
  maxQueueSizeFactor: clampNumber(
3796
- _optionalChain([cq, 'optionalAccess', _212 => _212.maxQueueSizeFactor]),
3799
+ _optionalChain([cq, 'optionalAccess', _213 => _213.maxQueueSizeFactor]),
3797
3800
  1,
3798
3801
  10,
3799
3802
  DEFAULT_CONCURRENCY_QUEUE.maxQueueSizeFactor
3800
3803
  ),
3801
- minQueueSize: clampNumber(_optionalChain([cq, 'optionalAccess', _213 => _213.minQueueSize]), 1, 100, DEFAULT_CONCURRENCY_QUEUE.minQueueSize),
3804
+ minQueueSize: clampNumber(_optionalChain([cq, 'optionalAccess', _214 => _214.minQueueSize]), 1, 100, DEFAULT_CONCURRENCY_QUEUE.minQueueSize),
3802
3805
  waitTimeoutMs: clampNumber(
3803
- _optionalChain([cq, 'optionalAccess', _214 => _214.waitTimeoutMs]),
3806
+ _optionalChain([cq, 'optionalAccess', _215 => _215.waitTimeoutMs]),
3804
3807
  1e3,
3805
3808
  3e5,
3806
3809
  DEFAULT_CONCURRENCY_QUEUE.waitTimeoutMs
@@ -3913,7 +3916,7 @@ function normalizeGatewayModelMappings(raw) {
3913
3916
  return mappings;
3914
3917
  }
3915
3918
  function hasConfiguredLegacyModels(config) {
3916
- return Object.values(_nullishCoalesce(config.modelMap, () => ( {}))).some((value) => typeof value === "string" && value.trim()) || Boolean(_optionalChain([config, 'access', _215 => _215.models, 'optionalAccess', _216 => _216.some, 'call', _217 => _217((value) => typeof value === "string" && value.trim())])) || Boolean(_optionalChain([config, 'access', _218 => _218.defaultModel, 'optionalAccess', _219 => _219.trim, 'call', _220 => _220()])) || Boolean(_optionalChain([config, 'access', _221 => _221.backgroundModel, 'optionalAccess', _222 => _222.trim, 'call', _223 => _223()])) || Boolean(Object.values(_nullishCoalesce(config.prefixTargets, () => ( {}))).some((value) => _optionalChain([value, 'optionalAccess', _224 => _224.trim, 'call', _225 => _225()])));
3919
+ return Object.values(_nullishCoalesce(config.modelMap, () => ( {}))).some((value) => typeof value === "string" && value.trim()) || Boolean(_optionalChain([config, 'access', _216 => _216.models, 'optionalAccess', _217 => _217.some, 'call', _218 => _218((value) => typeof value === "string" && value.trim())])) || Boolean(_optionalChain([config, 'access', _219 => _219.defaultModel, 'optionalAccess', _220 => _220.trim, 'call', _221 => _221()])) || Boolean(_optionalChain([config, 'access', _222 => _222.backgroundModel, 'optionalAccess', _223 => _223.trim, 'call', _224 => _224()])) || Boolean(Object.values(_nullishCoalesce(config.prefixTargets, () => ( {}))).some((value) => _optionalChain([value, 'optionalAccess', _225 => _225.trim, 'call', _226 => _226()])));
3917
3920
  }
3918
3921
  function splitModelRef(ref) {
3919
3922
  if (typeof ref !== "string") return null;
@@ -3981,7 +3984,7 @@ function legacyEndpointToBindings(config) {
3981
3984
  if (!parsed) continue;
3982
3985
  const route = routeFor(parsed.providerId);
3983
3986
  route[field] = ref;
3984
- if (_optionalChain([config, 'access', _226 => _226.backgroundModelIds, 'optionalAccess', _227 => _227.length])) {
3987
+ if (_optionalChain([config, 'access', _227 => _227.backgroundModelIds, 'optionalAccess', _228 => _228.length])) {
3985
3988
  route.backgroundModelIds = [...config.backgroundModelIds];
3986
3989
  }
3987
3990
  }
@@ -4131,6 +4134,60 @@ function mergeServerConfig(current, patch) {
4131
4134
  });
4132
4135
  }
4133
4136
 
4137
+ // src/outbound-api/auditSessionKey.ts
4138
+
4139
+ var EXPLICIT_ID_SOURCES = /* @__PURE__ */ new Set([
4140
+ "session-header",
4141
+ "thread-header",
4142
+ "body-session-id",
4143
+ "body-thread-id",
4144
+ "prompt-cache-key"
4145
+ ]);
4146
+ var ANTHROPIC_SESSION_RE = /_session_([A-Za-z0-9][A-Za-z0-9_-]{7,})/;
4147
+ var DIGEST_HEX = 32;
4148
+ function stableDigest(value) {
4149
+ return _crypto.createHash.call(void 0, "sha256").update(value, "utf8").digest("hex").slice(0, DIGEST_HEX);
4150
+ }
4151
+ function asObject(value) {
4152
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
4153
+ }
4154
+ function anthropicSessionId(body) {
4155
+ const userId = _optionalChain([asObject, 'call', _229 => _229(body["metadata"]), 'optionalAccess', _230 => _230["user_id"]]);
4156
+ if (typeof userId !== "string" || !userId) return void 0;
4157
+ const matched = ANTHROPIC_SESSION_RE.exec(userId);
4158
+ return _optionalChain([matched, 'optionalAccess', _231 => _231[1]]);
4159
+ }
4160
+ function anthropicContentFingerprint(body) {
4161
+ const messages = body["messages"];
4162
+ if (!Array.isArray(messages) || messages.length === 0) return void 0;
4163
+ const parts = [];
4164
+ const system = _chunkJ3QQ6JS5cjs.flattenMatchText.call(void 0, body["system"]).trim();
4165
+ if (system) parts.push(system.slice(0, _chunkJ3QQ6JS5cjs.MATCH_TEXT_PER_MESSAGE_CAP));
4166
+ let firstUser = "";
4167
+ for (const entry of messages) {
4168
+ const message = asObject(entry);
4169
+ if (!message || message["role"] !== "user") continue;
4170
+ const text = _chunkJ3QQ6JS5cjs.flattenMatchText.call(void 0, message["content"]).trim();
4171
+ if (!text) continue;
4172
+ firstUser = text.slice(0, _chunkJ3QQ6JS5cjs.MATCH_TEXT_PER_MESSAGE_CAP);
4173
+ break;
4174
+ }
4175
+ if (parts.length === 0 && !firstUser) return void 0;
4176
+ return `${parts.join("\0")}\0${firstUser}`;
4177
+ }
4178
+ function deriveAuditSessionKey(body, headers = {}, options = {}) {
4179
+ const anthropicSession = anthropicSessionId(body);
4180
+ if (anthropicSession) return stableDigest(`anthropic-session\0${anthropicSession}`);
4181
+ const gateway = _chunkJ3QQ6JS5cjs.deriveGatewaySessionKey.call(void 0, body, headers, {
4182
+ ...options.fallbackKey !== void 0 ? { fallbackKey: options.fallbackKey } : {},
4183
+ ...options.endpoint !== void 0 ? { endpoint: options.endpoint } : {}
4184
+ });
4185
+ if (EXPLICIT_ID_SOURCES.has(gateway.source)) return gateway.key;
4186
+ const fingerprint = anthropicContentFingerprint(body);
4187
+ if (fingerprint) return stableDigest(`anthropic-content\0${fingerprint}`);
4188
+ return gateway.key;
4189
+ }
4190
+
4134
4191
  // src/outbound-api/outboundApiKeyAuth.ts
4135
4192
 
4136
4193
 
@@ -4493,8 +4550,8 @@ var OutboundRateLimiter = (_class10 = class {
4493
4550
  * recorded (no bucket growth).
4494
4551
  */
4495
4552
  check(apiKeyId, now = Date.now(), override) {
4496
- const maxRequests = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _228 => _228.maxRequests]), () => ( this.maxRequests));
4497
- const windowMs = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _229 => _229.windowMs]), () => ( this.windowMs));
4553
+ const maxRequests = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _232 => _232.maxRequests]), () => ( this.maxRequests));
4554
+ const windowMs = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _233 => _233.windowMs]), () => ( this.windowMs));
4498
4555
  if (maxRequests === 0) return { allowed: true, retryAfterSeconds: 0 };
4499
4556
  const cutoff = now - windowMs;
4500
4557
  const timestamps = (_nullishCoalesce(this.hits.get(apiKeyId), () => ( []))).filter((ts) => ts > cutoff);
@@ -4525,7 +4582,7 @@ var OutboundRateLimiter = (_class10 = class {
4525
4582
  function asArray(v) {
4526
4583
  return Array.isArray(v) ? v : [];
4527
4584
  }
4528
- function asObject(v) {
4585
+ function asObject2(v) {
4529
4586
  return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
4530
4587
  }
4531
4588
  function last(arr) {
@@ -4533,13 +4590,13 @@ function last(arr) {
4533
4590
  }
4534
4591
  function isUserMessageAnthropic(body) {
4535
4592
  const messages = asArray(body["messages"]);
4536
- const lastMsg = asObject(last(messages));
4593
+ const lastMsg = asObject2(last(messages));
4537
4594
  if (!lastMsg || lastMsg["role"] !== "user") return false;
4538
4595
  const content = lastMsg["content"];
4539
4596
  if (typeof content === "string") return true;
4540
4597
  if (Array.isArray(content)) {
4541
4598
  const hasToolResult = content.some(
4542
- (block) => _optionalChain([asObject, 'call', _230 => _230(block), 'optionalAccess', _231 => _231["type"]]) === "tool_result"
4599
+ (block) => _optionalChain([asObject2, 'call', _234 => _234(block), 'optionalAccess', _235 => _235["type"]]) === "tool_result"
4543
4600
  );
4544
4601
  return !hasToolResult;
4545
4602
  }
@@ -4549,7 +4606,7 @@ function isUserMessageResponses(body) {
4549
4606
  const input = body["input"];
4550
4607
  if (typeof input === "string") return input.length > 0;
4551
4608
  if (Array.isArray(input)) {
4552
- const lastItem = asObject(last(input));
4609
+ const lastItem = asObject2(last(input));
4553
4610
  if (!lastItem) return false;
4554
4611
  if (lastItem["type"] === "function_call_output") return false;
4555
4612
  return lastItem["role"] === "user";
@@ -4558,22 +4615,22 @@ function isUserMessageResponses(body) {
4558
4615
  }
4559
4616
  function isUserMessageChat(body) {
4560
4617
  const messages = asArray(body["messages"]);
4561
- const lastMsg = asObject(last(messages));
4618
+ const lastMsg = asObject2(last(messages));
4562
4619
  if (!lastMsg) return false;
4563
4620
  return lastMsg["role"] === "user";
4564
4621
  }
4565
4622
  function isUserMessageGemini(body) {
4566
4623
  const contents = asArray(body["contents"]);
4567
- const lastContent = asObject(last(contents));
4624
+ const lastContent = asObject2(last(contents));
4568
4625
  if (!lastContent || lastContent["role"] !== "user") return false;
4569
4626
  const parts = asArray(lastContent["parts"]);
4570
4627
  const hasFunctionResponse = parts.some(
4571
- (part) => _optionalChain([asObject, 'call', _232 => _232(part), 'optionalAccess', _233 => _233["functionResponse"]]) !== void 0
4628
+ (part) => _optionalChain([asObject2, 'call', _236 => _236(part), 'optionalAccess', _237 => _237["functionResponse"]]) !== void 0
4572
4629
  );
4573
4630
  return !hasFunctionResponse;
4574
4631
  }
4575
4632
  function isUserMessageRequest(endpoint, parsedBody) {
4576
- const body = asObject(parsedBody);
4633
+ const body = asObject2(parsedBody);
4577
4634
  if (!body) return false;
4578
4635
  switch (endpoint) {
4579
4636
  case "messages":
@@ -4742,14 +4799,14 @@ function newVoucherId() {
4742
4799
  }
4743
4800
  function computeVoucherGrant(voucher, currentKey, now) {
4744
4801
  if (voucher.type === "credit") {
4745
- const current = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _234 => _234.totalCostLimitUsd]), () => ( 0));
4802
+ const current = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _238 => _238.totalCostLimitUsd]), () => ( 0));
4746
4803
  let granted2 = current + (_nullishCoalesce(voucher.creditUsd, () => ( 0)));
4747
4804
  if (voucher.maxTotalCostLimitUsd != null) {
4748
4805
  granted2 = Math.min(granted2, voucher.maxTotalCostLimitUsd);
4749
4806
  }
4750
4807
  return { totalCostLimitUsd: granted2 };
4751
4808
  }
4752
- const currentExpiry = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _235 => _235.expiresAt]), () => ( now));
4809
+ const currentExpiry = _nullishCoalesce(_optionalChain([currentKey, 'optionalAccess', _239 => _239.expiresAt]), () => ( now));
4753
4810
  let granted = currentExpiry + (_nullishCoalesce(voucher.renewalDays, () => ( 0))) * DAY_MS2;
4754
4811
  if (voucher.maxExpiryDays != null) {
4755
4812
  granted = Math.min(granted, now + voucher.maxExpiryDays * DAY_MS2);
@@ -4780,7 +4837,7 @@ function toVoucherInfo(v) {
4780
4837
  // src/outbound-api/voucherRedeem.ts
4781
4838
  function isRedeemRequest(method, url) {
4782
4839
  if (method !== "POST" || !url) return false;
4783
- const path = _nullishCoalesce(_optionalChain([url, 'access', _236 => _236.split, 'call', _237 => _237("?"), 'access', _238 => _238[0], 'optionalAccess', _239 => _239.replace, 'call', _240 => _240(/\/+$/, "")]), () => ( ""));
4840
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _240 => _240.split, 'call', _241 => _241("?"), 'access', _242 => _242[0], 'optionalAccess', _243 => _243.replace, 'call', _244 => _244(/\/+$/, "")]), () => ( ""));
4784
4841
  return path.endsWith("/redeem");
4785
4842
  }
4786
4843
  function writeErr(res, status, message, headers = {}) {
@@ -4810,8 +4867,8 @@ function grantToResult(type, granted) {
4810
4867
  function currentResult(type, keyRow) {
4811
4868
  const result = { type };
4812
4869
  if (type === "credit") {
4813
- if (_optionalChain([keyRow, 'optionalAccess', _241 => _241.totalCostLimitUsd]) != null) result.totalCostLimitUsd = keyRow.totalCostLimitUsd;
4814
- } else if (_optionalChain([keyRow, 'optionalAccess', _242 => _242.expiresAt]) != null) {
4870
+ if (_optionalChain([keyRow, 'optionalAccess', _245 => _245.totalCostLimitUsd]) != null) result.totalCostLimitUsd = keyRow.totalCostLimitUsd;
4871
+ } else if (_optionalChain([keyRow, 'optionalAccess', _246 => _246.expiresAt]) != null) {
4815
4872
  result.expiresAt = keyRow.expiresAt;
4816
4873
  }
4817
4874
  return result;
@@ -4898,7 +4955,7 @@ async function handleVoucherRedeem(req, res, deps, voucherEnabled, redeemLimiter
4898
4955
  const won = await voucherDb.voucherRedeemCas(voucher.id, verifiedKeyId, absolute, now);
4899
4956
  if (!won) {
4900
4957
  const after = await voucherDb.voucherGetByHash(codeHash);
4901
- if (_optionalChain([after, 'optionalAccess', _243 => _243.status]) === "redeemed" && after.redeemedByKeyId === verifiedKeyId) {
4958
+ if (_optionalChain([after, 'optionalAccess', _247 => _247.status]) === "redeemed" && after.redeemedByKeyId === verifiedKeyId) {
4902
4959
  return after.grantApplied === true ? { ok: true, result: currentResult(after.type, await deps.db.outboundApiKeysGetByHash(keyHash)) } : await applyFirstPass(after, recordedAbsolute(after));
4903
4960
  }
4904
4961
  return { ok: false, status: 409, message: "Code was already redeemed" };
@@ -4959,10 +5016,10 @@ function extractPresentedKey(req) {
4959
5016
  }
4960
5017
  const xApiKey = req.headers["x-api-key"];
4961
5018
  const xApi = Array.isArray(xApiKey) ? xApiKey[0] : xApiKey;
4962
- if (_optionalChain([xApi, 'optionalAccess', _244 => _244.trim, 'call', _245 => _245()])) return xApi.trim();
5019
+ if (_optionalChain([xApi, 'optionalAccess', _248 => _248.trim, 'call', _249 => _249()])) return xApi.trim();
4963
5020
  const goog = req.headers["x-goog-api-key"];
4964
5021
  const g = Array.isArray(goog) ? goog[0] : goog;
4965
- return _optionalChain([g, 'optionalAccess', _246 => _246.trim, 'call', _247 => _247()]) || void 0;
5022
+ return _optionalChain([g, 'optionalAccess', _250 => _250.trim, 'call', _251 => _251()]) || void 0;
4966
5023
  }
4967
5024
  function isLoopbackPeer(address) {
4968
5025
  if (!address) return false;
@@ -4971,7 +5028,7 @@ function isLoopbackPeer(address) {
4971
5028
  }
4972
5029
  function selectEndpoint(method, url) {
4973
5030
  if (method !== "POST" || !url) return null;
4974
- const path = _nullishCoalesce(_optionalChain([url, 'access', _248 => _248.split, 'call', _249 => _249("?"), 'access', _250 => _250[0], 'optionalAccess', _251 => _251.replace, 'call', _252 => _252(/\/+$/, "")]), () => ( ""));
5031
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _252 => _252.split, 'call', _253 => _253("?"), 'access', _254 => _254[0], 'optionalAccess', _255 => _255.replace, 'call', _256 => _256(/\/+$/, "")]), () => ( ""));
4975
5032
  if (path.endsWith("/chat/completions")) return "chat";
4976
5033
  if (path.endsWith("/responses")) return "responses";
4977
5034
  if (path.includes("/v1/messages")) return "messages";
@@ -4989,7 +5046,7 @@ function extractGeminiModelFromUrl(url) {
4989
5046
  }
4990
5047
  function isModelsListRequest(url) {
4991
5048
  if (!url) return false;
4992
- const path = _nullishCoalesce(_optionalChain([url, 'access', _253 => _253.split, 'call', _254 => _254("?"), 'access', _255 => _255[0], 'optionalAccess', _256 => _256.replace, 'call', _257 => _257(/\/+$/, "")]), () => ( ""));
5049
+ const path = _nullishCoalesce(_optionalChain([url, 'access', _257 => _257.split, 'call', _258 => _258("?"), 'access', _259 => _259[0], 'optionalAccess', _260 => _260.replace, 'call', _261 => _261(/\/+$/, "")]), () => ( ""));
4993
5050
  return path.endsWith("/models");
4994
5051
  }
4995
5052
  async function writeModelsList(res, llmConfig, config, apiKeyId, allowedEndpoints) {
@@ -5000,7 +5057,7 @@ async function writeModelsList(res, llmConfig, config, apiKeyId, allowedEndpoint
5000
5057
  if (binding.modelMode === "passthrough") {
5001
5058
  if (binding.target.kind === "provider") {
5002
5059
  const provider = await llmConfig.getProvider(binding.target.providerId);
5003
- modelIds.push(..._nullishCoalesce(_optionalChain([provider, 'optionalAccess', _258 => _258.models]), () => ( [])));
5060
+ modelIds.push(..._nullishCoalesce(_optionalChain([provider, 'optionalAccess', _262 => _262.models]), () => ( [])));
5004
5061
  } else if (Object.prototype.hasOwnProperty.call(
5005
5062
  _subscriptionmodelcatalog.SUBSCRIPTION_MODEL_CATALOG,
5006
5063
  binding.target.providerId
@@ -5011,7 +5068,7 @@ async function writeModelsList(res, llmConfig, config, apiKeyId, allowedEndpoint
5011
5068
  }
5012
5069
  continue;
5013
5070
  }
5014
- if (_optionalChain([binding, 'access', _259 => _259.modelMappings, 'optionalAccess', _260 => _260.length])) {
5071
+ if (_optionalChain([binding, 'access', _263 => _263.modelMappings, 'optionalAccess', _264 => _264.length])) {
5015
5072
  modelIds.push(
5016
5073
  ...binding.modelMappings.map((mapping) => mapping.source.trim()).filter((source) => source !== "" && !source.includes("*"))
5017
5074
  );
@@ -5027,7 +5084,7 @@ async function writeModelsList(res, llmConfig, config, apiKeyId, allowedEndpoint
5027
5084
  if (endpointConfig.backgroundModel) refs.push(endpointConfig.backgroundModel);
5028
5085
  }
5029
5086
  modelIds.push(
5030
- ...refs.map((ref) => _optionalChain([_chunk4VZX5F4Tcjs.parseModelRef.call(void 0, ref), 'optionalAccess', _261 => _261.modelId])).filter((modelId) => modelId !== void 0)
5087
+ ...refs.map((ref) => _optionalChain([_chunk4VZX5F4Tcjs.parseModelRef.call(void 0, ref), 'optionalAccess', _265 => _265.modelId])).filter((modelId) => modelId !== void 0)
5031
5088
  );
5032
5089
  }
5033
5090
  }
@@ -5055,7 +5112,7 @@ function shimAuthHeader(req, routeToken) {
5055
5112
  }
5056
5113
  async function handleOutboundRequest(req, res, deps, config, rateLimiter, serialQueue, concurrencyGate, redeemLimiter, redeemMutex) {
5057
5114
  const now = Date.now();
5058
- const audit = _chunkXPIOJQS2cjs.beginAuditCapture.call(void 0, req, res, now);
5115
+ const audit = _chunkUWDW6PN3cjs.beginAuditCapture.call(void 0, req, res, now);
5059
5116
  const billing = _chunkAPYG5QD7cjs.beginBillingCapture.call(void 0, req, res, now);
5060
5117
  const presented = extractPresentedKey(req);
5061
5118
  const verification = await verifyKey(deps.db, presented, now);
@@ -5070,7 +5127,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
5070
5127
  const verified = verification.key;
5071
5128
  if (audit) audit.keyId = verified.id;
5072
5129
  if (billing) billing.keyId = verified.id;
5073
- if (verified.loopbackOnly && !isLoopbackPeer(_optionalChain([req, 'access', _262 => _262.socket, 'optionalAccess', _263 => _263.remoteAddress]))) {
5130
+ if (verified.loopbackOnly && !isLoopbackPeer(_optionalChain([req, 'access', _266 => _266.socket, 'optionalAccess', _267 => _267.remoteAddress]))) {
5074
5131
  writeJsonError(res, 403, "This integration key is restricted to loopback clients");
5075
5132
  return;
5076
5133
  }
@@ -5083,7 +5140,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
5083
5140
  req,
5084
5141
  res,
5085
5142
  deps,
5086
- _optionalChain([config, 'access', _264 => _264.voucher, 'optionalAccess', _265 => _265.enabled]) === true,
5143
+ _optionalChain([config, 'access', _268 => _268.voucher, 'optionalAccess', _269 => _269.enabled]) === true,
5087
5144
  _nullishCoalesce(redeemLimiter, () => ( getFallbackRedeemLimiter())),
5088
5145
  verified.id,
5089
5146
  _nullishCoalesce(presented, () => ( "")),
@@ -5185,7 +5242,13 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
5185
5242
  writeJsonError(res, 400, "Invalid JSON in request body");
5186
5243
  return;
5187
5244
  }
5188
- if (audit) audit.setRequestBody(rawBody);
5245
+ if (audit) {
5246
+ audit.setRequestBody(rawBody);
5247
+ audit.sessionKey = deriveAuditSessionKey(parsedBody, req.headers, {
5248
+ fallbackKey: verified.id,
5249
+ endpoint
5250
+ });
5251
+ }
5189
5252
  if (endpoint === "gemini" && typeof parsedBody["model"] !== "string") {
5190
5253
  const urlModel = extractGeminiModelFromUrl(req.url);
5191
5254
  if (urlModel) parsedBody["model"] = urlModel;
@@ -5252,7 +5315,7 @@ async function handleOutboundRequest(req, res, deps, config, rateLimiter, serial
5252
5315
  }
5253
5316
  let releaseSerial = null;
5254
5317
  const providerKey = resolved.route.providerId;
5255
- if (_optionalChain([config, 'access', _266 => _266.userMessageQueue, 'optionalAccess', _267 => _267.enabled]) && providerKey && isUserMessageRequest(endpoint, parsedBody)) {
5318
+ if (_optionalChain([config, 'access', _270 => _270.userMessageQueue, 'optionalAccess', _271 => _271.enabled]) && providerKey && isUserMessageRequest(endpoint, parsedBody)) {
5256
5319
  const umq = config.userMessageQueue;
5257
5320
  try {
5258
5321
  const serialSlot = await serialQueue.acquire(providerKey, {
@@ -5392,7 +5455,7 @@ var OutboundApiServer = (_class13 = class {
5392
5455
  const actualPort = await this.listen(bindAddr, port);
5393
5456
  this.boundAddr = bindAddr;
5394
5457
  this.boundPort = actualPort;
5395
- if (actualPort !== port) _optionalChain([this, 'access', _268 => _268.onPortChange, 'optionalCall', _269 => _269(actualPort)]);
5458
+ if (actualPort !== port) _optionalChain([this, 'access', _272 => _272.onPortChange, 'optionalCall', _273 => _273(actualPort)]);
5396
5459
  this.logInfo(`[OutboundApiServer] Listening on ${bindAddr}:${actualPort}`);
5397
5460
  return actualPort;
5398
5461
  }
@@ -5461,7 +5524,7 @@ var OutboundApiServer = (_class13 = class {
5461
5524
  const provider = this.deps.healthReportProvider;
5462
5525
  if (!provider) return false;
5463
5526
  if (req.method !== "GET" && req.method !== "HEAD") return false;
5464
- const path = _optionalChain([(_nullishCoalesce(req.url, () => ( "/"))), 'access', _270 => _270.split, 'call', _271 => _271("?"), 'access', _272 => _272[0], 'optionalAccess', _273 => _273.replace, 'call', _274 => _274(/\/+$/, "")]) || "/";
5527
+ const path = _optionalChain([(_nullishCoalesce(req.url, () => ( "/"))), 'access', _274 => _274.split, 'call', _275 => _275("?"), 'access', _276 => _276[0], 'optionalAccess', _277 => _277.replace, 'call', _278 => _278(/\/+$/, "")]) || "/";
5465
5528
  if (path !== "/health" && path !== "/healthz") return false;
5466
5529
  const report = provider();
5467
5530
  res.writeHead(_healthloggingtypes.healthHttpStatus.call(void 0, report.status), { "Content-Type": "application/json" });
@@ -5676,7 +5739,7 @@ function resolveCompletionReasoningPlan(provider, options, target, requestMaxTok
5676
5739
  }
5677
5740
  function resolveOpenAIEffort(provider, options, target) {
5678
5741
  const plan = resolveCompletionReasoningPlan(provider, options, target);
5679
- return _optionalChain([plan, 'optionalAccess', _275 => _275.kind]) === "level" && plan.enabled ? plan.effort : void 0;
5742
+ return _optionalChain([plan, 'optionalAccess', _279 => _279.kind]) === "level" && plan.enabled ? plan.effort : void 0;
5680
5743
  }
5681
5744
  function buildAnthropicReasoningWire(provider, options) {
5682
5745
  const configuredMaxTokens = _nullishCoalesce(options.maxTokens, () => ( LEGACY_ANTHROPIC_MAX_TOKENS));
@@ -5687,7 +5750,7 @@ function buildAnthropicReasoningWire(provider, options) {
5687
5750
  "anthropic",
5688
5751
  legacyBound
5689
5752
  );
5690
- if (_optionalChain([plan, 'optionalAccess', _276 => _276.kind]) === "level" && plan.enabled) {
5753
+ if (_optionalChain([plan, 'optionalAccess', _280 => _280.kind]) === "level" && plan.enabled) {
5691
5754
  return {
5692
5755
  effectiveMaxTokens: configuredMaxTokens,
5693
5756
  thinking: { type: "adaptive" },
@@ -5695,7 +5758,7 @@ function buildAnthropicReasoningWire(provider, options) {
5695
5758
  legacyBudgetEnabled: false
5696
5759
  };
5697
5760
  }
5698
- if (_optionalChain([plan, 'optionalAccess', _277 => _277.kind]) === "budget" && plan.enabled) {
5761
+ if (_optionalChain([plan, 'optionalAccess', _281 => _281.kind]) === "budget" && plan.enabled) {
5699
5762
  return {
5700
5763
  effectiveMaxTokens: legacyBound,
5701
5764
  thinking: { type: "enabled", budget_tokens: plan.budgetTokens },
@@ -5709,13 +5772,13 @@ function buildAnthropicReasoningWire(provider, options) {
5709
5772
  }
5710
5773
  function buildGeminiThinkingConfig(provider, options) {
5711
5774
  const plan = resolveCompletionReasoningPlan(provider, options, "gemini");
5712
- if (_optionalChain([plan, 'optionalAccess', _278 => _278.kind]) === "level") {
5775
+ if (_optionalChain([plan, 'optionalAccess', _282 => _282.kind]) === "level") {
5713
5776
  return {
5714
5777
  includeThoughts: plan.enabled,
5715
5778
  thinkingLevel: plan.effort
5716
5779
  };
5717
5780
  }
5718
- if (_optionalChain([plan, 'optionalAccess', _279 => _279.kind]) === "budget") {
5781
+ if (_optionalChain([plan, 'optionalAccess', _283 => _283.kind]) === "budget") {
5719
5782
  return {
5720
5783
  includeThoughts: plan.enabled,
5721
5784
  thinkingBudget: plan.budgetTokens
@@ -5811,7 +5874,7 @@ async function callAnthropicCompletion(provider, apiKey, options, logger) {
5811
5874
  message: {
5812
5875
  id: `assistant-${Date.now()}`,
5813
5876
  role: "assistant",
5814
- content: _optionalChain([choice2, 'access', _280 => _280.message, 'optionalAccess', _281 => _281.content]) || "",
5877
+ content: _optionalChain([choice2, 'access', _284 => _284.message, 'optionalAccess', _285 => _285.content]) || "",
5815
5878
  timestamp: Date.now()
5816
5879
  },
5817
5880
  usage: openaiResponse2.usage ? {
@@ -5928,7 +5991,7 @@ async function callGeminiCompletion(provider, apiKey, options, logger) {
5928
5991
  const candidate = candidates[0];
5929
5992
  const content = candidate.content;
5930
5993
  let textContent = "";
5931
- if (_optionalChain([content, 'optionalAccess', _282 => _282.parts])) {
5994
+ if (_optionalChain([content, 'optionalAccess', _286 => _286.parts])) {
5932
5995
  for (const part of content.parts) {
5933
5996
  if (part.text) {
5934
5997
  textContent += part.text;
@@ -6056,7 +6119,7 @@ async function streamOpenAICompletion(provider, apiKey, options, messageId, call
6056
6119
  });
6057
6120
  if (!response.ok) {
6058
6121
  const errorText = await response.text();
6059
- _optionalChain([callbacks, 'access', _283 => _283.onError, 'optionalCall', _284 => _284(`API error (${response.status}): ${errorText}`)]);
6122
+ _optionalChain([callbacks, 'access', _287 => _287.onError, 'optionalCall', _288 => _288(`API error (${response.status}): ${errorText}`)]);
6060
6123
  return;
6061
6124
  }
6062
6125
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "openai", {
@@ -6066,7 +6129,7 @@ async function streamOpenAICompletion(provider, apiKey, options, messageId, call
6066
6129
  onVideo: callbacks.onVideo,
6067
6130
  onError: callbacks.onError
6068
6131
  });
6069
- _optionalChain([callbacks, 'access', _285 => _285.onDone, 'optionalCall', _286 => _286(
6132
+ _optionalChain([callbacks, 'access', _289 => _289.onDone, 'optionalCall', _290 => _290(
6070
6133
  {
6071
6134
  id: messageId,
6072
6135
  role: "assistant",
@@ -6141,7 +6204,7 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
6141
6204
  logger.info("Streaming Anthropic completion request", {
6142
6205
  url: apiUrl,
6143
6206
  model: anthropicRequest.model,
6144
- messagesCount: _optionalChain([anthropicRequest, 'access', _287 => _287.messages, 'optionalAccess', _288 => _288.length]),
6207
+ messagesCount: _optionalChain([anthropicRequest, 'access', _291 => _291.messages, 'optionalAccess', _292 => _292.length]),
6145
6208
  max_tokens: anthropicRequest.max_tokens,
6146
6209
  temperature: anthropicRequest.temperature,
6147
6210
  stream: anthropicRequest.stream,
@@ -6158,7 +6221,7 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
6158
6221
  if (!response.ok) {
6159
6222
  const errorText = await response.text();
6160
6223
  logger.error("Anthropic API error", void 0, { status: response.status, errorText });
6161
- _optionalChain([callbacks, 'access', _289 => _289.onError, 'optionalCall', _290 => _290(`API error (${response.status}): ${errorText}`)]);
6224
+ _optionalChain([callbacks, 'access', _293 => _293.onError, 'optionalCall', _294 => _294(`API error (${response.status}): ${errorText}`)]);
6162
6225
  return;
6163
6226
  }
6164
6227
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "anthropic", {
@@ -6169,10 +6232,10 @@ async function streamAnthropicCompletion(provider, apiKey, options, messageId, c
6169
6232
  });
6170
6233
  logger.info("Anthropic stream complete", {
6171
6234
  contentLength: result.content.length,
6172
- reasoningLength: _optionalChain([result, 'access', _291 => _291.reasoning, 'optionalAccess', _292 => _292.length]) || 0,
6235
+ reasoningLength: _optionalChain([result, 'access', _295 => _295.reasoning, 'optionalAccess', _296 => _296.length]) || 0,
6173
6236
  blocksCount: result.blocks.length
6174
6237
  });
6175
- _optionalChain([callbacks, 'access', _293 => _293.onDone, 'optionalCall', _294 => _294(
6238
+ _optionalChain([callbacks, 'access', _297 => _297.onDone, 'optionalCall', _298 => _298(
6176
6239
  {
6177
6240
  id: messageId,
6178
6241
  role: "assistant",
@@ -6230,7 +6293,7 @@ async function streamGeminiCompletion(provider, apiKey, options, messageId, call
6230
6293
  if (!response.ok) {
6231
6294
  const errorText = await response.text();
6232
6295
  logger.error("Gemini API error", void 0, { status: response.status, errorText });
6233
- _optionalChain([callbacks, 'access', _295 => _295.onError, 'optionalCall', _296 => _296(`API error (${response.status}): ${errorText}`)]);
6296
+ _optionalChain([callbacks, 'access', _299 => _299.onError, 'optionalCall', _300 => _300(`API error (${response.status}): ${errorText}`)]);
6234
6297
  return;
6235
6298
  }
6236
6299
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "gemini", {
@@ -6239,7 +6302,7 @@ async function streamGeminiCompletion(provider, apiKey, options, messageId, call
6239
6302
  onError: callbacks.onError
6240
6303
  });
6241
6304
  logger.info("Gemini stream complete", { contentLength: result.content.length });
6242
- _optionalChain([callbacks, 'access', _297 => _297.onDone, 'optionalCall', _298 => _298(
6305
+ _optionalChain([callbacks, 'access', _301 => _301.onDone, 'optionalCall', _302 => _302(
6243
6306
  {
6244
6307
  id: messageId,
6245
6308
  role: "assistant",
@@ -6289,7 +6352,7 @@ async function streamOpenAIResponseCompletion(provider, apiKey, options, message
6289
6352
  });
6290
6353
  if (!response.ok) {
6291
6354
  const errorText = await response.text();
6292
- _optionalChain([callbacks, 'access', _299 => _299.onError, 'optionalCall', _300 => _300(`API error (${response.status}): ${errorText}`)]);
6355
+ _optionalChain([callbacks, 'access', _303 => _303.onError, 'optionalCall', _304 => _304(`API error (${response.status}): ${errorText}`)]);
6293
6356
  return;
6294
6357
  }
6295
6358
  const result = await _chunkHQP3K7PUcjs.streamSSEResponse.call(void 0, response, "openai-response", {
@@ -6298,7 +6361,7 @@ async function streamOpenAIResponseCompletion(provider, apiKey, options, message
6298
6361
  onError: callbacks.onError
6299
6362
  });
6300
6363
  logger.info("OpenAI Response API stream complete", { contentLength: result.content.length });
6301
- _optionalChain([callbacks, 'access', _301 => _301.onDone, 'optionalCall', _302 => _302(
6364
+ _optionalChain([callbacks, 'access', _305 => _305.onDone, 'optionalCall', _306 => _306(
6302
6365
  {
6303
6366
  id: messageId,
6304
6367
  role: "assistant",
@@ -6326,7 +6389,7 @@ async function resolveEffectiveMaxTokens(llmConfig, _getProvider, logger, _provi
6326
6389
  }
6327
6390
  try {
6328
6391
  const globalParams = await llmConfig.getGlobalModelParameters();
6329
- if (_optionalChain([globalParams, 'optionalAccess', _303 => _303.maxTokens, 'optionalAccess', _304 => _304.enabled]) && globalParams.maxTokens.value > 0) {
6392
+ if (_optionalChain([globalParams, 'optionalAccess', _307 => _307.maxTokens, 'optionalAccess', _308 => _308.enabled]) && globalParams.maxTokens.value > 0) {
6330
6393
  logger.debug("Using global maxTokens", { maxTokens: globalParams.maxTokens.value });
6331
6394
  return globalParams.maxTokens.value;
6332
6395
  }
@@ -6354,7 +6417,7 @@ async function resolveThinkingBudget(getProvider, logger, providerId, modelId, m
6354
6417
  }
6355
6418
  const thinkingBudget = _thinkingconfig.calculateThinkingBudget.call(void 0, modelId, thinkLevel, maxTokens);
6356
6419
  const provider = await getProvider(providerId);
6357
- const providerName = _optionalChain([provider, 'optionalAccess', _305 => _305.name, 'optionalAccess', _306 => _306.toLowerCase, 'call', _307 => _307()]) || "";
6420
+ const providerName = _optionalChain([provider, 'optionalAccess', _309 => _309.name, 'optionalAccess', _310 => _310.toLowerCase, 'call', _311 => _311()]) || "";
6358
6421
  const apiFormat = provider ? _chunkA2YMUCBTcjs.resolveApiFormat.call(void 0, provider) : "openai";
6359
6422
  if (apiFormat === "anthropic" || providerName === "anthropic" || providerName.includes("claude")) {
6360
6423
  const thinkingConfig = _thinkingconfig.buildAnthropicThinking.call(void 0, modelId, thinkLevel, maxTokens);
@@ -6391,7 +6454,7 @@ function logToolFormat(tools, logger) {
6391
6454
  tools: openaiTools.map((t) => t.function.name),
6392
6455
  firstTool: {
6393
6456
  name: firstTool.function.name,
6394
- description: _optionalChain([firstTool, 'access', _308 => _308.function, 'access', _309 => _309.description, 'optionalAccess', _310 => _310.slice, 'call', _311 => _311(0, 100)]),
6457
+ description: _optionalChain([firstTool, 'access', _312 => _312.function, 'access', _313 => _313.description, 'optionalAccess', _314 => _314.slice, 'call', _315 => _315(0, 100)]),
6395
6458
  parameters: firstTool.function.parameters
6396
6459
  }
6397
6460
  });
@@ -6402,7 +6465,7 @@ function logToolFormat(tools, logger) {
6402
6465
  tools: anthropicTools.map((t) => t.name),
6403
6466
  firstTool: {
6404
6467
  name: firstTool.name,
6405
- description: _optionalChain([firstTool, 'access', _312 => _312.description, 'optionalAccess', _313 => _313.slice, 'call', _314 => _314(0, 100)]),
6468
+ description: _optionalChain([firstTool, 'access', _316 => _316.description, 'optionalAccess', _317 => _317.slice, 'call', _318 => _318(0, 100)]),
6406
6469
  input_schema: firstTool.input_schema
6407
6470
  }
6408
6471
  });
@@ -6413,9 +6476,9 @@ function logToolFormat(tools, logger) {
6413
6476
  count: allDeclarations.length,
6414
6477
  tools: allDeclarations.map((t) => t.name),
6415
6478
  firstTool: {
6416
- name: _optionalChain([allDeclarations, 'access', _315 => _315[0], 'optionalAccess', _316 => _316.name]),
6417
- description: _optionalChain([allDeclarations, 'access', _317 => _317[0], 'optionalAccess', _318 => _318.description, 'optionalAccess', _319 => _319.slice, 'call', _320 => _320(0, 100)]),
6418
- parameters: _optionalChain([allDeclarations, 'access', _321 => _321[0], 'optionalAccess', _322 => _322.parameters])
6479
+ name: _optionalChain([allDeclarations, 'access', _319 => _319[0], 'optionalAccess', _320 => _320.name]),
6480
+ description: _optionalChain([allDeclarations, 'access', _321 => _321[0], 'optionalAccess', _322 => _322.description, 'optionalAccess', _323 => _323.slice, 'call', _324 => _324(0, 100)]),
6481
+ parameters: _optionalChain([allDeclarations, 'access', _325 => _325[0], 'optionalAccess', _326 => _326.parameters])
6419
6482
  }
6420
6483
  });
6421
6484
  }
@@ -6478,7 +6541,7 @@ function buildToolRequest(apiFormat, conversationMessages, actualModel, options,
6478
6541
  function extractDeltaContent(rawJson, apiFormat) {
6479
6542
  const json = rawJson;
6480
6543
  if (apiFormat === "google") {
6481
- const parts = _optionalChain([json, 'access', _323 => _323.candidates, 'optionalAccess', _324 => _324[0], 'optionalAccess', _325 => _325.content, 'optionalAccess', _326 => _326.parts]) || [];
6544
+ const parts = _optionalChain([json, 'access', _327 => _327.candidates, 'optionalAccess', _328 => _328[0], 'optionalAccess', _329 => _329.content, 'optionalAccess', _330 => _330.parts]) || [];
6482
6545
  let text = "";
6483
6546
  for (const part of parts) {
6484
6547
  if (part.thought === true) continue;
@@ -6486,15 +6549,15 @@ function extractDeltaContent(rawJson, apiFormat) {
6486
6549
  }
6487
6550
  return text;
6488
6551
  } else if (apiFormat === "anthropic") {
6489
- return _optionalChain([json, 'access', _327 => _327.delta, 'optionalAccess', _328 => _328.text]) || "";
6552
+ return _optionalChain([json, 'access', _331 => _331.delta, 'optionalAccess', _332 => _332.text]) || "";
6490
6553
  } else {
6491
- return _optionalChain([json, 'access', _329 => _329.choices, 'optionalAccess', _330 => _330[0], 'optionalAccess', _331 => _331.delta, 'optionalAccess', _332 => _332.content]) || "";
6554
+ return _optionalChain([json, 'access', _333 => _333.choices, 'optionalAccess', _334 => _334[0], 'optionalAccess', _335 => _335.delta, 'optionalAccess', _336 => _336.content]) || "";
6492
6555
  }
6493
6556
  }
6494
6557
  function extractDeltaReasoning(rawJson, apiFormat) {
6495
6558
  const json = rawJson;
6496
6559
  if (apiFormat === "google") {
6497
- const parts = _optionalChain([json, 'access', _333 => _333.candidates, 'optionalAccess', _334 => _334[0], 'optionalAccess', _335 => _335.content, 'optionalAccess', _336 => _336.parts]) || [];
6560
+ const parts = _optionalChain([json, 'access', _337 => _337.candidates, 'optionalAccess', _338 => _338[0], 'optionalAccess', _339 => _339.content, 'optionalAccess', _340 => _340.parts]) || [];
6498
6561
  let reasoning = "";
6499
6562
  for (const part of parts) {
6500
6563
  if (part.thought === true && part.text) reasoning += part.text;
@@ -6503,14 +6566,14 @@ function extractDeltaReasoning(rawJson, apiFormat) {
6503
6566
  } else if (apiFormat === "anthropic") {
6504
6567
  return "";
6505
6568
  } else {
6506
- const delta = _optionalChain([json, 'access', _337 => _337.choices, 'optionalAccess', _338 => _338[0], 'optionalAccess', _339 => _339.delta]);
6507
- return (_optionalChain([delta, 'optionalAccess', _340 => _340.thinking, 'optionalAccess', _341 => _341.content]) || "") + (_optionalChain([delta, 'optionalAccess', _342 => _342.reasoning_content]) || "");
6569
+ const delta = _optionalChain([json, 'access', _341 => _341.choices, 'optionalAccess', _342 => _342[0], 'optionalAccess', _343 => _343.delta]);
6570
+ return (_optionalChain([delta, 'optionalAccess', _344 => _344.thinking, 'optionalAccess', _345 => _345.content]) || "") + (_optionalChain([delta, 'optionalAccess', _346 => _346.reasoning_content]) || "");
6508
6571
  }
6509
6572
  }
6510
6573
  function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pendingOpenAIToolCalls) {
6511
6574
  const json = rawJson;
6512
6575
  if (apiFormat === "google") {
6513
- const parts = _optionalChain([json, 'access', _343 => _343.candidates, 'optionalAccess', _344 => _344[0], 'optionalAccess', _345 => _345.content, 'optionalAccess', _346 => _346.parts]) || [];
6576
+ const parts = _optionalChain([json, 'access', _347 => _347.candidates, 'optionalAccess', _348 => _348[0], 'optionalAccess', _349 => _349.content, 'optionalAccess', _350 => _350.parts]) || [];
6514
6577
  for (const part of parts) {
6515
6578
  if (part.functionCall) {
6516
6579
  logger.info("Function call detected", { functionCall: part.functionCall });
@@ -6520,13 +6583,13 @@ function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pend
6520
6583
  args: part.functionCall.args || {}
6521
6584
  };
6522
6585
  toolCalls.push(toolCall);
6523
- _optionalChain([callbacks, 'access', _347 => _347.onToolCall, 'optionalCall', _348 => _348(toolCall)]);
6586
+ _optionalChain([callbacks, 'access', _351 => _351.onToolCall, 'optionalCall', _352 => _352(toolCall)]);
6524
6587
  logger.info("Tool called", { toolName: toolCall.name });
6525
6588
  }
6526
6589
  }
6527
6590
  } else if (apiFormat !== "anthropic") {
6528
- const delta = _optionalChain([json, 'access', _349 => _349.choices, 'optionalAccess', _350 => _350[0], 'optionalAccess', _351 => _351.delta]);
6529
- if (_optionalChain([delta, 'optionalAccess', _352 => _352.tool_calls]) && pendingOpenAIToolCalls) {
6591
+ const delta = _optionalChain([json, 'access', _353 => _353.choices, 'optionalAccess', _354 => _354[0], 'optionalAccess', _355 => _355.delta]);
6592
+ if (_optionalChain([delta, 'optionalAccess', _356 => _356.tool_calls]) && pendingOpenAIToolCalls) {
6530
6593
  for (const tc of delta.tool_calls) {
6531
6594
  const index = _nullishCoalesce(tc.index, () => ( 0));
6532
6595
  let pending = pendingOpenAIToolCalls.get(index);
@@ -6535,8 +6598,8 @@ function extractToolCalls(rawJson, apiFormat, toolCalls, callbacks, logger, pend
6535
6598
  pendingOpenAIToolCalls.set(index, pending);
6536
6599
  }
6537
6600
  if (tc.id) pending.id = tc.id;
6538
- if (_optionalChain([tc, 'access', _353 => _353.function, 'optionalAccess', _354 => _354.name])) pending.name += tc.function.name;
6539
- if (_optionalChain([tc, 'access', _355 => _355.function, 'optionalAccess', _356 => _356.arguments])) pending.arguments += tc.function.arguments;
6601
+ if (_optionalChain([tc, 'access', _357 => _357.function, 'optionalAccess', _358 => _358.name])) pending.name += tc.function.name;
6602
+ if (_optionalChain([tc, 'access', _359 => _359.function, 'optionalAccess', _360 => _360.arguments])) pending.arguments += tc.function.arguments;
6540
6603
  }
6541
6604
  }
6542
6605
  }
@@ -6551,7 +6614,7 @@ function finalizeOpenAIToolCalls(pendingOpenAIToolCalls, toolCalls, callbacks, l
6551
6614
  args: JSON.parse(pending.arguments || "{}")
6552
6615
  };
6553
6616
  toolCalls.push(toolCall);
6554
- _optionalChain([callbacks, 'access', _357 => _357.onToolCall, 'optionalCall', _358 => _358(toolCall)]);
6617
+ _optionalChain([callbacks, 'access', _361 => _361.onToolCall, 'optionalCall', _362 => _362(toolCall)]);
6555
6618
  logger.info("Tool called (OpenAI)", { toolName: toolCall.name, args: toolCall.args });
6556
6619
  } catch (e) {
6557
6620
  logger.error("Failed to parse OpenAI tool call arguments", e instanceof Error ? e : void 0, {
@@ -6565,38 +6628,38 @@ function finalizeOpenAIToolCalls(pendingOpenAIToolCalls, toolCalls, callbacks, l
6565
6628
  function parseStreamChunk(rawJson, apiFormat, callbacks, logger) {
6566
6629
  const json = rawJson;
6567
6630
  if (apiFormat === "google") {
6568
- const candidate = _optionalChain([json, 'access', _359 => _359.candidates, 'optionalAccess', _360 => _360[0]]);
6631
+ const candidate = _optionalChain([json, 'access', _363 => _363.candidates, 'optionalAccess', _364 => _364[0]]);
6569
6632
  if (!candidate) {
6570
6633
  logger.warn("No candidate found in Gemini response");
6571
6634
  return;
6572
6635
  }
6573
- const parts = _optionalChain([candidate, 'access', _361 => _361.content, 'optionalAccess', _362 => _362.parts]) || [];
6636
+ const parts = _optionalChain([candidate, 'access', _365 => _365.content, 'optionalAccess', _366 => _366.parts]) || [];
6574
6637
  for (const part of parts) {
6575
6638
  if (part.thought === true && part.text) {
6576
- _optionalChain([callbacks, 'access', _363 => _363.onReasoning, 'optionalCall', _364 => _364(part.text)]);
6639
+ _optionalChain([callbacks, 'access', _367 => _367.onReasoning, 'optionalCall', _368 => _368(part.text)]);
6577
6640
  continue;
6578
6641
  } else if (part.thoughtSignature && !part.thought) {
6579
6642
  logger.debug("Gemini returned thoughtSignature without thought content");
6580
6643
  }
6581
6644
  if (part.text) {
6582
- _optionalChain([callbacks, 'access', _365 => _365.onDelta, 'optionalCall', _366 => _366(part.text)]);
6645
+ _optionalChain([callbacks, 'access', _369 => _369.onDelta, 'optionalCall', _370 => _370(part.text)]);
6583
6646
  }
6584
6647
  }
6585
6648
  } else if (apiFormat === "anthropic") {
6586
6649
  const delta = json.delta;
6587
- if (_optionalChain([delta, 'optionalAccess', _367 => _367.text])) {
6588
- _optionalChain([callbacks, 'access', _368 => _368.onDelta, 'optionalCall', _369 => _369(delta.text)]);
6650
+ if (_optionalChain([delta, 'optionalAccess', _371 => _371.text])) {
6651
+ _optionalChain([callbacks, 'access', _372 => _372.onDelta, 'optionalCall', _373 => _373(delta.text)]);
6589
6652
  }
6590
6653
  } else {
6591
- const delta = _optionalChain([json, 'access', _370 => _370.choices, 'optionalAccess', _371 => _371[0], 'optionalAccess', _372 => _372.delta]);
6592
- if (_optionalChain([delta, 'optionalAccess', _373 => _373.content])) {
6593
- _optionalChain([callbacks, 'access', _374 => _374.onDelta, 'optionalCall', _375 => _375(delta.content)]);
6654
+ const delta = _optionalChain([json, 'access', _374 => _374.choices, 'optionalAccess', _375 => _375[0], 'optionalAccess', _376 => _376.delta]);
6655
+ if (_optionalChain([delta, 'optionalAccess', _377 => _377.content])) {
6656
+ _optionalChain([callbacks, 'access', _378 => _378.onDelta, 'optionalCall', _379 => _379(delta.content)]);
6594
6657
  }
6595
- if (_optionalChain([delta, 'optionalAccess', _376 => _376.thinking, 'optionalAccess', _377 => _377.content])) {
6596
- _optionalChain([callbacks, 'access', _378 => _378.onReasoning, 'optionalCall', _379 => _379(delta.thinking.content)]);
6658
+ if (_optionalChain([delta, 'optionalAccess', _380 => _380.thinking, 'optionalAccess', _381 => _381.content])) {
6659
+ _optionalChain([callbacks, 'access', _382 => _382.onReasoning, 'optionalCall', _383 => _383(delta.thinking.content)]);
6597
6660
  }
6598
- if (_optionalChain([delta, 'optionalAccess', _380 => _380.reasoning_content])) {
6599
- _optionalChain([callbacks, 'access', _381 => _381.onReasoning, 'optionalCall', _382 => _382(delta.reasoning_content)]);
6661
+ if (_optionalChain([delta, 'optionalAccess', _384 => _384.reasoning_content])) {
6662
+ _optionalChain([callbacks, 'access', _385 => _385.onReasoning, 'optionalCall', _386 => _386(delta.reasoning_content)]);
6600
6663
  }
6601
6664
  }
6602
6665
  }
@@ -6609,7 +6672,7 @@ function buildIterationBlocks(iteration, content, reasoning, blocks, callbacks)
6609
6672
  content: reasoning
6610
6673
  };
6611
6674
  blocks.push(thinkingBlock);
6612
- _optionalChain([callbacks, 'access', _383 => _383.onBlock, 'optionalCall', _384 => _384(thinkingBlock)]);
6675
+ _optionalChain([callbacks, 'access', _387 => _387.onBlock, 'optionalCall', _388 => _388(thinkingBlock)]);
6613
6676
  }
6614
6677
  if (content && content.trim()) {
6615
6678
  const textBlock = {
@@ -6618,7 +6681,7 @@ function buildIterationBlocks(iteration, content, reasoning, blocks, callbacks)
6618
6681
  content
6619
6682
  };
6620
6683
  blocks.push(textBlock);
6621
- _optionalChain([callbacks, 'access', _385 => _385.onBlock, 'optionalCall', _386 => _386(textBlock)]);
6684
+ _optionalChain([callbacks, 'access', _389 => _389.onBlock, 'optionalCall', _390 => _390(textBlock)]);
6622
6685
  }
6623
6686
  }
6624
6687
  async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbacks, logger, builtinExecutor) {
@@ -6633,7 +6696,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6633
6696
  status: "running"
6634
6697
  };
6635
6698
  blocks.push(toolUseBlock);
6636
- _optionalChain([callbacks, 'access', _387 => _387.onBlock, 'optionalCall', _388 => _388(toolUseBlock)]);
6699
+ _optionalChain([callbacks, 'access', _391 => _391.onBlock, 'optionalCall', _392 => _392(toolUseBlock)]);
6637
6700
  try {
6638
6701
  logger.info("Executing tool", { toolName: toolCall.name });
6639
6702
  const mcpTool = mcpTools.find((t) => t.id === toolCall.name);
@@ -6656,8 +6719,8 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6656
6719
  result = { isError: true, content: [{ type: "text", text: "MCP service not available" }] };
6657
6720
  }
6658
6721
  logger.info("Tool result received", { result });
6659
- _optionalChain([callbacks, 'access', _389 => _389.onToolResult, 'optionalCall', _390 => _390(toolCall.id, result)]);
6660
- const resultText = _optionalChain([result, 'access', _391 => _391.content, 'optionalAccess', _392 => _392[0], 'optionalAccess', _393 => _393.text]) || JSON.stringify(result);
6722
+ _optionalChain([callbacks, 'access', _393 => _393.onToolResult, 'optionalCall', _394 => _394(toolCall.id, result)]);
6723
+ const resultText = _optionalChain([result, 'access', _395 => _395.content, 'optionalAccess', _396 => _396[0], 'optionalAccess', _397 => _397.text]) || JSON.stringify(result);
6661
6724
  const toolResultBlock = {
6662
6725
  id: `${toolCall.id}_result`,
6663
6726
  type: "tool_result",
@@ -6667,11 +6730,11 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6667
6730
  isError: result.isError
6668
6731
  };
6669
6732
  blocks.push(toolResultBlock);
6670
- _optionalChain([callbacks, 'access', _394 => _394.onBlock, 'optionalCall', _395 => _395(toolResultBlock)]);
6733
+ _optionalChain([callbacks, 'access', _398 => _398.onBlock, 'optionalCall', _399 => _399(toolResultBlock)]);
6671
6734
  const toolUseBlockRef = blocks.find((b) => b.id === `${toolCall.id}_use`);
6672
6735
  if (toolUseBlockRef && toolUseBlockRef.type === "tool_use") {
6673
6736
  toolUseBlockRef.status = result.isError ? "error" : "completed";
6674
- _optionalChain([callbacks, 'access', _396 => _396.onBlock, 'optionalCall', _397 => _397({ ...toolUseBlockRef })]);
6737
+ _optionalChain([callbacks, 'access', _400 => _400.onBlock, 'optionalCall', _401 => _401({ ...toolUseBlockRef })]);
6675
6738
  }
6676
6739
  toolResults.push({ toolCall, result });
6677
6740
  } catch (error) {
@@ -6681,7 +6744,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6681
6744
  isError: true,
6682
6745
  content: [{ type: "text", text: `Error: ${errorMessage}` }]
6683
6746
  };
6684
- _optionalChain([callbacks, 'access', _398 => _398.onToolResult, 'optionalCall', _399 => _399(toolCall.id, errorResult)]);
6747
+ _optionalChain([callbacks, 'access', _402 => _402.onToolResult, 'optionalCall', _403 => _403(toolCall.id, errorResult)]);
6685
6748
  const errorToolResultBlock = {
6686
6749
  id: `${toolCall.id}_result`,
6687
6750
  type: "tool_result",
@@ -6691,11 +6754,11 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6691
6754
  isError: true
6692
6755
  };
6693
6756
  blocks.push(errorToolResultBlock);
6694
- _optionalChain([callbacks, 'access', _400 => _400.onBlock, 'optionalCall', _401 => _401(errorToolResultBlock)]);
6757
+ _optionalChain([callbacks, 'access', _404 => _404.onBlock, 'optionalCall', _405 => _405(errorToolResultBlock)]);
6695
6758
  const errorToolUseBlockRef = blocks.find((b) => b.id === `${toolCall.id}_use`);
6696
6759
  if (errorToolUseBlockRef && errorToolUseBlockRef.type === "tool_use") {
6697
6760
  errorToolUseBlockRef.status = "error";
6698
- _optionalChain([callbacks, 'access', _402 => _402.onBlock, 'optionalCall', _403 => _403({ ...errorToolUseBlockRef })]);
6761
+ _optionalChain([callbacks, 'access', _406 => _406.onBlock, 'optionalCall', _407 => _407({ ...errorToolUseBlockRef })]);
6699
6762
  }
6700
6763
  toolResults.push({ toolCall, result: errorResult });
6701
6764
  }
@@ -6705,7 +6768,7 @@ async function executeToolCalls(toolCalls, mcpTools, mcpService, blocks, callbac
6705
6768
  function mapToolArguments(args, mcpTool, logger) {
6706
6769
  const mappedArgs = { ...args };
6707
6770
  const toolSchema = mcpTool.inputSchema;
6708
- if (_optionalChain([toolSchema, 'optionalAccess', _404 => _404.properties])) {
6771
+ if (_optionalChain([toolSchema, 'optionalAccess', _408 => _408.properties])) {
6709
6772
  const expectedParams = Object.keys(toolSchema.properties);
6710
6773
  const paramMappings = {
6711
6774
  "search_query": ["query", "q", "searchQuery", "search"],
@@ -6739,25 +6802,25 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
6739
6802
  options.providerId,
6740
6803
  options.model
6741
6804
  );
6742
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _405 => _405.actualProviderId]) || options.providerId;
6743
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _406 => _406.actualModelId]) || options.model;
6805
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _409 => _409.actualProviderId]) || options.providerId;
6806
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _410 => _410.actualModelId]) || options.model;
6744
6807
  const provider = await getProvider(actualProviderId);
6745
6808
  if (!provider) {
6746
- _optionalChain([callbacks, 'access', _407 => _407.onError, 'optionalCall', _408 => _408(`Provider not found: ${actualProviderId}`)]);
6809
+ _optionalChain([callbacks, 'access', _411 => _411.onError, 'optionalCall', _412 => _412(`Provider not found: ${actualProviderId}`)]);
6747
6810
  return;
6748
6811
  }
6749
6812
  if (!provider.enabled) {
6750
- _optionalChain([callbacks, 'access', _409 => _409.onError, 'optionalCall', _410 => _410(`Provider is disabled: ${provider.name}`)]);
6813
+ _optionalChain([callbacks, 'access', _413 => _413.onError, 'optionalCall', _414 => _414(`Provider is disabled: ${provider.name}`)]);
6751
6814
  return;
6752
6815
  }
6753
6816
  const { apiKey: effectiveKey } = _chunkA2YMUCBTcjs.resolveProviderEndpoint.call(void 0, provider);
6754
6817
  const apiKey = resolveApiKey2(effectiveKey);
6755
6818
  if (!apiKey) {
6756
- _optionalChain([callbacks, 'access', _411 => _411.onError, 'optionalCall', _412 => _412("API key not configured")]);
6819
+ _optionalChain([callbacks, 'access', _415 => _415.onError, 'optionalCall', _416 => _416("API key not configured")]);
6757
6820
  return;
6758
6821
  }
6759
6822
  const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
6760
- _optionalChain([callbacks, 'access', _413 => _413.onStart, 'optionalCall', _414 => _414(messageId)]);
6823
+ _optionalChain([callbacks, 'access', _417 => _417.onStart, 'optionalCall', _418 => _418(messageId)]);
6761
6824
  const globalParams = await llmConfig.getGlobalModelParameters();
6762
6825
  const MAX_ITERATIONS = _nullishCoalesce(globalParams.toolMaxTurns, () => ( 100));
6763
6826
  let iteration = 0;
@@ -6804,12 +6867,12 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
6804
6867
  });
6805
6868
  if (!response.ok) {
6806
6869
  const errorText = await response.text();
6807
- _optionalChain([callbacks, 'access', _415 => _415.onError, 'optionalCall', _416 => _416(`API error (${response.status}): ${errorText}`)]);
6870
+ _optionalChain([callbacks, 'access', _419 => _419.onError, 'optionalCall', _420 => _420(`API error (${response.status}): ${errorText}`)]);
6808
6871
  return;
6809
6872
  }
6810
- const reader = _optionalChain([response, 'access', _417 => _417.body, 'optionalAccess', _418 => _418.getReader, 'call', _419 => _419()]);
6873
+ const reader = _optionalChain([response, 'access', _421 => _421.body, 'optionalAccess', _422 => _422.getReader, 'call', _423 => _423()]);
6811
6874
  if (!reader) {
6812
- _optionalChain([callbacks, 'access', _420 => _420.onError, 'optionalCall', _421 => _421("No response body")]);
6875
+ _optionalChain([callbacks, 'access', _424 => _424.onError, 'optionalCall', _425 => _425("No response body")]);
6813
6876
  return;
6814
6877
  }
6815
6878
  const decoder = new TextDecoder();
@@ -6842,7 +6905,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
6842
6905
  logger.debug("Parsed JSON", { json });
6843
6906
  if (json.error) {
6844
6907
  logger.error("API Error", void 0, { error: json.error });
6845
- _optionalChain([callbacks, 'access', _422 => _422.onError, 'optionalCall', _423 => _423(`API Error: ${json.error.message || JSON.stringify(json.error)}`)]);
6908
+ _optionalChain([callbacks, 'access', _426 => _426.onError, 'optionalCall', _427 => _427(`API Error: ${json.error.message || JSON.stringify(json.error)}`)]);
6846
6909
  return;
6847
6910
  }
6848
6911
  parseStreamChunk(json, apiFormat, callbacks, logger);
@@ -6875,7 +6938,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
6875
6938
  toolCallsLength: toolCalls.length,
6876
6939
  executableToolCallsLength: executableToolCalls.length,
6877
6940
  hasMcpTools: !!options.mcpTools,
6878
- mcpToolsLength: _optionalChain([options, 'access', _424 => _424.mcpTools, 'optionalAccess', _425 => _425.length]),
6941
+ mcpToolsLength: _optionalChain([options, 'access', _428 => _428.mcpTools, 'optionalAccess', _429 => _429.length]),
6879
6942
  hasMcpService: !!mcpService
6880
6943
  });
6881
6944
  if (executableToolCalls.length > 0 && options.mcpTools && (mcpService || builtinExecutor)) {
@@ -6896,7 +6959,7 @@ async function streamWithTools(options, callbacks, mcpService, llmConfig, getPro
6896
6959
  builtinExecutor
6897
6960
  );
6898
6961
  const toolResultsText = toolResults.map(({ toolCall, result }) => {
6899
- const resultText = typeof result === "string" ? result : _optionalChain([result, 'access', _426 => _426.content, 'optionalAccess', _427 => _427[0], 'optionalAccess', _428 => _428.text]) || JSON.stringify(result);
6962
+ const resultText = typeof result === "string" ? result : _optionalChain([result, 'access', _430 => _430.content, 'optionalAccess', _431 => _431[0], 'optionalAccess', _432 => _432.text]) || JSON.stringify(result);
6900
6963
  return `Tool ${toolCall.name} result:
6901
6964
  ${resultText}`;
6902
6965
  }).join("\n\n");
@@ -6914,12 +6977,12 @@ ${resultText}`;
6914
6977
  }
6915
6978
  } catch (streamError) {
6916
6979
  logger.error("Stream processing error", streamError instanceof Error ? streamError : void 0);
6917
- _optionalChain([callbacks, 'access', _429 => _429.onError, 'optionalCall', _430 => _430(`Stream error: ${streamError instanceof Error ? streamError.message : "Unknown error"}`)]);
6980
+ _optionalChain([callbacks, 'access', _433 => _433.onError, 'optionalCall', _434 => _434(`Stream error: ${streamError instanceof Error ? streamError.message : "Unknown error"}`)]);
6918
6981
  return;
6919
6982
  }
6920
6983
  }
6921
6984
  logger.info("Sending final callback", { blocksCount: blocks.length });
6922
- _optionalChain([callbacks, 'access', _431 => _431.onDone, 'optionalCall', _432 => _432({
6985
+ _optionalChain([callbacks, 'access', _435 => _435.onDone, 'optionalCall', _436 => _436({
6923
6986
  id: messageId,
6924
6987
  role: "assistant",
6925
6988
  content: finalContent,
@@ -6930,7 +6993,7 @@ ${resultText}`;
6930
6993
  } catch (error) {
6931
6994
  logger.error("Error in streamWithTools", error instanceof Error ? error : void 0);
6932
6995
  const message = error instanceof Error ? error.message : "Unknown error";
6933
- _optionalChain([callbacks, 'access', _433 => _433.onError, 'optionalCall', _434 => _434(message)]);
6996
+ _optionalChain([callbacks, 'access', _437 => _437.onError, 'optionalCall', _438 => _438(message)]);
6934
6997
  }
6935
6998
  }
6936
6999
 
@@ -6981,8 +7044,8 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
6981
7044
  options.providerId,
6982
7045
  options.model
6983
7046
  );
6984
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _435 => _435.actualProviderId]) || options.providerId;
6985
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _436 => _436.actualModelId]) || options.model;
7047
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _439 => _439.actualProviderId]) || options.providerId;
7048
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _440 => _440.actualModelId]) || options.model;
6986
7049
  const provider = await getProvider(actualProviderId);
6987
7050
  if (!provider) {
6988
7051
  return { success: false, error: `Provider not found: ${actualProviderId}` };
@@ -7059,18 +7122,18 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
7059
7122
  { endpointTransformer: void 0 }
7060
7123
  );
7061
7124
  const data = await transformedResponse.json();
7062
- const choice = _optionalChain([data, 'access', _437 => _437.choices, 'optionalAccess', _438 => _438[0]]);
7125
+ const choice = _optionalChain([data, 'access', _441 => _441.choices, 'optionalAccess', _442 => _442[0]]);
7063
7126
  if (!choice) {
7064
7127
  return { success: false, error: "No choices in response" };
7065
7128
  }
7066
- const rawToolCalls = _optionalChain([choice, 'access', _439 => _439.message, 'optionalAccess', _440 => _440.tool_calls]);
7067
- const toolCalls = _optionalChain([rawToolCalls, 'optionalAccess', _441 => _441.map, 'call', _442 => _442((tc) => ({
7129
+ const rawToolCalls = _optionalChain([choice, 'access', _443 => _443.message, 'optionalAccess', _444 => _444.tool_calls]);
7130
+ const toolCalls = _optionalChain([rawToolCalls, 'optionalAccess', _445 => _445.map, 'call', _446 => _446((tc) => ({
7068
7131
  id: tc.id,
7069
7132
  name: tc.function.name,
7070
7133
  args: typeof tc.function.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function.arguments
7071
7134
  }))]);
7072
7135
  const tapped = readUsageFromOpenAIResponse(data.usage);
7073
- if (_optionalChain([recording, 'optionalAccess', _443 => _443.recorder]) && tapped) {
7136
+ if (_optionalChain([recording, 'optionalAccess', _447 => _447.recorder]) && tapped) {
7074
7137
  recording.recorder.record({
7075
7138
  messageId: _nullishCoalesce(options.messageId, () => ( null)),
7076
7139
  parentMessageId: _nullishCoalesce(options.parentMessageId, () => ( null)),
@@ -7088,9 +7151,9 @@ async function completeWithTransformers(options, llmConfig, getProvider, resolve
7088
7151
  message: {
7089
7152
  id: `msg_${Date.now()}`,
7090
7153
  role: "assistant",
7091
- content: _optionalChain([choice, 'access', _444 => _444.message, 'optionalAccess', _445 => _445.content]) || "",
7154
+ content: _optionalChain([choice, 'access', _448 => _448.message, 'optionalAccess', _449 => _449.content]) || "",
7092
7155
  timestamp: Date.now(),
7093
- thinking: data.reasoning_content || _optionalChain([choice, 'access', _446 => _446.message, 'optionalAccess', _447 => _447.thinking, 'optionalAccess', _448 => _448.content]) ? { content: data.reasoning_content || _optionalChain([choice, 'access', _449 => _449.message, 'optionalAccess', _450 => _450.thinking, 'optionalAccess', _451 => _451.content]) || "", signature: _optionalChain([choice, 'access', _452 => _452.message, 'optionalAccess', _453 => _453.thinking, 'optionalAccess', _454 => _454.signature]) } : void 0,
7156
+ thinking: data.reasoning_content || _optionalChain([choice, 'access', _450 => _450.message, 'optionalAccess', _451 => _451.thinking, 'optionalAccess', _452 => _452.content]) ? { content: data.reasoning_content || _optionalChain([choice, 'access', _453 => _453.message, 'optionalAccess', _454 => _454.thinking, 'optionalAccess', _455 => _455.content]) || "", signature: _optionalChain([choice, 'access', _456 => _456.message, 'optionalAccess', _457 => _457.thinking, 'optionalAccess', _458 => _458.signature]) } : void 0,
7094
7157
  toolCalls
7095
7158
  },
7096
7159
  usage: data.usage ? {
@@ -7111,21 +7174,21 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7111
7174
  options.providerId,
7112
7175
  options.model
7113
7176
  );
7114
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _455 => _455.actualProviderId]) || options.providerId;
7115
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _456 => _456.actualModelId]) || options.model;
7177
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _459 => _459.actualProviderId]) || options.providerId;
7178
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _460 => _460.actualModelId]) || options.model;
7116
7179
  const provider = await getProvider(actualProviderId);
7117
7180
  if (!provider) {
7118
- _optionalChain([callbacks, 'access', _457 => _457.onError, 'optionalCall', _458 => _458(`Provider not found: ${actualProviderId}`)]);
7181
+ _optionalChain([callbacks, 'access', _461 => _461.onError, 'optionalCall', _462 => _462(`Provider not found: ${actualProviderId}`)]);
7119
7182
  return;
7120
7183
  }
7121
7184
  if (!provider.enabled) {
7122
- _optionalChain([callbacks, 'access', _459 => _459.onError, 'optionalCall', _460 => _460(`Provider is disabled: ${provider.name}`)]);
7185
+ _optionalChain([callbacks, 'access', _463 => _463.onError, 'optionalCall', _464 => _464(`Provider is disabled: ${provider.name}`)]);
7123
7186
  return;
7124
7187
  }
7125
7188
  const { apiKey: effectiveKey } = _chunkA2YMUCBTcjs.resolveProviderEndpoint.call(void 0, provider);
7126
7189
  const apiKey = resolveApiKey2(effectiveKey);
7127
7190
  if (!apiKey) {
7128
- _optionalChain([callbacks, 'access', _461 => _461.onError, 'optionalCall', _462 => _462("API key not configured")]);
7191
+ _optionalChain([callbacks, 'access', _465 => _465.onError, 'optionalCall', _466 => _466("API key not configured")]);
7129
7192
  return;
7130
7193
  }
7131
7194
  const { chain, hasTransformers } = await resolveChainWithMain(
@@ -7137,7 +7200,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7137
7200
  return completeStreamFallback(options, callbacks);
7138
7201
  }
7139
7202
  const messageId = `msg_${Date.now()}`;
7140
- _optionalChain([callbacks, 'access', _463 => _463.onStart, 'optionalCall', _464 => _464(messageId)]);
7203
+ _optionalChain([callbacks, 'access', _467 => _467.onStart, 'optionalCall', _468 => _468(messageId)]);
7141
7204
  const unifiedRequest = buildUnifiedCompletionRequest(actualModel, options, true);
7142
7205
  const transformerProvider = {
7143
7206
  name: provider.name,
@@ -7177,7 +7240,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7177
7240
  });
7178
7241
  if (!response.ok) {
7179
7242
  const errorText = await response.text();
7180
- _optionalChain([callbacks, 'access', _465 => _465.onError, 'optionalCall', _466 => _466(`API error (${response.status}): ${errorText}`)]);
7243
+ _optionalChain([callbacks, 'access', _469 => _469.onError, 'optionalCall', _470 => _470(`API error (${response.status}): ${errorText}`)]);
7181
7244
  return;
7182
7245
  }
7183
7246
  const transformedResponse = await executor.executeResponseChain(
@@ -7187,9 +7250,9 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7187
7250
  chain,
7188
7251
  { endpointTransformer: void 0 }
7189
7252
  );
7190
- const reader = _optionalChain([transformedResponse, 'access', _467 => _467.body, 'optionalAccess', _468 => _468.getReader, 'call', _469 => _469()]);
7253
+ const reader = _optionalChain([transformedResponse, 'access', _471 => _471.body, 'optionalAccess', _472 => _472.getReader, 'call', _473 => _473()]);
7191
7254
  if (!reader) {
7192
- _optionalChain([callbacks, 'access', _470 => _470.onError, 'optionalCall', _471 => _471("No response body")]);
7255
+ _optionalChain([callbacks, 'access', _474 => _474.onError, 'optionalCall', _475 => _475("No response body")]);
7193
7256
  return;
7194
7257
  }
7195
7258
  const decoder = new TextDecoder();
@@ -7207,22 +7270,22 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7207
7270
  if (data === "[DONE]") continue;
7208
7271
  try {
7209
7272
  const json = JSON.parse(data);
7210
- const delta = _optionalChain([json, 'access', _472 => _472.choices, 'optionalAccess', _473 => _473[0], 'optionalAccess', _474 => _474.delta]);
7211
- if (_optionalChain([delta, 'optionalAccess', _475 => _475.content])) {
7273
+ const delta = _optionalChain([json, 'access', _476 => _476.choices, 'optionalAccess', _477 => _477[0], 'optionalAccess', _478 => _478.delta]);
7274
+ if (_optionalChain([delta, 'optionalAccess', _479 => _479.content])) {
7212
7275
  content += delta.content;
7213
- _optionalChain([callbacks, 'access', _476 => _476.onDelta, 'optionalCall', _477 => _477(delta.content)]);
7276
+ _optionalChain([callbacks, 'access', _480 => _480.onDelta, 'optionalCall', _481 => _481(delta.content)]);
7214
7277
  }
7215
- if (_optionalChain([delta, 'optionalAccess', _478 => _478.thinking, 'optionalAccess', _479 => _479.content])) {
7278
+ if (_optionalChain([delta, 'optionalAccess', _482 => _482.thinking, 'optionalAccess', _483 => _483.content])) {
7216
7279
  reasoning += delta.thinking.content;
7217
- _optionalChain([callbacks, 'access', _480 => _480.onReasoning, 'optionalCall', _481 => _481(delta.thinking.content)]);
7280
+ _optionalChain([callbacks, 'access', _484 => _484.onReasoning, 'optionalCall', _485 => _485(delta.thinking.content)]);
7218
7281
  }
7219
- if (_optionalChain([delta, 'optionalAccess', _482 => _482.reasoning_content])) {
7282
+ if (_optionalChain([delta, 'optionalAccess', _486 => _486.reasoning_content])) {
7220
7283
  reasoning += delta.reasoning_content;
7221
- _optionalChain([callbacks, 'access', _483 => _483.onReasoning, 'optionalCall', _484 => _484(delta.reasoning_content)]);
7284
+ _optionalChain([callbacks, 'access', _487 => _487.onReasoning, 'optionalCall', _488 => _488(delta.reasoning_content)]);
7222
7285
  }
7223
7286
  if (json.usage) {
7224
7287
  const tapped = readUsageFromOpenAIResponse(json.usage);
7225
- if (_optionalChain([recording, 'optionalAccess', _485 => _485.recorder]) && tapped) {
7288
+ if (_optionalChain([recording, 'optionalAccess', _489 => _489.recorder]) && tapped) {
7226
7289
  recording.recorder.record({
7227
7290
  messageId: _nullishCoalesce(options.messageId, () => ( null)),
7228
7291
  parentMessageId: _nullishCoalesce(options.parentMessageId, () => ( null)),
@@ -7235,7 +7298,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7235
7298
  rawUsage: json.usage
7236
7299
  });
7237
7300
  }
7238
- _optionalChain([callbacks, 'access', _486 => _486.onDone, 'optionalCall', _487 => _487(
7301
+ _optionalChain([callbacks, 'access', _490 => _490.onDone, 'optionalCall', _491 => _491(
7239
7302
  {
7240
7303
  id: messageId,
7241
7304
  role: "assistant",
@@ -7256,7 +7319,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7256
7319
  }
7257
7320
  }
7258
7321
  }
7259
- _optionalChain([callbacks, 'access', _488 => _488.onDone, 'optionalCall', _489 => _489({
7322
+ _optionalChain([callbacks, 'access', _492 => _492.onDone, 'optionalCall', _493 => _493({
7260
7323
  id: messageId,
7261
7324
  role: "assistant",
7262
7325
  content,
@@ -7268,7 +7331,7 @@ async function completeStreamWithTransformers(options, callbacks, llmConfig, get
7268
7331
  }
7269
7332
  } catch (error) {
7270
7333
  const message = error instanceof Error ? error.message : "Unknown error";
7271
- _optionalChain([callbacks, 'access', _490 => _490.onError, 'optionalCall', _491 => _491(message)]);
7334
+ _optionalChain([callbacks, 'access', _494 => _494.onError, 'optionalCall', _495 => _495(message)]);
7272
7335
  }
7273
7336
  }
7274
7337
 
@@ -7335,8 +7398,8 @@ var CompletionService = (_class15 = class {
7335
7398
  options.providerId,
7336
7399
  options.model
7337
7400
  );
7338
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _492 => _492.actualProviderId]) || options.providerId;
7339
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _493 => _493.actualModelId]) || options.model;
7401
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _496 => _496.actualProviderId]) || options.providerId;
7402
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _497 => _497.actualModelId]) || options.model;
7340
7403
  const provider = await this.getProvider(actualProviderId);
7341
7404
  if (!provider) {
7342
7405
  return { success: false, error: `Provider not found: ${actualProviderId}` };
@@ -7369,7 +7432,7 @@ var CompletionService = (_class15 = class {
7369
7432
  this.apiKeyPool.reportSuccess(options.sessionId);
7370
7433
  }
7371
7434
  if (result.success && result.usage && options.sessionId) {
7372
- _optionalChain([this, 'access', _494 => _494.usageEventSink, 'optionalAccess', _495 => _495.emit, 'call', _496 => _496({
7435
+ _optionalChain([this, 'access', _498 => _498.usageEventSink, 'optionalAccess', _499 => _499.emit, 'call', _500 => _500({
7373
7436
  sessionId: options.sessionId,
7374
7437
  modelId: actualModel,
7375
7438
  usage: result.usage,
@@ -7398,8 +7461,8 @@ var CompletionService = (_class15 = class {
7398
7461
  options.model
7399
7462
  );
7400
7463
  this.logger.debug("Resolved routed model", { routedInfo });
7401
- const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _497 => _497.actualProviderId]) || options.providerId;
7402
- const actualModel = _optionalChain([routedInfo, 'optionalAccess', _498 => _498.actualModelId]) || options.model;
7464
+ const actualProviderId = _optionalChain([routedInfo, 'optionalAccess', _501 => _501.actualProviderId]) || options.providerId;
7465
+ const actualModel = _optionalChain([routedInfo, 'optionalAccess', _502 => _502.actualModelId]) || options.model;
7403
7466
  this.logger.debug("Resolved provider and model", { actualProviderId, actualModel });
7404
7467
  const provider = await this.getProvider(actualProviderId);
7405
7468
  this.logger.debug("Retrieved provider", provider ? {
@@ -7411,22 +7474,22 @@ var CompletionService = (_class15 = class {
7411
7474
  enabled: provider.enabled
7412
7475
  } : { error: "Provider not found" });
7413
7476
  if (!provider) {
7414
- _optionalChain([callbacks, 'access', _499 => _499.onError, 'optionalCall', _500 => _500(`Provider not found: ${actualProviderId}`)]);
7477
+ _optionalChain([callbacks, 'access', _503 => _503.onError, 'optionalCall', _504 => _504(`Provider not found: ${actualProviderId}`)]);
7415
7478
  return;
7416
7479
  }
7417
7480
  if (!provider.enabled) {
7418
- _optionalChain([callbacks, 'access', _501 => _501.onError, 'optionalCall', _502 => _502(`Provider is disabled: ${provider.name}`)]);
7481
+ _optionalChain([callbacks, 'access', _505 => _505.onError, 'optionalCall', _506 => _506(`Provider is disabled: ${provider.name}`)]);
7419
7482
  return;
7420
7483
  }
7421
7484
  const apiKey = await this.resolveApiKeyForRequest(provider, actualProviderId, options.sessionId);
7422
7485
  if (!apiKey) {
7423
- _optionalChain([callbacks, 'access', _503 => _503.onError, 'optionalCall', _504 => _504("API key not configured")]);
7486
+ _optionalChain([callbacks, 'access', _507 => _507.onError, 'optionalCall', _508 => _508("API key not configured")]);
7424
7487
  return;
7425
7488
  }
7426
7489
  const apiFormat = _chunkA2YMUCBTcjs.resolveApiFormat.call(void 0, provider);
7427
7490
  this.logger.info("Using API format for stream", { apiFormat });
7428
7491
  const messageId = `msg_${Date.now()}`;
7429
- _optionalChain([callbacks, 'access', _505 => _505.onStart, 'optionalCall', _506 => _506(messageId)]);
7492
+ _optionalChain([callbacks, 'access', _509 => _509.onStart, 'optionalCall', _510 => _510(messageId)]);
7430
7493
  const resolvedOptions = { ...options, model: actualModel };
7431
7494
  if (options.sessionId) {
7432
7495
  const sid = options.sessionId;
@@ -7435,14 +7498,14 @@ var CompletionService = (_class15 = class {
7435
7498
  ...callbacks,
7436
7499
  onDone: (message, usage, metrics) => {
7437
7500
  if (usage) {
7438
- _optionalChain([this, 'access', _507 => _507.usageEventSink, 'optionalAccess', _508 => _508.emit, 'call', _509 => _509({
7501
+ _optionalChain([this, 'access', _511 => _511.usageEventSink, 'optionalAccess', _512 => _512.emit, 'call', _513 => _513({
7439
7502
  sessionId: sid,
7440
7503
  modelId: actualModel,
7441
7504
  usage,
7442
7505
  engineOrigin: "completion"
7443
7506
  })]);
7444
7507
  }
7445
- _optionalChain([userOnDone, 'optionalCall', _510 => _510(message, usage, metrics)]);
7508
+ _optionalChain([userOnDone, 'optionalCall', _514 => _514(message, usage, metrics)]);
7446
7509
  }
7447
7510
  };
7448
7511
  }
@@ -7458,11 +7521,11 @@ var CompletionService = (_class15 = class {
7458
7521
  retryState.error = { status, message: error };
7459
7522
  return;
7460
7523
  }
7461
- _optionalChain([callbacks, 'access', _511 => _511.onError, 'optionalCall', _512 => _512(error)]);
7524
+ _optionalChain([callbacks, 'access', _515 => _515.onError, 'optionalCall', _516 => _516(error)]);
7462
7525
  },
7463
7526
  onDone: (message, usage, metrics) => {
7464
7527
  this.apiKeyPool.reportSuccess(options.sessionId);
7465
- _optionalChain([callbacks, 'access', _513 => _513.onDone, 'optionalCall', _514 => _514(message, usage, metrics)]);
7528
+ _optionalChain([callbacks, 'access', _517 => _517.onDone, 'optionalCall', _518 => _518(message, usage, metrics)]);
7466
7529
  }
7467
7530
  };
7468
7531
  await this.callStreamHandler(apiFormat, provider, apiKey, resolvedOptions, messageId, interceptCallbacks);
@@ -7483,7 +7546,7 @@ var CompletionService = (_class15 = class {
7483
7546
  // don't fire onStart again
7484
7547
  });
7485
7548
  } else {
7486
- _optionalChain([callbacks, 'access', _515 => _515.onError, 'optionalCall', _516 => _516(retryState.error.message)]);
7549
+ _optionalChain([callbacks, 'access', _519 => _519.onError, 'optionalCall', _520 => _520(retryState.error.message)]);
7487
7550
  }
7488
7551
  }
7489
7552
  } else {
@@ -7496,7 +7559,7 @@ var CompletionService = (_class15 = class {
7496
7559
  } catch (error) {
7497
7560
  const message = error instanceof Error ? error.message : "Unknown error";
7498
7561
  this.logger.error("Stream completion error", error instanceof Error ? error : void 0, { message });
7499
- _optionalChain([callbacks, 'access', _517 => _517.onError, 'optionalCall', _518 => _518(message)]);
7562
+ _optionalChain([callbacks, 'access', _521 => _521.onError, 'optionalCall', _522 => _522(message)]);
7500
7563
  }
7501
7564
  }
7502
7565
  /**
@@ -7536,7 +7599,7 @@ var CompletionService = (_class15 = class {
7536
7599
  return {
7537
7600
  success: true,
7538
7601
  message: "Connection successful",
7539
- response: _optionalChain([result, 'access', _519 => _519.message, 'optionalAccess', _520 => _520.content]) || "",
7602
+ response: _optionalChain([result, 'access', _523 => _523.message, 'optionalAccess', _524 => _524.content]) || "",
7540
7603
  model: modelId,
7541
7604
  durationMs
7542
7605
  };
@@ -7601,7 +7664,7 @@ ${description}`;
7601
7664
  * 3. Legacy single key from provider config
7602
7665
  */
7603
7666
  async resolveApiKeyForRequest(provider, providerId, sessionId) {
7604
- if (_optionalChain([provider, 'access', _521 => _521.codingPlan, 'optionalAccess', _522 => _522.enabled]) && provider.codingPlan.apiKey) {
7667
+ if (_optionalChain([provider, 'access', _525 => _525.codingPlan, 'optionalAccess', _526 => _526.enabled]) && provider.codingPlan.apiKey) {
7605
7668
  return this.resolveApiKey(provider.codingPlan.apiKey);
7606
7669
  }
7607
7670
  if (this.apiKeyPool) {