dal-code 1.0.55 → 1.0.57

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 (177) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/bundle/chunks/{anthropic-messages-LJWWEQIU.js → anthropic-messages-ASQGS6BL.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-GK4VH6GM.js → azure-openai-responses-ZSCUJBSU.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-DBT5OS5V.js → chunk-2E7RGBKM.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-3ANBT7AT.js → chunk-34D4KVPX.js} +1 -1
  7. package/dist/bundle/chunks/chunk-6PQZ4KMC.js +17 -0
  8. package/dist/bundle/chunks/chunk-6SPX3U36.js +1 -0
  9. package/dist/bundle/chunks/{chunk-DWMC4U2M.js → chunk-F577XLVZ.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-6U37J6E7.js → chunk-FSX34SAZ.js} +340 -366
  11. package/dist/bundle/chunks/chunk-G5AMLGXC.js +1 -0
  12. package/dist/bundle/chunks/{chunk-44EXLOHK.js → chunk-GPI2GHBH.js} +1 -1
  13. package/dist/bundle/chunks/chunk-HF334NQU.js +21 -0
  14. package/dist/bundle/chunks/{chunk-5TGFM4KW.js → chunk-IRSW3MVW.js} +2 -2
  15. package/dist/bundle/chunks/chunk-JPBJUBY4.js +17 -0
  16. package/dist/bundle/chunks/chunk-JPCWLZUZ.js +30 -0
  17. package/dist/bundle/chunks/chunk-JUUJCOIR.js +7 -0
  18. package/dist/bundle/chunks/{chunk-KSF7BFGS.js → chunk-KP7CMLOT.js} +1 -1
  19. package/dist/bundle/chunks/chunk-LZTZWS3N.js +9 -0
  20. package/dist/bundle/chunks/{chunk-ZYP3V3TD.js → chunk-MAJODFX6.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-SNBVCTMQ.js → chunk-MZ7O6YLD.js} +3 -3
  22. package/dist/bundle/chunks/chunk-NJDCSLWK.js +1 -0
  23. package/dist/bundle/chunks/{chunk-SCSGNIU5.js → chunk-O3XFDBJ3.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-2XX4WZT6.js → chunk-PD6QS7YD.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-SMPERFJU.js → chunk-S7K3JBWA.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-PRBATF6B.js → chunk-TNSXMGQB.js} +1 -1
  27. package/dist/bundle/chunks/chunk-XIJS4F22.js +14 -0
  28. package/dist/bundle/chunks/{chunk-GX37DI5S.js → chunk-YTDTROS5.js} +1 -1
  29. package/dist/bundle/chunks/{cli-Z44UHMMU.js → cli-IDAZVEZ2.js} +1 -1
  30. package/dist/bundle/chunks/{cli-VKNCK5P5.js → cli-NP7QEFQE.js} +1 -1
  31. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-G4E4L26A.js → cloudflare-workers-ai-system-one-WLKVTF6I.js} +1 -1
  32. package/dist/bundle/chunks/{execute-3FWM3EMV.js → execute-VXSJSHXH.js} +2 -2
  33. package/dist/bundle/chunks/github-copilot.js +1 -1
  34. package/dist/bundle/chunks/{google-generative-ai-HVFDKPI3.js → google-generative-ai-3HIBMVL4.js} +1 -1
  35. package/dist/bundle/chunks/{google-vertex-6E4HATAC.js → google-vertex-7PIUZFM3.js} +1 -1
  36. package/dist/bundle/chunks/{llama-cpp-classify-3HAEJDKO.js → llama-cpp-classify-5OLOZHKT.js} +1 -1
  37. package/dist/bundle/chunks/mcp-GHYUCPI4.js +10 -0
  38. package/dist/bundle/chunks/{mistral-conversations-6UC2WYUC.js → mistral-conversations-6Y33SI3U.js} +1 -1
  39. package/dist/bundle/chunks/{office-2F4B572E.js → office-2JSKOL7V.js} +1 -1
  40. package/dist/bundle/chunks/{openai-codex-responses-WPSZR4EE.js → openai-codex-responses-BYGMMTPH.js} +1 -1
  41. package/dist/bundle/chunks/{openai-completions-2RGIFVKJ.js → openai-completions-UWYQMOLR.js} +1 -1
  42. package/dist/bundle/chunks/{openai-decisions-BLZVYNRQ.js → openai-decisions-I5J7OD62.js} +1 -1
  43. package/dist/bundle/chunks/{openai-responses-N65DO7MB.js → openai-responses-LWVKQGLT.js} +1 -1
  44. package/dist/bundle/chunks/{openrouter-images-LQ4VP5P7.js → openrouter-images-BDUFN6XX.js} +1 -1
  45. package/dist/bundle/chunks/{pi-messages-VYTRLMVB.js → pi-messages-64FHWMQR.js} +1 -1
  46. package/dist/bundle/chunks/{review-MKITXKSI.js → review-OQEOVDLP.js} +2 -2
  47. package/dist/bundle/chunks/{router-RL7OYANY.js → router-3UQE4LBN.js} +1 -1
  48. package/dist/bundle/chunks/runtime-E7KOB62K.js +1 -0
  49. package/dist/bundle/chunks/sdk-5V64WBOZ.js +1 -0
  50. package/dist/bundle/chunks/sync-INSWGFSB.js +21 -0
  51. package/dist/bundle/chunks/{typesafe-system-one-6ZFGVJMV.js → typesafe-system-one-7QFJ5JNW.js} +1 -1
  52. package/dist/bundle/chunks/usage-MG7QDPG2.js +1 -0
  53. package/dist/bundle/chunks/virtual-modules-73ZLFCNE.js +1 -0
  54. package/dist/bundle/cli-runtime.js +1 -1
  55. package/dist/bundle/index.js +1 -1
  56. package/dist/bundle/rpc-entry.js +1 -1
  57. package/dist/core/agent-session-runtime.d.ts +1 -0
  58. package/dist/core/agent-session-runtime.js +1 -1
  59. package/dist/core/headless-approver.d.ts +3 -0
  60. package/dist/core/headless-approver.js +1 -0
  61. package/dist/dal/manifest.js +1 -1
  62. package/dist/index.d.ts +2 -1
  63. package/dist/index.js +1 -1
  64. package/dist/main.js +3 -3
  65. package/dist/modes/acp/acp-mapping.js +3 -2
  66. package/dist/modes/acp/acp-mode.js +1 -1
  67. package/dist/modes/acp/acp-permissions.js +1 -0
  68. package/dist/modes/acp/acp-session-options.d.ts +24 -0
  69. package/dist/modes/acp/acp-session-options.js +3 -0
  70. package/dist/modes/index.d.ts +1 -0
  71. package/dist/modes/index.js +1 -1
  72. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  73. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  74. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  75. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  76. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  77. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  78. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  81. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  82. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
  83. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  84. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  85. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  86. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  87. package/dist/node_modules/@dalcode/dal-learn/src/store.js +3 -3
  88. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  89. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  90. package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
  91. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +16 -16
  92. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +2 -0
  93. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  94. package/dist/node_modules/@dalcode/dal-pi-kit/dist/agent-dir.js +1 -0
  95. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  96. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  97. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  98. package/dist/node_modules/@dalcode/dal-pi-kit/src/agent-dir.js +1 -0
  99. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  100. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  101. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  102. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  104. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  105. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  106. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  107. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  108. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  109. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  110. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  111. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  112. package/dist/node_modules/@dalcode/dal-sync/package.json +7 -5
  113. package/dist/node_modules/@dalcode/dal-sync/src/client.d.ts +2 -0
  114. package/dist/node_modules/@dalcode/dal-sync/src/client.js +1 -1
  115. package/dist/node_modules/@dalcode/dal-sync/src/host.d.ts +11 -1
  116. package/dist/node_modules/@dalcode/dal-sync/src/host.js +2 -2
  117. package/dist/node_modules/@dalcode/dal-sync/src/index.js +3 -3
  118. package/dist/node_modules/@dalcode/dal-sync/src/sessions.d.ts +153 -0
  119. package/dist/node_modules/@dalcode/dal-sync/src/sessions.js +15 -0
  120. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  121. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  122. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  123. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  124. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  125. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  126. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  127. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  128. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  129. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  130. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/azure.json +1 -1
  131. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  132. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  133. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  134. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
  135. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  136. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  137. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  138. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  139. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  140. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  141. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  142. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  143. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  144. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  145. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  146. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  147. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  148. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  149. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  150. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  151. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  152. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  153. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  154. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  155. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  156. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  157. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  158. package/dist/sdk/sync.d.ts +8 -1
  159. package/dist/sdk/sync.js +1 -1
  160. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  161. package/examples/extensions/gondolin/package-lock.json +2 -2
  162. package/examples/extensions/gondolin/package.json +1 -1
  163. package/examples/extensions/with-deps/package-lock.json +2 -2
  164. package/examples/extensions/with-deps/package.json +1 -1
  165. package/npm-shrinkwrap.json +2 -2
  166. package/package.json +1 -1
  167. package/dist/bundle/chunks/chunk-3YGHTGYM.js +0 -7
  168. package/dist/bundle/chunks/chunk-D3HKK2ZD.js +0 -17
  169. package/dist/bundle/chunks/chunk-NMU45EFT.js +0 -9
  170. package/dist/bundle/chunks/chunk-SE42OS3U.js +0 -21
  171. package/dist/bundle/chunks/chunk-YDOF6JVP.js +0 -30
  172. package/dist/bundle/chunks/mcp-SGBPG7LV.js +0 -10
  173. package/dist/bundle/chunks/runtime-KB5ZUQB6.js +0 -1
  174. package/dist/bundle/chunks/sdk-C5BAFGNR.js +0 -1
  175. package/dist/bundle/chunks/sync-AQUDRXHM.js +0 -7
  176. package/dist/bundle/chunks/usage-CK3QZLTW.js +0 -1
  177. package/dist/bundle/chunks/virtual-modules-GRXCAWTO.js +0 -1
@@ -0,0 +1 @@
1
+ var b=Object.defineProperty;var n=(e,r)=>b(e,"name",{value:r,configurable:!0});import{createRequire as y}from"node:module";const D=y(import.meta.url);function d(e){return new RegExp(e.join("|"),"i")}n(d,"buildProviderErrorPattern");var c=d(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","^\\s*(?:error:?\\s*)?402\\b","\\b(?:status|http|code)\\W{0,3}402\\b","payment.?required","insufficient.?(?:balance|credits?|funds)","credit balance is too low","exceeded your current quota","quota.?exhausted","\u4F59\u989D\u4E0D\u8DB3","subscription_sharing_usage_limit_exceeded","subscription_sharing_workplace_individual_usage_limit_exceeded",'"code"\\s*:\\s*"?1308(?![0-9])']),h=d(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","empty response","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","connection.?reset","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","premature close","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","cut short after the reply had begun","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),R=6e4;function p(e,r){let a=e.baseDelayMs*2**Math.max(0,r-1),t=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(t,e.maxAgentDelayMs??R)}n(p,"retryDelayMs");var E=class extends Error{static{n(this,"RetrySleepAbortError")}constructor(){super("Aborted")}};function g(e,r){return new Promise((a,t)=>{if(r?.aborted){t(new E);return}let u=setTimeout(a,e);r?.addEventListener("abort",()=>{clearTimeout(u),t(new E)},{once:!0})})}n(g,"sleep");async function A(e,r,a,t){let u=r?.enabled?r.maxRetries:0,i=0,o;for(;;){let s=await e();if(s.stopReason==="aborted")return o&&await t?.onRetryFinished?.(!1,o.attempt),s;if(s.stopReason!=="error")return o&&await t?.onRetryFinished?.(!0,o.attempt),s;if(i>=u||!f(s))return o&&await t?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;i++,o={attempt:i,errorMessage:s.errorMessage||"Unknown error"};let l=p(r,i);await t?.onRetryScheduled?.(i,u,l,o.errorMessage);try{await g(l,a)}catch(m){if(await t?.onRetryFinished?.(!1,i,o.errorMessage),m instanceof E){let{errorMessage:T,..._}=s;return{..._,stopReason:"aborted"}}throw m}await t?.onRetryAttemptStart?.()}}n(A,"retryAssistantCall");function f(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let r=e.errorMessage;return c.test(r)?!1:h.test(r)}n(f,"isRetryableAssistantError");var N=d(["network.?error","connection.?error","connection.?refused","connection.?lost","connection.?reset","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","premature close","websocket.?closed","websocket.?error","ended without","stream ended before"]);function w(e){return e.stopReason!=="error"||!e.errorMessage||c.test(e.errorMessage)?!1:N.test(e.errorMessage)}n(w,"isNetworkAssistantError");function M(e){return e.stopReason!=="error"||!e.errorMessage?!1:c.test(e.errorMessage)}n(M,"isAccountLimitAssistantError");export{R as DEFAULT_MAX_AGENT_RETRY_DELAY_MS,M as isAccountLimitAssistantError,w as isNetworkAssistantError,f as isRetryableAssistantError,A as retryAssistantCall,p as retryDelayMs};
@@ -1,4 +1,4 @@
1
- var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-D3HKK2ZD.js";import{sliceTail as Y}from"./chunk-SE42OS3U.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
1
+ var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-6PQZ4KMC.js";import{sliceTail as Y}from"./chunk-HF334NQU.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
2
2
 
3
3
  ${e.details}`:e.message}s(bt,"plainText");var _e=class ze{static{s(this,"_OAuthCallbackServer")}redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(t,r,i,n,a){this.server=t,this.redirectUrl=r,this.paths=i,this.timeoutMs=n,this.renderPage=a}static async listen(t={}){let r=t.host??"127.0.0.1",i=t.redirectHost??r,n=t.path??"/callback",a,o=Ct((l,h)=>a?.handle(l.url??"/",h));await new Promise((l,h)=>{o.once("error",h),o.listen(t.port??0,r,()=>{o.off("error",h),l()})});let c=o.address();if(!c||typeof c=="string")throw new Error("OAuth callback server did not bind to TCP");return a=new ze(o,`http://${i.includes(":")?`[${i}]`:i}:${c.port}${n}`,[n,...t.extraPaths??[]],t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(t,r){if(this.pending.has(t))throw new Error("OAuth state is already pending");return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(t),n(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(t,{resolve:i,reject:n,timer:a,path:r})})}async close(){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(new Error("OAuth callback server closed"));this.pending.clear();let t=new Promise((r,i)=>{this.server.close(n=>n?i(n):r())});this.server.closeAllConnections(),await t}reply(t,r,i){this.renderPage?(t.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(this.renderPage(i))):t.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(bt(i))}handle(t,r){let i=new URL(t,this.redirectUrl);if(!this.paths.includes(i.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let n=i.searchParams.get("state"),a=n?this.pending.get(n):void 0;if(!n||!a){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(a.timer),this.pending.delete(n),a.path!==void 0&&i.pathname!==a.path){a.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=i.searchParams.get("error");if(o){let h=i.searchParams.get("error_description")??o;a.reject(new Error(h)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:h});return}let c=i.searchParams.get("code");if(!c){a.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let l=i.searchParams.get("iss");a.resolve({code:c,state:n,...l?{iss:l}:{}}),this.reply(r,200,{ok:!0})}},g=class extends Error{static{s(this,"McpSignInCancelledError")}constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function Tt(e){if(e.signal?.aborted)throw new g;let t=e.challenge?.error==="insufficient_scope";return!t&&await zt(e)==="AUTHORIZED"?{kind:"authorized"}:D(e.signal,()=>It(e,t))}s(Tt,"startMcpSignIn");async function zt(e){let{store:t,settings:r,challenge:i,redirectUrl:n,signal:a}=e,o=t.withRefreshLock(async()=>{if(a?.aborted)return"REDIRECT";let c=await t.load();return!c?.tokens?.refresh_token||r.clientRegistration==="cimd"&&c.clientInformation&&!r.clientId?"REDIRECT":me(e,c,{challenge:i,redirectUrl:n})});try{return await Pt(a,o)}catch(c){if(c instanceof oe)return"REDIRECT";throw c}}s(zt,"refreshBeforeSignIn");function Pt(e,t){return e?new Promise((r,i)=>{let n=s(()=>i(new g),"abort");e.addEventListener("abort",n,{once:!0}),t.then(r,i).finally(()=>e.removeEventListener("abort",n))}):t}s(Pt,"untilAborted");async function It(e,t){let{store:r,settings:i,redirectUrl:n,challenge:a}=e,o=await r.load();o&&await r.save(Ot(o,e));let c,l=P(e,n,f=>{c=f}),h=Lt(i.scope,t?Et(o?.tokens?.scope,a?.scope):a?.scope);if(await $(l,{...ve(e),scope:h,skipRefresh:!0}),!c)throw new Error("OAuth flow did not produce an authorization URL");let d=c.searchParams.get("scope");return{kind:"redirect",authorizationUrl:c.href,redirectUrl:c.searchParams.get("redirect_uri")??n,state:await l.state(),...d?{scope:d}:{}}}s(It,"startBrowserStep");function Ot(e,t){let{settings:r,redirectUrl:i}=t,n={...e};return delete n.oauthState,r.clientId||(e.clientInformation?r.clientRegistration!=="cimd"&&O(e.clientInformation).includes(i):I(r,t.clientMetadataDocuments,i))||(delete n.clientInformation,delete n.tokens,delete n.tokensExpireAt),n}s(Ot,"stateForSignIn");function Lt(...e){let t=[...new Set(e.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(" "):void 0}s(Lt,"mergeScopes");async function xt(e){await D(e.signal,async()=>{let{authorization:t,response:r}=e;if(r.state!==t.state)throw new Error("The authorization response belongs to a different sign-in");if((await e.store.load())?.oauthState!==t.state)throw new Error("Another sign-in to this MCP server started since; sign in again");await $(P(e,e.redirectUrl),{...ve(e),scope:t.scope,authorizationRedirectUrl:t.redirectUrl,authorizationCode:r.code,iss:r.iss})})}s(xt,"completeMcpSignIn");function ve(e){return{serverUrl:e.serverUrl,fetch:te(),signal:e.signal,resourceMetadataUrl:e.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl}}s(ve,"flowOptions");async function D(e,t){if(e?.aborted)throw new g;try{return await t()}catch(r){throw e?.aborted?new g:r}}s(D,"cancellable");async function $t(e){let{settings:t}=e,r=ne(t),i=O((await e.store.load())?.clientInformation)[0],n=r.port??(i&&Number(new URL(i).port)||void 0),a=I(t,e.clientMetadataDocuments,r.url),o={host:r.host,redirectHost:r.redirectHost,path:r.path,extraPaths:a?[X(r.path,e.serverUrl)]:[],renderPage:e.renderPage},c;try{c=await _e.listen({...o,port:n??0})}catch(l){if(r.port!==void 0||n===void 0)throw l;c=await _e.listen(o)}return{callback:c,redirectUrl:r.fixedRedirectUrl??c.redirectUrl}}s($t,"listenForLoopbackSignIn");async function Dt(e){let{authorization:t}=e,r=new AbortController,i=e.signal?AbortSignal.any([r.signal,e.signal]):r.signal,n=e.callback.waitForCallback(t.state,new URL(t.redirectUrl).pathname),a=e.promptForRedirectUrl?e.promptForRedirectUrl(i).then(o=>{if(!o?.trim())throw new g;return Ht(o,t)}):new Promise((o,c)=>{i.addEventListener("abort",()=>c(new g),{once:!0})});try{return await D(e.signal,()=>Promise.race([n,a]))}finally{r.abort(),n.catch(()=>{}),a.catch(()=>{})}}s(Dt,"waitForLoopbackSignIn");function Ht(e,t){let r;try{r=new URL(e.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let i=new URL(t.redirectUrl);if(r.origin!==i.origin||r.pathname!==i.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let n=r.searchParams.get("error");if(n)throw new Error(r.searchParams.get("error_description")??n);let a=r.searchParams.get("state");if(a!==t.state)throw new Error("The redirect URL belongs to a different sign-in");let o=r.searchParams.get("code");if(!o)throw new Error("The redirect URL does not contain an authorization code");let c=r.searchParams.get("iss");return{code:o,state:a,...c?{iss:c}:{}}}s(Ht,"responseFromRedirectUrl");import{createHash as Nt}from"node:crypto";import{mkdirSync as Ft}from"node:fs";import{join as ye}from"node:path";var Vt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function A(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}s(A,"escapeHtml");function Ue(e){let t=A(e.title),r=A(e.heading),i=A(e.message),n=e.details?A(e.details):void 0;return`<!doctype html>
4
4
  <html lang="en">
@@ -1,3 +1,3 @@
1
- var Ae=Object.defineProperty;var s=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{createRequire as ke}from"node:module";const pt=ke(import.meta.url);import{AssistantMessageEventStream as Te,formatThrownValue as Ce,withFirstTokenTimeout as G}from"./chunk-4LDEEFCY.js";import{contentText as Se,getOpenCodeSessionHeaders as Pe,getSystemMessageText as Ee,mergeClientIdentity as qe,ownedSlice as _e}from"./chunk-44EXLOHK.js";import{__export as Re}from"./chunk-JXWJOIH4.js";function Y(e,t){let r=e!==void 0&&e.length>0,i=t!==void 0&&t.length>0;if(!(!r&&!i))return{role:"system",content:e??"",...i?{toolsAdded:t}:{},timestamp:0}}s(Y,"createInitialSystemMessage");function $(e){let t=Y(e.systemPrompt,e.tools);return{messages:t?[t,...e.messages]:e.messages}}s($,"normalizeContext");function P(e){return e.role==="system"}s(P,"isSystemMessage");function I(e){let t=e[0];return t&&P(t)?t:void 0}s(I,"getInitialSystemMessage");function Oe(e){return I(e)?e.slice(1):e}s(Oe,"withoutInitialSystemMessage");function R(e){let t=new Map;for(let r of e)if(P(r)){for(let i of r.toolsRemoved??[])t.delete(i.name);for(let i of r.toolsAdded??[])t.set(i.name,i)}return[...t.values()]}s(R,"getCurrentTools");function L(e){let t=[],r=new Map,i;for(let a of e){if(!P(a))continue;i??=a.timestamp;let o=Se(a.content);o.length>0&&t.push(o);for(let[d,c]of Object.entries(a.sections??{}))c===null?r.delete(d):r.set(d,c)}let n=R(e);if(!(i===void 0&&n.length===0))return{role:"system",content:t.join(`
1
+ var Ae=Object.defineProperty;var s=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{createRequire as ke}from"node:module";const pt=ke(import.meta.url);import{AssistantMessageEventStream as Te,formatThrownValue as Ce,withFirstTokenTimeout as G}from"./chunk-4LDEEFCY.js";import{contentText as Se,getOpenCodeSessionHeaders as Pe,getSystemMessageText as Ee,mergeClientIdentity as qe,ownedSlice as _e}from"./chunk-GPI2GHBH.js";import{__export as Re}from"./chunk-JXWJOIH4.js";function Y(e,t){let r=e!==void 0&&e.length>0,i=t!==void 0&&t.length>0;if(!(!r&&!i))return{role:"system",content:e??"",...i?{toolsAdded:t}:{},timestamp:0}}s(Y,"createInitialSystemMessage");function $(e){let t=Y(e.systemPrompt,e.tools);return{messages:t?[t,...e.messages]:e.messages}}s($,"normalizeContext");function P(e){return e.role==="system"}s(P,"isSystemMessage");function I(e){let t=e[0];return t&&P(t)?t:void 0}s(I,"getInitialSystemMessage");function Oe(e){return I(e)?e.slice(1):e}s(Oe,"withoutInitialSystemMessage");function R(e){let t=new Map;for(let r of e)if(P(r)){for(let i of r.toolsRemoved??[])t.delete(i.name);for(let i of r.toolsAdded??[])t.set(i.name,i)}return[...t.values()]}s(R,"getCurrentTools");function L(e){let t=[],r=new Map,i;for(let a of e){if(!P(a))continue;i??=a.timestamp;let o=Se(a.content);o.length>0&&t.push(o);for(let[d,c]of Object.entries(a.sections??{}))c===null?r.delete(d):r.set(d,c)}let n=R(e);if(!(i===void 0&&n.length===0))return{role:"system",content:t.join(`
2
2
 
3
3
  `),...r.size>0?{sections:Object.fromEntries(r)}:{},...n.length>0?{toolsAdded:n}:{},timestamp:i??0}}s(L,"getCurrentSystemMessage");function De(e){let t=L(e);return t?Ee(t):""}s(De,"getCurrentSystemPrompt");function J(e){let t=L(e.messages),r=e.messages.filter(i=>i.role!=="system");return{messages:t?[t,...r]:r}}s(J,"collapseSystemMessages");function xe(e,t){return t?e:J(e)}s(xe,"resolveTranscript");function O(e){return{name:e.name,description:e.description,parameters:JSON.parse(JSON.stringify(e.parameters)),...e.constrainedSampling===void 0?{}:{constrainedSampling:e.constrainedSampling}}}s(O,"toToolDeclaration");function D(e,t){return JSON.stringify(O(e))===JSON.stringify(O(t))}s(D,"declarationsEqual");function $e(e,t){let r=new Map(e.map(n=>[n.name,n])),i=new Map(t.map(n=>[n.name,n]));return{toolsAdded:t.filter(n=>{let a=r.get(n.name);return a===void 0||!D(a,n)}).map(O),toolsRemoved:e.filter(n=>{let a=i.get(n.name);return a===void 0||!D(n,a)}).map(n=>({name:n.name}))}}s($e,"getToolStateChanges");function Ie(e){let t=new Map;for(let r of e)if(P(r))for(let i of r.toolsAdded??[])t.set(i.name,i);return[...t.values()]}s(Ie,"getDeclaredTools");function Le(e){let t=new Map;for(let r of e)if(P(r))for(let i of r.toolsAdded??[]){let n=t.get(i.name);if(n!==void 0&&!D(n,i))return!0;t.set(i.name,i)}return!1}s(Le,"hasToolRedefinitions");function Ne(e){return V(e.filter(P))>=0}s(Ne,"hasNonAdditiveToolChanges");function V(e){let t=new Set,r=-1;for(let i=0;i<e.length;i++){let n=e[i];(n.toolsRemoved?.length??0)>0&&(r=i);for(let a of n.toolsAdded??[])t.has(a.name)&&(r=i),t.add(a.name)}return r}s(V,"findLastNonAdditiveToolChange");function Ke(e,t){let r=e.filter(P);if(t==="none")return{requestTools:R(r),foldedSystemMessages:r.length};if(t==="changes")return{requestTools:[],foldedSystemMessages:0};let i=Math.max(I(e)?1:0,V(r)+1);return{requestTools:R(r.slice(0,i)),foldedSystemMessages:i}}s(Ke,"resolveTranscriptTools");var X={};Re(X,{AI_TELEMETRY_SCHEMA:s(()=>x,"AI_TELEMETRY_SCHEMA"),ModelsError:s(()=>h,"ModelsError"),calculateCost:s(()=>we,"calculateCost"),clampThinkingLevel:s(()=>ve,"clampThinkingLevel"),createModels:s(()=>ye,"createModels"),createProvider:s(()=>ge,"createProvider"),getModelType:s(()=>S,"getModelType"),getSupportedThinkingLevels:s(()=>F,"getSupportedThinkingLevels"),hasApi:s(()=>me,"hasApi"),isModelType:s(()=>A,"isModelType"),modelsAreEqual:s(()=>be,"modelsAreEqual")});function Ue(e,t,r,i){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:i,errorMessage:t instanceof Error?t.message:String(t),timestamp:r}}s(Ue,"createSetupErrorMessage");function We(e){return typeof e.result=="function"}s(We,"hasResult");async function je(e,t,r,i){let n;for await(let a of t)e.push(a),r?.onEvent?.(a),a.type==="done"?n=a.message:a.type==="error"&&(n=a.error);We(t)&&(n=await t.result()),e.end(n),i(n)}s(je,"forwardStream");function k(e,t,r,i){let n=Date.now(),a=new Te,o=!1,d=s(c=>{o||(o=!0,r?.onResult?.(c))},"observeResult");return t().then(c=>je(a,c,r,d)).catch(c=>{let f=i?.aborted?"aborted":"error",m=Ue(e,c,n,f),w={type:"error",reason:f,error:m};a.push(w),r?.onEvent?.(w),a.end(m),d(m)}),a}s(k,"lazyStream");function ze(e,t){let r={stream:s((i,n,a)=>k(i,async()=>(await e()).stream(i,n,a),void 0,a?.signal),"stream"),streamSimple:s((i,n,a)=>k(i,async()=>(await e()).streamSimple(i,n,a),void 0,a?.signal),"streamSimple")};return t?.fetchDeferred&&(r.fetchDeferred=(i,n,a)=>k(i,async()=>{let o=await e();if(!o.fetchDeferred)throw new Error("API does not support deferred responses");return o.fetchDeferred(i,n,a)},void 0,a?.signal)),t?.cancelDeferred&&(r.cancelDeferred=async(i,n,a)=>{let o=await e();if(!o.cancelDeferred)throw new Error("API cannot cancel deferred responses");await o.cancelDeferred(i,n,a)}),r}s(ze,"lazyApi");var He=s(function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,i,n,a,o){return i?t?".jsx":".js":n&&(!a||!o)?r:n+a+"."+o.toLowerCase()+"js"}):e},"__rewriteRelativeImportExtension"),B=s(e=>import(He(e)),"importNodeModule");function Fe(){return globalThis.process?.env}s(Fe,"getProcessEnv");function Q(){return{async env(e){let t=Fe()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await B("node:fs/promises"),r=e;return r.startsWith("~")&&(r=(await B("node:os")).homedir()+r.slice(1)),await t.access(r),!0}catch{return!1}}}}s(Q,"defaultProviderAuthContext");function Z(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}s(Z,"abortReason");function T(e){return e??new AbortController().signal}s(T,"operationSignal");function C(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(Z(t))):new Promise((r,i)=>{let n=!1,a=s(()=>t.removeEventListener("abort",o),"cleanup"),o=s(()=>{n||(n=!0,a(),i(Z(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(d=>{n||(n=!0,a(),r(d))},d=>{n||(n=!0,a(),i(d))}),t.aborted&&o()})}s(C,"raceWithAbortSignal");var ee=class{static{s(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(e,t,r){let i=T(r?.signal),n=this.chains.get(e)??Promise.resolve(),a=(async()=>(await n.catch(()=>{}),i.throwIfAborted(),t()))(),o=a.catch(()=>{});return this.chains.set(e,o),o.then(()=>{this.chains.get(e)===o&&this.chains.delete(e)}),C(a,i)}async read(e,t){return t?.signal?.throwIfAborted(),this.credentials.get(e)}async list(e){return e?.signal?.throwIfAborted(),[...this.credentials].map(([t,r])=>({providerId:t,type:r.type}))}modify(e,t,r){return this.enqueue(e,async()=>{let i=this.credentials.get(e),n=await t(i);return r?.signal?.throwIfAborted(),n!==void 0&&this.credentials.set(e,n),n??i},r)}delete(e,t){return this.enqueue(e,async()=>{this.credentials.delete(e)},t)}},h=class extends Error{static{s(this,"ModelsError")}code;constructor(e,t,r){super(Ge(t,r?.cause),r),this.name="ModelsError",this.code=e}};function Ge(e,t){if(t==null)return e;let r=Ce(t).trim();return!r||e.includes(r)?e:`${e}: ${r}`}s(Ge,"withCauseDetail");function te(e,t,r,i){let n=T(i?.signal);return C(Ye(e,t,r,i,n),n)}s(te,"resolveProviderAuth");async function Ye(e,t,r,i,n){n.throwIfAborted();let a=i?.env?Xe(r,i.env):r;if(i?.apiKey!==void 0&&e.auth.apiKey)return K(a,e.auth.apiKey,e.id,{type:"api_key",key:i.apiKey,env:i.env},n);let o=await et(t,e.id,n);if(o){if(o.type==="oauth"&&e.auth.oauth)return Ze(t,e.id,e.auth.oauth,o,n,i?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let d=i?.env?{...o,env:{...o.env,...i.env}}:o;return K(a,e.auth.apiKey,e.id,d,n)}return}if(Ve(e.id))return e.auth.apiKey?K(a,e.auth.apiKey,e.id,void 0,n):void 0}s(Ye,"resolveProviderAuthWithSignal");var N;function Je(e){N=e}s(Je,"setAmbientAuthPolicy");function Ve(e){return N?N(e):!0}s(Ve,"ambientAuthAllowed");function Xe(e,t){return{env:s(async r=>t[r]||await e.env(r),"env"),fileExists:s(r=>e.fileExists(r),"fileExists")}}s(Xe,"overlayEnvAuthContext");var Be=300*1e3,Qe=15e3;async function re(e,t,r,i,n){let a,o=new AbortController,d=s(()=>o.abort(n.reason),"cancelLockWait");n.addEventListener("abort",d,{once:!0}),n.aborted&&d();try{a=await e.modify(t,async c=>{if(n.removeEventListener("abort",d),n.throwIfAborted(),c?.type==="oauth"&&i(c))try{return await r.refresh(c,AbortSignal.timeout(Qe))}catch(f){throw new h("oauth",`OAuth refresh failed for ${t}`,{cause:f})}},{signal:o.signal})}catch(c){throw c instanceof h?c:(n.throwIfAborted(),new h("auth",`Credential store modify failed for ${t}`,{cause:c}))}finally{n.removeEventListener("abort",d)}return a?.type==="oauth"?a:void 0}s(re,"refreshStoredOAuthCredential");async function Ze(e,t,r,i,n,a){let o=Math.max(Be,a??0),d=s(f=>Date.now()+o>=f.expires,"expiresSoon"),c=i;if(d(c)){let f=await re(e,t,r,d,n);if(!f)return;if(c=f,a!==void 0&&d(c))throw new h("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await r.toAuth(c),source:"OAuth"}}catch(f){throw new h("oauth",`OAuth auth derivation failed for ${t}`,{cause:f})}}s(Ze,"resolveStoredOAuth");async function K(e,t,r,i,n){try{return await t.resolve({ctx:e,credential:i,signal:n})}catch(a){throw new h("auth",`API key auth failed for provider ${r}`,{cause:a})}}s(K,"resolveApiKey");async function et(e,t,r){try{return await e.read(t,{signal:r})}catch(i){throw new h("auth",`Credential store read failed for ${t}`,{cause:i})}}s(et,"readCredential");var ie=class{static{s(this,"InMemoryModelsStore")}entries=new Map;async read(e,t){t?.signal?.throwIfAborted();let r=this.entries.get(e);return r?structuredClone(r):void 0}async write(e,t,r){r?.signal?.throwIfAborted(),this.entries.set(e,structuredClone(t))}async delete(e,t){t?.signal?.throwIfAborted(),this.entries.delete(e)}};function tt(e,t){let r=new Map;for(let i of t)for(let[n,a]of Object.entries(i.metrics??{}))r.set(n,a);return{counter:s(i=>e.counter(i,r.get(i)),"counter"),upDownCounter:s(i=>e.upDownCounter(i,r.get(i)),"upDownCounter"),histogram:s(i=>e.histogram(i,r.get(i)),"histogram")}}s(tt,"createTypedMetrics");async function rt(e,t){return t(U)}s(rt,"startNoopSpan");var it=Object.freeze({add:s(()=>{},"add")}),nt=Object.freeze({add:s(()=>{},"add")}),at=Object.freeze({record:s(()=>{},"record")}),ne=Object.freeze({counter:s(()=>it,"counter"),upDownCounter:s(()=>nt,"upDownCounter"),histogram:s(()=>at,"histogram")}),st=Object.freeze({inject:s(()=>{},"inject"),extract:s(()=>ae,"extract")}),U={metrics:ne,propagation:st,startSpan:rt,addLink:s(()=>{},"addLink"),addEvent:s(()=>{},"addEvent"),setAttributes:s(()=>{},"setAttributes"),setStatus:s(()=>{},"setStatus")};Object.freeze(U);var ae=U,wt=performance.timeOrigin;function se(e){return(t,r,i)=>e.startSpan({name:t,attributes:r},n=>i(n,se(n)))}s(se,"bindTypedSpanStarter");function ot(e,t){return se(e)}s(ot,"createTypedSpanStarter");var E={type:"string",description:"Provider identifier.",required:!0},q={type:"string",description:"Requested model identifier.",required:!0},oe={type:"string",description:"Normalized stop reason.",values:["pending","stop","length","toolUse","error","aborted","deferred"]},le={description:"One logical model request, including authentication and provider setup.",parents:{kind:"any"},startAttributes:{provider:E,api:{type:"string",description:"API identifier.",required:!0},model:q,reasoning:{type:"string",description:"Scalar requested reasoning level.",required:!1}},endAttributes:{stop:oe,"usage.input":{type:"number",description:"Uncached input tokens."},"usage.output":{type:"number",description:"Output tokens."},"usage.cache_read":{type:"number",description:"Cache-read tokens."},"usage.cache_write":{type:"number",description:"Cache-write tokens."},"cost.total":{type:"number",description:"Total request cost in USD."},"response.id":{type:"string",description:"Provider response identifier.",cardinality:"high"}},events:{"pi.ai.first_chunk":{description:"First normalized stream event delivered.",attributes:{}},"pi.ai.block":{description:"A completed content block; content is never recorded.",attributes:{type:{type:"string",description:"Block kind.",values:["text","thinking","tool_call"],required:!0},index:{type:"number",description:"Content block index.",required:!0},chars:{type:"number",description:"UTF-16 character count.",required:!0},tool:{type:"string",description:"Tool name, for tool-call blocks only.",required:!1}}}},status:{default:"ok",errorWhen:"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."}},x={version:1,spans:{"pi.ai.request":le,"pi.ai.poll":{...le,description:"One deferred-response poll, not the deferred request's lifetime."}},metrics:{"pi.ai.request.duration":{kind:"histogram",description:"Logical request or poll duration.",unit:"ms",attributes:{provider:E,model:q,stop:{...oe,required:!0}}},"pi.ai.first_chunk.duration":{kind:"histogram",description:"Time to the first normalized stream event.",unit:"ms",attributes:{provider:E,model:q}},"pi.ai.tokens":{kind:"counter",description:"Reported model token usage; pending and deferred polls are excluded.",unit:"token",attributes:{provider:E,model:q,kind:{type:"string",description:"Token usage category.",values:["input","output","cache_read","cache_write"],required:!0}}},"pi.ai.cost":{kind:"counter",description:"Reported model cost; pending and deferred polls are excluded.",unit:"USD",attributes:{provider:E,model:q}}}};function lt(e){let t=tt(e,[x]);return{requestDuration:t.histogram("pi.ai.request.duration"),firstChunkDuration:t.histogram("pi.ai.first_chunk.duration"),tokens:t.counter("pi.ai.tokens"),cost:t.counter("pi.ai.cost")}}s(lt,"createInstruments");var de=new WeakMap;function W(e,t,r){let i=performance.now(),n={provider:e.provider,model:e.id},a=t?.telemetry?.metrics??ne,o=de.get(a);o||(o=lt(a),de.set(a,o));let{requestDuration:d,firstChunkDuration:c,tokens:f,cost:m}=o,w,v,b=!0,M=new Map,l=new Promise(u=>{v=u}),p=s(u=>(w=u,l),"run"),y={...n,api:e.api,...typeof t?.reasoning=="string"?{reasoning:t.reasoning}:{}};return ot(t?.telemetry??ae,[x])(r?"pi.ai.poll":"pi.ai.request",y,p),{onEvent(u){if(b&&(b=!1,w.addEvent("pi.ai.first_chunk"),c.record(performance.now()-i,n,w)),u.type==="toolcall_delta")M.set(u.contentIndex,(M.get(u.contentIndex)??0)+u.delta.length);else if(u.type==="text_end"||u.type==="thinking_end")w.addEvent("pi.ai.block",{type:u.type==="text_end"?"text":"thinking",index:u.contentIndex,chars:u.content.length});else if(u.type==="toolcall_end"){let Me=M.get(u.contentIndex)??0;M.delete(u.contentIndex),w.addEvent("pi.ai.block",{type:"tool_call",index:u.contentIndex,chars:Me,tool:u.toolCall.name})}},onResult(u){u&&(w.setAttributes({stop:u.stopReason,"usage.input":u.usage.input,"usage.output":u.usage.output,"usage.cache_read":u.usage.cacheRead,"usage.cache_write":u.usage.cacheWrite,"cost.total":u.usage.cost.total,"response.id":u.responseId}),u.stopReason==="error"&&w.setStatus({status:"error",error:{name:"provider_error",message:_e(u.errorMessage??"",0,500)}}),d.record(performance.now()-i,{...n,stop:u.stopReason},w),(!r||u.stopReason!=="pending"&&u.stopReason!=="deferred")&&(f.add(u.usage.input,{...n,kind:"input"}),f.add(u.usage.output,{...n,kind:"output"}),f.add(u.usage.cacheRead,{...n,kind:"cache_read"}),f.add(u.usage.cacheWrite,{...n,kind:"cache_write"}),m.add(u.usage.cost.total,n))),v()}}}s(W,"observeModelRequest");function S(e){return e.type??"chat"}s(S,"getModelType");function A(e,t){return S(e)===t}s(A,"isModelType");function ue(e){if(!A(e,"chat"))throw new h("provider",`Model ${e.provider}/${e.id} is not a chat model`)}s(ue,"assertChatModel");function ce(e){if(!A(e,"image"))throw new h("provider",`Model ${e.provider}/${e.id} is not an image model`)}s(ce,"assertImageModel");function he(e){if(!A(e,"classifier"))throw new h("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}s(he,"assertClassifierModel");function fe(e,t){if(t.images?.length&&!e.input.includes("image"))throw new h("provider",`Model ${e.provider}/${e.id} does not accept image input`)}s(fe,"assertClassifierInputSupported");function j(e,t,r=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:r?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}s(j,"imageErrorResult");function z(e,t,r=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:r?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}s(z,"classifierErrorResult");var dt={chat:!0,image:!0,classifier:!0};function pe(e){return Object.hasOwn(dt,S(e))}s(pe,"hasKnownModelType");function ut(e){return{...e,models:e.models.filter(pe)}}s(ut,"withKnownModelTypes");function H(e,t){if(!e&&!t)return;let r={...e};for(let[i,n]of Object.entries(t??{})){let a=i.toLowerCase();for(let o of Object.keys(r))o.toLowerCase()===a&&delete r[o];r[i]=n}return r}s(H,"mergeHeaders");var ct=class{static{s(this,"ModelsImpl")}providers=new Map;credentials;modelsStore;authContext;identity;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(e){this.credentials=e?.credentials??new ee,this.modelsStore=e?.modelsStore??new ie,this.authContext=e?.authContext??Q(),this.identity=e?.identity}setProvider(e){this.supersedeProviderRefresh(e.id),this.providers.set(e.id,e)}deleteProvider(e){this.supersedeProviderRefresh(e),this.providers.delete(e)}clearProviders(){for(let e of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(e);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let r=this.providers.get(e);if(!r)return[];try{return r.getModels()}catch{return[]}}let t=[];for(let r of this.providers.values())try{t.push(...r.getModels())}catch{}return t}getAllModels(e){if(e!==void 0){let r=this.providers.get(e);if(!r)return[];try{return r.getAllModels?.()??r.getModels()}catch{return[]}}let t=[];for(let r of this.providers.values())try{t.push(...r.getAllModels?.()??r.getModels())}catch{}return t}getModelsOfType(e,t){return this.getAllModels(t).filter(r=>A(r,e))}getModel(e,t){return this.getModels(e).find(r=>r.id===t)}getModelOfType(e,t,r){return this.getModelsOfType(e,t).find(i=>i.id===r)}supersedeProviderRefresh(e){let t=(this.refreshGenerations.get(e)??0)+1;this.refreshGenerations.set(e,t);let r=this.refreshControllers.get(e);return r&&(this.refreshControllers.delete(e),r.abort()),t}beginProviderRefresh(e){let t=this.supersedeProviderRefresh(e),r=new AbortController;return this.refreshControllers.set(e,r),{generation:t,controller:r}}publishProviderModels(e,t,r,i){let n=this.publicationChains.get(e)??Promise.resolve(),a=(async()=>(await n.catch(()=>{}),r.aborted||this.refreshGenerations.get(e)!==t||(i.persist===null?await this.modelsStore.delete(e,{signal:r}):i.persist!==void 0&&await this.modelsStore.write(e,structuredClone(i.persist),{signal:r}),r.aborted||this.refreshGenerations.get(e)!==t)?!1:(i.update?.(),!0)))(),o=a.catch(()=>{});return this.publicationChains.set(e,o),o.then(()=>{this.publicationChains.get(e)===o&&this.publicationChains.delete(e)}),C(a,r)}async runProviderRefreshPhase(e,t,r,i,n,a){let o=await this.modelsStore.read(e.id,{signal:a});await e.refreshModels({credential:t,stored:o?ut(structuredClone(o)):void 0,publish:s(d=>this.publishProviderModels(e.id,n,a,d),"publish"),allowNetwork:r,force:r?i:void 0,signal:a,baseUrl:e.baseUrl})}async refresh(e={}){let t=e.allowNetwork??!0,r=T(e.signal),i=new Map;if(r.aborted)return{aborted:!0,errors:i};let n=e.providers?new Set(e.providers):void 0,a=Array.from(this.providers.values()).filter(d=>d.refreshModels!==void 0&&(!n||n.has(d.id))),o=Promise.all(a.map(async d=>{let{generation:c,controller:f}=this.beginProviderRefresh(d.id),m=AbortSignal.any([r,f.signal]),w=(async()=>{let v,b;try{v=await this.readCredential(d.id,m)}catch(l){b=l}if(await this.runProviderRefreshPhase(d,v,!1,void 0,c,m),b!==void 0)throw b;if(!t||m.aborted)return;let M=await this.resolveNetworkRefresh(d,v,m);M&&await this.runProviderRefreshPhase(d,M.credential,!0,e.force,c,m)})();try{await C(w,m)}catch(v){m.aborted||i.set(d.id,v instanceof Error?v:new h("model_source",`Model refresh failed for ${d.id}`,{cause:v}))}finally{this.refreshControllers.get(d.id)===f&&this.refreshControllers.delete(d.id)}}));try{await C(o,r)}catch(d){if(!r.aborted)throw d}return{aborted:r.aborted,errors:new Map(i)}}async resolveNetworkRefresh(e,t,r){if(e.refreshModelsAuth==="configured")return await this.checkProviderAuth(e,t,r)?{}:void 0;let i=await this.resolveRefreshCredential(e,t,r);return i?{credential:i}:void 0}async resolveRefreshCredential(e,t,r){if(t?.type==="oauth"){let o=e.auth.oauth;return o?Date.now()<t.expires?t:r.aborted?void 0:re(this.credentials,e.id,o,d=>Date.now()>=d.expires,r):void 0}let i=e.auth.apiKey;if(!i)return;let n=t?.type==="api_key"?t:void 0,a=await i.resolve({ctx:this.authContext,credential:n,signal:r});if(a)return{type:"api_key",key:a.auth.apiKey,env:a.env}}async readCredential(e,t){try{return await this.credentials.read(e,{signal:t})}catch(r){throw new h("auth",`Credential store read failed for ${e}`,{cause:r})}}async checkProviderAuth(e,t,r){if(t?.type==="oauth")return e.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let i=e.auth.apiKey;if(!i)return;if(i.check)try{return await i.check({ctx:this.authContext,credential:t?.type==="api_key"?t:void 0,signal:r})}catch(a){throw new h("auth",`API key auth check failed for provider ${e.id}`,{cause:a})}let n=await te(e,this.credentials,this.authContext,{signal:r});return n?{source:n.source,type:"api_key"}:void 0}checkAuth(e,t){let r=T(t?.signal),i=(async()=>{r.throwIfAborted();let n=this.providers.get(e);if(n)return this.checkProviderAuth(n,await this.readCredential(e,r),r)})();return C(i,r)}async getAuthenticatedProviders(e,t){t.throwIfAborted();let r=e?[this.providers.get(e)].filter(i=>i!==void 0):this.getProviders();return(await Promise.all(r.map(async i=>{let n=await this.readCredential(i.id,t);return{provider:i,credential:n,auth:await this.checkProviderAuth(i,n,t)}}))).filter(i=>i.auth!==void 0)}getAvailable(e,t){let r=T(t?.signal),i=(async()=>(await this.getAuthenticatedProviders(e,r)).flatMap(({provider:n,credential:a})=>{let o=n.getModels();return n.filterModels?.(o,a)??o}))();return C(i,r)}async getAvailableOfType(e,t,r){return(await this.getAllAvailable(t,r)).filter(i=>A(i,e))}getAllAvailable(e,t){let r=T(t?.signal),i=(async()=>(await this.getAuthenticatedProviders(e,r)).flatMap(({provider:n,credential:a})=>{let o=n.getAllModels?.()??n.getModels();if(n.filterAllModels)return n.filterAllModels(o,a);if(!n.filterModels)return o;let d=new Set(n.filterModels(n.getModels(),a).map(c=>c.id));return o.filter(c=>!A(c,"chat")||d.has(c.id))}))();return C(i,r)}async getAuth(e,t){let r=T(t?.signal),i=typeof e=="string"?e:e.provider,n=this.providers.get(i);if(!n)return;let a=await te(n,this.credentials,this.authContext,{...t,signal:r});return!a||typeof e=="string"||!e.headers?a:{...a,auth:{...a.auth,headers:H(a.auth.headers,e.headers)}}}async login(e,t,r,i){let n=T(r.signal);n.throwIfAborted();let a=this.providers.get(e);if(!a)throw new h("provider",`Unknown provider: ${e}`);let o=t==="oauth"?a.auth.oauth:a.auth.apiKey;if(!o?.login)throw new h("auth",`${a.name} does not support ${t} login`);let d=o.login({...r,signal:n},i),c=await C(d,n),f=!1,m,w=new Promise(b=>{m=b}),v=this.credentials.modify(e,async()=>(f=!0,m?.(),c),{signal:n});v.catch(()=>{});try{await new Promise((b,M)=>{let l=s(()=>{f||M(n.reason)},"onAbort");n.addEventListener("abort",l,{once:!0}),Promise.race([w,v]).then(()=>{n.removeEventListener("abort",l),b()},p=>{n.removeEventListener("abort",l),M(p)}),n.aborted&&l()}),await v}catch(b){throw n.throwIfAborted(),new h("auth",`Credential store modify failed for ${e}`,{cause:b})}return c}async logout(e,t){let r=T(t?.signal);r.throwIfAborted();try{await this.credentials.delete(e,{signal:r})}catch(i){throw r.throwIfAborted(),new h("auth",`Credential store delete failed for ${e}`,{cause:i})}}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new h("provider",`Unknown provider: ${e.provider}`);return t}requireChatProvider(e){return ue(e),this.requireProvider(e)}async applyAuth(e,t){this.requireProvider(e);let r=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!r)throw new h("auth",`Provider is not configured: ${e.provider}`);let i=r.auth,n=t?.apiKey??i.apiKey,a=i.baseUrl?{...e,baseUrl:i.baseUrl}:e,o=t&&"sessionId"in t&&typeof t.sessionId=="string"?t.sessionId:void 0,d=H(H(Pe(a,o),i.headers),t?.headers);t?.transformHeaders&&(d=await t.transformHeaders(d??{}));let c=r.env||t?.env?{...r.env??{},...t?.env??{}}:void 0,f=qe(this.identity,t?.identity),{transformHeaders:m,firstTokenTimeoutMs:w,...v}=t??{},b={...v,apiKey:n,headers:d,env:c,...f===void 0?{}:{identity:f}};return{requestModel:a,requestOptions:b}}stream(e,t,r){let i=$(t);return G(r,r?.firstTokenTimeoutMs,n=>k(e,async()=>{let a=this.requireChatProvider(e),{requestModel:o,requestOptions:d}=await this.applyAuth(e,n);return a.stream(o,i,d)},W(e,r,!1),n?.signal))}async complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){let i=$(t);return G(r,r?.firstTokenTimeoutMs,n=>k(e,async()=>{let a=this.requireChatProvider(e),{requestModel:o,requestOptions:d}=await this.applyAuth(e,n);return a.streamSimple(o,i,d)},W(e,r,!1),n?.signal))}async completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}streamDeferred(e,t,r){return k(e,async()=>{let i=this.requireChatProvider(e);if(!i.fetchDeferred)throw new h("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:n,requestOptions:a}=await this.applyAuth(e,r);return i.fetchDeferred(n,t,a)},W(e,r,!0),r?.signal)}async fetchDeferred(e,t,r){return this.streamDeferred(e,t,r).result()}async cancelDeferred(e,t,r){let i=this.requireChatProvider(e);if(!i.cancelDeferred)throw new h("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:n,requestOptions:a}=await this.applyAuth(e,r);await i.cancelDeferred(n,t,a)}async generateImages(e,t,r){try{ce(e);let i=this.requireProvider(e);if(!i.generateImages)throw new h("provider",`Provider ${e.provider} does not support image generation`);let{requestModel:n,requestOptions:a}=await this.applyAuth(e,r);return await i.generateImages(n,t,a)}catch(i){return j(e,i,r?.signal?.aborted)}}async classify(e,t,r){try{he(e),fe(e,t);let i=this.requireProvider(e);if(!i.classify)throw new h("provider",`Provider ${e.provider} does not support classification`);let{requestModel:n,requestOptions:a}=await this.applyAuth(e,r);return await i.classify(n,t,a)}catch(i){return z(e,i,r?.signal?.aborted)}}};function ye(e){return new ct(e)}s(ye,"createModels");function ge(e){let t=e.api&&typeof e.api.stream=="function"?e.api:void 0,r=t||!e.api?void 0:e.api,i=e.images,n=e.classifiers,a=t?[t]:Object.values(r??{}).filter(l=>l!==void 0),o=Object.values(i??{}).filter(l=>l!==void 0),d=Object.values(n??{}).filter(l=>l!==void 0);if(a.length===0&&o.length===0&&d.length===0)throw new Error(`Provider ${e.id}: at least one of "api", "images", or "classifiers" is required.`);let c=e.models,f=[],m=e.fetchModels,w=s(()=>{let l=[...c];for(let p of f){let y=l.findIndex(g=>S(g)===S(p)&&g.id===p.id);y>=0?l[y]=p:l.push(p)}return l},"currentModels"),v=s(l=>t??r?.[l.api],"apiFor"),b=s((l,p,y)=>{let g=v(l);return g?p(g):k(l,async()=>{throw new h("stream",`Provider ${e.id} has no API implementation for "${l.api}"`)},void 0,y)},"dispatch"),M={id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:s(()=>w().filter(l=>A(l,"chat")),"getModels"),getAllModels:w,refreshModels:m?async l=>{if(l.stored){let g=l.stored.models.filter(u=>u.provider===e.id).map(u=>u);if(!await l.publish({update:s(()=>{f=g},"update")}))return}if(!l.allowNetwork||l.signal.aborted)return;let p=await m(l);if(l.signal.aborted)return;let y=p.filter(pe);await l.publish({persist:{models:y,checkedAt:Date.now()},update:s(()=>{f=y},"update")})}:void 0,filterModels:e.filterModels,supportsApi:s(l=>r?r[l]!==void 0:w().some(p=>p.api===l),"supportsApi"),filterAllModels:e.filterAllModels,stream:s((l,p,y)=>b(l,g=>g.stream(l,p,y),y?.signal),"stream"),streamSimple:s((l,p,y)=>b(l,g=>g.streamSimple(l,p,y),y?.signal),"streamSimple")};return a.some(l=>l.fetchDeferred!==void 0)&&(M.fetchDeferred=(l,p,y)=>k(l,async()=>{let g=v(l);if(!g?.fetchDeferred)throw new h("provider",`Provider ${e.id} does not support deferred responses for "${l.api}"`);return g.fetchDeferred(l,p,y)},void 0,y?.signal)),a.some(l=>l.cancelDeferred!==void 0)&&(M.cancelDeferred=async(l,p,y)=>{let g=v(l);if(!g?.cancelDeferred)throw new h("provider",`Provider ${e.id} cannot cancel deferred responses for "${l.api}"`);await g.cancelDeferred(l,p,y)}),i&&o.length>0&&(M.generateImages=async(l,p,y)=>{let g=i[l.api];return g?g.generateImages(l,p,y):j(l,new h("provider",`Provider ${e.id} has no image generation implementation for "${l.api}"`))}),n&&d.length>0&&(M.classify=async(l,p,y)=>{let g=n[l.api];return g?g.classify(l,p,y):z(l,new h("provider",`Provider ${e.id} has no classifier implementation for "${l.api}"`))}),M}s(ge,"createProvider");function me(e,t){return A(e,"chat")&&e.api===t}s(me,"hasApi");function we(e,t){let r=t.input+t.cacheRead+t.cacheWrite,i=e.cost,n=-1;for(let d of e.cost.tiers??[])r>d.inputTokensAbove&&d.inputTokensAbove>n&&(i=d,n=d.inputTokensAbove);let a=t.cacheWrite1h??0,o=t.cacheWrite-a;return t.cost.input=i.input/1e6*t.input,t.cost.output=i.output/1e6*t.output,t.cost.cacheRead=i.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(i.cacheWrite*o+i.input*2*a)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost.totalFromProvider=!1,t.cost}s(we,"calculateCost");var _=["off","minimal","low","medium","high","xhigh","max"];function F(e){return e.reasoning?_.filter(t=>{let r=e.thinkingLevelMap?.[t];return r===null?!1:t==="xhigh"||t==="max"?r!==void 0:!0}):["off"]}s(F,"getSupportedThinkingLevels");function ve(e,t){let r=F(e);if(r.includes(t))return t;let i=_.indexOf(t);if(i===-1)return r[0]??"off";for(let n=i;n<_.length;n++){let a=_[n];if(r.includes(a))return a}for(let n=i-1;n>=0;n--){let a=_[n];if(r.includes(a))return a}return r[0]??"off"}s(ve,"clampThinkingLevel");function be(e,t){return!e||!t?!1:S(e)===S(t)&&e.id===t.id&&e.provider===t.provider}s(be,"modelsAreEqual");export{x as AI_TELEMETRY_SCHEMA,ee as InMemoryCredentialStore,ie as InMemoryModelsStore,h as ModelsError,ue as assertChatModel,fe as assertClassifierInputSupported,he as assertClassifierModel,ce as assertImageModel,we as calculateCost,ve as clampThinkingLevel,z as classifierErrorResult,J as collapseSystemMessages,Y as createInitialSystemMessage,ye as createModels,ge as createProvider,D as declarationsEqual,Q as defaultProviderAuthContext,L as getCurrentSystemMessage,De as getCurrentSystemPrompt,R as getCurrentTools,Ie as getDeclaredTools,I as getInitialSystemMessage,S as getModelType,F as getSupportedThinkingLevels,$e as getToolStateChanges,me as hasApi,Ne as hasNonAdditiveToolChanges,Le as hasToolRedefinitions,j as imageErrorResult,A as isModelType,ze as lazyApi,k as lazyStream,be as modelsAreEqual,X as models_exports,$ as normalizeContext,xe as resolveTranscript,Ke as resolveTranscriptTools,Je as setAmbientAuthPolicy,O as toToolDeclaration,Oe as withoutInitialSystemMessage};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-44EXLOHK.js";var g=4e3;function m(t){if(!(t instanceof Error))return{message:a(t),messageCarriesBody:!1};let e=t,n=b(e),s=$(e),o=s===void 0||t.message.includes(s),u=n===void 0&&s===void 0?r(t):t.message;return{status:n,body:s,message:u,messageCarriesBody:o}}i(m,"normalizeProviderError");var l=5;function r(t){let e,n=t.cause;for(let u=0;u<l&&n instanceof Error;u++)e=n,n=n.cause;if(!e)return t.message;let s=(e.message||e.name).trim(),o=e.code;return(typeof o=="string"||typeof o=="number")&&!s.includes(String(o))&&(s=s?`${s} (${o})`:String(o)),!s||t.message.includes(s)?t.message:t.message?`${t.message}: ${s}`:s}i(r,"withCauseDetail");function b(t){if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;if(typeof t.$metadata?.httpStatusCode=="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode=="number")return t.$response.statusCode}i(b,"extractStatus");function $(t){let e=S(t);if(e===void 0)return;let n=e.trim();if(n.length!==0)return f(n,g)}i($,"extractBody");function S(t){if(typeof t.body=="string")return t.body;if(d(t.error))return a(t.error);let e=t.$response?.body;if(typeof e=="string")return e;if(!C(e)&&d(e))return a(e)}i(S,"pickBodyText");function C(t){return typeof t=="object"&&t!==null&&"pipe"in t&&typeof t.pipe=="function"}i(C,"isReadableStreamLike");function d(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e!==Object.prototype&&e!==null?!1:Object.keys(t).length>0}i(d,"isPlainNonEmptyObject");function E(t,e){return t.messageCarriesBody||t.status===void 0||t.body===void 0?e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message:e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}i(E,"formatProviderError");function f(t,e){return t.length<=e?t:`${p(t,0,e)}... [truncated ${t.length-e} chars]`}i(f,"truncateErrorText");function a(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}i(a,"safeJsonStringify");export{E as formatProviderError,m as normalizeProviderError,f as truncateErrorText,r as withCauseDetail};
1
+ var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-GPI2GHBH.js";var g=4e3;function m(t){if(!(t instanceof Error))return{message:a(t),messageCarriesBody:!1};let e=t,n=b(e),s=$(e),o=s===void 0||t.message.includes(s),u=n===void 0&&s===void 0?r(t):t.message;return{status:n,body:s,message:u,messageCarriesBody:o}}i(m,"normalizeProviderError");var l=5;function r(t){let e,n=t.cause;for(let u=0;u<l&&n instanceof Error;u++)e=n,n=n.cause;if(!e)return t.message;let s=(e.message||e.name).trim(),o=e.code;return(typeof o=="string"||typeof o=="number")&&!s.includes(String(o))&&(s=s?`${s} (${o})`:String(o)),!s||t.message.includes(s)?t.message:t.message?`${t.message}: ${s}`:s}i(r,"withCauseDetail");function b(t){if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;if(typeof t.$metadata?.httpStatusCode=="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode=="number")return t.$response.statusCode}i(b,"extractStatus");function $(t){let e=S(t);if(e===void 0)return;let n=e.trim();if(n.length!==0)return f(n,g)}i($,"extractBody");function S(t){if(typeof t.body=="string")return t.body;if(d(t.error))return a(t.error);let e=t.$response?.body;if(typeof e=="string")return e;if(!C(e)&&d(e))return a(e)}i(S,"pickBodyText");function C(t){return typeof t=="object"&&t!==null&&"pipe"in t&&typeof t.pipe=="function"}i(C,"isReadableStreamLike");function d(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e!==Object.prototype&&e!==null?!1:Object.keys(t).length>0}i(d,"isPlainNonEmptyObject");function E(t,e){return t.messageCarriesBody||t.status===void 0||t.body===void 0?e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message:e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}i(E,"formatProviderError");function f(t,e){return t.length<=e?t:`${p(t,0,e)}... [truncated ${t.length-e} chars]`}i(f,"truncateErrorText");function a(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}i(a,"safeJsonStringify");export{E as formatProviderError,m as normalizeProviderError,f as truncateErrorText,r as withCauseDetail};
@@ -1,4 +1,4 @@
1
- var Ha=Object.defineProperty;var p=(e,t)=>Ha(e,"name",{value:t,configurable:!0});import{createRequire as Va}from"node:module";const Fy=Va(import.meta.url);import{require_safe_buffer as Bt}from"./chunk-567OJLS7.js";import{getJsonSchemaToolParameters as $a,resolveJsonSchemaStrictSampling as tn,transformMessages as Ja}from"./chunk-KSF7BFGS.js";import{sanitizeSurrogates as St}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest as Wa}from"./chunk-ML5DIOWR.js";import{clampThinkingLevel as Xa,collapseSystemMessages as Ka,withoutInitialSystemMessage as Ya}from"./chunk-2XX4WZT6.js";import{__commonJS as z,__require as te,__toESM as ze}from"./chunk-JXWJOIH4.js";var za=z({"node_modules/retry/lib/retry_operation.js"(e,t){function r(n,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=i||{},this._maxRetryTime=i&&i.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}p(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var i=new Date().getTime();if(n&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},o),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(n,i){this._fn=n,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)},r.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},i=null,o=0,a=0;a<this._errors.length;a++){var c=this._errors[a],u=c.message,d=(n[u]||0)+1;n[u]=d,d>=o&&(i=c,o=d)}return i}}}),Qa=z({"node_modules/retry/lib/retry.js"(e){var t=za();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in r)n[i]=r[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],a=0;a<n.retries;a++)o.push(this.createTimeout(a,n));return r&&r.forever&&!o.length&&o.push(this.createTimeout(a,n)),o.sort(function(c,u){return c-u}),o},e.createTimeout=function(r,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return o=Math.min(o,n.maxTimeout),o},e.wrap=function(r,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in r)typeof r[o]=="function"&&i.push(o)}for(var a=0;a<i.length;a++){var c=i[a],u=r[c];r[c]=function(d){var h=e.operation(n),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){h.retry(_)||(_&&(arguments[0]=h.mainError()),g.apply(this,arguments))}),h.attempt(function(){d.apply(r,m)})}.bind(r,u),r[c].options=n}}}}),Za=z({"node_modules/retry/index.js"(e,t){t.exports=Qa()}}),ja=z({"node_modules/p-retry/index.js"(e,t){"use strict";var r=Za(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{static{p(this,"AbortError")}constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}},o=p((u,d,h)=>{let m=h.retries-(d-1);return u.attemptNumber=d,u.retriesLeft=m,u},"decorateErrorWithCounts"),a=p(u=>n.includes(u),"isNetworkError"),c=p((u,d)=>new Promise((h,m)=>{d={onFailedAttempt:p(()=>{},"onFailedAttempt"),retries:10,...d};let g=r.operation(d);g.attempt(async _=>{try{h(await u(_))}catch(f){if(!(f instanceof Error)){m(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof i)g.stop(),m(f.originalError);else if(f instanceof TypeError&&!a(f.message))g.stop(),m(f);else{o(f,_,d);try{await d.onFailedAttempt(f)}catch(y){m(y);return}g.retry(f)||m(g.mainError())}}})}),"pRetry2");t.exports=c,t.exports.default=c,t.exports.AbortError=i}}),rn=z({"node_modules/extend/index.js"(e,t){"use strict";var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=p(function(h){return typeof Array.isArray=="function"?Array.isArray(h):n.call(h)==="[object Array]"},"isArray"),c=p(function(h){if(!h||n.call(h)!=="[object Object]")return!1;var m=r.call(h,"constructor"),g=h.constructor&&h.constructor.prototype&&r.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!m&&!g)return!1;var _;for(_ in h);return typeof _>"u"||r.call(h,_)},"isPlainObject2"),u=p(function(h,m){i&&m.name==="__proto__"?i(h,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):h[m.name]=m.newValue},"setProperty"),d=p(function(h,m){if(m==="__proto__")if(r.call(h,m)){if(o)return o(h,m).value}else return;return h[m]},"getProperty");t.exports=p(function h(){var m,g,_,f,y,E,C=arguments[0],S=1,A=arguments.length,v=!1;for(typeof C=="boolean"&&(v=C,C=arguments[1]||{},S=2),(C==null||typeof C!="object"&&typeof C!="function")&&(C={});S<A;++S)if(m=arguments[S],m!=null)for(g in m)_=d(C,g),f=d(m,g),C!==f&&(v&&f&&(c(f)||(y=a(f)))?(y?(y=!1,E=_&&a(_)?_:[]):E=_&&c(_)?_:{},u(C,{name:g,newValue:h(v,E,f)})):typeof f<"u"&&u(C,{name:g,newValue:f}));return C},"extend")}}),el=z({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),tl=z({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){"use strict";var r=el();t.exports={pkg:r}}}),nn=z({"node_modules/gaxios/build/cjs/src/common.js"(e){"use strict";var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=c;var r=t(rn()),n=t(tl()),i=n.default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${i.name}-gaxios-error`);var o=class wa extends Error{static{p(this,"_GaxiosError")}config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=i.version;static[Symbol.hasInstance](d){return d&&typeof d=="object"&&e.GAXIOS_ERROR_SYMBOL in d&&d[e.GAXIOS_ERROR_SYMBOL]===i.version?!0:Function.prototype[Symbol.hasInstance].call(wa,d)}constructor(d,h,m,g){if(super(d,{cause:g}),this.config=h,this.response=m,this.error=g instanceof Error?g:void 0,this.config=(0,r.default)(!0,{},h),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=a(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}g instanceof DOMException?this.code=g.name:g&&typeof g=="object"&&"code"in g&&(typeof g.code=="string"||typeof g.code=="number")&&(this.code=g.code)}static extractAPIErrorFromResponse(d,h="The request failed"){let m=h;if(typeof d.data=="string"&&(m=d.data),d.data&&typeof d.data=="object"&&"error"in d.data&&d.data.error&&!d.ok){if(typeof d.data.error=="string")return{message:d.data.error,code:d.status,status:d.statusText};if(typeof d.data.error=="object"){m="message"in d.data.error&&typeof d.data.error.message=="string"?d.data.error.message:m;let g="status"in d.data.error&&typeof d.data.error.status=="string"?d.data.error.status:d.statusText,_="code"in d.data.error&&typeof d.data.error.code=="number"?d.data.error.code:d.status;if("errors"in d.data.error&&Array.isArray(d.data.error.errors)){let f=[];for(let y of d.data.error.errors)typeof y=="object"&&"message"in y&&typeof y.message=="string"&&f.push(y.message);return Object.assign({message:f.join(`
1
+ var Ha=Object.defineProperty;var p=(e,t)=>Ha(e,"name",{value:t,configurable:!0});import{createRequire as Va}from"node:module";const Fy=Va(import.meta.url);import{require_safe_buffer as Bt}from"./chunk-567OJLS7.js";import{getJsonSchemaToolParameters as $a,resolveJsonSchemaStrictSampling as tn,transformMessages as Ja}from"./chunk-KP7CMLOT.js";import{sanitizeSurrogates as St}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest as Wa}from"./chunk-ML5DIOWR.js";import{clampThinkingLevel as Xa,collapseSystemMessages as Ka,withoutInitialSystemMessage as Ya}from"./chunk-PD6QS7YD.js";import{__commonJS as z,__require as te,__toESM as ze}from"./chunk-JXWJOIH4.js";var za=z({"node_modules/retry/lib/retry_operation.js"(e,t){function r(n,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=i||{},this._maxRetryTime=i&&i.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}p(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var i=new Date().getTime();if(n&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},o),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(n,i){this._fn=n,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)},r.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},i=null,o=0,a=0;a<this._errors.length;a++){var c=this._errors[a],u=c.message,d=(n[u]||0)+1;n[u]=d,d>=o&&(i=c,o=d)}return i}}}),Qa=z({"node_modules/retry/lib/retry.js"(e){var t=za();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in r)n[i]=r[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],a=0;a<n.retries;a++)o.push(this.createTimeout(a,n));return r&&r.forever&&!o.length&&o.push(this.createTimeout(a,n)),o.sort(function(c,u){return c-u}),o},e.createTimeout=function(r,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return o=Math.min(o,n.maxTimeout),o},e.wrap=function(r,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in r)typeof r[o]=="function"&&i.push(o)}for(var a=0;a<i.length;a++){var c=i[a],u=r[c];r[c]=function(d){var h=e.operation(n),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){h.retry(_)||(_&&(arguments[0]=h.mainError()),g.apply(this,arguments))}),h.attempt(function(){d.apply(r,m)})}.bind(r,u),r[c].options=n}}}}),Za=z({"node_modules/retry/index.js"(e,t){t.exports=Qa()}}),ja=z({"node_modules/p-retry/index.js"(e,t){"use strict";var r=Za(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{static{p(this,"AbortError")}constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}},o=p((u,d,h)=>{let m=h.retries-(d-1);return u.attemptNumber=d,u.retriesLeft=m,u},"decorateErrorWithCounts"),a=p(u=>n.includes(u),"isNetworkError"),c=p((u,d)=>new Promise((h,m)=>{d={onFailedAttempt:p(()=>{},"onFailedAttempt"),retries:10,...d};let g=r.operation(d);g.attempt(async _=>{try{h(await u(_))}catch(f){if(!(f instanceof Error)){m(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof i)g.stop(),m(f.originalError);else if(f instanceof TypeError&&!a(f.message))g.stop(),m(f);else{o(f,_,d);try{await d.onFailedAttempt(f)}catch(y){m(y);return}g.retry(f)||m(g.mainError())}}})}),"pRetry2");t.exports=c,t.exports.default=c,t.exports.AbortError=i}}),rn=z({"node_modules/extend/index.js"(e,t){"use strict";var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=p(function(h){return typeof Array.isArray=="function"?Array.isArray(h):n.call(h)==="[object Array]"},"isArray"),c=p(function(h){if(!h||n.call(h)!=="[object Object]")return!1;var m=r.call(h,"constructor"),g=h.constructor&&h.constructor.prototype&&r.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!m&&!g)return!1;var _;for(_ in h);return typeof _>"u"||r.call(h,_)},"isPlainObject2"),u=p(function(h,m){i&&m.name==="__proto__"?i(h,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):h[m.name]=m.newValue},"setProperty"),d=p(function(h,m){if(m==="__proto__")if(r.call(h,m)){if(o)return o(h,m).value}else return;return h[m]},"getProperty");t.exports=p(function h(){var m,g,_,f,y,E,C=arguments[0],S=1,A=arguments.length,v=!1;for(typeof C=="boolean"&&(v=C,C=arguments[1]||{},S=2),(C==null||typeof C!="object"&&typeof C!="function")&&(C={});S<A;++S)if(m=arguments[S],m!=null)for(g in m)_=d(C,g),f=d(m,g),C!==f&&(v&&f&&(c(f)||(y=a(f)))?(y?(y=!1,E=_&&a(_)?_:[]):E=_&&c(_)?_:{},u(C,{name:g,newValue:h(v,E,f)})):typeof f<"u"&&u(C,{name:g,newValue:f}));return C},"extend")}}),el=z({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),tl=z({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){"use strict";var r=el();t.exports={pkg:r}}}),nn=z({"node_modules/gaxios/build/cjs/src/common.js"(e){"use strict";var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=c;var r=t(rn()),n=t(tl()),i=n.default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${i.name}-gaxios-error`);var o=class wa extends Error{static{p(this,"_GaxiosError")}config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=i.version;static[Symbol.hasInstance](d){return d&&typeof d=="object"&&e.GAXIOS_ERROR_SYMBOL in d&&d[e.GAXIOS_ERROR_SYMBOL]===i.version?!0:Function.prototype[Symbol.hasInstance].call(wa,d)}constructor(d,h,m,g){if(super(d,{cause:g}),this.config=h,this.response=m,this.error=g instanceof Error?g:void 0,this.config=(0,r.default)(!0,{},h),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=a(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}g instanceof DOMException?this.code=g.name:g&&typeof g=="object"&&"code"in g&&(typeof g.code=="string"||typeof g.code=="number")&&(this.code=g.code)}static extractAPIErrorFromResponse(d,h="The request failed"){let m=h;if(typeof d.data=="string"&&(m=d.data),d.data&&typeof d.data=="object"&&"error"in d.data&&d.data.error&&!d.ok){if(typeof d.data.error=="string")return{message:d.data.error,code:d.status,status:d.statusText};if(typeof d.data.error=="object"){m="message"in d.data.error&&typeof d.data.error.message=="string"?d.data.error.message:m;let g="status"in d.data.error&&typeof d.data.error.status=="string"?d.data.error.status:d.statusText,_="code"in d.data.error&&typeof d.data.error.code=="number"?d.data.error.code:d.status;if("errors"in d.data.error&&Array.isArray(d.data.error.errors)){let f=[];for(let y of d.data.error.errors)typeof y=="object"&&"message"in y&&typeof y.message=="string"&&f.push(y.message);return Object.assign({message:f.join(`
2
2
  `)||m,code:_,status:g},d.data.error)}return Object.assign({message:m,code:_,status:g},d.data.error)}}return{message:m,code:d.status,status:d.statusText}}};e.GaxiosError=o;function a(u,d){switch(u){case"stream":return d;case"json":return JSON.parse(JSON.stringify(d));case"arraybuffer":return JSON.parse(Buffer.from(d).toString("utf8"));case"blob":return JSON.parse(d.text());default:return d}}p(a,"translateData");function c(u){let d="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function h(_){_&&_.forEach((f,y)=>{(/^authentication$/i.test(y)||/^authorization$/i.test(y)||/secret/i.test(y))&&_.set(y,d)})}p(h,"redactHeaders");function m(_,f){if(typeof _=="object"&&_!==null&&typeof _[f]=="string"){let y=_[f];(/grant_type=/i.test(y)||/assertion=/i.test(y)||/secret/i.test(y))&&(_[f]=d)}}p(m,"redactString");function g(_){!_||typeof _!="object"||(_ instanceof FormData||_ instanceof URLSearchParams||"forEach"in _&&"set"in _?_.forEach((f,y)=>{(["grant_type","assertion"].includes(y)||/secret/.test(y))&&_.set(y,d)}):("grant_type"in _&&(_.grant_type=d),"assertion"in _&&(_.assertion=d),"client_secret"in _&&(_.client_secret=d)))}return p(g,"redactObject"),u.config&&(h(u.config.headers),m(u.config,"data"),g(u.config.data),m(u.config,"body"),g(u.config.body),u.config.url.searchParams.has("token")&&u.config.url.searchParams.set("token",d),u.config.url.searchParams.has("client_secret")&&u.config.url.searchParams.set("client_secret",d)),u.response&&(c({config:u.response.config}),h(u.response.headers),u.response.bodyUsed&&(m(u.response,"data"),g(u.response.data))),u}p(c,"defaultErrorRedactor")}}),rl=z({"node_modules/gaxios/build/cjs/src/retry.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=t;async function t(o){let a=n(o);if(!o||!o.config||!a&&!o.config.retry)return{shouldRetry:!1};a=a||{},a.currentRetryAttempt=a.currentRetryAttempt||0,a.retry=a.retry===void 0||a.retry===null?3:a.retry,a.httpMethodsToRetry=a.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],a.noResponseRetries=a.noResponseRetries===void 0||a.noResponseRetries===null?2:a.noResponseRetries,a.retryDelayMultiplier=a.retryDelayMultiplier?a.retryDelayMultiplier:2,a.timeOfFirstRequest=a.timeOfFirstRequest?a.timeOfFirstRequest:Date.now(),a.totalTimeout=a.totalTimeout?a.totalTimeout:Number.MAX_SAFE_INTEGER,a.maxRetryDelay=a.maxRetryDelay?a.maxRetryDelay:Number.MAX_SAFE_INTEGER;let c=[[100,199],[408,408],[429,429],[500,599]];if(a.statusCodesToRetry=a.statusCodesToRetry||c,o.config.retryConfig=a,!await(a.shouldRetry||r)(o))return{shouldRetry:!1,config:o.config};let u=i(a);o.config.retryConfig.currentRetryAttempt+=1;let d=a.retryBackoff?a.retryBackoff(o,u):new Promise(h=>{setTimeout(h,u)});return a.onRetryAttempt&&await a.onRetryAttempt(o),await d,{shouldRetry:!0,config:o.config}}p(t,"getRetryConfig");function r(o){let a=n(o);if(o.config.signal?.aborted&&o.code!=="TimeoutError"||o.code==="AbortError"||!a||a.retry===0||!o.response&&(a.currentRetryAttempt||0)>=a.noResponseRetries||!a.httpMethodsToRetry||!a.httpMethodsToRetry.includes(o.config.method?.toUpperCase()||"GET"))return!1;if(o.response&&o.response.status){let c=!1;for(let[u,d]of a.statusCodesToRetry){let h=o.response.status;if(h>=u&&h<=d){c=!0;break}}if(!c)return!1}return a.currentRetryAttempt=a.currentRetryAttempt||0,!(a.currentRetryAttempt>=a.retry)}p(r,"shouldRetryRequest");function n(o){if(o&&o.config&&o.config.retryConfig)return o.config.retryConfig}p(n,"getConfig");function i(o){let a=(o.currentRetryAttempt?0:o.retryDelay??100)+(Math.pow(o.retryDelayMultiplier,o.currentRetryAttempt)-1)/2*1e3,c=o.totalTimeout-(Date.now()-o.timeOfFirstRequest);return Math.min(a,c,o.maxRetryDelay)}p(i,"getNextRetryDelay")}}),on=z({"node_modules/gaxios/build/cjs/src/interceptor.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0;var t=class extends Set{static{p(this,"GaxiosInterceptorManager")}};e.GaxiosInterceptorManager=t}}),nl=z({"node_modules/gaxios/build/cjs/src/gaxios.js"(e){"use strict";var t=e&&e.__importDefault||function(g){return g&&g.__esModule?g:{default:g}},r;Object.defineProperty(e,"__esModule",{value:!0}),e.Gaxios=void 0;var n=t(rn()),i=te("https"),o=nn(),a=rl(),c=te("stream"),u=on(),d=p(async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),"randomUUID"),h=204,m=class{static{p(this,"Gaxios")}agentCache=new Map;defaults;interceptors;constructor(g){this.defaults=g||{},this.interceptors={request:new u.GaxiosInterceptorManager,response:new u.GaxiosInterceptorManager}}fetch(...g){let _=g[0],f=g[1],y,E=new Headers;return typeof _=="string"?y=new URL(_):_ instanceof URL?y=_:_&&_.url&&(y=new URL(_.url)),_&&typeof _=="object"&&"headers"in _&&r.mergeHeaders(E,_.headers),f&&r.mergeHeaders(E,new Headers(f.headers)),typeof _=="object"&&!(_ instanceof URL)?this.request({...f,..._,headers:E,url:y}):this.request({...f,headers:E,url:y})}async request(g={}){let _=await this.#n(g);return _=await this.#t(_),this.#r(this._request(_))}async _defaultAdapter(g){let _=g.fetchImplementation||this.defaults.fetchImplementation||await r.#l(),f={...g};delete f.data;let y=await _(g.url,f),E=await this.getResponseData(g,y);return Object.getOwnPropertyDescriptor(y,"data")?.configurable||Object.defineProperties(y,{data:{configurable:!0,writable:!0,enumerable:!0,value:E}}),Object.assign(y,{config:g,data:E})}async _request(g){try{let _;if(g.adapter?_=await g.adapter(g,this._defaultAdapter.bind(this)):_=await this._defaultAdapter(g),!g.validateStatus(_.status)){if(g.responseType==="stream"){let y=[];for await(let E of _.data)y.push(E);_.data=y.toString()}let f=o.GaxiosError.extractAPIErrorFromResponse(_,`Request failed with status code ${_.status}`);throw new o.GaxiosError(f?.message,g,_,f)}return _}catch(_){let f;_ instanceof o.GaxiosError?f=_:_ instanceof Error?f=new o.GaxiosError(_.message,g,void 0,_):f=new o.GaxiosError("Unexpected Gaxios Error",g,void 0,_);let{shouldRetry:y,config:E}=await(0,a.getRetryConfig)(f);if(y&&E)return f.config.retryConfig.currentRetryAttempt=E.retryConfig.currentRetryAttempt,g.retryConfig=f.config?.retryConfig,this.#i(g),this._request(g);throw g.errorRedactor&&g.errorRedactor(f),f}}async getResponseData(g,_){if(_.status===h)return"";if(g.maxContentLength&&_.headers.has("content-length")&&g.maxContentLength<Number.parseInt(_.headers?.get("content-length")||""))throw new o.GaxiosError("Response's `Content-Length` is over the limit.",g,Object.assign(_,{config:g}));switch(g.responseType){case"stream":return _.body;case"json":{let f=await _.text();try{return JSON.parse(f)}catch{return f}}case"arraybuffer":return _.arrayBuffer();case"blob":return _.blob();case"text":return _.text();default:return this.getResponseDataFromContentType(_)}}#e(g,_=[]){let f=new URL(g),y=[..._],E=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let C of E)y.push(C.trim());for(let C of y)if(C instanceof RegExp){if(C.test(f.toString()))return!1}else if(C instanceof URL){if(C.origin===f.origin)return!1}else if(C.startsWith("*.")||C.startsWith(".")){let S=C.replace(/^\*\./,".");if(f.hostname.endsWith(S))return!1}else if(C===f.origin||C===f.hostname||C===f.href)return!1;return!0}async#t(g){let _=Promise.resolve(g);for(let f of this.interceptors.request.values())f&&(_=_.then(f.resolved,f.rejected));return _}async#r(g){let _=Promise.resolve(g);for(let f of this.interceptors.response.values())f&&(_=_.then(f.resolved,f.rejected));return _}async#n(g){let _=new Headers(this.defaults.headers);r.mergeHeaders(_,g.headers);let f=(0,n.default)(!0,{},this.defaults,g);if(!f.url)throw new Error("URL is required.");if(f.baseURL&&(f.url=new URL(f.url,f.baseURL)),f.url=new URL(f.url),f.params)if(f.paramsSerializer){let C=f.paramsSerializer(f.params);C.startsWith("?")&&(C=C.slice(1));let S=f.url.toString().includes("?")?"&":"?";f.url=f.url+S+C}else{let C=f.url instanceof URL?f.url:new URL(f.url);for(let[S,A]of new URLSearchParams(f.params))C.searchParams.append(S,A);f.url=C}typeof g.maxContentLength=="number"&&(f.size=g.maxContentLength),typeof g.maxRedirects=="number"&&(f.follow=g.maxRedirects);let y=typeof f.data=="string"||f.data instanceof ArrayBuffer||f.data instanceof Blob||globalThis.File&&f.data instanceof File||f.data instanceof FormData||f.data instanceof c.Readable||f.data instanceof ReadableStream||f.data instanceof String||f.data instanceof URLSearchParams||ArrayBuffer.isView(f.data)||["Blob","File","FormData"].includes(f.data?.constructor?.name||"");if(f.multipart?.length){let C=await d();_.set("content-type",`multipart/related; boundary=${C}`),f.body=c.Readable.from(this.getMultipartRequest(f.multipart,C))}else y?f.body=f.data:typeof f.data=="object"?_.get("Content-Type")==="application/x-www-form-urlencoded"?f.body=f.paramsSerializer?f.paramsSerializer(f.data):new URLSearchParams(f.data):(_.has("content-type")||_.set("content-type","application/json"),f.body=JSON.stringify(f.data)):f.data&&(f.body=f.data);f.validateStatus=f.validateStatus||this.validateStatus,f.responseType=f.responseType||"unknown",!_.has("accept")&&f.responseType==="json"&&_.set("accept","application/json");let E=f.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!f.agent)if(E&&this.#e(f.url,f.noProxy)){let C=await r.#a();this.agentCache.has(E)?f.agent=this.agentCache.get(E):(f.agent=new C(E,{cert:f.cert,key:f.key}),this.agentCache.set(E,f.agent))}else f.cert&&f.key&&(this.agentCache.has(f.key)?f.agent=this.agentCache.get(f.key):(f.agent=new i.Agent({cert:f.cert,key:f.key}),this.agentCache.set(f.key,f.agent)));return typeof f.errorRedactor!="function"&&f.errorRedactor!==!1&&(f.errorRedactor=o.defaultErrorRedactor),f.body&&!("duplex"in f)&&(f.duplex="half"),this.#i(f),Object.assign(f,{headers:_,url:f.url instanceof URL?f.url:new URL(f.url)})}#i(g){if(g.timeout){let _=AbortSignal.timeout(g.timeout);g.signal&&!g.signal.aborted?g.signal=AbortSignal.any([g.signal,_]):g.signal=_}}validateStatus(g){return g>=200&&g<300}async getResponseDataFromContentType(g){let _=g.headers.get("Content-Type");if(_===null)return g.text();if(_=_.toLowerCase(),_.includes("application/json")){let f=await g.text();try{f=JSON.parse(f)}catch{}return f}else return _.match(/^text\//)?g.text():g.blob()}async*getMultipartRequest(g,_){let f=`--${_}--`;for(let y of g){let E=y.headers.get("Content-Type")||"application/octet-stream";yield`--${_}\r
3
3
  Content-Type: ${E}\r
4
4
  \r
@@ -0,0 +1,14 @@
1
+ var Yt=Object.defineProperty;var o=(e,t)=>Yt(e,"name",{value:t,configurable:!0});import{createRequire as Vt}from"node:module";const ks=Vt(import.meta.url);import{getProviderEnvValue as qt}from"./chunk-7DDKXS2Q.js";import{ToolCallArgumentsStream as Ht}from"./chunk-FFMDRXC4.js";import{calculateCost as Kt,createProvider as Jt}from"./chunk-PD6QS7YD.js";import{createAssistantMessageEventStream as be}from"./chunk-4LDEEFCY.js";import{getSystemMessageText as Xt}from"./chunk-GPI2GHBH.js";function Zt(e,t){return{name:e,login:o(async r=>{r.signal.throwIfAborted();let n=await r.prompt({type:"secret",message:`Enter ${e}`});return r.signal.throwIfAborted(),{type:"api_key",key:n}},"login"),resolve:o(async({ctx:r,credential:n,signal:i})=>{if(i.throwIfAborted(),n?.key)return{auth:{apiKey:n.key},env:n.env,source:"stored credential"};for(let s of t){let a=await r.env(s);if(i.throwIfAborted(),a)return{auth:{apiKey:a},source:s}}},"resolve")}}o(Zt,"envApiKeyAuth");function Qt(e){let t,r=o(()=>(t??=e.load(),t),"loaded");return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:o(async(n,i)=>(await r()).login(n,i),"login"),refresh:o(async(n,i)=>(await r()).refresh(n,i),"refresh"),toAuth:o(async n=>(await r()).toAuth(n),"toAuth")}}o(Qt,"lazyOAuth");var er=60*6e4,tr=30*6e4,Oe=.05,ke=.15;function rr(e){if(!(e<=1e4))return Math.max(1,Math.floor(Math.min(e*.9,e-1e4)))}o(rr,"getCacheWarmingDelayMs");function nr(e,t){let r=t?.cacheRetention??(qt("PI_CACHE_RETENTION",t?.env)==="long"?"long":"short");if(r==="none")return;let n=e.promptCache?.[r];return n===void 0?void 0:n*1e3}o(nr,"getPromptCacheTtlMs");function ir(e,t){return!t?.reasoning||e.api!=="anthropic-messages"?!0:e.compat?.forceAdaptiveThinking===!0}o(ir,"isCacheWarmingReplayable");function sr(e,t){return{...e,maxTokens:1,disableContinuation:!0,maxRetries:0,signal:t}}o(sr,"getCacheWarmingRequestOptions");function or(e,t,r){let n=ie(e,{cacheRead:t}),i=ie(e,e.cost.cacheWrite>0?{cacheWrite:t}:{input:t}),s=ie(e,{cacheRead:t,output:1}),a=Math.max(0,i-n),f=r==="idle"?ke:1,u=t>0&&(n>0||i>0),c=f*a-s;return{phase:r,warmCost:s,missCost:a,continuationProbability:f,expectedSavings:c,economicsAvailable:u,action:c>=Oe?"warm":"stop"}}o(or,"evaluateCacheWarming");function ie(e,t){let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},...t};return Kt(e,r).total}o(ie,"price");var Ee="faux",xe="faux",we="faux-1",ar="Faux Model",fr="http://localhost:0",ur=3,Re=5,V={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function _e(e){return{type:"text",text:e}}o(_e,"fauxText");function cr(e){return{type:"thinking",thinking:e}}o(cr,"fauxThinking");function lr(e,t,r={}){return{type:"toolCall",id:r.id??se("tool"),name:e,arguments:t}}o(lr,"fauxToolCall");function dr(e){return typeof e=="string"?[_e(e)]:Array.isArray(e)?e:[e]}o(dr,"normalizeFauxAssistantContent");function hr(e,t={}){return{role:"assistant",content:dr(e),api:Ee,provider:xe,model:we,usage:V,stopReason:t.stopReason??"stop",...t.deferred===void 0?{}:{deferred:t.deferred},...t.errorMessage===void 0?{}:{errorMessage:t.errorMessage},...t.responseId===void 0?{}:{responseId:t.responseId},timestamp:t.timestamp??Date.now()}}o(hr,"fauxAssistantMessage");function Ne(e){return Math.ceil(e.length/4)}o(Ne,"estimateTokens");function se(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}o(se,"randomId");function $e(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?t.text:`[image:${t.mimeType}:${t.data.length}]`).join(`
2
+ `)}o($e,"contentToText");function Se(e){return e.map(t=>t.type==="text"?t.text:t.type==="thinking"?t.thinking:`${t.name}:${JSON.stringify(t.arguments)}`).join(`
3
+ `)}o(Se,"assistantContentToText");function pr(e){return[e.toolName,...e.content.map(t=>$e([t]))].join(`
4
+ `)}o(pr,"toolResultToText");function mr(e){return e.role==="system"?[Xt(e),...e.toolsRemoved?.map(t=>`tool-:${JSON.stringify(t)}`)??[],...e.toolsAdded?.map(t=>`tool+:${JSON.stringify(t)}`)??[]].filter(t=>t.length>0).join(`
5
+ `):e.role==="user"?$e(e.content):e.role==="assistant"?Se(e.content):pr(e)}o(mr,"messageToText");function Ce(e,t=e.length){let r=t>0?(t-1)*2:0;for(let n=0;n<t;n++)r+=e[n].length;return r}o(Ce,"joinedLength");function yr(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let n=o(i=>r===i.length?"":(r>0?`
6
+
7
+ `:"")+i.slice(r).join(`
8
+
9
+ `),"rest");return Ce(e,r)+gr(n(e),n(t))}o(yr,"commonPromptPrefixLength");function gr(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}o(gr,"commonPrefixLength");function Pe(e,t,r,n){let i=t.messages.map(h=>`${h.role}:${mr(h)}`),s=Ce(i),a=Math.ceil(s/4),f=Ne(Se(e.content)),u=a,c=0,l=0,d=r?.sessionId;if(d&&r?.cacheRetention!=="none"){let h=n.get(d);if(h){let m=yr(h,i);c=Math.ceil(m/4),l=Math.max(0,a-c)}else l=a;u=0,n.set(d,i)}return{...e,usage:{input:u,output:f,cacheRead:c,cacheWrite:l,totalTokens:u+f+c+l,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}o(Pe,"withUsageEstimate");function oe(e,t,r){let n=[],i=0;for(;i<e.length;){let s=t+Math.floor(Math.random()*(r-t+1)),a=Math.max(1,s*4);n.push(e.slice(i,i+a)),i+=a}return n.length>0?n:[""]}o(oe,"splitStringByTokenSize");function Ir(e,t,r,n){let i=structuredClone(e);return{...i,api:t,provider:r,model:n,timestamp:i.timestamp??Date.now(),usage:i.usage??V}}o(Ir,"cloneMessage");function Te(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:V,stopReason:"deferred",deferred:t,timestamp:Date.now()}}o(Te,"createDeferredMessage");function q(e,t,r,n){return{role:"assistant",content:[],api:t,provider:r,model:n,usage:V,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}o(q,"createErrorMessage");function L(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}o(L,"createAbortedMessage");function ae(e,t){if(!t||t<=0)return new Promise(n=>queueMicrotask(n));let r=Ne(e)/t*1e3;return new Promise(n=>setTimeout(n,r))}o(ae,"scheduleChunk");async function H(e,t,r,n,i,s){let a={...t,content:[],stopReason:"pending"};if(s?.aborted){let f=L(a);e.push({type:"error",reason:"aborted",error:f}),e.end(f);return}e.push({type:"start",partial:{...a}});for(let f=0;f<t.content.length;f++){if(s?.aborted){let l=L(a);e.push({type:"error",reason:"aborted",error:l}),e.end(l);return}let u=t.content[f];if(u.type==="thinking"){a.content=[...a.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:f,partial:{...a}});for(let l of oe(u.thinking,r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].thinking+=l,e.push({type:"thinking_delta",contentIndex:f,delta:l,partial:{...a}})}e.push({type:"thinking_end",contentIndex:f,content:u.thinking,partial:{...a}});continue}if(u.type==="text"){a.content=[...a.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:f,partial:{...a}});for(let l of oe(u.text,r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].text+=l,e.push({type:"text_delta",contentIndex:f,delta:l,partial:{...a}})}e.push({type:"text_end",contentIndex:f,content:u.text,partial:{...a}});continue}a.content=[...a.content,{type:"toolCall",id:u.id,name:u.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:f,partial:{...a}});let c=new Ht;for(let l of oe(JSON.stringify(u.arguments),r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].arguments=c.append(l),e.push({type:"toolcall_delta",contentIndex:f,delta:l,partial:{...a}})}a.content[f].arguments=u.arguments,e.push({type:"toolcall_end",contentIndex:f,toolCall:u,partial:{...a}})}if(t.stopReason==="pending")throw new Error("Faux response ended without a stop reason");if(t.stopReason==="error"||t.stopReason==="aborted"){e.push({type:"error",reason:t.stopReason,error:t}),e.end(t);return}e.push({type:"done",reason:t.stopReason,message:t}),e.end(t)}o(H,"streamWithDeltas");function Me(e){let t=e.api??se(Ee),r=e.provider??xe,n=Math.max(1,Math.min(e.tokenSize?.min??ur,e.tokenSize?.max??Re)),i=Math.max(n,e.tokenSize?.max??Re),s=[],a=e.tokensPerSecond,f={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},u=new Map,c=new Map,l=(e.models?.length?e.models:[{id:we,name:ar,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384}]).map(y=>({id:y.id,name:y.name??y.id,api:t,provider:r,baseUrl:fr,reasoning:y.reasoning??!1,input:y.input??["text","image"],inputLimits:y.inputLimits,cost:y.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:y.contextWindow??128e3,maxTokens:y.maxTokens??16384})),d=o(async(y,I,b,A)=>{let g=typeof y=="function"?await y(I,b,f,A):y;return Pe(Ir(g,t,r,A.id),I,b,u)},"resolveResponse"),h=o((y,I,b)=>{let A=be(),g=s.shift();return f.callCount++,queueMicrotask(async()=>{try{if(await b?.onResponse?.({status:200,headers:{}},y),!g){let k=q(new Error("No more faux responses queued"),t,r,y.id);k=Pe(k,I,b,u),A.push({type:"error",reason:"error",error:k}),A.end(k);return}if(b?.deferred){let k={provider:y.provider,modelId:y.id,api:y.api,id:se("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};c.set(k.id,{handle:k,step:g,context:I,options:b,model:y,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await H(A,Te(y,k),n,i,a,b.signal);return}let N=await d(g,I,b,y);await H(A,N,n,i,a,b?.signal)}catch(N){let k=q(N,t,r,y.id);A.push({type:"error",reason:"error",error:k}),A.end(k)}}),A},"stream"),m=o((y,I,b)=>h(y,I,b),"streamSimple"),w=o((y,I,b)=>{let A=be();return f.deferredFetchCount++,queueMicrotask(async()=>{try{await b?.onResponse?.({status:200,headers:{}},y);let g=c.get(I.id);if(!g||g.handle.provider!==I.provider||g.handle.modelId!==I.modelId||g.handle.api!==I.api)throw new Error(`Unknown faux deferred response: ${I.id}`);if(g.cancelled)throw new Error(`Faux deferred response was cancelled: ${I.id}`);if(g.pendingFetches>0){g.pendingFetches--,await H(A,Te(y,g.handle),n,i,a,b?.signal);return}if(!g.final){let{deferred:N,signal:k,onResponse:As,...Gt}=g.options??{};try{g.final=await d(g.step,g.context,Gt,g.model)}catch(Wt){g.final=q(Wt,t,r,g.model.id)}}await H(A,g.final,n,i,a,b?.signal)}catch(g){let N=q(g,t,r,y.id);A.push({type:"error",reason:"error",error:N}),A.end(N)}}),A},"fetchDeferred"),j=o(async(y,I,b)=>{f.cancelledDeferred.push(structuredClone(I));let A=c.get(I.id);A&&(A.cancelled=!0),await b?.onResponse?.({status:200,headers:{}},y)},"cancelDeferred");function ne(y){return y?l.find(I=>I.id===y):l[0]}return o(ne,"getModel"),{api:t,provider:r,models:l,stream:h,streamSimple:m,fetchDeferred:w,cancelDeferred:j,getModel:ne,state:f,setResponses(y){s=[...y]},appendResponses(y){s.push(...y)},getPendingResponseCount(){return s.length}}}o(Me,"createFauxCore");function Ar(e={}){let t=Me(e);return{provider:Jt({id:t.provider,auth:{apiKey:{name:"Faux",resolve:o(async()=>({auth:{}}),"resolve")}},models:t.models,api:{stream:t.stream,streamSimple:t.streamSimple,fetchDeferred:t.fetchDeferred,cancelDeferred:t.cancelDeferred}}),api:t.api,models:t.models,getModel:t.getModel,state:t.state,setResponses:t.setResponses,appendResponses:t.appendResponses,getPendingResponseCount:t.getPendingResponseCount}}o(Ar,"fauxProvider");var je=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/context window exceeded/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^(?:[\w -]+ API error \(413\):|413(?:\s|:|$))/i],br=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Or=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function kr(e,t){return!!(e.stopReason==="error"&&e.errorMessage&&!Or.some(r=>r.test(e.errorMessage))&&(je.some(r=>r.test(e.errorMessage))||e.provider==="cerebras"&&br.test(e.errorMessage))||t&&e.stopReason==="stop"&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason==="length"&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}o(kr,"isContextOverflow");var Er=4096,xr=.9;function wr(e,t,r){if(e.stopReason!=="length"||t<=0||e.usage.output>=t)return!1;if(r===void 0||r<=0||!e.content.some(i=>i.type==="text"&&i.text.trim()!==""||i.type==="toolCall"))return!0;let n=e.usage;return n.input+n.cacheRead+n.cacheWrite+n.output+Er>=r*xr}o(wr,"isRecoverableLength");function Rr(){return[...je]}o(Rr,"getOverflowPatterns");function _r(e={}){return{type:"string",...e}}o(_r,"str");function Nr(e={}){return{type:"number",...e}}o(Nr,"num");function $r(e={}){return{type:"integer",...e}}o($r,"int");function Sr(e={}){return{type:"boolean",...e}}o(Sr,"bool");function Cr(e={}){return{type:"null",...e}}o(Cr,"nul");function Pr(e,t={}){return{enum:e,...t}}o(Pr,"oneOf");function Tr(e,t={}){return{anyOf:e,...t}}o(Tr,"union");function Mr(e,t={}){return{type:"array",items:e,...t}}o(Mr,"arr");var Le=class{static{o(this,"Optional")}schema;constructor(e){this.schema=e}};function jr(e){return new Le(e)}o(jr,"opt");function Lr(e,t={}){let{open:r,...n}=t,i={},s=[];for(let[a,f]of Object.entries(e))f instanceof Le?i[a]=f.schema:(i[a]=f,s.push(a));return{type:"object",properties:i,...s.length>0?{required:s}:{},...r===!0?{}:{additionalProperties:!1},...n}}o(Lr,"obj");var C=o(()=>!0,"ALWAYS"),fe=o(()=>!1,"NEVER"),Fe=o(e=>typeof e=="string","IS_STRING"),Ue=o(e=>Number.isFinite(e),"IS_NUMBER"),De=o(e=>Number.isInteger(e),"IS_INTEGER"),ve=o(e=>typeof e=="boolean","IS_BOOLEAN"),ze=o(e=>e===null,"IS_NULL"),Be=o(e=>Array.isArray(e),"IS_ARRAY"),Fr=o(e=>e instanceof Uint8Array,"IS_BYTES"),Ur=o(e=>typeof e=="bigint","IS_BIGINT"),Dr=o(e=>e===void 0,"IS_UNDEFINED"),Ge=o(e=>O(e),"IS_OBJECT");function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Uint8Array)}o(O,"isObject");var K=new Map([["string",Fe],["number",Ue],["integer",De],["boolean",ve],["null",ze],["array",Be],["object",Ge],["bytes",Fr],["bigint",Ur],["undefined",Dr]]),We=new WeakMap([[Fe,[1,void 0]],[Ue,[2,void 0]],[De,[3,void 0]],[ve,[4,void 0]],[ze,[5,void 0]],[C,[6,void 0]]]);function Ye(e){return We.get(e)}o(Ye,"leafOf");function P(e,t,r){return We.set(r,[e,t]),r}o(P,"leaf");var Ve=class{static{o(this,"Bounds")}min;max;xmin;xmax;constructor(e,t,r,n){this.min=e,this.max=t,this.xmin=r,this.xmax=n}};function ue(e,t,r){switch(e){case 1:return typeof t=="string";case 2:return Number.isFinite(t);case 3:return Number.isInteger(t);case 4:return typeof t=="boolean";case 5:return t===null;case 7:return t===r;case 8:{let n=r;for(let i=0;i<n.length;i++)if(n[i]===t)return!0;return!1}case 9:return(ce(t)&r)!==0;case 10:return Number.isInteger(t)&&qe(t,r);case 11:return Number.isFinite(t)&&qe(t,r);case 12:return typeof t=="string"&&Z(t,r.min,r.max);case 13:return typeof t=="string"&&r.test(t);default:return!0}}o(ue,"leafOk");function qe(e,t){return e>=t.min&&e<=t.max&&e>t.xmin&&e<t.xmax}o(qe,"inBounds");var J=0,He=1,F=2,Ke=15,U=16,Je=32;function X(e){switch(e.length){case 0:return C;case 1:return e[0];case 2:{let[t,r]=e;return n=>t(n)&&r(n)}case 3:{let[t,r,n]=e;return i=>t(i)&&r(i)&&n(i)}default:return t=>{for(let r=0;r<e.length;r++)if(!e[r](t))return!1;return!0}}}o(X,"and");function vr(e){return t=>e.check(t)}o(vr,"indirect");function Xe(e,t,r){return n=>{e.push(t);let i=r(n);return e.pop(),i}}o(Xe,"scopedCheck");function zr(e){return e.length===1?(typeof e[0]=="string"?K.get(e[0]):void 0)??fe:Qe(Ze(e))}o(zr,"typeCheck");var Br=new Map([["string",1],["number",2],["integer",4],["boolean",8],["null",16],["array",32],["object",64],["bytes",128],["bigint",256],["undefined",512]]);function Ze(e){let t=0;for(let r of e)typeof r=="string"&&(t|=Br.get(r)??0);return t}o(Ze,"typeMask");function ce(e){switch(typeof e){case"string":return 1;case"number":return Number.isInteger(e)?6:Number.isFinite(e)?2:0;case"boolean":return 8;case"object":return e===null?16:Array.isArray(e)?32:e instanceof Uint8Array?128:64;case"bigint":return 256;case"undefined":return 512;default:return 0}}o(ce,"typeBits");function Qe(e){return P(9,e,t=>(ce(t)&e)!==0)}o(Qe,"maskCheck");function Gr(e,t){if(t.length===0)return Qe(e);let r=t.length===1?t[0]:ot(t);return n=>(ce(n)&e)!==0||r(n)}o(Gr,"maskedAnyCheck");function Wr(e,t){return r=>r instanceof Uint8Array&&r.length>=e&&r.length<=t}o(Wr,"bytesCheck");function le(e){let t=0;for(let r=0;r<e.length;r++,t++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343&&r++}}return t}o(le,"codePoints");function Z(e,t,r){let n=e.length;return n<t||n<2*t&&le(e)<t?!1:n<=r||le(e)<=r}o(Z,"lengthOk");function Yr(e,t,r,n,i){return n!==void 0&&t===0&&r===Number.POSITIVE_INFINITY&&i===void 0?e?P(13,n,s=>typeof s=="string"&&n.test(s)):s=>typeof s!="string"||n.test(s):n===void 0&&i===void 0?e?P(12,new Ve(t,r,0,0),s=>typeof s=="string"&&Z(s,t,r)):s=>typeof s!="string"||Z(s,t,r):s=>typeof s!="string"?!e:Z(s,t,r)&&(n===void 0||n.test(s))&&(i===void 0||i(s))}o(Yr,"stringCheck");function Vr(e,t,r,n,i,s){let a=o(f=>typeof f!="number"&&typeof f!="bigint"?e===0:(e===3?typeof f!="bigint":e!==0&&!Number.isFinite(f))||e===2&&!Number.isInteger(f)?!1:f>=t&&f<=r&&f>n&&f<i&&(s===void 0||et(f,s)),"check");return e===0||e===3||s!==void 0||!(typeof t=="number"&&typeof r=="number"&&typeof n=="number"&&typeof i=="number")?a:P(e===2?10:11,new Ve(t,r,n,i),a)}o(Vr,"numberCheck");function et(e,t){if(typeof e=="bigint"||typeof t=="bigint"){if(typeof e=="number"&&!Number.isInteger(e)||typeof t=="number"&&!Number.isInteger(t))return!1;let f=BigInt(t);return f!==0n&&BigInt(e)%f===0n}let r=e/t;if(Number.isInteger(r))return!0;if(!Number.isFinite(r))return e%t===0;let[n,i]=tt(e),[s,a]=tt(t);return i>=a?n*10n**BigInt(i-a)%s===0n:n%(s*10n**BigInt(a-i))===0n}o(et,"isMultiple");function tt(e){let[t,r="0"]=Math.abs(e).toString().split("e"),n=t.indexOf("."),i=n<0?0:t.length-n-1;return[BigInt(t.replace(".","")),Number(r)-i]}o(tt,"decimal");function qr(e,t){return t?r=>O(r)&&e(r):r=>!O(r)||e(r)}o(qr,"guardObject");function Hr(e,t){return t?r=>Array.isArray(r)&&e(r):r=>!Array.isArray(r)||e(r)}o(Hr,"guardArray");function Kr(e,t,r,n){let i=e.length;return s=>{if(n!==J&&!O(s))return n===F;let a=s,f=0,u=0;for(let c in a){let l=u;if(e[l]!==c){for(l=0;l<i&&e[l]!==c;)l+=3;if(l===i){if(r)return!1;continue}}u=l+3;let d=a[c],h=e[l+2];if(d===void 0&&!(h&U))continue;let m=h&Ke;if(m!==0?!ue(m,d,e[l+1]):!e[l+1](d))return!1;h&U&&f++}return f===t}}o(Kr,"declaredObject");function Jr(e,t,r,n,i,s){let a=n.length>0||i!==void 0?new Set(t):void 0;return f=>{if(s!==J&&!O(f))return s===F;let u=f;for(let c=0;c<e.length;c+=3){let l=e[c],d=u[l],h=e[c+2];if(d===void 0&&!(h&U&&Object.hasOwn(u,l))||h&Je&&!Object.hasOwn(u,l)){if(h&U)return!1;continue}let m=h&Ke;if(m!==0?!ue(m,d,e[c+1]):!e[c+1](d))return!1}for(let c=0;c<r.length;c++)if(!Object.hasOwn(u,r[c]))return!1;if(a===void 0)return!0;for(let c of Object.keys(u)){let l=a.has(c);for(let d=0;d<n.length;d++)if(n[d][0].test(c)&&(l=!0,!n[d][1](u[c])))return!1;if(!l&&i!==void 0&&!i(u[c]))return!1}return!0}}o(Jr,"openObject");function Xr(e){return t=>{for(let r in t)if(!e(r))return!1;return!0}}o(Xr,"propertyNamesCheck");function Zr(e,t){return r=>{let n=0;for(let i in r)n++;return n>=e&&n<=t}}o(Zr,"propertyCountCheck");function Qr(e){return t=>{let r=t;for(let[n,i]of e)if(Object.hasOwn(r,n)){for(let s of i)if(!Object.hasOwn(r,s))return!1}return!0}}o(Qr,"dependentRequiredCheck");function en(e){return t=>{for(let[r,n]of e)if(Object.hasOwn(t,r)&&!n(t))return!1;return!0}}o(en,"dependentSchemasCheck");var tn=[0,void 0];function rt(e,t,r,n,i){let s=n.length,[a,f]=(i===void 0?void 0:Ye(i))??tn;return u=>{if(!Array.isArray(u))return e===F;let c=u.length;if(c<t||c>r)return!1;let l=c<s?c:s;for(let d=0;d<l;d++)if(!n[d](u[d]))return!1;if(i===void 0)return!0;if(a!==0){for(let d=s;d<c;d++)if(!ue(a,u[d],f))return!1;return!0}for(let d=s;d<c;d++)if(!i(u[d]))return!1;return!0}}o(rt,"listCheck");function rn(e,t){return rt(J,0,Number.POSITIVE_INFINITY,e,t)}o(rn,"itemsCheck");function nn(e,t){return r=>r.length>=e&&r.length<=t}o(nn,"lengthCheck");function nt(e,t,r){return n=>{let i=n,s=0;for(let a=0;a<i.length;a++)if(e(i[a])&&++s>r)return!1;return s>=t}}o(nt,"containsCheck");function it(e){let t=e;for(let r=1;r<t.length;r++)for(let n=0;n<r;n++)if(D(t[r],t[n]))return!1;return!0}o(it,"uniqueCheck");function de(e){let t=e.filter(i=>typeof i!="object"||i===null);if(t.length===e.length&&t.length<=8)return P(8,t,i=>{for(let s=0;s<t.length;s++)if(t[s]===i)return!0;return!1});let r=new Set(t),n=e.filter(i=>typeof i=="object"&&i!==null);return i=>r.has(i)||typeof i=="object"&&n.some(s=>D(i,s))}o(de,"enumCheck");function st(e){return typeof e!="object"||e===null?P(7,e,t=>t===e):t=>D(t,e)}o(st,"constCheck");function ot(e){return t=>{for(let r=0;r<e.length;r++)if(e[r](t))return!0;return!1}}o(ot,"anyCheck");function sn(e){return t=>{let r=0;for(let n=0;n<e.length;n++)if(e[n](t)&&++r>1)return!1;return r===1}}o(sn,"oneCheck");function on(e){return t=>!e(t)}o(on,"notCheck");function an(e,t,r){return n=>e(n)?t(n):r(n)}o(an,"ifCheck");function fn(e,t,r){return n=>{if(!O(n))return!1;let i=n[e];for(let s=0;s<t.length;s++)if(t[s]===i)return r[s](n);return!1}}o(fn,"taggedCheck");function D(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;let r=Array.isArray(e);if(r!==Array.isArray(t))return!1;if(r){let a=e,f=t;if(a.length!==f.length)return!1;for(let u=0;u<a.length;u++)if(!D(a[u],f[u]))return!1;return!0}let n=e,i=t,s=Object.keys(n);if(s.length!==Object.keys(i).length)return!1;for(let a of s)if(!Object.hasOwn(i,a)||!D(n[a],i[a]))return!1;return!0}o(D,"deepEqual");var Q="https://json-schema.invalid/root.json",un=class{static{o(this,"Resolver")}draft;rootBase=Q;baseOf=new Map;dynamicAnchors=new Map;root;options;registry=new Map;rejectUnresolved;unresolved=new Set;resources=new Map;anchors=new Map;indexed=!1;constructor(e,t){this.draft=t.draft==="7"?"7":"2020-12",this.root=e,this.options=t,this.rejectUnresolved=t.unresolvedRefs==="reject"}baseFor(e,t){let r=this.baseOf.get(e);if(r!==void 0)return r;let n=e.$id;return typeof n!="string"?t:!this.indexed&&(this.ensureIndexed(),r=this.baseOf.get(e),r!==void 0)?r:this.draft==="7"&&(typeof e.$ref=="string"||n.startsWith("#"))?t:S($(n,t))}ensureIndexed(){if(!this.indexed){this.indexed=!0;for(let[e,t]of Object.entries(this.options.schemas??{}))this.registry.set(S($(e,Q)),t);this.resources.set(Q,this.root),this.index(this.root,Q)}}resolve(e,t){if(this.ensureIndexed(),!this.rejectUnresolved)return this.find(e,t);try{return this.find(e,t)}catch{return this.unresolved.add($(e,t)),{node:!1,base:t}}}isUnresolved(e,t){return this.unresolved.has($(e,t))}find(e,t){let r=$(e,t),n=S(r),i=r.length>n.length?decodeURIComponent(r.slice(n.length+1)):"",s=this.resources.has(n)?this.resources.get(n):this.load(n);if(s===void 0)throw new Error(`Unresolved $ref ${e} (no schema registered for ${n})`);if(i==="")return{node:s,base:n};if(i.startsWith("/"))return this.pointer(s,n,i);let a=this.anchors.get(`${n}#${i}`);if(a===void 0)throw new Error(`Unresolved $ref ${e} (no anchor ${i} in ${n})`);return{node:a,base:this.baseOf.get(a)??n}}isResource(e,t){return this.ensureIndexed(),this.resources.get(t)===e}index(e,t){if(!p(e)||this.baseOf.has(e))return;let r=t,n=this.draft==="7"&&typeof e.$ref=="string";if(!n&&typeof e.$id=="string")if(this.draft==="7"&&e.$id.startsWith("#"))this.anchors.set(S(r)+e.$id,e);else{let i=$(e.$id,r);r=S(i),this.resources.set(r,e),i.length>r.length+1&&this.anchors.set(i,e)}if(this.baseOf.set(e,r),!n){this.draft!=="7"&&(typeof e.$anchor=="string"&&this.anchors.set(`${r}#${e.$anchor}`,e),typeof e.$dynamicAnchor=="string"&&(this.anchors.set(`${r}#${e.$dynamicAnchor}`,e),this.dynamicAnchors.set(`${r}#${e.$dynamicAnchor}`,e)));for(let i of cn)this.index(e[i],r);for(let i of ln){let s=e[i];if(p(s))for(let a of Object.keys(s))this.index(s[a],r)}for(let i of dn){let s=e[i];if(Array.isArray(s))for(let a of s)this.index(a,r)}}}load(e){let t=this.registry.get(e);if(t!==void 0)return this.resources.set(e,t),this.index(t,e),t}pointer(e,t,r){let n=e,i=t;for(let s of r.split("/").slice(1)){let a=s.replace(/~1/g,"/").replace(/~0/g,"~");if(n=typeof n=="object"&&n!==null&&Object.hasOwn(n,a)?n[a]:void 0,n===void 0)throw new Error(`Unresolved $ref #${r} in ${t}`);typeof n=="object"&&n!==null&&(i=this.baseOf.get(n)??i)}return{node:n,base:i}}},cn=["additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems","additionalItems","contentSchema","items"],ln=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"],dn=["allOf","anyOf","oneOf","prefixItems","items"];function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(p,"isSchemaObject");function $(e,t){try{return new URL(e,t).href}catch{return e.startsWith("#")?S(t)+e:e}}o($,"resolveUri");function S(e){let t=e.indexOf("#");return t<0?e:e.slice(0,t)}o(S,"documentOf");function _(e){let t=ee.get(e)?.deref();if(t!==void 0)return t;let r;try{r=new RegExp(e,"u")}catch{r=new RegExp(e)}return ee.set(e,new WeakRef(r)),hn.register(r,e),r}o(_,"sharedRegex");var ee=new Map,hn=new FinalizationRegistry(e=>{ee.get(e)?.deref()===void 0&&ee.delete(e)}),pn=class{static{o(this,"Coercer")}c;schema;entered=[];cuts=0;memo=void 0;constructor(e,t){this.c=e,this.schema=t}coerce(e){let t=this.c.r.rootBase,r=this.dropOptionalNulls(e,this.schema,t);return this.coerceTypes(this.convertOnly(r),this.schema,t)}convertOnly(e){try{return this.convert(this.schema,this.c.r.rootBase,e)}finally{this.memo=void 0,this.cuts=0}}reenter(e,t,r,n){let i=this.entered;for(let u=0;u<i.length;u+=2)if(i[u]===e&&Object.is(i[u+1],r))return this.cuts++,r;let s=n?this.memo?.get(e):void 0;if(s?.has(r))return s.get(r);let a=this.cuts;i.push(e,r);let f;try{f=this.convert(e,t,r)}finally{i.length-=2}if(n&&this.cuts===a){this.memo??=new Map;let u=this.memo.get(e);u===void 0&&(u=new Map,this.memo.set(e,u)),u.set(r,f)}return f}passes(e,t,r){try{return this.c.check(e,this.baseOf(e,t))(r)}catch{return}}baseOf(e,t){return p(e)?this.c.r.baseFor(e,t):t}dropOptionalNulls(e,t,r){if(!p(t))return e;let n=this.baseOf(t,r);if(Array.isArray(e))return te(e,(l,d)=>{let h=at(t,d);return h===void 0?l:this.dropOptionalNulls(l,h,n)});if(!re(e))return e;let i=p(t.properties)?t.properties:{},s=p(t.patternProperties)?Object.entries(t.patternProperties).map(([l,d])=>[_(l),d]):[],a=p(t.additionalProperties)?t.additionalProperties:void 0;if(s.length===0&&a===void 0&&!p(t.properties))return e;let f=new Set(Array.isArray(t.required)?t.required:[]),u,c=o((l,d)=>{d!==(u??e)[l]&&(u??={...e},u[l]=d)},"set");for(let[l,d]of Object.entries(i)){if(!Object.hasOwn(e,l))continue;let h=p(d)&&typeof d.$ref=="string";if(e[l]===null&&!f.has(l)&&!h&&this.passes(d,n,null)===!1){u??={...e},delete u[l];continue}c(l,this.dropOptionalNulls(e[l],d,n))}if(s.length>0||a!==void 0)for(let l of Object.keys(e)){let d=Object.hasOwn(i,l);for(let[h,m]of s)h.test(l)&&(d=!0,c(l,this.dropOptionalNulls((u??e)[l],m,n)));!d&&a!==void 0&&c(l,this.dropOptionalNulls(e[l],a,n))}return u??e}convert(e,t,r){if(!p(e))return r;let n=this.baseOf(e,t);if(typeof e.$ref=="string"){let i;try{i=this.c.r.resolve(e.$ref,n)}catch{return r}return p(i.node)?this.reenter(i.node,i.base,r,!0):r}return this.convertNode(e,n,r)}convertNode(e,t,r){if(Object.hasOwn(e,"const"))return ft(e.const,r);if(Array.isArray(e.enum))return this.convertEnum(e,e.enum,t,r);if(Array.isArray(e.anyOf))return this.convertUnion(e,e.anyOf,t,r);if(Array.isArray(e.oneOf))return this.convertUnion(e,e.oneOf,t,r);if(Array.isArray(e.allOf)){let n=r;for(let i of e.allOf)n=this.convert(i,t,n);return this.convertMembers(e,t,n)}switch(e.type){case"string":return T(ut(r),r);case"number":return T(he(r),r);case"integer":{let n=he(r);return n===void 0?r:Math.trunc(n.value)}case"boolean":return T(pt(r),r);case"null":return T(yn(r),r);case"bigint":return T(ht(r),r);case"undefined":return T(mn(r),r);case"array":return this.convertArray(e,t,r);case"object":return this.convertObject(e,t,r);case void 0:return e.properties!==void 0||e.patternProperties!==void 0?this.convertObject(e,t,r):e.items!==void 0||e.prefixItems!==void 0?this.convertArray(e,t,r):r;default:return r}}convertEnum(e,t,r,n){if(t.some(i=>i===n))return n;for(let i of t){let s=ft(i,n);if(s!==n&&this.passes(e,r,s)===!0)return s}return n}convertUnion(e,t,r,n){if(t.some(i=>this.passes(i,r,n)===!0))return this.convertMembers(e,r,n);for(let i of t){let s=this.convertMembers(e,r,this.convert(i,r,n));if(this.passes(e,r,s)===!0)return s}return this.convertMembers(e,r,n)}convertMembers(e,t,r){return e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0?this.convertObject(e,t,r):r}convertArray(e,t,r){let n=Array.isArray(e.items)?e.items:Array.isArray(e.prefixItems)?e.prefixItems:void 0;if(n!==void 0){if(!Array.isArray(r))return r;let s=Array.isArray(e.items)?void 0:e.items;return te(r,(a,f)=>{let u=f<n.length?n[f]:s;return u===void 0?a:this.convert(u,t,a)})}if(Array.isArray(r))return e.items===void 0?r:te(r,s=>this.convert(e.items,t,s));let i=e.items;return[p(i)?this.reenter(i,t,r,!1):r]}convertObject(e,t,r){if(!re(r))return r;let n=p(e.properties)?e.properties:{},i=p(e.patternProperties)?Object.entries(e.patternProperties).map(([f,u])=>[_(f),u]):[],s=p(e.additionalProperties)?e.additionalProperties:void 0,a;for(let f of Object.keys(r)){if(r[f]===void 0)continue;let u=r[f],c=Object.hasOwn(n,f);c&&(u=this.convert(n[f],t,u));for(let[l,d]of i)l.test(f)&&(c=!0,u=this.convert(d,t,u));!c&&s!==void 0&&(u=this.convert(s,t,u)),u!==r[f]&&(a??={...r},a[f]=u)}return a??r}coerceTypes(e,t,r){if(!p(t))return e;let n=this.baseOf(t,r),i=e;if(Array.isArray(t.allOf))for(let f of t.allOf)i=this.coerceTypes(i,f,n);Array.isArray(t.anyOf)&&(i=this.coerceUnion(i,t.anyOf,n)),Array.isArray(t.oneOf)&&(i=this.coerceUnion(i,t.oneOf,n));let s=gn(t),a=s.length>1&&s.some(f=>In(i,f));if(s.length>0&&!a)for(let f of s){let u=An(i,f);if(u!==i){i=u;break}}return s.includes("object")&&re(i)&&(i=this.coerceProperties(i,t,n)),s.includes("array")&&Array.isArray(i)&&(i=this.coerceItems(i,t,n)),i}coerceUnion(e,t,r){for(let n of t)if(this.passes(n,r,e)===!0)return e;for(let n of t){let i=this.coerceTypes(e,n,r);if(this.passes(n,r,i)===!0)return i}return e}coerceProperties(e,t,r){let n=p(t.properties)?t.properties:{},i=p(t.patternProperties)?Object.entries(t.patternProperties).map(([u,c])=>[_(u),c]):[],s=p(t.additionalProperties)?t.additionalProperties:void 0,a,f=o((u,c)=>{c!==(a??e)[u]&&(a??={...e},a[u]=c)},"set");for(let[u,c]of Object.entries(n))u in e&&f(u,this.coerceTypes(e[u],c,r));for(let u of Object.keys(e)){let c=Object.hasOwn(n,u);for(let[l,d]of i)l.test(u)&&(c=!0,f(u,this.coerceTypes((a??e)[u],d,r)));!c&&s!==void 0&&f(u,this.coerceTypes(e[u],s,r))}return a??e}coerceItems(e,t,r){return te(e,(n,i)=>{let s=at(t,i);return p(s)?this.coerceTypes(n,s,r):n})}};function at(e,t){return Array.isArray(e.items)?e.items[t]:Array.isArray(e.prefixItems)&&t<e.prefixItems.length?e.prefixItems[t]:e.items}o(at,"itemSchemaAt");function te(e,t){let r;for(let n=0;n<e.length;n++){let i=t(e[n],n);i!==e[n]&&(r??=e.slice(),r[n]=i)}return r??e}o(te,"mapItems");function T(e,t){return e===void 0?t:e.value}o(T,"orValue");function ft(e,t){if(e===t)return t;let r=typeof e=="string"?ut(t):typeof e=="number"?he(t):typeof e=="boolean"?pt(t):typeof e=="bigint"?ht(t):void 0;return r!==void 0&&r.value===e?r.value:t}o(ft,"convertLiteral");function ut(e){if(typeof e=="bigint"||typeof e=="boolean"||v(e))return{value:String(e)};if(e===null)return{value:"null"};if(typeof e=="string")return{value:e};if(e===void 0)return{value:""}}o(ut,"tryString");var ct=BigInt(Number.MAX_SAFE_INTEGER),lt=BigInt(Number.MIN_SAFE_INTEGER);function he(e){if(typeof e=="bigint")return e<=ct&&e>=lt?{value:Number(e)}:void 0;if(typeof e=="boolean")return{value:e?1:0};if(v(e))return{value:e};if(e==null)return{value:0};if(typeof e!="string")return;let t=+e;if(Number.isFinite(t))return{value:t};let r=e.toLowerCase();if(r==="false")return{value:0};if(r==="true")return{value:1};let n=dt(e);return n!==void 0&&n<=ct&&n>=lt?{value:Number(n)}:void 0}o(he,"tryNumber");function dt(e){if(/^-?(0|[1-9]\d*)n$/.test(e))return BigInt(e.slice(0,-1));if(/^-?(0|[1-9]\d*)\.\d+$/.test(e))return BigInt(e.split(".")[0]);if(/^-?(0|[1-9]\d*)$/.test(e))return BigInt(e)}o(dt,"bigIntOfString");function ht(e){if(typeof e=="bigint")return{value:e};if(typeof e=="boolean")return{value:e?1n:0n};if(v(e))return{value:BigInt(Math.trunc(e))};if(e==null)return{value:0n};if(typeof e!="string")return;let t=dt(e);if(t!==void 0)return{value:t};let r=e.toLowerCase();return r==="false"?{value:0n}:r==="true"?{value:1n}:void 0}o(ht,"tryBigInt");function mn(e){if(e==null||e===0n||e===!1||e===0)return{value:void 0};if(typeof e!="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:void 0}:void 0}o(mn,"tryUndefined");function pt(e){if(typeof e=="bigint")return e===0n?{value:!1}:e===1n?{value:!0}:void 0;if(typeof e=="boolean")return{value:e};if(v(e))return e===0?{value:!1}:e===1?{value:!0}:void 0;if(e==null)return{value:!1};if(typeof e!="string")return;let t=e.toLowerCase();if(t==="false"||e==="0")return{value:!1};if(t==="true"||e==="1")return{value:!0}}o(pt,"tryBoolean");function yn(e){if(typeof e=="bigint")return e===0n?{value:null}:void 0;if(typeof e=="boolean")return e===!1?{value:null}:void 0;if(v(e))return e===0?{value:null}:void 0;if(e==null)return{value:null};if(typeof e!="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:null}:void 0}o(yn,"tryNull");function v(e){return typeof e=="number"&&Number.isFinite(e)}o(v,"isFiniteNumber");function gn(e){return typeof e.type=="string"?[e.type]:Array.isArray(e.type)?e.type.filter(t=>typeof t=="string"):[]}o(gn,"typesOf");function In(e,t){switch(t){case"number":return Number.isFinite(e);case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"string":return typeof e=="string";case"null":return e===null;case"bigint":return typeof e=="bigint";case"undefined":return e===void 0;case"array":return Array.isArray(e);case"object":return re(e);default:return!1}}o(In,"matchesType");function An(e,t){switch(t){case"number":case"integer":{if(e===null)return 0;if(typeof e=="string"&&e.trim()!==""){let r=Number(e);if(t==="number"?Number.isFinite(r):Number.isInteger(r))return r}return typeof e=="boolean"?e?1:0:e}case"boolean":return e===null?!1:e==="true"||e===1?!0:e==="false"||e===0?!1:e;case"string":return e===null?"":typeof e=="number"||typeof e=="boolean"?String(e):e;case"null":return e===""||e===0||e===!1?null:e;default:return e}}o(An,"coercePrimitive");function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(re,"isPlainObject");function z(){return{props:null,allProps:!1,items:0,allItems:!1,indexes:null}}o(z,"newAnnotations");function pe(e,t){if(t.props!==null)for(let r of t.props)mt(e,r);if(e.allProps||=t.allProps,t.items>e.items&&(e.items=t.items),e.allItems||=t.allItems,t.indexes!==null)for(let r of t.indexes)yt(e,r)}o(pe,"merge");function mt(e,t){e.props===null&&(e.props=new Set),e.props.add(t)}o(mt,"addProp");function yt(e,t){e.indexes===null&&(e.indexes=new Set),e.indexes.add(t)}o(yt,"addIndex");var bn=o(()=>!0,"ANNOTATING_TRUE"),On=o(()=>!1,"ANNOTATING_FALSE");function kn(e){return(t,r)=>e.check(t,r)}o(kn,"indirectAnnotating");function En(e){return t=>e(t)}o(En,"ignoreAnnotations");function xn(e){return t=>e(t,z())}o(xn,"withFreshAnnotations");function gt(e,t,r){return(n,i)=>{e.push(t);let s=r(n,i);return e.pop(),s}}o(gt,"scopedAnnotating");function wn(e){return(t,r)=>{let n=z();return e(t,n)?(pe(r,n),!0):!1}}o(wn,"isolateAnnotations");function Rn(e,t){return(r,n)=>{if(!e(r))return!1;for(let i=0;i<t.length;i++)if(!t[i](r,n))return!1;return!0}}o(Rn,"annotateAll");function _n(e,t,r){let n=new Set(e.map(([i])=>i));return(i,s)=>{if(!O(i))return!0;let a=[];for(let[f,u]of e)if(Object.hasOwn(i,f)){if(!u(i[f]))return!1;a.push(f)}for(let f of Object.keys(i)){let u=n.has(f);for(let[c,l]of t)if(c.test(f)){if(!l(i[f]))return!1;u=!0,a.push(f)}if(!u&&r!==void 0){if(!r(i[f]))return!1;a.push(f)}}for(let f of a)mt(s,f);return!0}}o(_n,"annotateObject");function Nn(e,t,r,n,i){return(s,a)=>{if(!Array.isArray(s))return!0;let f=Math.min(s.length,e.length);for(let u=0;u<f;u++)if(!e[u](s[u]))return!1;if(t!==void 0){for(let u=e.length;u<s.length;u++)if(!t(s[u]))return!1;a.allItems=!0}if(f>a.items&&(a.items=f),r!==void 0){let u=0;for(let c=0;c<s.length;c++)r(s[c])&&(u++,yt(a,c));if(u<n||u>i)return!1}return!0}}o(Nn,"annotateArray");function It(e,t){return(r,n)=>{let i=0;for(let s of e){let a=z();s(r,a)&&(i++,pe(n,a))}return t?i===1:i>0}}o(It,"annotateAny");function $n(e,t,r){return(n,i)=>{let s=z();return e(n,s)?(pe(i,s),t===void 0||t(n,i)):r===void 0||r(n,i)}}o($n,"annotateIf");function Sn(e,t){return(r,n)=>!O(r)||!Object.hasOwn(r,e)||t(r,n)}o(Sn,"annotateDependent");function Cn(e){return(t,r)=>{if(!O(t)||r.allProps)return!0;for(let n of Object.keys(t))if(!(r.props?.has(n)??!1)&&!e(t[n]))return!1;return r.allProps=!0,!0}}o(Cn,"unevaluatedProperties");function Pn(e){return(t,r)=>{if(!Array.isArray(t)||r.allItems)return!0;for(let n=r.items;n<t.length;n++)if(!(r.indexes?.has(n)??!1)&&!e(t[n]))return!1;return r.allItems=!0,!0}}o(Pn,"unevaluatedItems");var At=Symbol("restart"),bt=class{static{o(this,"Compiler")}r;draft;formats;dynamic;schema;scope;cache=new Map;annotatingCache=new Map;constructor(e,t,r){this.schema=e,this.r=new un(e,t),this.draft=this.r.draft,this.formats=t.formats,this.dynamic=r,this.scope=[]}root(){return this.check(this.schema,this.r.rootBase)}check(e,t){if(e===!0)return C;if(e===!1)return fe;if(!p(e))throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let r=this.cache.get(e);if(r!==void 0)return r;let n=this.bareType(e);if(n!==void 0)return n;let i={check:void 0};this.cache.set(e,vr(i));let s=this.build(e,this.r.baseFor(e,t));return i.check=s,this.cache.set(e,s),s}build(e,t){if(this.draft==="7"&&typeof e.$ref=="string")return this.ref(e.$ref,t);if(this.draft!=="7"&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))return xn(this.annotating(e,t));let r=this.plain(e,t);return this.dynamic&&this.r.isResource(e,t)?Xe(this.scope,t,r):r}bareType(e){let t;for(let r in e)if(r==="type")t=e.type;else if(!Ot.has(r))return;return t===void 0?C:typeof t=="string"?K.get(t):void 0}plain(e,t){let r=[],n=e.type===void 0?void 0:Array.isArray(e.type)?e.type:[e.type],i=n?.length===1?n[0]:void 0,s=!1;if(i==="bytes")r.push(Wr(E(e.minLength)??0,E(e.maxLength)??Number.POSITIVE_INFINITY)),s=!0;else{let a=this.stringGroup(e,i==="string");a!==void 0&&r.push(a);let f=i==="number"||i==="integer"||i==="bigint",u=i==="number"?1:i==="integer"?2:i==="bigint"?3:0,c=this.numberGroup(e,u);c!==void 0&&r.push(c);let l=this.objectGroup(e,t,i==="object");l!==void 0&&r.push(l);let d=this.arrayGroup(e,t,i==="array");d!==void 0&&r.push(d),s=i==="string"&&a!==void 0||f&&c!==void 0||i==="object"&&l!==void 0||i==="array"&&d!==void 0}return n!==void 0&&!s&&r.unshift(zr(n)),this.inPlace(e,t,r),X(r)}inPlace(e,t,r){if(Array.isArray(e.enum)&&r.push(de(e.enum)),Object.hasOwn(e,"const")&&r.push(st(e.const)),Array.isArray(e.allOf)&&r.push(X(e.allOf.map(n=>this.check(n,t)))),Array.isArray(e.anyOf)&&r.push(this.union(e.anyOf,t,!1)),Array.isArray(e.oneOf)&&r.push(this.union(e.oneOf,t,!0)),e.not!==void 0&&r.push(on(this.check(e.not,t))),e.if!==void 0&&(e.then!==void 0||e.else!==void 0)){let n=e.then===void 0?C:this.check(e.then,t),i=e.else===void 0?C:this.check(e.else,t);r.push(an(this.check(e.if,t),n,i))}typeof e.$ref=="string"&&r.push(this.ref(e.$ref,t)),this.draft!=="7"&&typeof e.$dynamicRef=="string"&&r.push(this.dynamicRef(e.$dynamicRef,t))}union(e,t,r){let n=o(()=>e.map(i=>this.check(i,t)),"checks");return jn(e,r)??this.tagged(e,t)??(r?sn(n()):Ln(n()))}ref(e,t){let r=this.r.resolve(e,t),n=this.check(r.node,r.base);return this.dynamic&&r.base!==t?Xe(this.scope,r.base,n):n}dynamicRef(e,t){let r=this.bookended(e,t);if(r===void 0)return this.ref(e,t);let{initial:n,name:i}=r,s=this.check(n.node,n.base),a=this.dynamicLookup(i,(u,c)=>this.check(u,c)),f=this.scope;return u=>{for(let c=0;c<f.length;c++){let l=a(f[c]);if(l!==null)return l(u)}return s(u)}}bookended(e,t){let r=this.r.resolve(e,t),n=$(e,t),i=n.slice(S(n).length+1),s=p(r.node)&&r.node.$dynamicAnchor===i;if(!(i===""||i.startsWith("/")||!s)){if(!this.dynamic)throw At;return{initial:r,name:i}}}dynamicLookup(e,t){let r=new Map;return n=>{let i=`${n}#${e}`,s=r.get(i);if(s===void 0){let a=this.r.dynamicAnchors.get(i);s=a===void 0?null:t(a,this.r.baseOf.get(a)??n),r.set(i,s)}return s}}tagged(e,t){if(e.length<2)return;let r=[];for(let i of e){if(!p(i))return;let s=typeof i.$ref=="string"&&Object.keys(i).length===1?i.$ref:void 0,a=s===void 0?i:this.r.resolve(s,this.r.baseFor(i,t)).node;if(!p(a))return;r.push(a)}let n=r[0].properties;if(p(n))for(let i of Object.keys(n)){let s=r.map(a=>Un(a,i));if(!(s.some(a=>a===void 0)||new Set(s).size!==s.length))return fn(i,s,e.map(a=>this.check(a,t)))}}stringGroup(e,t){let r=E(e.minLength)??0,n=E(e.maxLength)??Number.POSITIVE_INFINITY,i=typeof e.pattern=="string"?_(e.pattern):void 0,s=this.formats!==void 0&&typeof e.format=="string"&&Object.hasOwn(this.formats,e.format)?this.formats[e.format]:void 0;if(!(r===0&&n===Number.POSITIVE_INFINITY&&i===void 0&&s===void 0))return Yr(t,r,n,i,s)}numberGroup(e,t){let r=B(e.minimum),n=B(e.maximum),i=B(e.exclusiveMinimum),s=B(e.exclusiveMaximum),a=B(e.multipleOf);if([r,n,i,s,a].every(u=>u===void 0))return;let f=Number.POSITIVE_INFINITY;return Vr(t,r??-f,n??f,i??-f,s??f,a)}objectGroup(e,t,r){let n=Tn.every(l=>e[l]===void 0),i=this.objectCore(e,t,n?r?He:F:J);if(i!==void 0&&n)return i;let s=i===void 0?[]:[i];e.propertyNames!==void 0&&s.push(Xr(this.check(e.propertyNames,t)));let a=E(e.minProperties),f=E(e.maxProperties);(a!==void 0||f!==void 0)&&s.push(Zr(a??0,f??Number.POSITIVE_INFINITY));let u=[],c=[];if(this.draft!=="7"){for(let[l,d]of M(e.dependentRequired))Array.isArray(d)&&u.push([l,d]);for(let[l,d]of M(e.dependentSchemas))c.push([l,this.check(d,t)])}for(let[l,d]of M(e.dependencies))Array.isArray(d)?u.push([l,d]):c.push([l,this.check(d,t)]);return u.length>0&&s.push(Qr(u)),c.length>0&&s.push(en(c)),s.length===0?r?Ge:void 0:qr(X(s),r)}objectCore(e,t,r){let n=p(e.properties)?e.properties:{},i=Array.isArray(e.required)?e.required.filter(m=>typeof m=="string"):[],s=p(e.patternProperties)?e.patternProperties:{},a=e.additionalProperties,f=Object.keys(n),u=Object.keys(s);if(f.length+i.length+u.length===0&&(a===void 0||a===!0))return;let c=[];for(let m of f){let w=this.check(n[m],t),j=Ye(w),ne=(j?.[0]??0)|(i.includes(m)?U:0)|(m in Object.prototype?Je:0);c.push(m,j===void 0?w:j[1],ne)}let l=i.filter(m=>!Object.hasOwn(n,m)),d=u.map(m=>[_(m),this.check(s[m],t)]),h=a===void 0||a===!0?void 0:this.check(a,t);if(d.length===0&&l.length===0&&(h===void 0||a===!1)){let m=f.filter(w=>i.includes(w)).length;return Kr(c,m,a===!1,r)}return Jr(c,f,l,d,h,r)}arrayGroup(e,t,r){let n=[],i;Array.isArray(e.items)?(n=e.items,i=e.additionalItems):(this.draft!=="7"&&Array.isArray(e.prefixItems)&&(n=e.prefixItems),i=e.items);let s=n.map(l=>this.check(l,t)),a=i===void 0||i===!0?void 0:this.check(i,t),f=E(e.minItems),u=E(e.maxItems);if(e.contains===void 0&&e.uniqueItems!==!0&&(s.length>0||a!==void 0))return rt(r?He:F,f??0,u??Number.POSITIVE_INFINITY,s,a);let c=[];if((s.length>0||a!==void 0)&&c.push(rn(s,a)),(f!==void 0||u!==void 0)&&c.push(nn(f??0,u??Number.POSITIVE_INFINITY)),e.contains!==void 0){let l=this.draft==="7"?1:E(e.minContains)??1,d=this.draft==="7"?Number.POSITIVE_INFINITY:E(e.maxContains)??Number.POSITIVE_INFINITY;c.push(nt(this.check(e.contains,t),l,d))}return e.uniqueItems===!0&&c.push(it),c.length===0?r?Be:void 0:Hr(X(c),r)}annotating(e,t){if(e===!0)return bn;if(e===!1)return On;if(!p(e))throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let r=this.annotatingCache.get(e);if(r!==void 0)return r;let n={check:void 0};this.annotatingCache.set(e,kn(n));let i=this.buildAnnotating(e,this.r.baseFor(e,t));return n.check=i,this.annotatingCache.set(e,i),i}buildAnnotating(e,t){let r={},n=!1;for(let u of Object.keys(e))Mn.has(u)?n=!0:r[u]=e[u];let i=this.plain(r,t),s=[];n&&this.annotatingParts(e,t,s);let a=s.length===0?En(i):Rn(i,s),f=e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0?wn(a):a;return this.dynamic&&this.r.isResource(e,t)?gt(this.scope,t,f):f}annotatingParts(e,t,r){if(e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0){let n=M(e.properties).map(([a,f])=>[a,this.check(f,t)]),i=M(e.patternProperties).map(([a,f])=>[_(a),this.check(f,t)]),s=e.additionalProperties===void 0?void 0:this.check(e.additionalProperties,t);r.push(_n(n,i,s))}if(e.prefixItems!==void 0||e.items!==void 0||e.contains!==void 0){let n=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[],i=Array.isArray(e.items)?e.additionalItems:e.items;r.push(Nn(n.map(s=>this.check(s,t)),i===void 0?void 0:this.check(i,t),e.contains===void 0?void 0:this.check(e.contains,t),E(e.minContains)??1,E(e.maxContains)??Number.POSITIVE_INFINITY))}if(Array.isArray(e.allOf))for(let n of e.allOf)r.push(this.annotating(n,t));if(Array.isArray(e.anyOf)&&r.push(It(e.anyOf.map(n=>this.annotating(n,t)),!1)),Array.isArray(e.oneOf)&&r.push(It(e.oneOf.map(n=>this.annotating(n,t)),!0)),e.if!==void 0){let n=e.then===void 0?void 0:this.annotating(e.then,t),i=e.else===void 0?void 0:this.annotating(e.else,t);r.push($n(this.annotating(e.if,t),n,i))}typeof e.$ref=="string"&&r.push(this.annotatingRef(e.$ref,t)),typeof e.$dynamicRef=="string"&&r.push(this.annotatingDynamicRef(e.$dynamicRef,t));for(let[n,i]of M(e.dependentSchemas))r.push(Sn(n,this.annotating(i,t)));e.unevaluatedProperties!==void 0&&r.push(Cn(this.check(e.unevaluatedProperties,t))),e.unevaluatedItems!==void 0&&r.push(Pn(this.check(e.unevaluatedItems,t)))}annotatingRef(e,t){let r=this.r.resolve(e,t),n=this.annotating(r.node,r.base);return this.dynamic&&r.base!==t?gt(this.scope,r.base,n):n}annotatingDynamicRef(e,t){let r=this.bookended(e,t);if(r===void 0)return this.annotatingRef(e,t);let{initial:n,name:i}=r,s=this.annotating(n.node,n.base),a=this.dynamicLookup(i,(u,c)=>this.annotating(u,c)),f=this.scope;return(u,c)=>{for(let l=0;l<f.length;l++){let d=a(f[l]);if(d!==null)return d(u,c)}return s(u,c)}}},Ot=new Set(["$schema","$comment","title","description","default","examples","deprecated","readOnly","writeOnly","$defs","definitions","contentEncoding","contentMediaType","minContains","maxContains","$vocabulary"]),Tn=["propertyNames","minProperties","maxProperties","dependentRequired","dependentSchemas","dependencies"],Mn=new Set(["properties","patternProperties","additionalProperties","prefixItems","items","additionalItems","contains","minContains","maxContains","allOf","anyOf","oneOf","if","then","else","$ref","$dynamicRef","dependentSchemas","unevaluatedProperties","unevaluatedItems"]);function jn(e,t){let r=[];for(let n of e){if(!p(n)||!Object.hasOwn(n,"const"))return;for(let i of Object.keys(n))if(i!=="const"&&!Ot.has(i))return;if(typeof n.const=="object"&&n.const!==null||t&&r.includes(n.const))return;r.push(n.const)}return de(r)}o(jn,"constUnion");function Ln(e){let t=[],r=[];for(let n of e){let i=Fn.get(n);i===void 0?r.push(n):t.push(i)}return t.length===0?ot(r):Gr(Ze(t),r)}o(Ln,"anyOf");var Fn=new Map([...K].map(([e,t])=>[t,e]));function Un(e,t){let r=e.properties;if(e.type!=="object"||!Array.isArray(e.required)||!e.required.includes(t))return;let n=p(r)?r[t]:void 0;if(!(!p(n)||!Object.hasOwn(n,"const")))return typeof n.const=="object"&&n.const!==null?void 0:n.const}o(Un,"tagOf");function B(e){return typeof e=="number"||typeof e=="bigint"?e:void 0}o(B,"bound");function E(e){return typeof e=="number"?e:void 0}o(E,"number");function M(e){return p(e)?Object.entries(e):[]}o(M,"entries");var Dn=class{static{o(this,"Explainer")}c;schema;memo=void 0;constructor(e,t){this.c=e,this.schema=t,e.root()}errors(e){let t=[];try{this.walk(this.schema,this.c.r.rootBase,e,"",t)}finally{this.memo=void 0}return t.length===0&&t.push({path:"",keyword:"schema",message:"invalid"}),t}ok(e,t,r){return this.c.check(e,t)(r)}walk(e,t,r,n,i){if(e===!0)return;if(e===!1){i.push({path:n,keyword:"false",message:"no value is allowed here"});return}if(!p(e))return;let s=this.c.r.baseFor(e,t);if(this.ok(e,s,r))return;let a=i.length,f=o((u,c,l=n)=>{i.push({path:l,keyword:u,message:c})},"push");if(this.c.draft==="7"&&typeof e.$ref=="string"){this.walkRef(e.$ref,s,r,n,i);return}if(e.type!==void 0){let u=Array.isArray(e.type)?e.type:[e.type];if(!u.map(c=>(typeof c=="string"?K.get(c):void 0)??fe).some(c=>c(r))){f("type",`expected ${u.join(" or ")}, got ${zn(r)}`);return}}if(Array.isArray(e.enum)&&!de(e.enum)(r)&&f("enum",`expected one of ${kt(e.enum)}`),Object.hasOwn(e,"const")&&!st(e.const)(r)&&f("const",`expected ${JSON.stringify(e.const)}`),typeof r=="string"&&e.type!=="bytes"&&this.walkString(e,r,f),r instanceof Uint8Array&&e.type==="bytes"&&this.walkBytes(e,r,f),(typeof r=="number"||typeof r=="bigint")&&this.walkNumber(e,r,f),O(r)&&this.walkObject(e,s,r,n,i,f),Array.isArray(r)&&this.walkArray(e,s,r,n,i,f),Array.isArray(e.allOf))for(let u of e.allOf)this.walk(u,s,r,n,i);if(Array.isArray(e.anyOf)&&this.walkUnion(e.anyOf,s,r,n,i,!1),Array.isArray(e.oneOf)&&this.walkUnion(e.oneOf,s,r,n,i,!0),e.not!==void 0&&this.ok(e.not,s,r)&&f("not","must not match the schema in not"),e.if!==void 0){let u=this.ok(e.if,s,r)?e.then:e.else;u!==void 0&&this.walk(u,s,r,n,i)}typeof e.$ref=="string"&&this.walkRef(e.$ref,s,r,n,i),i.length===a&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0)&&this.walkUnevaluated(e,s,r,n,i),i.length===a&&typeof e.$dynamicRef=="string"&&f("$dynamicRef","does not match the dynamically referenced schema")}walkRef(e,t,r,n,i){let s=this.c.r.resolve(e,t);if(s.node===!1&&this.c.r.isUnresolved(e,t)){i.push({path:n,keyword:"$ref",message:`unresolved reference ${e}`});return}if(!p(s.node)||typeof r!="object"||r===null){this.walk(s.node,s.base,r,n,i);return}this.memo??=new Map;let a=this.memo.get(s.node),f=a?.get(r);if(f!==void 0&&f.path===n){i.push(...f.errors);return}let u=[];this.walk(s.node,s.base,r,n,u),a===void 0&&(a=new Map,this.memo.set(s.node,a)),a.set(r,{path:n,errors:u}),i.push(...u)}walkString(e,t,r){let n=le(t);typeof e.minLength=="number"&&n<e.minLength&&r("minLength",`expected at least ${e.minLength} characters`),typeof e.maxLength=="number"&&n>e.maxLength&&r("maxLength",`expected at most ${e.maxLength} characters`),typeof e.pattern=="string"&&!_(e.pattern).test(t)&&r("pattern",`expected to match ${e.pattern}`);let i=this.c.formats,s=i!==void 0&&typeof e.format=="string"&&Object.hasOwn(i,e.format)?i[e.format]:void 0;s!==void 0&&!s(t)&&r("format",`expected format ${e.format}`)}walkBytes(e,t,r){typeof e.minLength=="number"&&t.length<e.minLength&&r("minLength",`expected at least ${e.minLength} bytes`),typeof e.maxLength=="number"&&t.length>e.maxLength&&r("maxLength",`expected at most ${e.maxLength} bytes`)}walkNumber(e,t,r){let{minimum:n,maximum:i,exclusiveMinimum:s,exclusiveMaximum:a,multipleOf:f}=e;G(n)&&t<n&&r("minimum",`expected >= ${n}`),G(i)&&t>i&&r("maximum",`expected <= ${i}`),G(s)&&t<=s&&r("exclusiveMinimum",`expected > ${s}`),G(a)&&t>=a&&r("exclusiveMaximum",`expected < ${a}`),G(f)&&!et(t,f)&&r("multipleOf",`expected a multiple of ${f}`)}walkObject(e,t,r,n,i,s){let a=p(e.properties)?e.properties:{},f=Array.isArray(e.required)?e.required:[];for(let d of f){if(typeof d!="string")continue;let h=r[d]===void 0&&Object.hasOwn(a,d)&&this.ok(a[d],t,void 0);(!Object.hasOwn(r,d)||r[d]===void 0&&!h)&&s("required","missing",R(n,d))}for(let d of Object.keys(a))Object.hasOwn(r,d)&&r[d]!==void 0&&this.walk(a[d],t,r[d],R(n,d),i);let u=p(e.patternProperties)?Object.entries(e.patternProperties):[];for(let d of Object.keys(r)){let h=Object.hasOwn(a,d);for(let[m,w]of u)_(m).test(d)&&(h=!0,this.walk(w,t,r[d],R(n,d),i));!h&&e.additionalProperties!==void 0&&(e.additionalProperties===!1?s("additionalProperties","unknown field",R(n,d)):this.walk(e.additionalProperties,t,r[d],R(n,d),i)),e.propertyNames!==void 0&&!this.ok(e.propertyNames,t,d)&&s("propertyNames","invalid property name",R(n,d))}let c=Object.keys(r).length;typeof e.minProperties=="number"&&c<e.minProperties&&s("minProperties",`expected at least ${e.minProperties} properties`),typeof e.maxProperties=="number"&&c>e.maxProperties&&s("maxProperties",`expected at most ${e.maxProperties} properties`);let l={...this.c.draft==="7"||!p(e.dependentRequired)?{}:e.dependentRequired,...p(e.dependencies)?e.dependencies:{}};for(let[d,h]of Object.entries(l))if(Object.hasOwn(r,d))if(!Array.isArray(h))this.walk(h,t,r,n,i);else for(let m of h)Object.hasOwn(r,m)||s("dependentRequired",`required when ${d} is present`,R(n,m));if(this.c.draft!=="7"&&p(e.dependentSchemas))for(let[d,h]of Object.entries(e.dependentSchemas))Object.hasOwn(r,d)&&this.walk(h,t,r,n,i)}walkArray(e,t,r,n,i,s){let a=[],f;Array.isArray(e.items)?(a=e.items,f=e.additionalItems):(this.c.draft!=="7"&&Array.isArray(e.prefixItems)&&(a=e.prefixItems),f=e.items);for(let u=0;u<r.length;u++){let c=u<a.length?a[u]:f;c!==void 0&&this.walk(c,t,r[u],`${n}/${u}`,i)}if(typeof e.minItems=="number"&&r.length<e.minItems&&s("minItems",`expected at least ${e.minItems} items`),typeof e.maxItems=="number"&&r.length>e.maxItems&&s("maxItems",`expected at most ${e.maxItems} items`),e.uniqueItems===!0&&!it(r)&&s("uniqueItems","expected unique items"),e.contains!==void 0){let u=this.c.draft==="7",c=u||typeof e.minContains!="number"?1:e.minContains,l=u||typeof e.maxContains!="number"?Number.POSITIVE_INFINITY:e.maxContains;nt(this.c.check(e.contains,t),c,l)(r)||s("contains",vn(c,l))}}walkUnion(e,t,r,n,i,s){let a=e.filter(l=>this.ok(l,t,r)).length;if(a===1||!s&&a>0)return;let f=s?"oneOf":"anyOf";if(a>1){i.push({path:n,keyword:f,message:"matches more than one alternative"});return}let u=this.tagOf(e,t);if(u!==void 0&&O(r)){let l=u.values.indexOf(r[u.key]);l<0?i.push({path:R(n,u.key),keyword:f,message:`expected one of ${kt(u.values)}`}):this.walk(e[l],t,r,n,i);return}let c;for(let l of e){let d=[];if(this.walk(l,t,r,n,d),d.length===0)continue;let h=O(r)?this.declaredKeys(l,t,r):0;(c===void 0||h>c.declared||h===c.declared&&d[0].path.length>c.errors[0].path.length)&&(c={errors:d,declared:h})}i.push(...c?.errors??[{path:n,keyword:f,message:"matches no alternative"}])}declaredKeys(e,t,r){let n=p(e)&&typeof e.$ref=="string"?this.c.r.resolve(e.$ref,this.c.r.baseFor(e,t)).node:e,i=p(n)&&p(n.properties)?n.properties:{};return Object.keys(r).filter(s=>Object.hasOwn(i,s)).length}tagOf(e,t){let r=e.map(i=>p(i)&&typeof i.$ref=="string"?this.c.r.resolve(i.$ref,this.c.r.baseFor(i,t)).node:i),n=r[0];if(!(!p(n)||!p(n.properties)))for(let i of Object.keys(n.properties)){let s=r.map(a=>{let f=p(a)&&p(a.properties)?a.properties[i]:void 0;return p(f)?f.const:void 0});if(s.every(a=>a!==void 0&&(typeof a!="object"||a===null))&&new Set(s).size===s.length)return{key:i,values:s}}}walkUnevaluated(e,t,r,n,i){let{unevaluatedProperties:s,unevaluatedItems:a,$id:f,...u}=e,c=z();if(this.c.annotating(u,t)(r,c),O(r)&&s!==void 0&&!c.allProps)for(let l of Object.keys(r))c.props?.has(l)||(s===!1?i.push({path:R(n,l),keyword:"unevaluatedProperties",message:"unknown field"}):this.walk(s,t,r[l],R(n,l),i));if(Array.isArray(r)&&a!==void 0&&!c.allItems)for(let l=c.items;l<r.length;l++)c.indexes?.has(l)||(a===!1?i.push({path:`${n}/${l}`,keyword:"unevaluatedItems",message:"unexpected item"}):this.walk(a,t,r[l],`${n}/${l}`,i))}},me=20;function kt(e){return e.length<=me?JSON.stringify(e):`${JSON.stringify(e.slice(0,me)).slice(0,-1)}, ... and ${e.length-me} more]`}o(kt,"listValues");function vn(e,t){return t===Number.POSITIVE_INFINITY?`expected at least ${e} matching ${e===1?"item":"items"}`:e===0?`expected at most ${t} matching ${t===1?"item":"items"}`:`expected between ${e} and ${t} matching items`}o(vn,"containsMessage");function G(e){return typeof e=="number"||typeof e=="bigint"}o(G,"isBound");function R(e,t){return`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`}o(R,"pointer");function zn(e){return e===null?"null":Array.isArray(e)?"array":e instanceof Uint8Array?"bytes":typeof e=="bigint"?"bigint":typeof e=="number"&&Number.isInteger(e)?"integer":typeof e=="number"&&!Number.isFinite(e)?String(e):typeof e}o(zn,"typeName");function Bn(e,t=Gn){let r=Yn(e,t);return t.coerce===!0?new Wn(e,t,r):new Et(e,t,r)}o(Bn,"compile");var Gn=Object.freeze({}),Et=class{static{o(this,"Validator")}check;schema;options;explainer=void 0;constructor(e,t,r){this.check=r,this.schema=e,this.options=t}errors(e){return this.check(e)?[]:(this.explainer??=new Dn(ye(this.schema,this.options),this.schema),this.explainer.errors(e))}validate(e){return this.check(e)?{ok:!0,value:e}:{ok:!1,errors:this.errors(e)}}},Wn=class extends Et{static{o(this,"CoercingValidator")}coercer=void 0;coerce(e){return this.coercer??=new pn(ye(this.schema,this.options),this.schema),this.coercer.coerce(e)}parse(e){return this.validate(this.coerce(e))}};function Yn(e,t){return ye(e,t).root()}o(Yn,"compileCheck");function ye(e,t){let r=new bt(e,t,!1);try{return r.root(),r}catch(n){if(n!==At)throw n;return new bt(e,t,!0)}}o(ye,"compiler");var Vn=[0,31,28,31,30,31,30,31,31,30,31,30,31],qn=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Hn(e){return e%4===0&&(e%100!==0||e%400===0)}o(Hn,"IsLeapYear");function xt(e){let t=qn.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&Hn(r)?29:Vn[n])}o(xt,"IsDate");var Kn=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function wt(e,t=!0){let r=Kn.exec(e);if(!r||t&&!r[4]&&!r[5])return!1;let n=+r[1],i=+r[2],s=+r[3];if(n>23||i>59||s>60)return!1;if(r[5]){let c=+r[6],l=+r[7];if(c>23||l>59)return!1}if(s<60)return!0;let a=r[5]==="-"?-1:1,f=+(r[6]||0),u=+(r[7]||0);return((n*60+i-a*(f*60+u))%1440+1440)%1440===1439}o(wt,"IsTime");function Jn(e){let t=e.split(/T/i);return t.length===2&&xt(t[0])&&wt(t[1])}o(Jn,"IsDateTime");var Xn=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Zn(e){return Xn.test(e)}o(Zn,"IsDuration");var Qn=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function ei(e){return Qn.test(e)}o(ei,"IsEmail");var ti=/^(?!-).*(?<!-)$/,ri=/^(?!..--)/,ni=/^[a-zA-Z0-9-]*$/,Ns=new RegExp("^\\p{ASCII}*$","u"),ge=/[^\p{ASCII}]/u,ii=/[0-9]/,si=/[\u{0660}-\u{0669}]/u,oi=/[\u{06f0}-\u{06f9}]/u,ai=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,fi=/[\u{002d}\u{002b}]/u,Rt=new RegExp("\\p{Mn}","u"),ui=new RegExp("\\p{Mc}","u"),$s=new RegExp("\\p{Me}","u"),ci=/[\p{Mn}\p{Mc}\p{Me}]/u,_t=new RegExp("\\p{L}","u"),li=new RegExp("\\p{Nd}","u"),di=new RegExp("\\p{Script=Greek}","u"),Nt=new RegExp("\\p{Script=Hebrew}","u"),hi=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,pi=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,$t=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,mi=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,yi=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,gi=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Ii=new RegExp([ii,oi].map(e=>e.source).join("|"),"u"),Ai=new RegExp([_t,fi,ai,li,Rt,ui,yi,gi].map(e=>e.source).join("|"),"u");function bi(e){return ti.test(e)&&ri.test(e)&&ni.test(e)}o(bi,"IsAsciiLabel");var x=36,W=1,Y=26,Oi=38,ki=700,St=72,Ct=128;function Ie(){throw null}o(Ie,"ThrowDontCare");function Pt(e){return e.toLowerCase().startsWith("xn--")}o(Pt,"IsAcePrefixed");function Tt(e,t,r){e=r?Math.floor(e/ki):e>>1,e+=Math.floor(e/t);let n=0;for(;e>(x-W)*Y>>1;)e=Math.floor(e/(x-W)),n+=x;return n+Math.floor((x-W+1)*e/(e+Oi))}o(Tt,"Adapt");function Mt(e){let t=[],r=Ct,n=0,i=St,s=e.lastIndexOf("-");if(s>0)for(let f=0;f<s;f++){let u=e.charCodeAt(f);u>=128&&Ie(),t.push(u)}let a=s<0?0:s+1;for(;a<e.length;){let f=n,u=1,c=x;for(;;){a>=e.length&&Ie();let d=e.charCodeAt(a++),h;d>=97&&d<=122?h=d-97:d>=48&&d<=57?h=d-48+26:Ie(),n+=h*u;let m=c<=i?W:c>=i+Y?Y:c-i;if(h<m)break;u*=x-m,c+=x}let l=t.length+1;i=Tt(n-f,l,f===0),r+=Math.floor(n/l),n%=l,t.splice(n,0,r),n++}return String.fromCodePoint(...t)}o(Mt,"Decode");function jt(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}o(jt,"DigitToChar");var Ei=new RegExp(ge.source,"gu");function xi(e){let t=e.replace(Ei,""),r=t.length,n=r>0?[t,"-"]:[],i=Array.from(e,c=>c.codePointAt(0)),s=Ct,a=0,f=St,u=r;for(;u<i.length;){let c=1/0;for(let l of i)l>=s&&l<c&&(c=l);a+=(c-s)*(u+1),s=c;for(let l of i)if(l<s&&a++,l===s){let d=a;for(let h=x;;h+=x){let m=h<=f?W:h>=f+Y?Y:h-f;if(d<m)break;let w=m+(d-m)%(x-m);n.push(jt(w)),d=Math.floor((d-m)/(x-m))}n.push(jt(d)),f=Tt(a,u+1,u===r),a=0,u++}a++,s++}return n.join("")}o(xi,"Encode");var wi=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Lt=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,Ri=/^(?:R|AL|AN)$/;function _i(e){if(Pt(e))try{return Ae(Mt(e.slice(4).toLowerCase()))}catch{return!1}return Ae(e)}o(_i,"HasBidiChars");function Ft(e){let t=String.fromCodePoint(e);return Ii.test(t)?"EN":si.test(t)?"AN":Rt.test(t)?"NSM":Nt.test(t)?"R":pi.test(t)?"AL":_t.test(t)?"L":"ON"}o(Ft,"GetBidiClass");function Ae(e){for(let t of e)if(Ri.test(Ft(t.codePointAt(0))))return!0;return!1}o(Ae,"HasRightToLeftCharacters");function Ut(e){let t=!1,r=Lt,n=!1,i=!1,s=!0;for(let a of e){let f=Ft(a.codePointAt(0));if(s){if(f!=="L"&&f!=="R"&&f!=="AL")return!1;t=f==="R"||f==="AL",r=t?wi:Lt,s=!1}if(!r.test(f))return!1;f==="EN"?n=!0:f==="AN"&&(i=!0)}return!(t&&n&&i)}o(Ut,"SatisfiesBidiRule");function Ni(e){return ge.test(e)&&xi(e).length+4>63}o(Ni,"ExceedsMaxALabelLength");function $i(e){return e[0]==="-"||e[e.length-1]==="-"?!0:e.slice(2).join("").startsWith("--")}o($i,"HasInvalidHyphens");function Dt(e){if(Ni(e)||Ae(e)&&!Ut(e))return!1;let t=[...e],r=t.map(s=>s.codePointAt(0)),n=r.length;if($i(t)||ci.test(t[0]))return!1;let i=!1;for(let s=0;s<n;s++){let a=r[s],f=t[s];if(mi.test(f)||!Ai.test(f))return!1;hi.test(f)&&(i=!0);let u=r[s-1],c=r[s+1];switch(a){case 183:if(u!==108||c!==108)return!1;break;case 885:if(!c||!di.test(t[s+1]))return!1;break;case 1523:case 1524:if(!u||!Nt.test(t[s-1]))return!1;break;case 8204:if(!u||u<128&&!$t.test(t[s-1]))return!1;break;case 8205:if(!u||!$t.test(t[s-1]))return!1;break;case 12539:break}}return!(e.includes("\u30FB")&&!i)}o(Dt,"IsUnicodeLabel");function vt(e){if(!Pt(e))return!1;try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf("-")===0)return!1;let r=Mt(t);return ge.test(r)?Dt(r):!1}catch{return!1}}o(vt,"IsPunyLabel");function Si(e){return e.length>0&&e.length<=63}o(Si,"IsValidLabelLength");function Ci(e){return Si(e)&&(vt(e)||bi(e))}o(Ci,"IsLabel");function Pi(e){return e.length===0||e.length>253||e.charCodeAt(e.length-1)===46?!1:e.split(".").every(t=>Ci(t))}o(Pi,"IsHostname");function Ti(e){return e.length>0&&e.length<=63}o(Ti,"IsValidLabelLength2");function Mi(e){return Ti(e)&&(vt(e)||Dt(e))}o(Mi,"IsLabel2");function ji(e){return e.replace(/[\uff01-\uff5e]/g,t=>String.fromCharCode(t.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}o(ji,"NormalizeHostname");function Li(e){if(e.length===0||e.includes(" "))return!1;let t=ji(e);if(t.length>253)return!1;let r=t.split("."),n=r.some(i=>_i(i));return r.every(i=>Mi(i)&&(!n||Ut(i)))}o(Li,"IsIdnHostname");function Fi(e){return Pi(e)}o(Fi,"IsHostname2");var Ui=/^(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Di(e){return Ui.test(e.normalize("NFC"))}o(Di,"IsIdnEmail");function vi(e){return Li(e)}o(vi,"IsIdnHostname2");var zi=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Bi(e){return zi.test(e)}o(Bi,"IsIPv4");var Gi=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Wi(e){return Gi.test(e)}o(Wi,"IsIPv6");var Yi=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,Vi=/[\x00-\x20<>^`{|}\\]/,qi=/%(?![0-9a-fA-F]{2})/;function Hi(e){return e.length<2048?e.replace(Yi,"[::1]"):e}o(Hi,"NarrowIpvFuture");function Ki(e){return Vi.test(e)||qi.test(e)?!1:URL.canParse(Hi(e))}o(Ki,"IsIri");var Ji=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,Xi=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Zi(e){return!Ji.test(e)&&!Xi.test(e)&&URL.canParse(e,"http://example.com")}o(Zi,"IsIriReference");var Qi=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function es(e){return Qi.test(e)}o(es,"IsJsonPointer");var ts=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function rs(e){return ts.test(e)}o(rs,"IsJsonPointerUriFragment");function ns(e){try{return new RegExp(e,"u"),!0}catch{return!1}}o(ns,"IsRegex");var is=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function ss(e){return is.test(e)}o(ss,"IsRelativeJsonPointer");var os=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function as(e){return os.test(e)}o(as,"IsUri");var fs=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function us(e){return fs.test(e)}o(us,"IsUriReference");var cs=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function ls(e){return cs.test(e)}o(ls,"IsUriTemplate");function ds(e){return URL.canParse(e)}o(ds,"IsUrl");var hs=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function ps(e){return hs.test(e)}o(ps,"IsUuid");var ms=Object.freeze({date:xt,"date-time":Jn,duration:Zn,email:ei,hostname:Fi,"idn-email":Di,"idn-hostname":vi,ipv4:Bi,ipv6:Wi,iri:Ki,"iri-reference":Zi,"json-pointer":es,"json-pointer-uri-fragment":rs,regex:ns,"relative-json-pointer":ss,time:wt,uri:as,"uri-reference":us,"uri-template":ls,url:ds,uuid:ps}),zt=new WeakMap;function ys(e){let t=zt.get(e);if(t)return t;let r=Bn(e,{formats:ms,coerce:!0,unresolvedRefs:"reject"});return zt.set(e,r),r}o(ys,"getValidator");function gs(e){return e===""?"root":e.slice(1).split("/").map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")}o(gs,"formatValidationPath");function Is(e,t){let r=e.find(n=>n.name===t.name);if(!r)throw new Error(`Tool "${t.name}" not found`);return Bt(r,t)}o(Is,"validateToolCall");function Bt(e,t){if(t.argumentsError)throw new Error(`Invalid arguments for tool "${t.name}": ${t.argumentsError}`);let r=ys(e.parameters).parse(structuredClone(t.arguments));if(r.ok)return r.value;let n=r.errors.map(s=>` - ${gs(s.path)}: ${s.message}`).join(`
10
+ `),i=`Validation failed for tool "${t.name}":
11
+ ${n}
12
+
13
+ Received arguments:
14
+ ${JSON.stringify(t.arguments,null,2)}`;throw new Error(i)}o(Bt,"validateToolArguments");export{ke as CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY,er as CACHE_WARMING_MAX_AGE_MS,tr as CACHE_WARMING_MAX_IDLE_AGE_MS,Oe as CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS,Mr as arr,Sr as bool,Me as createFauxCore,Zt as envApiKeyAuth,or as evaluateCacheWarming,hr as fauxAssistantMessage,Ar as fauxProvider,_e as fauxText,cr as fauxThinking,lr as fauxToolCall,rr as getCacheWarmingDelayMs,sr as getCacheWarmingRequestOptions,Rr as getOverflowPatterns,nr as getPromptCacheTtlMs,$r as int,ir as isCacheWarmingReplayable,kr as isContextOverflow,wr as isRecoverableLength,Qt as lazyOAuth,Cr as nul,Nr as num,Lr as obj,Pr as oneOf,jr as opt,_r as str,Tr as union,Bt as validateToolArguments,Is as validateToolCall};