@cortexkit/opencode-openai-auth 0.11.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +15 -26
  2. package/dist/index-766sfrh5.js +1 -0
  3. package/dist/index-8kj7sa1p.js +12 -0
  4. package/dist/index-8rqfbhfw.js +221 -0
  5. package/dist/index-b3q3j39x.js +2 -0
  6. package/dist/index-bmd7x5aq.js +2 -0
  7. package/dist/index-eqh53k8v.js +2 -0
  8. package/dist/{index-sdt2d2ra.js → index-hy9030jh.js} +1 -1
  9. package/dist/index-jyr8y8k4.js +7 -0
  10. package/dist/index-rv08jmd4.js +2 -0
  11. package/dist/index.d.ts +578 -145
  12. package/dist/index.js +1 -110
  13. package/dist/pool-lifecycle-DbDmgabd.d.ts +2430 -0
  14. package/dist/port-file-Do3lQIEk.d.ts +29 -0
  15. package/dist/protocol-BOBdkqqm.d.ts +198 -0
  16. package/dist/rpc/port-file.d.ts +4 -17
  17. package/dist/rpc/port-file.js +1 -1
  18. package/dist/rpc/protocol.d.ts +2 -2
  19. package/dist/rpc/protocol.js +1 -0
  20. package/dist/rpc/rpc-client.d.ts +5 -4
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.d.ts +2 -0
  23. package/dist/rpc/rpc-dir.js +1 -1
  24. package/dist/sidebar-state-D6cUKgkm.d.ts +385 -0
  25. package/dist/sidebar-state.d.ts +2 -2
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/token-util-wdza526f.js +1 -0
  28. package/dist/{token-9823y0pc.js → token-ypk61xj0.js} +1 -1
  29. package/dist/tui-preferences.js +5 -2
  30. package/dist/tui.d.ts +9 -4
  31. package/dist/v2/server.d.ts +54 -0
  32. package/dist/v2/server.js +4 -0
  33. package/package.json +21 -9
  34. package/src/tui/entry.mjs +26 -25
  35. package/src/tui-compiled/raw/logger.js +24 -0
  36. package/src/tui-compiled/raw/rpc/protocol.js +3 -0
  37. package/src/tui-compiled/raw/rpc/rpc-client.js +7 -0
  38. package/src/tui-compiled/raw/rpc/rpc-dir.js +27 -0
  39. package/src/tui-compiled/raw/selector.js +21 -0
  40. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +138 -0
  41. package/src/tui-compiled/raw/shared/04a6357627de5ed0-errors.js +38 -0
  42. package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +12 -0
  43. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +157 -0
  44. package/src/tui-compiled/raw/shared/08eef45626a94992-reserved.js +13 -0
  45. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +134 -0
  46. package/src/tui-compiled/raw/shared/3c2d4169d00f907e-tui-support.js +5 -0
  47. package/src/tui-compiled/raw/shared/3e7d45a77c6ad4d5-index.js +4 -0
  48. package/src/tui-compiled/raw/shared/415792e85d80819e-capture-sink.js +13 -0
  49. package/src/tui-compiled/raw/shared/42ae93ab554fcec2-open-url.js +28 -0
  50. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +136 -0
  51. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +500 -0
  52. package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +142 -0
  53. package/src/tui-compiled/raw/shared/46f3dff1266160e8-client.js +2 -0
  54. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +48 -0
  55. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +162 -0
  56. package/src/tui-compiled/raw/shared/54eba94fd64c8c3c-index.js +7 -0
  57. package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +80 -0
  58. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +534 -0
  59. package/src/tui-compiled/raw/shared/75bd8c3bd63b315f-identity.js +79 -0
  60. package/src/tui-compiled/raw/shared/7a91bb630e6f4804-index.js +1 -0
  61. package/src/tui-compiled/raw/shared/826342a4b6a8b89b-model.js +16 -0
  62. package/src/tui-compiled/raw/shared/83068c0dbe8a6f13-publication.js +304 -0
  63. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +120 -0
  64. package/src/tui-compiled/raw/shared/83bc3ba9d0fe2761-runtime.js +68 -0
  65. package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +300 -0
  66. package/src/tui-compiled/raw/shared/901e149c5a0dbbff-sticky.js +339 -0
  67. package/src/tui-compiled/raw/shared/9020c407ce64f672-ordered.js +58 -0
  68. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +105 -0
  69. package/src/tui-compiled/raw/shared/94820e324f2b4c09-seam.js +301 -0
  70. package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +226 -0
  71. package/src/tui-compiled/raw/shared/9968e3cade6969a1-index.js +2 -0
  72. package/src/tui-compiled/raw/shared/9b4da614c45f9cd0-lock-constants.js +14 -0
  73. package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +225 -0
  74. package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +34 -0
  75. package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +77 -0
  76. package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +60 -0
  77. package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +143 -0
  78. package/src/tui-compiled/raw/shared/b85c5301fddcb98a-paths.js +5 -0
  79. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +217 -0
  80. package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +157 -0
  81. package/src/tui-compiled/raw/shared/c6b176708c446d6d-pins.js +34 -0
  82. package/src/tui-compiled/raw/shared/c7d252bedee01600-pi.js +206 -0
  83. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +120 -0
  84. package/src/tui-compiled/raw/shared/cc9e0702a752cea7-index.js +3 -0
  85. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +754 -0
  86. package/src/tui-compiled/raw/shared/d319517e3ea6ad70-redact.js +83 -0
  87. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +5 -0
  88. package/src/tui-compiled/raw/shared/d669d72c40e9e116-logger.js +19 -0
  89. package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +246 -0
  90. package/src/tui-compiled/raw/shared/dbef697d1df1cd84-index.js +5 -0
  91. package/src/tui-compiled/raw/shared/e4acc4cb713f300c-protocol.js +3 -0
  92. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +501 -0
  93. package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +6 -0
  94. package/src/tui-compiled/raw/shared/f37fcefc7aedbf25-error.js +11 -0
  95. package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +253 -0
  96. package/src/tui-compiled/raw/shared/fd45e82f2f9c0a0d-torn.js +294 -0
  97. package/src/tui-compiled/raw/shared/fe02abeadc535f77-rows.js +1258 -0
  98. package/src/tui-compiled/raw/sidebar-state.js +960 -0
  99. package/src/tui-compiled/raw/tui/command-dialogs.tsx +424 -0
  100. package/src/tui-compiled/raw/tui-preferences.js +135 -0
  101. package/src/tui-compiled/raw/tui.tsx +135 -143
  102. package/src/tui-compiled/runtime/logger.js +24 -0
  103. package/src/tui-compiled/runtime/rpc/protocol.js +3 -0
  104. package/src/tui-compiled/runtime/rpc/rpc-client.js +7 -0
  105. package/src/tui-compiled/runtime/rpc/rpc-dir.js +27 -0
  106. package/src/tui-compiled/runtime/selector.js +21 -0
  107. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +138 -0
  108. package/src/tui-compiled/runtime/shared/04a6357627de5ed0-errors.js +38 -0
  109. package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +12 -0
  110. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +157 -0
  111. package/src/tui-compiled/runtime/shared/08eef45626a94992-reserved.js +13 -0
  112. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +134 -0
  113. package/src/tui-compiled/runtime/shared/3c2d4169d00f907e-tui-support.js +5 -0
  114. package/src/tui-compiled/runtime/shared/3e7d45a77c6ad4d5-index.js +4 -0
  115. package/src/tui-compiled/runtime/shared/415792e85d80819e-capture-sink.js +13 -0
  116. package/src/tui-compiled/runtime/shared/42ae93ab554fcec2-open-url.js +28 -0
  117. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +136 -0
  118. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +500 -0
  119. package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +142 -0
  120. package/src/tui-compiled/runtime/shared/46f3dff1266160e8-client.js +2 -0
  121. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +48 -0
  122. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +162 -0
  123. package/src/tui-compiled/runtime/shared/54eba94fd64c8c3c-index.js +7 -0
  124. package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +80 -0
  125. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +534 -0
  126. package/src/tui-compiled/runtime/shared/75bd8c3bd63b315f-identity.js +79 -0
  127. package/src/tui-compiled/runtime/shared/7a91bb630e6f4804-index.js +1 -0
  128. package/src/tui-compiled/runtime/shared/826342a4b6a8b89b-model.js +16 -0
  129. package/src/tui-compiled/runtime/shared/83068c0dbe8a6f13-publication.js +304 -0
  130. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +120 -0
  131. package/src/tui-compiled/runtime/shared/83bc3ba9d0fe2761-runtime.js +68 -0
  132. package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +300 -0
  133. package/src/tui-compiled/runtime/shared/901e149c5a0dbbff-sticky.js +339 -0
  134. package/src/tui-compiled/runtime/shared/9020c407ce64f672-ordered.js +58 -0
  135. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +105 -0
  136. package/src/tui-compiled/runtime/shared/94820e324f2b4c09-seam.js +301 -0
  137. package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +226 -0
  138. package/src/tui-compiled/runtime/shared/9968e3cade6969a1-index.js +2 -0
  139. package/src/tui-compiled/runtime/shared/9b4da614c45f9cd0-lock-constants.js +14 -0
  140. package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +225 -0
  141. package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +34 -0
  142. package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +77 -0
  143. package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +60 -0
  144. package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +143 -0
  145. package/src/tui-compiled/runtime/shared/b85c5301fddcb98a-paths.js +5 -0
  146. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +217 -0
  147. package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +157 -0
  148. package/src/tui-compiled/runtime/shared/c6b176708c446d6d-pins.js +34 -0
  149. package/src/tui-compiled/runtime/shared/c7d252bedee01600-pi.js +206 -0
  150. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +120 -0
  151. package/src/tui-compiled/runtime/shared/cc9e0702a752cea7-index.js +3 -0
  152. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +754 -0
  153. package/src/tui-compiled/runtime/shared/d319517e3ea6ad70-redact.js +83 -0
  154. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +5 -0
  155. package/src/tui-compiled/runtime/shared/d669d72c40e9e116-logger.js +19 -0
  156. package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +246 -0
  157. package/src/tui-compiled/runtime/shared/dbef697d1df1cd84-index.js +5 -0
  158. package/src/tui-compiled/runtime/shared/e4acc4cb713f300c-protocol.js +3 -0
  159. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +501 -0
  160. package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +6 -0
  161. package/src/tui-compiled/runtime/shared/f37fcefc7aedbf25-error.js +11 -0
  162. package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +253 -0
  163. package/src/tui-compiled/runtime/shared/fd45e82f2f9c0a0d-torn.js +294 -0
  164. package/src/tui-compiled/runtime/shared/fe02abeadc535f77-rows.js +1258 -0
  165. package/src/tui-compiled/runtime/sidebar-state.js +960 -0
  166. package/src/tui-compiled/runtime/tui/command-dialogs.js +378 -0
  167. package/src/tui-compiled/runtime/tui-preferences.js +135 -0
  168. package/src/tui-compiled/runtime/{tui.tsx → tui.js} +288 -316
  169. package/dist/index-4effjmr6.js +0 -2
  170. package/dist/index-9ehhb051.js +0 -2
  171. package/dist/index-g3hsdjh4.js +0 -2
  172. package/dist/index-hh52v8sb.js +0 -2
  173. package/dist/index-jwn4r3sw.js +0 -1
  174. package/dist/index-sq36b120.js +0 -211
  175. package/dist/internal-BTndPmW2.d.ts +0 -914
  176. package/dist/quota-normalize-08hpp51v.js +0 -1
  177. package/dist/sidebar-state-CoKYKcLn.d.ts +0 -220
  178. package/dist/token-util-ypgz7rge.js +0 -1
  179. package/src/tui-compiled/raw/core-account-paths.ts +0 -114
  180. package/src/tui-compiled/raw/core-custody-state.ts +0 -243
  181. package/src/tui-compiled/raw/logger.ts +0 -53
  182. package/src/tui-compiled/raw/rpc-port-file.ts +0 -177
  183. package/src/tui-compiled/raw/rpc-protocol.ts +0 -12
  184. package/src/tui-compiled/raw/rpc-rpc-client.ts +0 -82
  185. package/src/tui-compiled/raw/rpc-rpc-dir.ts +0 -46
  186. package/src/tui-compiled/raw/sidebar-state.ts +0 -1659
  187. package/src/tui-compiled/raw/tui-command-dialogs.tsx +0 -1096
  188. package/src/tui-compiled/raw/tui-preferences.ts +0 -328
  189. package/src/tui-compiled/runtime/core-account-paths.ts +0 -114
  190. package/src/tui-compiled/runtime/core-custody-state.ts +0 -243
  191. package/src/tui-compiled/runtime/logger.ts +0 -53
  192. package/src/tui-compiled/runtime/rpc-port-file.ts +0 -177
  193. package/src/tui-compiled/runtime/rpc-protocol.ts +0 -12
  194. package/src/tui-compiled/runtime/rpc-rpc-client.ts +0 -82
  195. package/src/tui-compiled/runtime/rpc-rpc-dir.ts +0 -46
  196. package/src/tui-compiled/runtime/sidebar-state.ts +0 -1659
  197. package/src/tui-compiled/runtime/tui-command-dialogs.tsx +0 -855
  198. package/src/tui-compiled/runtime/tui-preferences.ts +0 -328
  199. package/src/tui-compiled/shared/internal.ts +0 -6
  200. package/src/tui-compiled/shared/logger.ts +0 -264
  201. package/src/tui-compiled/shared/paths.ts +0 -33
  202. package/src/tui-compiled/shared/refresh-file-lock.ts +0 -384
  203. package/src/tui-compiled/shared/util/error.ts +0 -9
  204. package/src/tui-compiled/shared/util/open-url.ts +0 -30
package/dist/index.js CHANGED
@@ -1,110 +1 @@
1
- import{A as v4,B as h4,C as g4,D as y4,c as k9,e as vX,h as GY,i as S4,j as YY,m as a1,q as aQ,r as k4,s as x4,t as b4,y as z8,z as VX}from"./index-g3hsdjh4.js";import{I as j5,J as q5}from"./index-4effjmr6.js";import{$ as GQ,$a as A9,Aa as p8,Ba as t9,Ca as HX,Da as TY,Ea as V1,Fa as R4,Ga as CY,Ha as N0,Ia as T4,Ja as c1,Ka as o8,L as G4,La as A0,M as W4,Ma as m1,N as z4,Na as LX,O as n8,Oa as P0,P as D4,Pa as JY,Q as P4,Qa as QY,R as MY,Ra as W8,S as E4,Sa as $Y,T as TQ,Ta as C4,U as R0,Ua as _4,V as f0,Va as v1,W as _Y,Wa as M1,X as cX,Xa as I4,Y as J5,Ya as i,Z as O0,Za as M9,_ as M4,_a as w9,aa as WQ,ab as R9,ba as W1,bb as T9,ca as z1,cb as C9,da as J9,db as _9,ea as zQ,eb as I9,fa as KQ,fb as S9,ga as UQ,gb as EX,ha as ZQ,hb as E1,ia as HQ,ja as LQ,ka as VQ,la as RY,ma as $9,na as g1,oa as t1,pa as w4,qa as N1,ra as v0,sa as K4,ta as eJ,ua as zX,va as G8,wa as U4,xa as A4,ya as Y8,za as u8}from"./index-sq36b120.js";import{kb as f4}from"./index-jwn4r3sw.js";import{mb as Q9,nb as XY,ob as gK}from"./index-hh52v8sb.js";import{sb as sX}from"./index-9ehhb051.js";import{createHash as wF}from"node:crypto";import{mkdirSync as AF,readFileSync as m4,renameSync as RF,statSync as TF,writeFileSync as CF}from"node:fs";import KX from"node:os";import{join as K8}from"node:path";import{execFileSync as AU}from"node:child_process";import{readFileSync as GU}from"node:fs";import{homedir as WU,tmpdir as zU}from"node:os";import{join as jY}from"node:path";var KU="https://chatgpt.com/backend-api/codex/responses",UU="openai-auth.json",P1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function qY(){let Y=process.env[P1.configDir]?.trim();if(Y)return Y;return jY(process.env.XDG_CONFIG_HOME||jY(WU(),".config"),"opencode")}function Y0(){return process.env[P1.configFile]?.trim()||jY(qY(),UU)}function ZU(){try{let Y=JSON.parse(GU(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function HU(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function FY(Y,X,J){let Q=HU(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function LU(){let Y=ZU(),X;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")X=Y.dump.enabled;else if(typeof Y.dump==="boolean")X=Y.dump}return{webSockets:FY(P1.webSockets,Y.webSockets,!1),rawWebSocket:FY(P1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(P1.responsesLite,Y.responsesLite,!1),dump:FY(P1.dump,X,!1),dumpDir:process.env[P1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():jY(zU(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[P1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():KU)}}var OY;function r0(){if(!OY)OY=LU();return OY}function DX(){return OY=void 0,r0()}import{realpathSync as m8}from"node:fs";import{homedir as VU}from"node:os";import{basename as NU,dirname as BU,join as PY,resolve as l8}from"node:path";function FU(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return PY(process.env.XDG_CONFIG_HOME||PY(VU(),".config"),"opencode")}function d8(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||PY(FU(),u8)}function DY(Y,X){let J=l8(Y);return X==="win32"||X==="darwin"?J.toLowerCase():J}function c8(Y){try{return m8.native(Y)}catch{try{return PY(m8.native(BU(Y)),NU(Y))}catch{return}}}function OU(Y,X,J=process.platform){if(DY(Y,J)===DY(X,J))return!0;let Q=c8(Y),$=c8(X);return Q!==void 0&&$!==void 0&&DY(Q,J)===DY($,J)}function EY(Y=d8()){let X=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(X){if(OU(Y,X))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${l8(Y)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return X}return p8(Y)}function s(Y=d8()){return{configPath:Y,statePath:EY(Y)}}var E9="0.11.1";import{readFile as jU}from"node:fs/promises";function i8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function r8(Y){let X=await o8(Y.configPath),J=[];try{let $=JSON.parse(await jU(Y.statePath,"utf8"));if(i8($)){let G=$.accounts;if(i8(G))J=Object.keys(G)}}catch($){if($.code!=="ENOENT")throw $}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter(($)=>!X.has($)):[]}}function PX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&N0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>N0(J)&&J.accountId===Y.mainAccountId)}function qU(Y,X){let J=Y.lastRefreshError;return MY(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=n8}function s8(Y){let X=[],J=[],Q=Y.now??Date.now(),$=PX(Y.storage),G=!1;if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if($&&(!Y.auth.refresh||$.refresh!==Y.auth.refresh))X.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),G=!0;if(G&&$){let Z={type:"restore-main-credential"};J.push(Z);let U=X.find((H)=>H.code==="auth-slot-missing"||H.code==="auth-slot-not-oauth"||H.code==="main-refresh-not-in-store");if(U)U.repair=Z}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((Z)=>Z.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let Z of W){if(!N0(Z))continue;if(!qU(Z,Q))continue;let U={type:"clear-refresh-backoff",accountId:Z.id};J.push(U),X.push({code:"armed-non-transient-refresh-backoff",accountId:Z.id,message:`Account ${Z.id} has an armed non-transient refresh backoff.`,repair:U})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let Z={type:"prune-orphan-state-ids",ids:K};J.push(Z),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:Z})}return{findings:X,repairs:J}}function a8(Y){let X=["OpenAI auth doctor"];if(Y.findings.length===0)return X.push("No problems found."),X.join(`
2
- `);for(let J of Y.findings){let Q=J.repair?" (repair available)":"";X.push(`- ${J.message}${Q}`)}return X.join(`
3
- `)}var X0={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Y=1)=>`\x1B[${Y}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:(Y,X)=>`\x1B[${Y};${X}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function t8(Y){let X=Y.toString();if(X==="\x1B[A"||X==="\x1BOA")return"up";if(X==="\x1B[B"||X==="\x1BOB")return"down";if(X==="\r"||X===`
4
- `)return"enter";if(X==="\x03")return"escape";if(X==="\x1B")return"escape-start";return null}function e8(){return Boolean(process.stdin.isTTY)}var DU=50,YQ=`${String.fromCharCode(27)}\\[[0-9;]*m`,PU=new RegExp(YQ,"g"),EU=new RegExp(`^${YQ}`);function MU(Y){return Y.replace(PU,"")}function wY(Y,X){if(X<=0)return"";if(MU(Y).length<=X)return Y;let J=X>=3?"...":".".repeat(X),Q=Math.max(0,X-J.length),$="",G=0,W=0;while(G<Y.length&&W<Q){if(Y[G]==="\x1B"){let K=Y.slice(G).match(EU);if(K){$+=K[0],G+=K[0].length;continue}}$+=Y[G],G+=1,W+=1}return $.includes("\x1B[")?`${$}${X0.reset}${J}`:$+J}function wU(Y){if(Y==="red")return X0.red;if(Y==="cyan")return X0.cyan;return""}async function AY(Y,X){if(!e8())throw Error("Interactive select requires a TTY terminal");if(Y.length===0)throw Error("No menu items provided");if(Y.length===1)return Y[0]?.value??null;let{stdin:J,stdout:Q}=process,$=0,G=null,W=!1,K=0,Z=()=>{let U=Q.columns??80,H=Q.rows??24,F=K;if(X.clearScreen)Q.write(X0.clearScreen+X0.moveTo(1,1));else if(F>0)Q.write(X0.up(F));let V=0,N=(E)=>{Q.write(`${X0.clearLine}${E}
5
- `),V+=1},q=X.subtitle?3:0,w=Math.max(1,Math.min(Y.length,H-(1+q+2)-1)),h=Math.max(0,Math.min($-Math.floor(w/2),Math.max(0,Y.length-w))),g=Y.slice(h,h+w);if(N(`${X0.dim}┌ ${X0.reset}${wY(X.message,Math.max(1,U-4))}`),X.subtitle)N(`${X0.dim}│${X0.reset}`),N(`${X0.cyan}◆${X0.reset} ${wY(X.subtitle,Math.max(1,U-4))}`),N("");for(let E=0;E<g.length;E++){let k=g[E];if(!k)continue;let m=h+E===$,r=wU(k.color),a=r?`${m?"":X0.dim}${r}${k.label}${X0.reset}`:m?k.label:`${X0.dim}${k.label}${X0.reset}`;a=wY(a,Math.max(1,U-8)),N(m?`${X0.cyan}│${X0.reset} ${X0.green}●${X0.reset} ${a}`:`${X0.cyan}│${X0.reset} ${X0.dim}○${X0.reset} ${a}`)}let R=g.length<Y.length?` (${h+1}-${h+g.length}/${Y.length})`:"";N(`${X0.cyan}│${X0.reset} ${X0.dim}${wY(`Up/Down to select | Enter: confirm | Esc: back${R}`,Math.max(1,U-6))}${X0.reset}`),N(`${X0.cyan}└${X0.reset}`);for(let E=V;E<F;E++)N("");K=V};return new Promise((U)=>{let H=J.isRaw??!1,F=()=>{if(W)return;if(W=!0,G)clearTimeout(G);J.removeListener("data",q);try{J.setRawMode(H),J.pause(),Q.write(X0.show)}catch{}process.removeListener("SIGINT",N),process.removeListener("SIGTERM",N)},V=(w)=>{F(),U(w)},N=()=>V(null),q=(w)=>{if(G)clearTimeout(G),G=null;switch(t8(w)){case"up":$=($-1+Y.length)%Y.length,Z();break;case"down":$=($+1)%Y.length,Z();break;case"enter":V(Y[$]?.value??null);break;case"escape":V(null);break;case"escape-start":G=setTimeout(()=>V(null),DU);break}};process.once("SIGINT",N),process.once("SIGTERM",N);try{J.setRawMode(!0)}catch{F(),U(null);return}J.resume(),Q.write(X0.hide),Z(),J.on("data",q)})}var XQ=[{label:"Add account",value:"add-account",color:"cyan"},{label:"Auth current",value:"auth-current",color:"cyan"},{label:"Check quotas",value:"check-quotas",color:"cyan"},{label:"Auth doctor",value:"auth-doctor",color:"cyan"},{label:"Apply repairs",value:"apply-repairs",color:"cyan"},{label:"Delete all accounts",value:"delete-all",color:"red"}],TO=XQ.map((Y)=>Y.label);async function JQ(){return await AY(XQ,{message:"OpenAI accounts",subtitle:"Select an account action",clearScreen:!0})??"cancel"}async function QQ(Y,X=!1){return await AY(X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Y})??!1}function RU(Y,X=process.platform,J=AU){try{if(X==="win32")J("cmd",["/c","start","",Y],{stdio:"ignore",timeout:3000});else J(X==="darwin"?"open":"xdg-open",[Y],{stdio:"ignore",timeout:3000});return!0}catch{return!1}}function TU(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}async function CU(){let{redirectUri:Y}=await UQ(),X=await WQ(),J=GQ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=zQ(Y,X,J),$=ZQ(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await $;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:J9(G)}}finally{KQ(J)}}}}async function _U(Y){let{deviceData:X,url:J,instructions:Q}=await HQ(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let $=await LQ(X,Y);return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:J9($)}}catch{return{type:"failed"}}}}}function $Q(Y){if(console.log(`
6
- Open this URL in your browser and complete sign-in:
7
- `),console.log(`${Y.url}
8
- `),Y.instructions)console.log(`${Y.instructions}
9
- `)}function NQ({client:Y,getAuth:X,getPaths:J=()=>s(Y0()),fetchImpl:Q=fetch,packageVersion:$=E9,dependencies:G}){let W={authorizeBrowser:G?.authorizeBrowser??CU,authorizeHeadless:G?.authorizeHeadless??(()=>_U($)),beginAccountLogin:G?.beginAccountLogin??RY,loadAccounts:G?.loadAccounts??A0,mutateAccounts:G?.mutateAccounts??P0,refreshAllQuota:G?.refreshAllQuota??E1,showAuthMenu:G?.showAuthMenu??JQ,confirm:G?.confirm??QQ,readStoreIds:G?.readStoreIds??r8,openBrowser:G?.openBrowser??RU,now:G?.now??Date.now,custodyQuotaDeps:G?.custodyQuotaDeps??{}},K=async()=>await X?.().catch(()=>{return})??{type:"missing"},Z=async()=>{if((await K()).type!=="missing")return!0;return((await W.loadAccounts(J()))?.accounts.length??0)>0},U=async(R)=>{await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...R}})},H=async()=>{let R=new AbortController,E=await W.beginAccountLogin({version:$,signal:R.signal});E.completion.catch(()=>{}),$Q(E);let k=!1;try{k=await W.openBrowser(E.url)!==!1}catch{k=!1}if(!k)R.abort(),console.log(`Could not open a browser. Switching to device authorization.
10
- `),E=await W.beginAccountLogin({version:$,headless:!0}),$Q(E);return E.completion},F=async()=>{let R=await W.loadAccounts(J());if(m1(R)==="claustrum"){console.log("That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.");return}let E=await H(),k=!1;if(await W.mutateAccounts((m)=>{if(E.accountId&&m.mainAccountId&&E.accountId===m.mainAccountId)return k=!0,m;return VQ(m.accounts,E),m},J()),k){console.log("That account is already the OpenCode main credential.");return}console.log(`Added fallback account ${E.id}.`)},V=async()=>{let R=await H();await U({refresh:R.refresh,access:R.access??"",expires:R.expires??0}),console.log("Updated the OpenCode main credential.")},N=async()=>{let R=J(),E=await W.loadAccounts(R),k=new CY({storage:E,configPath:R.configPath,fetchImpl:Q,now:W.now}),m={refreshAccount:async($0)=>$0},r=async()=>{throw Error("No usable main access token for quota check")},a=async($0)=>{let Z0=await W.loadAccounts($0);if(!Z0)return null;return{...Z0,accounts:Z0.accounts.map((u0)=>N0(u0)?{...u0,lastRefreshError:void 0}:{...u0})}},q0=await W.refreshAllQuota({getAuth:K,codexRefreshFn:r,refreshMainWithLease:r,fallbackManager:m,quotaManager:k,loadAccounts:a,writeSidebarState:async()=>{},client:{auth:{set:async()=>{throw Error("Quota checks cannot write credentials")}}},fetchImpl:Q,now:W.now,paths:R,storageMainAccountId:E?.mainAccountId,isOAuthAccountFn:N0,whamFn:TY,respectBackoff:!1,readSidebarState:async()=>({main:{},fallbacks:[]}),...W.custodyQuotaDeps});IU(q0)},q=async()=>{let R=J(),[E,k,m]=await Promise.all([W.loadAccounts(R),W.readStoreIds(R),K()]),r=s8({auth:m.type==="missing"?void 0:m,storage:E,orphanStateIds:k.orphanStateIds,now:W.now()});return console.log(a8(r)),r},w=async()=>{let R=await q();if(R.repairs.length===0){console.log("No repairs are available.");return}if(!await W.confirm("Apply the listed auth repairs?")){console.log("Repairs cancelled.");return}let E=J();for(let k of R.repairs){if(k.type==="restore-main-credential"){let m=await W.loadAccounts(E),r=PX(m);if(!r)continue;await U({refresh:r.refresh,access:r.access??"",expires:r.expires??0});continue}if(k.type==="prune-orphan-state-ids"){await W.mutateAccounts((m)=>m,E);continue}await W.mutateAccounts((m)=>{let r=m.accounts.find((a)=>a.id===k.accountId&&N0(a));if(r)r.lastRefreshError=void 0;return m},E)}console.log(`Applied ${R.repairs.length} auth repair(s).`)},h=async()=>{if(!await W.confirm("Delete all fallback accounts?")){console.log("Delete cancelled.");return}let R=[];await W.mutateAccounts((E,k)=>{let m=new Set([...k?.rawRosterIds??[],...E.accounts.map((r)=>r.id)].filter((r)=>r!=="main"));return R.splice(0,R.length,...m),E.accounts=E.accounts.filter((r)=>r.id==="main"),E},J(),{allowDrop:R}),console.log("Deleted all fallback accounts.")},g=async(R)=>{switch(R){case"add-account":await F();break;case"auth-current":await V();break;case"check-quotas":await N();break;case"auth-doctor":await q();break;case"apply-repairs":await w();break;case"delete-all":await h();break;case"cancel":break}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async(R)=>{if(R&&await Z())return await g(await W.showAuthMenu()),TU();return W.authorizeBrowser()}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:W.authorizeHeadless},{label:"Manually enter API Key",type:"api"}]}function IU(Y){for(let X of Y)console.log(X.ok?`${X.account}: quota refreshed`:`${X.account}: ${X.error??"quota refresh failed"}`)}var s0=O0("commands");function b0(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}async function xU(Y,X){let J=await X.loadAccounts(b0(X))??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let Z=Q.main??{},U=Z.primary??Z["5h"]??c1.primary,H=Z.secondary??Z["1w"]??c1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${H}% |`);for(let F of $){let V=Q.accounts?.[F]??Q.main??{},N=V.primary??V["5h"]??c1.primary,q=V.secondary??V["1w"]??c1.secondary;K.push(`| ${F} | ≥ ${N}% | ≥ ${q}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
11
- `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:c1.primary,secondary:c1.secondary}};return await P0((K)=>{return K.killswitch=W,K},b0(X)),s0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await P0((K)=>{return K.killswitch=W,K},b0(X)),s0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let Z=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!Z)continue;let[,U,H,F]=Z,V={primary:Number.parseInt(H,10),secondary:Number.parseInt(F,10)};if(U==="main")W.main=V;else if(U==="all"){W.main=V;for(let N of $)W.accounts[N]=V}else W.accounts[U]=V}return await P0((K)=>{return K.killswitch=W,K},b0(X)),s0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function bU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=r0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
12
-
13
- - Enabled: ${$?"ON":"OFF"}
14
- - Directory: ${Q.dumpDir}
15
-
16
- Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on"){await P0((W)=>{return W.dump={...W.dump??{},enabled:!0},W},b0(X));let G=DX();return s0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
17
-
18
- Dump directory: ${G.dumpDir}
19
-
20
- Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}}}if(J[0]==="off")return await P0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},b0(X)),DX(),s0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function vU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(b0(X)))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
21
-
22
- - Level: \`${W}\`
23
-
24
- Valid levels: ${Q.map((K)=>`\`${K}\``).join(", ")}
25
-
26
- Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return _Y(G),await P0((W)=>{return W.logging={...W.logging??{},level:G},W},b0(X)),s0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
27
-
28
- Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
29
-
30
- Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function hU(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(!Number.isInteger(J)||!Number.isInteger(Q)||J<0||J>23||Q<0||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}async function gU(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(b0(X)),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
31
-
32
- Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),Z=K.window,U=Z?`${String(Z.startHour).padStart(2,"0")}-${String(Z.endHour).padStart(2,"0")}`:"always (no window)",H=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(H.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){H.push("");for(let V of K.targets){let N=V.sessionKey.length>12?`${V.sessionKey.slice(0,12)}…`:V.sessionKey,q=Math.ceil((V.cacheExpiresAt-K.generatedAt)/1000);H.push(`- \`${N}\` (${V.accountId??"main"}) — expires in ${q}s`+(V.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-V.lastWarmedAt)/1000)}s ago`:"")+(V.backoffUntil&&V.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((V.backoffUntil-K.generatedAt)/1000)}s`:""))}}H.push(""),H.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),H.push(""),H.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let F=Math.max(0,...K.targets.map((V)=>V.lastWarmedAt??0));return{command:"openai-cachekeep",text:H.join(`
33
- `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:Z,running:K.running,tracked:K.tracked,lastWarmAt:F||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
34
-
35
- Cannot start: manager not wired.`,knobs:{}};await P0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},b0(X)),s0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),Z=Math.max(0,...K.targets.map((U)=>U.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
36
-
37
- TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:Z||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await P0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},b0(X)),s0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let Z=K==="on";await P0((H)=>{return H.cachekeep={...H.cachekeep??{},sustain:Z},H},b0(X)),s0.info(`cachekeep sustain ${Z?"enabled":"disabled"}`),X.setCacheKeepSustain?.(Z);let U=J?.status();return{command:"openai-cachekeep",text:Z?`## Cachekeep Sustain Enabled
38
-
39
- Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
40
-
41
- Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
42
-
43
- Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let Z=K==="on";await P0((H)=>{return H.cachekeep={...H.cachekeep??{},subagents:Z},H},b0(X)),s0.info(Z?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(Z);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
44
-
45
- Subagent warming: **${Z?"ON":"OFF"}**`,knobs:{enabled:G,subagents:Z,sustain:U?.sustain??$?.cachekeep?.sustain===!0,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let K=Q[1];if(K==="clear"||K==="off"){await P0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},b0(X)),X.setCacheKeepWindow?.(void 0),s0.info("cachekeep window cleared");let Z=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
46
-
47
- Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:Z?.running??!1,tracked:Z?.tracked??0,generatedAt:Z?.generatedAt??Date.now(),maxIdleWarmMs:Z?.maxIdleWarmMs??3600000,maxSubagentIdleMs:Z?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=hU(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
48
-
49
- ${K.reason}`,knobs:{}};let{startHour:Z,endHour:U}=K;await P0((V)=>{return V.cachekeep={...V.cachekeep??{},startHour:Z,endHour:U},V},b0(X)),X.setCacheKeepWindow?.({startHour:Z,endHour:U}),s0.info("cachekeep window set",{startHour:Z,endHour:U});let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
50
-
51
- Warming limited to **${`${String(Z).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:Z,endHour:U},running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}var yU={"openai-killswitch":xU,"openai-dump":bU,"openai-logging":vU,"openai-cachekeep":gU};function MX(Y,X,J){return EX(Y,X,J,yU)}var fU=300000,mU=30000,cU=240000,uU="bg-quota-refresh",pU=120000;function lU(Y,X){return V1({name:uU,ttlMs:pU,path:Y,renew:!0,...X})}function BQ(Y,X=E1,J=()=>lU(Y.paths.configPath)){return dU(Y,X,J)}async function dU(Y,X,J){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return[];try{return await X({...Y,respectBackoff:!0,skipFresherThanMs:cU})}finally{await Q?.release().catch(()=>{})}}class wX{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*mU);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},fU+J),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function AX(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return i(X)&&i(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function RX(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!i(X)||!i(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function IY(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),AX(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:RX(Y.body)}}function DQ(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function PQ(Y){let X=Number(Y?.cachekeep?.startHour),J=Number(Y?.cachekeep?.endHour);if(!Number.isInteger(X)||!Number.isInteger(J)||X<0||X>23||J<0||J>23||X===J)return;return{startHour:X,endHour:J}}function FQ(Y,X=new Date){if(!Y)return!1;let J=X.getHours();if(Y.startHour<Y.endHour)return J>=Y.startHour&&J<Y.endHour;return J>=Y.startHour||J<Y.endHour}var iU=300000,EQ=1800000,OQ=2*EQ+900000,nU=3600000,jQ=1800000,qQ=60000,oU=32,rU=8388608,TX=600000;function MQ(Y){try{let J=JSON.parse(Y).model;if(typeof J!=="string")return!1;return J==="gpt-5.6"||J.startsWith("gpt-5.6-")}catch{return!1}}function sU(Y){let J=JSON.parse(Y);return J.store=!1,delete J.max_output_tokens,delete J.max_tokens,delete J.max_completion_tokens,JSON.stringify(J)}function aU(Y,X){return MQ(Y)?EQ:X}function CX(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function wQ(Y){if(!Y||typeof Y!=="object")return CX();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function tU(Y){try{let X=JSON.parse(Y);return wQ(X.usage)}catch{return CX()}}function eU(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
52
- `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),Z=K.type??W;if(Z!=="response.completed"&&Z!=="response.done")return;let U=K.response;Q=wQ(U?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??CX()}class _X{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??iU,this.tickIntervalMs=Y.tickIntervalMs??qQ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:nU;let J=Y.maxSubagentIdleMs??jQ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:jQ,this.tickIntervalMs=Y.tickIntervalMs??qQ,this.maxTargets=Y.maxTargets??oU,this.maxBytes=Y.maxBytes??rU,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!FQ(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let H=this.targets.get(Y);if(H)this.totalBytes-=H.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let H,F=Number.POSITIVE_INFINITY;for(let[N,q]of this.targets){let w=Math.max(q.lastRealRequestAt,q.lastWarmedAt??0);if(w<F)H=N,F=w}if(H===void 0)break;let V=this.targets.get(H);if(V)this.totalBytes-=V.bodyText.length;this.targets.delete(H)}let Z=aU(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:Z,cacheExpiresAt:this.now()+Z,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:MQ(X)};this.targets.set(Y,U),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-OQ;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=OQ;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!FQ(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J,Q;try{if(X.accountId&&X.accountId!=="main"){let G=await this.refreshFallback(X.accountId);if(typeof G==="string")J=G;else J=G.token,Q=G.onAuthFailure}else J=await this.getMainToken()}catch(G){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+TX;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let $={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)$["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete $["ChatGPT-Account-Id"];try{let G=sU(X.bodyText),W;try{let h=JSON.parse(G);W={warmBodyKeys:Object.keys(h),stream:h.stream,max_output_tokens:h.max_output_tokens,store:h.store,has_stream_options:"stream_options"in h,has_max_tokens:"max_tokens"in h,model:h.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...W,headerKeys:Object.keys($),hasChatGptAccountId:"ChatGPT-Account-Id"in $}));let K=IY({method:"POST",headers:$,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),Z=await this.fetchImpl(this.codexResponsesUrl,K),U="";try{U=await Z.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!Z.ok){if(X.backoffUntil=this.now()+TX,Z.status===401)await Q?.(Z.status);this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:Z.status,error:`HTTP ${Z.status}`,responseBody:U.slice(0,600)}));return}let H=Z.headers.get("content-type")??"",F=H.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:Z.status,contentType:H,bodyLen:U.length,isSse:F}));let V=F?eU(U):tU(U),N=Q9(Z.headers),q=N.primary?.usedPercent??null,w=N.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:V.input_tokens,cached_tokens:V.cached_tokens,hit_rate:V.hit_rate,output_tokens:V.output_tokens,quota_primary_pct:q,quota_secondary_pct:w})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch(G){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+TX,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}import{createHash as JZ}from"node:crypto";import{isAbsolute as YZ,join as AQ}from"node:path";var XZ=O0("custody"),RQ=new Set;function IX(Y=process.env){let X=Y.CLAUSTRUM_OPENCODE_HANDLES;if(X&&YZ(X))return X;if(X&&!RQ.has(X))RQ.add(X),XZ.warn("ignoring non-absolute CLAUSTRUM_OPENCODE_HANDLES",{configuredPath:X});let J=Y.XDG_CONFIG_HOME||(Y.HOME?AQ(Y.HOME,".config"):".config");return AQ(J,"cortexkit","opencode-handles.json")}function Y1(Y=IX(),X={}){return TQ(Y,X)}var SX="openai",CQ=250,xQ=new Set;function bQ(Y){if(typeof Y.access!=="string"||typeof Y.refresh!=="string")return;let X=Buffer.from(Y.access),J=Buffer.from(Y.refresh),Q=($)=>{let G=Buffer.alloc(4);return G.writeUInt32BE($.length),G};return JZ("sha256").update(Q(X)).update(X).update(Q(J)).update(J).digest("hex")}function vQ(Y){let X=bQ(Y);if(X)xQ.add(X)}function QZ(Y){let X=bQ(Y);return X!==void 0&&xQ.has(X)}function hQ(Y){if(!Y||typeof Y!=="object")return;let X=Y;if(X.type!=="oauth")return;return{type:"oauth",...typeof X.access==="string"?{access:X.access}:{},...typeof X.refresh==="string"?{refresh:X.refresh}:{},...typeof X.expires==="number"?{expires:X.expires}:{}}}function kY(Y){let X=hQ(Y);if(typeof X?.access!=="string"||typeof X.refresh!=="string")return;return{access:X.access,refresh:X.refresh,...typeof X.expires==="number"?{expires:X.expires}:{}}}function SY(Y){let X=hQ(Y);if(!X)return{kind:"indeterminate"};if(!v0({id:"main",type:"oauth",access:X.access??"",refresh:X.refresh??"",expires:X.expires??0,addedAt:0},SX))return{kind:"real",oauth:X};let J=N1(SX);if(X.access===J.access&&X.expires===J.expires)return{kind:"tombstone",oauth:X};return{kind:"empty",oauth:X}}async function _Q(Y){if(!Y.auth.get)return;return Y.auth.get({path:{id:SX}})}async function IQ(Y){if(!Y.auth.all)return!1;return Object.keys(await Y.auth.all()).length>0}async function $Z(Y){let X=await _Q(Y.client);if(X!==void 0)return SY(X);let J=await IQ(Y.client),Q=Y.now();if(await Y.sleep(CQ),Y.now()-Q<CQ)return{kind:"indeterminate"};let $=await _Q(Y.client);if($!==void 0)return SY($);let G=await IQ(Y.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function GZ(Y){if(Y.ok)return"present";return Y.reason==="absent"?"absent":"unreadable"}function x9(Y){let X=W1(Y);return X?z1(X):void 0}async function SQ(Y){let X=f0(Y.manifest).get("main");if(!X)return"no_handle";if(!Y.getCredential)return"cold";try{let J=await Y.getCredential(X),Q=x9(J.access);if(Y.mainAccountId&&Q&&Q!==Y.mainAccountId)return"identity_mismatch";return"serves"}catch{return Y.isReauth?.(X)?"needs_reauth":"cold"}}function kQ(Y){return Y.kind==="real"&&QZ(Y.oauth)}async function gQ(Y){let X=await $Z(Y);if(X.kind==="indeterminate")return;let J=GZ(Y.manifest);if(X.kind==="slot-absent"){let $=await SQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:kQ(X),vault:()=>$==="no_handle"||$==="identity_mismatch"?$:"serves"})}let Q=await SQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:kQ(X),vault:()=>Q})}import{createHash as WZ}from"node:crypto";var lQ="claustrum-mode",u1="main-refresh",yQ=Promise.resolve();async function xX(){let Y,X=new Promise(($)=>{Y=$}),J=yQ;yQ=J.then(()=>X),await J;let Q=!1;return{async release(){if(Q)return;Q=!0,Y()}}}async function dQ(Y){let X=Y.now()+5000;while(Y.now()<X){try{let J=await Y.getAuth();if(J?.access===Y.accessToken&&J.refresh===Y.refreshToken){await Y.onObserved?.({access:J.access,refresh:J.refresh}),await Y.release();return}}catch{}await Y.sleep(Math.max(0,Math.min(100,X-Y.now())))}Y.warn("host write not observed within 5s; lease released"),await Y.release()}function fQ(Y){return Y.accounts.filter((X)=>N0(X)&&X.enabled!==!1)}function kX(Y,X){return Y<X?-1:Y>X?1:0}function mQ(Y,X){return[{id:"main",accountId:X?.mainAccountId,kind:"main"},...Y.map((J)=>({id:J,accountId:X?.accounts.find((Q)=>Q.id===J)?.accountId,kind:"fallback"}))].sort((J,Q)=>kX(J.id,Q.id))}function zZ(Y){return Y.kind==="main"?u1:M1(Y.id)}function cQ(Y){return Y.access?$9(Y.access,Y.refresh):void 0}function uQ(Y){return Object.values(Y).some((X)=>X==="new-local-family-under-claustrum"||X==="torn-read-deferred"||X.startsWith("aborted:"))}async function iQ(Y){let X=await xX(),J=[],Q={},$=!1,G=async(W)=>{await Y.onStep?.(W)};try{if(await G("mutex-acquired"),Y.accountIds.includes("main")||new Set(Y.accountIds).size!==Y.accountIds.length)return{status:"aborted",outcomes:Q,reason:"duplicate-account-lock"};let W=await Y.acquireLock({name:lQ,renew:!0});if(!W)return{status:"aborted",outcomes:Q,reason:"mode-lock-unavailable"};J.push(W),Y.warn?.(`transition deps: ${JSON.stringify({acquireLock:typeof Y.acquireLock,withStoreTransaction:typeof Y.withStoreTransaction,readManifest:typeof Y.readManifest,preflight:typeof Y.preflight,auth:typeof Y.auth,authAll:typeof Y.auth?.all,authGet:typeof Y.auth?.get,authSet:typeof Y.auth?.set,accountIds:Y.accountIds?.length})}`);let K=mQ(Y.accountIds);Y.warn?.(`transition participants: ${K.map((Z)=>Z.id).join(",")}`);for(let Z of K){let U=await Y.acquireLock({name:zZ(Z),renew:!0});if(!U)return{status:"aborted",outcomes:Q,reason:`account-lock-unavailable:${Z.id}`};J.push(U)}return await Y.withStoreTransaction(async(Z)=>{let U=await Z.read(),H=mQ(Y.accountIds,U),F=fQ(U).map((E)=>E.id).sort(kX),V=[...Y.accountIds].sort(kX);if(F.length!==V.length||F.some((E,k)=>E!==V[k]))return{status:"aborted",outcomes:Q,reason:"account-roster-changed"};let N=await Y.readManifest();if(!N.ok)return{status:"aborted",outcomes:Q,reason:`manifest-${N.reason}`};let q=f0(N),w=U.claustrum?.mode==="claustrum"?U.claustrum?.transition:void 0,h=w?w.fingerprints:{fallbacks:{}},g=w?.storeGeneration??pQ(U);if(!w){Y.warn?.(`capturing main slot fingerprint; auth.get is ${typeof Y.auth?.get}`);let E=kY(await Y.auth.get({path:{id:"openai"}}));if(Y.warn?.(`main slot captured: ${E?"complete":"absent"}`),E)h.main=$9(E.access,E.refresh);for(let k of fQ(U)){let m=cQ(k);if(m)h.fallbacks[k.id]=m}}await G("captured"),Y.warn?.(`handles resolved: isMap=${q instanceof Map} size=${q instanceof Map?q.size:"n/a"}`);for(let E of H){let k=q.get(E.id);if(Y.warn?.(`participant ${E.id}: handle=${k?"yes":"NO"}`),!k){Q[E.id]="no-handle";continue}let m=await Y.preflight({id:E.id,accountId:E.accountId,handle:k});Q[E.id]=m}if(await G("preflight"),Object.values(Q).some((E)=>E!=="ready"))return{status:"aborted",outcomes:Q,reason:"preflight-failed"};if(!w){let E=await Y.readManifest(),k=await Z.read();if(!E.ok||E.revision!==N.revision)return{status:"aborted",outcomes:Q,reason:"manifest-revision-changed"};if(pQ(k)!==g)return{status:"aborted",outcomes:Q,reason:"store-generation-changed"};await G("revalidated"),await Z.writeMode("claustrum",{manifestRevision:N.revision,storeGeneration:g,fingerprints:h}),await G("mode-written")}let R=!1;for(let E of K){if(E.kind==="main")continue;let k=await Z.read(),m=k.accounts.find(($0)=>$0.id===E.id&&$0.type==="oauth");if(m&&v0(m,"openai")){Q[E.id]="tombstoned";continue}let r=h.fallbacks[E.id];if(!m||!r||cQ(m)!==r){Q[E.id]="new-local-family-under-claustrum";continue}let a=structuredClone(k),q0=a.accounts.find(($0)=>$0.id===E.id&&$0.type==="oauth");if(!q0){Q[E.id]="new-local-family-under-claustrum";continue}Object.assign(q0,N1("openai"));try{await Z.write(a);let $0=(await Z.read()).accounts.find((Z0)=>Z0.id===E.id&&Z0.type==="oauth");Q[E.id]=$0&&v0($0,"openai")?"tombstoned":"aborted:post-write-readback"}catch{Q[E.id]="aborted:write-failed",R=!0;break}}if(R)return await G("material-written"),{status:"incomplete",outcomes:Q};if(Q.main=h.main?await bX(h.main,{auth:Y.auth,warn:(E)=>{if($)return;$=!0,Y.warn?.(E)}}):"new-local-family-under-claustrum",await G("material-written"),!uQ(Q))await Z.writeMode("claustrum");return{status:uQ(Q)?"incomplete":"completed",outcomes:Q}})}finally{for(let W of J.reverse())await W.release().catch(()=>{});await X.release(),await G("mutex-released").catch(()=>{})}}async function bX(Y,X){let J=kY(await X.auth.get({path:{id:"openai"}}));if(J&&v0({id:"main",type:"oauth",access:J.access,refresh:J.refresh,expires:J.expires??0},"openai"))return"tombstoned";if(!J||$9(J.access,J.refresh)!==Y)return"new-local-family-under-claustrum";let Q=await X.auth.all();if(Object.keys(Q).length===0)return X.warn?.("host auth store read empty; refusing to write — possible torn read"),"torn-read-deferred";try{let $=N1("openai");await X.auth.set.bind(X.auth)({path:{id:"openai"},body:$});let W=kY(await X.auth.get({path:{id:"openai"}}));return W&&W.access===$.access&&W.refresh===$.refresh&&W.expires===$.expires?"tombstoned":"new-local-family-under-claustrum"}catch{return"aborted:write-failed"}}async function nQ(Y){let X=await Y.acquireLock({name:lQ,renew:!0});if(!X)throw Error("Claustrum mode lock unavailable");try{await Y.withStoreTransaction(async(J)=>{return await J.writeMode("local"),{status:"completed",outcomes:{}}})}finally{await X.release()}}function pQ(Y){let X=Y.accounts.filter((J)=>J.type==="oauth").map((J)=>({id:J.id,enabled:J.enabled!==!1,accountId:J.accountId??"",access:J.access??"",refresh:J.refresh,expires:J.expires??null})).sort((J,Q)=>J.id<Q.id?-1:J.id>Q.id?1:0);return WZ("sha256").update(JSON.stringify(X)).digest("hex")}var tQ=900000,KZ=0.016666666666666666,oQ=0.000001;function hX(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function gX(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=hX(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>tQ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=vX(Y.quota).sort(($,G)=>{let W=$.windowMs,K=G.windowMs,Z=typeof W==="number"&&Number.isFinite(W),U=typeof K==="number"&&Number.isFinite(K);if(Z!==U)return Z?-1:1;if(Z&&U)return K-W;return 0});for(let{key:$,window:G}of J)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:$,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let Q=aQ(Y.quota,Y.now);if(Q)return{action:"migrate",reason:"exhausted",resetsAt:Q.resetsAt};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function rQ(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,KZ);return Q/G}function sQ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function UZ(Y,X){if(!Y.quota)return;let J=hX(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>tQ)return;let Q=vX(Y.quota).map(({key:W,window:K})=>{return rQ(K,Y.reservePercent[W]??0,X)}),$=Y.quota.spendControl;if($&&Number.isFinite($.remainingPercent))Q.push(rQ($,0,X));let G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function eQ(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>UZ($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,oQ),Z=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,oQ);return K-Z||G.candidate.configuredOrder-W.candidate.configuredOrder||sQ(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||sQ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:hX(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as ZZ}from"node:crypto";import{chmod as HZ,mkdir as LZ,readdir as VZ,readFile as NZ,writeFile as yX}from"node:fs/promises";import{join as Q5}from"node:path";var uX=O0("dump"),w1="x-cortexkit-openai-auth-dump-session",BZ=["http","prewarm","main"],Y5=0,G9=new Map,FZ=100;function fX(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function $5(Y){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return"session-unknown";return X.length<=80?X:X.slice(0,80)}function G5(Y){return ZZ("sha256").update(Y).digest("hex")}function mX(Y){return G5(JSON.stringify(Y))}function W5(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function OZ(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function jZ(Y,X){if(!G9.has(Y))while(G9.size>=FZ){let J=G9.keys().next().value;if(J===void 0)break;G9.delete(J)}G9.set(Y,X)}var X5=new Set;async function qZ(Y,X,J){let Q=$5(X),$=BZ.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await VZ(Y)).filter((K)=>$.some((Z)=>K.endsWith(Z))).sort().pop();if(!W)return;return await NZ(Q5(Y,W),"utf8")}catch{return}}function DZ(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function pX(Y){if(Array.isArray(Y))return Y.map(pX);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=pX(Q)}return X}function PZ(Y){let X=W5(Y);if(X===void 0)return Y;let J=EZ(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function EZ(Y){if(!i(Y))return cX(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?J5(Q):cX({[J]:Q})[J];return X}function MZ(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function wZ(Y){let X=W5(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(MZ),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:mX(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:mX(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:mX(Q),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function W9(Y){let X=r0();if(!X.dump)return;Y5++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(Y5).padStart(5,"0")}-${$5(J)}-${Y.transport}-${Y.phase}`,$=Q5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=G9.get(W),Z=K?"memory":void 0;if(K===void 0&&!X5.has(W)){if(X5.add(W),K=await qZ(X.dumpDir,J,Y.transport),K!==void 0)Z="disk"}try{await LZ(X.dumpDir,{recursive:!0,mode:448}),await HZ(X.dumpDir,448).catch(()=>{});let U=PZ(Y.bodyText),H={id:Q,createdAt:new Date().toISOString(),session:fX(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:G5(Y.bodyText),diff:OZ(K,U),baselineSource:Z,body:wZ(Y.bodyText),files:G};await Promise.all([yX(G.body,U,{encoding:"utf8",mode:384}),yX(G.metadata,`${JSON.stringify(H,null,2)}
53
- `,{encoding:"utf8",mode:384}),yX(G.request,`${JSON.stringify(pX({url:Y.url,method:Y.method,accountId:Y.accountId,headers:DZ(Y.headers)}),null,2)}
54
- `,{encoding:"utf8",mode:384})]),uX.debug("dumped request",{id:Q,session:fX(J),body:G.body,meta:G.metadata}),jZ(W,U)}catch(U){uX.warn("request dump failed",{session:fX(J),error:U instanceof Error?U.message:String(U)})}}async function p1(Y){if(!r0().dump)return;uX.debug("diagnostic",Y)}import{readFile as AZ}from"node:fs/promises";import{homedir as RZ}from"node:os";import{join as z5}from"node:path";var TZ="https://models.dev/api.json",CZ="OPENCODE_OPENAI_AUTH_MODELS_CACHE",_Z="OPENCODE_MODELS_PATH",IZ="OPENCODE_DISABLE_MODELS_FETCH",SZ=1e4,kZ=300000;function A1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function K5(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function lX(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=K5(Y.cache_read),$=K5(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function xZ(Y){let X=A1(Y);if(!X)return null;let J=lX(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let Z=A1(K);if(!Z)continue;let U=A1(Z.tier),H=U?.size;if(U?.type!=="context")continue;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)continue;let F=lX(Z);if(!F)continue;W.push({...F,tier:{type:"context",size:H}})}if(W.length>0)Q.tiers=W}let $=A1(X.context_over_200k),G=$?lX($):null;if(G)Q.experimentalOver200K=G;return Q}function U5(Y){let X=A1(Y),J=A1(X?.openai),Q=A1(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=A1(W),Z=xZ(K?.cost);if(Z)$[G]=Z}return Object.keys($).length>0?$:null}function bZ(){let Y=process.env[CZ]?.trim();if(Y)return Y;let X=process.env[_Z]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||z5(RZ(),".cache");return z5(J,"opencode","models.json")}function vZ(){let Y=process.env[IZ]?.toLowerCase();return Y==="true"||Y==="1"}async function hZ(){try{let Y=U5(JSON.parse(await AZ(bZ(),"utf8")));if(Y)return Y}catch{}if(vZ())return null;try{let Y=await fetch(TZ,{signal:AbortSignal.timeout(SZ)});if(!Y.ok)return null;return U5(await Y.json())}catch{return null}}var z9;function Z5(){let Y=Date.now();if(z9&&z9.expiresAt>Y)return z9.promise;let X={expiresAt:Y+kZ,promise:hZ()};return z9=X,X.promise.then((J)=>{if(J===null&&z9===X)z9=void 0}),X.promise}function K9(Y){return typeof Y==="object"&&Y!==null}function gZ(Y){if(Array.isArray(Y))return Y;if(K9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function yZ(Y){if(!K9(Y)||!K9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function H5(Y){if(!K9(Y)||!K9(Y.info))return null;let X=Y.info,J=K9(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function L5(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function V5(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function N5(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=gZ(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(yZ(Q[G])!=="assistant")continue;let W=H5(Q[G]);if(!W)continue;if($=L5($,W),V5($))return $}for(let G=Q.length-1;G>=0;G--){let W=H5(Q[G]);if(!W)continue;if($=L5($,W),V5($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var R1=[],fZ=1,B5=new Map;function dX(Y,X){if(R1.push({id:fZ++,type:"open-dialog",payload:Y,sessionId:X}),R1.length>100)R1=R1.slice(R1.length-100)}function F5(Y=0,X){let J=Date.now();if(X!==void 0)B5.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)R1=R1.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!0;return $.sessionId!==X});return R1.filter(($)=>$.id>Y&&Q($))}function O5(Y){let X=Date.now(),J=B5.get(Y)??0;return J>0&&X-J<3000}import{randomBytes as mZ,timingSafeEqual as cZ}from"node:crypto";import{readFile as uZ,unlink as pZ}from"node:fs/promises";import{createServer as lZ}from"node:http";import{join as dZ}from"node:path";var iX=O0("rpc");function iZ(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function nZ(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&cZ(J,Q)}async function D5(Y){let X=mZ(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=!1,G=lZ((Z,U)=>{Z.setTimeout(J,()=>{Z.socket.destroy()}),W(Z,U)});G.requestTimeout=Q,G.headersTimeout=Q;async function W(Z,U){let H=(F,V)=>{if(U.headersSent||U.writableEnded||U.destroyed)return;U.writeHead(F,{"content-type":"application/json"}),U.end(JSON.stringify(V))};try{let F=Z.url??"";if(Z.method==="GET"&&F==="/health")return H(200,{ok:!0});if(Z.method!=="POST"||!F.startsWith("/rpc/"))return H(404,{error:"not found"});if(!nZ(Z.headers.authorization,X))return H(401,{error:"unauthorized"});let V=F.slice(5),N=await iZ(Z),q=JSON.parse(N||"{}");if(V==="pending-notifications"){let w=typeof q.sessionId==="string"?q.sessionId:void 0;if(w===void 0&&!$)$=!0,iX.warn("rpc notification drain missing session id",{pid:process.pid});let h=Y.drain(Number(q.lastReceivedId??0),w);return H(200,{messages:h})}if(V==="apply"){let w=await Y.apply(q);return H(200,w)}return H(404,{error:"unknown method"})}catch(F){H(500,{error:F instanceof Error?F.message:String(F)})}}let K=await new Promise((Z,U)=>{G.on("error",U),G.listen(0,"127.0.0.1",()=>{let H=G.address();if(H&&typeof H==="object")Z(H.port);else U(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await q5(Y.sweepRoot,Y.dir)}catch(Z){iX.warn("rpc state sweep failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})}try{await j5(Y.dir,{port:K,token:X,pid:process.pid},{secureDir:Y.secureDir}),iX.debug("rpc server pid",{pid:process.pid,rpcPort:K})}catch(Z){throw await new Promise((U)=>G.close(()=>U())),Z}return{port:K,token:X,async stop(){await new Promise((H)=>G.close(()=>H()));let Z=dZ(Y.dir,`port-${process.pid}.json`),U=await uZ(Z,"utf8").then((H)=>JSON.parse(H)).catch(()=>{return});if(U?.port===K&&U.token===X)await pZ(Z).catch(()=>{})}}}function K1(Y){return JSON.stringify(nX(Y))??"undefined"}function nX(Y){if(Array.isArray(Y))return Y.map(nX);if(!i(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,nX(Y[X])]))}function l1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var b1={};sX(b1,{withoutInternalHeaders:()=>Q4,sanitizeHttpFallbackBody:()=>RX,orderCodexBody:()=>e9,hasWebSocketResponsesLiteMetadata:()=>AX,createWebSocketFetch:()=>aB,applyTurnId:()=>eK,advanceTurn:()=>rJ,TITLE_HEADER:()=>oJ,QUOTA_ACCOUNT_HEADER:()=>WX,OpenAIWebSocketPool:()=>b1,CODEX_BODY_KEY_ORDER:()=>aK});import{createHash as iB}from"node:crypto";var e5="vercel.ai.error",oZ=Symbol.for(e5),P5,E5,A=class Y extends(E5=Error,P5=oZ,E5){constructor({name:X,message:J,cause:Q}){super(J);this[P5]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,e5)}static hasMarker(X,J){let Q=Symbol.for(J);return X!=null&&typeof X==="object"&&Q in X&&typeof X[Q]==="boolean"&&X[Q]===!0}},Y$="AI_APICallError",X$=`vercel.ai.error.${Y$}`,rZ=Symbol.for(X$),M5,w5,b9=class extends(w5=A,M5=rZ,w5){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:Z}){super({name:Y$,message:Y,cause:W});this[M5]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=Z}static isInstance(Y){return A.hasMarker(Y,X$)}},J$="AI_EmptyResponseBodyError",Q$=`vercel.ai.error.${J$}`,sZ=Symbol.for(Q$),A5,R5,aZ=class extends(R5=A,A5=sZ,R5){constructor({message:Y="Empty response body"}={}){super({name:J$,message:Y});this[A5]=!0}static isInstance(Y){return A.hasMarker(Y,Q$)}},$$="AI_EvaluationUnsupportedQuestionTypeError",G$=`vercel.ai.error.${$$}`,tZ=Symbol.for(G$),T5,C5,eZ=class extends(C5=A,T5=tZ,C5){constructor({questionId:Y,questionType:X,provider:J,modelId:Q,message:$=`Question "${Y}" has type "${X}", which is not supported by provider "${J}" and model "${Q}".`}){super({name:$$,message:$});this[T5]=!0,this.questionId=Y,this.questionType=X,this.provider=J,this.modelId=Q}static isInstance(Y){return A.hasMarker(Y,G$)}};function d1(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var W$="AI_InvalidArgumentError",z$=`vercel.ai.error.${W$}`,YH=Symbol.for(z$),_5,I5,K$=class extends(I5=A,_5=YH,I5){constructor({message:Y,cause:X,argument:J}){super({name:W$,message:Y,cause:X});this[_5]=!0,this.argument=J}static isInstance(Y){return A.hasMarker(Y,z$)}},U$="AI_InvalidPromptError",Z$=`vercel.ai.error.${U$}`,XH=Symbol.for(Z$),S5,k5,JH=class extends(k5=A,S5=XH,k5){constructor({prompt:Y,message:X,cause:J}){super({name:U$,message:`Invalid prompt: ${X}`,cause:J});this[S5]=!0,this.prompt=Y}static isInstance(Y){return A.hasMarker(Y,Z$)}},H$="AI_InvalidResponseDataError",L$=`vercel.ai.error.${H$}`,QH=Symbol.for(L$),x5,b5,$H=class extends(b5=A,x5=QH,b5){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:H$,message:X});this[x5]=!0,this.data=Y}static isInstance(Y){return A.hasMarker(Y,L$)}},V$="AI_JSONParseError",N$=`vercel.ai.error.${V$}`,GH=Symbol.for(N$),v5,h5,xY=class extends(h5=A,v5=GH,h5){constructor({text:Y,cause:X}){super({name:V$,message:`JSON parsing failed: Text: ${Y}.
55
- Error message: ${d1(X)}`,cause:X});this[v5]=!0,this.text=Y}static isInstance(Y){return A.hasMarker(Y,N$)}},B$="AI_LoadAPIKeyError",F$=`vercel.ai.error.${B$}`,WH=Symbol.for(F$),g5,y5,zH=class extends(y5=A,g5=WH,y5){constructor({message:Y}){super({name:B$,message:Y});this[g5]=!0}static isInstance(Y){return A.hasMarker(Y,F$)}},O$="AI_LoadSettingError",j$=`vercel.ai.error.${O$}`,KH=Symbol.for(j$),f5,m5,UH=class extends(m5=A,f5=KH,m5){constructor({message:Y}){super({name:O$,message:Y});this[f5]=!0}static isInstance(Y){return A.hasMarker(Y,j$)}},q$="AI_NoContentGeneratedError",D$=`vercel.ai.error.${q$}`,ZH=Symbol.for(D$),c5,u5,HH=class extends(u5=A,c5=ZH,u5){constructor({message:Y="No content generated."}={}){super({name:q$,message:Y});this[c5]=!0}static isInstance(Y){return A.hasMarker(Y,D$)}},P$="AI_NoSuchModelError",E$=`vercel.ai.error.${P$}`,LH=Symbol.for(E$),p5,l5,oX=class extends(l5=A,p5=LH,l5){constructor({errorName:Y=P$,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[p5]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return A.hasMarker(Y,E$)}},M$="AI_NoSuchProviderReferenceError",w$=`vercel.ai.error.${M$}`,VH=Symbol.for(w$),d5,i5,NH=class extends(i5=A,d5=VH,i5){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:M$,message:J});this[d5]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return A.hasMarker(Y,w$)}},A$="AI_TooManyEmbeddingValuesForCallError",R$=`vercel.ai.error.${A$}`,BH=Symbol.for(R$),n5,o5,FH=class extends(o5=A,n5=BH,o5){constructor(Y){super({name:A$,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[n5]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return A.hasMarker(Y,R$)}},T$="AI_TypeValidationError",C$=`vercel.ai.error.${T$}`,OH=Symbol.for(C$),r5,s5,a0=class Y extends(s5=A,r5=OH,s5){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:T$,message:`${$}: Value: ${JSON.stringify(X)}.
56
- Error message: ${d1(J)}`,cause:J});this[r5]=!0,this.value=X,this.context=Q}static isInstance(X){return A.hasMarker(X,C$)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},_$="AI_UnsupportedFunctionalityError",I$=`vercel.ai.error.${_$}`,jH=Symbol.for(I$),a5,t5,qH=class extends(t5=A,a5=jH,t5){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:_$,message:X});this[a5]=!0,this.functionality=Y}static isInstance(Y){return A.hasMarker(Y,I$)}};var zq=Object.freeze({status:"aborted"});function P(Y,X,J){function Q(K,Z){var U;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(U=K._zod).traits??(U.traits=new Set),K._zod.traits.add(Y),X(K,Z);for(let H in W.prototype)if(!(H in K))Object.defineProperty(K,H,{value:W.prototype[H].bind(K)});K._zod.constr=W,K._zod.def=Z}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var Z;let U=J?.Parent?new G:this;Q(U,K),(Z=U._zod).deferred??(Z.deferred=[]);for(let H of U._zod.deferred)H();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var Kq=Symbol("zod_brand");class B1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v9 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var bY={};function U1(Y){if(Y)Object.assign(bY,Y);return bY}var e={};sX(e,{unwrapMessage:()=>h9,uint8ArrayToHex:()=>dH,uint8ArrayToBase64url:()=>pH,uint8ArrayToBase64:()=>y$,stringifyPrimitive:()=>b$,shallowClone:()=>k$,safeExtend:()=>gH,required:()=>mH,randomString:()=>IH,propertyKeyTypes:()=>eX,promiseAllObject:()=>_H,primitiveTypes:()=>x$,prefixIssues:()=>O1,pick:()=>bH,partial:()=>fH,optionalKeys:()=>YJ,omit:()=>vH,objectClone:()=>RH,numKeys:()=>SH,nullish:()=>y9,normalizeParams:()=>n,mergeDefs:()=>C1,merge:()=>yH,jsonStringifyReplacer:()=>U9,joinValues:()=>AH,issue:()=>H9,isPlainObject:()=>_1,isObject:()=>i1,hexToUint8Array:()=>lH,getSizableOrigin:()=>h$,getParsedType:()=>kH,getLengthableOrigin:()=>m9,getEnumValues:()=>g9,getElementAtPath:()=>CH,floatSafeRemainder:()=>aX,finalizeIssue:()=>J1,extend:()=>hH,escapeRegex:()=>F1,esc:()=>vY,defineLazy:()=>J0,createTransparentProxy:()=>xH,cloneDef:()=>TH,clone:()=>X1,cleanRegex:()=>f9,cleanEnum:()=>cH,captureStackTrace:()=>hY,cached:()=>Z9,base64urlToUint8Array:()=>uH,base64ToUint8Array:()=>g$,assignProp:()=>T1,assertNotEqual:()=>PH,assertNever:()=>MH,assertIs:()=>EH,assertEqual:()=>DH,assert:()=>wH,allowsEval:()=>tX,aborted:()=>I1,NUMBER_FORMAT_RANGES:()=>XJ,Class:()=>f$,BIGINT_FORMAT_RANGES:()=>v$});function DH(Y){return Y}function PH(Y){return Y}function EH(Y){}function MH(Y){throw Error()}function wH(Y){}function g9(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function AH(Y,X="|"){return Y.map((J)=>b$(J)).join(X)}function U9(Y,X){if(typeof X==="bigint")return X.toString();return X}function Z9(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function y9(Y){return Y===null||Y===void 0}function f9(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function aX(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let Z=Q.match(/\d?e-(\d?)/);if(Z?.[1])$=Number.parseInt(Z[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var S$=Symbol("evaluating");function J0(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===S$)return;if(Q===void 0)Q=S$,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function RH(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function T1(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function C1(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function TH(Y){return C1(Y._zod.def)}function CH(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function _H(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function IH(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function vY(Y){return JSON.stringify(Y)}var hY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function i1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var tX=Z9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function _1(Y){if(i1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(i1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function k$(Y){if(_1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function SH(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var kH=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},eX=new Set(["string","number","symbol"]),x$=new Set(["string","number","bigint","boolean","symbol","undefined"]);function F1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X1(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function n(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function xH(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function b$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function YJ(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var XJ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},v$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function bH(Y,X){let J=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return T1(this,"shape",$),$},checks:[]});return X1(Y,Q)}function vH(Y,X){let J=Y._zod.def,Q=C1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return T1(this,"shape",$),$},checks:[]});return X1(Y,Q)}function hH(Y,X){if(!_1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=C1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return T1(this,"shape",G),G},checks:[]});return X1(Y,$)}function gH(Y,X){if(!_1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return T1(this,"shape",Q),Q},checks:Y._zod.def.checks};return X1(Y,J)}function yH(Y,X){let J=C1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return T1(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return X1(Y,J)}function fH(Y,X,J){let Q=C1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return T1(this,"shape",G),G},checks:[]});return X1(X,Q)}function mH(Y,X,J){let Q=C1(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return T1(this,"shape",G),G},checks:[]});return X1(X,Q)}function I1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function O1(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function h9(Y){return typeof Y==="string"?Y:Y?.message}function J1(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=h9(Y.inst?._zod.def?.error?.(Y))??h9(X?.error?.(Y))??h9(J.customError?.(Y))??h9(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function h$(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function m9(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function H9(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function cH(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function g$(Y){let X=atob(Y),J=new Uint8Array(X.length);for(let Q=0;Q<X.length;Q++)J[Q]=X.charCodeAt(Q);return J}function y$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function uH(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return g$(X+J)}function pH(Y){return y$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function lH(Y){let X=Y.replace(/^0x/,"");if(X.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(X.length/2);for(let Q=0;Q<X.length;Q+=2)J[Q/2]=Number.parseInt(X.slice(Q,Q+2),16);return J}function dH(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class f${constructor(...Y){}}var m$=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,U9,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},gY=P("$ZodError",m$),JJ=P("$ZodError",m$,{Parent:Error});function c$(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function u$(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,Z=0;while(Z<W.path.length){let U=W.path[Z];if(Z!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],Z++}}};return $(Y),Q}var yY=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new B1;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>J1(Z,G,U1())));throw hY(K,$?.callee),K}return W.value};var fY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((Z)=>J1(Z,G,U1())));throw hY(K,$?.callee),K}return W.value};var c9=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new B1;return G.issues.length?{success:!1,error:new(Y??gY)(G.issues.map((W)=>J1(W,$,U1())))}:{success:!0,data:G.value}},p$=c9(JJ),u9=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>J1(W,$,U1())))}:{success:!0,data:G.value}},l$=u9(JJ),d$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yY(Y)(X,J,$)};var i$=(Y)=>(X,J,Q)=>{return yY(Y)(X,J,Q)};var n$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return fY(Y)(X,J,$)};var o$=(Y)=>async(X,J,Q)=>{return fY(Y)(X,J,Q)};var r$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return c9(Y)(X,J,$)};var s$=(Y)=>(X,J,Q)=>{return c9(Y)(X,J,Q)};var a$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return u9(Y)(X,J,$)};var t$=(Y)=>async(X,J,Q)=>{return u9(Y)(X,J,Q)};var e$=/^[cC][^\s-]{8,}$/,YG=/^[0-9a-z]+$/,XG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,JG=/^[0-9a-vA-V]{20}$/,QG=/^[A-Za-z0-9]{27}$/,$G=/^[a-zA-Z0-9_-]{21}$/,GG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var WG=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,QJ=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var zG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function KG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var UG=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ZG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,HG=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,LG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,VG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$J=/^[A-Za-z0-9_-]*$/,NG=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var BG=/^\+(?:[0-9]){6,14}[0-9]$/,FG="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",OG=new RegExp(`^${FG}$`);function jG(Y){return typeof Y.precision==="number"?Y.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Y.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Y.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function qG(Y){return new RegExp(`^${jG(Y)}$`)}function DG(Y){let X=jG({precision:Y.precision}),J=["Z"];if(Y.local)J.push("");if(Y.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${X}(?:${J.join("|")})`;return new RegExp(`^${FG}T(?:${Q})$`)}var PG=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var EG=/^-?\d+$/,MG=/^-?\d+(?:\.\d+)?/,wG=/^(?:true|false)$/i,AG=/^null$/i;var RG=/^[^A-Z]*$/,TG=/^[^a-z]*$/;var _0=P("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),CG={number:"number",bigint:"bigint",object:"date"},GJ=P("$ZodCheckLessThan",(Y,X)=>{_0.init(Y,X);let J=CG[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),WJ=P("$ZodCheckGreaterThan",(Y,X)=>{_0.init(Y,X);let J=CG[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),_G=P("$ZodCheckMultipleOf",(Y,X)=>{_0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):aX(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),IG=P("$ZodCheckNumberFormat",(Y,X)=>{_0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=XJ[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=EG}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var SG=P("$ZodCheckMaxLength",(Y,X)=>{var J;_0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=m9($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),kG=P("$ZodCheckMinLength",(Y,X)=>{var J;_0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=m9($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),xG=P("$ZodCheckLengthEquals",(Y,X)=>{var J;_0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!y9($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=m9($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),p9=P("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(_0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),bG=P("$ZodCheckRegex",(Y,X)=>{p9.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),vG=P("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=RG),p9.init(Y,X)}),hG=P("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=TG),p9.init(Y,X)}),gG=P("$ZodCheckIncludes",(Y,X)=>{_0.init(Y,X);let J=F1(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),yG=P("$ZodCheckStartsWith",(Y,X)=>{_0.init(Y,X);let J=new RegExp(`^${F1(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),fG=P("$ZodCheckEndsWith",(Y,X)=>{_0.init(Y,X);let J=new RegExp(`.*${F1(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var mG=P("$ZodCheckOverwrite",(Y,X)=>{_0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class zJ{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
57
- `).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
58
- `))}}var uG={major:4,minor:1,patch:8};var z0=P("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=uG;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,Z)=>{let U=I1(W),H;for(let F of K){if(F._zod.def.when){if(!F._zod.def.when(W))continue}else if(U)continue;let V=W.issues.length,N=F._zod.check(W);if(N instanceof Promise&&Z?.async===!1)throw new B1;if(H||N instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await N,W.issues.length===V)return;if(!U)U=I1(W,V)});else{if(W.issues.length===V)continue;if(!U)U=I1(W,V)}}if(H)return H.then(()=>{return W});return W},G=(W,K,Z)=>{if(I1(W))return W.aborted=!0,W;let U=$(K,Q,Z);if(U instanceof Promise){if(Z.async===!1)throw new B1;return U.then((H)=>Y._zod.parse(H,Z))}return Y._zod.parse(U,Z)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(U instanceof Promise)return U.then((H)=>{return G(H,W,K)});return G(U,W,K)}let Z=Y._zod.parse(W,K);if(Z instanceof Promise){if(K.async===!1)throw new B1;return Z.then((U)=>$(U,Q,K))}return $(Z,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=p$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return l$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),pY=P("$ZodString",(Y,X)=>{z0.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??PG(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),U0=P("$ZodStringFormat",(Y,X)=>{p9.init(Y,X),pY.init(Y,X)}),aG=P("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=WG),U0.init(Y,X)}),tG=P("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=QJ(Q))}else X.pattern??(X.pattern=QJ());U0.init(Y,X)}),eG=P("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=zG),U0.init(Y,X)}),Y2=P("$ZodURL",(Y,X)=>{U0.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:NG.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),X2=P("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=KG()),U0.init(Y,X)}),J2=P("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=$G),U0.init(Y,X)}),Q2=P("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=e$),U0.init(Y,X)}),$2=P("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=YG),U0.init(Y,X)}),G2=P("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=XG),U0.init(Y,X)}),W2=P("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=JG),U0.init(Y,X)}),z2=P("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=QG),U0.init(Y,X)}),K2=P("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=DG(X)),U0.init(Y,X)}),U2=P("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=OG),U0.init(Y,X)}),Z2=P("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=qG(X)),U0.init(Y,X)}),H2=P("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=GG),U0.init(Y,X)}),L2=P("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=UG),U0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),V2=P("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=ZG),U0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv6"}),Y._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:Y,continue:!X.abort})}}}),N2=P("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=HG),U0.init(Y,X)}),B2=P("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=LG),U0.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function F2(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var O2=P("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=VG),U0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(F2(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function nH(Y){if(!$J.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return F2(J)}var j2=P("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=$J),U0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(nH(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),q2=P("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=BG),U0.init(Y,X)});function oH(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var D2=P("$ZodJWT",(Y,X)=>{U0.init(Y,X),Y._zod.check=(J)=>{if(oH(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var UJ=P("$ZodNumber",(Y,X)=>{z0.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??MG,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),P2=P("$ZodNumber",(Y,X)=>{IG.init(Y,X),UJ.init(Y,X)}),E2=P("$ZodBoolean",(Y,X)=>{z0.init(Y,X),Y._zod.pattern=wG,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var M2=P("$ZodNull",(Y,X)=>{z0.init(Y,X),Y._zod.pattern=AG,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var w2=P("$ZodUnknown",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J)=>J}),A2=P("$ZodNever",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function pG(Y,X,J){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));X.value[J]=Y.value}var R2=P("$ZodArray",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],Z=X.element._zod.run({value:K,issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>pG(U,J,W)));else pG(Z,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function uY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function T2(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=YJ(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function C2(Y,X,J,Q,$,G){let W=[],K=$.keySet,Z=$.catchall._zod,U=Z.def.type;for(let H of Object.keys(X)){if(K.has(H))continue;if(U==="never"){W.push(H);continue}let F=Z.run({value:X[H],issues:[]},Q);if(F instanceof Promise)Y.push(F.then((V)=>uY(V,J,H,X)));else uY(F,J,H,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var rH=P("$ZodObject",(Y,X)=>{z0.init(Y,X);let J=Z9(()=>T2(X));J0(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let Z in W){let U=W[Z]._zod;if(U.values){K[Z]??(K[Z]=new Set);for(let H of U.values)K[Z].add(H)}}return K});let Q=i1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let Z=W.value;if(!Q(Z))return W.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),W;W.value={};let U=[],H=G.shape;for(let F of G.keys){let N=H[F]._zod.run({value:Z[F],issues:[]},K);if(N instanceof Promise)U.push(N.then((q)=>uY(q,W,F,Z)));else uY(N,W,F,Z)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return C2(U,Z,W,K,J.value,Y)}}),_2=P("$ZodObjectJIT",(Y,X)=>{rH.init(Y,X);let J=Y._zod.parse,Q=Z9(()=>T2(X)),$=(V)=>{let N=new zJ(["shape","payload","ctx"]),q=Q.value,w=(E)=>{let k=vY(E);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};N.write("const input = payload.value;");let h=Object.create(null),g=0;for(let E of q.keys)h[E]=`key_${g++}`;N.write("const newResult = {};");for(let E of q.keys){let k=h[E],m=vY(E);N.write(`const ${k} = ${w(E)};`),N.write(`
59
- if (${k}.issues.length) {
60
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
61
- ...iss,
62
- path: iss.path ? [${m}, ...iss.path] : [${m}]
63
- })));
64
- }
65
-
66
-
67
- if (${k}.value === undefined) {
68
- if (${m} in input) {
69
- newResult[${m}] = undefined;
70
- }
71
- } else {
72
- newResult[${m}] = ${k}.value;
73
- }
74
-
75
- `)}N.write("payload.value = newResult;"),N.write("return payload;");let R=N.compile();return(E,k)=>R(V,E,k)},G,W=i1,K=!bY.jitless,U=K&&tX.value,H=X.catchall,F;Y._zod.parse=(V,N)=>{F??(F=Q.value);let q=V.value;if(!W(q))return V.issues.push({expected:"object",code:"invalid_type",input:q,inst:Y}),V;if(K&&U&&N?.async===!1&&N.jitless!==!0){if(!G)G=$(X.shape);if(V=G(V,N),!H)return V;return C2([],q,V,N,F,Y)}return J(V,N)}});function lG(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!I1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>J1(W,Q,U1())))}),X}var ZJ=P("$ZodUnion",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),J0(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),J0(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),J0(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>f9(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let Z of X.options){let U=Z._zod.run({value:$.value,issues:[]},G);if(U instanceof Promise)K.push(U),W=!0;else{if(U.issues.length===0)return U;K.push(U)}}if(!W)return lG(K,$,Y,G);return Promise.all(K).then((Z)=>{return lG(Z,$,Y,G)})}}),I2=P("$ZodDiscriminatedUnion",(Y,X)=>{ZJ.init(Y,X);let J=Y._zod.parse;J0(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,Z]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of Z)$[K].add(U)}}return $});let Q=Z9(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let Z of K){if(G.has(Z))throw Error(`Duplicate discriminator value "${String(Z)}"`);G.set(Z,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!i1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),S2=P("$ZodIntersection",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([Z,U])=>{return dG(J,Z,U)});return dG(J,G,W)}});function KJ(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(_1(Y)&&_1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=KJ(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=KJ($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function dG(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(I1(Y))return Y;let Q=KJ(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var k2=P("$ZodRecord",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!_1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let Z of W)if(typeof Z==="string"||typeof Z==="number"||typeof Z==="symbol"){let U=X.valueType._zod.run({value:$[Z],issues:[]},Q);if(U instanceof Promise)G.push(U.then((H)=>{if(H.issues.length)J.issues.push(...O1(Z,H.issues));J.value[Z]=H.value}));else{if(U.issues.length)J.issues.push(...O1(Z,U.issues));J.value[Z]=U.value}}let K;for(let Z in $)if(!W.has(Z))K=K??[],K.push(Z);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((U)=>J1(U,Q,U1())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let Z=X.valueType._zod.run({value:$[W],issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((U)=>{if(U.issues.length)J.issues.push(...O1(W,U.issues));J.value[K.value]=U.value}));else{if(Z.issues.length)J.issues.push(...O1(W,Z.issues));J.value[K.value]=Z.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var x2=P("$ZodEnum",(Y,X)=>{z0.init(Y,X);let J=g9(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>eX.has(typeof $)).map(($)=>typeof $==="string"?F1($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),b2=P("$ZodLiteral",(Y,X)=>{if(z0.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?F1(J):J?F1(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var v2=P("$ZodTransform",(Y,X)=>{z0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new B1;return J.value=$,J}});function iG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var h2=P("$ZodOptional",(Y,X)=>{z0.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",J0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),J0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>iG(G,J.value));return iG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),g2=P("$ZodNullable",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"optin",()=>X.innerType._zod.optin),J0(Y._zod,"optout",()=>X.innerType._zod.optout),J0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)}|null)$`):void 0}),J0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),y2=P("$ZodDefault",(Y,X)=>{z0.init(Y,X),Y._zod.optin="optional",J0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>nG(G,X));return nG($,X)}});function nG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var f2=P("$ZodPrefault",(Y,X)=>{z0.init(Y,X),Y._zod.optin="optional",J0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),m2=P("$ZodNonOptional",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>oG(G,Y));return oG($,Y)}});function oG(Y,X){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:X});return Y}var c2=P("$ZodCatch",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"optin",()=>X.innerType._zod.optin),J0(Y._zod,"optout",()=>X.innerType._zod.optout),J0(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>J1(W,Q,U1()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>J1(G,Q,U1()))},input:J.value}),J.issues=[];return J}});var u2=P("$ZodPipe",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"values",()=>X.in._zod.values),J0(Y._zod,"optin",()=>X.in._zod.optin),J0(Y._zod,"optout",()=>X.out._zod.optout),J0(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>cY(W,X.in,Q));return cY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>cY(G,X.out,Q));return cY($,X.out,Q)}});function cY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var p2=P("$ZodReadonly",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"propValues",()=>X.innerType._zod.propValues),J0(Y._zod,"values",()=>X.innerType._zod.values),J0(Y._zod,"optin",()=>X.innerType._zod.optin),J0(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(rG);return rG($)}});function rG(Y){return Y.value=Object.freeze(Y.value),Y}var l2=P("$ZodLazy",(Y,X)=>{z0.init(Y,X),J0(Y._zod,"innerType",()=>X.getter()),J0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),J0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),J0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),J0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),d2=P("$ZodCustom",(Y,X)=>{_0.init(Y,X),z0.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>sG(G,J,Q,Y));sG($,J,Q,Y);return}});function sG(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(H9($))}}var Mq=Symbol("ZodOutput"),wq=Symbol("ZodInput");class lY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function sH(){return new lY}var n1=sH();function i2(Y,X){return new Y({type:"string",...n(X)})}function n2(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...n(X)})}function HJ(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...n(X)})}function o2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...n(X)})}function r2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...n(X)})}function s2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...n(X)})}function a2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...n(X)})}function t2(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...n(X)})}function e2(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...n(X)})}function Y7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...n(X)})}function X7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...n(X)})}function J7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...n(X)})}function Q7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...n(X)})}function $7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...n(X)})}function G7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...n(X)})}function W7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...n(X)})}function z7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...n(X)})}function K7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...n(X)})}function U7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...n(X)})}function Z7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...n(X)})}function H7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...n(X)})}function L7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...n(X)})}function V7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...n(X)})}function N7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...n(X)})}function B7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...n(X)})}function F7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...n(X)})}function O7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...n(X)})}function j7(Y,X){return new Y({type:"number",checks:[],...n(X)})}function q7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...n(X)})}function D7(Y,X){return new Y({type:"boolean",...n(X)})}function P7(Y,X){return new Y({type:"null",...n(X)})}function E7(Y){return new Y({type:"unknown"})}function M7(Y,X){return new Y({type:"never",...n(X)})}function dY(Y,X){return new GJ({check:"less_than",...n(X),value:Y,inclusive:!1})}function l9(Y,X){return new GJ({check:"less_than",...n(X),value:Y,inclusive:!0})}function iY(Y,X){return new WJ({check:"greater_than",...n(X),value:Y,inclusive:!1})}function d9(Y,X){return new WJ({check:"greater_than",...n(X),value:Y,inclusive:!0})}function nY(Y,X){return new _G({check:"multiple_of",...n(X),value:Y})}function oY(Y,X){return new SG({check:"max_length",...n(X),maximum:Y})}function L9(Y,X){return new kG({check:"min_length",...n(X),minimum:Y})}function rY(Y,X){return new xG({check:"length_equals",...n(X),length:Y})}function LJ(Y,X){return new bG({check:"string_format",format:"regex",...n(X),pattern:Y})}function VJ(Y){return new vG({check:"string_format",format:"lowercase",...n(Y)})}function NJ(Y){return new hG({check:"string_format",format:"uppercase",...n(Y)})}function BJ(Y,X){return new gG({check:"string_format",format:"includes",...n(X),includes:Y})}function FJ(Y,X){return new yG({check:"string_format",format:"starts_with",...n(X),prefix:Y})}function OJ(Y,X){return new fG({check:"string_format",format:"ends_with",...n(X),suffix:Y})}function o1(Y){return new mG({check:"overwrite",tx:Y})}function jJ(Y){return o1((X)=>X.normalize(Y))}function qJ(){return o1((Y)=>Y.trim())}function DJ(){return o1((Y)=>Y.toLowerCase())}function PJ(){return o1((Y)=>Y.toUpperCase())}function w7(Y,X,J){return new Y({type:"array",element:X,...n(J)})}function A7(Y,X,J){let Q=n(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function R7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...n(J)})}function T7(Y){let X=aH((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(H9(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(H9($))}},Y(J.value,J)});return X}function aH(Y,X){let J=new _0({check:"custom",...n(X)});return J._zod.check=Y,J}class EJ{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??n1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let H={...X,schemaPath:[...X.schemaPath,Y],path:X.path},F=Y._zod.parent;if(F)W.ref=F,this.process(F,H),this.seen.get(F).isParent=!0;else{let V=W.schema;switch(Q.type){case"string":{let N=V;N.type="string";let{minimum:q,maximum:w,format:h,patterns:g,contentEncoding:R}=Y._zod.bag;if(typeof q==="number")N.minLength=q;if(typeof w==="number")N.maxLength=w;if(h){if(N.format=$[h]??h,N.format==="")delete N.format}if(R)N.contentEncoding=R;if(g&&g.size>0){let E=[...g];if(E.length===1)N.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((k)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:k.source}))]}break}case"number":{let N=V,{minimum:q,maximum:w,format:h,multipleOf:g,exclusiveMaximum:R,exclusiveMinimum:E}=Y._zod.bag;if(typeof h==="string"&&h.includes("int"))N.type="integer";else N.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=E,N.exclusiveMinimum=!0;else N.exclusiveMinimum=E;if(typeof q==="number"){if(N.minimum=q,typeof E==="number"&&this.target!=="draft-4")if(E>=q)delete N.minimum;else delete N.exclusiveMinimum}if(typeof R==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=R,N.exclusiveMaximum=!0;else N.exclusiveMaximum=R;if(typeof w==="number"){if(N.maximum=w,typeof R==="number"&&this.target!=="draft-4")if(R<=w)delete N.maximum;else delete N.exclusiveMaximum}if(typeof g==="number")N.multipleOf=g;break}case"boolean":{let N=V;N.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")V.type="string",V.nullable=!0,V.enum=[null];else V.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{V.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let N=V,{minimum:q,maximum:w}=Y._zod.bag;if(typeof q==="number")N.minItems=q;if(typeof w==="number")N.maxItems=w;N.type="array",N.items=this.process(Q.element,{...H,path:[...H.path,"items"]});break}case"object":{let N=V;N.type="object",N.properties={};let q=Q.shape;for(let g in q)N.properties[g]=this.process(q[g],{...H,path:[...H.path,"properties",g]});let w=new Set(Object.keys(q)),h=new Set([...w].filter((g)=>{let R=Q.shape[g]._zod;if(this.io==="input")return R.optin===void 0;else return R.optout===void 0}));if(h.size>0)N.required=Array.from(h);if(Q.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")N.additionalProperties=!1}else if(Q.catchall)N.additionalProperties=this.process(Q.catchall,{...H,path:[...H.path,"additionalProperties"]});break}case"union":{let N=V,q=Q.options.map((w,h)=>this.process(w,{...H,path:[...H.path,"anyOf",h]}));N.anyOf=q;break}case"intersection":{let N=V,q=this.process(Q.left,{...H,path:[...H.path,"allOf",0]}),w=this.process(Q.right,{...H,path:[...H.path,"allOf",1]}),h=(R)=>("allOf"in R)&&Object.keys(R).length===1,g=[...h(q)?q.allOf:[q],...h(w)?w.allOf:[w]];N.allOf=g;break}case"tuple":{let N=V;N.type="array";let q=this.target==="draft-2020-12"?"prefixItems":"items",w=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",h=Q.items.map((k,m)=>this.process(k,{...H,path:[...H.path,q,m]})),g=Q.rest?this.process(Q.rest,{...H,path:[...H.path,w,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=h,g)N.items=g}else if(this.target==="openapi-3.0"){if(N.items={anyOf:h},g)N.items.anyOf.push(g);if(N.minItems=h.length,!g)N.maxItems=h.length}else if(N.items=h,g)N.additionalItems=g;let{minimum:R,maximum:E}=Y._zod.bag;if(typeof R==="number")N.minItems=R;if(typeof E==="number")N.maxItems=E;break}case"record":{let N=V;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process(Q.keyType,{...H,path:[...H.path,"propertyNames"]});N.additionalProperties=this.process(Q.valueType,{...H,path:[...H.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let N=V,q=g9(Q.entries);if(q.every((w)=>typeof w==="number"))N.type="number";if(q.every((w)=>typeof w==="string"))N.type="string";N.enum=q;break}case"literal":{let N=V,q=[];for(let w of Q.values)if(w===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else q.push(Number(w));else q.push(w);if(q.length===0);else if(q.length===1){let w=q[0];if(N.type=w===null?"null":typeof w,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[w];else N.const=w}else{if(q.every((w)=>typeof w==="number"))N.type="number";if(q.every((w)=>typeof w==="string"))N.type="string";if(q.every((w)=>typeof w==="boolean"))N.type="string";if(q.every((w)=>w===null))N.type="null";N.enum=q}break}case"file":{let N=V,q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:h,mime:g}=Y._zod.bag;if(w!==void 0)q.minLength=w;if(h!==void 0)q.maxLength=h;if(g)if(g.length===1)q.contentMediaType=g[0],Object.assign(N,q);else N.anyOf=g.map((R)=>{return{...q,contentMediaType:R}});else Object.assign(N,q);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process(Q.innerType,H);if(this.target==="openapi-3.0")W.ref=Q.innerType,V.nullable=!0;else V.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"success":{let N=V;N.type="boolean";break}case"default":{this.process(Q.innerType,H),W.ref=Q.innerType,V.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,H),W.ref=Q.innerType,this.io==="input")V._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,H),W.ref=Q.innerType;let N;try{N=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}V.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=V,q=Y._zod.pattern;if(!q)throw Error("Pattern not found in template literal");N.type="string",N.pattern=q.source;break}case"pipe":{let N=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(N,H),W.ref=N;break}case"readonly":{this.process(Q.innerType,H),W.ref=Q.innerType,V.readOnly=!0;break}case"promise":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,H),W.ref=Q.innerType;break}case"lazy":{let N=Y._zod.innerType;this.process(N,H),W.ref=N;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let Z=this.metadataRegistry.get(Y);if(Z)Object.assign(W.schema,Z);if(this.io==="input"&&w0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let H=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let q=J.external.registry.get(U[0])?.id,w=J.external.uri??((g)=>g);if(q)return{ref:w(q)};let h=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=h,{defId:h,ref:`${w("__shared")}#/${H}/${h}`}}if(U[1]===Q)return{ref:"#"};let V=`${"#"}/${H}/`,N=U[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:V+N}},G=(U)=>{if(U[1].schema.$ref)return;let H=U[1],{ref:F,defId:V}=$(U);if(H.def={...H.schema},V)H.defId=V;let N=H.schema;for(let q in N)delete N[q];N.$ref=F};if(J.cycles==="throw")for(let U of this.seen.entries()){let H=U[1];if(H.cycle)throw Error(`Cycle detected: #/${H.cycle?.join("/")}/<root>
76
-
77
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let H=U[1];if(Y===U[0]){G(U);continue}if(J.external){let V=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&V){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(H.cycle){G(U);continue}if(H.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,H)=>{let F=this.seen.get(U),V=F.def??F.schema,N={...V};if(F.ref===null)return;let q=F.ref;if(F.ref=null,q){W(q,H);let w=this.seen.get(q).schema;if(w.$ref&&(H.target==="draft-7"||H.target==="draft-4"||H.target==="openapi-3.0"))V.allOf=V.allOf??[],V.allOf.push(w);else Object.assign(V,w),Object.assign(V,N)}if(!F.isParent)this.override({zodSchema:U,jsonSchema:V,path:F.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let U=J.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(U)}Object.assign(K,Q.def);let Z=J.external?.defs??{};for(let U of this.seen.entries()){let H=U[1];if(H.def&&H.defId)Z[H.defId]=H.def}if(J.external);else if(Object.keys(Z).length>0)if(this.target==="draft-2020-12")K.$defs=Z;else K.definitions=Z;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function C7(Y,X){if(Y instanceof lY){let Q=new EJ(X),$={};for(let K of Y._idmap.entries()){let[Z,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[Z,U]=K;G[Z]=Q.emit(U,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new EJ(X);return J.process(Y),J.emit(Y,X)}function w0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return w0($.element,J);case"object":{for(let G in $.shape)if(w0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(w0(G,J))return!0;return!1}case"intersection":return w0($.left,J)||w0($.right,J);case"tuple":{for(let G of $.items)if(w0(G,J))return!0;if($.rest&&w0($.rest,J))return!0;return!1}case"record":return w0($.keyType,J)||w0($.valueType,J);case"map":return w0($.keyType,J)||w0($.valueType,J);case"set":return w0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return w0($.innerType,J);case"lazy":return w0($.getter(),J);case"default":return w0($.innerType,J);case"prefault":return w0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return w0($.in,J)||w0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var QL=P("ZodISODateTime",(Y,X)=>{K2.init(Y,X),L0.init(Y,X)});function _7(Y){return N7(QL,Y)}var $L=P("ZodISODate",(Y,X)=>{U2.init(Y,X),L0.init(Y,X)});function I7(Y){return B7($L,Y)}var GL=P("ZodISOTime",(Y,X)=>{Z2.init(Y,X),L0.init(Y,X)});function S7(Y){return F7(GL,Y)}var WL=P("ZodISODuration",(Y,X)=>{H2.init(Y,X),L0.init(Y,X)});function k7(Y){return O7(WL,Y)}var x7=(Y,X)=>{gY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>u$(Y,J)},flatten:{value:(J)=>c$(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,U9,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,U9,2)}},isEmpty:{get(){return Y.issues.length===0}}})},Y6=P("ZodError",x7),i0=P("ZodError",x7,{Parent:Error});var b7=yY(i0),v7=fY(i0),h7=c9(i0),aY=u9(i0),g7=d$(i0),y7=i$(i0),f7=n$(i0),m7=o$(i0),c7=r$(i0),u7=s$(i0),p7=a$(i0),l7=t$(i0);var V0=P("ZodType",(Y,X)=>{return z0.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>X1(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>b7(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>h7(Y,J,Q),Y.parseAsync=async(J,Q)=>v7(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>aY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>g7(Y,J,Q),Y.decode=(J,Q)=>y7(Y,J,Q),Y.encodeAsync=async(J,Q)=>f7(Y,J,Q),Y.decodeAsync=async(J,Q)=>m7(Y,J,Q),Y.safeEncode=(J,Q)=>c7(Y,J,Q),Y.safeDecode=(J,Q)=>u7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>p7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>l7(Y,J,Q),Y.refine=(J,Q)=>Y.check(eL(J,Q)),Y.superRefine=(J)=>Y.check(YV(J)),Y.overwrite=(J)=>Y.check(o1(J)),Y.optional=()=>n7(Y),Y.nullable=()=>o7(Y),Y.nullish=()=>n7(o7(Y)),Y.nonoptional=(J)=>iL(Y,J),Y.array=()=>AJ(Y),Y.or=(J)=>RJ([Y,J]),Y.and=(J)=>hL(Y,J),Y.transform=(J)=>r7(Y,mL(J)),Y.default=(J)=>pL(Y,J),Y.prefault=(J)=>dL(Y,J),Y.catch=(J)=>oL(Y,J),Y.pipe=(J)=>r7(Y,J),Y.readonly=()=>aL(Y),Y.describe=(J)=>{let Q=Y.clone();return n1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return n1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return n1.get(Y);let Q=Y.clone();return n1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),s7=P("_ZodString",(Y,X)=>{pY.init(Y,X),V0.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(LJ(...Q)),Y.includes=(...Q)=>Y.check(BJ(...Q)),Y.startsWith=(...Q)=>Y.check(FJ(...Q)),Y.endsWith=(...Q)=>Y.check(OJ(...Q)),Y.min=(...Q)=>Y.check(L9(...Q)),Y.max=(...Q)=>Y.check(oY(...Q)),Y.length=(...Q)=>Y.check(rY(...Q)),Y.nonempty=(...Q)=>Y.check(L9(1,...Q)),Y.lowercase=(Q)=>Y.check(VJ(Q)),Y.uppercase=(Q)=>Y.check(NJ(Q)),Y.trim=()=>Y.check(qJ()),Y.normalize=(...Q)=>Y.check(jJ(...Q)),Y.toLowerCase=()=>Y.check(DJ()),Y.toUpperCase=()=>Y.check(PJ())}),ZL=P("ZodString",(Y,X)=>{pY.init(Y,X),s7.init(Y,X),Y.email=(J)=>Y.check(n2(HL,J)),Y.url=(J)=>Y.check(t2(LL,J)),Y.jwt=(J)=>Y.check(V7(TL,J)),Y.emoji=(J)=>Y.check(e2(VL,J)),Y.guid=(J)=>Y.check(HJ(d7,J)),Y.uuid=(J)=>Y.check(o2(tY,J)),Y.uuidv4=(J)=>Y.check(r2(tY,J)),Y.uuidv6=(J)=>Y.check(s2(tY,J)),Y.uuidv7=(J)=>Y.check(a2(tY,J)),Y.nanoid=(J)=>Y.check(Y7(NL,J)),Y.guid=(J)=>Y.check(HJ(d7,J)),Y.cuid=(J)=>Y.check(X7(BL,J)),Y.cuid2=(J)=>Y.check(J7(FL,J)),Y.ulid=(J)=>Y.check(Q7(OL,J)),Y.base64=(J)=>Y.check(Z7(wL,J)),Y.base64url=(J)=>Y.check(H7(AL,J)),Y.xid=(J)=>Y.check($7(jL,J)),Y.ksuid=(J)=>Y.check(G7(qL,J)),Y.ipv4=(J)=>Y.check(W7(DL,J)),Y.ipv6=(J)=>Y.check(z7(PL,J)),Y.cidrv4=(J)=>Y.check(K7(EL,J)),Y.cidrv6=(J)=>Y.check(U7(ML,J)),Y.e164=(J)=>Y.check(L7(RL,J)),Y.datetime=(J)=>Y.check(_7(J)),Y.date=(J)=>Y.check(I7(J)),Y.time=(J)=>Y.check(S7(J)),Y.duration=(J)=>Y.check(k7(J))});function a7(Y){return i2(ZL,Y)}var L0=P("ZodStringFormat",(Y,X)=>{U0.init(Y,X),s7.init(Y,X)}),HL=P("ZodEmail",(Y,X)=>{eG.init(Y,X),L0.init(Y,X)});var d7=P("ZodGUID",(Y,X)=>{aG.init(Y,X),L0.init(Y,X)});var tY=P("ZodUUID",(Y,X)=>{tG.init(Y,X),L0.init(Y,X)});var LL=P("ZodURL",(Y,X)=>{Y2.init(Y,X),L0.init(Y,X)});var VL=P("ZodEmoji",(Y,X)=>{X2.init(Y,X),L0.init(Y,X)});var NL=P("ZodNanoID",(Y,X)=>{J2.init(Y,X),L0.init(Y,X)});var BL=P("ZodCUID",(Y,X)=>{Q2.init(Y,X),L0.init(Y,X)});var FL=P("ZodCUID2",(Y,X)=>{$2.init(Y,X),L0.init(Y,X)});var OL=P("ZodULID",(Y,X)=>{G2.init(Y,X),L0.init(Y,X)});var jL=P("ZodXID",(Y,X)=>{W2.init(Y,X),L0.init(Y,X)});var qL=P("ZodKSUID",(Y,X)=>{z2.init(Y,X),L0.init(Y,X)});var DL=P("ZodIPv4",(Y,X)=>{L2.init(Y,X),L0.init(Y,X)});var PL=P("ZodIPv6",(Y,X)=>{V2.init(Y,X),L0.init(Y,X)});var EL=P("ZodCIDRv4",(Y,X)=>{N2.init(Y,X),L0.init(Y,X)});var ML=P("ZodCIDRv6",(Y,X)=>{B2.init(Y,X),L0.init(Y,X)});var wL=P("ZodBase64",(Y,X)=>{O2.init(Y,X),L0.init(Y,X)});var AL=P("ZodBase64URL",(Y,X)=>{j2.init(Y,X),L0.init(Y,X)});var RL=P("ZodE164",(Y,X)=>{q2.init(Y,X),L0.init(Y,X)});var TL=P("ZodJWT",(Y,X)=>{D2.init(Y,X),L0.init(Y,X)});var t7=P("ZodNumber",(Y,X)=>{UJ.init(Y,X),V0.init(Y,X),Y.gt=(Q,$)=>Y.check(iY(Q,$)),Y.gte=(Q,$)=>Y.check(d9(Q,$)),Y.min=(Q,$)=>Y.check(d9(Q,$)),Y.lt=(Q,$)=>Y.check(dY(Q,$)),Y.lte=(Q,$)=>Y.check(l9(Q,$)),Y.max=(Q,$)=>Y.check(l9(Q,$)),Y.int=(Q)=>Y.check(i7(Q)),Y.safe=(Q)=>Y.check(i7(Q)),Y.positive=(Q)=>Y.check(iY(0,Q)),Y.nonnegative=(Q)=>Y.check(d9(0,Q)),Y.negative=(Q)=>Y.check(dY(0,Q)),Y.nonpositive=(Q)=>Y.check(l9(0,Q)),Y.multipleOf=(Q,$)=>Y.check(nY(Q,$)),Y.step=(Q,$)=>Y.check(nY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function e7(Y){return j7(t7,Y)}var CL=P("ZodNumberFormat",(Y,X)=>{P2.init(Y,X),t7.init(Y,X)});function i7(Y){return q7(CL,Y)}var _L=P("ZodBoolean",(Y,X)=>{E2.init(Y,X),V0.init(Y,X)});function YW(Y){return D7(_L,Y)}var IL=P("ZodNull",(Y,X)=>{M2.init(Y,X),V0.init(Y,X)});function XW(Y){return P7(IL,Y)}var SL=P("ZodUnknown",(Y,X)=>{w2.init(Y,X),V0.init(Y,X)});function i9(){return E7(SL)}var kL=P("ZodNever",(Y,X)=>{A2.init(Y,X),V0.init(Y,X)});function wJ(Y){return M7(kL,Y)}var xL=P("ZodArray",(Y,X)=>{R2.init(Y,X),V0.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(L9(J,Q)),Y.nonempty=(J)=>Y.check(L9(1,J)),Y.max=(J,Q)=>Y.check(oY(J,Q)),Y.length=(J,Q)=>Y.check(rY(J,Q)),Y.unwrap=()=>Y.element});function AJ(Y,X){return w7(xL,Y,X)}var JW=P("ZodObject",(Y,X)=>{_2.init(Y,X),V0.init(Y,X),e.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>TJ(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:i9()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:wJ()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return e.extend(Y,J)},Y.safeExtend=(J)=>{return e.safeExtend(Y,J)},Y.merge=(J)=>e.merge(Y,J),Y.pick=(J)=>e.pick(Y,J),Y.omit=(J)=>e.omit(Y,J),Y.partial=(...J)=>e.partial(UW,Y,J[0]),Y.required=(...J)=>e.required(ZW,Y,J[0])});function QW(Y,X){let J={type:"object",get shape(){return e.assignProp(this,"shape",Y?e.objectClone(Y):{}),this.shape},...e.normalizeParams(X)};return new JW(J)}function $W(Y,X){return new JW({type:"object",get shape(){return e.assignProp(this,"shape",e.objectClone(Y)),this.shape},catchall:i9(),...e.normalizeParams(X)})}var GW=P("ZodUnion",(Y,X)=>{ZJ.init(Y,X),V0.init(Y,X),Y.options=X.options});function RJ(Y,X){return new GW({type:"union",options:Y,...e.normalizeParams(X)})}var bL=P("ZodDiscriminatedUnion",(Y,X)=>{GW.init(Y,X),I2.init(Y,X)});function WW(Y,X,J){return new bL({type:"union",options:X,discriminator:Y,...e.normalizeParams(J)})}var vL=P("ZodIntersection",(Y,X)=>{S2.init(Y,X),V0.init(Y,X)});function hL(Y,X){return new vL({type:"intersection",left:Y,right:X})}var gL=P("ZodRecord",(Y,X)=>{k2.init(Y,X),V0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function zW(Y,X,J){return new gL({type:"record",keyType:Y,valueType:X,...e.normalizeParams(J)})}var MJ=P("ZodEnum",(Y,X)=>{x2.init(Y,X),V0.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new MJ({...X,checks:[],...e.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new MJ({...X,checks:[],...e.normalizeParams($),entries:G})}});function TJ(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new MJ({type:"enum",entries:J,...e.normalizeParams(X)})}var yL=P("ZodLiteral",(Y,X)=>{b2.init(Y,X),V0.init(Y,X),Y.values=new Set(X.values),Object.defineProperty(Y,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function KW(Y,X){return new yL({type:"literal",values:Array.isArray(Y)?Y:[Y],...e.normalizeParams(X)})}var fL=P("ZodTransform",(Y,X)=>{v2.init(Y,X),V0.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new v9(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(e.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(e.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function mL(Y){return new fL({type:"transform",transform:Y})}var UW=P("ZodOptional",(Y,X)=>{h2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function n7(Y){return new UW({type:"optional",innerType:Y})}var cL=P("ZodNullable",(Y,X)=>{g2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function o7(Y){return new cL({type:"nullable",innerType:Y})}var uL=P("ZodDefault",(Y,X)=>{y2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function pL(Y,X){return new uL({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():e.shallowClone(X)}})}var lL=P("ZodPrefault",(Y,X)=>{f2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function dL(Y,X){return new lL({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():e.shallowClone(X)}})}var ZW=P("ZodNonOptional",(Y,X)=>{m2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function iL(Y,X){return new ZW({type:"nonoptional",innerType:Y,...e.normalizeParams(X)})}var nL=P("ZodCatch",(Y,X)=>{c2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function oL(Y,X){return new nL({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var rL=P("ZodPipe",(Y,X)=>{u2.init(Y,X),V0.init(Y,X),Y.in=X.in,Y.out=X.out});function r7(Y,X){return new rL({type:"pipe",in:Y,out:X})}var sL=P("ZodReadonly",(Y,X)=>{p2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function aL(Y){return new sL({type:"readonly",innerType:Y})}var tL=P("ZodLazy",(Y,X)=>{l2.init(Y,X),V0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function HW(Y){return new tL({type:"lazy",getter:Y})}var CJ=P("ZodCustom",(Y,X)=>{d2.init(Y,X),V0.init(Y,X)});function LW(Y,X){return A7(CJ,Y??(()=>!0),X)}function eL(Y,X={}){return R7(CJ,Y,X)}function YV(Y){return T7(Y)}function VW(Y,X={error:`Input not instance of ${Y.name}`}){let J=new CJ({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...e.normalizeParams(X)});return J._zod.bag.Class=Y,J}function MW(Y=globalThis){var X,J,Q;if(Y.window)return"runtime/browser";if((X=Y.navigator)==null?void 0:X.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((Q=(J=Y.process)==null?void 0:J.versions)==null?void 0:Q.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function XV(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function r1(Y,...X){let J=new Headers(XV(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var JV=[{mediaType:"audio/aac",bytesPrefix:[255,240]},{mediaType:"audio/aac",bytesPrefix:[255,241]},{mediaType:"audio/aac",bytesPrefix:[255,248]},{mediaType:"audio/aac",bytesPrefix:[255,249]},{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],c6=[...JV,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var QV=12,$V=131072,u6=$V+QV;async function eY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var wW="AI_DownloadError",AW=`vercel.ai.error.${wW}`,GV=Symbol.for(AW),NW,BW,g0=class extends(BW=A,NW=GV,BW){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:wW,message:$,cause:Q});this[NW]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return A.hasMarker(Y,AW)}};function WV(Y=globalThis){return Y.window!=null}function FW(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function zV(Y){let X;try{X=new URL(Y)}catch(Q){throw new g0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new g0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new g0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new g0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(RW(Q))throw new g0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(bJ(J)){if(vJ(J))throw new g0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function KV({address:Y,family:X,hostname:J}){if(X===4?!bJ(Y)||vJ(Y):X===6?RW(Y):!0)throw new g0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function bJ(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function vJ(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function UV(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],Z=W.split(":");for(let U=0;U<Z.length;U++){let H=Z[U];if(H.includes(".")){if(U!==Z.length-1||!bJ(H))return null;let[F,V,N,q]=H.split(".").map(Number);K.push(F<<8|V,N<<8|q);continue}if(!/^[0-9a-f]{1,4}$/.test(H))return null;K.push(parseInt(H,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function RW(Y){let X=UV(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return vJ(`${$}.${G}.${W}.${K}`)}return!1}function ZV(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:Z}of G)KV({address:K,family:Z,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var _J;function HV(){var Y,X,J;let Q=globalThis.process;return((Y=Q==null?void 0:Q.release)==null?void 0:Y.name)==="node"&&((X=Q.versions)==null?void 0:X.bun)==null&&((J=Q.versions)==null?void 0:J.deno)==null&&Q.title!=="workerd"&&globalThis.EdgeRuntime==null}async function LV(){if(!HV())return globalThis.fetch;return _J!=null?_J:_J=Promise.resolve().then(VV)}function VV(){let Y=OW("node:module"),{lookup:X}=OW("node:dns"),J=Y.createRequire(TW()),{Agent:Q,fetch:$}=J("undici"),G=new Q({connect:{lookup:ZV(X)}});return(W,K)=>$(W,{...K,dispatcher:G})}function OW(Y){var X;let J=globalThis.process,Q=(X=J==null?void 0:J.getBuiltinModule)==null?void 0:X.call(J,Y);if(Q==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return Q}function TW(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,TW);let[J]=X.stack,Q=J==null?void 0:J.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var NV=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function BV(Y){let X=new Headers(Y);for(let J of NV)X.delete(J);return X}var FV=10,OV=new Set([301,302,303,307,308]);async function jV(Y){return Y==null||Y===globalThis.fetch?await LV():Y}async function CW({url:Y,headers:X,abortSignal:J,maxRedirects:Q=FV,fetch:$,trustedOrigin:G}){var W;let K=X===void 0?void 0:BV(X),Z=(H)=>{let F={signal:J,redirect:H};if(K!==void 0)F.headers=new Headers(K);return F},U=Y;for(let H=0;H<=Q;H++){let F=G!==void 0&&FW(U,G);if(!F)zV(U);let V=F&&$!=null?$:F?globalThis.fetch:await jV($),N=await V(U,Z("manual"));if(N.type==="opaqueredirect"){if(!WV())throw new g0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await V(U,Z("follow"))}let q=(W=N.headers)==null?void 0:W.get("location");if(OV.has(N.status)&&q){eY(N);let w=new URL(q,U).toString();if(K!==void 0&&!FW(w,U)){let h=K.get("user-agent");K=new Headers(h==null?void 0:{"user-agent":h})}U=w;continue}return N}throw new g0({url:Y,message:`Too many redirects (max ${Q})`})}var hJ=2147483648;async function _W({response:Y,url:X,maxBytes:J=hJ}){let Q=Y.headers.get("content-length");if(Q!=null){let H=parseInt(Q,10);if(!isNaN(H)&&H>J)throw await eY(Y),new g0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${H}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:H,value:F}=await G.read();if(H)break;if(K+=F.length,K>J)throw new g0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(F)}}finally{try{await G.cancel()}catch(H){}finally{G.releaseLock()}}let Z=new Uint8Array(K),U=0;for(let H of W)Z.set(H,U),U+=H.length;return Z}var j0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new K$({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},d6=j0();function IW(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var qV=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,DV=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function jW(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(qV.test(Y)===!1&&DV.test(Y)===!1)return X;return PV(X)}function PV(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function EV(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return jW(Y)}try{return jW(Y)}finally{Error.stackTraceLimit=X}}function gJ(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:J}=Y;Y.additionalProperties=J!=null&&typeof J!=="boolean"?S1(J):!1;let{properties:Q}=Y;if(Q!=null)for(let $ of Object.keys(Q))Q[$]=S1(Q[$])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(S1):S1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(S1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(S1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(S1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=S1(X[J]);return Y}function S1(Y){if(typeof Y==="boolean")return Y;return gJ(Y)}var MV=Symbol("Let zodToJsonSchema decide on which parser to use"),qW={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},wV=(Y)=>typeof Y==="string"?{...qW,name:Y}:{...qW,...Y};function n0(){return{}}function AV(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=W0(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function RV(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function TV(){return{type:"boolean"}}function SW(Y,X){return W0(Y.type._def,X)}var CV=(Y,X)=>{return W0(Y.innerType._def,X)};function kW(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>kW(Y,X,$))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return _V(Y)}}var _V=(Y)=>{let X={type:"integer",format:"unix-time"};for(let J of Y.checks)switch(J.kind){case"min":X.minimum=J.value;break;case"max":X.maximum=J.value;break}return X};function IV(Y,X){return{...W0(Y.innerType._def,X),default:Y.defaultValue()}}function SV(Y,X){return X.effectStrategy==="input"?W0(Y.schema._def,X):n0()}function kV(Y){return{type:"string",enum:Array.from(Y.values)}}var xV=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function bV(Y,X){let J=[W0(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),W0(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(xV($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function vV(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var IJ=void 0,Q1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(IJ===void 0)IJ=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return IJ},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function xW(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":$1(J,"email",Q.message,X);break;case"format:idn-email":$1(J,"idn-email",Q.message,X);break;case"pattern:zod":h0(J,Q1.email,Q.message,X);break}break;case"url":$1(J,"uri",Q.message,X);break;case"uuid":$1(J,"uuid",Q.message,X);break;case"regex":h0(J,Q.regex,Q.message,X);break;case"cuid":h0(J,Q1.cuid,Q.message,X);break;case"cuid2":h0(J,Q1.cuid2,Q.message,X);break;case"startsWith":h0(J,RegExp(`^${SJ(Q.value,X)}`),Q.message,X);break;case"endsWith":h0(J,RegExp(`${SJ(Q.value,X)}$`),Q.message,X);break;case"datetime":$1(J,"date-time",Q.message,X);break;case"date":$1(J,"date",Q.message,X);break;case"time":$1(J,"time",Q.message,X);break;case"duration":$1(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{h0(J,RegExp(SJ(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")$1(J,"ipv4",Q.message,X);if(Q.version!=="v4")$1(J,"ipv6",Q.message,X);break}case"base64url":h0(J,Q1.base64url,Q.message,X);break;case"jwt":h0(J,Q1.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")h0(J,Q1.ipv4Cidr,Q.message,X);if(Q.version!=="v4")h0(J,Q1.ipv6Cidr,Q.message,X);break}case"emoji":h0(J,Q1.emoji(),Q.message,X);break;case"ulid":{h0(J,Q1.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{$1(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{h0(J,Q1.base64,Q.message,X);break}}break}case"nanoid":h0(J,Q1.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function SJ(Y,X){return X.patternStrategy==="escape"?gV(Y):Y}var hV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function gV(Y){let X="";for(let J=0;J<Y.length;J++){if(!hV.has(Y[J]))X+="\\";X+=Y[J]}return X}function $1(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function h0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:DW(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=DW(X,Q)}function DW(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,Z=!1;for(let U=0;U<$.length;U++){if(W){G+=$[U],W=!1;continue}if(Q.i){if(K){if($[U].match(/[a-z]/)){if(Z)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),Z=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],Z=!0;else G+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){G+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(Q.m){if($[U]==="^"){G+=`(^|(?<=[\r
78
- ]))`;continue}else if($[U]==="$"){G+=`($|(?=[\r
79
- ]))`;continue}}if(Q.s&&$[U]==="."){G+=K?`${$[U]}\r
80
- `:`[${$[U]}\r
81
- ]`;continue}if(G+=$[U],$[U]==="\\")W=!0;else if(K&&$[U]==="]")K=!1;else if(!K&&$[U]==="[")K=!0}try{new RegExp(G)}catch(U){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function bW(Y,X){var J,Q,$,G,W,K;let Z={type:"object",additionalProperties:(J=W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:U,...H}=xW(Y.keyType._def,X);return{...Z,propertyNames:H}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...Z,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...H}=SW(Y.keyType._def,X);return{...Z,propertyNames:H}}return Z}function yV(Y,X){if(X.mapStrategy==="record")return bW(Y,X);let J=W0(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||n0(),Q=W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||n0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function fV(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function mV(){return{not:n0()}}function cV(){return{type:"null"}}var kJ={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function uV(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in kJ)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=kJ[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return pV(Y,X)}var pV=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>W0(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function lV(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[kJ[Y.innerType._def.typeName],"null"]};let J=W0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function dV(Y){let X={type:"number"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"int":X.type="integer";break;case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function iV(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let Z=oV(K),U=W0(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!Z)Q.push(W)}if(Q.length)J.required=Q;let G=nV(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function nV(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return W0(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function oV(Y){try{return Y.isOptional()}catch(X){return!0}}var rV=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return W0(Y.innerType._def,X);let Q=W0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:n0()},Q]}:n0()},sV=(Y,X)=>{if(X.pipeStrategy==="input")return W0(Y.in._def,X);else if(X.pipeStrategy==="output")return W0(Y.out._def,X);let J=W0(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=W0(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function aV(Y,X){return W0(Y.type._def,X)}function tV(Y,X){let Q={type:"array",uniqueItems:!0,items:W0(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function eV(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>W0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:W0(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>W0(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function YN(){return{not:n0()}}function XN(){return n0()}var JN=(Y,X)=>{return W0(Y.innerType._def,X)},QN=(Y,X,J)=>{switch(X){case"ZodString":return xW(Y,J);case"ZodNumber":return dV(Y);case"ZodObject":return iV(Y,J);case"ZodBigInt":return RV(Y);case"ZodBoolean":return TV();case"ZodDate":return kW(Y,J);case"ZodUndefined":return YN();case"ZodNull":return cV();case"ZodArray":return AV(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return uV(Y,J);case"ZodIntersection":return bV(Y,J);case"ZodTuple":return eV(Y,J);case"ZodRecord":return bW(Y,J);case"ZodLiteral":return vV(Y);case"ZodEnum":return kV(Y);case"ZodNativeEnum":return fV(Y);case"ZodNullable":return lV(Y,J);case"ZodOptional":return rV(Y,J);case"ZodMap":return yV(Y,J);case"ZodSet":return tV(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return aV(Y,J);case"ZodNaN":case"ZodNever":return mV();case"ZodEffects":return SV(Y,J);case"ZodAny":return n0();case"ZodUnknown":return XN();case"ZodDefault":return IV(Y,J);case"ZodBranded":return SW(Y,J);case"ZodReadonly":return JN(Y,J);case"ZodCatch":return CV(Y,J);case"ZodPipeline":return sV(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},$N=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function W0(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let Z=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(Z!==MV)return Z}if($&&!J){let Z=GN($,X);if(Z!==void 0)return Z}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=QN(Y,Y.typeName,X),K=typeof W==="function"?W0(W(),X):W;if(K)WN(Y,X,K);if(X.postProcess){let Z=X.postProcess(K,Y,X);return G.jsonSchema=K,Z}return G.jsonSchema=K,K}var GN=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:$N(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),n0();return X.$refStrategy==="seen"?n0():void 0}}},WN=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},zN=(Y)=>{let X=wV(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},KN=(Y,X)=>{var J;let Q=zN(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[H,F])=>{var V;return{...U,[H]:(V=W0(F._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,H]},!0))!=null?V:n0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=W0(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:n0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let Z=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return Z.$schema="http://json-schema.org/draft-07/schema#",Z},xJ=Symbol.for("vercel.ai.schema");function YX(Y){let X;return()=>{if(X==null)X=Y();return X}}function XX(Y,{validate:X}={}){return{[xJ]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function UN(Y){return typeof Y==="object"&&Y!==null&&xJ in Y&&Y[xJ]===!0&&"jsonSchema"in Y&&"validate"in Y}function JX(Y){return Y==null?XX({type:"object",properties:{},additionalProperties:!1}):UN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?n9(Y):ZN(Y):Y()}function ZN(Y){return XX(()=>{if(!HN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return gJ(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new a0({value:X,cause:J.issues})}}})}function HN(Y){return Y["~standard"].jsonSchema!=null}function LN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return XX(()=>KN(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function VN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return XX(()=>gJ(C7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await aY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function NN(Y){return"_zod"in Y}function n9(Y,X){if(NN(Y))return VN(Y,X);else return LN(Y,X)}async function V9({value:Y,schema:X,context:J}){let Q=JX(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:a0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:a0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function k1({text:Y,schema:X}){try{let J=EV(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await V9({value:J,schema:X})}catch(J){return{success:!1,error:xY.isInstance(J)?J:new xY({text:Y,cause:J}),rawValue:void 0}}}async function yJ(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var vW="AI_SerializationError",hW=`vercel.ai.error.${vW}`,BN=Symbol.for(hW),PW,EW,t6=class extends(EW=A,PW=BN,EW){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:vW,message:Y,cause:X});this[PW]=!0}static isInstance(Y){return A.hasMarker(Y,hW)}};var jN=Object.defineProperty,qN=(Y,X)=>{for(var J in X)jN(Y,J,{get:X[J],enumerable:!0})},xz="AI_InvalidArgumentError",bz=`vercel.ai.error.${xz}`,DN=Symbol.for(bz),gW,yW,fJ=class extends(yW=A,gW=DN,yW){constructor({parameter:Y,value:X,message:J}){super({name:xz,message:`Invalid argument for parameter ${Y}: ${J}`});this[gW]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return A.hasMarker(Y,bz)}},vz="AI_InvalidStreamPartError",hz=`vercel.ai.error.${vz}`,PN=Symbol.for(hz),fW,mW,ZD=class extends(mW=A,fW=PN,mW){constructor({chunk:Y,message:X}){super({name:vz,message:X});this[fW]=!0,this.chunk=Y}static isInstance(Y){return A.hasMarker(Y,hz)}},gz="AI_InvalidToolApprovalError",yz=`vercel.ai.error.${gz}`,EN=Symbol.for(yz),cW,uW,LD=class extends(uW=A,cW=EN,uW){constructor({approvalId:Y}){super({name:gz,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[cW]=!0,this.approvalId=Y}static isInstance(Y){return A.hasMarker(Y,yz)}},fz="AI_InvalidToolApprovalSignatureError",mz=`vercel.ai.error.${fz}`,MN=Symbol.for(mz),pW,lW,ND=class extends(lW=A,pW=MN,lW){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:fz,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[pW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return A.hasMarker(Y,mz)}},cz="AI_InvalidToolInputError",uz=`vercel.ai.error.${cz}`,wN=Symbol.for(uz),dW,iW,FD=class extends(iW=A,dW=wN,iW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${d1(J)}`}){super({name:cz,message:Q,cause:J});this[dW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return A.hasMarker(Y,uz)}},pz="AI_ToolCallNotFoundForApprovalError",lz=`vercel.ai.error.${pz}`,AN=Symbol.for(lz),nW,oW,jD=class extends(oW=A,nW=AN,oW){constructor({toolCallId:Y,approvalId:X}){super({name:pz,message:`Tool call "${Y}" not found for approval request "${X}".`});this[nW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return A.hasMarker(Y,lz)}},dz="AI_MissingToolResultsError",iz=`vercel.ai.error.${dz}`,RN=Symbol.for(iz),rW,sW,DD=class extends(sW=A,rW=RN,sW){constructor({toolCallIds:Y}){super({name:dz,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[rW]=!0,this.toolCallIds=Y}static isInstance(Y){return A.hasMarker(Y,iz)}},nz="AI_NoImageGeneratedError",oz=`vercel.ai.error.${nz}`,TN=Symbol.for(oz),aW,tW,ED=class extends(tW=A,aW=TN,tW){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:nz,message:Y,cause:X});this[aW]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return A.hasMarker(Y,oz)}},rz="AI_NoObjectGeneratedError",sz=`vercel.ai.error.${rz}`,CN=Symbol.for(sz),eW,Yz,j1=class extends(Yz=A,eW=CN,Yz){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:rz,message:Y,cause:X});this[eW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return A.hasMarker(Y,sz)}},az="AI_NoOutputGeneratedError",tz=`vercel.ai.error.${az}`,_N=Symbol.for(tz),Xz,Jz,AD=class extends(Jz=A,Xz=_N,Jz){constructor({message:Y="No output generated.",cause:X}={}){super({name:az,message:Y,cause:X});this[Xz]=!0}static isInstance(Y){return A.hasMarker(Y,tz)}},ez="AI_NoSpeechGeneratedError",YK=`vercel.ai.error.${ez}`,IN=Symbol.for(YK),Qz,$z,TD=class extends($z=A,Qz=IN,$z){constructor(Y){super({name:ez,message:"No speech audio generated."});this[Qz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,YK)}},XK="AI_NoTranscriptGeneratedError",JK=`vercel.ai.error.${XK}`,SN=Symbol.for(JK),Gz,Wz,_D=class extends(Wz=A,Gz=SN,Wz){constructor(Y){super({name:XK,message:"No transcript generated."});this[Gz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,JK)}},QK="AI_NoTranslationGeneratedError",$K=`vercel.ai.error.${QK}`,kN=Symbol.for($K),zz,Kz,SD=class extends(Kz=A,zz=kN,Kz){constructor(Y){super({name:QK,message:"No translation generated."});this[zz]=!0,this.response=Y.response}static isInstance(Y){return A.hasMarker(Y,$K)}},mJ="AI_NoVideoGeneratedError",GK=`vercel.ai.error.${mJ}`,xN=Symbol.for(GK),Uz,Zz,xD=class extends(Zz=A,Uz=xN,Zz){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:mJ,message:Y,cause:X});this[Uz]=!0,this.responses=J}static isInstance(Y){return A.hasMarker(Y,GK)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===mJ&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},WK="AI_NoSuchToolError",zK=`vercel.ai.error.${WK}`,bN=Symbol.for(zK),Hz,Lz,vD=class extends(Lz=A,Hz=bN,Lz){constructor({toolName:Y,availableTools:X=void 0,message:J=`Model tried to call unavailable tool '${Y}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:WK,message:J});this[Hz]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return A.hasMarker(Y,zK)}},KK="AI_StreamProviderError",UK=`vercel.ai.error.${KK}`,vN=Symbol.for(UK),Vz,Nz,gD=class extends(Nz=A,Vz=vN,Nz){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=hN(Q),data:G,cause:W}){super({name:KK,message:Y,cause:W});this[Vz]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return A.hasMarker(Y,UK)}};function hN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var ZK="AI_ToolCallRepairError",HK=`vercel.ai.error.${ZK}`,gN=Symbol.for(HK),Bz,Fz,fD=class extends(Fz=A,Bz=gN,Fz){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${d1(Y)}`}){super({name:ZK,message:J,cause:Y});this[Bz]=!0,this.originalError=X}static isInstance(Y){return A.hasMarker(Y,HK)}},LK="AI_ToolChoiceViolationError",VK=`vercel.ai.error.${LK}`,yN=Symbol.for(VK),Oz,jz,cD=class extends(jz=A,Oz=yN,jz){constructor({toolChoice:Y,finishReason:X,provider:J,modelId:Q,content:$,message:G=Y.type==="required"?"Model response did not contain a tool call even though tool choice was required.":`Model response did not contain a call to the required tool '${Y.toolName}'.`}){super({name:LK,message:G});this[Oz]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return A.hasMarker(Y,VK)}};var NK="AI_UIMessageStreamError",BK=`vercel.ai.error.${NK}`,fN=Symbol.for(BK),qz,Dz,pD=class extends(Dz=A,qz=fN,Dz){constructor({chunkType:Y,chunkId:X,message:J}){super({name:NK,message:J});this[qz]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return A.hasMarker(Y,BK)}},FK="AI_InvalidDataContentError",OK=`vercel.ai.error.${FK}`,mN=Symbol.for(OK),Pz,Ez,dD=class extends(Ez=A,Pz=mN,Ez){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:FK,message:J,cause:X});this[Pz]=!0,this.content=Y}static isInstance(Y){return A.hasMarker(Y,OK)}},jK="AI_InvalidMessageRoleError",qK=`vercel.ai.error.${jK}`,cN=Symbol.for(qK),Mz,wz,nD=class extends(wz=A,Mz=cN,wz){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:jK,message:X});this[Mz]=!0,this.role=Y}static isInstance(Y){return A.hasMarker(Y,qK)}},DK="AI_MessageConversionError",PK=`vercel.ai.error.${DK}`,uN=Symbol.for(PK),Az,Rz,rD=class extends(Rz=A,Az=uN,Rz){constructor({originalMessage:Y,message:X}){super({name:DK,message:X});this[Az]=!0,this.originalMessage=Y}static isInstance(Y){return A.hasMarker(Y,PK)}},EK="AI_RetryError",MK=`vercel.ai.error.${EK}`,pN=Symbol.for(MK),Tz,Cz,aD=class extends(Cz=A,Tz=pN,Cz){constructor({message:Y,reason:X,errors:J}){super({name:EK,message:Y});this[Tz]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return A.hasMarker(Y,MK)}};var lN="7.0.111",dN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=r1({},`ai-sdk/${lN}`,MW()),W=await CW({url:$,headers:G,abortSignal:J});if(!W.ok)throw await eY(W),new g0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await _W({response:W,url:$,maxBytes:X!=null?X:hJ}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(g0.isInstance(G))throw G;throw new g0({url:$,cause:G})}};var z={array:AJ,boolean:YW,custom:LW,discriminatedUnion:WW,enum:TJ,instanceof:VW,lazy:HW,literal:KW,looseObject:$W,never:wJ,null:XW,number:e7,object:QW,record:zW,string:a7,union:RJ,unknown:i9},s1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),s1.optional()),z.array(s1)])),y=z.record(z.string(),z.record(z.string(),s1.optional())),r9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(IW,{message:"Must be a Buffer"})]),cJ=z.record(z.string(),z.string()),wK=z.object({type:z.literal("text"),text:z.string(),providerOptions:y.optional()}),iN=z.object({type:z.literal("image"),image:z.union([r9,z.instanceof(URL),cJ]),mediaType:z.string().optional(),providerOptions:y.optional()}),AK=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:cJ}),z.object({type:z.literal("text"),text:z.string()})]),nN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),RK=z.object({type:z.literal("file"),data:z.union([AK,r9,z.instanceof(URL),cJ]),filename:z.string().optional(),mediaType:z.string(),providerOptions:y.optional()}),oN=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:y.optional()}),rN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:y.optional()}),sN=z.object({type:z.literal("reasoning-file"),data:z.union([nN,r9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:y.optional()}),aN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:y.optional(),providerExecuted:z.boolean().optional()}),tN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:y.optional()}),z.object({type:z.literal("json"),value:s1,providerOptions:y.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:y.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:y.optional()}),z.object({type:z.literal("error-json"),value:s1,providerOptions:y.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:y.optional()}),z.object({type:z.literal("file"),data:AK,mediaType:z.string(),filename:z.string().optional(),providerOptions:y.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:y.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:y.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:y.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:y.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:y.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:y.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:y.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:y.optional()}),z.object({type:z.literal("custom"),providerOptions:y.optional()})]))})]),TK=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:tN,providerOptions:y.optional()}),eN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),YB=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),XB=z.object({role:z.literal("system"),content:z.string(),providerOptions:y.optional()}),JB=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([wK,iN,RK]))]),providerOptions:y.optional()}),QB=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([wK,rN,RK,oN,sN,aN,TK,eN]))]),providerOptions:y.optional()}),$B=z.object({role:z.literal("tool"),content:z.array(z.union([TK,YB])),providerOptions:y.optional()}),XP=z.union([XB,JB,QB,$B]);var GB={};qN(GB,{array:()=>UB,choice:()=>ZB,json:()=>HB,object:()=>KB,text:()=>zB});function WB(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(H){return H>="0"&&H<="9"||H>="A"&&H<="F"||H>="a"&&H<="f"}function W(H,F,V){switch(H){case'"':{J=F,X.pop(),X.push(V),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=F,Q=F,X.pop(),X.push(V),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(V),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=F,X.pop(),X.push(V),X.push("INSIDE_NUMBER");break}case"{":{J=F,X.pop(),X.push(V),X.push("INSIDE_OBJECT_START");break}case"[":{J=F,X.pop(),X.push(V),X.push("INSIDE_ARRAY_START");break}}}function K(H,F){switch(H){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=F,X.pop();break}}}function Z(H,F){switch(H){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=F,X.pop();break}}}for(let H=0;H<Y.length;H++){let F=Y[H];switch(X[X.length-1]){case"ROOT":W(F,H,"FINISH");break;case"INSIDE_OBJECT_START":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=H,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(F){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(F,H,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(F,H);break}case"INSIDE_STRING":{switch(F){case'"':{X.pop(),J=H;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=H}break}case"INSIDE_ARRAY_START":{switch(F){case"]":{J=H,X.pop();break}default:{J=H,W(F,H,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(F){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=H,X.pop();break}default:{J=H;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(F,H,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),F==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=H;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(F)){if($++,$===4)X.pop(),J=H}break}case"INSIDE_NUMBER":{switch(F){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=H;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,H);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,H);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,H);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,H);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let N=Y.substring(Q,H+1);if(!"false".startsWith(N)&&!"true".startsWith(N)&&!"null".startsWith(N)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,H);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(F,H)}else J=H;break}}}let U=Y.slice(0,J+1);for(let H=X.length-1;H>=0;H--)switch(X[H]){case"INSIDE_STRING":{U+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{U+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{U+="]";break}case"INSIDE_LITERAL":{let V=Y.substring(Q,Y.length);if("true".startsWith(V))U+="true".slice(V.length);else if("false".startsWith(V))U+="false".slice(V.length);else if("null".startsWith(V))U+="null".slice(V.length)}}return U}async function QX(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await k1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await k1({text:WB(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var zB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),KB=({schema:Y,name:X,description:J})=>{let Q=JX(Y);return{name:"object",responseFormat:yJ(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await k1({text:$});if(!W.success)throw new j1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await V9({value:W.value,schema:Q});if(!K.success)throw new j1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await QX($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},UB=({element:Y,minItems:X,maxItems:J,name:Q,description:$})=>{if(_z({name:"minItems",value:X}),_z({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new fJ({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let G=JX(Y);return{name:"array",responseFormat:yJ(G.jsonSchema).then((W)=>{let{$schema:K,definitions:Z,$defs:U,...H}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...Z!=null&&{definitions:Z},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:H,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},K){let Z=await k1({text:W});if(!Z.success)throw new j1({message:"No object generated: could not parse the response.",cause:Z.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let U=Z.value;if(U==null||typeof U!=="object"||!("elements"in U)||!Array.isArray(U.elements))throw new j1({message:"No object generated: response did not match schema.",cause:new a0({value:U,cause:"response must be an object with an elements array"}),text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let H=Iz({value:U.elements,minItems:X,maxItems:J});if(H!=null)throw new j1({message:"No object generated: response did not match schema.",cause:H,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let F=[];for(let V of U.elements){let N=await V9({value:V,schema:G});if(!N.success)throw new j1({message:"No object generated: response did not match schema.",cause:N.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});F.push(N.value)}return F},async parsePartialOutput({text:W}){let K=await QX(W);switch(K.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Z=K.value;if(Z==null||typeof Z!=="object"||!("elements"in Z)||!Array.isArray(Z.elements))return;let U=K.state==="repaired-parse"&&Z.elements.length>0?Z.elements.slice(0,-1):Z.elements,H=[];for(let F of U){let V=await V9({value:F,schema:G});if(V.success)H.push(V.value)}return{partial:H}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:K},Z){if(K!=null)for(;W<K.length;W++){if(J!=null&&W>=J){Z.error(Iz({value:K,maxItems:J}));return}Z.enqueue(K[W])}}})}}};function _z({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new fJ({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new fJ({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function Iz({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new a0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new a0({value:Y,cause:`elements array must contain at most ${J} items`});return}var ZB=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await k1({text:Q});if(!G.success)throw new j1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new j1({message:"No object generated: response did not match schema.",cause:new a0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await QX(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},HB=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await k1({text:J});if(!$.success)throw new j1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await QX(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var GP=j0({prefix:"aitxt",size:24}),WP=j0({prefix:"call",size:24});var KP=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
82
-
83
- `)},flush(Y){Y.enqueue(`data: [DONE]
84
-
85
- `)}})}};var o9=z.record(z.string(),s1.optional()),ZP=YX(()=>n9(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:o9.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.looseObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:o9.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:o9.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),approvalDescriptor:z.unknown().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:o9.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:y.optional(),toolMetadata:o9.optional(),dynamic:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.looseObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:y.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:y.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("reset-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var LP=j0({prefix:"aitxt",size:24}),VP=j0({prefix:"call",size:24});var NP=j0({prefix:"aitxt",size:24}),BP=j0({prefix:"call",size:24});var m0=z.record(z.string(),s1.optional()),LB=z.record(z.string(),z.string());var OP=YX(()=>n9(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:y.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:y.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:y.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:y.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:y.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:LB.optional(),providerMetadata:y.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:y.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:y.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:y.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.boolean(),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:y.optional(),resultProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),title:z.string().optional(),toolMetadata:m0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:y.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),descriptor:z.unknown().optional(),requestReason:z.string().optional(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var qP=j0({prefix:"call",size:24});var PP=j0({prefix:"call",size:24});var MP=j0({prefix:"call",size:24});var AP=j0({prefix:"aiobj",size:24});function CK(Y){return({url:X,abortSignal:J})=>dN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var TP=j0({prefix:"aiobj",size:24});var CP=CK();var _P=z.object({token:z.string().refine((Y)=>Y.trim().length>0),url:z.string().refine((Y)=>{try{let X=new URL(Y);return(X.protocol==="ws:"||X.protocol==="wss:")&&X.hostname!==""}catch(X){return!1}}),expiresAt:z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:z.array(z.object({type:z.literal("function"),name:z.string().min(1),description:z.string().optional(),parameters:z.record(z.string(),z.unknown())})).optional()});var _K="AI_NoSuchProviderError",IK=`vercel.ai.error.${_K}`,VB=Symbol.for(IK),Sz,kz,SP=class extends(kz=oX,Sz=VB,kz){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:_K,modelId:Y,modelType:X,message:$});this[Sz]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return A.hasMarker(Y,IK)}};var xP=j0({prefix:"call",size:24});var bP=CK();class c0 extends b9{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var x0={};sX(x0,{toWebSocketUrl:()=>SB,streamResponsesWebSocket:()=>hB,parseRateLimitSignal:()=>a9,normalizeHeaders:()=>kB,markOversizedFrame:()=>cK,isUpgradeFailure:()=>xB,isOversizedFrame:()=>bB,isAbortError:()=>iJ,connectResponsesWebSocket:()=>vB,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>dJ,PROTOCOL_HEADER:()=>yK,OpenAIWebSocket:()=>x0,OVERSIZED_FRAME_MESSAGE:()=>pK});function s9(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function $X(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
86
- `),G=$[0]??"",W=s9(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((N)=>{let q=N.indexOf(":");return q===-1?[]:[[N.slice(0,q).trim().toLowerCase(),N.slice(q+1).trim()]]})),Z=Y.slice(X+4),U=K["content-length"],H=Number(U);if(!J&&(U===void 0||Number.isFinite(H)&&Z.length<H))return;let F=Buffer.from(Z).toString("utf8"),V=(()=>{try{let N=JSON.parse(F);return i(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:F,...i(V?.error)?{error:V.error}:{}}}var NB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",SK=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class uJ{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),Z=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+NB));this.expectedAccept=Buffer.from(new Uint8Array(Z)).toString("base64");let U={};for(let[V,N]of Object.entries(X))U[V.toLowerCase()]=N;let H=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let V of SK)if(U[V]!==void 0)H.push(`${BB(V)}: ${U[V]}`);for(let[V,N]of Object.entries(X))if(!SK.includes(V.toLowerCase())&&V.toLowerCase()!=="content-length")H.push(`${V}: ${N}`);let F=`${H.join(`\r
87
- `)}\r
88
- \r
89
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let V=globalThis.Bun?.connect;if(!V)throw Error("Bun.connect is not available");this.socket=await V({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(F))},data:(N,q)=>this.onData(q),drain:()=>this.flushWrites(),error:(N,q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let w=q instanceof Error?q.message:String(q);this.log("socket_error",{message:w}),this.emit("error",{message:w})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(V){this.readyState=3;let N=V instanceof Error?V.message:String(V);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(Y){if(this.rxBuffer=FB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
90
- \r
91
- `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
92
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
93
- \r
94
- `);if(X===-1)return!1;let J=$X(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let Z=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,Z)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=OB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p1({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function BB(Y){return Y}function FB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function OB(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as jB}from"node:net";import{connect as qB}from"node:tls";var DB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kK=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class pJ{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}peerClose;closeEmitted=!1;emitClose(Y,X){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:X})}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),Z=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+DB));this.expectedAccept=Buffer.from(new Uint8Array(Z)).toString("base64");let U={};for(let[V,N]of Object.entries(X))U[V.toLowerCase()]=N;let H=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let V of kK)if(U[V]!==void 0)H.push(`${PB(V)}: ${U[V]}`);for(let[V,N]of Object.entries(X))if(!kK.includes(V.toLowerCase())&&V.toLowerCase()!=="content-length")H.push(`${V}: ${N}`);let F=`${H.join(`\r
95
- `)}\r
96
- \r
97
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let V=()=>{this.socket?.write(F)},N=J.protocol==="https:"?qB({host:Q,port:$,servername:Q},V):jB({host:Q,port:$},V);this.socket=N,N.on("data",(q)=>{this.onData(typeof q==="string"?Buffer.from(q,"binary"):q)}),N.on("error",(q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let w=q instanceof Error?q.message:String(q);this.log("socket_error",{message:w}),this.emit("error",{message:w})}),N.on("close",(q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:q}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(V){this.readyState=3,this.log("connect_exception",{message:V instanceof Error?V.message:String(V)}),this.emit("error",{message:V instanceof Error?V.message:String(V)})}}onData(Y){if(this.rxBuffer=EB(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
98
- \r
99
- `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
100
- `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=s9($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
101
- \r
102
- `);if(X===-1)return!1;let J=$X(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let Z=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,Z)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:$,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emitClose($,G);return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=MB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return p1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function PB(Y){return Y}function EB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function MB(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function wB(){return typeof globalThis.Bun?.connect==="function"}var xK=wB()?uJ:pJ;function GX(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function AB(Y){let X=GX("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function RB(Y){let X=new URL(Y);if(AB(X))return;if(X.protocol==="http:")return GX("HTTP_PROXY");if(X.protocol==="https:")return GX("HTTPS_PROXY")??GX("HTTP_PROXY");return}var bK={getProxyForUrl:RB};var TB=O0("quota"),x1=O0("transport"),yK="responses_websockets=2026-02-06",vK=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],CB=new Set([w1,"x-opencode-title"]);function _B(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of vK){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!vK.includes(Q.toLowerCase()))J[Q]=$;return J}function IB(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(CB.has(J.toLowerCase()))continue;X[J]=Q}return X}function SB(Y){return Y.replace(/^http/,"ws")}function kB(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function iJ(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var fK=new WeakSet;function xB(Y){return typeof Y==="object"&&Y!==null&&fK.has(Y)}var mK=new WeakSet;function bB(Y){return typeof Y==="object"&&Y!==null&&mK.has(Y)}function cK(Y){return mK.add(Y),Y}function hK(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return fK.add(J),J}function vB(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(lJ(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??yK},$=Q[w1]??Q["session-id"];delete Q["content-length"],Q=_B(IB(Q));let G=typeof Bun>"u"?void 0:bK.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new xK(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),Z=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(Z)clearTimeout(Z);K.removeEventListener("open",H),K.removeEventListener("error",F),K.removeEventListener("close",V),Y.signal?.removeEventListener("abort",N)}function H(){U(),X(K)}function F(q){U(),J(hK(t9(q),q))}function V(q){U(),J(hK(lK("WebSocket closed before open",q.code,q.reason)))}function N(){U(),K.close(),J(lJ(Y.signal))}K.addEventListener("open",H,{once:!0}),K.addEventListener("error",F,{once:!0}),K.addEventListener("close",V,{once:!0}),Y.signal?.addEventListener("abort",N,{once:!0})})}function hB(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,K=!1,Z=!1,U,H=[],F=12,V=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,N=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:N},w,h=0,g,R=new Set,E={addedItemIds:new Set,finished:!1,other:!1};function k(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",j)}function m(_=J){_.close()}function r(){k(),Q?.enqueue(X.encode(`data: [DONE]
103
-
104
- `)),Q?.close()}function a(_){u0(_,_)}function q0(){if(!Z)return"none";if(E.other)return"other";return E.finished?"finished-calls":"unfinished-calls"}function $0(){Q?.enqueue(X.encode(`data: ${JSON.stringify(lB)}
105
-
106
- `)),r()}function Z0(_){let p={...q,openingFrameTypes:H,responseID:w,previousResponseID:V,hasContinuation:V!==void 0,framesSinceCreated:h,msSinceLastFrame:g===void 0?void 0:Date.now()-g},I=q0();if(I==="finished-calls"){if(G)return;x1.warn("stream failed after finished function calls only; ended as completed",{reason:_.message,emittedOutput:!0,outputShape:I,...p}),G=!0,k(),Y.onConnectionInvalid?.(_),$0();return}if(I==="other"){let o=dJ;x1.warn("stream failed after output; not retried",{reason:_.message,emittedOutput:!0,outputShape:I,...p}),u0(Error(o,{cause:_}),new c0(o,{cause:_}));return}x1.warn(I==="none"?"stream failed before output; retryable":"stream failed after unfinished function calls only; retryable",{reason:_.message,emittedOutput:I!=="none",outputShape:I,...p}),a(_)}function u0(_,p){if(G)return;G=!0,k(),Y.onConnectionInvalid?.(p),Q?.error(_)}function o0(_){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>Z0(new c0(_)),Y.idleTimeout)}async function c(_){if(G)return;if(typeof _.data!=="string"){Z0(new c0("Unexpected binary WebSocket frame"));return}let p=_.data,I=(()=>{try{let Q0=JSON.parse(p);return typeof Q0==="object"&&Q0!==null?Q0:void 0}catch{return}})();if(I?.type==="codex.rate_limits"){TB.debug("codex.rate_limits frame received",{pid:process.pid}),o0("idle timeout waiting for websocket");let Q0=gK(I);Y.onQuota?.(Q0);return}let o=q0(),B0=o==="none"||o==="unfinished-calls"?a9(I):void 0;if(B0&&I){G=!0,k(),Y.onRateLimitReached?.(B0.window,B0.resetAt),Y.onTerminal?.(I),Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached at admission (${B0.window})`));return}if(I?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let Q0=await Y.onRetryableTerminal(I);if(G){if(Q0)m(Q0);return}if(Q0){T(Q0);return}}catch(Q0){Z0(new c0(Q0 instanceof Error?Q0.message:String(Q0),{cause:Q0}));return}}let F0=fB(I,p);if(F0&&I){if(!K)Y.onFirstEvent?.(F0);G=!0,k(),Y.onTerminal?.(I);let Q0=new b9({message:F0.message,url:J.url,requestBodyValues:Y.body,statusCode:F0.status,responseHeaders:F0.headers,responseBody:F0.body}),H0=q0();if(H0==="none"||H0==="unfinished-calls"){if(H0==="unfinished-calls")x1.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:F0.status,reason:F0.message,outputShape:H0,responseID:w,previousResponseID:V});Q?.error(Q0);return}if(x1.warn(H0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:F0.status,reason:F0.message,outputShape:H0,responseID:w,previousResponseID:V}),H0==="finished-calls"){$0();return}Q?.error(Error(dJ,{cause:Q0}));return}if(i(I)&&I.type==="response.failed"){let Q0=i(I.response)?I.response.failed:void 0,H0=i(Q0)?Q0.rate_limit_reached_type:void 0;if(typeof H0==="string"){G=!0,k(),Y.onRateLimitReached?.(H0),Y.onTerminal?.(I);let E0=q0();if(E0!=="none")x1.warn(E0==="other"?"rate limit reached after output; ended without retry":E0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...q,outputShape:E0,responseID:w,previousResponseID:V});if(E0==="none"||E0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached mid-stream (${H0})`));else if(E0==="finished-calls")$0();else r();return}}if(!I){if(!K)Y.onFirstEvent?.();o0("idle timeout waiting for websocket");return}if(gB(I,R),!K)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${p.split(/\r?\n/).map((Q0)=>`data: ${Q0}`).join(`
107
- `)}
108
-
109
- `)),K=!0,g=Date.now(),w!==void 0)h++;if(H.length<F)H.push(String(I.type));if(I.type==="response.created")w=uB(I),x1.debug("response created",{...q,responseID:w,previousResponseID:V,hasContinuation:V!==void 0});if(!dB(I.type))Z=!0,pB(I,E);if(o0("idle timeout waiting for websocket"),I.type==="response.completed"||I.type==="response.done"){G=!0,yB(I,R),Y.onComplete?.(I,R),Y.onTerminal?.(I),r();return}if(I.type==="response.failed"||I.type==="response.incomplete"||I.type==="error")G=!0,Y.onTerminal?.(I),r()}function u(_){Z0(new c0(t9(_),{cause:_}))}function D(_){if(G)return;let p=_.code===1009,I=new c0(p?pK:lK("WebSocket closed before response.completed",_.code,_.reason),{retryable:!p});if(p)x1.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:_.reason.toString()});Z0(p?cK(I):I)}function j(){let _=lJ(Y.signal);if(G)return;G=!0,k(),m(),Y.onAbort?.(_),Q?.error(_)}function M(_){if(G)return;G=!0,k(),m(),Y.onAbort?.(mB(_))}function T(_){$(),J=_,J.addEventListener("message",c),J.addEventListener("error",u,{once:!0}),J.addEventListener("close",D,{once:!0}),$=()=>{J.removeEventListener("message",c),J.removeEventListener("error",u),J.removeEventListener("close",D)};let{background:p,...I}=Y.body;o0("idle timeout sending websocket request");try{let o=JSON.stringify({type:"response.create",...I});W=o.length,J.send(o),o0("idle timeout waiting for websocket")}catch(o){if(G)return;a(new c0(o instanceof Error?o.message:String(o),{cause:o}))}}return new Response(new ReadableStream({start(_){if(Q=_,Y.signal?.addEventListener("abort",j,{once:!0}),Y.signal?.aborted){j();return}T(J)},cancel(_){M(_)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function gB(Y,X){if(Y.type!=="response.output_item.done")return;if(!i(Y.item))return;uK(Y.item,X)}function yB(Y,X){let J=Y.response;if(!i(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(i(Q))uK(Q,X)}function uK(Y,X){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let J=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(J)X.add(J)}function fB(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:i(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:i(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function a9(Y){if(typeof Y==="string")try{return a9(JSON.parse(Y))}catch{return}if(!i(Y))return;let X=a9(Y.cause);if(X)return X;let J=a9(Y.body);if(J)return J;let Q=i(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,Z=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:$??"primary",resetAt:Z}}function mB(Y){if(iJ(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function lJ(Y){let X=Y?.reason;if(iJ(X))return X;if(cB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function cB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function uB(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function pB(Y,X){let J=i(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(J?.type==="function_call"&&typeof J.id==="string"){X.addedItemIds.add(J.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&X.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(J?.type==="function_call"&&J.status==="completed"&&typeof J.id==="string"&&typeof J.call_id==="string"&&typeof J.name==="string"&&typeof J.arguments==="string"){X.finished=!0;return}break}X.other=!0}var lB={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function dB(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var dJ="The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started. The transport log records what ended it.",pK="The request was larger than the websocket would carry, so it was sent over HTTP instead. Resending it unchanged over the same socket cannot succeed. The transport log records the size.";function lK(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var oJ="x-opencode-title",WX="x-openai-auth-quota-account",nJ=new Set([oJ,w1,WX,"x-opencode-session"]),nB=15000,oB=300000,rB=3300000,dK="websocket_connection_limit_reached";function sB(Y){let X=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",J=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",Q=X?`acct:${X}`:`tok:${J}`;return iB("sha256").update(Q).digest("hex").slice(0,12)}function aB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??nB,$=Y?.idleTimeout??oB,G=Y?.maxConnectionAge??rB,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,Z=Y?.rawWebSocket??!1,U=Y?.onQuota,H=Y?.onRateLimitReached,F=setInterval(()=>w(),Math.min($,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function V(R,E,k){if(!E||!k)return k;rJ(R,iK(E));let m=new Headers(k.headers),r=m.get("x-codex-turn-metadata");if(!r)return k;let a=Y4(r,R.turnID,R.turnStartedAt);if(!a)return k;return m.set("x-codex-turn-metadata",a),{...k,headers:m}}async function N(R,E){let k=R instanceof URL?R.toString():typeof R==="string"?R:R.url,m=x0.normalizeHeaders(E?.headers),r=Q4(E),a=IY(r);if(E?.method!=="POST"||!new URL(k).pathname.endsWith("/responses"))return X(R,a);let q0=(()=>{try{if(typeof E?.body!=="string")return;let M=JSON.parse(E.body);return typeof M==="object"&&M!==null?M:void 0}catch{return}})();if(!q0?.stream)return X(R,a);if(m[oJ]==="true")return X(R,a);let $0=m[w1]??m["x-session-affinity"]??m["session-id"],Z0=$0;if(!$0)return X(R,a);let u0=x0.normalizeHeaders(r?.headers),o0=sB(u0),c=`${$0}:${o0}:conversation`,u=typeof m[WX]==="string"?m[WX]:void 0,D=H?(M,T)=>H(M,u,T):void 0,j=J.get(c)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(c,j),j.fallback)return X(R,V(j,q0,a));if(j.busy)return X(R,V(j,q0,a));j.busy=!0,j.lastUsedAt=Date.now();try{let M=iK(q0),T=x0.normalizeHeaders(r?.headers),_=typeof T.authorization==="string"&&T.authorization.startsWith("Bearer ")?T.authorization.slice(7):"",p=typeof T["chatgpt-account-id"]==="string"?T["chatgpt-account-id"]:void 0,I=U?(D0)=>U(D0,_,u,p):void 0,o=!j.socket&&!j.continuation?WF(T):T;if(j.socket=await XF(j,Y?.url??k,o,Q,G,Z,E?.signal),ZF(j,M))await JF(j,M,$,{signal:E?.signal??void 0,sessionID:Z0,url:Y?.url??k,headers:r?.headers,onRateLimitReached:D});let B0=()=>{},F0=()=>{},Q0=new Promise((D0,T0)=>{B0=D0,F0=T0}),H0=UF(j,M),E0=e9(eK(j,H0,M)),WY=typeof E0.previous_response_id==="string";await W9({sessionID:Z0,transport:"websocket",phase:"main",bodyText:JSON.stringify(E0),url:Y?.url??k,method:r?.method,headers:r?.headers});let t0=x0.streamResponsesWebSocket({socket:j.socket,body:E0,sessionID:Z0??void 0,idleTimeout:$,signal:E?.signal??void 0,onQuota:I,onRateLimitReached:D,onFirstEvent:(D0)=>B0(D0??!0),onComplete:(D0,T0)=>{let e0=rK(D0);p1({component:"ws-pool",event:"main_completed",sessionID:Z0,responseID:oK(D0),usage:e0}),tK(j,M,D0,T0,WY)},onTerminal:(D0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,D0.type!=="response.completed"&&D0.type!=="response.done")j.continuation=void 0,q1(j)},onConnectionInvalid:(D0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),x0.isOversizedFrame(D0))j.fallback=!0;if(!j.fallback)q(j);j.continuation=void 0,q1(j),B0(!1)},onAbort:(D0)=>{j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,j.continuation=void 0,q1(j),F0(D0)},onRetryableTerminal:async(D0)=>{let T0=nK(D0);if(!T0)return;throw j.fallback=!0,T0}}),t=await tB(Q0,K);if(t!==!1){if(t===!0||t.status<200||t.status>599)return t0;return new Response(t.body,{status:t.status,headers:{"content-type":"application/json",...t.headers}})}let y1=()=>X(R,V(j,q0,a));if(!j.fallback)return eB(t0,y1);return y1()}catch(M){if(j.busy=!1,j.lastUsedAt=Date.now(),x0.isAbortError(M))throw j.streamFailures=0,j.continuation=void 0,q1(j),M;let T=x0.parseRateLimitSignal(M);if(T)D?.(T.window,T.resetAt);if(x0.isUpgradeFailure(M)&&!Z)j.fallback=!0;if(q(j),j.continuation=void 0,q1(j),j.fallback)return X(R,V(j,q0,a));return YF(new c0(M instanceof Error?M.message:String(M),{cause:M}))}}function q(R){if(R.streamFailures++,R.streamFailures>W)R.fallback=!0}function w(){let R=Date.now();for(let[E,k]of J){if(k.busy)continue;if(R-k.lastUsedAt<$)continue;q1(k),J.delete(E)}}function h(){clearInterval(F);for(let R of J.values())q1(R);J.clear()}function g(R){let E=`${R}:`;for(let[k,m]of J){if(!k.startsWith(E))continue;q1(m),J.delete(k)}}return Object.assign(N,{close:h,remove:g})}function nK(Y){if(Y.type!=="error"||!i(Y.error)||Y.error.code!==dK)return;return Error(typeof Y.error.message==="string"?Y.error.message:dK)}async function tB(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function eB(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=J.getReader(),K=async(Z)=>{while(!0){let{done:U,value:H}=await Z.read();if(U)return;if(H&&H.length>0)Q=!0,G.enqueue(H)}};try{await K(W),G.close()}catch(Z){if(Q||!x0.isOversizedFrame(Z)){G.error(Z);return}try{let U=await X();if(!U.ok){G.error(new c0(`HTTP fallback after an oversized WebSocket frame failed with ${U.status}`));return}if(U.body)await K(U.body.getReader());G.close()}catch(U){G.error(U)}}},cancel(G){J.cancel(G)}});return new Response($,{status:Y.status,headers:Y.headers})}function YF(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function XF(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;q1(Y);let K=await x0.connectResponsesWebSocket({url:x0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function q1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function JF(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=$F(X);await W9({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=x0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{p1({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:oK(W),usage:rK(W)}),tK(Y,$,W,K,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(W)=>{let K=nK(W);if(!K)return;throw Y.fallback=!0,K}});await QF(G)}function oK(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function rK(Y){let X=Y.response;if(!i(X))return;return i(X.usage)?X.usage:void 0}async function QF(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function $F(Y){return e9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:GF(Y.client_metadata)})}function sK(Y){return JSON.stringify({session_id:Y.session_id,thread_id:Y.thread_id,thread_source:Y.thread_source,turn_id:"",sandbox:Y.sandbox,request_kind:"prewarm",window_id:Y.window_id})}function GF(Y){if(!i(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!i(X))return Y;return{...Y,"x-codex-turn-metadata":sK(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function WF(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!i(J))return Y;return{...Y,"x-codex-turn-metadata":sK(J)}}catch{return Y}}var aK=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function iK(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(zF);return X}function e9(Y){let X={};for(let J of aK)if(J in Y)X[J]=Y[J];for(let J of Object.keys(Y))if(!(J in X))X[J]=Y[J];return X}function zF(Y){if(!i(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function tK(Y,X,J,Q,$){let G=J.response,W=i(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let Z of Q)K.add(Z);Y.continuation={responseID:W,input:X.input,signature:sJ(X),finalizedCallIds:K}}function rJ(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=sJ(J),W=Y.turnInput&&Y.turnSignature===G?KF(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(X4)||!Y.turnID)Y.turnID=l1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function eK(Y,X,J=X){rJ(Y,X,J);let Q=X.client_metadata;if(!i(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=Y4(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function Y4(Y,X,J){let Q;try{Q=JSON.parse(Y)}catch{return}if(!i(Q))return;return JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:X,sandbox:Q.sandbox,turn_started_at_unix_ms:J,request_kind:"turn",window_id:Q.window_id})}function KF(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(K1(Y[J])!==K1(X[J]))return;return Y.length}function UF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==sJ(X))return Y.continuation=void 0,X;if(!J4(Y.continuation.input,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let Q=J.slice(Y.continuation.input.length),$=HF(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function ZF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!J4(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(X4)}function X4(Y){if(!i(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function HF(Y,X){return Y.filter((J)=>{if(!i(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function sJ(Y){return K1(LF(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function LF(Y){if(!i(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function J4(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(K1(Y[J])!==K1(X[J]))return!1;return!0}function Q4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of nJ)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!nJ.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!nJ.has(X.toLowerCase())))}}var VF=300000,NF=30000,BF=5000,FF=100;function J8(Y){let X=Y.logger,J=Y.now??Date.now,Q=Y.manifestPath??IX(),$=Y.cacheConnector??PF(X),G=Y.detectClaustrumConnection??W4,W,K,Z,U,H,F=!1,V=new Map,N=new Set,q,h={isEnabled:()=>U?.status==="available",wasDetected:()=>U?.status==="available",getCache:()=>W,async ensureCache(){if(W)return W;return await g(),W},getTransport:()=>K,getCustodyProjection:(c,u)=>{let D=V.get(c.id);if(D)return D;return $4(c,Y.storage,u,W,q)},async boot(){if(F)return;try{U=await G()}catch(T){X.warn("custody detection failed",{error:T instanceof Error?T.message:String(T)});return}if(U.status!=="available"){if(U.status==="malformed")X.warn("custody connection malformed; disabled for this process",{reason:U.reason});else X.info("custody not configured; no client/timer created",{});return}let c=await Y.readCustodyManifest(Q);if(q=c,await E(c),Y.storage?.claustrum?.mode!=="claustrum"){X.info("custody connection available but mode is local; manifest read for the refresh gate, no client/timer",{});return}if(!await g()){Z0();return}let u=W;if(!u)return;if(!c.ok&&c.reason!=="absent"){R(await Y.loadAccounts(s(Y.configPath))),Z0();return}await m(),await r(c);let D=await Y.loadAccounts(s(Y.configPath));await Y.onReconcileStep?.("enabled-manifest-join");let j=aJ(c,D),M=[];for(let T of tJ(D)){if(D?.claustrum?.transition?.fingerprints.fallbacks[T.id])continue;if(!eJ(T,c,R0)&&!(v0(T,R0)&&!T.accountId))continue;if(!j.get(T.id))continue;let p=u0(u);M.push(Y8(T,p).then((I)=>o0(T,I,c)).catch((I)=>X.warn("custody boot sweep failed",{error:I instanceof Error?I.message:String(I)})))}await Promise.all(M),await DF(j,u,D,FF),Z0()},async runTick(){if(F)return;if(Y.storage?.claustrum?.mode!=="claustrum")return;let c=q?.ok?q.revision:void 0,u=Y.readCustodyManifest(Q),D=W?void 0:g(),j=await u;if(q=j,!j.ok&&j.reason!=="absent"){R(await Y.loadAccounts(s(Y.configPath)));return}let M=j.ok&&j.revision!==c?await E(j):await Y.loadAccounts(s(Y.configPath));if(!W&&!await D)return;if(j.ok&&j.revision===c){await m(),await Y.onReconcileStep?.("enabled-manifest-join");let _=aJ(j,M);await k(j,_),await $0(j,_);return}await m(),await r(j),await Y.onReconcileStep?.("enabled-manifest-join");let T=aJ(j,M);await k(j,T),await $0(j,T)},dispose(){if(F)return;if(F=!0,H)(Y.clearIntervalFn??clearInterval)(H),H=void 0;try{W?.close()}catch{}if(!W)try{K?.close()}catch{}W=void 0,K=void 0}};async function g(){if(F)return!1;if(W)return!0;if(Z)return Z;if(!U)return!1;let c=(async()=>{let u;try{let D=$({connectionFile:MF(U),handshakeTimeoutMs:BF});u=new U4({connector:()=>D,now:J});let j=await D;if(F)return u.close(),!1;return W=u,K=j,!0}catch(D){return u?.close(),X.warn("custody connect failed; disabled until tick reconnect",{error:D instanceof Error?D.message:String(D)}),!1}})();Z=c;try{return await c}finally{if(Z===c)Z=void 0}}function R(c){for(let u of tJ(c))V.set(u.id,{state:"inert",reason:"manifest-unreadable"})}async function E(c){let u=await Y.loadAccounts(s(Y.configPath));if(!u||!c.ok)return u;for(let[D,j]of f0(c)){if(!u)break;if(D==="main")continue;if(u.accounts.some((p)=>p.id===D))continue;let M=u.claustrum?.rowHistory?.includes(D)?"row removed":"awaiting discovery",T=`${D}:${M}`;if(!N.has(T))N.add(T),X.info(`orphan-binding: ${M}`,{accountId:D});if(u.claustrum?.mode!=="claustrum")continue;let _=null;while(!_&&!F)if(_=await Y.acquireRefreshFileLock({name:M1(D),ttlMs:v1,path:Y.configPath,renew:!0}),!_)await new Promise((p)=>setTimeout(p,5));if(!_)continue;try{await Y.onReconcileStep?.("discovery-lock-acquired",D);let p=await Y.readCustodyManifest(Q),I=await Y.loadAccounts(s(Y.configPath));if(I?.claustrum?.mode!=="claustrum"||!p.ok||f0(p).get(D)!==j||I.accounts.some((o)=>o.id===D))continue;await Y.mutateAccounts((o)=>{if(o.claustrum?.mode!=="claustrum"||o.accounts.some((B0)=>B0.id===D))return o;return{...o,claustrum:{...o.claustrum,mode:"claustrum",rowHistory:[...new Set([...o.claustrum?.rowHistory??[],D])]},accounts:[...o.accounts,{id:D,...N1(R0),enabled:!0}]}},s(Y.configPath))}finally{await _.release().catch(()=>{})}u=await Y.loadAccounts(s(Y.configPath))}return u}async function k(c,u){if(!W)return;let D=await Y.loadAccounts(s(Y.configPath)),j=u0(W);for(let M of tJ(D)){if(D?.claustrum?.transition?.fingerprints.fallbacks[M.id])continue;if(!eJ(M,c,R0)&&!(v0(M,R0)&&!M.accountId))continue;if(!u.has(M.id))continue;let T=await Y8(M,j);o0(M,T,c)}}async function m(){let c=await Y.loadAccounts(s(Y.configPath)),u=c?.claustrum?.transition;if(c?.claustrum?.mode!=="claustrum"||!u)return;let D=!1;for(let[j,M]of Object.entries(u.fingerprints.fallbacks)){let T=await Y.acquireRefreshFileLock({name:M1(j),ttlMs:v1,path:Y.configPath,renew:!0});if(!T){D=!0;continue}try{if(!await Y.withAccountStoreTransaction(async(p)=>{let I=await p.read(),o=I.accounts.find((H0)=>H0.id===j);if(o?.type==="oauth"&&v0(o,"openai"))return!0;if(!o||!N0(o)||!o.access||$9(o.access,o.refresh)!==M)return V.set(j,{state:"inert",reason:"new-local-family-under-claustrum"}),!1;let B0=structuredClone(I),F0=B0.accounts.find((H0)=>H0.id===j);if(!F0||!N0(F0))return!1;Object.assign(F0,N1(R0)),await p.write(B0);let Q0=(await p.read()).accounts.find((H0)=>H0.id===j);return!!(Q0?.type==="oauth"&&v0(Q0,"openai"))},s(Y.configPath)))D=!0}catch{D=!0}finally{await T.release().catch(()=>{})}}if(u.fingerprints.main)if(!Y.auth)D=!0;else{let j=await Y.acquireRefreshFileLock({name:u1,ttlMs:v1,path:Y.configPath,renew:!0});if(!j)D=!0;else try{if(await bX(u.fingerprints.main,{auth:Y.auth,warn:(T)=>X.warn(T,{})})!=="tombstoned")D=!0}finally{await j.release().catch(()=>{})}}if(D)return;await Y.withAccountStoreTransaction(async(j)=>{let M=await j.read();if(M.claustrum?.mode!=="claustrum"||M.claustrum.transition?.manifestRevision!==u.manifestRevision||M.claustrum.transition?.storeGeneration!==u.storeGeneration)return;await j.writeMode("claustrum")},s(Y.configPath))}async function r(c){if(!W||!c.ok)return;let u=await Y.loadAccounts(s(Y.configPath));if(u?.claustrum?.mode!=="claustrum")return;let D=f0(c);for(let j of u.accounts){if(j.type!=="oauth"||j.corrupt!==!0)continue;let M=D.get(j.id),T=M?await a(j.id,j.accountId,M):"no_handle",_=k9({mode:"claustrum",manifest:M?"present":"absent",local:"gone",vault:()=>T,verifiedInProcessLogin:!1});if(!("installTombstone"in _)||!_.installTombstone||!M)continue;await q0(j.id,M)}}async function a(c,u,D){if(Y.resolveFallbackVaultState)return Y.resolveFallbackVaultState({accountId:c,handle:D});if(!W)return"cold";if(W.isReauth(D,J()))return"needs_reauth";try{let j=await W.get(D,h1(Y.storage),{force:!0}),M=W1(j.payload.access),T=M?z1(M):void 0;if(u&&T&&T!==u)return"identity_mismatch";if(!T)X.warn("custody identity unverifiable; serving",{credentialId:D});return"serves"}catch{return W.isReauth(D,J())?"needs_reauth":"cold"}}async function q0(c,u){let D=await Y.acquireRefreshFileLock({name:M1(c),ttlMs:v1,path:Y.configPath,renew:!0});if(!D)return;try{let j=await Y.readCustodyManifest(Q),M=await Y.loadAccounts(s(Y.configPath)),T=M?.accounts.find((_)=>_.id===c);if(M?.claustrum?.mode!=="claustrum"||!j.ok||f0(j).get(c)!==u||T?.type!=="oauth"||T.corrupt!==!0)return;await Y.mutateAccounts((_)=>{let p=_.accounts.find((B0)=>B0.id===c);if(p?.type!=="oauth"||p.corrupt!==!0)return _;let{corrupt:I,...o}=p;return{..._,accounts:_.accounts.map((B0)=>B0.id===c?{...o,...N1(R0)}:B0)}},s(Y.configPath))}finally{await D.release().catch(()=>{})}}async function $0(c,u){if(!W)return;for(let[D,j]of u){if(W.isReauth(j,J()))continue;let T=(await Y.loadAccounts(s(Y.configPath)))?.accounts.find((_)=>_.id===D);if(!T||!N0(T))continue;if(!K4(T,c,Y.storage??{}))continue;try{let _=await W.get(j);V.set(D,{state:"vault",recordVersion:_.recordVersion})}catch{}}}function Z0(){if(F)return;let c=Y.setIntervalFn??setInterval,u=Math.floor((Math.random()*2-1)*NF),D=VF+u;if(H=c(()=>{if(F)return;h.runTick().catch((M)=>X.warn("custody tick failed",{error:M instanceof Error?M.message:String(M)}))},D),H&&typeof H==="object"&&"unref"in H)H.unref?.()}function u0(c){return{loadAccounts:Y.loadAccounts,readCustodyManifest:Y.readCustodyManifest,acquireRefreshFileLock:Y.acquireRefreshFileLock,configPath:Y.configPath,paths:s(Y.configPath),manifestPath:Q,cache:c,minTtlMs:h1(Y.storage),mutateAccounts:Y.mutateAccounts,provider:R0,now:J}}function o0(c,u,D){if(u.kind==="succeeded"){V.set(c.id,{state:"vault",recordVersion:u.recordVersion});return}if(u.kind==="failed"){let M={gone:"gone",identityMismatch:"identityMismatch",nullClaim:"nullClaim",unavailable:"unavailable"}[u.reason];V.set(c.id,{state:"inert",reason:M==="unavailable"?"takeover-incomplete/vault-unavailable":"identity-mismatch"}),jF(X,c.id,M,u.recordVersion,J());return}if(u.reason==="notEnrolling"){let j=J(),M=$4(c,Y.storage,j,W,D);if(M)V.set(c.id,M)}}return h}var OF=3600000,X8=new Map;function jF(Y,X,J,Q,$){let G=`${X}:${J}`,W=X8.get(G);if(W!==void 0&&$-W<OF)return;X8.set(G,$),Y.warn("custody enroll-completion sweep failed",{accountId:X,reason:J,...typeof Q==="number"?{recordVersion:Q}:{}})}function qF(){X8.clear()}function h1(Y){return((Y?.refresh?.refreshBeforeExpiryMinutes??240)+30)*60000}function aJ(Y,X){let J=new Map;for(let[Q,$]of f0(Y)){let G=X?.accounts.find((W)=>W.id===Q);if(G?.type!=="oauth")continue;if(!zX(G,Y,R0))continue;J.set(Q,$)}return J}function $4(Y,X,J,Q,$){let G=X??{},W=$?f0($).get(Y.id):void 0;if(!v0(Y,R0)&&!W)return;if(!v0(Y,R0))return;if(G.claustrum?.mode!=="claustrum"||!W)return YY({kind:"NEEDS_LOGIN"});return YY({kind:"INERT",reason:Q?.isReauth(W,J)?"vault-reauth":"vault-cold"})}async function DF(Y,X,J,Q,$=[]){if(Y.size===0&&$.length===0)return;let G=[...$];for(let[,W]of Y)G.push(X.get(W).then(()=>{return}).catch(()=>{}));await Promise.race([Promise.all(G),new Promise((W)=>setTimeout(W,Q))])}function tJ(Y){if(!Y)return[];return Y.accounts.filter(N0)}function PF(Y){return async(X)=>{let J=await z4.connect({connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs});return EF(J,Y)}}function EF(Y,X){return{getCredential:(J,Q)=>Y.getCredential(J,Q),statusCredential:(J)=>Y.statusCredential(J),reportAuthFailure:(J)=>Y.reportAuthFailure({handle:J.handle,providerStatus:J.providerStatus,recordVersion:J.recordVersion,reporterSource:J.reporterSource}),close:()=>Y.close()}}function MF(Y){if(Y.status!=="available")return Y.path??"";return G4()}var _F=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),IF=new Set(["gpt-5.6","gpt-6","gpt-6.1"]),SF="Refusing to send a request with no access token. This is a defect in the plugin, not a problem with the provider or the account; the transport log names the account and the path that produced it.",kF=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),xF="opencode-oauth-dummy-key",bF="terminal_resize_reflow",U8="0.159.0",vF=`codex_exec/${U8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${U8})`,hF="seccomp",qM=()=>u1,Q8=120000,gF=90000,yF=4000,Z4=50,H4=3,fF=25,mF=60000,cF="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",Z8=!1;function DM(){Z8=!1}var L4=O0("models"),V4=!1,N4=!1;class L8 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}class Z1 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function B4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function uF(Y){return async(X)=>{if(X==="main"){let Z=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=await Y.getAuth();if(U.type!=="oauth")throw new Z1("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(B4(U.access,U.expires,Z,Y.now()))U={type:"oauth",...await Y.refreshMainWithLease()};if(!U.access)throw new Z1("token_unavailable","Main OpenAI account has no usable access token.");let H=W1(U.access),F=H?z1(H):void 0,V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:U.access,chatgptAccountId:F??V?.mainAccountId}}let J=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=J?.accounts.find((Z)=>Z.id===X);if(!J||!Q)throw new Z1("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new Z1("disabled_account",`Fallback account ${X} is disabled.`);if(!N0(Q))throw new Z1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(!await Y.isFallbackRefreshInert?.($,J)&&B4($.access,$.expires,J,Y.now()))$=await Y.refreshFallbackAccount($,J);let G=Y.resolveFallbackAccess?await Y.resolveFallbackAccess($,J):$.access?{token:$.access,provenance:"local"}:g1;if(G===g1||G===t1)throw new Z1("token_unavailable",`Fallback account ${X} has no usable access token.`);let W=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),K=W?.accounts.find((Z)=>Z.id===X);if(!W||!K)throw new Z1("unknown_account",`Fallback account ${X} was not found.`);if(K.enabled===!1)throw new Z1("disabled_account",`Fallback account ${X} is disabled.`);if(!N0(K))throw new Z1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:$.label??X,accessToken:G.token,chatgptAccountId:K.accountId,onAuthFailure:G.provenance==="local"?void 0:async(Z)=>{await Y.reportAuthFailure?.({handle:G.provenance.handle,providerStatus:Z,recordVersion:G.provenance.recordVersion})}}}}function pF(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function $8(Y){return Y instanceof L8}function F4(){throw Error(cF)}function lF(Y){return Math.floor(Math.random()*Y)}function dF(Y){if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:void 0}catch{return}}function iF(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=l1(),G={threadID:$,turnID:l1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function c4(){return K8(qY(),"openai-auth-sessions.json")}function nF(){let Y=new Map;try{let X=JSON.parse(m4(c4(),"utf8"));if(!i(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!i(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:l1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function oF(Y){let X=c4(),J=`${X}.tmp-${process.pid}`;try{AF(qY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};CF(J,`${JSON.stringify(Q,null,2)}
110
- `,"utf8"),RF(J,X)}catch{}}function NX(Y,X){return i(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function rF(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(K1(Y[J])!==K1(X[J]))return!1;return!0}function sF(Y,X){if(!Y.input)return X.length>0;if(!rF(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>NX(Q,"user")||NX(Q,"developer"))}function aF(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(sF(Y,J)||!Y.turnID))Y.turnID=l1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J.slice()}function tF(Y){let X=Y.headers.get(BX);if(Y.headers.delete(BX),!Y.metadata)return{init:Y.init};let J=dF(Y.init?.body);if(!Y.websocket)aF(Y.metadata,J);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let Q=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:hF,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",bF),Y.headers.set("x-codex-turn-metadata",Q),Y.headers.set("user-agent",vF),Y.headers.set("version",U8),Y.dumpSessionID)Y.headers.set(w1,Y.dumpSessionID);let $=J;if(!$)return{init:Y.init};let G=Y.responsesLite&&typeof $.model==="string"&&kF.has($.model);if(G&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(GO);if(QO($,Y.metadata,X),G)$O($);let W={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(W["x-codex-turn-metadata"]=Q,W["x-codex-ws-stream-request-start-ms"]=String(Date.now()),G)W.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=W,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(e9($))}}}function eF(Y,X){return Y.find((J)=>J.enabled!==!1&&N0(J)&&(J.id===X||J.accountId===X))}function O4(Y,X){if(!X)return Y;let J={...Y};for(let Q of["resetCreditsAvailable","resetCreditsApplicable"]){let $=X[Q];if(J[Q]===void 0&&$!==void 0)J[Q]=$}if(J.spendControl===void 0&&J.spendControlCleared!==!0&&X.spendControl!==void 0)J.spendControl=X.spendControl;return J}function UX(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function ZX(Y,X){return f0(Y).get(X)}function u4(Y,X,J=Date.now(),Q=X.mainAccountId,$){let G=Y.getMain(),W=G?.quota;return{main:{quota:W?{...W,checkedAt:G.checkedAt,primary:UX(W.primary,G.checkedAt),secondary:UX(W.secondary,G.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((K)=>K.enabled).map((K)=>{let Z=Y.getFallback(K.id),U=Z?.quota,H=$?.(K,J);return{id:K.id,label:K.label,accountId:Z?.accountId??K.accountId,quota:U?{...U,checkedAt:Z.checkedAt,primary:UX(U.primary,Z.checkedAt),secondary:UX(U.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{},...H?{custody:H}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function EM(Y,X,J,Q=Date.now()){return{...u4(Y,X,Q),activeId:J}}function j4(Y,X){if(X?.headers!==void 0)return new Headers(X.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function YO(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function q4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function H8(Y){if(Array.isArray(Y)){for(let X of Y)H8(X);return}if(!i(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))H8(X)}var XO=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),BX="x-openai-auth-agent",JO=new Set(["title","compaction","summary"]);function QO(Y,X,J){if(J!==null&&JO.has(J))return;let Q=typeof Y.model==="string"?Y.model:"";if(!XO.has(Q))return;let $=i(Y.reasoning)?Y.reasoning:void 0,G=typeof $?.effort==="string"?$.effort:void 0;if(!G)return;let W=Array.isArray(Y.input)?Y.input:void 0;X.effortUpdates??=[];let K=X.effortUpdates,Z=(V)=>wF("sha256").update(K1(V)).digest("hex").slice(0,16);if(X.pinnedEffort===void 0||K.some((V)=>!W||!NX(W[V.anchor],"user")||Z(W[V.anchor])!==V.fingerprint)){X.pinnedEffort=G,X.effortUpdates=[];return}if(!W||W.length===0)return;let U=W.findLastIndex((V)=>NX(V,"user")),H=K.at(-1),F=H?.effort??X.pinnedEffort;if(U>=0&&G!==F)if(H?.anchor===U){let V=K.at(-2)?.effort??X.pinnedEffort;if(G===V)K.pop();else H.effort=G}else K.push({anchor:U,fingerprint:Z(W[U]),effort:G});else if(U<0&&G!==F)return;if(K.some((V,N)=>N>0&&V.anchor<=(K[N-1]?.anchor??-1))){X.pinnedEffort=G,X.effortUpdates=[];return}Y.reasoning={...$,effort:X.pinnedEffort};for(let V=K.length-1;V>=0;V--){let N=K[V];if(!N)continue;W.splice(N.anchor,0,{type:"configuration_update",reasoning:{effort:N.effort}})}}function $O(Y){let X=i(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];H8(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(i(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function GO(Y){if(!i(Y))return Y;if(Y.type!=="function")return Y;let X=i(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:Z,...U}=Y.parameters;return U})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function WO(Y,X={}){let J=X.codexApiEndpoint??r0().codexApiEndpoint,Q=crypto.randomUUID(),$=nF(),G=()=>oF($),W=!1,K=!1,Z=[],U=null,H=Y.client.auth,F=new Map,V=new Map,N,q,w,h={},g=X.custody,R=O0("custody"),E=(D,j="")=>D?async()=>{let M=await D();return{url:M.url,instructions:M.instructions??j,method:"auto",callback:async()=>{try{let T=await M.tokens;return{type:"success",refresh:T.refresh_token,access:T.access_token,expires:Date.now()+(T.expires_in??3600)*1000,accountId:J9(T)}}finally{M.cleanup?.()}}}}:void 0;function k(D,j){return J8({storage:D,configPath:Y0(),loadAccounts:A0,mutateAccounts:P0,withAccountStoreTransaction:LX,readCustodyManifest:Y1,acquireRefreshFileLock:V1,auth:j,...g?{detectClaustrumConnection:async()=>g.detection==="absent"?{status:"absent",path:"test"}:{status:"available",schema:1,wireVersion:1,endpoints:[]},cacheConnector:async()=>g.transport}:{},logger:{info:(M,T)=>R.info(M,T??{}),warn:(M,T)=>R.warn(M,T??{}),debug:(M,T)=>R.debug(M,T??{}),error:(M,T)=>R.error(M,T??{})},now:g?.now})}let m=await A0(s(Y0())),r=await Y1(),a=Y.client.auth;if(a.get&&a.all){if(m1(m??{})==="claustrum")w=k(m,{all:a.all,get:a.get,set:a.set}),g?.onRuntime?.(w),await w.boot();let D=w?.getCache();if(D)h.cache=D;if(h.mainVerdict=await gQ({client:{auth:a},mode:m1(m??{}),manifest:r,mainAccountId:m?.mainAccountId,getCredential:D?async(j)=>{return{access:(await D.get(j,h1(m))).payload.access}}:void 0,isReauth:D?(j)=>D.isReauth(j):void 0,now:Date.now,sleep:(j)=>new Promise((M)=>setTimeout(M,j))}),h.mainVerdict){let j=await a1();await z8({...j,main:{...j.main,custody:YY(h.mainVerdict)}})}}let q0=new wX,$0,Z0={},u0=NQ({client:Y.client,getAuth:async()=>$0?.(),fetchImpl:fetch,dependencies:{...g?.authorize?{authorizeBrowser:E(g.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:E(g.authorize.headless)}:{},custodyQuotaDeps:Z0}}),o0=(D)=>async(j)=>{let M=await xX();try{let T=await D(j);if(T.method!=="auto")return await M.release(),T;return{...T,callback:async()=>{try{let _=await T.callback();if(_.type!=="success"||!("refresh"in _))return await M.release(),_;return dQ({accessToken:_.access??"",refreshToken:_.refresh,getAuth:async()=>{let p=await H.get({path:{id:"openai"}});return i(p)&&typeof p.access==="string"&&typeof p.refresh==="string"?{access:p.access,refresh:p.refresh}:void 0},onObserved:({access:p,refresh:I})=>vQ({type:"oauth",access:p,refresh:I}),release:()=>M.release(),warn:(p)=>g?.warn?.(p)??R.warn(p),now:g?.now??Date.now,sleep:g?.sleep??((p)=>Bun.sleep(p))}).catch(()=>M.release()),_}catch(_){throw await M.release(),_}}}}catch(T){throw await M.release(),T}},c=u0.map((D)=>D.type==="oauth"?{...D,authorize:o0(D.authorize)}:D);async function u(D,j){let M=Y.client.session;if(typeof M?.promptAsync==="function"){let T=await N5(Y.client,D),_={noReply:!0,parts:[{type:"text",text:j,ignored:!0}]};if(T?.agent)_.agent=T.agent;if(T?.model)_.model=T.model;if(T?.variant)_.variant=T.variant;await M.promptAsync({path:{id:D},body:_});return}}return{async dispose(){q0.stop(),w?.dispose(),N?.stopBackgroundRefresh(),N=void 0;for(let M of Z)M.close();Z.length=0;let D=globalThis;for(let[M,T]of F)if(D.__openaiAuthCacheKeepManagers?.get(M)===T)T.stop(),D.__openaiAuthCacheKeepManagers.delete(M);F.clear();let j=globalThis;for(let[M,T]of V)if(j.__openaiAuthRpcServers?.get(M)===T)await T.stop().catch(()=>{}),j.__openaiAuthRpcServers.delete(M);V.clear()},async event(D){if(D.event.type!=="session.deleted")return;let j=D.event.properties.info,M=$.get(j.id);if(M)U?.cacheKeepManager?.remove(M.threadID);if($.delete(j.id))G();if(q){let T=(await A0(s(Y0())))?.accounts;await h4(j.id,T,q)}for(let T of Z)T.remove(j.id)},provider:{id:"openai",async models(D,j){if(j.auth?.type!=="oauth")return D.models;let M=await A0(s(Y0())),T=!M||T4(M),_=T?null:await Z5();if(!T&&_&&!V4)V4=!0,L4.debug("restoring OAuth model costs from models.dev catalog");if(!T&&!_&&!N4)N4=!0,L4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(D.models).filter(([,p])=>{if(p.options.reasoningMode==="pro")return!1;if(_F.has(p.api.id))return!0;if(IF.has(p.api.id))return!1;let o=p.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return o?parseFloat(o)>5.4:!1}).map(([p,I])=>[p,{...I,cost:T?{input:0,output:0,cache:{read:0,write:0}}:_?.[I.api.id]??_?.[p]??I.cost,limit:I.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:I.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:I.id.includes("gpt-5.6")||I.id.includes("gpt-6-sol")||I.id.includes("gpt-6-luna")||I.id.includes("gpt-6.1-sol")?{context:372000,input:244000,output:128000}:I.limit}]))}},auth:{provider:"openai",async loader(D){$0=D;let j=await D();if(j.type!=="oauth")return{};let M=SY(j),T=M.kind==="tombstone"||M.kind==="empty",_=Y.directory?await f4(Y.directory):void 0,p=_?.dir??Y0();if(!T)await _4({type:"oauth",access:j.access??"",refresh:j.refresh??"",expires:j.expires??0},s(Y0()));let I=await A0(s(Y0())).catch((L)=>{let B=Y0();throw Error(`OpenAI auth store at ${B} is corrupt or unreadable: ${L instanceof Error?L.message:String(L)}. Fix or remove it to continue.`,{cause:L})}),o;async function B0(){let L=Y0();try{let B=TF(L);if(o?.path===L&&o.mtimeMs===B.mtimeMs&&o.size===B.size)return o.storage;let O=await A0(s(L));return o={path:L,mtimeMs:B.mtimeMs,size:B.size,storage:O},O}catch{return o=void 0,A0(s(L))}}function F0(){o=void 0}if(I&&j.access&&!T){let L=J9({id_token:"",access_token:j.access,refresh_token:j.refresh??""});if(L&&L!==I.mainAccountId)await P0((B)=>{return B.mainAccountId=L,B},s(Y0())),I.mainAccountId=L,F0()}let Q0=I?.logging?.level;if(Q0&&typeof Q0==="string")_Y(Q0);let H0=O0("transport"),E0=O0("quota"),WY=O0("refresh"),t0=O0("accounts");H0.info("codex auth loader ready",{codexApiEndpoint:J,transport:r0().rawWebSocket?"raw-websocket":r0().webSockets?"websocket":"http"});let t=new CY({storage:I,configPath:Y0(),fetchQuotaFn:void 0}),y1,D0=0,T0=new I4({paths:s(Y0()),refreshFn:(L)=>HX({refreshToken:L.refreshToken,fetchImpl:L.fetchImpl,now:L.now}),quotaManager:t,custody:{readManifest:Y1},onFallbackStorageChanged:F0}),e0=w??k(I);if(!w)g?.onRuntime?.(e0),await e0.boot(),w=e0;if(T){let L=await Y1(),B=ZX(L,"main"),O=e0.getCache();if(B&&O)try{let C=await O.get(B,h1(I)),S=x9(C.payload.access);if(S&&S!==I?.mainAccountId){if(await P0((x)=>{return x.mainAccountId=S,x},s(Y0())),I)I.mainAccountId=S;h.mainAccountId=S,F0()}}catch{}}if(e0.runTick().catch((L)=>R.warn("custody first tick failed",{error:L instanceof Error?L.message:String(L)})),w=e0,I&&I.accounts.length>0)T0.startBackgroundRefresh();let N9=e0;async function zY(L,B){let O=await Y1();return zX(L,O,R0)}async function e1(L,B){let O=await Y1(),C=N9.getCache(),S=ZX(O,L.id);if(!C||!S)return G8(L,B,O);return G8(L,B,O,{cache:C,manifestHandle:S,requestPath:!0,now:g?.now??Date.now,refreshBeforeExpiryMs:(B.refresh?.refreshBeforeExpiryMinutes??240)*60000,completeEnrollmentDeps:{loadAccounts:A0,readCustodyManifest:Y1,acquireRefreshFileLock:V1,configPath:Y0(),paths:s(Y0()),cache:C,minTtlMs:h1(B),mutateAccounts:P0,provider:R0,now:Date.now}})}async function V8(L){if(m1(L)!=="claustrum")return t1;let B=await Y1(),O=ZX(B,"main"),C=N9.getCache(),S=(v)=>{return R.warn("custody main request refused",{reason:v}),g1};if(!O||!C)return S("no-handle");let x=(g?.now??Date.now)();if(C.isBlocked(O))return S("blocked");if(C.isReauth(O,x))return S("reauth");let b=await C.peek(O);if(!b||b.expiresAtMs<=x)return S("cache-miss");return{token:b.payload.access,provenance:{handle:O,recordVersion:b.recordVersion}}}async function B9(L){let B=N9.getCache();if(!B)return;await B.reportAuthFailure({handle:L.handle,providerStatus:L.providerStatus,recordVersion:L.recordVersion})}Object.assign(Z0,{isFallbackRefreshInert:zY,resolveFallbackAccess:e1,reportCustodyAuthFailure:B9});function KY(L={}){let{readSidebarState:B,respectBackoff:O,skipFresherThanMs:C}=L;return{getAuth:D,codexRefreshFn:HX,refreshMainWithLease:HY,fallbackManager:T0,quotaManager:t,loadAccounts:A0,writeSidebarState:LY,client:Y.client,fetchImpl:fetch,now:Date.now,paths:s(Y0()),readSidebarState:B??(()=>a1(p0)),storageMainAccountId:I?.mainAccountId,isOAuthAccountFn:N0,whamFn:TY,isFallbackRefreshInert:zY,resolveFallbackAccess:e1,resolveMainAccess:V8,reportCustodyAuthFailure:B9,...O===void 0?{}:{respectBackoff:O},...C===void 0?{}:{skipFresherThanMs:C}}}let N8=O0("cachekeep"),B8=I?.cachekeep?.enabled===!0,F8=I?.cachekeep?.subagents===!0,O8=I?.cachekeep?.sustain===!0,j8=PQ(I),UY;async function p4(L){await new Promise((B)=>setTimeout(B,L))}async function l4(L){let B;for(let O=1;O<=H4;O++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:L.refresh,access:L.access,expires:L.expires}});return}catch(C){if(B=C,O<H4)await p4(fF*O)}throw new L8(B)}async function ZY(L){await P0((B)=>{return B.refresh=B.refresh??{},L(B),B},s(Y0())),F0()}async function q8(L){let B=Date.now()+yF;while(Date.now()<B){await new Promise((S)=>setTimeout(S,Z4+lF(Z4)));let O=await D();if(O.type!=="oauth"||!O.access)continue;if((O.access!==L.access||O.refresh!==L.refresh||(O.expires??0)>(L.expires??0)+60000)&&(!O.expires||O.expires>Date.now()))return WY.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:O.expires?O.expires-Date.now():void 0}),{access:O.access,refresh:O.refresh??L.refresh??"",expires:O.expires??0}}return null}async function HY(){if(!UY)UY=(async()=>{let L=await D();if(L.type!=="oauth")throw Error("not oauth");if(v0({id:"main",type:"oauth",access:L.access??"",refresh:L.refresh??"",expires:L.expires??0,addedAt:0},R0))throw new A4(R0);if(!L.refresh)throw Error("Token refresh failed: missing refresh token");let B=D4(L.refresh),O=await A0(s(Y0())),C=O?.refresh?.mainLastRefreshError;if(C&&MY(C,L.refresh,Date.now()))throw Error(E4(C,Date.now()));if(O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===B){let v=await q8(L);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let S=await V1({name:u1,ttlMs:Q8,path:Y0(),renew:!0});if(!S){let v=await q8(L);if(v)return v;throw Error("Codex OAuth refresh is already in progress")}let x=crypto.randomUUID(),b=B;try{await ZY((l)=>{l.refresh=l.refresh??{},l.refresh.mainRefreshLeaseId=x,l.refresh.mainRefreshLeaseUntil=Date.now()+gF,l.refresh.mainRefreshLeaseTokenHash=B});let v=await A0(s(Y0()));if(v?.refresh?.mainRefreshLeaseId!==x||v.refresh.mainRefreshLeaseTokenHash!==B)throw Error("Codex OAuth refresh is already in progress");let f=await HX({refreshToken:L.refresh,fetchImpl:fetch,now:Date.now});return await l4(f),await ZY((l)=>{if(l.refresh=l.refresh??{},l.refresh.mainLastRefreshError=void 0,l.refresh.mainRefreshLeaseId===x)l.refresh.mainRefreshLeaseId=void 0,l.refresh.mainRefreshLeaseUntil=void 0,l.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),b=void 0,f}catch(v){if(L.refresh&&!$8(v))await ZY((f)=>{f.refresh=f.refresh??{},f.refresh.mainLastRefreshError=P4({error:v,now:Date.now(),refreshToken:L.refresh??"",previous:f.refresh.mainLastRefreshError})}).catch(()=>{});throw v}finally{if(b)await ZY((v)=>{if(v.refresh?.mainRefreshLeaseId===x&&v.refresh.mainRefreshLeaseTokenHash===b)v.refresh.mainRefreshLeaseId=void 0,v.refresh.mainRefreshLeaseUntil=void 0,v.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S.release().catch(()=>{})}})().finally(()=>{UY=void 0});return UY}let D8=globalThis,FX=D8.__openaiAuthCacheKeepManagers??new Map;D8.__openaiAuthCacheKeepManagers=FX,FX.get(p)?.stop();let F9=new _X({fetchImpl:fetch,getMainToken:async()=>{let L=await D();if(L.type!=="oauth")throw Error("not oauth");if(!L.access||(L.expires??0)<Date.now())try{return(await HY()).access}catch(B){if($8(B))throw B;if(L.access)return L.access;throw Error("main token refresh failed")}return L.access},refreshFallback:async(L)=>{let B=await B0(),O=B?eF(B.accounts,L):void 0;if(!O)throw Error(`fallback account ${L} not found`);let C=B??{version:1,accounts:[O]},S=O;if(!await zY(O,C))S=await T0.refreshAccount(O,C);let x=await e1(S,C);if(x===g1||x===t1)throw Error(`no access token for ${L}`);return{token:x.token,onAuthFailure:x.provenance==="local"?void 0:async(b)=>{await B9({handle:x.provenance.handle,providerStatus:b,recordVersion:x.provenance.recordVersion})}}},codexResponsesUrl:J,logger:N8,now:Date.now,getWindow:()=>j8,getSustain:()=>O8});FX.set(p,F9),F.set(p,F9);async function O9(L,B,O,C,S=!1){if(Object.keys(L).length===0&&!S)return;let x=Date.now(),b=L,v={quota:b,refreshAfter:x+300000,checkedAt:x},f;if(O&&O!=="main"){let d=B?W1(B):null,K0=d?z1(d):void 0,l0=t.peekFallbackForPolicy(O)?.quota,I0=O4(b,l0);v={...v,quota:I0},t.setFallback(O,v,B,S,K0)}else{if(f=C,!f&&B){let l0=W1(B);f=l0?z1(l0):void 0}if(f&&y1&&f!==y1){E0.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:f,currentMainIdentity:y1});return}let d=t.peekMainForPolicy(f)?.quota,K0=O4(b,d);v={...v,quota:K0},t.setMain(B,v,f,S)}E0.debug("quota pushed",{pid:process.pid,accountId:O??"main",snapshot:v.quota});let l=await B0();await LY(t,l,O&&O!=="main"?l?.mainAccountId:f)}function d4(L,B,O){let C=L==="main"?t.peekMainForPolicy()?.quota:t.peekFallbackForPolicy(L)?.quota;return R4(C,B,Date.now(),mF,O)}let j9=X.experimentalWebSockets?b1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:r0().rawWebSocket,onQuota:(L,B,O,C)=>{O9(L,B,O,!O||O==="main"?C:void 0,!0)},onRateLimitReached:(L,B,O)=>{if(!B)E0.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:L});let C=B??"main",S=d4(C,L,O);t.markRateLimited(C,S),E0.debug("mid-stream rate limit mark",{pid:process.pid,accountId:C,window:L})}}):void 0;if(j9)Z.push(j9),W=!0;let p0=S4();q=p0;async function LY(L,B,O=B?.mainAccountId){if(!B)return;await z8(u4(L,B,Date.now(),O,i4),p0)}function i4(L,B){if(!N0(L))return;return N9.getCustodyProjection(L,B)}async function P8(L,B,O,C,S){let x={activeId:O,route:C,updatedAt:Date.now()};if(L){if(await VX({sessionId:L,...x},S,p0),B&&B!==L){if(C==="sticky-balanced"){let b=(await a1(p0)).stickyAssignments?.[GY(B)]?.accountId,v=S===void 0||b==="main"||S.some((f)=>f.enabled!==!1&&f.id===b);if(!b||!v)return;await VX({sessionId:B,activeId:b,route:C,updatedAt:Date.now()},S,p0);return}await VX({sessionId:B,...x},S,p0)}return}await v4(x,p0)}let n4=async(L,B)=>{let O=await V1({name:M1(L),ttlMs:v1,path:Y0(),renew:!0});if(!O)throw Error("Fallback account lock unavailable");try{return await B()}finally{await O.release()}},o4=g?.withFallbackAccountLock??n4,r4=async(L)=>{let B=await Y1();if(!B.ok)return{ready:!1,reason:"manifest-unreadable"};let O=ZX(B,L.id);if(!O)return{ready:!1,reason:"no-handle"};let C=e0.getCache();if(!C)return{ready:!1,reason:"vault-cold"};if(C.isReauth(O,g?.now?.()??Date.now()))return{ready:!1,reason:"vault-reauth"};if(C.isBlocked(O))return{ready:!1,reason:"vault-cold"};try{let S=await C.get(O,h1(I)),x=x9(S.payload.access);if(!x||L.accountId&&L.accountId!==x)return{ready:!1,reason:"identity-mismatch"};return{ready:!0,accountId:x}}catch{return{ready:!1,reason:C.isReauth(O,g?.now?.()??Date.now())?"vault-reauth":"vault-cold"}}};N?.stopBackgroundRefresh(),N=T0,U={accountStoragePath:Y0(),accountStatePath:EY(Y0()),packageVersion:E9,quotaManager:t,loadAccounts:A0,client:Y.client,beginAccountLogin:RY,withFallbackAccountLock:o4,checkUsableCustodyBinding:r4,enterClaustrumMode:async()=>{let L=await A0(s(Y0())),B=(L?.accounts??[]).filter((O)=>O.type==="oauth"&&O.enabled!==!1).map((O)=>O.id);return iQ({accountIds:B,acquireLock:({name:O,renew:C})=>V1({name:O,ttlMs:O===u1?Q8:v1,path:Y0(),renew:C}),withStoreTransaction:(O)=>LX(O,s(Y0())),readManifest:Y1,preflight:async({accountId:O,handle:C})=>{R.info("preflight probing participant",{accountId:O,hasHandle:C.length>0});let S=await e0.ensureCache(),x=S?.isBlocked(C);if(!S||x)return R.warn("preflight vault-cold",{accountId:O,hasCache:S!==void 0,blocked:x}),"vault-cold";if(S.isReauth(C,g?.now?.()??Date.now()))return"vault-reauth";try{let b=await S.get(C,h1(L)),v=x9(b.payload.access);if(!v||O&&O!==v)return"identity-mismatch";return"ready"}catch{return S.isReauth(C,g?.now?.()??Date.now())?"vault-reauth":"vault-cold"}},auth:{all:async()=>{if(typeof H.all==="function")return H.all();let O=process.env.XDG_DATA_HOME??K8(KX.homedir(),".local","share"),C=K8(O,"opencode","auth.json");try{let S=JSON.parse(m4(C,"utf8"));return i(S)?S:{}}catch{return{}}},get:async(O)=>{if(typeof H.get==="function")return H.get(O);if(O.path.id!=="openai"||!$0){R.warn("auth.get unavailable for slot",{id:O.path.id,hasLoaderGetAuth:$0!==void 0});return}return $0()},set:async(O)=>{await H.set(O)}},warn:(O)=>R.warn(O)})},leaveClaustrumMode:()=>nQ({acquireLock:({name:L,renew:B})=>V1({name:L,ttlMs:Q8,path:Y0(),renew:B}),withStoreTransaction:(L)=>LX(L,s(Y0()))}),resolveResetTarget:uF({getAuth:D,refreshMainWithLease:HY,refreshFallbackAccount:(L,B)=>T0.refreshAccount(L,B),loadAccounts:A0,accountStoragePath:Y0(),accountStatePath:EY(Y0()),now:Date.now,isFallbackRefreshInert:zY,resolveFallbackAccess:e1,reportAuthFailure:B9}),...pF(),cacheKeepManager:F9,setCacheKeepEnabled:(L)=>{B8=L},setCacheKeepSubagents:(L)=>{F8=L},setCacheKeepSustain:(L)=>{O8=L},setCacheKeepWindow:(L)=>{j8=L},clearStickyRouting:(L)=>y4(L,p0),getStickyRouting:async(L)=>b4(await a1(p0),L),refreshSidebar:async()=>{let L=await A0(s(Y0()));await LY(t,L)},refreshAllQuota:async()=>E1(KY()),refreshResetTargetQuota:async(L)=>{return(await E1(KY({respectBackoff:!1}),{accountKey:L})).find((O)=>O.account===L)??{account:L,ok:!1,error:"targeted quota refresh returned no result"}}};let OX=null;if(_){let L=globalThis,B=L.__openaiAuthRpcServers??new Map;L.__openaiAuthRpcServers=B;let O=B.get(_.dir);if(O)await O.stop().catch(()=>{}),B.delete(_.dir);try{OX=await D5({dir:_.dir,secureDir:_.secureDir,sweepRoot:_.sweepRoot,drain:F5,apply:async(C)=>{let S={...U,sessionId:C.sessionId},x=await MX(C.command,C.arguments,S);return{text:x.text,knobs:x.knobs}}}),B.set(_.dir,OX),V.set(_.dir,OX)}catch{}}let E8=new WeakMap;function s4(L,B){let O=E8.get(L);if(!O||B.hostname!=="chatgpt.com"||!B.pathname.startsWith("/backend-api/codex/"))return;if(L.status>=200&&L.status<300){N9.getCache()?.markVaultSuccess(O.handle);return}if(L.status!==401)return;B9({handle:O.handle,providerStatus:L.status,recordVersion:O.recordVersion}).catch(()=>{})}async function q9(L,B,O,C,S="main",x){if(!O.trim())throw H0.warn("refusing to send a request with no access token",{account:S,accountId:C,hasProvenance:Boolean(x&&x!=="local")}),Error(SF);let b=j4(L,B);if(b.delete("x-api-key"),b.delete("api-key"),b.set("authorization",`Bearer ${O}`),C)b.set("ChatGPT-Account-Id",C);b.set(b1.QUOTA_ACCOUNT_HEADER,S);let v=q4(b),f=v?iF($,v,G):void 0,l=L instanceof URL?L:new URL(typeof L==="string"?L:L.url),d=l.pathname.includes("/v1/responses")||l.pathname.includes("/chat/completions")?new URL(J):l,K0=(k0)=>{let Y9=w4(k0,x,E8);return s4(Y9,d),Y9},I0=tF({init:{...B,headers:b},headers:b,metadata:f,installationID:Q,websocket:Boolean(j9&&l.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:v}).init,H1=B8,D1=new Headers(I0?.headers),d0=DQ({enabled:H1,includeSubagents:F8,headers:D1,body:I0?.body});if(H1)N8.trace("cachekeep headers",{pid:process.pid,hasParent:D1.has("x-parent-session-id"),sessionKey:d0?.sessionKey,captured:Boolean(d0),affinity:D1.get("x-session-affinity"),opencodeSession:D1.get("x-opencode-session"),sessionId:D1.get("session-id")});if(j9&&l.pathname.endsWith("/responses")){if(H0.debug("WS transport",{pid:process.pid,pathname:l.pathname,accountId:S}),d0)F9.track(d0.sessionKey,d0.bodyText,S,C,d0.replayHeaders,d0.isSubagent);return K0(await j9(d,I0))}let S0=b1.withoutInternalHeaders(I0);if(typeof S0?.body!=="string")return K0(await fetch(d,S0));if(d0)F9.track(d0.sessionKey,d0.bodyText,S,C,d0.replayHeaders,d0.isSubagent);H0.debug("HTTP transport",{pid:process.pid,pathname:l.pathname,accountId:S});try{let k0=await fetch(d,S0);return await W9({sessionID:v,transport:"http",phase:"http",bodyText:S0.body,accountId:S,url:d.toString(),method:S0.method,headers:S0.headers,status:k0.status}),K0(k0)}catch(k0){throw await W9({sessionID:v,transport:"http",phase:"http",bodyText:S0.body,accountId:S,url:d.toString(),method:S0.method,headers:S0.headers,error:k0 instanceof Error?k0.message:String(k0)}),k0}}function VY(L,B){if((B?.method??(L instanceof Request?L.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof B?.body!=="string")return!1;try{let C=L instanceof URL?L.toString():typeof L==="string"?L:L.url;return new URL(C).pathname.endsWith("/responses")}catch{return!1}}function a4(L){return t.peekMainForPolicy(L)?.quota}function M8(L,B){for(let O of[L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt,B])if(typeof O==="number"&&Number.isFinite(O))return O;return}function D9(L,B,O,C,S){let x=M8(L,B),b=M8(O),v=C===S&&O!=null&&(L===void 0||b!==void 0&&(x===void 0||b>x));return{quota:v?O:L,quotaCheckedAt:v?b:x,source:v?"file":"memory"}}function w8(L,B,O,C,S){let x=L?.quota,b=D9(x,L?.checkedAt,B,C,S),v=b.source,f=b.quota;if(!x4(f,O))return{exhausted:!1};let l=k4(f,O);if(!l)return{exhausted:!1};return{exhausted:!0,source:v,...l}}function A8(L,B){E0.debug("admission skip: exhausted account",{accountId:L,source:B.source,resetsAt:B.resetsAt})}function t4(L,B="killswitch",O){let C=Date.now(),S=t.getMain()?.quota,x=(L?.accounts??[]).filter((d)=>d.enabled!==!1&&N0(d)).map((d)=>({accountId:d.id,quota:t.getFallback(d.id)?.quota})),b=C4(S,x,C,L);if(B==="quota-exhausted"&&O!==void 0)b=Math.max(1,Math.ceil((O-C)/1000));else if(B==="mid-stream-rate-limit"&&O!==void 0){let d=Math.max(1,Math.ceil((O-C)/1000));b=Math.min(b,d)}let v=Math.floor(b/60),f=b%60,l=B==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${v}m ${f}s.`:B==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${v}m ${f}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${v}m ${f}s.`;return new Response(JSON.stringify({error:{message:l,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(b)}})}function R8(L){let B=L?.resetCreditsAvailable;return typeof B==="number"&&Number.isFinite(B)?B:void 0}async function e4(L){let B=QY(L.storage),O=Date.now(),C=t.peekMainForPolicy(L.mainAccountIdentity),S=D9(C?.quota,C?.checkedAt,L.sidebarState.main.quota,L.sidebarState.main.mainAccountId,L.mainAccountIdentity),x=B?$Y(C?.quota,L.storage,void 0,O):void 0,b=L.mainCustodyRefused?[]:[{accountId:"main",wireAccountId:L.mainAccountIdentity,access:L.primaryAccess,provenance:L.primaryProvenance,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:W8(L.storage),configuredOrder:0,resetCreditsApplicable:R8(S.quota),killswitchPasses:x}],v=await T0.getUsableFallbackAccounts(L.storage);if(!L.storage)return b;for(let f of v){let l=await e1(f,L.storage);if(l===g1||l===t1)continue;let d=L.sidebarState.fallbacks.find((H1)=>H1.id===f.id),K0=t.peekFallbackForPolicy(f.id,f.accountId),l0=D9(K0?.quota,K0?.checkedAt,d?.quota,d?.accountId,f.accountId),I0=B?$Y(K0?.quota,L.storage,f.id,O):void 0;b.push({accountId:f.id,wireAccountId:f.accountId,access:l.token,provenance:l.provenance,keepwarmAccountKey:f.id,fallback:f,quota:l0.quota,quotaCheckedAt:l0.quotaCheckedAt,reservePercent:W8(L.storage,f.id),configuredOrder:b.length,resetCreditsApplicable:R8(l0.quota),killswitchPasses:I0})}return b}function T8(L,B,O,C,S){let x=QY(S)?L.killswitchPasses:void 0;if(L.accountId==="main"){let l=t.peekMainForPolicy(L.wireAccountId),d=D9(l?.quota,l?.checkedAt,B.main.quota,B.main.mainAccountId,L.wireAccountId);return gX({quota:d.quota,quotaCheckedAt:d.quotaCheckedAt,status:O,now:C,killswitchPasses:x})}let b=B.fallbacks.find((l)=>l.id===L.accountId),v=t.peekFallbackForPolicy(L.accountId,L.wireAccountId),f=D9(v?.quota,v?.checkedAt,b?.quota,b?.accountId,L.wireAccountId);return gX({quota:f.quota,quotaCheckedAt:f.quotaCheckedAt,status:O,now:C,killswitchPasses:x})}function YU(L){return L.accountId==="main"?"main":L.keepwarmAccountKey}function C8(L){return t.isRateLimited(YU(L))}async function jX(L){let B=L.candidates.filter((f)=>!C8(f)),O=new Map(B.map((f)=>[f.accountId,f])),C=Object.fromEntries(B.map((f)=>[f.accountId,f.quotaCheckedAt])),S=Object.fromEntries(B.map((f)=>[f.accountId,f.wireAccountId])),x=new Set(L.excludeAccountIds),b,v=await g4({sessionId:L.sessionId,requestBytes:L.requestBytes,now:L.now,validPinnedAccountIds:[...O.keys()],excludeAccountIds:L.excludeAccountIds,quotaCheckedAtByAccount:C,wireAccountIdByAccount:S,choose:(f)=>{let l=B.filter((K0)=>!x.has(K0.accountId));if(l.length===0)return;let d=eQ({candidates:l,pendingBytes:f,requestBytes:L.requestBytes,now:L.now,onEmptyWeightedSet:()=>{t0.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!d)return;return b={accountId:d.accountId,source:d.source,pendingBytes:f.get(d.accountId)??0},d}},p0);if(b&&v?.accountId===b.accountId)t0.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:GY(L.sessionId),accountId:b.accountId,source:b.source,requestBytes:L.requestBytes,pendingBytes:b.pendingBytes});return v?O.get(v.accountId):void 0}async function XU(L,B){let O=await T0.getUsableFallbackAccounts(L),C=[];if(!L)return{current:[],retained:[],skipped:[]};for(let d of O){let K0=await e1(d,L);if(K0===g1||K0===t1)continue;C.push({access:K0.token,provenance:K0.provenance,accountId:d.accountId,keepwarmAccountKey:d.id,quotaAccountId:d.id,fallback:d})}let S=C.filter((d)=>!t.isRateLimited(d.quotaAccountId)),x=QY(L)?S.filter((d)=>$Y(t.peekFallbackForPolicy(d.quotaAccountId,d.accountId)?.quota,L,d.quotaAccountId,Date.now())):S,b=new Map(B.fallbacks.map((d)=>[d.id,{quota:d.quota,accountId:d.accountId}])),v=[],f=[],l=Date.now();for(let d of x){let K0=b.get(d.quotaAccountId),l0=w8(t.peekFallbackForPolicy(d.quotaAccountId,d.accountId),K0?.quota,l,K0?.accountId,d.accountId);if(l0.exhausted)f.push({candidate:d,decision:l0});else v.push(d)}return{current:x,retained:v,skipped:f}}function _8(L,B){if(L.retained.length===0&&!B)return L.current;for(let{candidate:O,decision:C}of L.skipped)A8(O.quotaAccountId,C);return L.retained}async function I8(L,B){try{let O=Q9(L.headers);await O9(O,B.access,B.quotaAccountId,void 0,XY(L.headers))}catch{}}async function JU(L,B,O,C){for(let S of C){let x;try{x=await q9(L,B,S.access,S.accountId,S.keepwarmAccountKey,S.provenance)}catch(b){if(b instanceof DOMException&&b.name==="AbortError")throw b;if(B?.signal?.aborted)throw b;throw t0.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),b}if(!JY(x.status,O))return T0.markUsed(S.fallback),{response:x,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};await I8(x,S),x.body?.cancel().catch(()=>{})}return}async function QU(L,B,O,C,S){if(!VY(L,B))return{response:O};if(!S.length)return{response:O};let x=O,b;for(let v of S){let f;try{f=await q9(L,B,v.access,v.accountId,v.keepwarmAccountKey,v.provenance)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")throw l;if(B?.signal?.aborted)throw l;return t0.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:x,...b}}if(x.body?.cancel().catch(()=>{}),x=f,b={accessToken:v.access,accountId:v.quotaAccountId},!JY(f.status,C))return T0.markUsed(v.fallback),{response:f,...b};await I8(f,v)}return{response:x,...b}}if(I){let L=[];for(let B of I.accounts)if(N0(B))L.push(B);t.seedFallbacksFromAccounts(L)}if(!Z8)Z8=!0,LY(t,I).catch(()=>{}),E1(KY({respectBackoff:!0})).catch((L)=>E0.warn("boot quota seed failed",{pid:process.pid,error:t9(L)}));return q0.start(async()=>{let B=(await BQ(KY({readSidebarState:()=>a1(p0)}))).filter((O)=>!O.ok);if(B.length>0)E0.warn("background quota refresh completed with failures",{pid:process.pid,failures:B})},(L)=>{E0.warn("background quota refresh failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)})}),K=!0,{apiKey:xF,async fetch(L,B){let O=j4(L,B),C=q4(O),S=O.get("x-parent-session-id")?.trim()||void 0,x=await B0(),b=await D(),v=++D0;if(b.type!=="oauth")return O.delete(BX),fetch(L,{...B,headers:O});B=await YO(L,B);let f=T&&m1(x)==="claustrum",l="",d,K0=!1;if(f){let G0=await V8(x);if(G0===g1||G0===t1)K0=!0;else l=G0.token,d=G0.provenance==="local"?void 0:G0.provenance}else{if(!b.access||(b.expires??0)<Date.now()){WY.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(b.access),expiresInMs:b.expires?b.expires-Date.now():void 0});try{let G0=await HY();b.access=G0.access,b.refresh=G0.refresh,b.expires=G0.expires}catch(G0){if($8(G0))throw G0}}l=b.access??""}let I0=b.accountId??(l?z1(W1(l)??{}):void 0);if(v===D0)y1=I0;let H1=x?.routing?.mode??"main-first",D1,S0=await(()=>{return D1??=a1(p0),D1})();if(H1==="sticky-balanced"&&C&&VY(L,B)&&typeof B?.body==="string"){let G0=Buffer.byteLength(B.body,"utf8"),C0=await e4({storage:x,sidebarState:S0,primaryAccess:l,mainAccountIdentity:I0,mainCustodyRefused:K0,primaryProvenance:d}),M0=await jX({sessionId:C,requestBytes:G0,candidates:C0,now:Date.now()});if(M0){let g8=C8(M0)?{action:"migrate",reason:"exhausted"}:T8(M0,S0,void 0,Date.now(),x);if(g8.action==="migrate"){let y0=await jX({sessionId:C,requestBytes:G0,candidates:C0,excludeAccountIds:[M0.accountId],now:Date.now()});if(y0)t0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:M0.accountId,toAccountId:y0.accountId,reason:g8.reason}),M0=y0}let G1=await q9(L,B,M0.access,M0.wireAccountId,M0.keepwarmAccountKey,M0.provenance),y8=async(y0,f1)=>{try{let $U=Q9(y0.headers);await O9($U,f1.access,f1.accountId==="main"?void 0:f1.accountId,f1.accountId==="main"?f1.wireAccountId:void 0,XY(y0.headers))}catch{}};await y8(G1,M0);let f8=T8(M0,S0,G1.status,Date.now(),x);if((G1.status===401||G1.status===403||G1.status===429)&&f8.action==="migrate"){let y0=await jX({sessionId:C,requestBytes:G0,candidates:C0,excludeAccountIds:[M0.accountId],now:Date.now()});if(y0){t0.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(C),fromAccountId:M0.accountId,toAccountId:y0.accountId,reason:f8.reason});let f1=G1;G1=await q9(L,B,y0.access,y0.wireAccountId,y0.keepwarmAccountKey,y0.provenance),f1.body?.cancel().catch(()=>{}),M0=y0,await y8(G1,M0)}}if(M0.fallback&&!JY(G1.status,x))T0.markUsed(M0.fallback);return await P8(C,S,M0.accountId,H1,x?.accounts).catch(()=>{}),G1}}let k0=w8(t.peekMainForPolicy(I0),S0.main.quota,Date.now(),S0.main.mainAccountId,I0),Y9=QY(x)&&!$Y(a4(I0),x,void 0,Date.now()),NY=t.isRateLimited("main"),S8,qX=()=>{return S8??=XU(x,S0),S8},L1,X9,k8=!1,BY;if(H1==="fallback-first"&&VY(L,B)){k8=!0;let G0=await qX();BY=_8(G0,!Y9&&!NY&&!k0.exhausted);let C0=await JU(L,B,x,BY);if(C0)L1=C0.response,X9={accessToken:C0.accessToken,accountId:C0.quotaAccountId,activeId:C0.activeId}}if(!L1){let G0=k0.exhausted&&VY(L,B)&&(await qX()).retained.length>0;if(Y9||NY||G0){let C0=Y9?"killswitch":NY?"mid-stream-rate-limit":"quota-exhausted";if(C0==="quota-exhausted"&&k0.exhausted)A8("main",k0);t0.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:C0}),L1=t4(x,C0,C0==="quota-exhausted"&&k0.exhausted?k0.resetAtMs:NY?t.rateLimitedUntil("main"):void 0)}else L1=K0?new Response(null,{status:401}):await q9(L,B,l,I0,"main",d)}let x8=Boolean(X9),P9=L1,b8=X9?.accessToken??l,v8=X9?.accountId,h8=X9?.activeId??"main";if(!X9&&!k8&&JY(L1.status,x)){t0.debug("reactive fallback triggered",{pid:process.pid,status:L1.status}),BY??=_8(await qX(),!1);let G0=await QU(L,B,L1,x,BY),C0=G0.response;if(C0!==L1){if(x8=!0,P9=C0,b8=G0.accessToken??l,v8=G0.accountId,G0.accountId)h8=G0.accountId}}try{let G0=Q9(P9.headers);if(x8)await O9(G0,b8,v8,void 0,XY(P9.headers));else await O9(G0,l,void 0,I0,XY(P9.headers))}catch{}return await P8(C,S,h8,H1,x?.accounts).catch(()=>{}),P9}}},methods:c},"chat.headers":async(D,j)=>{if(D.model.providerID!=="openai")return;if(j.headers.originator="opencode",j.headers["User-Agent"]=`${M4(E9)} (${KX.platform()} ${KX.release()}; ${KX.arch()})`,j.headers["session-id"]=D.sessionID,K)j.headers[BX]=D.agent;if(W&&D.agent==="title")j.headers[b1.TITLE_HEADER]="true"},"chat.params":async(D,j)=>{if(D.model.providerID!=="openai")return;j.maxOutputTokens=void 0},config:async(D)=>{O0("commands").info("registering commands",{existing:Object.keys(D.command??{}).length,pid:process.pid}),D.command={...D.command??{},[M9]:{template:M9,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[w9]:{template:w9,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[A9]:{template:A9,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[R9]:{template:R9,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[T9]:{template:T9,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[C9]:{template:C9,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[_9]:{template:_9,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."},[I9]:{template:I9,description:"Spend one reset credit on an exhausted Codex account."}}},"command.execute.before":async(D)=>{if(O0("commands").info("command hook entered",{command:D.command,arguments:D.arguments,modal:S9.includes(D.command),hasCmdCtx:U!==null,pid:process.pid}),!S9.includes(D.command))return;if(!U)O0("commands").warn("command rejected: context not loaded",{command:D.command,pid:process.pid}),await u(D.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),F4();let j=D.command,M={...U,sessionId:D.sessionID,notify:(_)=>{dX(_,D.sessionID)}},T=await MX(j,D.arguments,M);if(O5(D.sessionID))dX(T,D.sessionID);else await u(D.sessionID,T.text);F4()}}}var zO=async(Y)=>{let X=r0();return WO(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},MM={id:"cortexkit-openai-auth",server:zO};export{q4 as resolveSidebarSessionId,W1 as parseJwtClaims,O4 as mergePushedQuotaMetadata,qM as getMainRefreshLockName,eF as findCachekeepFallbackAccount,z1 as extractAccountIdFromClaims,MM as default,uF as createResetTargetResolver,EM as buildSidebarState,u4 as buildSidebarMachineState,pF as buildResetRedemptionDeps,qF as __resetSweepFailureLogDedupeForTest,DM as __resetBootQuotaSeedForTest,J8 as __createCustodyRuntimeForTest,Z1 as ResetTargetResolutionError,zO as OpenAIAuthPlugin,Q8 as MAIN_REFRESH_LOCK_TTL_MS,gF as MAIN_REFRESH_LEASE_TTL_MS,SF as EMPTY_BEARER_MESSAGE,WO as CodexAuthPlugin,L8 as AuthPersistError};
1
+ import{Aa as u,Ba as v,Ca as w,Da as x,Ea as y,Fa as z,Ga as A,Ha as B,Ia as C,Ja as D,Ka as E,e as a,f as b,ia as c,ja as d,ka as e,la as f,ma as g,na as h,oa as i,pa as j,qa as k,ra as l,sa as m,ta as n,ua as o,va as p,wa as q,xa as r,ya as s,za as t}from"./index-8rqfbhfw.js";import"./index-eqh53k8v.js";import"./index-jyr8y8k4.js";import"./index-rv08jmd4.js";import"./index-8kj7sa1p.js";import"./index-bmd7x5aq.js";import"./index-766sfrh5.js";import"./index-b3q3j39x.js";export{B as rewriteResponsesLiteBody,z as resolveSidebarSessionId,a as parseJwtClaims,w as mergePushedQuotaMetadata,k as getMainRefreshLockName,v as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,E as default,r as createResetTargetResolver,e as codexOAuthModelListed,f as codexOAuthModelLimit,y as buildSidebarState,x as buildSidebarMachineState,s as buildResetRedemptionDeps,o as __resetBootQuotaSeedForTest,t as __menuContextForTest,n as __bootQuotaSeedPromiseForTest,q as ResetTargetResolutionError,h as RESPONSES_LITE_MODELS,u as POOL_MIGRATION_ENABLED,D as OpenAIAuthPlugin,A as MID_CONVERSATION_EFFORT_MODELS,l as MAIN_REFRESH_LOCK_TTL_MS,m as MAIN_REFRESH_LEASE_TTL_MS,g as EMPTY_BEARER_MESSAGE,d as DISALLOWED_MODELS,C as CodexAuthPlugin,i as CODEX_VERSION,j as CODEX_USER_AGENT,p as AuthPersistError,c as ALLOWED_MODELS};