@cortexkit/opencode-openai-auth 0.11.0 → 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 x4,B as b4,C as v4,D as h4,c as k9,e as kX,h as GY,i as _4,j as YY,m as a1,q as oQ,r as I4,s as S4,t as k4,y as $8,z as LX}from"./index-g3hsdjh4.js";import{I as B5,J as F5}from"./index-4effjmr6.js";import{$ as JQ,$a as A9,Aa as m8,Ba as t9,Ca as HX,Da as RY,Ea as L1,Fa as w4,Ga as TY,Ha as O0,Ia as A4,Ja as c1,Ka as d8,L as J4,La as w0,M as Q4,Ma as m1,N as $4,Na as ZX,O as l8,Oa as P0,P as j4,Pa as JY,Q as q4,Qa as QY,R as EY,Ra as Q8,S as D4,Sa as $Y,T as wQ,Ta as R4,U as A0,Ua as T4,V as f0,Va as v1,W as CY,Wa as M1,X as yX,Xa as C4,Y as eQ,Ya as i,Z as j0,Za as M9,_ as P4,_a as w9,aa as QQ,ab as R9,ba as W1,bb as T9,ca as z1,cb as C9,da as J9,db as _9,ea as $Q,eb as I9,fa as GQ,fb as S9,ga as WQ,gb as qX,ha as zQ,hb as E1,ia as KQ,ja as UQ,ka as HQ,la as AY,ma as $9,na as g1,oa as t1,pa as E4,qa as V1,ra as b0,sa as G4,ta as sJ,ua as WX,va as J8,wa as W4,xa as M4,ya as aJ,za as f8}from"./index-sq36b120.js";import{kb as g4}from"./index-jwn4r3sw.js";import{mb as Q9,nb as XY,ob as bK}from"./index-hh52v8sb.js";import{sb as nX}from"./index-9ehhb051.js";import{mkdirSync as EF,readFileSync as y4,renameSync as MF,statSync as wF,writeFileSync as AF}from"node:fs";import zX from"node:os";import{join as G8}from"node:path";import{execFileSync as MU}from"node:child_process";import{readFileSync as QU}from"node:fs";import{homedir as $U,tmpdir as GU}from"node:os";import{join as OY}from"node:path";var WU="https://chatgpt.com/backend-api/codex/responses",zU="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 jY(){let Y=process.env[P1.configDir]?.trim();if(Y)return Y;return OY(process.env.XDG_CONFIG_HOME||OY($U(),".config"),"opencode")}function t(){return process.env[P1.configFile]?.trim()||OY(jY(),zU)}function KU(){try{let Y=JSON.parse(QU(t(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function UU(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 BY(Y,X,J){let Q=UU(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function HU(){let Y=KU(),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:BY(P1.webSockets,Y.webSockets,!1),rawWebSocket:BY(P1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:BY(P1.responsesLite,Y.responsesLite,!1),dump:BY(P1.dump,X,!1),dumpDir:process.env[P1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():OY(GU(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[P1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():WU)}}var FY;function s0(){if(!FY)FY=HU();return FY}function OX(){return FY=void 0,s0()}import{realpathSync as g8}from"node:fs";import{homedir as ZU}from"node:os";import{basename as LU,dirname as VU,join as DY,resolve as c8}from"node:path";function NU(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return DY(process.env.XDG_CONFIG_HOME||DY(ZU(),".config"),"opencode")}function u8(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||DY(NU(),f8)}function qY(Y,X){let J=c8(Y);return X==="win32"||X==="darwin"?J.toLowerCase():J}function y8(Y){try{return g8.native(Y)}catch{try{return DY(g8.native(VU(Y)),LU(Y))}catch{return}}}function BU(Y,X,J=process.platform){if(qY(Y,J)===qY(X,J))return!0;let Q=y8(Y),$=y8(X);return Q!==void 0&&$!==void 0&&qY(Q,J)===qY($,J)}function PY(Y=u8()){let X=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(X){if(BU(Y,X))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${c8(Y)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return X}return m8(Y)}function r(Y=u8()){return{configPath:Y,statePath:PY(Y)}}var E9="0.11.0";import{readFile as FU}from"node:fs/promises";function p8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function i8(Y){let X=await d8(Y.configPath),J=[];try{let $=JSON.parse(await FU(Y.statePath,"utf8"));if(p8($)){let G=$.accounts;if(p8(G))J=Object.keys(G)}}catch($){if($.code!=="ENOENT")throw $}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter(($)=>!X.has($)):[]}}function jX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&O0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>O0(J)&&J.accountId===Y.mainAccountId)}function OU(Y,X){let J=Y.lastRefreshError;return EY(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=l8}function n8(Y){let X=[],J=[],Q=Y.now??Date.now(),$=jX(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 H={type:"restore-main-credential"};J.push(H);let U=X.find((Z)=>Z.code==="auth-slot-missing"||Z.code==="auth-slot-not-oauth"||Z.code==="main-refresh-not-in-store");if(U)U.repair=H}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((H)=>H.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let H of W){if(!O0(H))continue;if(!OU(H,Q))continue;let U={type:"clear-refresh-backoff",accountId:H.id};J.push(U),X.push({code:"armed-non-transient-refresh-backoff",accountId:H.id,message:`Account ${H.id} has an armed non-transient refresh backoff.`,repair:U})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let H={type:"prune-orphan-state-ids",ids:K};J.push(H),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:H})}return{findings:X,repairs:J}}function o8(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 e={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 r8(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 s8(){return Boolean(process.stdin.isTTY)}var jU=50,a8=`${String.fromCharCode(27)}\\[[0-9;]*m`,qU=new RegExp(a8,"g"),DU=new RegExp(`^${a8}`);function PU(Y){return Y.replace(qU,"")}function MY(Y,X){if(X<=0)return"";if(PU(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(DU);if(K){$+=K[0],G+=K[0].length;continue}}$+=Y[G],G+=1,W+=1}return $.includes("\x1B[")?`${$}${e.reset}${J}`:$+J}function EU(Y){if(Y==="red")return e.red;if(Y==="cyan")return e.cyan;return""}async function wY(Y,X){if(!s8())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,H=()=>{let U=Q.columns??80,Z=Q.rows??24,F=K;if(X.clearScreen)Q.write(e.clearScreen+e.moveTo(1,1));else if(F>0)Q.write(e.up(F));let N=0,V=(E)=>{Q.write(`${e.clearLine}${E}
5
- `),N+=1},q=X.subtitle?3:0,R=Math.max(1,Math.min(Y.length,Z-(1+q+2)-1)),k=Math.max(0,Math.min($-Math.floor(R/2),Math.max(0,Y.length-R))),u=Y.slice(k,k+R);if(V(`${e.dim}┌ ${e.reset}${MY(X.message,Math.max(1,U-4))}`),X.subtitle)V(`${e.dim}│${e.reset}`),V(`${e.cyan}◆${e.reset} ${MY(X.subtitle,Math.max(1,U-4))}`),V("");for(let E=0;E<u.length;E++){let S=u[E];if(!S)continue;let c=k+E===$,o=EU(S.color),J0=o?`${c?"":e.dim}${o}${S.label}${e.reset}`:c?S.label:`${e.dim}${S.label}${e.reset}`;J0=MY(J0,Math.max(1,U-8)),V(c?`${e.cyan}│${e.reset} ${e.green}●${e.reset} ${J0}`:`${e.cyan}│${e.reset} ${e.dim}○${e.reset} ${J0}`)}let C=u.length<Y.length?` (${k+1}-${k+u.length}/${Y.length})`:"";V(`${e.cyan}│${e.reset} ${e.dim}${MY(`Up/Down to select | Enter: confirm | Esc: back${C}`,Math.max(1,U-6))}${e.reset}`),V(`${e.cyan}└${e.reset}`);for(let E=N;E<F;E++)V("");K=N};return new Promise((U)=>{let Z=J.isRaw??!1,F=()=>{if(W)return;if(W=!0,G)clearTimeout(G);J.removeListener("data",q);try{J.setRawMode(Z),J.pause(),Q.write(e.show)}catch{}process.removeListener("SIGINT",V),process.removeListener("SIGTERM",V)},N=(R)=>{F(),U(R)},V=()=>N(null),q=(R)=>{if(G)clearTimeout(G),G=null;switch(r8(R)){case"up":$=($-1+Y.length)%Y.length,H();break;case"down":$=($+1)%Y.length,H();break;case"enter":N(Y[$]?.value??null);break;case"escape":N(null);break;case"escape-start":G=setTimeout(()=>N(null),jU);break}};process.once("SIGINT",V),process.once("SIGTERM",V);try{J.setRawMode(!0)}catch{F(),U(null);return}J.resume(),Q.write(e.hide),H(),J.on("data",q)})}var t8=[{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"}],MO=t8.map((Y)=>Y.label);async function e8(){return await wY(t8,{message:"OpenAI accounts",subtitle:"Select an account action",clearScreen:!0})??"cancel"}async function YQ(Y,X=!1){return await wY(X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Y})??!1}function wU(Y,X=process.platform,J=MU){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 AU(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}async function RU(){let{redirectUri:Y}=await WQ(),X=await QQ(),J=JQ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=$Q(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{GQ(J)}}}}async function TU(Y){let{deviceData:X,url:J,instructions:Q}=await KQ(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let $=await UQ(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 XQ(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 ZQ({client:Y,getAuth:X,getPaths:J=()=>r(t()),fetchImpl:Q=fetch,packageVersion:$=E9,dependencies:G}){let W={authorizeBrowser:G?.authorizeBrowser??RU,authorizeHeadless:G?.authorizeHeadless??(()=>TU($)),beginAccountLogin:G?.beginAccountLogin??AY,loadAccounts:G?.loadAccounts??w0,mutateAccounts:G?.mutateAccounts??P0,refreshAllQuota:G?.refreshAllQuota??E1,showAuthMenu:G?.showAuthMenu??e8,confirm:G?.confirm??YQ,readStoreIds:G?.readStoreIds??i8,openBrowser:G?.openBrowser??wU,now:G?.now??Date.now,custodyQuotaDeps:G?.custodyQuotaDeps??{}},K=async()=>await X?.().catch(()=>{return})??{type:"missing"},H=async()=>{if((await K()).type!=="missing")return!0;return((await W.loadAccounts(J()))?.accounts.length??0)>0},U=async(C)=>{await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...C}})},Z=async()=>{let C=new AbortController,E=await W.beginAccountLogin({version:$,signal:C.signal});E.completion.catch(()=>{}),XQ(E);let S=!1;try{S=await W.openBrowser(E.url)!==!1}catch{S=!1}if(!S)C.abort(),console.log(`Could not open a browser. Switching to device authorization.
10
- `),E=await W.beginAccountLogin({version:$,headless:!0}),XQ(E);return E.completion},F=async()=>{let C=await W.loadAccounts(J());if(m1(C)==="claustrum"){console.log("That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.");return}let E=await Z(),S=!1;if(await W.mutateAccounts((c)=>{if(E.accountId&&c.mainAccountId&&E.accountId===c.mainAccountId)return S=!0,c;return HQ(c.accounts,E),c},J()),S){console.log("That account is already the OpenCode main credential.");return}console.log(`Added fallback account ${E.id}.`)},N=async()=>{let C=await Z();await U({refresh:C.refresh,access:C.access??"",expires:C.expires??0}),console.log("Updated the OpenCode main credential.")},V=async()=>{let C=J(),E=await W.loadAccounts(C),S=new TY({storage:E,configPath:C.configPath,fetchImpl:Q,now:W.now}),c={refreshAccount:async(K0)=>K0},o=async()=>{throw Error("No usable main access token for quota check")},J0=async(K0)=>{let B0=await W.loadAccounts(K0);if(!B0)return null;return{...B0,accounts:B0.accounts.map((u0)=>O0(u0)?{...u0,lastRefreshError:void 0}:{...u0})}},L0=await W.refreshAllQuota({getAuth:K,codexRefreshFn:o,refreshMainWithLease:o,fallbackManager:c,quotaManager:S,loadAccounts:J0,writeSidebarState:async()=>{},client:{auth:{set:async()=>{throw Error("Quota checks cannot write credentials")}}},fetchImpl:Q,now:W.now,paths:C,storageMainAccountId:E?.mainAccountId,isOAuthAccountFn:O0,whamFn:RY,respectBackoff:!1,readSidebarState:async()=>({main:{},fallbacks:[]}),...W.custodyQuotaDeps});CU(L0)},q=async()=>{let C=J(),[E,S,c]=await Promise.all([W.loadAccounts(C),W.readStoreIds(C),K()]),o=n8({auth:c.type==="missing"?void 0:c,storage:E,orphanStateIds:S.orphanStateIds,now:W.now()});return console.log(o8(o)),o},R=async()=>{let C=await q();if(C.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 S of C.repairs){if(S.type==="restore-main-credential"){let c=await W.loadAccounts(E),o=jX(c);if(!o)continue;await U({refresh:o.refresh,access:o.access??"",expires:o.expires??0});continue}if(S.type==="prune-orphan-state-ids"){await W.mutateAccounts((c)=>c,E);continue}await W.mutateAccounts((c)=>{let o=c.accounts.find((J0)=>J0.id===S.accountId&&O0(J0));if(o)o.lastRefreshError=void 0;return c},E)}console.log(`Applied ${C.repairs.length} auth repair(s).`)},k=async()=>{if(!await W.confirm("Delete all fallback accounts?")){console.log("Delete cancelled.");return}let C=[];await W.mutateAccounts((E,S)=>{let c=new Set([...S?.rawRosterIds??[],...E.accounts.map((o)=>o.id)].filter((o)=>o!=="main"));return C.splice(0,C.length,...c),E.accounts=E.accounts.filter((o)=>o.id==="main"),E},J(),{allowDrop:C}),console.log("Deleted all fallback accounts.")},u=async(C)=>{switch(C){case"add-account":await F();break;case"auth-current":await N();break;case"check-quotas":await V();break;case"auth-doctor":await q();break;case"apply-repairs":await R();break;case"delete-all":await k();break;case"cancel":break}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async(C)=>{if(C&&await H())return await u(await W.showAuthMenu()),AU();return W.authorizeBrowser()}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:W.authorizeHeadless},{label:"Manually enter API Key",type:"api"}]}function CU(Y){for(let X of Y)console.log(X.ok?`${X.account}: quota refreshed`:`${X.account}: ${X.error??"quota refresh failed"}`)}var a0=j0("commands");function x0(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}async function SU(Y,X){let J=await X.loadAccounts(x0(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 H=Q.main??{},U=H.primary??H["5h"]??c1.primary,Z=H.secondary??H["1w"]??c1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${Z}% |`);for(let F of $){let N=Q.accounts?.[F]??Q.main??{},V=N.primary??N["5h"]??c1.primary,q=N.secondary??N["1w"]??c1.secondary;K.push(`| ${F} | ≥ ${V}% | ≥ ${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},x0(X)),a0.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},x0(X)),a0.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 H=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,U,Z,F]=H,N={primary:Number.parseInt(Z,10),secondary:Number.parseInt(F,10)};if(U==="main")W.main=N;else if(U==="all"){W.main=N;for(let V of $)W.accounts[V]=N}else W.accounts[U]=N}return await P0((K)=>{return K.killswitch=W,K},x0(X)),a0.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 kU(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=s0(),$=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},x0(X));let G=OX();return a0.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},x0(X)),OX(),a0.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 xU(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(x0(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 CY(G),await P0((W)=>{return W.logging={...W.logging??{},level:G},W},x0(X)),a0.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 bU(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 vU(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(x0(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(),H=K.window,U=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",Z=["## 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(Z.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){Z.push("");for(let N of K.targets){let V=N.sessionKey.length>12?`${N.sessionKey.slice(0,12)}…`:N.sessionKey,q=Math.ceil((N.cacheExpiresAt-K.generatedAt)/1000);Z.push(`- \`${V}\` (${N.accountId??"main"}) — expires in ${q}s`+(N.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-N.lastWarmedAt)/1000)}s ago`:"")+(N.backoffUntil&&N.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((N.backoffUntil-K.generatedAt)/1000)}s`:""))}}Z.push(""),Z.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),Z.push(""),Z.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((N)=>N.lastWarmedAt??0));return{command:"openai-cachekeep",text:Z.join(`
33
- `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:H,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},x0(X)),a0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),H=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:H||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},x0(X)),a0.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 H=K==="on";await P0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},sustain:H},Z},x0(X)),a0.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let U=J?.status();return{command:"openai-cachekeep",text:H?`## 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:H,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 H=K==="on";await P0((Z)=>{return Z.cachekeep={...Z.cachekeep??{},subagents:H},Z},x0(X)),a0.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
44
-
45
- Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:G,subagents:H,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},x0(X)),X.setCacheKeepWindow?.(void 0),a0.info("cachekeep window cleared");let H=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:H?.sustain??$?.cachekeep?.sustain===!0,window:void 0,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 window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=bU(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
48
-
49
- ${K.reason}`,knobs:{}};let{startHour:H,endHour:U}=K;await P0((N)=>{return N.cachekeep={...N.cachekeep??{},startHour:H,endHour:U},N},x0(X)),X.setCacheKeepWindow?.({startHour:H,endHour:U}),a0.info("cachekeep window set",{startHour:H,endHour:U});let Z=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
50
-
51
- Warming limited to **${`${String(H).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:Z?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:H,endHour:U},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`, `/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 hU={"openai-killswitch":SU,"openai-dump":kU,"openai-logging":xU,"openai-cachekeep":vU};function DX(Y,X,J){return qX(Y,X,J,hU)}var gU=300000,yU=30000,fU=240000,mU="bg-quota-refresh",cU=120000;function uU(Y,X){return L1({name:mU,ttlMs:cU,path:Y,renew:!0,...X})}function LQ(Y,X=E1,J=()=>uU(Y.paths.configPath)){return pU(Y,X,J)}async function pU(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:fU})}finally{await Q?.release().catch(()=>{})}}class PX{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)*yU);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=$},gU+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 EX(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 MX(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 _Y(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"),EX(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:MX(Y.body)}}function OQ(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 jQ(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 VQ(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 lU=300000,qQ=1800000,NQ=2*qQ+900000,dU=3600000,BQ=1800000,FQ=60000,iU=32,nU=8388608,wX=600000;function DQ(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 oU(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 rU(Y,X){return DQ(Y)?qQ:X}function AX(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function PQ(Y){if(!Y||typeof Y!=="object")return AX();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 sU(Y){try{let X=JSON.parse(Y);return PQ(X.usage)}catch{return AX()}}function aU(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),H=K.type??W;if(H!=="response.completed"&&H!=="response.done")return;let U=K.response;Q=PQ(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??AX()}class RX{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??lU,this.tickIntervalMs=Y.tickIntervalMs??FQ,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:dU;let J=Y.maxSubagentIdleMs??BQ;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:BQ,this.tickIntervalMs=Y.tickIntervalMs??FQ,this.maxTargets=Y.maxTargets??iU,this.maxBytes=Y.maxBytes??nU,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&&!VQ(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 Z=this.targets.get(Y);if(Z)this.totalBytes-=Z.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 Z,F=Number.POSITIVE_INFINITY;for(let[V,q]of this.targets){let R=Math.max(q.lastRealRequestAt,q.lastWarmedAt??0);if(R<F)Z=V,F=R}if(Z===void 0)break;let N=this.targets.get(Z);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Z)}let H=rU(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:H,cacheExpiresAt:this.now()+H,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:DQ(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-NQ;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=NQ;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&&!VQ(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()+wX;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=oU(X.bodyText),W;try{let k=JSON.parse(G);W={warmBodyKeys:Object.keys(k),stream:k.stream,max_output_tokens:k.max_output_tokens,store:k.store,has_stream_options:"stream_options"in k,has_max_tokens:"max_tokens"in k,model:k.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...W,headerKeys:Object.keys($),hasChatGptAccountId:"ChatGPT-Account-Id"in $}));let K=_Y({method:"POST",headers:$,body:G,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),H=await this.fetchImpl(this.codexResponsesUrl,K),U="";try{U=await H.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!H.ok){if(X.backoffUntil=this.now()+wX,H.status===401)await Q?.(H.status);this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:H.status,error:`HTTP ${H.status}`,responseBody:U.slice(0,600)}));return}let Z=H.headers.get("content-type")??"",F=Z.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(U.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:H.status,contentType:Z,bodyLen:U.length,isSse:F}));let N=F?aU(U):sU(U),V=Q9(H.headers),q=V.primary?.usedPercent??null,R=V.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:N.input_tokens,cached_tokens:N.cached_tokens,hit_rate:N.hit_rate,output_tokens:N.output_tokens,quota_primary_pct:q,quota_secondary_pct:R})),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()+wX,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:G instanceof Error?G.message:String(G)}))}}}import{createHash as YH}from"node:crypto";import{isAbsolute as tU,join as EQ}from"node:path";var eU=j0("custody"),MQ=new Set;function TX(Y=process.env){let X=Y.CLAUSTRUM_OPENCODE_HANDLES;if(X&&tU(X))return X;if(X&&!MQ.has(X))MQ.add(X),eU.warn("ignoring non-absolute CLAUSTRUM_OPENCODE_HANDLES",{configuredPath:X});let J=Y.XDG_CONFIG_HOME||(Y.HOME?EQ(Y.HOME,".config"):".config");return EQ(J,"cortexkit","opencode-handles.json")}function e0(Y=TX(),X={}){return wQ(Y,X)}var CX="openai",AQ=250,IQ=new Set;function SQ(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 YH("sha256").update(Q(X)).update(X).update(Q(J)).update(J).digest("hex")}function kQ(Y){let X=SQ(Y);if(X)IQ.add(X)}function XH(Y){let X=SQ(Y);return X!==void 0&&IQ.has(X)}function xQ(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 SY(Y){let X=xQ(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 IY(Y){let X=xQ(Y);if(!X)return{kind:"indeterminate"};if(!b0({id:"main",type:"oauth",access:X.access??"",refresh:X.refresh??"",expires:X.expires??0,addedAt:0},CX))return{kind:"real",oauth:X};let J=V1(CX);if(X.access===J.access&&X.expires===J.expires)return{kind:"tombstone",oauth:X};return{kind:"empty",oauth:X}}async function RQ(Y){if(!Y.auth.get)return;return Y.auth.get({path:{id:CX}})}async function TQ(Y){if(!Y.auth.all)return!1;return Object.keys(await Y.auth.all()).length>0}async function JH(Y){let X=await RQ(Y.client);if(X!==void 0)return IY(X);let J=await TQ(Y.client),Q=Y.now();if(await Y.sleep(AQ),Y.now()-Q<AQ)return{kind:"indeterminate"};let $=await RQ(Y.client);if($!==void 0)return IY($);let G=await TQ(Y.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function QH(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 CQ(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 _Q(Y){return Y.kind==="real"&&XH(Y.oauth)}async function bQ(Y){let X=await JH(Y);if(X.kind==="indeterminate")return;let J=QH(Y.manifest);if(X.kind==="slot-absent"){let $=await CQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:_Q(X),vault:()=>$==="no_handle"||$==="identity_mismatch"?$:"serves"})}let Q=await CQ(Y);return k9({mode:Y.mode,manifest:J,local:X.kind,verifiedInProcessLogin:_Q(X),vault:()=>Q})}import{createHash as $H}from"node:crypto";var cQ="claustrum-mode",u1="main-refresh",vQ=Promise.resolve();async function IX(){let Y,X=new Promise(($)=>{Y=$}),J=vQ;vQ=J.then(()=>X),await J;let Q=!1;return{async release(){if(Q)return;Q=!0,Y()}}}async function uQ(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 hQ(Y){return Y.accounts.filter((X)=>O0(X)&&X.enabled!==!1)}function _X(Y,X){return Y<X?-1:Y>X?1:0}function gQ(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)=>_X(J.id,Q.id))}function GH(Y){return Y.kind==="main"?u1:M1(Y.id)}function yQ(Y){return Y.access?$9(Y.access,Y.refresh):void 0}function fQ(Y){return Object.values(Y).some((X)=>X==="new-local-family-under-claustrum"||X==="torn-read-deferred"||X.startsWith("aborted:"))}async function pQ(Y){let X=await IX(),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:cQ,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=gQ(Y.accountIds);Y.warn?.(`transition participants: ${K.map((H)=>H.id).join(",")}`);for(let H of K){let U=await Y.acquireLock({name:GH(H),renew:!0});if(!U)return{status:"aborted",outcomes:Q,reason:`account-lock-unavailable:${H.id}`};J.push(U)}return await Y.withStoreTransaction(async(H)=>{let U=await H.read(),Z=gQ(Y.accountIds,U),F=hQ(U).map((E)=>E.id).sort(_X),N=[...Y.accountIds].sort(_X);if(F.length!==N.length||F.some((E,S)=>E!==N[S]))return{status:"aborted",outcomes:Q,reason:"account-roster-changed"};let V=await Y.readManifest();if(!V.ok)return{status:"aborted",outcomes:Q,reason:`manifest-${V.reason}`};let q=f0(V),R=U.claustrum?.mode==="claustrum"?U.claustrum?.transition:void 0,k=R?R.fingerprints:{fallbacks:{}},u=R?.storeGeneration??mQ(U);if(!R){Y.warn?.(`capturing main slot fingerprint; auth.get is ${typeof Y.auth?.get}`);let E=SY(await Y.auth.get({path:{id:"openai"}}));if(Y.warn?.(`main slot captured: ${E?"complete":"absent"}`),E)k.main=$9(E.access,E.refresh);for(let S of hQ(U)){let c=yQ(S);if(c)k.fallbacks[S.id]=c}}await G("captured"),Y.warn?.(`handles resolved: isMap=${q instanceof Map} size=${q instanceof Map?q.size:"n/a"}`);for(let E of Z){let S=q.get(E.id);if(Y.warn?.(`participant ${E.id}: handle=${S?"yes":"NO"}`),!S){Q[E.id]="no-handle";continue}let c=await Y.preflight({id:E.id,accountId:E.accountId,handle:S});Q[E.id]=c}if(await G("preflight"),Object.values(Q).some((E)=>E!=="ready"))return{status:"aborted",outcomes:Q,reason:"preflight-failed"};if(!R){let E=await Y.readManifest(),S=await H.read();if(!E.ok||E.revision!==V.revision)return{status:"aborted",outcomes:Q,reason:"manifest-revision-changed"};if(mQ(S)!==u)return{status:"aborted",outcomes:Q,reason:"store-generation-changed"};await G("revalidated"),await H.writeMode("claustrum",{manifestRevision:V.revision,storeGeneration:u,fingerprints:k}),await G("mode-written")}let C=!1;for(let E of K){if(E.kind==="main")continue;let S=await H.read(),c=S.accounts.find((K0)=>K0.id===E.id&&K0.type==="oauth");if(c&&b0(c,"openai")){Q[E.id]="tombstoned";continue}let o=k.fallbacks[E.id];if(!c||!o||yQ(c)!==o){Q[E.id]="new-local-family-under-claustrum";continue}let J0=structuredClone(S),L0=J0.accounts.find((K0)=>K0.id===E.id&&K0.type==="oauth");if(!L0){Q[E.id]="new-local-family-under-claustrum";continue}Object.assign(L0,V1("openai"));try{await H.write(J0);let K0=(await H.read()).accounts.find((B0)=>B0.id===E.id&&B0.type==="oauth");Q[E.id]=K0&&b0(K0,"openai")?"tombstoned":"aborted:post-write-readback"}catch{Q[E.id]="aborted:write-failed",C=!0;break}}if(C)return await G("material-written"),{status:"incomplete",outcomes:Q};if(Q.main=k.main?await SX(k.main,{auth:Y.auth,warn:(E)=>{if($)return;$=!0,Y.warn?.(E)}}):"new-local-family-under-claustrum",await G("material-written"),!fQ(Q))await H.writeMode("claustrum");return{status:fQ(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 SX(Y,X){let J=SY(await X.auth.get({path:{id:"openai"}}));if(J&&b0({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 $=V1("openai");await X.auth.set.bind(X.auth)({path:{id:"openai"},body:$});let W=SY(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 lQ(Y){let X=await Y.acquireLock({name:cQ,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 mQ(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 $H("sha256").update(JSON.stringify(X)).digest("hex")}var rQ=900000,WH=0.016666666666666666,dQ=0.000001;function xX(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function bX(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=xX(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>rQ)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=kX(Y.quota).sort(($,G)=>{let W=$.windowMs,K=G.windowMs,H=typeof W==="number"&&Number.isFinite(W),U=typeof K==="number"&&Number.isFinite(K);if(H!==U)return H?-1:1;if(H&&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=oQ(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 iQ(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,WH);return Q/G}function nQ(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function zH(Y,X){if(!Y.quota)return;let J=xX(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>rQ)return;let Q=kX(Y.quota).map(({key:W,window:K})=>{return iQ(K,Y.reservePercent[W]??0,X)}),$=Y.quota.spendControl;if($&&Number.isFinite($.remainingPercent))Q.push(iQ($,0,X));let G=Q.length>0?Math.min(...Q):0;return G>0?{candidate:Y,quotaCheckedAt:J,weight:G}:void 0}function sQ(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(($)=>zH($,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,dQ),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,dQ);return K-H||G.candidate.configuredOrder-W.candidate.configuredOrder||nQ(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||nQ($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:xX(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as KH}from"node:crypto";import{chmod as UH,mkdir as HH,readdir as ZH,readFile as LH,writeFile as vX}from"node:fs/promises";import{join as Y5}from"node:path";var fX=j0("dump"),w1="x-cortexkit-openai-auth-dump-session",VH=["http","prewarm","main"],aQ=0,G9=new Map,NH=100;function hX(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X5(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 J5(Y){return KH("sha256").update(Y).digest("hex")}function gX(Y){return J5(JSON.stringify(Y))}function Q5(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function BH(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 FH(Y,X){if(!G9.has(Y))while(G9.size>=NH){let J=G9.keys().next().value;if(J===void 0)break;G9.delete(J)}G9.set(Y,X)}var tQ=new Set;async function OH(Y,X,J){let Q=X5(X),$=VH.map((G)=>`-${Q}-${J}-${G}.body.json`);try{let W=(await ZH(Y)).filter((K)=>$.some((H)=>K.endsWith(H))).sort().pop();if(!W)return;return await LH(Y5(Y,W),"utf8")}catch{return}}function jH(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function mX(Y){if(Array.isArray(Y))return Y.map(mX);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]=mX(Q)}return X}function qH(Y){let X=Q5(Y);if(X===void 0)return Y;let J=DH(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function DH(Y){if(!i(Y))return yX(Y);let X={};for(let[J,Q]of Object.entries(Y))X[J]=J==="tools"?eQ(Q):yX({[J]:Q})[J];return X}function PH(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function EH(Y){let X=Q5(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(PH),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:gX(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:gX(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:gX(Q),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function W9(Y){let X=s0();if(!X.dump)return;aQ++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${process.pid}-${String(aQ).padStart(5,"0")}-${X5(J)}-${Y.transport}-${Y.phase}`,$=Y5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=G9.get(W),H=K?"memory":void 0;if(K===void 0&&!tQ.has(W)){if(tQ.add(W),K=await OH(X.dumpDir,J,Y.transport),K!==void 0)H="disk"}try{await HH(X.dumpDir,{recursive:!0,mode:448}),await UH(X.dumpDir,448).catch(()=>{});let U=qH(Y.bodyText),Z={id:Q,createdAt:new Date().toISOString(),session:hX(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:J5(Y.bodyText),diff:BH(K,U),baselineSource:H,body:EH(Y.bodyText),files:G};await Promise.all([vX(G.body,U,{encoding:"utf8",mode:384}),vX(G.metadata,`${JSON.stringify(Z,null,2)}
53
- `,{encoding:"utf8",mode:384}),vX(G.request,`${JSON.stringify(mX({url:Y.url,method:Y.method,accountId:Y.accountId,headers:jH(Y.headers)}),null,2)}
54
- `,{encoding:"utf8",mode:384})]),fX.debug("dumped request",{id:Q,session:hX(J),body:G.body,meta:G.metadata}),FH(W,U)}catch(U){fX.warn("request dump failed",{session:hX(J),error:U instanceof Error?U.message:String(U)})}}async function p1(Y){if(!s0().dump)return;fX.debug("diagnostic",Y)}import{readFile as MH}from"node:fs/promises";import{homedir as wH}from"node:os";import{join as $5}from"node:path";var AH="https://models.dev/api.json",RH="OPENCODE_OPENAI_AUTH_MODELS_CACHE",TH="OPENCODE_MODELS_PATH",CH="OPENCODE_DISABLE_MODELS_FETCH",_H=1e4,IH=300000;function A1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function G5(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function cX(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=G5(Y.cache_read),$=G5(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function SH(Y){let X=A1(Y);if(!X)return null;let J=cX(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let H=A1(K);if(!H)continue;let U=A1(H.tier),Z=U?.size;if(U?.type!=="context")continue;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=0)continue;let F=cX(H);if(!F)continue;W.push({...F,tier:{type:"context",size:Z}})}if(W.length>0)Q.tiers=W}let $=A1(X.context_over_200k),G=$?cX($):null;if(G)Q.experimentalOver200K=G;return Q}function W5(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),H=SH(K?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function kH(){let Y=process.env[RH]?.trim();if(Y)return Y;let X=process.env[TH]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||$5(wH(),".cache");return $5(J,"opencode","models.json")}function xH(){let Y=process.env[CH]?.toLowerCase();return Y==="true"||Y==="1"}async function bH(){try{let Y=W5(JSON.parse(await MH(kH(),"utf8")));if(Y)return Y}catch{}if(xH())return null;try{let Y=await fetch(AH,{signal:AbortSignal.timeout(_H)});if(!Y.ok)return null;return W5(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+IH,promise:bH()};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 vH(Y){if(Array.isArray(Y))return Y;if(K9(Y)&&Array.isArray(Y.data))return Y.data;return[]}function hH(Y){if(!K9(Y)||!K9(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function K5(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 U5(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function H5(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function Z5(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=vH(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(hH(Q[G])!=="assistant")continue;let W=K5(Q[G]);if(!W)continue;if($=U5($,W),H5($))return $}for(let G=Q.length-1;G>=0;G--){let W=K5(Q[G]);if(!W)continue;if($=U5($,W),H5($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var R1=[],gH=1,L5=new Map;function uX(Y,X){if(R1.push({id:gH++,type:"open-dialog",payload:Y,sessionId:X}),R1.length>100)R1=R1.slice(R1.length-100)}function V5(Y=0,X){let J=Date.now();if(X!==void 0)L5.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 N5(Y){let X=Date.now(),J=L5.get(Y)??0;return J>0&&X-J<3000}import{randomBytes as yH,timingSafeEqual as fH}from"node:crypto";import{readFile as mH,unlink as cH}from"node:fs/promises";import{createServer as uH}from"node:http";import{join as pH}from"node:path";var pX=j0("rpc");function lH(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 dH(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&fH(J,Q)}async function O5(Y){let X=yH(32).toString("hex"),J=Y.timeoutMs??90000,Q=Y.receiptTimeoutMs??2000,$=!1,G=uH((H,U)=>{H.setTimeout(J,()=>{H.socket.destroy()}),W(H,U)});G.requestTimeout=Q,G.headersTimeout=Q;async function W(H,U){let Z=(F,N)=>{if(U.headersSent||U.writableEnded||U.destroyed)return;U.writeHead(F,{"content-type":"application/json"}),U.end(JSON.stringify(N))};try{let F=H.url??"";if(H.method==="GET"&&F==="/health")return Z(200,{ok:!0});if(H.method!=="POST"||!F.startsWith("/rpc/"))return Z(404,{error:"not found"});if(!dH(H.headers.authorization,X))return Z(401,{error:"unauthorized"});let N=F.slice(5),V=await lH(H),q=JSON.parse(V||"{}");if(N==="pending-notifications"){let R=typeof q.sessionId==="string"?q.sessionId:void 0;if(R===void 0&&!$)$=!0,pX.warn("rpc notification drain missing session id",{pid:process.pid});let k=Y.drain(Number(q.lastReceivedId??0),R);return Z(200,{messages:k})}if(N==="apply"){let R=await Y.apply(q);return Z(200,R)}return Z(404,{error:"unknown method"})}catch(F){Z(500,{error:F instanceof Error?F.message:String(F)})}}let K=await new Promise((H,U)=>{G.on("error",U),G.listen(0,"127.0.0.1",()=>{let Z=G.address();if(Z&&typeof Z==="object")H(Z.port);else U(Error("no port"))})});if(G.unref(),Y.sweepRoot)try{await F5(Y.sweepRoot,Y.dir)}catch(H){pX.warn("rpc state sweep failed",{pid:process.pid,error:H instanceof Error?H.message:String(H)})}try{await B5(Y.dir,{port:K,token:X,pid:process.pid},{secureDir:Y.secureDir}),pX.debug("rpc server pid",{pid:process.pid,rpcPort:K})}catch(H){throw await new Promise((U)=>G.close(()=>U())),H}return{port:K,token:X,async stop(){await new Promise((Z)=>G.close(()=>Z()));let H=pH(Y.dir,`port-${process.pid}.json`),U=await mH(H,"utf8").then((Z)=>JSON.parse(Z)).catch(()=>{return});if(U?.port===K&&U.token===X)await cH(H).catch(()=>{})}}}function N1(Y){return JSON.stringify(lX(Y))??"undefined"}function lX(Y){if(Array.isArray(Y))return Y.map(lX);if(!i(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,lX(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={};nX(b1,{withoutInternalHeaders:()=>Y4,sanitizeHttpFallbackBody:()=>MX,orderCodexBody:()=>e9,hasWebSocketResponsesLiteMetadata:()=>EX,createWebSocketFetch:()=>rB,applyTurnId:()=>sK,advanceTurn:()=>iJ,TITLE_HEADER:()=>dJ,QUOTA_ACCOUNT_HEADER:()=>GX,OpenAIWebSocketPool:()=>b1,CODEX_BODY_KEY_ORDER:()=>oK});import{createHash as lB}from"node:crypto";var s5="vercel.ai.error",iH=Symbol.for(s5),j5,q5,A=class Y extends(q5=Error,j5=iH,q5){constructor({name:X,message:J,cause:Q}){super(J);this[j5]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,s5)}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}},a5="AI_APICallError",t5=`vercel.ai.error.${a5}`,nH=Symbol.for(t5),D5,P5,b9=class extends(P5=A,D5=nH,P5){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:H}){super({name:a5,message:Y,cause:W});this[D5]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=H}static isInstance(Y){return A.hasMarker(Y,t5)}},e5="AI_EmptyResponseBodyError",Y$=`vercel.ai.error.${e5}`,oH=Symbol.for(Y$),E5,M5,rH=class extends(M5=A,E5=oH,M5){constructor({message:Y="Empty response body"}={}){super({name:e5,message:Y});this[E5]=!0}static isInstance(Y){return A.hasMarker(Y,Y$)}},X$="AI_EvaluationUnsupportedQuestionTypeError",J$=`vercel.ai.error.${X$}`,sH=Symbol.for(J$),w5,A5,aH=class extends(A5=A,w5=sH,A5){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:X$,message:$});this[w5]=!0,this.questionId=Y,this.questionType=X,this.provider=J,this.modelId=Q}static isInstance(Y){return A.hasMarker(Y,J$)}};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 Q$="AI_InvalidArgumentError",$$=`vercel.ai.error.${Q$}`,tH=Symbol.for($$),R5,T5,G$=class extends(T5=A,R5=tH,T5){constructor({message:Y,cause:X,argument:J}){super({name:Q$,message:Y,cause:X});this[R5]=!0,this.argument=J}static isInstance(Y){return A.hasMarker(Y,$$)}},W$="AI_InvalidPromptError",z$=`vercel.ai.error.${W$}`,eH=Symbol.for(z$),C5,_5,YZ=class extends(_5=A,C5=eH,_5){constructor({prompt:Y,message:X,cause:J}){super({name:W$,message:`Invalid prompt: ${X}`,cause:J});this[C5]=!0,this.prompt=Y}static isInstance(Y){return A.hasMarker(Y,z$)}},K$="AI_InvalidResponseDataError",U$=`vercel.ai.error.${K$}`,XZ=Symbol.for(U$),I5,S5,JZ=class extends(S5=A,I5=XZ,S5){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:K$,message:X});this[I5]=!0,this.data=Y}static isInstance(Y){return A.hasMarker(Y,U$)}},H$="AI_JSONParseError",Z$=`vercel.ai.error.${H$}`,QZ=Symbol.for(Z$),k5,x5,kY=class extends(x5=A,k5=QZ,x5){constructor({text:Y,cause:X}){super({name:H$,message:`JSON parsing failed: Text: ${Y}.
55
- Error message: ${d1(X)}`,cause:X});this[k5]=!0,this.text=Y}static isInstance(Y){return A.hasMarker(Y,Z$)}},L$="AI_LoadAPIKeyError",V$=`vercel.ai.error.${L$}`,$Z=Symbol.for(V$),b5,v5,GZ=class extends(v5=A,b5=$Z,v5){constructor({message:Y}){super({name:L$,message:Y});this[b5]=!0}static isInstance(Y){return A.hasMarker(Y,V$)}},N$="AI_LoadSettingError",B$=`vercel.ai.error.${N$}`,WZ=Symbol.for(B$),h5,g5,zZ=class extends(g5=A,h5=WZ,g5){constructor({message:Y}){super({name:N$,message:Y});this[h5]=!0}static isInstance(Y){return A.hasMarker(Y,B$)}},F$="AI_NoContentGeneratedError",O$=`vercel.ai.error.${F$}`,KZ=Symbol.for(O$),y5,f5,UZ=class extends(f5=A,y5=KZ,f5){constructor({message:Y="No content generated."}={}){super({name:F$,message:Y});this[y5]=!0}static isInstance(Y){return A.hasMarker(Y,O$)}},j$="AI_NoSuchModelError",q$=`vercel.ai.error.${j$}`,HZ=Symbol.for(q$),m5,c5,dX=class extends(c5=A,m5=HZ,c5){constructor({errorName:Y=j$,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[m5]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return A.hasMarker(Y,q$)}},D$="AI_NoSuchProviderReferenceError",P$=`vercel.ai.error.${D$}`,ZZ=Symbol.for(P$),u5,p5,LZ=class extends(p5=A,u5=ZZ,p5){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:D$,message:J});this[u5]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return A.hasMarker(Y,P$)}},E$="AI_TooManyEmbeddingValuesForCallError",M$=`vercel.ai.error.${E$}`,VZ=Symbol.for(M$),l5,d5,NZ=class extends(d5=A,l5=VZ,d5){constructor(Y){super({name:E$,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[l5]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return A.hasMarker(Y,M$)}},w$="AI_TypeValidationError",A$=`vercel.ai.error.${w$}`,BZ=Symbol.for(A$),i5,n5,t0=class Y extends(n5=A,i5=BZ,n5){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:w$,message:`${$}: Value: ${JSON.stringify(X)}.
56
- Error message: ${d1(J)}`,cause:J});this[i5]=!0,this.value=X,this.context=Q}static isInstance(X){return A.hasMarker(X,A$)}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})}},R$="AI_UnsupportedFunctionalityError",T$=`vercel.ai.error.${R$}`,FZ=Symbol.for(T$),o5,r5,OZ=class extends(r5=A,o5=FZ,r5){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:R$,message:X});this[o5]=!0,this.functionality=Y}static isInstance(Y){return A.hasMarker(Y,T$)}};var Qq=Object.freeze({status:"aborted"});function D(Y,X,J){function Q(K,H){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,H);for(let Z in W.prototype)if(!(Z in K))Object.defineProperty(K,Z,{value:W.prototype[Z].bind(K)});K._zod.constr=W,K._zod.def=H}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var H;let U=J?.Parent?new G:this;Q(U,K),(H=U._zod).deferred??(H.deferred=[]);for(let Z of U._zod.deferred)Z();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 $q=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 xY={};function K1(Y){if(Y)Object.assign(xY,Y);return xY}var a={};nX(a,{unwrapMessage:()=>h9,uint8ArrayToHex:()=>pZ,uint8ArrayToBase64url:()=>cZ,uint8ArrayToBase64:()=>v$,stringifyPrimitive:()=>S$,shallowClone:()=>_$,safeExtend:()=>vZ,required:()=>yZ,randomString:()=>CZ,propertyKeyTypes:()=>sX,promiseAllObject:()=>TZ,primitiveTypes:()=>I$,prefixIssues:()=>O1,pick:()=>kZ,partial:()=>gZ,optionalKeys:()=>aX,omit:()=>xZ,objectClone:()=>wZ,numKeys:()=>_Z,nullish:()=>y9,normalizeParams:()=>n,mergeDefs:()=>C1,merge:()=>hZ,jsonStringifyReplacer:()=>U9,joinValues:()=>MZ,issue:()=>Z9,isPlainObject:()=>_1,isObject:()=>i1,hexToUint8Array:()=>uZ,getSizableOrigin:()=>x$,getParsedType:()=>IZ,getLengthableOrigin:()=>m9,getEnumValues:()=>g9,getElementAtPath:()=>RZ,floatSafeRemainder:()=>oX,finalizeIssue:()=>X1,extend:()=>bZ,escapeRegex:()=>F1,esc:()=>bY,defineLazy:()=>X0,createTransparentProxy:()=>SZ,cloneDef:()=>AZ,clone:()=>Y1,cleanRegex:()=>f9,cleanEnum:()=>fZ,captureStackTrace:()=>vY,cached:()=>H9,base64urlToUint8Array:()=>mZ,base64ToUint8Array:()=>b$,assignProp:()=>T1,assertNotEqual:()=>qZ,assertNever:()=>PZ,assertIs:()=>DZ,assertEqual:()=>jZ,assert:()=>EZ,allowsEval:()=>rX,aborted:()=>I1,NUMBER_FORMAT_RANGES:()=>tX,Class:()=>h$,BIGINT_FORMAT_RANGES:()=>k$});function jZ(Y){return Y}function qZ(Y){return Y}function DZ(Y){}function PZ(Y){throw Error()}function EZ(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 MZ(Y,X="|"){return Y.map((J)=>S$(J)).join(X)}function U9(Y,X){if(typeof X==="bigint")return X.toString();return X}function H9(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 oX(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])$=Number.parseInt(H[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 C$=Symbol("evaluating");function X0(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===C$)return;if(Q===void 0)Q=C$,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function wZ(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 AZ(Y){return C1(Y._zod.def)}function RZ(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function TZ(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 CZ(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function bY(Y){return JSON.stringify(Y)}var vY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function i1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var rX=H9(()=>{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 _$(Y){if(_1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function _Z(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var IZ=(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}`)}},sX=new Set(["string","number","symbol"]),I$=new Set(["string","number","bigint","boolean","symbol","undefined"]);function F1(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y1(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 SZ(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 S$(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function aX(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var tX={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]},k$={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function kZ(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 Y1(Y,Q)}function xZ(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 Y1(Y,Q)}function bZ(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 Y1(Y,$)}function vZ(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 Y1(Y,J)}function hZ(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 Y1(Y,J)}function gZ(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 Y1(X,Q)}function yZ(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 Y1(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 X1(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 x$(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 Z9(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function fZ(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function b$(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 v$(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function mZ(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return b$(X+J)}function cZ(Y){return v$(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uZ(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 pZ(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class h${constructor(...Y){}}var g$=(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})},hY=D("$ZodError",g$),eX=D("$ZodError",g$,{Parent:Error});function y$(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 f$(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,H=0;while(H<W.path.length){let U=W.path[H];if(H!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],H++}}};return $(Y),Q}var gY=(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((H)=>X1(H,G,K1())));throw vY(K,$?.callee),K}return W.value};var yY=(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((H)=>X1(H,G,K1())));throw vY(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??hY)(G.issues.map((W)=>X1(W,$,K1())))}:{success:!0,data:G.value}},m$=c9(eX),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)=>X1(W,$,K1())))}:{success:!0,data:G.value}},c$=u9(eX),u$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return gY(Y)(X,J,$)};var p$=(Y)=>(X,J,Q)=>{return gY(Y)(X,J,Q)};var l$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return yY(Y)(X,J,$)};var d$=(Y)=>async(X,J,Q)=>{return yY(Y)(X,J,Q)};var i$=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return c9(Y)(X,J,$)};var n$=(Y)=>(X,J,Q)=>{return c9(Y)(X,J,Q)};var o$=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return u9(Y)(X,J,$)};var r$=(Y)=>async(X,J,Q)=>{return u9(Y)(X,J,Q)};var s$=/^[cC][^\s-]{8,}$/,a$=/^[0-9a-z]+$/,t$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,e$=/^[0-9a-vA-V]{20}$/,YG=/^[A-Za-z0-9]{27}$/,XG=/^[a-zA-Z0-9_-]{21}$/,JG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var QG=/^([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})$/,YJ=(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 $G=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function GG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var WG=/^(?:(?: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}|:))$/,KG=/^((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])$/,UG=/^(([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])$/,HG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,XJ=/^[A-Za-z0-9_-]*$/,ZG=/^(?=.{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 LG=/^\+(?:[0-9]){6,14}[0-9]$/,VG="(?:(?:\\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])))",NG=new RegExp(`^${VG}$`);function BG(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 FG(Y){return new RegExp(`^${BG(Y)}$`)}function OG(Y){let X=BG({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(`^${VG}T(?:${Q})$`)}var jG=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var qG=/^-?\d+$/,DG=/^-?\d+(?:\.\d+)?/,PG=/^(?:true|false)$/i,EG=/^null$/i;var MG=/^[^A-Z]*$/,wG=/^[^a-z]*$/;var T0=D("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),AG={number:"number",bigint:"bigint",object:"date"},JJ=D("$ZodCheckLessThan",(Y,X)=>{T0.init(Y,X);let J=AG[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})}}),QJ=D("$ZodCheckGreaterThan",(Y,X)=>{T0.init(Y,X);let J=AG[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})}}),RG=D("$ZodCheckMultipleOf",(Y,X)=>{T0.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):oX(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})}}),TG=D("$ZodCheckNumberFormat",(Y,X)=>{T0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=tX[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=qG}),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 CG=D("$ZodCheckMaxLength",(Y,X)=>{var J;T0.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})}}),_G=D("$ZodCheckMinLength",(Y,X)=>{var J;T0.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})}}),IG=D("$ZodCheckLengthEquals",(Y,X)=>{var J;T0.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=D("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(T0.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=()=>{})}),SG=D("$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})}}),kG=D("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=MG),p9.init(Y,X)}),xG=D("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=wG),p9.init(Y,X)}),bG=D("$ZodCheckIncludes",(Y,X)=>{T0.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})}}),vG=D("$ZodCheckStartsWith",(Y,X)=>{T0.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})}}),hG=D("$ZodCheckEndsWith",(Y,X)=>{T0.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 gG=D("$ZodCheckOverwrite",(Y,X)=>{T0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class $J{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 fG={major:4,minor:1,patch:8};var U0=D("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=fG;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,H)=>{let U=I1(W),Z;for(let F of K){if(F._zod.def.when){if(!F._zod.def.when(W))continue}else if(U)continue;let N=W.issues.length,V=F._zod.check(W);if(V instanceof Promise&&H?.async===!1)throw new B1;if(Z||V instanceof Promise)Z=(Z??Promise.resolve()).then(async()=>{if(await V,W.issues.length===N)return;if(!U)U=I1(W,N)});else{if(W.issues.length===N)continue;if(!U)U=I1(W,N)}}if(Z)return Z.then(()=>{return W});return W},G=(W,K,H)=>{if(I1(W))return W.aborted=!0,W;let U=$(K,Q,H);if(U instanceof Promise){if(H.async===!1)throw new B1;return U.then((Z)=>Y._zod.parse(Z,H))}return Y._zod.parse(U,H)};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((Z)=>{return G(Z,W,K)});return G(U,W,K)}let H=Y._zod.parse(W,K);if(H instanceof Promise){if(K.async===!1)throw new B1;return H.then((U)=>$(U,Q,K))}return $(H,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=m$(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return c$(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),uY=D("$ZodString",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??jG(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}}),Z0=D("$ZodStringFormat",(Y,X)=>{p9.init(Y,X),uY.init(Y,X)}),oG=D("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=QG),Z0.init(Y,X)}),rG=D("$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=YJ(Q))}else X.pattern??(X.pattern=YJ());Z0.init(Y,X)}),sG=D("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=$G),Z0.init(Y,X)}),aG=D("$ZodURL",(Y,X)=>{Z0.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:ZG.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})}}}),tG=D("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=GG()),Z0.init(Y,X)}),eG=D("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=XG),Z0.init(Y,X)}),Y2=D("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=s$),Z0.init(Y,X)}),X2=D("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=a$),Z0.init(Y,X)}),J2=D("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=t$),Z0.init(Y,X)}),Q2=D("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=e$),Z0.init(Y,X)}),$2=D("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=YG),Z0.init(Y,X)}),G2=D("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=OG(X)),Z0.init(Y,X)}),W2=D("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=NG),Z0.init(Y,X)}),z2=D("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=FG(X)),Z0.init(Y,X)}),K2=D("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=JG),Z0.init(Y,X)}),U2=D("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=WG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),H2=D("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=zG),Z0.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})}}}),Z2=D("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=KG),Z0.init(Y,X)}),L2=D("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=UG),Z0.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 V2(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var N2=D("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=HG),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(V2(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function dZ(Y){if(!XJ.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return V2(J)}var B2=D("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=XJ),Z0.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(dZ(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),F2=D("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=LG),Z0.init(Y,X)});function iZ(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 O2=D("$ZodJWT",(Y,X)=>{Z0.init(Y,X),Y._zod.check=(J)=>{if(iZ(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var WJ=D("$ZodNumber",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??DG,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}}),j2=D("$ZodNumber",(Y,X)=>{TG.init(Y,X),WJ.init(Y,X)}),q2=D("$ZodBoolean",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=PG,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 D2=D("$ZodNull",(Y,X)=>{U0.init(Y,X),Y._zod.pattern=EG,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 P2=D("$ZodUnknown",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J)=>J}),E2=D("$ZodNever",(Y,X)=>{U0.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function mG(Y,X,J){if(Y.issues.length)X.issues.push(...O1(J,Y.issues));X.value[J]=Y.value}var M2=D("$ZodArray",(Y,X)=>{U0.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],H=X.element._zod.run({value:K,issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>mG(U,J,W)));else mG(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function cY(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 w2(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=aX(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function A2(Y,X,J,Q,$,G){let W=[],K=$.keySet,H=$.catchall._zod,U=H.def.type;for(let Z of Object.keys(X)){if(K.has(Z))continue;if(U==="never"){W.push(Z);continue}let F=H.run({value:X[Z],issues:[]},Q);if(F instanceof Promise)Y.push(F.then((N)=>cY(N,J,Z,X)));else cY(F,J,Z,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 nZ=D("$ZodObject",(Y,X)=>{U0.init(Y,X);let J=H9(()=>w2(X));X0(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let H in W){let U=W[H]._zod;if(U.values){K[H]??(K[H]=new Set);for(let Z of U.values)K[H].add(Z)}}return K});let Q=i1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let H=W.value;if(!Q(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:Y}),W;W.value={};let U=[],Z=G.shape;for(let F of G.keys){let V=Z[F]._zod.run({value:H[F],issues:[]},K);if(V instanceof Promise)U.push(V.then((q)=>cY(q,W,F,H)));else cY(V,W,F,H)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return A2(U,H,W,K,J.value,Y)}}),R2=D("$ZodObjectJIT",(Y,X)=>{nZ.init(Y,X);let J=Y._zod.parse,Q=H9(()=>w2(X)),$=(N)=>{let V=new $J(["shape","payload","ctx"]),q=Q.value,R=(E)=>{let S=bY(E);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};V.write("const input = payload.value;");let k=Object.create(null),u=0;for(let E of q.keys)k[E]=`key_${u++}`;V.write("const newResult = {};");for(let E of q.keys){let S=k[E],c=bY(E);V.write(`const ${S} = ${R(E)};`),V.write(`
59
- if (${S}.issues.length) {
60
- payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
61
- ...iss,
62
- path: iss.path ? [${c}, ...iss.path] : [${c}]
63
- })));
64
- }
65
-
66
-
67
- if (${S}.value === undefined) {
68
- if (${c} in input) {
69
- newResult[${c}] = undefined;
70
- }
71
- } else {
72
- newResult[${c}] = ${S}.value;
73
- }
74
-
75
- `)}V.write("payload.value = newResult;"),V.write("return payload;");let C=V.compile();return(E,S)=>C(N,E,S)},G,W=i1,K=!xY.jitless,U=K&&rX.value,Z=X.catchall,F;Y._zod.parse=(N,V)=>{F??(F=Q.value);let q=N.value;if(!W(q))return N.issues.push({expected:"object",code:"invalid_type",input:q,inst:Y}),N;if(K&&U&&V?.async===!1&&V.jitless!==!0){if(!G)G=$(X.shape);if(N=G(N,V),!Z)return N;return A2([],q,N,V,F,Y)}return J(N,V)}});function cG(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)=>X1(W,Q,K1())))}),X}var zJ=D("$ZodUnion",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),X0(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),X0(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),X0(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 H of X.options){let U=H._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 cG(K,$,Y,G);return Promise.all(K).then((H)=>{return cG(H,$,Y,G)})}}),T2=D("$ZodDiscriminatedUnion",(Y,X)=>{zJ.init(Y,X);let J=Y._zod.parse;X0(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,H]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of H)$[K].add(U)}}return $});let Q=H9(()=>{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 H of K){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,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}),$}}),C2=D("$ZodIntersection",(Y,X)=>{U0.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(([H,U])=>{return uG(J,H,U)});return uG(J,G,W)}});function GJ(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=GJ(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=GJ($,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 uG(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=GJ(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var _2=D("$ZodRecord",(Y,X)=>{U0.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 H of W)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=X.valueType._zod.run({value:$[H],issues:[]},Q);if(U instanceof Promise)G.push(U.then((Z)=>{if(Z.issues.length)J.issues.push(...O1(H,Z.issues));J.value[H]=Z.value}));else{if(U.issues.length)J.issues.push(...O1(H,U.issues));J.value[H]=U.value}}let K;for(let H in $)if(!W.has(H))K=K??[],K.push(H);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)=>X1(U,Q,K1())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let H=X.valueType._zod.run({value:$[W],issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>{if(U.issues.length)J.issues.push(...O1(W,U.issues));J.value[K.value]=U.value}));else{if(H.issues.length)J.issues.push(...O1(W,H.issues));J.value[K.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var I2=D("$ZodEnum",(Y,X)=>{U0.init(Y,X);let J=g9(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>sX.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}),$}}),S2=D("$ZodLiteral",(Y,X)=>{if(U0.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 k2=D("$ZodTransform",(Y,X)=>{U0.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 pG(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var x2=D("$ZodOptional",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",X0(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),X0(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)=>pG(G,J.value));return pG($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),b2=D("$ZodNullable",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${f9(J.source)}|null)$`):void 0}),X0(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)}}),v2=D("$ZodDefault",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",X0(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)=>lG(G,X));return lG($,X)}});function lG(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var h2=D("$ZodPrefault",(Y,X)=>{U0.init(Y,X),Y._zod.optin="optional",X0(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)}}),g2=D("$ZodNonOptional",(Y,X)=>{U0.init(Y,X),X0(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)=>dG(G,Y));return dG($,Y)}});function dG(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 y2=D("$ZodCatch",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(Y._zod,"optout",()=>X.innerType._zod.optout),X0(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)=>X1(W,Q,K1()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>X1(G,Q,K1()))},input:J.value}),J.issues=[];return J}});var f2=D("$ZodPipe",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"values",()=>X.in._zod.values),X0(Y._zod,"optin",()=>X.in._zod.optin),X0(Y._zod,"optout",()=>X.out._zod.optout),X0(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)=>mY(W,X.in,Q));return mY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>mY(G,X.out,Q));return mY($,X.out,Q)}});function mY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var m2=D("$ZodReadonly",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"propValues",()=>X.innerType._zod.propValues),X0(Y._zod,"values",()=>X.innerType._zod.values),X0(Y._zod,"optin",()=>X.innerType._zod.optin),X0(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(iG);return iG($)}});function iG(Y){return Y.value=Object.freeze(Y.value),Y}var c2=D("$ZodLazy",(Y,X)=>{U0.init(Y,X),X0(Y._zod,"innerType",()=>X.getter()),X0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),X0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),X0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),X0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),u2=D("$ZodCustom",(Y,X)=>{T0.init(Y,X),U0.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)=>nG(G,J,Q,Y));nG($,J,Q,Y);return}});function nG(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(Z9($))}}var qq=Symbol("ZodOutput"),Dq=Symbol("ZodInput");class pY{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 oZ(){return new pY}var n1=oZ();function p2(Y,X){return new Y({type:"string",...n(X)})}function l2(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...n(X)})}function KJ(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...n(X)})}function d2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...n(X)})}function i2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...n(X)})}function n2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...n(X)})}function o2(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...n(X)})}function r2(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...n(X)})}function s2(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...n(X)})}function a2(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...n(X)})}function t2(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...n(X)})}function e2(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...n(X)})}function Y7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...n(X)})}function X7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...n(X)})}function J7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...n(X)})}function Q7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...n(X)})}function $7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...n(X)})}function G7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...n(X)})}function W7(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 K7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...n(X)})}function U7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...n(X)})}function H7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...n(X)})}function Z7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...n(X)})}function L7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...n(X)})}function V7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...n(X)})}function N7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...n(X)})}function B7(Y,X){return new Y({type:"number",checks:[],...n(X)})}function F7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...n(X)})}function O7(Y,X){return new Y({type:"boolean",...n(X)})}function j7(Y,X){return new Y({type:"null",...n(X)})}function q7(Y){return new Y({type:"unknown"})}function D7(Y,X){return new Y({type:"never",...n(X)})}function lY(Y,X){return new JJ({check:"less_than",...n(X),value:Y,inclusive:!1})}function l9(Y,X){return new JJ({check:"less_than",...n(X),value:Y,inclusive:!0})}function dY(Y,X){return new QJ({check:"greater_than",...n(X),value:Y,inclusive:!1})}function d9(Y,X){return new QJ({check:"greater_than",...n(X),value:Y,inclusive:!0})}function iY(Y,X){return new RG({check:"multiple_of",...n(X),value:Y})}function nY(Y,X){return new CG({check:"max_length",...n(X),maximum:Y})}function L9(Y,X){return new _G({check:"min_length",...n(X),minimum:Y})}function oY(Y,X){return new IG({check:"length_equals",...n(X),length:Y})}function UJ(Y,X){return new SG({check:"string_format",format:"regex",...n(X),pattern:Y})}function HJ(Y){return new kG({check:"string_format",format:"lowercase",...n(Y)})}function ZJ(Y){return new xG({check:"string_format",format:"uppercase",...n(Y)})}function LJ(Y,X){return new bG({check:"string_format",format:"includes",...n(X),includes:Y})}function VJ(Y,X){return new vG({check:"string_format",format:"starts_with",...n(X),prefix:Y})}function NJ(Y,X){return new hG({check:"string_format",format:"ends_with",...n(X),suffix:Y})}function o1(Y){return new gG({check:"overwrite",tx:Y})}function BJ(Y){return o1((X)=>X.normalize(Y))}function FJ(){return o1((Y)=>Y.trim())}function OJ(){return o1((Y)=>Y.toLowerCase())}function jJ(){return o1((Y)=>Y.toUpperCase())}function P7(Y,X,J){return new Y({type:"array",element:X,...n(J)})}function E7(Y,X,J){let Q=n(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function M7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...n(J)})}function w7(Y){let X=rZ((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(Z9(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(Z9($))}},Y(J.value,J)});return X}function rZ(Y,X){let J=new T0({check:"custom",...n(X)});return J._zod.check=Y,J}class qJ{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 Z={...X,schemaPath:[...X.schemaPath,Y],path:X.path},F=Y._zod.parent;if(F)W.ref=F,this.process(F,Z),this.seen.get(F).isParent=!0;else{let N=W.schema;switch(Q.type){case"string":{let V=N;V.type="string";let{minimum:q,maximum:R,format:k,patterns:u,contentEncoding:C}=Y._zod.bag;if(typeof q==="number")V.minLength=q;if(typeof R==="number")V.maxLength=R;if(k){if(V.format=$[k]??k,V.format==="")delete V.format}if(C)V.contentEncoding=C;if(u&&u.size>0){let E=[...u];if(E.length===1)V.pattern=E[0].source;else if(E.length>1)W.schema.allOf=[...E.map((S)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))]}break}case"number":{let V=N,{minimum:q,maximum:R,format:k,multipleOf:u,exclusiveMaximum:C,exclusiveMinimum:E}=Y._zod.bag;if(typeof k==="string"&&k.includes("int"))V.type="integer";else V.type="number";if(typeof E==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.minimum=E,V.exclusiveMinimum=!0;else V.exclusiveMinimum=E;if(typeof q==="number"){if(V.minimum=q,typeof E==="number"&&this.target!=="draft-4")if(E>=q)delete V.minimum;else delete V.exclusiveMinimum}if(typeof C==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")V.maximum=C,V.exclusiveMaximum=!0;else V.exclusiveMaximum=C;if(typeof R==="number"){if(V.maximum=R,typeof C==="number"&&this.target!=="draft-4")if(C<=R)delete V.maximum;else delete V.exclusiveMaximum}if(typeof u==="number")V.multipleOf=u;break}case"boolean":{let V=N;V.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")N.type="string",N.nullable=!0,N.enum=[null];else N.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":{N.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let V=N,{minimum:q,maximum:R}=Y._zod.bag;if(typeof q==="number")V.minItems=q;if(typeof R==="number")V.maxItems=R;V.type="array",V.items=this.process(Q.element,{...Z,path:[...Z.path,"items"]});break}case"object":{let V=N;V.type="object",V.properties={};let q=Q.shape;for(let u in q)V.properties[u]=this.process(q[u],{...Z,path:[...Z.path,"properties",u]});let R=new Set(Object.keys(q)),k=new Set([...R].filter((u)=>{let C=Q.shape[u]._zod;if(this.io==="input")return C.optin===void 0;else return C.optout===void 0}));if(k.size>0)V.required=Array.from(k);if(Q.catchall?._zod.def.type==="never")V.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")V.additionalProperties=!1}else if(Q.catchall)V.additionalProperties=this.process(Q.catchall,{...Z,path:[...Z.path,"additionalProperties"]});break}case"union":{let V=N,q=Q.options.map((R,k)=>this.process(R,{...Z,path:[...Z.path,"anyOf",k]}));V.anyOf=q;break}case"intersection":{let V=N,q=this.process(Q.left,{...Z,path:[...Z.path,"allOf",0]}),R=this.process(Q.right,{...Z,path:[...Z.path,"allOf",1]}),k=(C)=>("allOf"in C)&&Object.keys(C).length===1,u=[...k(q)?q.allOf:[q],...k(R)?R.allOf:[R]];V.allOf=u;break}case"tuple":{let V=N;V.type="array";let q=this.target==="draft-2020-12"?"prefixItems":"items",R=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",k=Q.items.map((S,c)=>this.process(S,{...Z,path:[...Z.path,q,c]})),u=Q.rest?this.process(Q.rest,{...Z,path:[...Z.path,R,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(V.prefixItems=k,u)V.items=u}else if(this.target==="openapi-3.0"){if(V.items={anyOf:k},u)V.items.anyOf.push(u);if(V.minItems=k.length,!u)V.maxItems=k.length}else if(V.items=k,u)V.additionalItems=u;let{minimum:C,maximum:E}=Y._zod.bag;if(typeof C==="number")V.minItems=C;if(typeof E==="number")V.maxItems=E;break}case"record":{let V=N;if(V.type="object",this.target==="draft-7"||this.target==="draft-2020-12")V.propertyNames=this.process(Q.keyType,{...Z,path:[...Z.path,"propertyNames"]});V.additionalProperties=this.process(Q.valueType,{...Z,path:[...Z.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 V=N,q=g9(Q.entries);if(q.every((R)=>typeof R==="number"))V.type="number";if(q.every((R)=>typeof R==="string"))V.type="string";V.enum=q;break}case"literal":{let V=N,q=[];for(let R of Q.values)if(R===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof R==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else q.push(Number(R));else q.push(R);if(q.length===0);else if(q.length===1){let R=q[0];if(V.type=R===null?"null":typeof R,this.target==="draft-4"||this.target==="openapi-3.0")V.enum=[R];else V.const=R}else{if(q.every((R)=>typeof R==="number"))V.type="number";if(q.every((R)=>typeof R==="string"))V.type="string";if(q.every((R)=>typeof R==="boolean"))V.type="string";if(q.every((R)=>R===null))V.type="null";V.enum=q}break}case"file":{let V=N,q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:R,maximum:k,mime:u}=Y._zod.bag;if(R!==void 0)q.minLength=R;if(k!==void 0)q.maxLength=k;if(u)if(u.length===1)q.contentMediaType=u[0],Object.assign(V,q);else V.anyOf=u.map((C)=>{return{...q,contentMediaType:C}});else Object.assign(V,q);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let V=this.process(Q.innerType,Z);if(this.target==="openapi-3.0")W.ref=Q.innerType,N.nullable=!0;else N.anyOf=[V,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"success":{let V=N;V.type="boolean";break}case"default":{this.process(Q.innerType,Z),W.ref=Q.innerType,N.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,Z),W.ref=Q.innerType,this.io==="input")N._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,Z),W.ref=Q.innerType;let V;try{V=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}N.default=V;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let V=N,q=Y._zod.pattern;if(!q)throw Error("Pattern not found in template literal");V.type="string",V.pattern=q.source;break}case"pipe":{let V=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(V,Z),W.ref=V;break}case"readonly":{this.process(Q.innerType,Z),W.ref=Q.innerType,N.readOnly=!0;break}case"promise":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,Z),W.ref=Q.innerType;break}case"lazy":{let V=Y._zod.innerType;this.process(V,Z),W.ref=V;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 H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);if(this.io==="input"&&M0(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 Z=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let q=J.external.registry.get(U[0])?.id,R=J.external.uri??((u)=>u);if(q)return{ref:R(q)};let k=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=k,{defId:k,ref:`${R("__shared")}#/${Z}/${k}`}}if(U[1]===Q)return{ref:"#"};let N=`${"#"}/${Z}/`,V=U[1].schema.id??`__schema${this.counter++}`;return{defId:V,ref:N+V}},G=(U)=>{if(U[1].schema.$ref)return;let Z=U[1],{ref:F,defId:N}=$(U);if(Z.def={...Z.schema},N)Z.defId=N;let V=Z.schema;for(let q in V)delete V[q];V.$ref=F};if(J.cycles==="throw")for(let U of this.seen.entries()){let Z=U[1];if(Z.cycle)throw Error(`Cycle detected: #/${Z.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 Z=U[1];if(Y===U[0]){G(U);continue}if(J.external){let N=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&N){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(Z.cycle){G(U);continue}if(Z.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,Z)=>{let F=this.seen.get(U),N=F.def??F.schema,V={...N};if(F.ref===null)return;let q=F.ref;if(F.ref=null,q){W(q,Z);let R=this.seen.get(q).schema;if(R.$ref&&(Z.target==="draft-7"||Z.target==="draft-4"||Z.target==="openapi-3.0"))N.allOf=N.allOf??[],N.allOf.push(R);else Object.assign(N,R),Object.assign(N,V)}if(!F.isParent)this.override({zodSchema:U,jsonSchema:N,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 H=J.external?.defs??{};for(let U of this.seen.entries()){let Z=U[1];if(Z.def&&Z.defId)H[Z.defId]=Z.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")K.$defs=H;else K.definitions=H;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function A7(Y,X){if(Y instanceof pY){let Q=new qJ(X),$={};for(let K of Y._idmap.entries()){let[H,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[H,U]=K;G[H]=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 qJ(X);return J.process(Y),J.emit(Y,X)}function M0(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 M0($.element,J);case"object":{for(let G in $.shape)if(M0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(M0(G,J))return!0;return!1}case"intersection":return M0($.left,J)||M0($.right,J);case"tuple":{for(let G of $.items)if(M0(G,J))return!0;if($.rest&&M0($.rest,J))return!0;return!1}case"record":return M0($.keyType,J)||M0($.valueType,J);case"map":return M0($.keyType,J)||M0($.valueType,J);case"set":return M0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return M0($.innerType,J);case"lazy":return M0($.getter(),J);case"default":return M0($.innerType,J);case"prefault":return M0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return M0($.in,J)||M0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var XL=D("ZodISODateTime",(Y,X)=>{G2.init(Y,X),V0.init(Y,X)});function R7(Y){return Z7(XL,Y)}var JL=D("ZodISODate",(Y,X)=>{W2.init(Y,X),V0.init(Y,X)});function T7(Y){return L7(JL,Y)}var QL=D("ZodISOTime",(Y,X)=>{z2.init(Y,X),V0.init(Y,X)});function C7(Y){return V7(QL,Y)}var $L=D("ZodISODuration",(Y,X)=>{K2.init(Y,X),V0.init(Y,X)});function _7(Y){return N7($L,Y)}var I7=(Y,X)=>{hY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>f$(Y,J)},flatten:{value:(J)=>y$(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}}})},sq=D("ZodError",I7),i0=D("ZodError",I7,{Parent:Error});var S7=gY(i0),k7=yY(i0),x7=c9(i0),sY=u9(i0),b7=u$(i0),v7=p$(i0),h7=l$(i0),g7=d$(i0),y7=i$(i0),f7=n$(i0),m7=o$(i0),c7=r$(i0);var N0=D("ZodType",(Y,X)=>{return U0.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)=>Y1(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>S7(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>x7(Y,J,Q),Y.parseAsync=async(J,Q)=>k7(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>sY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>b7(Y,J,Q),Y.decode=(J,Q)=>v7(Y,J,Q),Y.encodeAsync=async(J,Q)=>h7(Y,J,Q),Y.decodeAsync=async(J,Q)=>g7(Y,J,Q),Y.safeEncode=(J,Q)=>y7(Y,J,Q),Y.safeDecode=(J,Q)=>f7(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>m7(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>c7(Y,J,Q),Y.refine=(J,Q)=>Y.check(aL(J,Q)),Y.superRefine=(J)=>Y.check(tL(J)),Y.overwrite=(J)=>Y.check(o1(J)),Y.optional=()=>l7(Y),Y.nullable=()=>d7(Y),Y.nullish=()=>l7(d7(Y)),Y.nonoptional=(J)=>lL(Y,J),Y.array=()=>EJ(Y),Y.or=(J)=>MJ([Y,J]),Y.and=(J)=>bL(Y,J),Y.transform=(J)=>i7(Y,yL(J)),Y.default=(J)=>cL(Y,J),Y.prefault=(J)=>pL(Y,J),Y.catch=(J)=>iL(Y,J),Y.pipe=(J)=>i7(Y,J),Y.readonly=()=>rL(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}),n7=D("_ZodString",(Y,X)=>{uY.init(Y,X),N0.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(UJ(...Q)),Y.includes=(...Q)=>Y.check(LJ(...Q)),Y.startsWith=(...Q)=>Y.check(VJ(...Q)),Y.endsWith=(...Q)=>Y.check(NJ(...Q)),Y.min=(...Q)=>Y.check(L9(...Q)),Y.max=(...Q)=>Y.check(nY(...Q)),Y.length=(...Q)=>Y.check(oY(...Q)),Y.nonempty=(...Q)=>Y.check(L9(1,...Q)),Y.lowercase=(Q)=>Y.check(HJ(Q)),Y.uppercase=(Q)=>Y.check(ZJ(Q)),Y.trim=()=>Y.check(FJ()),Y.normalize=(...Q)=>Y.check(BJ(...Q)),Y.toLowerCase=()=>Y.check(OJ()),Y.toUpperCase=()=>Y.check(jJ())}),KL=D("ZodString",(Y,X)=>{uY.init(Y,X),n7.init(Y,X),Y.email=(J)=>Y.check(l2(UL,J)),Y.url=(J)=>Y.check(r2(HL,J)),Y.jwt=(J)=>Y.check(H7(AL,J)),Y.emoji=(J)=>Y.check(s2(ZL,J)),Y.guid=(J)=>Y.check(KJ(u7,J)),Y.uuid=(J)=>Y.check(d2(aY,J)),Y.uuidv4=(J)=>Y.check(i2(aY,J)),Y.uuidv6=(J)=>Y.check(n2(aY,J)),Y.uuidv7=(J)=>Y.check(o2(aY,J)),Y.nanoid=(J)=>Y.check(a2(LL,J)),Y.guid=(J)=>Y.check(KJ(u7,J)),Y.cuid=(J)=>Y.check(t2(VL,J)),Y.cuid2=(J)=>Y.check(e2(NL,J)),Y.ulid=(J)=>Y.check(Y7(BL,J)),Y.base64=(J)=>Y.check(z7(EL,J)),Y.base64url=(J)=>Y.check(K7(ML,J)),Y.xid=(J)=>Y.check(X7(FL,J)),Y.ksuid=(J)=>Y.check(J7(OL,J)),Y.ipv4=(J)=>Y.check(Q7(jL,J)),Y.ipv6=(J)=>Y.check($7(qL,J)),Y.cidrv4=(J)=>Y.check(G7(DL,J)),Y.cidrv6=(J)=>Y.check(W7(PL,J)),Y.e164=(J)=>Y.check(U7(wL,J)),Y.datetime=(J)=>Y.check(R7(J)),Y.date=(J)=>Y.check(T7(J)),Y.time=(J)=>Y.check(C7(J)),Y.duration=(J)=>Y.check(_7(J))});function o7(Y){return p2(KL,Y)}var V0=D("ZodStringFormat",(Y,X)=>{Z0.init(Y,X),n7.init(Y,X)}),UL=D("ZodEmail",(Y,X)=>{sG.init(Y,X),V0.init(Y,X)});var u7=D("ZodGUID",(Y,X)=>{oG.init(Y,X),V0.init(Y,X)});var aY=D("ZodUUID",(Y,X)=>{rG.init(Y,X),V0.init(Y,X)});var HL=D("ZodURL",(Y,X)=>{aG.init(Y,X),V0.init(Y,X)});var ZL=D("ZodEmoji",(Y,X)=>{tG.init(Y,X),V0.init(Y,X)});var LL=D("ZodNanoID",(Y,X)=>{eG.init(Y,X),V0.init(Y,X)});var VL=D("ZodCUID",(Y,X)=>{Y2.init(Y,X),V0.init(Y,X)});var NL=D("ZodCUID2",(Y,X)=>{X2.init(Y,X),V0.init(Y,X)});var BL=D("ZodULID",(Y,X)=>{J2.init(Y,X),V0.init(Y,X)});var FL=D("ZodXID",(Y,X)=>{Q2.init(Y,X),V0.init(Y,X)});var OL=D("ZodKSUID",(Y,X)=>{$2.init(Y,X),V0.init(Y,X)});var jL=D("ZodIPv4",(Y,X)=>{U2.init(Y,X),V0.init(Y,X)});var qL=D("ZodIPv6",(Y,X)=>{H2.init(Y,X),V0.init(Y,X)});var DL=D("ZodCIDRv4",(Y,X)=>{Z2.init(Y,X),V0.init(Y,X)});var PL=D("ZodCIDRv6",(Y,X)=>{L2.init(Y,X),V0.init(Y,X)});var EL=D("ZodBase64",(Y,X)=>{N2.init(Y,X),V0.init(Y,X)});var ML=D("ZodBase64URL",(Y,X)=>{B2.init(Y,X),V0.init(Y,X)});var wL=D("ZodE164",(Y,X)=>{F2.init(Y,X),V0.init(Y,X)});var AL=D("ZodJWT",(Y,X)=>{O2.init(Y,X),V0.init(Y,X)});var r7=D("ZodNumber",(Y,X)=>{WJ.init(Y,X),N0.init(Y,X),Y.gt=(Q,$)=>Y.check(dY(Q,$)),Y.gte=(Q,$)=>Y.check(d9(Q,$)),Y.min=(Q,$)=>Y.check(d9(Q,$)),Y.lt=(Q,$)=>Y.check(lY(Q,$)),Y.lte=(Q,$)=>Y.check(l9(Q,$)),Y.max=(Q,$)=>Y.check(l9(Q,$)),Y.int=(Q)=>Y.check(p7(Q)),Y.safe=(Q)=>Y.check(p7(Q)),Y.positive=(Q)=>Y.check(dY(0,Q)),Y.nonnegative=(Q)=>Y.check(d9(0,Q)),Y.negative=(Q)=>Y.check(lY(0,Q)),Y.nonpositive=(Q)=>Y.check(l9(0,Q)),Y.multipleOf=(Q,$)=>Y.check(iY(Q,$)),Y.step=(Q,$)=>Y.check(iY(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 s7(Y){return B7(r7,Y)}var RL=D("ZodNumberFormat",(Y,X)=>{j2.init(Y,X),r7.init(Y,X)});function p7(Y){return F7(RL,Y)}var TL=D("ZodBoolean",(Y,X)=>{q2.init(Y,X),N0.init(Y,X)});function a7(Y){return O7(TL,Y)}var CL=D("ZodNull",(Y,X)=>{D2.init(Y,X),N0.init(Y,X)});function t7(Y){return j7(CL,Y)}var _L=D("ZodUnknown",(Y,X)=>{P2.init(Y,X),N0.init(Y,X)});function i9(){return q7(_L)}var IL=D("ZodNever",(Y,X)=>{E2.init(Y,X),N0.init(Y,X)});function PJ(Y){return D7(IL,Y)}var SL=D("ZodArray",(Y,X)=>{M2.init(Y,X),N0.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(nY(J,Q)),Y.length=(J,Q)=>Y.check(oY(J,Q)),Y.unwrap=()=>Y.element});function EJ(Y,X){return P7(SL,Y,X)}var e7=D("ZodObject",(Y,X)=>{R2.init(Y,X),N0.init(Y,X),a.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>wJ(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:PJ()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return a.extend(Y,J)},Y.safeExtend=(J)=>{return a.safeExtend(Y,J)},Y.merge=(J)=>a.merge(Y,J),Y.pick=(J)=>a.pick(Y,J),Y.omit=(J)=>a.omit(Y,J),Y.partial=(...J)=>a.partial(WW,Y,J[0]),Y.required=(...J)=>a.required(zW,Y,J[0])});function YW(Y,X){let J={type:"object",get shape(){return a.assignProp(this,"shape",Y?a.objectClone(Y):{}),this.shape},...a.normalizeParams(X)};return new e7(J)}function XW(Y,X){return new e7({type:"object",get shape(){return a.assignProp(this,"shape",a.objectClone(Y)),this.shape},catchall:i9(),...a.normalizeParams(X)})}var JW=D("ZodUnion",(Y,X)=>{zJ.init(Y,X),N0.init(Y,X),Y.options=X.options});function MJ(Y,X){return new JW({type:"union",options:Y,...a.normalizeParams(X)})}var kL=D("ZodDiscriminatedUnion",(Y,X)=>{JW.init(Y,X),T2.init(Y,X)});function QW(Y,X,J){return new kL({type:"union",options:X,discriminator:Y,...a.normalizeParams(J)})}var xL=D("ZodIntersection",(Y,X)=>{C2.init(Y,X),N0.init(Y,X)});function bL(Y,X){return new xL({type:"intersection",left:Y,right:X})}var vL=D("ZodRecord",(Y,X)=>{_2.init(Y,X),N0.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function $W(Y,X,J){return new vL({type:"record",keyType:Y,valueType:X,...a.normalizeParams(J)})}var DJ=D("ZodEnum",(Y,X)=>{I2.init(Y,X),N0.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 DJ({...X,checks:[],...a.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 DJ({...X,checks:[],...a.normalizeParams($),entries:G})}});function wJ(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new DJ({type:"enum",entries:J,...a.normalizeParams(X)})}var hL=D("ZodLiteral",(Y,X)=>{S2.init(Y,X),N0.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 GW(Y,X){return new hL({type:"literal",values:Array.isArray(Y)?Y:[Y],...a.normalizeParams(X)})}var gL=D("ZodTransform",(Y,X)=>{k2.init(Y,X),N0.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(a.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(a.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function yL(Y){return new gL({type:"transform",transform:Y})}var WW=D("ZodOptional",(Y,X)=>{x2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function l7(Y){return new WW({type:"optional",innerType:Y})}var fL=D("ZodNullable",(Y,X)=>{b2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function d7(Y){return new fL({type:"nullable",innerType:Y})}var mL=D("ZodDefault",(Y,X)=>{v2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function cL(Y,X){return new mL({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var uL=D("ZodPrefault",(Y,X)=>{h2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function pL(Y,X){return new uL({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():a.shallowClone(X)}})}var zW=D("ZodNonOptional",(Y,X)=>{g2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function lL(Y,X){return new zW({type:"nonoptional",innerType:Y,...a.normalizeParams(X)})}var dL=D("ZodCatch",(Y,X)=>{y2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function iL(Y,X){return new dL({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var nL=D("ZodPipe",(Y,X)=>{f2.init(Y,X),N0.init(Y,X),Y.in=X.in,Y.out=X.out});function i7(Y,X){return new nL({type:"pipe",in:Y,out:X})}var oL=D("ZodReadonly",(Y,X)=>{m2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function rL(Y){return new oL({type:"readonly",innerType:Y})}var sL=D("ZodLazy",(Y,X)=>{c2.init(Y,X),N0.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function KW(Y){return new sL({type:"lazy",getter:Y})}var AJ=D("ZodCustom",(Y,X)=>{u2.init(Y,X),N0.init(Y,X)});function UW(Y,X){return E7(AJ,Y??(()=>!0),X)}function aL(Y,X={}){return M7(AJ,Y,X)}function tL(Y){return w7(Y)}function HW(Y,X={error:`Input not instance of ${Y.name}`}){let J=new AJ({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...a.normalizeParams(X)});return J._zod.bag.Class=Y,J}function DW(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 eL(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(eL(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var YV=[{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]}],g6=[...YV,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var XV=12,JV=131072,y6=JV+XV;async function tY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var PW="AI_DownloadError",EW=`vercel.ai.error.${PW}`,QV=Symbol.for(EW),ZW,LW,h0=class extends(LW=A,ZW=QV,LW){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:PW,message:$,cause:Q});this[ZW]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return A.hasMarker(Y,EW)}};function $V(Y=globalThis){return Y.window!=null}function VW(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function GV(Y){let X;try{X=new URL(Y)}catch(Q){throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new h0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new h0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(MW(Q))throw new h0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(SJ(J)){if(kJ(J))throw new h0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function WV({address:Y,family:X,hostname:J}){if(X===4?!SJ(Y)||kJ(Y):X===6?MW(Y):!0)throw new h0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function SJ(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 kJ(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 zV(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=[],H=W.split(":");for(let U=0;U<H.length;U++){let Z=H[U];if(Z.includes(".")){if(U!==H.length-1||!SJ(Z))return null;let[F,N,V,q]=Z.split(".").map(Number);K.push(F<<8|N,V<<8|q);continue}if(!/^[0-9a-f]{1,4}$/.test(Z))return null;K.push(parseInt(Z,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 MW(Y){let X=zV(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 kJ(`${$}.${G}.${W}.${K}`)}return!1}function KV(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:H}of G)WV({address:K,family:H,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 RJ;function UV(){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 HV(){if(!UV())return globalThis.fetch;return RJ!=null?RJ:RJ=Promise.resolve().then(ZV)}function ZV(){let Y=NW("node:module"),{lookup:X}=NW("node:dns"),J=Y.createRequire(wW()),{Agent:Q,fetch:$}=J("undici"),G=new Q({connect:{lookup:KV(X)}});return(W,K)=>$(W,{...K,dispatcher:G})}function NW(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 wW(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,wW);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 LV=["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 VV(Y){let X=new Headers(Y);for(let J of LV)X.delete(J);return X}var NV=10,BV=new Set([301,302,303,307,308]);async function FV(Y){return Y==null||Y===globalThis.fetch?await HV():Y}async function AW({url:Y,headers:X,abortSignal:J,maxRedirects:Q=NV,fetch:$,trustedOrigin:G}){var W;let K=X===void 0?void 0:VV(X),H=(Z)=>{let F={signal:J,redirect:Z};if(K!==void 0)F.headers=new Headers(K);return F},U=Y;for(let Z=0;Z<=Q;Z++){let F=G!==void 0&&VW(U,G);if(!F)GV(U);let N=F&&$!=null?$:F?globalThis.fetch:await FV($),V=await N(U,H("manual"));if(V.type==="opaqueredirect"){if(!$V())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await N(U,H("follow"))}let q=(W=V.headers)==null?void 0:W.get("location");if(BV.has(V.status)&&q){tY(V);let R=new URL(q,U).toString();if(K!==void 0&&!VW(R,U)){let k=K.get("user-agent");K=new Headers(k==null?void 0:{"user-agent":k})}U=R;continue}return V}throw new h0({url:Y,message:`Too many redirects (max ${Q})`})}var xJ=2147483648;async function RW({response:Y,url:X,maxBytes:J=xJ}){let Q=Y.headers.get("content-length");if(Q!=null){let Z=parseInt(Q,10);if(!isNaN(Z)&&Z>J)throw await tY(Y),new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${Z}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:Z,value:F}=await G.read();if(Z)break;if(K+=F.length,K>J)throw new h0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(F)}}finally{try{await G.cancel()}catch(Z){}finally{G.releaseLock()}}let H=new Uint8Array(K),U=0;for(let Z of W)H.set(Z,U),U+=Z.length;return H}var q0=({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 G$({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},c6=q0();function TW(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var OV=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,jV=/"(?: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 BW(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(OV.test(Y)===!1&&jV.test(Y)===!1)return X;return qV(X)}function qV(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 DV(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return BW(Y)}try{return BW(Y)}finally{Error.stackTraceLimit=X}}function bJ(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 bJ(Y)}var PV=Symbol("Let zodToJsonSchema decide on which parser to use"),FW={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"},EV=(Y)=>typeof Y==="string"?{...FW,name:Y}:{...FW,...Y};function n0(){return{}}function MV(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 wV(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 AV(){return{type:"boolean"}}function CW(Y,X){return W0(Y.type._def,X)}var RV=(Y,X)=>{return W0(Y.innerType._def,X)};function _W(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>_W(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 TV(Y)}}var TV=(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 CV(Y,X){return{...W0(Y.innerType._def,X),default:Y.defaultValue()}}function _V(Y,X){return X.effectStrategy==="input"?W0(Y.schema._def,X):n0()}function IV(Y){return{type:"string",enum:Array.from(Y.values)}}var SV=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function kV(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(SV($))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 xV(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 TJ=void 0,J1={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(TJ===void 0)TJ=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return TJ},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 IW(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":Q1(J,"email",Q.message,X);break;case"format:idn-email":Q1(J,"idn-email",Q.message,X);break;case"pattern:zod":v0(J,J1.email,Q.message,X);break}break;case"url":Q1(J,"uri",Q.message,X);break;case"uuid":Q1(J,"uuid",Q.message,X);break;case"regex":v0(J,Q.regex,Q.message,X);break;case"cuid":v0(J,J1.cuid,Q.message,X);break;case"cuid2":v0(J,J1.cuid2,Q.message,X);break;case"startsWith":v0(J,RegExp(`^${CJ(Q.value,X)}`),Q.message,X);break;case"endsWith":v0(J,RegExp(`${CJ(Q.value,X)}$`),Q.message,X);break;case"datetime":Q1(J,"date-time",Q.message,X);break;case"date":Q1(J,"date",Q.message,X);break;case"time":Q1(J,"time",Q.message,X);break;case"duration":Q1(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":{v0(J,RegExp(CJ(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")Q1(J,"ipv4",Q.message,X);if(Q.version!=="v4")Q1(J,"ipv6",Q.message,X);break}case"base64url":v0(J,J1.base64url,Q.message,X);break;case"jwt":v0(J,J1.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")v0(J,J1.ipv4Cidr,Q.message,X);if(Q.version!=="v4")v0(J,J1.ipv6Cidr,Q.message,X);break}case"emoji":v0(J,J1.emoji(),Q.message,X);break;case"ulid":{v0(J,J1.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{Q1(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{v0(J,J1.base64,Q.message,X);break}}break}case"nanoid":v0(J,J1.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function CJ(Y,X){return X.patternStrategy==="escape"?vV(Y):Y}var bV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vV(Y){let X="";for(let J=0;J<Y.length;J++){if(!bV.has(Y[J]))X+="\\";X+=Y[J]}return X}function Q1(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 v0(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:OW(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=OW(X,Q)}function OW(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,H=!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(H)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),H=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],H=!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 SW(Y,X){var J,Q,$,G,W,K;let H={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,...Z}=IW(Y.keyType._def,X);return{...H,propertyNames:Z}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...H,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,...Z}=CW(Y.keyType._def,X);return{...H,propertyNames:Z}}return H}function hV(Y,X){if(X.mapStrategy==="record")return SW(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 gV(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 yV(){return{not:n0()}}function fV(){return{type:"null"}}var _J={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function mV(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in _J)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=_J[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 cV(Y,X)}var cV=(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 uV(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[_J[Y.innerType._def.typeName],"null"]};let J=W0(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function pV(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 lV(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 H=iV(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,!H)Q.push(W)}if(Q.length)J.required=Q;let G=dV(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function dV(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 iV(Y){try{return Y.isOptional()}catch(X){return!0}}var nV=(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()},oV=(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 rV(Y,X){return W0(Y.type._def,X)}function sV(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 aV(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 tV(){return{not:n0()}}function eV(){return n0()}var YN=(Y,X)=>{return W0(Y.innerType._def,X)},XN=(Y,X,J)=>{switch(X){case"ZodString":return IW(Y,J);case"ZodNumber":return pV(Y);case"ZodObject":return lV(Y,J);case"ZodBigInt":return wV(Y);case"ZodBoolean":return AV();case"ZodDate":return _W(Y,J);case"ZodUndefined":return tV();case"ZodNull":return fV();case"ZodArray":return MV(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return mV(Y,J);case"ZodIntersection":return kV(Y,J);case"ZodTuple":return aV(Y,J);case"ZodRecord":return SW(Y,J);case"ZodLiteral":return xV(Y);case"ZodEnum":return IV(Y);case"ZodNativeEnum":return gV(Y);case"ZodNullable":return uV(Y,J);case"ZodOptional":return nV(Y,J);case"ZodMap":return hV(Y,J);case"ZodSet":return sV(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return rV(Y,J);case"ZodNaN":case"ZodNever":return yV();case"ZodEffects":return _V(Y,J);case"ZodAny":return n0();case"ZodUnknown":return eV();case"ZodDefault":return CV(Y,J);case"ZodBranded":return CW(Y,J);case"ZodReadonly":return YN(Y,J);case"ZodCatch":return RV(Y,J);case"ZodPipeline":return oV(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},JN=(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 H=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(H!==PV)return H}if($&&!J){let H=QN($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=XN(Y,Y.typeName,X),K=typeof W==="function"?W0(W(),X):W;if(K)$N(Y,X,K);if(X.postProcess){let H=X.postProcess(K,Y,X);return G.jsonSchema=K,H}return G.jsonSchema=K,K}var QN=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:JN(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}}},$N=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},GN=(Y)=>{let X=EV(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}]))}},WN=(Y,X)=>{var J;let Q=GN(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[Z,F])=>{var N;return{...U,[Z]:(N=W0(F._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,Z]},!0))!=null?N: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 H=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},IJ=Symbol.for("vercel.ai.schema");function eY(Y){let X;return()=>{if(X==null)X=Y();return X}}function YX(Y,{validate:X}={}){return{[IJ]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function zN(Y){return typeof Y==="object"&&Y!==null&&IJ in Y&&Y[IJ]===!0&&"jsonSchema"in Y&&"validate"in Y}function XX(Y){return Y==null?YX({type:"object",properties:{},additionalProperties:!1}):zN(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?n9(Y):KN(Y):Y()}function KN(Y){return YX(()=>{if(!UN(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return bJ(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 t0({value:X,cause:J.issues})}}})}function UN(Y){return Y["~standard"].jsonSchema!=null}function HN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return YX(()=>WN(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 ZN(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return YX(()=>bJ(A7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await sY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function LN(Y){return"_zod"in Y}function n9(Y,X){if(LN(Y))return ZN(Y,X);else return HN(Y,X)}async function V9({value:Y,schema:X,context:J}){let Q=XX(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:t0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:t0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function k1({text:Y,schema:X}){try{let J=DV(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await V9({value:J,schema:X})}catch(J){return{success:!1,error:kY.isInstance(J)?J:new kY({text:Y,cause:J}),rawValue:void 0}}}async function vJ(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var kW="AI_SerializationError",xW=`vercel.ai.error.${kW}`,VN=Symbol.for(xW),jW,qW,o6=class extends(qW=A,jW=VN,qW){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:kW,message:Y,cause:X});this[jW]=!0}static isInstance(Y){return A.hasMarker(Y,xW)}};var FN=Object.defineProperty,ON=(Y,X)=>{for(var J in X)FN(Y,J,{get:X[J],enumerable:!0})},Iz="AI_InvalidArgumentError",Sz=`vercel.ai.error.${Iz}`,jN=Symbol.for(Sz),bW,vW,hJ=class extends(vW=A,bW=jN,vW){constructor({parameter:Y,value:X,message:J}){super({name:Iz,message:`Invalid argument for parameter ${Y}: ${J}`});this[bW]=!0,this.parameter=Y,this.value=X}static isInstance(Y){return A.hasMarker(Y,Sz)}},kz="AI_InvalidStreamPartError",xz=`vercel.ai.error.${kz}`,qN=Symbol.for(xz),hW,gW,WD=class extends(gW=A,hW=qN,gW){constructor({chunk:Y,message:X}){super({name:kz,message:X});this[hW]=!0,this.chunk=Y}static isInstance(Y){return A.hasMarker(Y,xz)}},bz="AI_InvalidToolApprovalError",vz=`vercel.ai.error.${bz}`,DN=Symbol.for(vz),yW,fW,KD=class extends(fW=A,yW=DN,fW){constructor({approvalId:Y}){super({name:bz,message:`Tool approval response references unknown approvalId: "${Y}". No matching tool-approval-request found in message history.`});this[yW]=!0,this.approvalId=Y}static isInstance(Y){return A.hasMarker(Y,vz)}},hz="AI_InvalidToolApprovalSignatureError",gz=`vercel.ai.error.${hz}`,PN=Symbol.for(gz),mW,cW,HD=class extends(cW=A,mW=PN,cW){constructor({approvalId:Y,toolCallId:X,reason:J}){super({name:hz,message:`Tool approval signature verification failed for approval "${Y}" (tool call "${X}"): ${J}`});this[mW]=!0,this.approvalId=Y,this.toolCallId=X}static isInstance(Y){return A.hasMarker(Y,gz)}},yz="AI_InvalidToolInputError",fz=`vercel.ai.error.${yz}`,EN=Symbol.for(fz),uW,pW,LD=class extends(pW=A,uW=EN,pW){constructor({toolInput:Y,toolName:X,cause:J,message:Q=`Invalid input for tool ${X}: ${d1(J)}`}){super({name:yz,message:Q,cause:J});this[uW]=!0,this.toolInput=Y,this.toolName=X}static isInstance(Y){return A.hasMarker(Y,fz)}},mz="AI_ToolCallNotFoundForApprovalError",cz=`vercel.ai.error.${mz}`,MN=Symbol.for(cz),lW,dW,ND=class extends(dW=A,lW=MN,dW){constructor({toolCallId:Y,approvalId:X}){super({name:mz,message:`Tool call "${Y}" not found for approval request "${X}".`});this[lW]=!0,this.toolCallId=Y,this.approvalId=X}static isInstance(Y){return A.hasMarker(Y,cz)}},uz="AI_MissingToolResultsError",pz=`vercel.ai.error.${uz}`,wN=Symbol.for(pz),iW,nW,FD=class extends(nW=A,iW=wN,nW){constructor({toolCallIds:Y}){super({name:uz,message:`Tool result${Y.length>1?"s are":" is"} missing for tool call${Y.length>1?"s":""} ${Y.join(", ")}.`});this[iW]=!0,this.toolCallIds=Y}static isInstance(Y){return A.hasMarker(Y,pz)}},lz="AI_NoImageGeneratedError",dz=`vercel.ai.error.${lz}`,AN=Symbol.for(dz),oW,rW,jD=class extends(rW=A,oW=AN,rW){constructor({message:Y="No image generated.",cause:X,calls:J,responses:Q}){super({name:lz,message:Y,cause:X});this[oW]=!0,this.calls=J,this.responses=Q}static isInstance(Y){return A.hasMarker(Y,dz)}},iz="AI_NoObjectGeneratedError",nz=`vercel.ai.error.${iz}`,RN=Symbol.for(nz),sW,aW,j1=class extends(aW=A,sW=RN,aW){constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:iz,message:Y,cause:X});this[sW]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return A.hasMarker(Y,nz)}},oz="AI_NoOutputGeneratedError",rz=`vercel.ai.error.${oz}`,TN=Symbol.for(rz),tW,eW,PD=class extends(eW=A,tW=TN,eW){constructor({message:Y="No output generated.",cause:X}={}){super({name:oz,message:Y,cause:X});this[tW]=!0}static isInstance(Y){return A.hasMarker(Y,rz)}},sz="AI_NoSpeechGeneratedError",az=`vercel.ai.error.${sz}`,CN=Symbol.for(az),Yz,Xz,MD=class extends(Xz=A,Yz=CN,Xz){constructor(Y){super({name:sz,message:"No speech audio generated."});this[Yz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,az)}},tz="AI_NoTranscriptGeneratedError",ez=`vercel.ai.error.${tz}`,_N=Symbol.for(ez),Jz,Qz,AD=class extends(Qz=A,Jz=_N,Qz){constructor(Y){super({name:tz,message:"No transcript generated."});this[Jz]=!0,this.responses=Y.responses}static isInstance(Y){return A.hasMarker(Y,ez)}},YK="AI_NoTranslationGeneratedError",XK=`vercel.ai.error.${YK}`,IN=Symbol.for(XK),$z,Gz,TD=class extends(Gz=A,$z=IN,Gz){constructor(Y){super({name:YK,message:"No translation generated."});this[$z]=!0,this.response=Y.response}static isInstance(Y){return A.hasMarker(Y,XK)}},gJ="AI_NoVideoGeneratedError",JK=`vercel.ai.error.${gJ}`,SN=Symbol.for(JK),Wz,zz,_D=class extends(zz=A,Wz=SN,zz){constructor({message:Y="No video generated.",cause:X,responses:J}){super({name:gJ,message:Y,cause:X});this[Wz]=!0,this.responses=J}static isInstance(Y){return A.hasMarker(Y,JK)}static isNoVideoGeneratedError(Y){return Y instanceof Error&&Y.name===gJ&&typeof Y.responses<"u"?!0:!1}toJSON(){return{name:this.name,message:this.message,stack:this.stack,cause:this.cause,responses:this.responses}}},QK="AI_NoSuchToolError",$K=`vercel.ai.error.${QK}`,kN=Symbol.for($K),Kz,Uz,SD=class extends(Uz=A,Kz=kN,Uz){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:QK,message:J});this[Kz]=!0,this.toolName=Y,this.availableTools=X}static isInstance(Y){return A.hasMarker(Y,$K)}},GK="AI_StreamProviderError",WK=`vercel.ai.error.${GK}`,xN=Symbol.for(WK),Hz,Zz,xD=class extends(Zz=A,Hz=xN,Zz){constructor({message:Y,type:X,code:J,statusCode:Q,isRetryable:$=bN(Q),data:G,cause:W}){super({name:GK,message:Y,cause:W});this[Hz]=!0,this.type=X,this.code=J,this.statusCode=Q,this.isRetryable=$,this.data=G}static isInstance(Y){return A.hasMarker(Y,WK)}};function bN(Y){return Y!=null&&(Y===408||Y===409||Y===429||Y>=500)}var zK="AI_ToolCallRepairError",KK=`vercel.ai.error.${zK}`,vN=Symbol.for(KK),Lz,Vz,vD=class extends(Vz=A,Lz=vN,Vz){constructor({cause:Y,originalError:X,message:J=`Error repairing tool call: ${d1(Y)}`}){super({name:zK,message:J,cause:Y});this[Lz]=!0,this.originalError=X}static isInstance(Y){return A.hasMarker(Y,KK)}},UK="AI_ToolChoiceViolationError",HK=`vercel.ai.error.${UK}`,hN=Symbol.for(HK),Nz,Bz,gD=class extends(Bz=A,Nz=hN,Bz){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:UK,message:G});this[Nz]=!0,this.toolChoice=Y,this.finishReason=X,this.provider=J,this.modelId=Q,this.content=$}static isInstance(Y){return A.hasMarker(Y,HK)}};var ZK="AI_UIMessageStreamError",LK=`vercel.ai.error.${ZK}`,gN=Symbol.for(LK),Fz,Oz,fD=class extends(Oz=A,Fz=gN,Oz){constructor({chunkType:Y,chunkId:X,message:J}){super({name:ZK,message:J});this[Fz]=!0,this.chunkType=Y,this.chunkId=X}static isInstance(Y){return A.hasMarker(Y,LK)}},VK="AI_InvalidDataContentError",NK=`vercel.ai.error.${VK}`,yN=Symbol.for(NK),jz,qz,cD=class extends(qz=A,jz=yN,qz){constructor({content:Y,cause:X,message:J=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof Y}.`}){super({name:VK,message:J,cause:X});this[jz]=!0,this.content=Y}static isInstance(Y){return A.hasMarker(Y,NK)}},BK="AI_InvalidMessageRoleError",FK=`vercel.ai.error.${BK}`,fN=Symbol.for(FK),Dz,Pz,pD=class extends(Pz=A,Dz=fN,Pz){constructor({role:Y,message:X=`Invalid message role: '${Y}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:BK,message:X});this[Dz]=!0,this.role=Y}static isInstance(Y){return A.hasMarker(Y,FK)}},OK="AI_MessageConversionError",jK=`vercel.ai.error.${OK}`,mN=Symbol.for(jK),Ez,Mz,dD=class extends(Mz=A,Ez=mN,Mz){constructor({originalMessage:Y,message:X}){super({name:OK,message:X});this[Ez]=!0,this.originalMessage=Y}static isInstance(Y){return A.hasMarker(Y,jK)}},qK="AI_RetryError",DK=`vercel.ai.error.${qK}`,cN=Symbol.for(DK),wz,Az,nD=class extends(Az=A,wz=cN,Az){constructor({message:Y,reason:X,errors:J}){super({name:qK,message:Y});this[wz]=!0,this.reason=X,this.errors=J,this.lastError=J[J.length-1]}static isInstance(Y){return A.hasMarker(Y,DK)}};var uN="7.0.111",pN=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=r1({},`ai-sdk/${uN}`,DW()),W=await AW({url:$,headers:G,abortSignal:J});if(!W.ok)throw await tY(W),new h0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await RW({response:W,url:$,maxBytes:X!=null?X:xJ}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(h0.isInstance(G))throw G;throw new h0({url:$,cause:G})}};var z={array:EJ,boolean:a7,custom:UW,discriminatedUnion:QW,enum:wJ,instanceof:HW,lazy:KW,literal:GW,looseObject:XW,never:PJ,null:t7,number:s7,object:YW,record:$W,string:o7,union:MJ,unknown:i9},s1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),s1.optional()),z.array(s1)])),f=z.record(z.string(),z.record(z.string(),s1.optional())),r9=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(TW,{message:"Must be a Buffer"})]),yJ=z.record(z.string(),z.string()),PK=z.object({type:z.literal("text"),text:z.string(),providerOptions:f.optional()}),lN=z.object({type:z.literal("image"),image:z.union([r9,z.instanceof(URL),yJ]),mediaType:z.string().optional(),providerOptions:f.optional()}),EK=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:yJ}),z.object({type:z.literal("text"),text:z.string()})]),dN=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:r9}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),MK=z.object({type:z.literal("file"),data:z.union([EK,r9,z.instanceof(URL),yJ]),filename:z.string().optional(),mediaType:z.string(),providerOptions:f.optional()}),iN=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:f.optional()}),nN=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:f.optional()}),oN=z.object({type:z.literal("reasoning-file"),data:z.union([dN,r9,z.instanceof(URL)]),mediaType:z.string(),providerOptions:f.optional()}),rN=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:f.optional(),providerExecuted:z.boolean().optional()}),sN=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("json"),value:s1,providerOptions:f.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("error-json"),value:s1,providerOptions:f.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("file"),data:EK,mediaType:z.string(),filename:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:f.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:f.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:f.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:f.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:f.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:f.optional()}),z.object({type:z.literal("custom"),providerOptions:f.optional()})]))})]),wK=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:sN,providerOptions:f.optional()}),aN=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),reason:z.string().optional()}),tN=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),eN=z.object({role:z.literal("system"),content:z.string(),providerOptions:f.optional()}),YB=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([PK,lN,MK]))]),providerOptions:f.optional()}),XB=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([PK,nN,MK,iN,oN,rN,wK,aN]))]),providerOptions:f.optional()}),JB=z.object({role:z.literal("tool"),content:z.array(z.union([wK,tN])),providerOptions:f.optional()}),aD=z.union([eN,YB,XB,JB]);var QB={};ON(QB,{array:()=>zB,choice:()=>KB,json:()=>UB,object:()=>WB,text:()=>GB});function $B(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(Z){return Z>="0"&&Z<="9"||Z>="A"&&Z<="F"||Z>="a"&&Z<="f"}function W(Z,F,N){switch(Z){case'"':{J=F,X.pop(),X.push(N),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=F,Q=F,X.pop(),X.push(N),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(N),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(N),X.push("INSIDE_NUMBER");break}case"{":{J=F,X.pop(),X.push(N),X.push("INSIDE_OBJECT_START");break}case"[":{J=F,X.pop(),X.push(N),X.push("INSIDE_ARRAY_START");break}}}function K(Z,F){switch(Z){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=F,X.pop();break}}}function H(Z,F){switch(Z){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=F,X.pop();break}}}for(let Z=0;Z<Y.length;Z++){let F=Y[Z];switch(X[X.length-1]){case"ROOT":W(F,Z,"FINISH");break;case"INSIDE_OBJECT_START":{switch(F){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=Z,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,Z,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(F,Z);break}case"INSIDE_STRING":{switch(F){case'"':{X.pop(),J=Z;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=Z}break}case"INSIDE_ARRAY_START":{switch(F){case"]":{J=Z,X.pop();break}default:{J=Z,W(F,Z,"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=Z,X.pop();break}default:{J=Z;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(F,Z,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),F==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=Z;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(F)){if($++,$===4)X.pop(),J=Z}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=Z;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Y.substring(Q,Z+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(F,Z);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(F,Z)}else J=Z;break}}}let U=Y.slice(0,J+1);for(let Z=X.length-1;Z>=0;Z--)switch(X[Z]){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 N=Y.substring(Q,Y.length);if("true".startsWith(N))U+="true".slice(N.length);else if("false".startsWith(N))U+="false".slice(N.length);else if("null".startsWith(N))U+="null".slice(N.length)}}return U}async function JX(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:$B(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var GB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),WB=({schema:Y,name:X,description:J})=>{let Q=XX(Y);return{name:"object",responseFormat:vJ(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 JX($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},zB=({element:Y,minItems:X,maxItems:J,name:Q,description:$})=>{if(Rz({name:"minItems",value:X}),Rz({name:"maxItems",value:J}),X!=null&&J!=null&&X>J)throw new hJ({parameter:"minItems",value:X,message:"minItems must be less than or equal to maxItems"});let G=XX(Y);return{name:"array",responseFormat:vJ(G.jsonSchema).then((W)=>{let{$schema:K,definitions:H,$defs:U,...Z}=W;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...H!=null&&{definitions:H},...U!=null&&{$defs:U},type:"object",properties:{elements:{type:"array",items:Z,...X!=null&&{minItems:X},...J!=null&&{maxItems:J}}},required:["elements"],additionalProperties:!1},...Q!=null&&{name:Q},...$!=null&&{description:$}}}),async parseCompleteOutput({text:W},K){let H=await k1({text:W});if(!H.success)throw new j1({message:"No object generated: could not parse the response.",cause:H.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let U=H.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 t0({value:U,cause:"response must be an object with an elements array"}),text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let Z=Tz({value:U.elements,minItems:X,maxItems:J});if(Z!=null)throw new j1({message:"No object generated: response did not match schema.",cause:Z,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});let F=[];for(let N of U.elements){let V=await V9({value:N,schema:G});if(!V.success)throw new j1({message:"No object generated: response did not match schema.",cause:V.error,text:W,response:K.response,usage:K.usage,finishReason:K.finishReason});F.push(V.value)}return F},async parsePartialOutput({text:W}){let K=await JX(W);switch(K.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let H=K.value;if(H==null||typeof H!=="object"||!("elements"in H)||!Array.isArray(H.elements))return;let U=K.state==="repaired-parse"&&H.elements.length>0?H.elements.slice(0,-1):H.elements,Z=[];for(let F of U){let N=await V9({value:F,schema:G});if(N.success)Z.push(N.value)}return{partial:Z}}}},createElementStreamTransform(){let W=0;return new TransformStream({transform({partialOutput:K},H){if(K!=null)for(;W<K.length;W++){if(J!=null&&W>=J){H.error(Tz({value:K,maxItems:J}));return}H.enqueue(K[W])}}})}}};function Rz({name:Y,value:X}){if(X==null)return;if(!Number.isInteger(X))throw new hJ({parameter:Y,value:X,message:`${Y} must be an integer`});if(X<0)throw new hJ({parameter:Y,value:X,message:`${Y} must be greater than or equal to 0`})}function Tz({value:Y,minItems:X,maxItems:J}){if(X!=null&&Y.length<X)return new t0({value:Y,cause:`elements array must contain at least ${X} items`});if(J!=null&&Y.length>J)return new t0({value:Y,cause:`elements array must contain at most ${J} items`});return}var KB=({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 t0({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 JX(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}}},UB=({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 JX(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 XP=q0({prefix:"aitxt",size:24}),JP=q0({prefix:"call",size:24});var $P=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()),WP=eY(()=>n9(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:f.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:f.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:f.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:f.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:f.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:f.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:f.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:f.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:f.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:f.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:f.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 KP=q0({prefix:"aitxt",size:24}),UP=q0({prefix:"call",size:24});var HP=q0({prefix:"aitxt",size:24}),ZP=q0({prefix:"call",size:24});var m0=z.record(z.string(),s1.optional()),HB=z.record(z.string(),z.string());var VP=eY(()=>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:f.optional()}),z.object({type:z.literal("reasoning"),id:z.string().optional(),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:f.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:f.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:f.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:f.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:HB.optional(),providerMetadata:f.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:f.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:f.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:f.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:f.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:f.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:f.optional(),resultProviderMetadata:f.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:f.optional(),resultProviderMetadata:f.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:f.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:f.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:f.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:f.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:f.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:f.optional(),resultProviderMetadata:f.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:f.optional(),resultProviderMetadata:f.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:f.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 BP=q0({prefix:"call",size:24});var OP=q0({prefix:"call",size:24});var qP=q0({prefix:"call",size:24});var PP=q0({prefix:"aiobj",size:24});function AK(Y){return({url:X,abortSignal:J})=>pN({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var MP=q0({prefix:"aiobj",size:24});var wP=AK();var AP=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 RK="AI_NoSuchProviderError",TK=`vercel.ai.error.${RK}`,ZB=Symbol.for(TK),Cz,_z,TP=class extends(_z=dX,Cz=ZB,_z){constructor({modelId:Y,modelType:X,providerId:J,availableProviders:Q,message:$=`No such provider: ${J} (available providers: ${Q.join()})`}){super({errorName:RK,modelId:Y,modelType:X,message:$});this[Cz]=!0,this.providerId=J,this.availableProviders=Q}static isInstance(Y){return A.hasMarker(Y,TK)}};var _P=q0({prefix:"call",size:24});var IP=AK();class c0 extends b9{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:X?.retryable??!0})}}var k0={};nX(k0,{toWebSocketUrl:()=>_B,streamResponsesWebSocket:()=>bB,parseRateLimitSignal:()=>a9,normalizeHeaders:()=>IB,markOversizedFrame:()=>yK,isUpgradeFailure:()=>SB,isOversizedFrame:()=>kB,isAbortError:()=>pJ,connectResponsesWebSocket:()=>xB,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>uJ,PROTOCOL_HEADER:()=>vK,OpenAIWebSocket:()=>k0,OVERSIZED_FRAME_MESSAGE:()=>mK});function s9(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function QX(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((V)=>{let q=V.indexOf(":");return q===-1?[]:[[V.slice(0,q).trim().toLowerCase(),V.slice(q+1).trim()]]})),H=Y.slice(X+4),U=K["content-length"],Z=Number(U);if(!J&&(U===void 0||Number.isFinite(Z)&&H.length<Z))return;let F=Buffer.from(H).toString("utf8"),N=(()=>{try{let V=JSON.parse(F);return i(V)?V:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:F,...i(N?.error)?{error:N.error}:{}}}var LB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",CK=["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 fJ{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"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+LB));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let Z=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of CK)if(U[N]!==void 0)Z.push(`${VB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!CK.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")Z.push(`${N}: ${V}`);let F=`${Z.join(`\r
87
- `)}\r
88
- \r
89
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let N=globalThis.Bun?.connect;if(!N)throw Error("Bun.connect is not available");this.socket=await N({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(V)=>{this.socket=V,this.enqueueWrite(new TextEncoder().encode(F))},data:(V,q)=>this.onData(q),drain:()=>this.flushWrites(),error:(V,q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=q instanceof Error?q.message:String(q);this.log("socket_error",{message:R}),this.emit("error",{message:R})},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(N){this.readyState=3;let V=N instanceof Error?N.message:String(N);this.log("connect_exception",{message:V}),this.emit("error",{message:V})}}onData(Y){if(this.rxBuffer=NB(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=QX(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 H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}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=BB(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 VB(Y){return Y}function NB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function BB(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 FB}from"node:net";import{connect as OB}from"node:tls";var jB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_K=["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 mJ{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"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+jB));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[N,V]of Object.entries(X))U[N.toLowerCase()]=V;let Z=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let N of _K)if(U[N]!==void 0)Z.push(`${qB(N)}: ${U[N]}`);for(let[N,V]of Object.entries(X))if(!_K.includes(N.toLowerCase())&&N.toLowerCase()!=="content-length")Z.push(`${N}: ${V}`);let F=`${Z.join(`\r
95
- `)}\r
96
- \r
97
- `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let N=()=>{this.socket?.write(F)},V=J.protocol==="https:"?OB({host:Q,port:$,servername:Q},N):FB({host:Q,port:$},N);this.socket=V,V.on("data",(q)=>{this.onData(typeof q==="string"?Buffer.from(q,"binary"):q)}),V.on("error",(q)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let R=q instanceof Error?q.message:String(q);this.log("socket_error",{message:R}),this.emit("error",{message:R})}),V.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(N){this.readyState=3,this.log("connect_exception",{message:N instanceof Error?N.message:String(N)}),this.emit("error",{message:N instanceof Error?N.message:String(N)})}}onData(Y){if(this.rxBuffer=DB(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=QX(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 H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}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=PB(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 qB(Y){return Y}function DB(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function PB(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 EB(){return typeof globalThis.Bun?.connect==="function"}var IK=EB()?fJ:mJ;function $X(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function MB(Y){let X=$X("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 wB(Y){let X=new URL(Y);if(MB(X))return;if(X.protocol==="http:")return $X("HTTP_PROXY");if(X.protocol==="https:")return $X("HTTPS_PROXY")??$X("HTTP_PROXY");return}var SK={getProxyForUrl:wB};var AB=j0("quota"),x1=j0("transport"),vK="responses_websockets=2026-02-06",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"],RB=new Set([w1,"x-opencode-title"]);function TB(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of kK){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(!kK.includes(Q.toLowerCase()))J[Q]=$;return J}function CB(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(RB.has(J.toLowerCase()))continue;X[J]=Q}return X}function _B(Y){return Y.replace(/^http/,"ws")}function IB(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 pJ(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var hK=new WeakSet;function SB(Y){return typeof Y==="object"&&Y!==null&&hK.has(Y)}var gK=new WeakSet;function kB(Y){return typeof Y==="object"&&Y!==null&&gK.has(Y)}function yK(Y){return gK.add(Y),Y}function xK(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return hK.add(J),J}function xB(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(cJ(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??vK},$=Q[w1]??Q["session-id"];delete Q["content-length"],Q=TB(CB(Q));let G=typeof Bun>"u"?void 0:SK.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new IK(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(H)clearTimeout(H);K.removeEventListener("open",Z),K.removeEventListener("error",F),K.removeEventListener("close",N),Y.signal?.removeEventListener("abort",V)}function Z(){U(),X(K)}function F(q){U(),J(xK(t9(q),q))}function N(q){U(),J(xK(cK("WebSocket closed before open",q.code,q.reason)))}function V(){U(),K.close(),J(cJ(Y.signal))}K.addEventListener("open",Z,{once:!0}),K.addEventListener("error",F,{once:!0}),K.addEventListener("close",N,{once:!0}),Y.signal?.addEventListener("abort",V,{once:!0})})}function bB(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=0,K=!1,H=!1,U,Z=[],F=12,N=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,V=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,q={sessionID:Y.sessionID,codexSessionID:V},R,k=0,u,C=new Set,E={addedItemIds:new Set,finished:!1,other:!1};function S(){if(U)clearTimeout(U);$(),Y.signal?.removeEventListener("abort",j)}function c(I=J){I.close()}function o(){S(),Q?.enqueue(X.encode(`data: [DONE]
103
-
104
- `)),Q?.close()}function J0(I){u0(I,I)}function L0(){if(!H)return"none";if(E.other)return"other";return E.finished?"finished-calls":"unfinished-calls"}function K0(){Q?.enqueue(X.encode(`data: ${JSON.stringify(uB)}
105
-
106
- `)),o()}function B0(I){let y={...q,openingFrameTypes:Z,responseID:R,previousResponseID:N,hasContinuation:N!==void 0,framesSinceCreated:k,msSinceLastFrame:u===void 0?void 0:Date.now()-u},g=L0();if(g==="finished-calls"){if(G)return;x1.warn("stream failed after finished function calls only; ended as completed",{reason:I.message,emittedOutput:!0,outputShape:g,...y}),G=!0,S(),Y.onConnectionInvalid?.(I),K0();return}if(g==="other"){let s=uJ;x1.warn("stream failed after output; not retried",{reason:I.message,emittedOutput:!0,outputShape:g,...y}),u0(Error(s,{cause:I}),new c0(s,{cause:I}));return}x1.warn(g==="none"?"stream failed before output; retryable":"stream failed after unfinished function calls only; retryable",{reason:I.message,emittedOutput:g!=="none",outputShape:g,...y}),J0(I)}function u0(I,y){if(G)return;G=!0,S(),Y.onConnectionInvalid?.(y),Q?.error(I)}function o0(I){if(G)return;if(!Y.idleTimeout)return;if(U)clearTimeout(U);U=setTimeout(()=>B0(new c0(I)),Y.idleTimeout)}async function p(I){if(G)return;if(typeof I.data!=="string"){B0(new c0("Unexpected binary WebSocket frame"));return}let y=I.data,g=(()=>{try{let Y0=JSON.parse(y);return typeof Y0==="object"&&Y0!==null?Y0:void 0}catch{return}})();if(g?.type==="codex.rate_limits"){AB.debug("codex.rate_limits frame received",{pid:process.pid}),o0("idle timeout waiting for websocket");let Y0=bK(g);Y.onQuota?.(Y0);return}let s=L0(),F0=s==="none"||s==="unfinished-calls"?a9(g):void 0;if(F0&&g){G=!0,S(),Y.onRateLimitReached?.(F0.window,F0.resetAt),Y.onTerminal?.(g),Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached at admission (${F0.window})`));return}if(g?.type==="error"&&Y.onRetryableTerminal){if($(),U)clearTimeout(U);U=void 0;try{let Y0=await Y.onRetryableTerminal(g);if(G){if(Y0)c(Y0);return}if(Y0){x(Y0);return}}catch(Y0){B0(new c0(Y0 instanceof Error?Y0.message:String(Y0),{cause:Y0}));return}}let D0=gB(g,y);if(D0&&g){if(!K)Y.onFirstEvent?.(D0);G=!0,S(),Y.onTerminal?.(g);let Y0=new b9({message:D0.message,url:J.url,requestBodyValues:Y.body,statusCode:D0.status,responseHeaders:D0.headers,responseBody:D0.body}),z0=L0();if(z0==="none"||z0==="unfinished-calls"){if(z0==="unfinished-calls")x1.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:D0.status,reason:D0.message,outputShape:z0,responseID:R,previousResponseID:N});Q?.error(Y0);return}if(x1.warn(z0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:D0.status,reason:D0.message,outputShape:z0,responseID:R,previousResponseID:N}),z0==="finished-calls"){K0();return}Q?.error(Error(uJ,{cause:Y0}));return}if(i(g)&&g.type==="response.failed"){let Y0=i(g.response)?g.response.failed:void 0,z0=i(Y0)?Y0.rate_limit_reached_type:void 0;if(typeof z0==="string"){G=!0,S(),Y.onRateLimitReached?.(z0),Y.onTerminal?.(g);let g0=L0();if(g0!=="none")x1.warn(g0==="other"?"rate limit reached after output; ended without retry":g0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...q,outputShape:g0,responseID:R,previousResponseID:N});if(g0==="none"||g0==="unfinished-calls")Y.onFirstEvent?.(),Q?.error(new c0(`OpenAI account rate limit reached mid-stream (${z0})`));else if(g0==="finished-calls")K0();else o();return}}if(!g){if(!K)Y.onFirstEvent?.();o0("idle timeout waiting for websocket");return}if(vB(g,C),!K)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${y.split(/\r?\n/).map((Y0)=>`data: ${Y0}`).join(`
107
- `)}
108
-
109
- `)),K=!0,u=Date.now(),R!==void 0)k++;if(Z.length<F)Z.push(String(g.type));if(g.type==="response.created")R=mB(g),x1.debug("response created",{...q,responseID:R,previousResponseID:N,hasContinuation:N!==void 0});if(!pB(g.type))H=!0,cB(g,E);if(o0("idle timeout waiting for websocket"),g.type==="response.completed"||g.type==="response.done"){G=!0,hB(g,C),Y.onComplete?.(g,C),Y.onTerminal?.(g),o();return}if(g.type==="response.failed"||g.type==="response.incomplete"||g.type==="error")G=!0,Y.onTerminal?.(g),o()}function P(I){B0(new c0(t9(I),{cause:I}))}function w(I){if(G)return;let y=I.code===1009,g=new c0(y?mK:cK("WebSocket closed before response.completed",I.code,I.reason),{retryable:!y});if(y)x1.warn("websocket peer refused the request size",{...q,requestBytes:W,reason:I.reason.toString()});B0(y?yK(g):g)}function j(){let I=cJ(Y.signal);if(G)return;G=!0,S(),c(),Y.onAbort?.(I),Q?.error(I)}function M(I){if(G)return;G=!0,S(),c(),Y.onAbort?.(yB(I))}function x(I){$(),J=I,J.addEventListener("message",p),J.addEventListener("error",P,{once:!0}),J.addEventListener("close",w,{once:!0}),$=()=>{J.removeEventListener("message",p),J.removeEventListener("error",P),J.removeEventListener("close",w)};let{background:y,...g}=Y.body;o0("idle timeout sending websocket request");try{let s=JSON.stringify({type:"response.create",...g});W=s.length,J.send(s),o0("idle timeout waiting for websocket")}catch(s){if(G)return;J0(new c0(s instanceof Error?s.message:String(s),{cause:s}))}}return new Response(new ReadableStream({start(I){if(Q=I,Y.signal?.addEventListener("abort",j,{once:!0}),Y.signal?.aborted){j();return}x(J)},cancel(I){M(I)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function vB(Y,X){if(Y.type!=="response.output_item.done")return;if(!i(Y.item))return;fK(Y.item,X)}function hB(Y,X){let J=Y.response;if(!i(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(i(Q))fK(Q,X)}function fK(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 gB(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,H=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:H}}function yB(Y){if(pJ(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function cJ(Y){let X=Y?.reason;if(pJ(X))return X;if(fB(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function fB(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function mB(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function cB(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 uB={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function pB(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var uJ="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.",mK="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 cK(Y,X,J){let Q=[`code ${X}`];if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var dJ="x-opencode-title",GX="x-openai-auth-quota-account",lJ=new Set([dJ,w1,GX,"x-opencode-session"]),dB=15000,iB=300000,nB=3300000,uK="websocket_connection_limit_reached";function oB(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 lB("sha256").update(Q).digest("hex").slice(0,12)}function rB(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??dB,$=Y?.idleTimeout??iB,G=Y?.maxConnectionAge??nB,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,U=Y?.onQuota,Z=Y?.onRateLimitReached,F=setInterval(()=>R(),Math.min($,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function N(C,E,S){if(!E||!S)return S;iJ(C,pK(E));let c=new Headers(S.headers),o=c.get("x-codex-turn-metadata");if(!o)return S;let J0=aK(o,C.turnID,C.turnStartedAt);if(!J0)return S;return c.set("x-codex-turn-metadata",J0),{...S,headers:c}}async function V(C,E){let S=C instanceof URL?C.toString():typeof C==="string"?C:C.url,c=k0.normalizeHeaders(E?.headers),o=Y4(E),J0=_Y(o);if(E?.method!=="POST"||!new URL(S).pathname.endsWith("/responses"))return X(C,J0);let L0=(()=>{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(!L0?.stream)return X(C,J0);if(c[dJ]==="true")return X(C,J0);let K0=c[w1]??c["x-session-affinity"]??c["session-id"],B0=K0;if(!K0)return X(C,J0);let u0=k0.normalizeHeaders(o?.headers),o0=oB(u0),p=`${K0}:${o0}:conversation`,P=typeof c[GX]==="string"?c[GX]:void 0,w=Z?(M,x)=>Z(M,P,x):void 0,j=J.get(p)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(p,j),j.fallback)return X(C,N(j,L0,J0));if(j.busy)return X(C,N(j,L0,J0));j.busy=!0,j.lastUsedAt=Date.now();try{let M=pK(L0),x=k0.normalizeHeaders(o?.headers),I=typeof x.authorization==="string"&&x.authorization.startsWith("Bearer ")?x.authorization.slice(7):"",y=typeof x["chatgpt-account-id"]==="string"?x["chatgpt-account-id"]:void 0,g=U?($0)=>U($0,I,P,y):void 0,s=!j.socket&&!j.continuation?$F(x):x;if(j.socket=await eB(j,Y?.url??S,s,Q,G,H,E?.signal),KF(j,M))await YF(j,M,$,{signal:E?.signal??void 0,sessionID:B0,url:Y?.url??S,headers:o?.headers,onRateLimitReached:w});let F0=()=>{},D0=()=>{},Y0=new Promise(($0,C0)=>{F0=$0,D0=C0}),z0=zF(j,M),g0=e9(sK(j,z0,M)),$1=typeof g0.previous_response_id==="string";await W9({sessionID:B0,transport:"websocket",phase:"main",bodyText:JSON.stringify(g0),url:Y?.url??S,method:o?.method,headers:o?.headers});let Q0=k0.streamResponsesWebSocket({socket:j.socket,body:g0,sessionID:B0??void 0,idleTimeout:$,signal:E?.signal??void 0,onQuota:g,onRateLimitReached:w,onFirstEvent:($0)=>F0($0??!0),onComplete:($0,C0)=>{let y1=iK($0);p1({component:"ws-pool",event:"main_completed",sessionID:B0,responseID:dK($0),usage:y1}),rK(j,M,$0,C0,$1)},onTerminal:($0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,$0.type!=="response.completed"&&$0.type!=="response.done")j.continuation=void 0,q1(j)},onConnectionInvalid:($0)=>{if(j.busy=!1,j.lastUsedAt=Date.now(),k0.isOversizedFrame($0))j.fallback=!0;if(!j.fallback)q(j);j.continuation=void 0,q1(j),F0(!1)},onAbort:($0)=>{j.busy=!1,j.lastUsedAt=Date.now(),j.streamFailures=0,j.continuation=void 0,q1(j),D0($0)},onRetryableTerminal:async($0)=>{let C0=lK($0);if(!C0)return;throw j.fallback=!0,C0}}),r0=await sB(Y0,K);if(r0!==!1){if(r0===!0||r0.status<200||r0.status>599)return Q0;return new Response(r0.body,{status:r0.status,headers:{"content-type":"application/json",...r0.headers}})}let N9=()=>X(C,N(j,L0,J0));if(!j.fallback)return aB(Q0,N9);return N9()}catch(M){if(j.busy=!1,j.lastUsedAt=Date.now(),k0.isAbortError(M))throw j.streamFailures=0,j.continuation=void 0,q1(j),M;let x=k0.parseRateLimitSignal(M);if(x)w?.(x.window,x.resetAt);if(k0.isUpgradeFailure(M)&&!H)j.fallback=!0;if(q(j),j.continuation=void 0,q1(j),j.fallback)return X(C,N(j,L0,J0));return tB(new c0(M instanceof Error?M.message:String(M),{cause:M}))}}function q(C){if(C.streamFailures++,C.streamFailures>W)C.fallback=!0}function R(){let C=Date.now();for(let[E,S]of J){if(S.busy)continue;if(C-S.lastUsedAt<$)continue;q1(S),J.delete(E)}}function k(){clearInterval(F);for(let C of J.values())q1(C);J.clear()}function u(C){let E=`${C}:`;for(let[S,c]of J){if(!S.startsWith(E))continue;q1(c),J.delete(S)}}return Object.assign(V,{close:k,remove:u})}function lK(Y){if(Y.type!=="error"||!i(Y.error)||Y.error.code!==uK)return;return Error(typeof Y.error.message==="string"?Y.error.message:uK)}async function sB(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 aB(Y,X){let J=Y.body;if(!J)return Y;let Q=!1,$=new ReadableStream({async start(G){let W=J.getReader(),K=async(H)=>{while(!0){let{done:U,value:Z}=await H.read();if(U)return;if(Z&&Z.length>0)Q=!0,G.enqueue(Z)}};try{await K(W),G.close()}catch(H){if(Q||!k0.isOversizedFrame(H)){G.error(H);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 tB(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function eB(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 k0.connectResponsesWebSocket({url:k0.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 YF(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=JF(X);await W9({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=k0.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:dK(W),usage:iK(W)}),rK(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=lK(W);if(!K)return;throw Y.fallback=!0,K}});await XF(G)}function dK(Y){let X=Y.response;if(!i(X))return;return typeof X.id==="string"?X.id:void 0}function iK(Y){let X=Y.response;if(!i(X))return;return i(X.usage)?X.usage:void 0}async function XF(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function JF(Y){return e9({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:QF(Y.client_metadata)})}function nK(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 QF(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":nK(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function $F(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":nK(J)}}catch{return Y}}var oK=["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 pK(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(GF);return X}function e9(Y){let X={};for(let J of oK)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 GF(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 rK(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 H of Q)K.add(H);Y.continuation={responseID:W,input:X.input,signature:nJ(X),finalizedCallIds:K}}function iJ(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=nJ(J),W=Y.turnInput&&Y.turnSignature===G?WF(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(tK)||!Y.turnID)Y.turnID=l1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G}function sK(Y,X,J=X){iJ(Y,X,J);let Q=X.client_metadata;if(!i(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return X;let $=aK(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!$)return X;return{...X,client_metadata:{...Q,"x-codex-turn-metadata":$}}}function aK(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 WF(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return;return Y.length}function zF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==nJ(X))return Y.continuation=void 0,X;if(!eK(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),$=UF(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function KF(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!eK(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(tK)}function tK(Y){if(!i(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function UF(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 nJ(Y){return N1(HF(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function HF(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 eK(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return!1;return!0}function Y4(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of lJ)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!lJ.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!lJ.has(X.toLowerCase())))}}var ZF=300000,LF=30000,VF=5000,NF=100;function eJ(Y){let X=Y.logger,J=Y.now??Date.now,Q=Y.manifestPath??TX(),$=Y.cacheConnector??qF(X),G=Y.detectClaustrumConnection??Q4,W,K,H,U,Z,F=!1,N=new Map,V=new Set,q,k={isEnabled:()=>U?.status==="available",wasDetected:()=>U?.status==="available",getCache:()=>W,async ensureCache(){if(W)return W;return await u(),W},getTransport:()=>K,getCustodyProjection:(p,P)=>{let w=N.get(p.id);if(w)return w;return X4(p,Y.storage,P,W,q)},async boot(){if(F)return;try{U=await G()}catch(x){X.warn("custody detection failed",{error:x instanceof Error?x.message:String(x)});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 p=await Y.readCustodyManifest(Q);if(q=p,await E(p),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 u()){B0();return}let P=W;if(!P)return;if(!p.ok&&p.reason!=="absent"){C(await Y.loadAccounts(r(Y.configPath))),B0();return}await c(),await o(p);let w=await Y.loadAccounts(r(Y.configPath));await Y.onReconcileStep?.("enabled-manifest-join");let j=oJ(p,w),M=[];for(let x of rJ(w)){if(w?.claustrum?.transition?.fingerprints.fallbacks[x.id])continue;if(!sJ(x,p,A0)&&!(b0(x,A0)&&!x.accountId))continue;if(!j.get(x.id))continue;let y=u0(P);M.push(aJ(x,y).then((g)=>o0(x,g,p)).catch((g)=>X.warn("custody boot sweep failed",{error:g instanceof Error?g.message:String(g)})))}await Promise.all(M),await jF(j,P,w,NF),B0()},async runTick(){if(F)return;if(Y.storage?.claustrum?.mode!=="claustrum")return;let p=q?.ok?q.revision:void 0,P=Y.readCustodyManifest(Q),w=W?void 0:u(),j=await P;if(q=j,!j.ok&&j.reason!=="absent"){C(await Y.loadAccounts(r(Y.configPath)));return}let M=j.ok&&j.revision!==p?await E(j):await Y.loadAccounts(r(Y.configPath));if(!W&&!await w)return;if(j.ok&&j.revision===p){await c(),await Y.onReconcileStep?.("enabled-manifest-join");let I=oJ(j,M);await S(j,I),await K0(j,I);return}await c(),await o(j),await Y.onReconcileStep?.("enabled-manifest-join");let x=oJ(j,M);await S(j,x),await K0(j,x)},dispose(){if(F)return;if(F=!0,Z)(Y.clearIntervalFn??clearInterval)(Z),Z=void 0;try{W?.close()}catch{}if(!W)try{K?.close()}catch{}W=void 0,K=void 0}};async function u(){if(F)return!1;if(W)return!0;if(H)return H;if(!U)return!1;let p=(async()=>{let P;try{let w=$({connectionFile:PF(U),handshakeTimeoutMs:VF});P=new W4({connector:()=>w,now:J});let j=await w;if(F)return P.close(),!1;return W=P,K=j,!0}catch(w){return P?.close(),X.warn("custody connect failed; disabled until tick reconnect",{error:w instanceof Error?w.message:String(w)}),!1}})();H=p;try{return await p}finally{if(H===p)H=void 0}}function C(p){for(let P of rJ(p))N.set(P.id,{state:"inert",reason:"manifest-unreadable"})}async function E(p){let P=await Y.loadAccounts(r(Y.configPath));if(!P||!p.ok)return P;for(let[w,j]of f0(p)){if(!P)break;if(w==="main")continue;if(P.accounts.some((y)=>y.id===w))continue;let M=P.claustrum?.rowHistory?.includes(w)?"row removed":"awaiting discovery",x=`${w}:${M}`;if(!V.has(x))V.add(x),X.info(`orphan-binding: ${M}`,{accountId:w});if(P.claustrum?.mode!=="claustrum")continue;let I=null;while(!I&&!F)if(I=await Y.acquireRefreshFileLock({name:M1(w),ttlMs:v1,path:Y.configPath,renew:!0}),!I)await new Promise((y)=>setTimeout(y,5));if(!I)continue;try{await Y.onReconcileStep?.("discovery-lock-acquired",w);let y=await Y.readCustodyManifest(Q),g=await Y.loadAccounts(r(Y.configPath));if(g?.claustrum?.mode!=="claustrum"||!y.ok||f0(y).get(w)!==j||g.accounts.some((s)=>s.id===w))continue;await Y.mutateAccounts((s)=>{if(s.claustrum?.mode!=="claustrum"||s.accounts.some((F0)=>F0.id===w))return s;return{...s,claustrum:{...s.claustrum,mode:"claustrum",rowHistory:[...new Set([...s.claustrum?.rowHistory??[],w])]},accounts:[...s.accounts,{id:w,...V1(A0),enabled:!0}]}},r(Y.configPath))}finally{await I.release().catch(()=>{})}P=await Y.loadAccounts(r(Y.configPath))}return P}async function S(p,P){if(!W)return;let w=await Y.loadAccounts(r(Y.configPath)),j=u0(W);for(let M of rJ(w)){if(w?.claustrum?.transition?.fingerprints.fallbacks[M.id])continue;if(!sJ(M,p,A0)&&!(b0(M,A0)&&!M.accountId))continue;if(!P.has(M.id))continue;let x=await aJ(M,j);o0(M,x,p)}}async function c(){let p=await Y.loadAccounts(r(Y.configPath)),P=p?.claustrum?.transition;if(p?.claustrum?.mode!=="claustrum"||!P)return;let w=!1;for(let[j,M]of Object.entries(P.fingerprints.fallbacks)){let x=await Y.acquireRefreshFileLock({name:M1(j),ttlMs:v1,path:Y.configPath,renew:!0});if(!x){w=!0;continue}try{if(!await Y.withAccountStoreTransaction(async(y)=>{let g=await y.read(),s=g.accounts.find((z0)=>z0.id===j);if(s?.type==="oauth"&&b0(s,"openai"))return!0;if(!s||!O0(s)||!s.access||$9(s.access,s.refresh)!==M)return N.set(j,{state:"inert",reason:"new-local-family-under-claustrum"}),!1;let F0=structuredClone(g),D0=F0.accounts.find((z0)=>z0.id===j);if(!D0||!O0(D0))return!1;Object.assign(D0,V1(A0)),await y.write(F0);let Y0=(await y.read()).accounts.find((z0)=>z0.id===j);return!!(Y0?.type==="oauth"&&b0(Y0,"openai"))},r(Y.configPath)))w=!0}catch{w=!0}finally{await x.release().catch(()=>{})}}if(P.fingerprints.main)if(!Y.auth)w=!0;else{let j=await Y.acquireRefreshFileLock({name:u1,ttlMs:v1,path:Y.configPath,renew:!0});if(!j)w=!0;else try{if(await SX(P.fingerprints.main,{auth:Y.auth,warn:(x)=>X.warn(x,{})})!=="tombstoned")w=!0}finally{await j.release().catch(()=>{})}}if(w)return;await Y.withAccountStoreTransaction(async(j)=>{let M=await j.read();if(M.claustrum?.mode!=="claustrum"||M.claustrum.transition?.manifestRevision!==P.manifestRevision||M.claustrum.transition?.storeGeneration!==P.storeGeneration)return;await j.writeMode("claustrum")},r(Y.configPath))}async function o(p){if(!W||!p.ok)return;let P=await Y.loadAccounts(r(Y.configPath));if(P?.claustrum?.mode!=="claustrum")return;let w=f0(p);for(let j of P.accounts){if(j.type!=="oauth"||j.corrupt!==!0)continue;let M=w.get(j.id),x=M?await J0(j.id,j.accountId,M):"no_handle",I=k9({mode:"claustrum",manifest:M?"present":"absent",local:"gone",vault:()=>x,verifiedInProcessLogin:!1});if(!("installTombstone"in I)||!I.installTombstone||!M)continue;await L0(j.id,M)}}async function J0(p,P,w){if(Y.resolveFallbackVaultState)return Y.resolveFallbackVaultState({accountId:p,handle:w});if(!W)return"cold";if(W.isReauth(w,J()))return"needs_reauth";try{let j=await W.get(w,h1(Y.storage),{force:!0}),M=W1(j.payload.access),x=M?z1(M):void 0;if(P&&x&&x!==P)return"identity_mismatch";if(!x)X.warn("custody identity unverifiable; serving",{credentialId:w});return"serves"}catch{return W.isReauth(w,J())?"needs_reauth":"cold"}}async function L0(p,P){let w=await Y.acquireRefreshFileLock({name:M1(p),ttlMs:v1,path:Y.configPath,renew:!0});if(!w)return;try{let j=await Y.readCustodyManifest(Q),M=await Y.loadAccounts(r(Y.configPath)),x=M?.accounts.find((I)=>I.id===p);if(M?.claustrum?.mode!=="claustrum"||!j.ok||f0(j).get(p)!==P||x?.type!=="oauth"||x.corrupt!==!0)return;await Y.mutateAccounts((I)=>{let y=I.accounts.find((F0)=>F0.id===p);if(y?.type!=="oauth"||y.corrupt!==!0)return I;let{corrupt:g,...s}=y;return{...I,accounts:I.accounts.map((F0)=>F0.id===p?{...s,...V1(A0)}:F0)}},r(Y.configPath))}finally{await w.release().catch(()=>{})}}async function K0(p,P){if(!W)return;for(let[w,j]of P){if(W.isReauth(j,J()))continue;let x=(await Y.loadAccounts(r(Y.configPath)))?.accounts.find((I)=>I.id===w);if(!x||!O0(x))continue;if(!G4(x,p,Y.storage??{}))continue;try{let I=await W.get(j);N.set(w,{state:"vault",recordVersion:I.recordVersion})}catch{}}}function B0(){if(F)return;let p=Y.setIntervalFn??setInterval,P=Math.floor((Math.random()*2-1)*LF),w=ZF+P;if(Z=p(()=>{if(F)return;k.runTick().catch((M)=>X.warn("custody tick failed",{error:M instanceof Error?M.message:String(M)}))},w),Z&&typeof Z==="object"&&"unref"in Z)Z.unref?.()}function u0(p){return{loadAccounts:Y.loadAccounts,readCustodyManifest:Y.readCustodyManifest,acquireRefreshFileLock:Y.acquireRefreshFileLock,configPath:Y.configPath,paths:r(Y.configPath),manifestPath:Q,cache:p,minTtlMs:h1(Y.storage),mutateAccounts:Y.mutateAccounts,provider:A0,now:J}}function o0(p,P,w){if(P.kind==="succeeded"){N.set(p.id,{state:"vault",recordVersion:P.recordVersion});return}if(P.kind==="failed"){let M={gone:"gone",identityMismatch:"identityMismatch",nullClaim:"nullClaim",unavailable:"unavailable"}[P.reason];N.set(p.id,{state:"inert",reason:M==="unavailable"?"takeover-incomplete/vault-unavailable":"identity-mismatch"}),FF(X,p.id,M,P.recordVersion,J());return}if(P.reason==="notEnrolling"){let j=J(),M=X4(p,Y.storage,j,W,w);if(M)N.set(p.id,M)}}return k}var BF=3600000,tJ=new Map;function FF(Y,X,J,Q,$){let G=`${X}:${J}`,W=tJ.get(G);if(W!==void 0&&$-W<BF)return;tJ.set(G,$),Y.warn("custody enroll-completion sweep failed",{accountId:X,reason:J,...typeof Q==="number"?{recordVersion:Q}:{}})}function OF(){tJ.clear()}function h1(Y){return((Y?.refresh?.refreshBeforeExpiryMinutes??240)+30)*60000}function oJ(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(!WX(G,Y,A0))continue;J.set(Q,$)}return J}function X4(Y,X,J,Q,$){let G=X??{},W=$?f0($).get(Y.id):void 0;if(!b0(Y,A0)&&!W)return;if(!b0(Y,A0))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 jF(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 rJ(Y){if(!Y)return[];return Y.accounts.filter(O0)}function qF(Y){return async(X)=>{let J=await $4.connect({connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs});return DF(J,Y)}}function DF(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 PF(Y){if(Y.status!=="available")return Y.path??"";return J4()}var RF=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),TF=new Set(["gpt-5.6","gpt-6","gpt-6.1"]),CF="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.",_F=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"]),IF="opencode-oauth-dummy-key",SF="terminal_resize_reflow",W8="0.159.0",kF=`codex_exec/${W8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${W8})`,xF="seccomp",NM=()=>u1,Y8=120000,bF=90000,vF=4000,z4=50,K4=3,hF=25,gF=60000,yF="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",z8=!1;function BM(){z8=!1}var U4=j0("models"),H4=!1,Z4=!1;class U8 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 U1 extends Error{code;constructor(Y,X){super(X);this.name="ResetTargetResolutionError",this.code=Y}}function L4(Y,X,J,Q){let $=(J?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!X||X-Q<=$}function fF(Y){return async(X)=>{if(X==="main"){let H=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),U=await Y.getAuth();if(U.type!=="oauth")throw new U1("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(L4(U.access,U.expires,H,Y.now()))U={type:"oauth",...await Y.refreshMainWithLease()};if(!U.access)throw new U1("token_unavailable","Main OpenAI account has no usable access token.");let Z=W1(U.access),F=Z?z1(Z):void 0,N=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:U.access,chatgptAccountId:F??N?.mainAccountId}}let J=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),Q=J?.accounts.find((H)=>H.id===X);if(!J||!Q)throw new U1("unknown_account",`Fallback account ${X} was not found.`);if(Q.enabled===!1)throw new U1("disabled_account",`Fallback account ${X} is disabled.`);if(!O0(Q))throw new U1("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let $=Q;if(!await Y.isFallbackRefreshInert?.($,J)&&L4($.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 U1("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((H)=>H.id===X);if(!W||!K)throw new U1("unknown_account",`Fallback account ${X} was not found.`);if(K.enabled===!1)throw new U1("disabled_account",`Fallback account ${X} is disabled.`);if(!O0(K))throw new U1("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(H)=>{await Y.reportAuthFailure?.({handle:G.provenance.handle,providerStatus:H,recordVersion:G.provenance.recordVersion})}}}}function mF(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function X8(Y){return Y instanceof U8}function V4(){throw Error(yF)}function cF(Y){return Math.floor(Math.random()*Y)}function uF(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 pF(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 f4(){return G8(jY(),"openai-auth-sessions.json")}function lF(){let Y=new Map;try{let X=JSON.parse(y4(f4(),"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 dF(Y){let X=f4(),J=`${X}.tmp-${process.pid}`;try{EF(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};AF(J,`${JSON.stringify(Q,null,2)}
110
- `,"utf8"),MF(J,X)}catch{}}function N4(Y,X){return i(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function iF(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(N1(Y[J])!==N1(X[J]))return!1;return!0}function nF(Y,X){if(!Y.input)return X.length>0;if(!iF(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>N4(Q,"user")||N4(Q,"developer"))}function oF(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(nF(Y,J)||!Y.turnID))Y.turnID=l1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function rF(Y){if(!Y.metadata)return{init:Y.init};let X=uF(Y.init?.body);if(!Y.websocket)oF(Y.metadata,X);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let J=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:xF,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",SF),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",kF),Y.headers.set("version",W8),Y.dumpSessionID)Y.headers.set(w1,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&_F.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(XO);if(eF(Q,Y.metadata),$)YO(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(e9(Q))}}}function sF(Y,X){return Y.find((J)=>J.enabled!==!1&&O0(J)&&(J.id===X||J.accountId===X))}function B4(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 KX(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function UX(Y,X){return f0(Y).get(X)}function m4(Y,X,J=Date.now(),Q=X.mainAccountId,$){let G=Y.getMain(),W=G?.quota;return{main:{quota:W?{...W,checkedAt:G.checkedAt,primary:KX(W.primary,G.checkedAt),secondary:KX(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 H=Y.getFallback(K.id),U=H?.quota,Z=$?.(K,J);return{id:K.id,label:K.label,accountId:H?.accountId??K.accountId,quota:U?{...U,checkedAt:H.checkedAt,primary:KX(U.primary,H.checkedAt),secondary:KX(U.secondary,H.checkedAt)}:null,killed:!1,enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{},...Z?{custody:Z}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function OM(Y,X,J,Q=Date.now()){return{...m4(Y,X,Q),activeId:J}}function F4(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 aF(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 O4(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function K8(Y){if(Array.isArray(Y)){for(let X of Y)K8(X);return}if(!i(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))K8(X)}var tF=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]);function eF(Y,X){let J=typeof Y.model==="string"?Y.model:"";if(!tF.has(J))return;let Q=i(Y.reasoning)?Y.reasoning:void 0,$=typeof Q?.effort==="string"?Q.effort:void 0;if(!$)return;if(X.pinnedEffort===void 0){X.pinnedEffort=$;return}if($===X.pinnedEffort)return;let G=Array.isArray(Y.input)?Y.input:void 0;if(!G||G.length===0)return;Y.reasoning={...Q,effort:X.pinnedEffort},G.splice(G.length-1,0,{type:"configuration_update",reasoning:{effort:$}})}function YO(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:[];K8(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 XO(Y){if(!i(Y))return Y;if(Y.type!=="function")return Y;let X=i(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...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 JO(Y,X={}){let J=X.codexApiEndpoint??s0().codexApiEndpoint,Q=crypto.randomUUID(),$=lF(),G=()=>dF($),W=!1,K=[],H=null,U=Y.client.auth,Z=new Map,F=new Map,N,V,q,R={},k=X.custody,u=j0("custody"),C=(P,w="")=>P?async()=>{let j=await P();return{url:j.url,instructions:j.instructions??w,method:"auto",callback:async()=>{try{let M=await j.tokens;return{type:"success",refresh:M.refresh_token,access:M.access_token,expires:Date.now()+(M.expires_in??3600)*1000,accountId:J9(M)}}finally{j.cleanup?.()}}}}:void 0;function E(P,w){return eJ({storage:P,configPath:t(),loadAccounts:w0,mutateAccounts:P0,withAccountStoreTransaction:ZX,readCustodyManifest:e0,acquireRefreshFileLock:L1,auth:w,...k?{detectClaustrumConnection:async()=>k.detection==="absent"?{status:"absent",path:"test"}:{status:"available",schema:1,wireVersion:1,endpoints:[]},cacheConnector:async()=>k.transport}:{},logger:{info:(j,M)=>u.info(j,M??{}),warn:(j,M)=>u.warn(j,M??{}),debug:(j,M)=>u.debug(j,M??{}),error:(j,M)=>u.error(j,M??{})},now:k?.now})}let S=await w0(r(t())),c=await e0(),o=Y.client.auth;if(o.get&&o.all){if(m1(S??{})==="claustrum")q=E(S,{all:o.all,get:o.get,set:o.set}),k?.onRuntime?.(q),await q.boot();let P=q?.getCache();if(P)R.cache=P;if(R.mainVerdict=await bQ({client:{auth:o},mode:m1(S??{}),manifest:c,mainAccountId:S?.mainAccountId,getCredential:P?async(w)=>{return{access:(await P.get(w,h1(S))).payload.access}}:void 0,isReauth:P?(w)=>P.isReauth(w):void 0,now:Date.now,sleep:(w)=>new Promise((j)=>setTimeout(j,w))}),R.mainVerdict){let w=await a1();await $8({...w,main:{...w.main,custody:YY(R.mainVerdict)}})}}let J0=new PX,L0,K0={},B0=ZQ({client:Y.client,getAuth:async()=>L0?.(),fetchImpl:fetch,dependencies:{...k?.authorize?{authorizeBrowser:C(k.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:C(k.authorize.headless)}:{},custodyQuotaDeps:K0}}),u0=(P)=>async(w)=>{let j=await IX();try{let M=await P(w);if(M.method!=="auto")return await j.release(),M;return{...M,callback:async()=>{try{let x=await M.callback();if(x.type!=="success"||!("refresh"in x))return await j.release(),x;return uQ({accessToken:x.access??"",refreshToken:x.refresh,getAuth:async()=>{let I=await U.get({path:{id:"openai"}});return i(I)&&typeof I.access==="string"&&typeof I.refresh==="string"?{access:I.access,refresh:I.refresh}:void 0},onObserved:({access:I,refresh:y})=>kQ({type:"oauth",access:I,refresh:y}),release:()=>j.release(),warn:(I)=>k?.warn?.(I)??u.warn(I),now:k?.now??Date.now,sleep:k?.sleep??((I)=>Bun.sleep(I))}).catch(()=>j.release()),x}catch(x){throw await j.release(),x}}}}catch(M){throw await j.release(),M}},o0=B0.map((P)=>P.type==="oauth"?{...P,authorize:u0(P.authorize)}:P);async function p(P,w){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let M=await Z5(Y.client,P),x={noReply:!0,parts:[{type:"text",text:w,ignored:!0}]};if(M?.agent)x.agent=M.agent;if(M?.model)x.model=M.model;if(M?.variant)x.variant=M.variant;await j.promptAsync({path:{id:P},body:x});return}}return{async dispose(){J0.stop(),q?.dispose(),N?.stopBackgroundRefresh(),N=void 0;for(let j of K)j.close();K.length=0;let P=globalThis;for(let[j,M]of Z)if(P.__openaiAuthCacheKeepManagers?.get(j)===M)M.stop(),P.__openaiAuthCacheKeepManagers.delete(j);Z.clear();let w=globalThis;for(let[j,M]of F)if(w.__openaiAuthRpcServers?.get(j)===M)await M.stop().catch(()=>{}),w.__openaiAuthRpcServers.delete(j);F.clear()},async event(P){if(P.event.type!=="session.deleted")return;let w=P.event.properties.info,j=$.get(w.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(w.id))G();if(V){let M=(await w0(r(t())))?.accounts;await b4(w.id,M,V)}for(let M of K)M.remove(w.id)},provider:{id:"openai",async models(P,w){if(w.auth?.type!=="oauth")return P.models;let j=await w0(r(t())),M=!j||A4(j),x=M?null:await z5();if(!M&&x&&!H4)H4=!0,U4.debug("restoring OAuth model costs from models.dev catalog");if(!M&&!x&&!Z4)Z4=!0,U4.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(P.models).filter(([,I])=>{if(I.options.reasoningMode==="pro")return!1;if(RF.has(I.api.id))return!0;if(TF.has(I.api.id))return!1;let g=I.api.id.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return g?parseFloat(g)>5.4:!1}).map(([I,y])=>[I,{...y,cost:M?{input:0,output:0,cache:{read:0,write:0}}:x?.[y.api.id]??x?.[I]??y.cost,limit:y.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:y.id.includes("gpt-6-astra")?{context:872000,input:744000,output:128000}:y.id.includes("gpt-5.6")||y.id.includes("gpt-6-sol")||y.id.includes("gpt-6-luna")||y.id.includes("gpt-6.1-sol")?{context:372000,input:244000,output:128000}:y.limit}]))}},auth:{provider:"openai",async loader(P){L0=P;let w=await P();if(w.type!=="oauth")return{};let j=IY(w),M=j.kind==="tombstone"||j.kind==="empty",x=Y.directory?await g4(Y.directory):void 0,I=x?.dir??t();if(!M)await T4({type:"oauth",access:w.access??"",refresh:w.refresh??"",expires:w.expires??0},r(t()));let y=await w0(r(t())).catch((L)=>{let B=t();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})}),g;async function s(){let L=t();try{let B=wF(L);if(g?.path===L&&g.mtimeMs===B.mtimeMs&&g.size===B.size)return g.storage;let O=await w0(r(L));return g={path:L,mtimeMs:B.mtimeMs,size:B.size,storage:O},O}catch{return g=void 0,w0(r(L))}}function F0(){g=void 0}if(y&&w.access&&!M){let L=J9({id_token:"",access_token:w.access,refresh_token:w.refresh??""});if(L&&L!==y.mainAccountId)await P0((B)=>{return B.mainAccountId=L,B},r(t())),y.mainAccountId=L,F0()}let D0=y?.logging?.level;if(D0&&typeof D0==="string")CY(D0);let Y0=j0("transport"),z0=j0("quota"),g0=j0("refresh"),$1=j0("accounts");Y0.info("codex auth loader ready",{codexApiEndpoint:J,transport:s0().rawWebSocket?"raw-websocket":s0().webSockets?"websocket":"http"});let Q0=new TY({storage:y,configPath:t(),fetchQuotaFn:void 0}),r0,N9=0,$0=new C4({paths:r(t()),refreshFn:(L)=>HX({refreshToken:L.refreshToken,fetchImpl:L.fetchImpl,now:L.now}),quotaManager:Q0,custody:{readManifest:e0},onFallbackStorageChanged:F0}),C0=q??E(y);if(!q)k?.onRuntime?.(C0),await C0.boot(),q=C0;if(M){let L=await e0(),B=UX(L,"main"),O=C0.getCache();if(B&&O)try{let T=await O.get(B,h1(y)),_=x9(T.payload.access);if(_&&_!==y?.mainAccountId){if(await P0((b)=>{return b.mainAccountId=_,b},r(t())),y)y.mainAccountId=_;R.mainAccountId=_,F0()}}catch{}}if(C0.runTick().catch((L)=>u.warn("custody first tick failed",{error:L instanceof Error?L.message:String(L)})),q=C0,y&&y.accounts.length>0)$0.startBackgroundRefresh();let y1=C0;async function WY(L,B){let O=await e0();return WX(L,O,A0)}async function e1(L,B){let O=await e0(),T=y1.getCache(),_=UX(O,L.id);if(!T||!_)return J8(L,B,O);return J8(L,B,O,{cache:T,manifestHandle:_,requestPath:!0,now:k?.now??Date.now,refreshBeforeExpiryMs:(B.refresh?.refreshBeforeExpiryMinutes??240)*60000,completeEnrollmentDeps:{loadAccounts:w0,readCustodyManifest:e0,acquireRefreshFileLock:L1,configPath:t(),paths:r(t()),cache:T,minTtlMs:h1(B),mutateAccounts:P0,provider:A0,now:Date.now}})}async function H8(L){if(m1(L)!=="claustrum")return t1;let B=await e0(),O=UX(B,"main"),T=y1.getCache(),_=(h)=>{return u.warn("custody main request refused",{reason:h}),g1};if(!O||!T)return _("no-handle");let b=(k?.now??Date.now)();if(T.isBlocked(O))return _("blocked");if(T.isReauth(O,b))return _("reauth");let v=await T.peek(O);if(!v||v.expiresAtMs<=b)return _("cache-miss");return{token:v.payload.access,provenance:{handle:O,recordVersion:v.recordVersion}}}async function B9(L){let B=y1.getCache();if(!B)return;await B.reportAuthFailure({handle:L.handle,providerStatus:L.providerStatus,recordVersion:L.recordVersion})}Object.assign(K0,{isFallbackRefreshInert:WY,resolveFallbackAccess:e1,reportCustodyAuthFailure:B9});function zY(L={}){let{readSidebarState:B,respectBackoff:O,skipFresherThanMs:T}=L;return{getAuth:P,codexRefreshFn:HX,refreshMainWithLease:HY,fallbackManager:$0,quotaManager:Q0,loadAccounts:w0,writeSidebarState:ZY,client:Y.client,fetchImpl:fetch,now:Date.now,paths:r(t()),readSidebarState:B??(()=>a1(p0)),storageMainAccountId:y?.mainAccountId,isOAuthAccountFn:O0,whamFn:RY,isFallbackRefreshInert:WY,resolveFallbackAccess:e1,resolveMainAccess:H8,reportCustodyAuthFailure:B9,...O===void 0?{}:{respectBackoff:O},...T===void 0?{}:{skipFresherThanMs:T}}}let Z8=j0("cachekeep"),L8=y?.cachekeep?.enabled===!0,V8=y?.cachekeep?.subagents===!0,N8=y?.cachekeep?.sustain===!0,B8=jQ(y),KY;async function c4(L){await new Promise((B)=>setTimeout(B,L))}async function u4(L){let B;for(let O=1;O<=K4;O++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:L.refresh,access:L.access,expires:L.expires}});return}catch(T){if(B=T,O<K4)await c4(hF*O)}throw new U8(B)}async function UY(L){await P0((B)=>{return B.refresh=B.refresh??{},L(B),B},r(t())),F0()}async function F8(L){let B=Date.now()+vF;while(Date.now()<B){await new Promise((_)=>setTimeout(_,z4+cF(z4)));let O=await P();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 g0.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(!KY)KY=(async()=>{let L=await P();if(L.type!=="oauth")throw Error("not oauth");if(b0({id:"main",type:"oauth",access:L.access??"",refresh:L.refresh??"",expires:L.expires??0,addedAt:0},A0))throw new M4(A0);if(!L.refresh)throw Error("Token refresh failed: missing refresh token");let B=j4(L.refresh),O=await w0(r(t())),T=O?.refresh?.mainLastRefreshError;if(T&&EY(T,L.refresh,Date.now()))throw Error(D4(T,Date.now()));if(O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===B){let h=await F8(L);if(h)return h;throw Error("Codex OAuth refresh is already in progress")}let _=await L1({name:u1,ttlMs:Y8,path:t(),renew:!0});if(!_){let h=await F8(L);if(h)return h;throw Error("Codex OAuth refresh is already in progress")}let b=crypto.randomUUID(),v=B;try{await UY((l)=>{l.refresh=l.refresh??{},l.refresh.mainRefreshLeaseId=b,l.refresh.mainRefreshLeaseUntil=Date.now()+bF,l.refresh.mainRefreshLeaseTokenHash=B});let h=await w0(r(t()));if(h?.refresh?.mainRefreshLeaseId!==b||h.refresh.mainRefreshLeaseTokenHash!==B)throw Error("Codex OAuth refresh is already in progress");let m=await HX({refreshToken:L.refresh,fetchImpl:fetch,now:Date.now});return await u4(m),await UY((l)=>{if(l.refresh=l.refresh??{},l.refresh.mainLastRefreshError=void 0,l.refresh.mainRefreshLeaseId===b)l.refresh.mainRefreshLeaseId=void 0,l.refresh.mainRefreshLeaseUntil=void 0,l.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),v=void 0,m}catch(h){if(L.refresh&&!X8(h))await UY((m)=>{m.refresh=m.refresh??{},m.refresh.mainLastRefreshError=q4({error:h,now:Date.now(),refreshToken:L.refresh??"",previous:m.refresh.mainLastRefreshError})}).catch(()=>{});throw h}finally{if(v)await UY((h)=>{if(h.refresh?.mainRefreshLeaseId===b&&h.refresh.mainRefreshLeaseTokenHash===v)h.refresh.mainRefreshLeaseId=void 0,h.refresh.mainRefreshLeaseUntil=void 0,h.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await _.release().catch(()=>{})}})().finally(()=>{KY=void 0});return KY}let O8=globalThis,VX=O8.__openaiAuthCacheKeepManagers??new Map;O8.__openaiAuthCacheKeepManagers=VX,VX.get(I)?.stop();let F9=new RX({fetchImpl:fetch,getMainToken:async()=>{let L=await P();if(L.type!=="oauth")throw Error("not oauth");if(!L.access||(L.expires??0)<Date.now())try{return(await HY()).access}catch(B){if(X8(B))throw B;if(L.access)return L.access;throw Error("main token refresh failed")}return L.access},refreshFallback:async(L)=>{let B=await s(),O=B?sF(B.accounts,L):void 0;if(!O)throw Error(`fallback account ${L} not found`);let T=B??{version:1,accounts:[O]},_=O;if(!await WY(O,T))_=await $0.refreshAccount(O,T);let b=await e1(_,T);if(b===g1||b===t1)throw Error(`no access token for ${L}`);return{token:b.token,onAuthFailure:b.provenance==="local"?void 0:async(v)=>{await B9({handle:b.provenance.handle,providerStatus:v,recordVersion:b.provenance.recordVersion})}}},codexResponsesUrl:J,logger:Z8,now:Date.now,getWindow:()=>B8,getSustain:()=>N8});VX.set(I,F9),Z.set(I,F9);async function O9(L,B,O,T,_=!1){if(Object.keys(L).length===0&&!_)return;let b=Date.now(),v=L,h={quota:v,refreshAfter:b+300000,checkedAt:b},m;if(O&&O!=="main"){let d=B?W1(B):null,H0=d?z1(d):void 0,l0=Q0.peekFallbackForPolicy(O)?.quota,_0=B4(v,l0);h={...h,quota:_0},Q0.setFallback(O,h,B,_,H0)}else{if(m=T,!m&&B){let l0=W1(B);m=l0?z1(l0):void 0}if(m&&r0&&m!==r0){z0.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:m,currentMainIdentity:r0});return}let d=Q0.peekMainForPolicy(m)?.quota,H0=B4(v,d);h={...h,quota:H0},Q0.setMain(B,h,m,_)}z0.debug("quota pushed",{pid:process.pid,accountId:O??"main",snapshot:h.quota});let l=await s();await ZY(Q0,l,O&&O!=="main"?l?.mainAccountId:m)}function p4(L,B,O){let T=L==="main"?Q0.peekMainForPolicy()?.quota:Q0.peekFallbackForPolicy(L)?.quota;return w4(T,B,Date.now(),gF,O)}let j9=X.experimentalWebSockets?b1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:s0().rawWebSocket,onQuota:(L,B,O,T)=>{O9(L,B,O,!O||O==="main"?T:void 0,!0)},onRateLimitReached:(L,B,O)=>{if(!B)z0.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:L});let T=B??"main",_=p4(T,L,O);Q0.markRateLimited(T,_),z0.debug("mid-stream rate limit mark",{pid:process.pid,accountId:T,window:L})}}):void 0;if(j9)K.push(j9),W=!0;let p0=_4();V=p0;async function ZY(L,B,O=B?.mainAccountId){if(!B)return;await $8(m4(L,B,Date.now(),O,l4),p0)}function l4(L,B){if(!O0(L))return;return y1.getCustodyProjection(L,B)}async function j8(L,B,O,T,_){let b={activeId:O,route:T,updatedAt:Date.now()};if(L){if(await LX({sessionId:L,...b},_,p0),B&&B!==L){if(T==="sticky-balanced"){let v=(await a1(p0)).stickyAssignments?.[GY(B)]?.accountId,h=_===void 0||v==="main"||_.some((m)=>m.enabled!==!1&&m.id===v);if(!v||!h)return;await LX({sessionId:B,activeId:v,route:T,updatedAt:Date.now()},_,p0);return}await LX({sessionId:B,...b},_,p0)}return}await x4(b,p0)}let d4=async(L,B)=>{let O=await L1({name:M1(L),ttlMs:v1,path:t(),renew:!0});if(!O)throw Error("Fallback account lock unavailable");try{return await B()}finally{await O.release()}},i4=k?.withFallbackAccountLock??d4,n4=async(L)=>{let B=await e0();if(!B.ok)return{ready:!1,reason:"manifest-unreadable"};let O=UX(B,L.id);if(!O)return{ready:!1,reason:"no-handle"};let T=C0.getCache();if(!T)return{ready:!1,reason:"vault-cold"};if(T.isReauth(O,k?.now?.()??Date.now()))return{ready:!1,reason:"vault-reauth"};if(T.isBlocked(O))return{ready:!1,reason:"vault-cold"};try{let _=await T.get(O,h1(y)),b=x9(_.payload.access);if(!b||L.accountId&&L.accountId!==b)return{ready:!1,reason:"identity-mismatch"};return{ready:!0,accountId:b}}catch{return{ready:!1,reason:T.isReauth(O,k?.now?.()??Date.now())?"vault-reauth":"vault-cold"}}};N?.stopBackgroundRefresh(),N=$0,H={accountStoragePath:t(),accountStatePath:PY(t()),packageVersion:E9,quotaManager:Q0,loadAccounts:w0,client:Y.client,beginAccountLogin:AY,withFallbackAccountLock:i4,checkUsableCustodyBinding:n4,enterClaustrumMode:async()=>{let L=await w0(r(t())),B=(L?.accounts??[]).filter((O)=>O.type==="oauth"&&O.enabled!==!1).map((O)=>O.id);return pQ({accountIds:B,acquireLock:({name:O,renew:T})=>L1({name:O,ttlMs:O===u1?Y8:v1,path:t(),renew:T}),withStoreTransaction:(O)=>ZX(O,r(t())),readManifest:e0,preflight:async({accountId:O,handle:T})=>{u.info("preflight probing participant",{accountId:O,hasHandle:T.length>0});let _=await C0.ensureCache(),b=_?.isBlocked(T);if(!_||b)return u.warn("preflight vault-cold",{accountId:O,hasCache:_!==void 0,blocked:b}),"vault-cold";if(_.isReauth(T,k?.now?.()??Date.now()))return"vault-reauth";try{let v=await _.get(T,h1(L)),h=x9(v.payload.access);if(!h||O&&O!==h)return"identity-mismatch";return"ready"}catch{return _.isReauth(T,k?.now?.()??Date.now())?"vault-reauth":"vault-cold"}},auth:{all:async()=>{if(typeof U.all==="function")return U.all();let O=process.env.XDG_DATA_HOME??G8(zX.homedir(),".local","share"),T=G8(O,"opencode","auth.json");try{let _=JSON.parse(y4(T,"utf8"));return i(_)?_:{}}catch{return{}}},get:async(O)=>{if(typeof U.get==="function")return U.get(O);if(O.path.id!=="openai"||!L0){u.warn("auth.get unavailable for slot",{id:O.path.id,hasLoaderGetAuth:L0!==void 0});return}return L0()},set:async(O)=>{await U.set(O)}},warn:(O)=>u.warn(O)})},leaveClaustrumMode:()=>lQ({acquireLock:({name:L,renew:B})=>L1({name:L,ttlMs:Y8,path:t(),renew:B}),withStoreTransaction:(L)=>ZX(L,r(t()))}),resolveResetTarget:fF({getAuth:P,refreshMainWithLease:HY,refreshFallbackAccount:(L,B)=>$0.refreshAccount(L,B),loadAccounts:w0,accountStoragePath:t(),accountStatePath:PY(t()),now:Date.now,isFallbackRefreshInert:WY,resolveFallbackAccess:e1,reportAuthFailure:B9}),...mF(),cacheKeepManager:F9,setCacheKeepEnabled:(L)=>{L8=L},setCacheKeepSubagents:(L)=>{V8=L},setCacheKeepSustain:(L)=>{N8=L},setCacheKeepWindow:(L)=>{B8=L},clearStickyRouting:(L)=>h4(L,p0),getStickyRouting:async(L)=>k4(await a1(p0),L),refreshSidebar:async()=>{let L=await w0(r(t()));await ZY(Q0,L)},refreshAllQuota:async()=>E1(zY()),refreshResetTargetQuota:async(L)=>{return(await E1(zY({respectBackoff:!1}),{accountKey:L})).find((O)=>O.account===L)??{account:L,ok:!1,error:"targeted quota refresh returned no result"}}};let NX=null;if(x){let L=globalThis,B=L.__openaiAuthRpcServers??new Map;L.__openaiAuthRpcServers=B;let O=B.get(x.dir);if(O)await O.stop().catch(()=>{}),B.delete(x.dir);try{NX=await O5({dir:x.dir,secureDir:x.secureDir,sweepRoot:x.sweepRoot,drain:V5,apply:async(T)=>{let _={...H,sessionId:T.sessionId},b=await DX(T.command,T.arguments,_);return{text:b.text,knobs:b.knobs}}}),B.set(x.dir,NX),F.set(x.dir,NX)}catch{}}let q8=new WeakMap;function o4(L,B){let O=q8.get(L);if(!O||B.hostname!=="chatgpt.com"||!B.pathname.startsWith("/backend-api/codex/"))return;if(L.status>=200&&L.status<300){y1.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,T,_="main",b){if(!O.trim())throw Y0.warn("refusing to send a request with no access token",{account:_,accountId:T,hasProvenance:Boolean(b&&b!=="local")}),Error(CF);let v=F4(L,B);if(v.delete("x-api-key"),v.delete("api-key"),v.set("authorization",`Bearer ${O}`),T)v.set("ChatGPT-Account-Id",T);v.set(b1.QUOTA_ACCOUNT_HEADER,_);let h=O4(v),m=h?pF($,h,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,H0=(S0)=>{let Y9=E4(S0,b,q8);return o4(Y9,d),Y9},_0=rF({init:{...B,headers:v},headers:v,metadata:m,installationID:Q,websocket:Boolean(j9&&l.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:h}).init,H1=L8,D1=new Headers(_0?.headers),d0=OQ({enabled:H1,includeSubagents:V8,headers:D1,body:_0?.body});if(H1)Z8.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(Y0.debug("WS transport",{pid:process.pid,pathname:l.pathname,accountId:_}),d0)F9.track(d0.sessionKey,d0.bodyText,_,T,d0.replayHeaders,d0.isSubagent);return H0(await j9(d,_0))}let I0=b1.withoutInternalHeaders(_0);if(typeof I0?.body!=="string")return H0(await fetch(d,I0));if(d0)F9.track(d0.sessionKey,d0.bodyText,_,T,d0.replayHeaders,d0.isSubagent);Y0.debug("HTTP transport",{pid:process.pid,pathname:l.pathname,accountId:_});try{let S0=await fetch(d,I0);return await W9({sessionID:h,transport:"http",phase:"http",bodyText:I0.body,accountId:_,url:d.toString(),method:I0.method,headers:I0.headers,status:S0.status}),H0(S0)}catch(S0){throw await W9({sessionID:h,transport:"http",phase:"http",bodyText:I0.body,accountId:_,url:d.toString(),method:I0.method,headers:I0.headers,error:S0 instanceof Error?S0.message:String(S0)}),S0}}function LY(L,B){if((B?.method??(L instanceof Request?L.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof B?.body!=="string")return!1;try{let T=L instanceof URL?L.toString():typeof L==="string"?L:L.url;return new URL(T).pathname.endsWith("/responses")}catch{return!1}}function r4(L){return Q0.peekMainForPolicy(L)?.quota}function D8(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,T,_){let b=D8(L,B),v=D8(O),h=T===_&&O!=null&&(L===void 0||v!==void 0&&(b===void 0||v>b));return{quota:h?O:L,quotaCheckedAt:h?v:b,source:h?"file":"memory"}}function P8(L,B,O,T,_){let b=L?.quota,v=D9(b,L?.checkedAt,B,T,_),h=v.source,m=v.quota;if(!S4(m,O))return{exhausted:!1};let l=I4(m,O);if(!l)return{exhausted:!1};return{exhausted:!0,source:h,...l}}function E8(L,B){z0.debug("admission skip: exhausted account",{accountId:L,source:B.source,resetsAt:B.resetsAt})}function s4(L,B="killswitch",O){let T=Date.now(),_=Q0.getMain()?.quota,b=(L?.accounts??[]).filter((d)=>d.enabled!==!1&&O0(d)).map((d)=>({accountId:d.id,quota:Q0.getFallback(d.id)?.quota})),v=R4(_,b,T,L);if(B==="quota-exhausted"&&O!==void 0)v=Math.max(1,Math.ceil((O-T)/1000));else if(B==="mid-stream-rate-limit"&&O!==void 0){let d=Math.max(1,Math.ceil((O-T)/1000));v=Math.min(v,d)}let h=Math.floor(v/60),m=v%60,l=B==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${h}m ${m}s.`:B==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${h}m ${m}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${h}m ${m}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(v)}})}function M8(L){let B=L?.resetCreditsAvailable;return typeof B==="number"&&Number.isFinite(B)?B:void 0}async function a4(L){let B=QY(L.storage),O=Date.now(),T=Q0.peekMainForPolicy(L.mainAccountIdentity),_=D9(T?.quota,T?.checkedAt,L.sidebarState.main.quota,L.sidebarState.main.mainAccountId,L.mainAccountIdentity),b=B?$Y(T?.quota,L.storage,void 0,O):void 0,v=L.mainCustodyRefused?[]:[{accountId:"main",wireAccountId:L.mainAccountIdentity,access:L.primaryAccess,provenance:L.primaryProvenance,keepwarmAccountKey:"main",quota:_.quota,quotaCheckedAt:_.quotaCheckedAt,reservePercent:Q8(L.storage),configuredOrder:0,resetCreditsApplicable:M8(_.quota),killswitchPasses:b}],h=await $0.getUsableFallbackAccounts(L.storage);if(!L.storage)return v;for(let m of h){let l=await e1(m,L.storage);if(l===g1||l===t1)continue;let d=L.sidebarState.fallbacks.find((H1)=>H1.id===m.id),H0=Q0.peekFallbackForPolicy(m.id,m.accountId),l0=D9(H0?.quota,H0?.checkedAt,d?.quota,d?.accountId,m.accountId),_0=B?$Y(H0?.quota,L.storage,m.id,O):void 0;v.push({accountId:m.id,wireAccountId:m.accountId,access:l.token,provenance:l.provenance,keepwarmAccountKey:m.id,fallback:m,quota:l0.quota,quotaCheckedAt:l0.quotaCheckedAt,reservePercent:Q8(L.storage,m.id),configuredOrder:v.length,resetCreditsApplicable:M8(l0.quota),killswitchPasses:_0})}return v}function w8(L,B,O,T,_){let b=QY(_)?L.killswitchPasses:void 0;if(L.accountId==="main"){let l=Q0.peekMainForPolicy(L.wireAccountId),d=D9(l?.quota,l?.checkedAt,B.main.quota,B.main.mainAccountId,L.wireAccountId);return bX({quota:d.quota,quotaCheckedAt:d.quotaCheckedAt,status:O,now:T,killswitchPasses:b})}let v=B.fallbacks.find((l)=>l.id===L.accountId),h=Q0.peekFallbackForPolicy(L.accountId,L.wireAccountId),m=D9(h?.quota,h?.checkedAt,v?.quota,v?.accountId,L.wireAccountId);return bX({quota:m.quota,quotaCheckedAt:m.quotaCheckedAt,status:O,now:T,killswitchPasses:b})}function t4(L){return L.accountId==="main"?"main":L.keepwarmAccountKey}function A8(L){return Q0.isRateLimited(t4(L))}async function BX(L){let B=L.candidates.filter((m)=>!A8(m)),O=new Map(B.map((m)=>[m.accountId,m])),T=Object.fromEntries(B.map((m)=>[m.accountId,m.quotaCheckedAt])),_=Object.fromEntries(B.map((m)=>[m.accountId,m.wireAccountId])),b=new Set(L.excludeAccountIds),v,h=await v4({sessionId:L.sessionId,requestBytes:L.requestBytes,now:L.now,validPinnedAccountIds:[...O.keys()],excludeAccountIds:L.excludeAccountIds,quotaCheckedAtByAccount:T,wireAccountIdByAccount:_,choose:(m)=>{let l=B.filter((H0)=>!b.has(H0.accountId));if(l.length===0)return;let d=sQ({candidates:l,pendingBytes:m,requestBytes:L.requestBytes,now:L.now,onEmptyWeightedSet:()=>{$1.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!d)return;return v={accountId:d.accountId,source:d.source,pendingBytes:m.get(d.accountId)??0},d}},p0);if(v&&h?.accountId===v.accountId)$1.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:GY(L.sessionId),accountId:v.accountId,source:v.source,requestBytes:L.requestBytes,pendingBytes:v.pendingBytes});return h?O.get(h.accountId):void 0}async function e4(L,B){let O=await $0.getUsableFallbackAccounts(L),T=[];if(!L)return{current:[],retained:[],skipped:[]};for(let d of O){let H0=await e1(d,L);if(H0===g1||H0===t1)continue;T.push({access:H0.token,provenance:H0.provenance,accountId:d.accountId,keepwarmAccountKey:d.id,quotaAccountId:d.id,fallback:d})}let _=T.filter((d)=>!Q0.isRateLimited(d.quotaAccountId)),b=QY(L)?_.filter((d)=>$Y(Q0.peekFallbackForPolicy(d.quotaAccountId,d.accountId)?.quota,L,d.quotaAccountId,Date.now())):_,v=new Map(B.fallbacks.map((d)=>[d.id,{quota:d.quota,accountId:d.accountId}])),h=[],m=[],l=Date.now();for(let d of b){let H0=v.get(d.quotaAccountId),l0=P8(Q0.peekFallbackForPolicy(d.quotaAccountId,d.accountId),H0?.quota,l,H0?.accountId,d.accountId);if(l0.exhausted)m.push({candidate:d,decision:l0});else h.push(d)}return{current:b,retained:h,skipped:m}}function R8(L,B){if(L.retained.length===0&&!B)return L.current;for(let{candidate:O,decision:T}of L.skipped)E8(O.quotaAccountId,T);return L.retained}async function T8(L,B){try{let O=Q9(L.headers);await O9(O,B.access,B.quotaAccountId,void 0,XY(L.headers))}catch{}}async function YU(L,B,O,T){for(let _ of T){let b;try{b=await q9(L,B,_.access,_.accountId,_.keepwarmAccountKey,_.provenance)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")throw v;if(B?.signal?.aborted)throw v;throw $1.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:_.quotaAccountId}),v}if(!JY(b.status,O))return $0.markUsed(_.fallback),{response:b,accessToken:_.access,quotaAccountId:_.quotaAccountId,activeId:_.keepwarmAccountKey};await T8(b,_),b.body?.cancel().catch(()=>{})}return}async function XU(L,B,O,T,_){if(!LY(L,B))return{response:O};if(!_.length)return{response:O};let b=O,v;for(let h of _){let m;try{m=await q9(L,B,h.access,h.accountId,h.keepwarmAccountKey,h.provenance)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")throw l;if(B?.signal?.aborted)throw l;return $1.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:h.quotaAccountId}),{response:b,...v}}if(b.body?.cancel().catch(()=>{}),b=m,v={accessToken:h.access,accountId:h.quotaAccountId},!JY(m.status,T))return $0.markUsed(h.fallback),{response:m,...v};await T8(m,h)}return{response:b,...v}}if(y){let L=[];for(let B of y.accounts)if(O0(B))L.push(B);Q0.seedFallbacksFromAccounts(L)}if(!z8)z8=!0,ZY(Q0,y).catch(()=>{}),E1(zY({respectBackoff:!0})).catch((L)=>z0.warn("boot quota seed failed",{pid:process.pid,error:t9(L)}));return J0.start(async()=>{let B=(await LQ(zY({readSidebarState:()=>a1(p0)}))).filter((O)=>!O.ok);if(B.length>0)z0.warn("background quota refresh completed with failures",{pid:process.pid,failures:B})},(L)=>{z0.warn("background quota refresh failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)})}),{apiKey:IF,async fetch(L,B){let O=F4(L,B),T=O4(O),_=O.get("x-parent-session-id")?.trim()||void 0,b=await s(),v=await P(),h=++N9;if(v.type!=="oauth")return fetch(L,B);B=await aF(L,B);let m=M&&m1(b)==="claustrum",l="",d,H0=!1;if(m){let G0=await H8(b);if(G0===g1||G0===t1)H0=!0;else l=G0.token,d=G0.provenance==="local"?void 0:G0.provenance}else{if(!v.access||(v.expires??0)<Date.now()){g0.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(v.access),expiresInMs:v.expires?v.expires-Date.now():void 0});try{let G0=await HY();v.access=G0.access,v.refresh=G0.refresh,v.expires=G0.expires}catch(G0){if(X8(G0))throw G0}}l=v.access??""}let _0=v.accountId??(l?z1(W1(l)??{}):void 0);if(h===N9)r0=_0;let H1=b?.routing?.mode??"main-first",D1,I0=await(()=>{return D1??=a1(p0),D1})();if(H1==="sticky-balanced"&&T&&LY(L,B)&&typeof B?.body==="string"){let G0=Buffer.byteLength(B.body,"utf8"),R0=await a4({storage:b,sidebarState:I0,primaryAccess:l,mainAccountIdentity:_0,mainCustodyRefused:H0,primaryProvenance:d}),E0=await BX({sessionId:T,requestBytes:G0,candidates:R0,now:Date.now()});if(E0){let b8=A8(E0)?{action:"migrate",reason:"exhausted"}:w8(E0,I0,void 0,Date.now(),b);if(b8.action==="migrate"){let y0=await BX({sessionId:T,requestBytes:G0,candidates:R0,excludeAccountIds:[E0.accountId],now:Date.now()});if(y0)$1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(T),fromAccountId:E0.accountId,toAccountId:y0.accountId,reason:b8.reason}),E0=y0}let G1=await q9(L,B,E0.access,E0.wireAccountId,E0.keepwarmAccountKey,E0.provenance),v8=async(y0,f1)=>{try{let JU=Q9(y0.headers);await O9(JU,f1.access,f1.accountId==="main"?void 0:f1.accountId,f1.accountId==="main"?f1.wireAccountId:void 0,XY(y0.headers))}catch{}};await v8(G1,E0);let h8=w8(E0,I0,G1.status,Date.now(),b);if((G1.status===401||G1.status===403||G1.status===429)&&h8.action==="migrate"){let y0=await BX({sessionId:T,requestBytes:G0,candidates:R0,excludeAccountIds:[E0.accountId],now:Date.now()});if(y0){$1.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:GY(T),fromAccountId:E0.accountId,toAccountId:y0.accountId,reason:h8.reason});let f1=G1;G1=await q9(L,B,y0.access,y0.wireAccountId,y0.keepwarmAccountKey,y0.provenance),f1.body?.cancel().catch(()=>{}),E0=y0,await v8(G1,E0)}}if(E0.fallback&&!JY(G1.status,b))$0.markUsed(E0.fallback);return await j8(T,_,E0.accountId,H1,b?.accounts).catch(()=>{}),G1}}let S0=P8(Q0.peekMainForPolicy(_0),I0.main.quota,Date.now(),I0.main.mainAccountId,_0),Y9=QY(b)&&!$Y(r4(_0),b,void 0,Date.now()),VY=Q0.isRateLimited("main"),C8,FX=()=>{return C8??=e4(b,I0),C8},Z1,X9,_8=!1,NY;if(H1==="fallback-first"&&LY(L,B)){_8=!0;let G0=await FX();NY=R8(G0,!Y9&&!VY&&!S0.exhausted);let R0=await YU(L,B,b,NY);if(R0)Z1=R0.response,X9={accessToken:R0.accessToken,accountId:R0.quotaAccountId,activeId:R0.activeId}}if(!Z1){let G0=S0.exhausted&&LY(L,B)&&(await FX()).retained.length>0;if(Y9||VY||G0){let R0=Y9?"killswitch":VY?"mid-stream-rate-limit":"quota-exhausted";if(R0==="quota-exhausted"&&S0.exhausted)E8("main",S0);$1.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:R0}),Z1=s4(b,R0,R0==="quota-exhausted"&&S0.exhausted?S0.resetAtMs:VY?Q0.rateLimitedUntil("main"):void 0)}else Z1=H0?new Response(null,{status:401}):await q9(L,B,l,_0,"main",d)}let I8=Boolean(X9),P9=Z1,S8=X9?.accessToken??l,k8=X9?.accountId,x8=X9?.activeId??"main";if(!X9&&!_8&&JY(Z1.status,b)){$1.debug("reactive fallback triggered",{pid:process.pid,status:Z1.status}),NY??=R8(await FX(),!1);let G0=await XU(L,B,Z1,b,NY),R0=G0.response;if(R0!==Z1){if(I8=!0,P9=R0,S8=G0.accessToken??l,k8=G0.accountId,G0.accountId)x8=G0.accountId}}try{let G0=Q9(P9.headers);if(I8)await O9(G0,S8,k8,void 0,XY(P9.headers));else await O9(G0,l,void 0,_0,XY(P9.headers))}catch{}return await j8(T,_,x8,H1,b?.accounts).catch(()=>{}),P9}}},methods:o0},"chat.headers":async(P,w)=>{if(P.model.providerID!=="openai")return;if(w.headers.originator="opencode",w.headers["User-Agent"]=`${P4(E9)} (${zX.platform()} ${zX.release()}; ${zX.arch()})`,w.headers["session-id"]=P.sessionID,W&&P.agent==="title")w.headers[b1.TITLE_HEADER]="true"},"chat.params":async(P,w)=>{if(P.model.providerID!=="openai")return;w.maxOutputTokens=void 0},config:async(P)=>{j0("commands").info("registering commands",{existing:Object.keys(P.command??{}).length,pid:process.pid}),P.command={...P.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(P)=>{if(j0("commands").info("command hook entered",{command:P.command,arguments:P.arguments,modal:S9.includes(P.command),hasCmdCtx:H!==null,pid:process.pid}),!S9.includes(P.command))return;if(!H)j0("commands").warn("command rejected: context not loaded",{command:P.command,pid:process.pid}),await p(P.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),V4();let w=P.command,j={...H,sessionId:P.sessionID,notify:(x)=>{uX(x,P.sessionID)}},M=await DX(w,P.arguments,j);if(N5(P.sessionID))uX(M,P.sessionID);else await p(P.sessionID,M.text);V4()}}}var QO=async(Y)=>{let X=s0();return JO(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},jM={id:"cortexkit-openai-auth",server:QO};export{O4 as resolveSidebarSessionId,W1 as parseJwtClaims,B4 as mergePushedQuotaMetadata,NM as getMainRefreshLockName,sF as findCachekeepFallbackAccount,z1 as extractAccountIdFromClaims,jM as default,fF as createResetTargetResolver,OM as buildSidebarState,m4 as buildSidebarMachineState,mF as buildResetRedemptionDeps,OF as __resetSweepFailureLogDedupeForTest,BM as __resetBootQuotaSeedForTest,eJ as __createCustodyRuntimeForTest,U1 as ResetTargetResolutionError,QO as OpenAIAuthPlugin,Y8 as MAIN_REFRESH_LOCK_TTL_MS,bF as MAIN_REFRESH_LEASE_TTL_MS,CF as EMPTY_BEARER_MESSAGE,JO as CodexAuthPlugin,U8 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};