@cortexkit/opencode-openai-auth 1.23.0 → 1.23.2

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 (234) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{index-897br01q.js → index-49ncs7dr.js} +1 -1
  3. package/dist/{index-s7dwe5n8.js → index-by5wfvqm.js} +20 -20
  4. package/dist/{index-bbrpg1ms.js → index-drm4dk5y.js} +1 -1
  5. package/dist/index-nd2ks7er.js +2 -0
  6. package/dist/index-t876xhkr.js +60 -0
  7. package/dist/{index-fasy4end.js → index-td4g5dc9.js} +1 -1
  8. package/dist/{index-7hcv94as.js → index-v8w8j1wx.js} +1 -1
  9. package/dist/{index-r31f36mn.js → index-v8wrmhyp.js} +1 -1
  10. package/dist/{index-bpx4spyr.js → index-wjp3q15r.js} +1 -1
  11. package/dist/{index-f340dq90.js → index-x00sxt2w.js} +10 -10
  12. package/dist/index.d.ts +4 -3
  13. package/dist/index.js +1 -1
  14. package/dist/{runtime-layout-B07ApQZL.d.ts → internal-DacVgEWs.d.ts} +86 -663
  15. package/dist/rpc/port-file.js +1 -1
  16. package/dist/rpc/protocol.js +1 -1
  17. package/dist/rpc/rpc-client.js +1 -1
  18. package/dist/runtime-layout-Dcbj_Rq3.d.ts +650 -0
  19. package/dist/{sidebar-state--OTpRzFd.d.ts → sidebar-state-L--CdbLi.d.ts} +4 -15
  20. package/dist/sidebar-state.d.ts +1 -1
  21. package/dist/sidebar-state.js +1 -1
  22. package/dist/tui-preferences.js +1 -1
  23. package/dist/tui.d.ts +5 -2
  24. package/dist/v2/server.d.ts +2 -1
  25. package/dist/v2/server.js +4 -4
  26. package/package.json +6 -6
  27. package/src/tui-compiled/raw/shared/054118b2705fdc20-ansi.js +98 -0
  28. package/src/tui-compiled/raw/shared/0895e780489c494d-window.js +33 -0
  29. package/src/tui-compiled/raw/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  30. package/src/tui-compiled/raw/shared/0c9533222cb4380c-namespace.js +224 -0
  31. package/src/tui-compiled/raw/shared/112607e46a5b5f58-accounts.js +393 -0
  32. package/src/tui-compiled/raw/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  33. package/src/tui-compiled/raw/shared/1547bd74f4214d2d-index.js +28 -0
  34. package/src/tui-compiled/raw/shared/1567207f323dc733-codex-http.js +44 -0
  35. package/src/tui-compiled/raw/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  36. package/src/tui-compiled/raw/shared/18df43cab4563acf-families.js +149 -0
  37. package/src/tui-compiled/raw/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  38. package/src/tui-compiled/raw/shared/1afd446e190ef85c-vault-messages.js +12 -0
  39. package/src/tui-compiled/raw/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  40. package/src/tui-compiled/raw/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  41. package/src/tui-compiled/raw/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  42. package/src/tui-compiled/raw/shared/22b2bce42f2d6806-handle.js +10 -0
  43. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  44. package/src/tui-compiled/raw/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  45. package/src/tui-compiled/raw/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  46. package/src/tui-compiled/raw/shared/2bb681e99c2721d7-registry.js +538 -0
  47. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +13 -20
  48. package/src/tui-compiled/raw/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  49. package/src/tui-compiled/raw/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  50. package/src/tui-compiled/raw/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  51. package/src/tui-compiled/raw/shared/3b31b36bf0877602-wording.js +120 -0
  52. package/src/tui-compiled/raw/shared/3c4c1a2d3fc92726-failure.js +59 -0
  53. package/src/tui-compiled/raw/shared/3dfe71eec6e0487d-presets.js +240 -0
  54. package/src/tui-compiled/raw/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  55. package/src/tui-compiled/raw/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  56. package/src/tui-compiled/raw/shared/4adf46e07e025363-axes.js +7 -0
  57. package/src/tui-compiled/raw/shared/4ba847b77580b1eb-confirm.js +21 -0
  58. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +48 -36
  59. package/src/tui-compiled/raw/shared/5018d4665e969588-limit-policy.js +159 -0
  60. package/src/tui-compiled/raw/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  61. package/src/tui-compiled/raw/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  62. package/src/tui-compiled/raw/shared/5d806e1a305d14f5-commands.js +879 -0
  63. package/src/tui-compiled/raw/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  64. package/src/tui-compiled/raw/shared/63c1ee7e70e85e8d-vault.js +1 -0
  65. package/src/tui-compiled/raw/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  66. package/src/tui-compiled/raw/shared/66937534c260d20b-stable-json.js +11 -0
  67. package/src/tui-compiled/raw/shared/7056acef1b021f19-bridge.js +10 -0
  68. package/src/tui-compiled/raw/shared/72d2ca42883809b4-marker.js +107 -0
  69. package/src/tui-compiled/raw/shared/775431e21f469203-record.js +3 -0
  70. package/src/tui-compiled/raw/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  71. package/src/tui-compiled/raw/shared/7b2a0471b29e4f5e-wake.js +47 -0
  72. package/src/tui-compiled/raw/shared/7b5d6afff4ff32b9-select.js +159 -0
  73. package/src/tui-compiled/raw/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  74. package/src/tui-compiled/raw/shared/7c98bde36aad4819-input-transformations.js +34 -0
  75. package/src/tui-compiled/raw/shared/7fb0418303f20a10-index.js +3 -0
  76. package/src/tui-compiled/raw/shared/806e12ccbad34388-pi-wait.js +51 -0
  77. package/src/tui-compiled/raw/shared/81ae201b724cac14-menu.js +73 -0
  78. package/src/tui-compiled/raw/shared/8349ed25dc629e97-scope.js +10 -0
  79. package/src/tui-compiled/raw/shared/86da3379973780b9-limit-provenance.js +60 -0
  80. package/src/tui-compiled/raw/shared/8aba66ed486d30a7-decide.js +425 -0
  81. package/src/tui-compiled/raw/shared/8c0c8df25a5dca1f-manager.js +735 -0
  82. package/src/tui-compiled/raw/shared/8c42bbec02f59636-vault-routing.js +212 -0
  83. package/src/tui-compiled/raw/shared/8ca6175bfae53e13-envelope.js +123 -0
  84. package/src/tui-compiled/raw/shared/8d0245e41049d83f-header-classifier.js +121 -0
  85. package/src/tui-compiled/raw/shared/9c162809179c7560-login.js +89 -0
  86. package/src/tui-compiled/raw/shared/a1f495296a4b756f-frame-turn.js +72 -0
  87. package/src/tui-compiled/raw/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  88. package/src/tui-compiled/raw/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  89. package/src/tui-compiled/raw/shared/adc5eeb5a8d28280-persistence.js +9 -0
  90. package/src/tui-compiled/raw/shared/b301c79e6378d1fb-vault.js +678 -0
  91. package/src/tui-compiled/raw/shared/b3c11de5f36e617a-reset.js +44 -0
  92. package/src/tui-compiled/raw/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  93. package/src/tui-compiled/raw/shared/bd4aef685681048c-duration.js +20 -0
  94. package/src/tui-compiled/raw/shared/bd5977eca210d2b8-index.js +662 -0
  95. package/src/tui-compiled/raw/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  96. package/src/tui-compiled/raw/shared/c66495424ad84aee-hold.js +25 -0
  97. package/src/tui-compiled/raw/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  98. package/src/tui-compiled/raw/shared/c9340fb545c4e5de-internal.js +73 -0
  99. package/src/tui-compiled/raw/shared/c954c6447b7b9b64-activity.js +52 -0
  100. package/src/tui-compiled/raw/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  101. package/src/tui-compiled/raw/shared/cec39ccddab4fe9c-labels.js +11 -0
  102. package/src/tui-compiled/raw/shared/cef0f2346957e83c-index.js +552 -0
  103. package/src/tui-compiled/raw/shared/cf7dedf24f902d68-dump-size.js +41 -0
  104. package/src/tui-compiled/raw/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  105. package/src/tui-compiled/raw/shared/d5b268767d330507-doctor.js +81 -0
  106. package/src/tui-compiled/raw/shared/d7ac5ca41f49121b-index.js +12 -0
  107. package/src/tui-compiled/raw/shared/d7fa77560855dee2-jitter.js +9 -0
  108. package/src/tui-compiled/raw/shared/de7f7d8803624369-path.js +31 -0
  109. package/src/tui-compiled/raw/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  110. package/src/tui-compiled/raw/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  111. package/src/tui-compiled/raw/shared/e2ae081583adfce3-dump.js +80 -0
  112. package/src/tui-compiled/raw/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  113. package/src/tui-compiled/raw/shared/e5229952fc12f647-codex-models.js +34 -0
  114. package/src/tui-compiled/raw/shared/e8fda84e90176436-uuid-v7.js +13 -0
  115. package/src/tui-compiled/raw/shared/ea56007991dbf068-terminal.js +19 -0
  116. package/src/tui-compiled/raw/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  117. package/src/tui-compiled/raw/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  118. package/src/tui-compiled/raw/shared/f1012265b3a768c7-merge-laws.js +31 -0
  119. package/src/tui-compiled/raw/shared/f2ca864fe967415a-cache-policy.js +198 -0
  120. package/src/tui-compiled/raw/shared/f317a4740f9d76f8-identity.js +21 -0
  121. package/src/tui-compiled/raw/shared/f607353c4126272a-routing-wait.js +19 -0
  122. package/src/tui-compiled/raw/shared/f6189f5c9aee31eb-decision.js +55 -0
  123. package/src/tui-compiled/raw/shared/f6d728f5e601f98b-request-history.js +120 -0
  124. package/src/tui-compiled/raw/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  125. package/src/tui-compiled/raw/shared/fda579e5a0a54165-codex-effort.js +60 -0
  126. package/src/tui-compiled/raw/sidebar-state.js +54 -4
  127. package/src/tui-compiled/raw/tui/v2-dialog.js +1 -1
  128. package/src/tui-compiled/raw/tui.tsx +27 -5
  129. package/src/tui-compiled/runtime/shared/054118b2705fdc20-ansi.js +98 -0
  130. package/src/tui-compiled/runtime/shared/0895e780489c494d-window.js +33 -0
  131. package/src/tui-compiled/runtime/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  132. package/src/tui-compiled/runtime/shared/0c9533222cb4380c-namespace.js +224 -0
  133. package/src/tui-compiled/runtime/shared/112607e46a5b5f58-accounts.js +393 -0
  134. package/src/tui-compiled/runtime/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  135. package/src/tui-compiled/runtime/shared/1547bd74f4214d2d-index.js +28 -0
  136. package/src/tui-compiled/runtime/shared/1567207f323dc733-codex-http.js +44 -0
  137. package/src/tui-compiled/runtime/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  138. package/src/tui-compiled/runtime/shared/18df43cab4563acf-families.js +149 -0
  139. package/src/tui-compiled/runtime/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  140. package/src/tui-compiled/runtime/shared/1afd446e190ef85c-vault-messages.js +12 -0
  141. package/src/tui-compiled/runtime/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  142. package/src/tui-compiled/runtime/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  143. package/src/tui-compiled/runtime/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  144. package/src/tui-compiled/runtime/shared/22b2bce42f2d6806-handle.js +10 -0
  145. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  146. package/src/tui-compiled/runtime/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  147. package/src/tui-compiled/runtime/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  148. package/src/tui-compiled/runtime/shared/2bb681e99c2721d7-registry.js +538 -0
  149. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +13 -20
  150. package/src/tui-compiled/runtime/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  151. package/src/tui-compiled/runtime/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  152. package/src/tui-compiled/runtime/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  153. package/src/tui-compiled/runtime/shared/3b31b36bf0877602-wording.js +120 -0
  154. package/src/tui-compiled/runtime/shared/3c4c1a2d3fc92726-failure.js +59 -0
  155. package/src/tui-compiled/runtime/shared/3dfe71eec6e0487d-presets.js +240 -0
  156. package/src/tui-compiled/runtime/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  157. package/src/tui-compiled/runtime/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  158. package/src/tui-compiled/runtime/shared/4adf46e07e025363-axes.js +7 -0
  159. package/src/tui-compiled/runtime/shared/4ba847b77580b1eb-confirm.js +21 -0
  160. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +48 -36
  161. package/src/tui-compiled/runtime/shared/5018d4665e969588-limit-policy.js +159 -0
  162. package/src/tui-compiled/runtime/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  163. package/src/tui-compiled/runtime/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  164. package/src/tui-compiled/runtime/shared/5d806e1a305d14f5-commands.js +879 -0
  165. package/src/tui-compiled/runtime/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  166. package/src/tui-compiled/runtime/shared/63c1ee7e70e85e8d-vault.js +1 -0
  167. package/src/tui-compiled/runtime/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  168. package/src/tui-compiled/runtime/shared/66937534c260d20b-stable-json.js +11 -0
  169. package/src/tui-compiled/runtime/shared/7056acef1b021f19-bridge.js +10 -0
  170. package/src/tui-compiled/runtime/shared/72d2ca42883809b4-marker.js +107 -0
  171. package/src/tui-compiled/runtime/shared/775431e21f469203-record.js +3 -0
  172. package/src/tui-compiled/runtime/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  173. package/src/tui-compiled/runtime/shared/7b2a0471b29e4f5e-wake.js +47 -0
  174. package/src/tui-compiled/runtime/shared/7b5d6afff4ff32b9-select.js +159 -0
  175. package/src/tui-compiled/runtime/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  176. package/src/tui-compiled/runtime/shared/7c98bde36aad4819-input-transformations.js +34 -0
  177. package/src/tui-compiled/runtime/shared/7fb0418303f20a10-index.js +3 -0
  178. package/src/tui-compiled/runtime/shared/806e12ccbad34388-pi-wait.js +51 -0
  179. package/src/tui-compiled/runtime/shared/81ae201b724cac14-menu.js +73 -0
  180. package/src/tui-compiled/runtime/shared/8349ed25dc629e97-scope.js +10 -0
  181. package/src/tui-compiled/runtime/shared/86da3379973780b9-limit-provenance.js +60 -0
  182. package/src/tui-compiled/runtime/shared/8aba66ed486d30a7-decide.js +425 -0
  183. package/src/tui-compiled/runtime/shared/8c0c8df25a5dca1f-manager.js +735 -0
  184. package/src/tui-compiled/runtime/shared/8c42bbec02f59636-vault-routing.js +212 -0
  185. package/src/tui-compiled/runtime/shared/8ca6175bfae53e13-envelope.js +123 -0
  186. package/src/tui-compiled/runtime/shared/8d0245e41049d83f-header-classifier.js +121 -0
  187. package/src/tui-compiled/runtime/shared/9c162809179c7560-login.js +89 -0
  188. package/src/tui-compiled/runtime/shared/a1f495296a4b756f-frame-turn.js +72 -0
  189. package/src/tui-compiled/runtime/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  190. package/src/tui-compiled/runtime/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  191. package/src/tui-compiled/runtime/shared/adc5eeb5a8d28280-persistence.js +9 -0
  192. package/src/tui-compiled/runtime/shared/b301c79e6378d1fb-vault.js +678 -0
  193. package/src/tui-compiled/runtime/shared/b3c11de5f36e617a-reset.js +44 -0
  194. package/src/tui-compiled/runtime/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  195. package/src/tui-compiled/runtime/shared/bd4aef685681048c-duration.js +20 -0
  196. package/src/tui-compiled/runtime/shared/bd5977eca210d2b8-index.js +662 -0
  197. package/src/tui-compiled/runtime/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  198. package/src/tui-compiled/runtime/shared/c66495424ad84aee-hold.js +25 -0
  199. package/src/tui-compiled/runtime/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  200. package/src/tui-compiled/runtime/shared/c9340fb545c4e5de-internal.js +73 -0
  201. package/src/tui-compiled/runtime/shared/c954c6447b7b9b64-activity.js +52 -0
  202. package/src/tui-compiled/runtime/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  203. package/src/tui-compiled/runtime/shared/cec39ccddab4fe9c-labels.js +11 -0
  204. package/src/tui-compiled/runtime/shared/cef0f2346957e83c-index.js +552 -0
  205. package/src/tui-compiled/runtime/shared/cf7dedf24f902d68-dump-size.js +41 -0
  206. package/src/tui-compiled/runtime/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  207. package/src/tui-compiled/runtime/shared/d5b268767d330507-doctor.js +81 -0
  208. package/src/tui-compiled/runtime/shared/d7ac5ca41f49121b-index.js +12 -0
  209. package/src/tui-compiled/runtime/shared/d7fa77560855dee2-jitter.js +9 -0
  210. package/src/tui-compiled/runtime/shared/de7f7d8803624369-path.js +31 -0
  211. package/src/tui-compiled/runtime/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  212. package/src/tui-compiled/runtime/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  213. package/src/tui-compiled/runtime/shared/e2ae081583adfce3-dump.js +80 -0
  214. package/src/tui-compiled/runtime/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  215. package/src/tui-compiled/runtime/shared/e5229952fc12f647-codex-models.js +34 -0
  216. package/src/tui-compiled/runtime/shared/e8fda84e90176436-uuid-v7.js +13 -0
  217. package/src/tui-compiled/runtime/shared/ea56007991dbf068-terminal.js +19 -0
  218. package/src/tui-compiled/runtime/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  219. package/src/tui-compiled/runtime/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  220. package/src/tui-compiled/runtime/shared/f1012265b3a768c7-merge-laws.js +31 -0
  221. package/src/tui-compiled/runtime/shared/f2ca864fe967415a-cache-policy.js +198 -0
  222. package/src/tui-compiled/runtime/shared/f317a4740f9d76f8-identity.js +21 -0
  223. package/src/tui-compiled/runtime/shared/f607353c4126272a-routing-wait.js +19 -0
  224. package/src/tui-compiled/runtime/shared/f6189f5c9aee31eb-decision.js +55 -0
  225. package/src/tui-compiled/runtime/shared/f6d728f5e601f98b-request-history.js +120 -0
  226. package/src/tui-compiled/runtime/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  227. package/src/tui-compiled/runtime/shared/fda579e5a0a54165-codex-effort.js +60 -0
  228. package/src/tui-compiled/runtime/sidebar-state.js +54 -4
  229. package/src/tui-compiled/runtime/tui/v2-dialog.js +1 -1
  230. package/src/tui-compiled/runtime/tui.js +11 -4
  231. package/dist/index-2z4dbnsf.js +0 -60
  232. package/dist/index-x25m9spd.js +0 -2
  233. package/dist/map-D5PHhv4z.d.ts +0 -72
  234. /package/dist/{index-sx9jjkry.js → index-4ktepxn1.js} +0 -0
@@ -0,0 +1,60 @@
1
+ import{$b as Z5,Aa as a$,Ac as nz,Bb as SJ,Cb as MK,Cc as X$,Db as IJ,Dc as LJ,Ec as H4,Fa as t$,Fc as wK,Ga as e$,Gb as U3,Gc as x1,Ha as Y5,Hb as H3,Ia as J5,Ib as B3,Ic as $5,Ja as az,Jc as I$,Ka as K4,Kb as yW,Kc as b$,La as U9,Lc as Q5,Ma as W1,Mb as W5,Mc as SK,Na as GJ,Nc as z3,Oa as C1,Ob as F$,Oc as IK,Pa as zJ,Pb as m1,Pc as t4,Qa as WJ,Qb as $9,Qc as fY,Ra as KJ,Rb as Gz,Rc as PY,Sa as UJ,Sb as I8,Sc as qY,Ta as HJ,Tb as kY,Tc as G4,Ua as gY,Ub as xY,Uc as k5,Va as _K,Vb as h1,Vc as e4,Wa as DK,Wc as W3,Xa as OK,Xc as G5,Ya as PK,Za as kW,Zb as v8,_a as b8,_b as qJ,_c as bK,ac as RJ,bb as j$,cb as _J,cd as kK,da as Q4,db as xW,dc as TK,ea as n4,eb as hW,ec as RK,ed as xK,fa as $K,fb as vW,fc as bJ,fd as hK,ga as e0,gc as yJ,gd as rK,ha as Iz,hb as A7,hd as JW,ia as x5,ib as wJ,ic as uz,id as sK,jb as qK,jc as pz,jd as aK,kc as b7,kd as WW,la as Q0,lc as k7,ma as GW,mc as G3,nc as _9,pc as kJ,qa as ZK,qc as B4,rc as C5,sa as kz,sc as w5,ta as xz,tb as F9,tc as S5,ua as vY,uc as I5,va as yY,vb as EK,vc as b5,wa as zW,xa as r$,xb as h8,xc as lz,ya as PJ,yc as dz,za as s$,zb as AK,zc as iz}from"./index-by5wfvqm.js";import{Ad as LW,Bd as gK,Cd as fK,Dd as mK,Id as mY,Jd as cY,Kd as cK,Ld as uK,Od as pK,Pd as lK,Qd as dK,Sd as D9,Td as $8,Ud as iK,Vd as nK,Wd as n1,Xd as oK,od as u7,qd as q5,sd as m6,td as vK,wd as yK}from"./index-nd2ks7er.js";import{$e as c$,$f as c6,Af as p4,Ag as fz,Be as g$,Bf as n8,Bg as mz,Ce as f$,Cf as f3,Cg as cz,De as H9,Df as w1,Ef as J4,Ff as s3,Gf as n6,Hf as a4,If as YW,Jf as y6,Kf as J$,Le as m$,Lf as n0,Mf as s8,Nf as HK,Qf as S$,Rf as k1,Sf as BK,Tf as V9,Ue as w$,Vf as S7,We as X8,Wf as x8,Xe as GK,Xf as I7,Ye as r6,Yf as d1,Ze as Q3,Zf as j9,_e as zK,_f as U1,af as u$,ag as VK,bf as R6,bg as NK,cf as C6,cg as R5,de as p1,df as b1,dg as bz,ef as p$,eg as g6,fe as $4,ff as l$,fg as t0,gf as d$,gg as I1,hf as i$,hg as OJ,if as n$,jf as o$,kf as B9,kg as LK,le as MY,lf as l1,me as Sz,mf as R4,mg as xJ,nf as DY,ng as U4,of as c0,og as U6,pf as WK,pg as b6,qe as C7,qf as k8,qg as hz,rf as Y8,rg as w8,sf as KK,sg as jK,te as Y$,uf as UK,ug as vz,vf as a0,vg as yz,wf as u4,xf as K1,xg as FK,yf as i8,yg as gz,zf as e1,zg as w7}from"./index-x00sxt2w.js";import{Hg as XK,Mg as e3}from"./index-49ncs7dr.js";import{Rg as U5,Sg as H5,Tg as B5,Ug as TW,Vg as QK,Wg as f6,Xg as RW,Yg as CW}from"./index-v8wrmhyp.js";import{gh as c7,lh as E4,nh as X5}from"./index-wjp3q15r.js";import{rh as Z9,th as U0}from"./index-td4g5dc9.js";import{Hh as V5,Jh as CK}from"./index-j700j6at.js";import{Lh as cJ}from"./index-q2czrasr.js";import{randomUUID as e7}from"node:crypto";import{statSync as GF}from"node:fs";import Y3 from"node:os";var BJ={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},q6={...BJ,overrides:{host:!0}},v6={...BJ,overrides:{host:!0,isolatedHosts:["pi"]}},c4={hosts:"OpenCode 1 only",project:"user-only"},m3=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),E6=(...Y)=>m3(["opencode-store","pi-store"],Y),i0=(...Y)=>m3(["opencode-store"],Y),T0=f3({plugin:"openai-auth",settings:{routing_mode:{...q6,value:e1(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:E6(["routing","mode"])},max_same_account_wait:{...q6,value:e1(["off","15m","cache"]),default:"15m",legacy:E6(["routing","maxSameAccountWait"])},wait_for_reset:{...q6,value:a0(),default:!1,legacy:[]},fallback_on:{...q6,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:p4(u4()),default:[401,403,429],legacy:E6(["fallbackOn"])},refresh_enabled:{...c4,hosts:"OpenCode 1 legacy fallback refresh only",value:a0(),default:!0,legacy:i0(["refresh","enabled"])},refresh_before_expiry_minutes:{...q6,value:K1(),default:240,legacy:E6(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...q6,value:a0(),default:!0,legacy:E6(["quota","enabled"])},quota_check_interval_minutes:{...c4,hosts:"OpenCode 1 legacy quota freshness and polling only",value:K1({min:1}),default:5,legacy:i0(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...q6,value:p4(n8({window:e1(["primary","secondary"]),floor:K1()})),default:[],legacy:E6(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...q6,value:a0(),default:!1,legacy:E6(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...c4,value:a0(),default:!0,legacy:i0(["costZeroing","enabled"])},killswitch_enabled:{...q6,value:a0(),default:!1,legacy:E6(["killswitch","enabled"])},killswitch_default_primary:{...q6,value:K1(),default:5,legacy:E6(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...q6,value:K1(),default:10,legacy:E6(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...BJ,value:p4(n8({account:i8(),host:e1(["opencode","pi","both"]),primary:K1(),secondary:K1()})),default:[],legacy:E6(["killswitch","accounts"])},cache_keep_enabled:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...v6,value:p4(n8({start_hour:u4({min:0,max:23}),end_hour:u4({min:0,max:23})})),default:[],legacy:i0(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...v6,value:e1(["error","warn","info","debug","trace","default"]),default:"default",legacy:i0(["logging","level"])},request_dumps:{...v6,value:a0(),default:!1,legacy:i0(["dump"],["dump","enabled"])},dump_dir:{...v6,value:i8(),default:"",legacy:i0(["dumpDir"])},dump_max_bytes:{...v6,value:u4({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:i0(["dumpMaxBytes"])},web_sockets:{...c4,value:a0(),default:!1,legacy:i0(["webSockets"])},raw_web_socket:{...c4,value:a0(),default:!1,legacy:i0(["rawWebSocket"])},responses_lite:{...v6,value:a0(),default:!1,legacy:i0(["responsesLite"])},codex_api_endpoint:{...v6,value:i8(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:i0(["codexApiEndpoint"])}}});import{chmod as RU,mkdir as CU}from"node:fs/promises";import{join as wU}from"node:path";import{existsSync as p3,readFileSync as ZU}from"node:fs";import{readFileSync as VU}from"node:fs";var c3="Settings moved to ";function NU(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(c3)||!J.endsWith("."))return;return J.slice(c3.length,-1)}function LU(Y){try{return NU(VU(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function u3(Y,J){let X=LU(Y);return X!==void 0&&n6(X)===n6(J)}function jU(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function FU(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!jU(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function _U(Y,J){return Object.values(T0.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&FU(Y,$.path)))}function DU(Y){try{return _U(JSON.parse(ZU(Y.configPath,"utf8")),Y.host)}catch{return!1}}function o8(Y){let J=p3(Y.target),X=Y.sources.some((K)=>u3(K.configPath,Y.target)),$=Y.sources.filter((K)=>p3(K.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(DU);return{kind:J?"target-exists":X?"target-removed":Q?"move-needed":"no-source",completed:J||X,targetExists:J,noteNamesTarget:X,sourcePresent:Q,preExistingFile:z,removedFile:G}}function r8(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function l3(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function VJ(Y,J){let X=U1(Y,J);return{primary:l3(X.primary),secondary:l3(X.secondary)}}function d3(Y,J,X,$){if(!r8(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function i3(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,K)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,H=r8(z.value)?z.value:{},V=r8(H.killswitch)?H.killswitch:void 0,F={killswitch:H.killswitch},Z=V?.schema===s8,N=Z?VJ({killswitch:{...V,accounts:void 0}}):VJ(F);if(X.push({source:K,floors:N}),!Z)d3(V?.main,"killswitch.main",K,J.unmapped);if(!r8(V?.accounts))return;for(let j of Object.keys(V.accounts)){let P=`killswitch.accounts.${j}`;if(!Z&&j==="main"){J.unmapped.push({source:K,key:P,reason:"shadowed"});continue}if(!Z)d3(V.accounts[j],P,K,J.unmapped);$.push({account:j,host:U,...VJ(F,j==="main"?void 0:j)})}});for(let[z,K]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===K))continue;for(let{source:U,floors:H}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:H[z]})}let Q=[];for(let z of $){let K=z.account.startsWith("vault:")?Q.find((U)=>U.account===z.account&&U.host!==z.host&&U.primary===z.primary&&U.secondary===z.secondary):void 0;if(K)K.host="both";else Q.push(z)}let G=X[0];if(G&&Q.length>0)J.entries.push({source:G.source,setting:"killswitch_account_floors",value:Q});return J}function H1(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function n3(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!H1(J))throw Error("Settings source is not an object");return J}function Y4(Y,J){let X=Y;for(let $ of J){if(!H1(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function l4(Y,J,X=!1){switch(Y.kind){case"boolean":return typeof J==="boolean";case"string":return typeof J==="string";case"integer":case"number":return typeof J==="number"&&Number.isFinite(J)&&(Y.kind!=="integer"||Number.isInteger(J))&&(Y.min===void 0||J>=Y.min)&&(Y.max===void 0||J<=Y.max);case"oneOf":return typeof J==="string"&&Y.values.includes(J);case"list":return Array.isArray(J)&&Array.from(J).every(($)=>l4(Y.item,$,!0));case"object":return H1(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&l4(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return H1(J)&&Object.values(J).every(($)=>l4(Y.value,$,!0))}}class t8 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function a8(Y,J){throw new t8(Y,J)}function o3(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return a8(J,X)}function OU(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=Y4(Y,[...G,$]),K=Y4(Y,[...G,Q]);for(let[H,V]of[[$,z],[Q,K]])if(V===null)J([...G,H].join("."),"invalid");if(z!=null&&K!=null)J([...G,Q].join("."),"shadowed");let U=z??K;if(U==null)continue;X.push({window:$,floor:o3(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function PU(Y,J,X){let $=Y4(Y,[J,"startHour"]),Q=Y4(Y,[J,"endHour"]);if($===void 0&&Q===void 0)return[];let G,z;try{G=Number($),z=Number(Q)}catch{G=Number.NaN,z=Number.NaN}if(Number.isInteger(G)&&G>=0&&G<=23&&Number.isInteger(z)&&z>=0&&z<=23&&G!==z)return[{start_hour:G,end_hour:z}];if($!==void 0)X(`${J}.startHour`,"invalid");if(Q!==void 0)X(`${J}.endHour`,"invalid");return[]}function qU(Y,J,X){let $=T0.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return OU(J,X);let G=H1(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return PU(J,G,X);let z=$.legacy[0];if(!z)return a8(Y);let K=z.path;if(Y.startsWith("cache_keep_"))K=[G,...K.slice(1)];if(Y==="request_dumps")K=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=Y4(J,K),H=K.join(".");if(U===void 0)return Q;if(Y==="max_same_account_wait"){if(U===0)return"off";if(U===15)return"15m";if(U==="max")return"cache"}else if(Y==="fallback_on"){if(Array.isArray(U)){let V=U.filter((F)=>Number.isInteger(F));if(V.length!==U.length)X(H,"invalid");return V.length?V:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let V=o3(U,Y,H);return Y==="quota_check_interval_minutes"?Math.max(1,V):V}}else if(Y==="quota_fail_closed_on_unknown"){if(U!=null)return Boolean(U)}else if(Y==="dump_dir"||Y==="codex_api_endpoint"){if(typeof U==="string"&&U.trim())return U.trim()}else if(l4($.value,U))return U;return X(H,"invalid"),Q}var EU=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),AU=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function MU(Y,J,X){let $=new Set;for(let G of Object.values(T0.settings))for(let z of G.legacy){let K=z.path.join(".");if($.add(K),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&Y4(Y,z.path)!==void 0){if(K==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(K,"other-host")}}let Q=(G,z="")=>{for(let[K,U]of Object.entries(G)){let H=z?`${z}.${K}`:K;if(!z&&EU.has(K)||AU.has(H)||H==="killswitch.schema")continue;if($.has(H))continue;if([...$].some((V)=>V.startsWith(`${H}.`)))if(H1(U))Q(U,H);else X(H,"invalid");else X(H,"retired")}};if(Q(Y),J==="opencode"&&H1(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function r3(Y){let J={entries:[],unmapped:[]},X=Y.flatMap((Q,G)=>{if(!Q.present)return[];if(Q.host!=="opencode"&&Q.host!=="pi")throw Error("Unsupported settings source host");if(!H1(Q.value))throw Error("Settings source is not an object");let z=(K,U)=>{if(!J.unmapped.some((H)=>H.source===G&&H.key===K&&H.reason===U))J.unmapped.push({source:G,key:K,reason:U})};return MU(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(T0.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=T0.settings[Q],z=X.filter((K)=>G.legacy.some((U)=>U.source===`${K.host}-store`)).map((K)=>({source:K.source,value:qU(Q,K.store,K.report)}));if(z.every((K)=>JSON.stringify(K.value)===JSON.stringify(G.default)))continue;for(let K of z)J.entries.push({...K,setting:Q})}let $=i3(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(T0.settings,Q.setting))a8(Q.setting);if(!l4(T0.settings[Q.setting].value,Q.value))a8(Q.setting)}return J}class NJ extends Error{host;path;code;constructor(Y,J,X){super(`Settings source ${Y} ${J}: ${X}`);this.host=Y;this.path=J;this.code=X}}function a3(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function TU(Y,J){if(Y instanceof NJ)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof t8)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=a3(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function t3({install:Y,fence:J,log:X}){if(Y.separate||Y.sources.length===0)return;let $=[...Y.sources].sort((G,z)=>Number(G.host==="pi")-Number(z.host==="pi")).map((G)=>({host:G.host,path:G.configPath,locks:[{path:G.configPath,name:"save"},{path:G.statePath,name:"save"}],read(z){try{return n3(z)}catch(K){throw new NJ(G.host,G.configPath,K instanceof Error&&K.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await s3({definition:T0,target:Y.target,separateInstall:!1,sources:$,map:r3,fence:J,log:{warn(){},info(){}}});for(let G of Q.unmapped)X.warn(`Settings move: ${$[G.source]?.host??"unknown"} ${G.key}: ${G.reason}`);for(let G of Q.noteFailures){let z=$.find((K)=>`${K.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${a3(G.error)}`)}if(Q.outcome==="failed"){Q.failure=TU(Q.cause,$);let G=Q.failure;X.warn(G.kind==="setting"?`Settings move failed: cannot move setting ${G.setting}`:("host"in G)?`Settings move failed: ${G.host} ${G.path}: ${G.code}`:`Settings move failed: ${G.code}`)}return Q}class Y9 extends Error{folder;constructor(Y,J){let X=J instanceof Error?J.message:String(J);super(`Cannot record settings authority in ${Y}: ${X}`,{cause:J});this.folder=Y;this.name="SettingsAuthorityRefusal"}}var $$=Symbol.for("@cortexkit/openai-auth/settings-authority"),Q$=globalThis,e8=Q$[$$]??new Map;Q$[$$]=e8;function d4(Y){return e8.get(n6(Y))}function G$(Y){let J=n6(Y.install.configIdentity),X=e8.get(J);if(X)return X;let $=Promise.resolve().then(()=>SU(Y));return e8.set(J,$),$}async function SU({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return J$(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let K=X$(J),U=()=>{return G.completion=o8(Y),G.completion},H=(V)=>V.completed||!V.sourcePresent;try{return await CU(K,{recursive:!0,mode:448}),await RU(K,448),await e3(wU(K,"settings-authority"),{name:"settings-authority",...Y$},async(V)=>{if(!H(U()))if(G.fence=await LJ({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await t3({install:Y,log:$,async fence(){let N=await LJ({...Q,stateHome:J});if(!N.open)G.fence=N;return N.open}})}catch(N){G.move={outcome:"failed",cause:N,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[],failure:{kind:"cause",code:"SETTINGS_MOVE_FAILED"}}}let F=G.move?.outcome,Z=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||Z.completed?"shared":"legacy"}else G.decision="legacy";await V.assertOwned(),await X(G.decision)}),z()}catch(V){if(!H(U()))throw new Y9(K,V);return G.decision="shared",z()}}var B1=Object.freeze({file:(Y)=>`Settings file: ${Y}`,separate:"Settings stay in this install's account store.",legacyProcess:"Settings stay in the old account store because another process still uses it.",legacyBusy:"Settings stay in the old account store because the stores were busy.",legacySetting:(Y)=>`Settings stay in the old account store because ${Y} couldn't be moved.`,legacyFailed:(Y)=>`Settings stay in the old account store because the move failed: ${Y}.`,sharedMissing:"No settings file, so defaults are in use.",sharedMoved:"Settings were moved to the settings file in this process.",sharedFound:"Settings file found.",waitForResetOn:"wait_for_reset is on: when every account is at a usage limit with a known reset, the turn waits for the reset.",preExistingFile:(Y)=>`Settings come from ${Y}. Preferences in the old account store weren't copied, because this file already existed.`,removedFile:(Y)=>`The settings file ${Y} was removed, so defaults are in use. Old preferences aren't copied again.`,refused:(Y,J)=>`openai-auth didn't start. Process records folder: ${Y}. Cause: ${J}`,report:{"unknown-key":(Y)=>`Unknown settings key: ${Y}.`,"override-not-allowed":(Y)=>`Settings override not allowed: ${Y}.`,"user-only-in-project":(Y)=>`User-only setting found in a project file: ${Y}.`,"invalid-value":(Y)=>`Invalid settings value: ${Y}.`,"invalid-schema-version":(Y)=>`Invalid settings schema version: ${Y}.`,"newer-version-key-ignored":(Y)=>`Settings key from a newer version ignored: ${Y}.`,"duplicate-key":(Y)=>`Duplicate settings key: ${Y}.`,unparseable:(Y)=>`The settings file ${Y} can't be parsed.`,unreadable:(Y)=>`The settings file ${Y} can't be read.`},checks:{duplicateFloors:"Invalid killswitch_account_floors: duplicate account and host pair.",localBoth:"Invalid killswitch_account_floors: only vault accounts may use host both.",duplicateQuota:"Invalid quota_minimum_remaining: duplicate quota window.",warmWindow:"Invalid cache_keep_window: use at most one window with unequal hours."},refusal:{"settings-unparseable":"The settings file can't be read. Fix it or remove it, then try again.","settings-newer-version":"The settings file is from a newer openai-auth. Update openai-auth to change settings.","settings-invalid-value":"That value isn't allowed for this setting.","settings-busy":"The settings file is busy. Try again.","settings-unavailable":"Settings can't be saved for this install."}});function J9(Y){return B1.refusal[Y]}function IU(Y){let J=B1;if(Y.reason==="invalid-value"&&Y.keyPath.length===1)switch(Y.keyPath[0]){case"killswitch_account_floors":if(Y.detail==="Duplicate account and host pair")return J.checks.duplicateFloors;if(Y.detail==="Only vault accounts may use host both")return J.checks.localBoth;break;case"quota_minimum_remaining":if(Y.detail==="Duplicate quota window")return J.checks.duplicateQuota;break;case"cache_keep_window":if(Y.detail==="Use at most one window with unequal hours")return J.checks.warmWindow}let X=Y.reason==="unparseable"||Y.reason==="unreadable"?Y.file.path:Y.keyPath.length?Y.keyPath.join("."):Y.file.path;return J.report[Y.reason](X)}function bU(Y,J,X=!1){let $=B1;if(Y.decision==="separate")return $.separate;if(Y.decision==="shared"){if(!J?.targetExists)return $.sharedMissing;return Y.ranMove&&Y.move?.outcome==="moved"&&!X?$.sharedMoved:$.sharedFound}if(Y.move?.outcome==="busy")return $.legacyBusy;if(Y.move?.outcome==="fence-closed"||Y.fence?.open===!1)return $.legacyProcess;let Q=Y.move?.failure;if(Q?.kind==="setting")return $.legacySetting(Q.setting);let G=Q?.kind==="cause"?"path"in Q?`${Q.host} ${Q.path}: ${Q.code}`:Q.code:"SETTINGS_MOVE_FAILED";return $.legacyFailed(G)}var z$=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),W$=globalThis,i4=W$[z$]??{logged:new Set,sawTargetMissing:new Set};W$[z$]=i4;async function K$({configPath:Y,snapshot:J,log:X}){let $=d4(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof Y9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let H=U.cause;return{lines:[B1.refused(String(U.folder),H instanceof Error?H.message:String(H))]}}throw U}if(Q.decision==="separate")return{lines:[B1.separate]};let G=Q.decision==="shared"?o8(Q.install):Q.completion,z=n6(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)i4.sawTargetMissing.add(z);let K=[B1.file(Q.install.target),bU(Q,G,i4.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let H=B1[U](Q.install.target);K.push(H);let V=`${U}:${n6(Q.install.target)}`;if(!i4.logged.has(V))i4.logged.add(V),X.warn(H)}if(await J?.refresh(),K.push(...J?.report().map(IU)??[]),J?.get("wait_for_reset"))K.push(B1.waitForResetOn)}return{lines:K}}var m0=(Y)=>Q0(Y)?Y:{},kU=["primary","secondary"];function U$(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(m0(G)).filter(([,z])=>z!==0))]));for(let{account:Q}of Y.get("killswitch_account_floors"))if(!Object.hasOwn($,Q))Object.defineProperty($,Q,{value:{},enumerable:!0,writable:!0,configurable:!0});return{routing:J,killswitch:{...X,accounts:$}}}function xU(Y){let J=new Map,X=(K,U)=>{let H=J.get(K)??new Set;H.add(U),J.set(K,H)},$=!1,Q=!0,G=(K,U=!1)=>{if(!Q)return;if(K[0]!=="killswitch"||K[1]!=="accounts")return;$=!0;let[,,H,V]=K;if(U&&H!==void 0&&(V==="primary"||V==="secondary"))X(H,V)},z=(K,U)=>new Proxy(K,{ownKeys(H){return G(U),Reflect.ownKeys(H)},get(H,V){let F=Reflect.get(H,V);return typeof V==="string"&&Q0(F)?z(F,[...U,V]):F},set(H,V,F){if(typeof V==="string")G([...U,V],!0);return Reflect.set(H,V,F)},deleteProperty(H,V){if(typeof V==="string")G([...U,V],!0);return Reflect.deleteProperty(H,V)}});return{value:z(Y,[]),windows:J,add:X,touched:()=>$,finish:()=>{Q=!1}}}function o4(Y){let{host:J,snapshot:X}=Y,$=Y.writer??J4(T0,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),U$(X)},async update(Q){try{await X.refresh();let G=U$(X),z=xU(structuredClone(G)),K=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(K)),H=[],V=m0(U.routing),F=m0(G.routing);if(V.mode!==F.mode)H.push({setting:"routing_mode",value:V.mode});if(V.maxSameAccountWait!==F.maxSameAccountWait)H.push({setting:"max_same_account_wait",value:V.maxSameAccountWait===0?"off":V.maxSameAccountWait==="max"?"cache":"15m"});let Z=m0(U.killswitch);if(Z.enabled!==m0(G.killswitch).enabled)H.push({setting:"killswitch_enabled",value:Z.enabled});let N=m0(m0(G.killswitch).accounts),j=m0(Z.accounts);for(let v of new Set([...Object.keys(N),...Object.keys(j)])){let y=Object.hasOwn(N,v)&&!Object.hasOwn(j,v)&&!z.windows.has(v);for(let I of kU)if(y||!Object.is(m0(N[v])[I],m0(j[v])[I]))z.add(v,I)}let P=z.touched()||z.windows.size>0;if(P){if(X.report().some((v)=>v.keyPath[0]==="killswitch_account_floors"||v.reason==="unreadable"||v.reason==="unparseable"))throw new w1("settings-invalid-value",Y.file)}await $.update((v)=>{let y=[...H];if(P){let I=v.status==="ready"&&Object.hasOwn(v.document,"killswitch_account_floors")?v.document.killswitch_account_floors:T0.settings.killswitch_account_floors.default;if(!Array.isArray(I))throw new w1("settings-invalid-value",Y.file);let A=I;for(let[q,C]of z.windows){let m=q.startsWith("vault:"),r=(f)=>m0(f).account===q,l=m0(A.find((f)=>r(f)&&m0(f).host===J)??(m?A.find((f)=>r(f)&&m0(f).host==="both"):void 0));A=A.filter((f)=>!r(f)||!m&&m0(f).host!==J);let R0=m0(j[q]),B0=(f)=>{if(C.has(f))return R0[f];let V0=l[f];return V0===0?void 0:V0},z0=B0("primary"),A0=B0("secondary");if(z0!==void 0||A0!==void 0)A.push({account:q,host:m?"both":J,primary:z0??0,secondary:A0??0})}y.push({setting:"killswitch_account_floors",value:A})}return y},{host:J}),await X.refresh()}catch(G){if(G instanceof w1)throw new n4(G.code,J9(G.code));throw G}}}}import{readFile as tU}from"node:fs/promises";import{readFileSync as yU,statSync as gU}from"node:fs";import{homedir as fU,tmpdir as mU}from"node:os";import{join as Q9}from"node:path";var hU=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function H$(Y,J){return structuredClone(J&&Y==="killswitch_enabled"?!0:T0.settings[Y].default)}function vU(Y,J){let X=[],$=(U,H)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:H})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:H})=>JSON.stringify([U,H]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:H})=>H==="both"&&!U.startsWith("vault:")))$("killswitch_account_floors","Only vault accounts may use host both");let z=Y.quota_minimum_remaining.map(({window:U})=>U);if(new Set(z).size!==z.length)$("quota_minimum_remaining","Duplicate quota window");let K=Y.cache_keep_window;if(K.length>1||K.some(({start_hour:U,end_hour:H})=>U===H))$("cache_keep_window","Use at most one window with unequal hours");return X}function B$(Y,J){let X=Y.killswitch_account_floors,$=Object.fromEntries([...X.filter((G)=>G.host==="both"),...X.filter((G)=>G.host===J)].map(({account:G,primary:z,secondary:K})=>[G,{primary:z,secondary:K}])),Q=Y.cache_keep_window[0];return{version:1,accounts:[],routing:{mode:Y.routing_mode,maxSameAccountWait:{off:0,"15m":15,cache:"max"}[Y.max_same_account_wait]},waitForReset:Y.wait_for_reset,fallbackOn:Y.fallback_on,refresh:{enabled:Y.refresh_enabled,refreshBeforeExpiryMinutes:Y.refresh_before_expiry_minutes},quota:{enabled:Y.quota_enabled,checkIntervalMinutes:Y.quota_check_interval_minutes,minimumRemaining:Object.fromEntries(Y.quota_minimum_remaining.map(({window:G,floor:z})=>[G,z])),failClosedOnUnknownQuota:Y.quota_fail_closed_on_unknown},costZeroing:{enabled:Y.cost_zeroing},killswitch:{schema:s8,enabled:Y.killswitch_enabled,defaults:{primary:Y.killswitch_default_primary,secondary:Y.killswitch_default_secondary},accounts:$},logging:{level:Y.log_level==="default"?void 0:Y.log_level},cachekeep:void 0,cacheKeep:{enabled:Y.cache_keep_enabled,subagents:Y.cache_keep_subagents,sustain:Y.cache_keep_sustain,startHour:Q?.start_hour,endHour:Q?.end_hour},dump:{enabled:Y.request_dumps},dumpDir:Y.dump_dir,dumpMaxBytes:Y.dump_max_bytes,webSockets:Y.web_sockets,rawWebSocket:Y.raw_web_socket,responsesLite:Y.responses_lite,codexApiEndpoint:Y.codex_api_endpoint}}function V$(Y,J){return{...J,...Y,accounts:J?.accounts??[],main:J?.main,refresh:{...Y.refresh,mainLastRefreshError:J?.refresh?.mainLastRefreshError,mainRefreshLeaseId:J?.refresh?.mainRefreshLeaseId,mainRefreshLeaseUntil:J?.refresh?.mainRefreshLeaseUntil,mainRefreshLeaseTokenHash:J?.refresh?.mainRefreshLeaseTokenHash},quota:{...Y.quota,mainQuota:J?.quota?.mainQuota,mainQuotaCheckedAt:J?.quota?.mainQuotaCheckedAt,mainQuotaToken:J?.quota?.mainQuotaToken,mainLastQuotaApiError:J?.quota?.mainLastQuotaApiError}}}function ZJ(Y,J){let X=Object.fromEntries(Object.keys(T0.settings).map(($)=>[$,H$($,!0)]));return V$(B$(X,Y),J)}async function N$(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],K=!1,U=Promise.resolve(),H=new Set,V=async()=>{if(K)return;if(await J.read(),K)return;let N=Object.fromEntries(await Promise.all(Object.keys(T0.settings).map(async(A)=>[A,await J.get(A,{host:X})])));if(K)return;let j=J.report(),P=vU(N,$);z=[...j,...P];let v=j.some((A)=>A.file.path===$&&(A.reason==="unreadable"||A.reason==="unparseable")),y=(A)=>P.some((q)=>q.keyPath[0]===A)||j.some((q)=>{if(q.reason!=="invalid-value"||q.keyPath[0]!==A)return!1;if(A==="cache_keep_window")return X==="pi"===(q.keyPath[1]==="pi");return!0}),I=(A)=>{N[A]=Q?structuredClone(Q[A]):H$(A,v)};for(let A of hU)if(v||y(A))I(A);if(y("killswitch_account_floors"))N.killswitch_default_primary=Q?.killswitch_default_primary??N.killswitch_default_primary,N.killswitch_default_secondary=Q?.killswitch_default_secondary??N.killswitch_default_secondary;if(Q=N,G=B$(N,X),!K)for(let A of H)A()},F=()=>{return U=U.then(V,V),U},Z=J.watch(()=>{F()});try{await F()}catch(N){throw Z(),N}return{view(N){return V$(structuredClone(G),N)},get(N){return structuredClone(Q[N])},report(){return structuredClone(z)},refresh:F,onChange(N){return H.add(N),()=>{H.delete(N)}},dispose(){K=!0,Z(),H.clear()}}}var _$=U0("config"),L$=!1,cU="openai-auth.json",A6={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function uU(){let Y=process.env[A6.configDir]?.trim();if(Y)return Y;return Q9(process.env.XDG_CONFIG_HOME||Q9(fU(),".config"),"opencode")}function _6(){return process.env[A6.configFile]?.trim()||Q9(uU(),cU)}function D$(Y){try{let J=JSON.parse(yU(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var O$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),P$=Symbol.for("@cortexkit/openai-auth/opencode-retired-settings-snapshots"),q$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),X4=globalThis;X4[O$]??=new Map;X4[P$]??=new Map;X4[q$]??=new Set;var X9=X4[O$],jJ=X4[P$],Z$=X4[q$];function E$(Y,J){let X=a4(Y),$=X9.get(X)??new Set;if($.size===0)s4.delete(X);jJ.delete(X),X9.set(X,$),$.add(J);let Q=J.onChange(()=>{$.delete(J),$.add(J)}),G=!0;return()=>{if(!G)return;if(G=!1,Q(),$.delete(J),$.size===0)X9.delete(X),jJ.set(X,J),s4.delete(X)}}function A$(Y){let J=a4(Y),X=X9.get(J),$=jJ.get(J);for(let Q of X??[])$=Q;if(!$&&!Z$.has(J))Z$.add(J),_$.warn("Holding protection values strict until the shared settings file is read",{configPath:J});return $}function M6(Y,J=_6()){if(y6(J)!=="shared")return Y??{version:1,accounts:[]};return A$(J)?.view(Y)??ZJ("opencode",Y)}function M$(Y){if(y6(Y)!=="shared")return D$(Y);return A$(Y)?.view()??ZJ("opencode")}function r4(Y,J,X){let $=_J(process.env[Y]);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function pU(Y){let J=process.env[A6.dumpMaxBytes],X=J??Y;if(X===void 0)return $9;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!L$)L$=!0,_$.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:A6.dumpMaxBytes});return $9}function FJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var S1;function G9(Y=_6()){let J=_J(process.env[A6.dump]);if(J!==void 0)return J;if(y6(Y)==="shared")return r4(A6.dump,FJ(M$(Y)),!1);let X=Y,$;try{$=gU(X)}catch{}if(S1?.path===X&&S1.mtimeMs===$?.mtimeMs&&S1.ctimeMs===$?.ctimeMs&&S1.size===$?.size)return S1.enabled;let Q=r4(A6.dump,FJ(D$(X)),!1);return S1={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function lU(Y){let J=M$(Y);return{webSockets:r4(A6.webSockets,J.webSockets,!1),rawWebSocket:r4(A6.rawWebSocket,J.rawWebSocket,!1),responsesLite:j$(J.responsesLite),dump:r4(A6.dump,FJ(J),!1),dumpDir:process.env[A6.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():Q9(mU(),"opencode-openai-auth-dumps")),dumpMaxBytes:pU(J.dumpMaxBytes),codexApiEndpoint:F$(J.codexApiEndpoint)}}var s4=new Map;function T6(Y=_6()){let J=a4(Y),X=y6(Y)==="shared",$=s4.get(J);if(!$||$.shared!==X)$={shared:X,settings:lU(Y)},s4.set(J,$);return $.settings}function T$(Y=_6()){return s4.delete(a4(Y)),S1=void 0,T6(Y)}import{readFileSync as dU}from"node:fs";var iU="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function nU(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function z4(Y,J={}){return Q4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:$4,...J})}function DJ(Y){try{let J=JSON.parse(dU(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return t4(J).migratedAt!==void 0}catch{return!1}}async function z9(Y,J){if(!DJ(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function W9(Y,J){if(Y===g6)return iU;if(t4(J.config).pending?.rowId===Y)return nU(Y);return}function oU(Y,J){return G4(Y,g6,J.legacyLocks).filter((X)=>X.name===e4)}function o6(Y,J={}){return oU(Y,J)}var W4="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class V1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function R$(Y){let J=Y.storage,X=I1(J);if(!J||!X||c0(X))return;let $=X,Q=Y.now(),G=(M6(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!r6($.lastRefreshError,$.refresh,Q))try{$=await Y.refreshAccount($,J)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=$.access?.trim();if(!K)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:K}}import{readFile as k$}from"node:fs/promises";function K9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function x$(Y){let J=await S$(Y.configPath),X=[];try{let Q=JSON.parse(await k$(Y.statePath,"utf8"));if(K9(Q)){let G=Q.accounts;if(K9(G))X=Object.keys(G)}}catch(Q){if(Q.code!=="ENOENT")throw Q}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((Q)=>!J.has(Q)):[]}}async function rU(Y){try{let J=JSON.parse(await k$(Y.configPath,"utf8"));return K9(J)&&K9(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var C$="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function h$(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&n0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>n0(X)&&X.accountId===Y.mainAccountId)}function sU(Y,J){let X=Y.lastRefreshError;return r6(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=w$}function aU(Y){let J=[],X=[],$=Y.now??Date.now(),Q=h$(Y.storage),G=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`});else if(t0(Y.auth)){if(!I1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if(Q&&(!Y.auth.refresh||Q.refresh!==Y.auth.refresh))J.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&&Q){let U={type:"restore-main-credential"};X.push(U);let H=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(H)H.repair=U}let z=Y.storage?.accounts??[];if(z.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!z.some((U)=>U.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of z){if(!n0(U)||!c0(U))continue;J.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of z){if(!n0(U))continue;if(!sU(U,$))continue;let H={type:"clear-refresh-backoff",accountId:U.id};X.push(H),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:H})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function v$(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(t0(await Y.readAuth()))return;let $=h$(await Y.loadAccounts(Y.paths));if(!$)return;await Y.setMainAuth({refresh:$.refresh,access:$.access??"",expires:$.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts(($)=>$,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts(($)=>{let Q=$.accounts.find((G)=>G.id===X.accountId&&n0(G));if(Q)Q.lastRefreshError=void 0;return $},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,$,Q,G]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),rU(Y.paths)]),z=aU({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),K=await Q4({provider:"openai",quota:$4,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==I$)continue;z.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${b$}`})}return z.findings.map((U)=>{let H=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...H?{repair:H}:{}}})}}]}var eU=X5,y$="OpenAI accounts",YH="ChatGPT accounts in the vault",JH="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function XH(){let{redirectUri:Y}=await d$(),J=await u$(),X=c$(crypto.getRandomValues(new Uint8Array(32)).buffer),$=p$(Y,J,X),Q=i$(J,X);return{url:$,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await Q;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:b1(G)}}finally{l$(X)}}}}async function $H(Y){let{deviceData:J,url:X,instructions:$}=await n$(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await o$(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:b1(Q)}}catch{return{type:"failed"}}}}}function z5({client:Y,getAuth:J,getPaths:X=()=>x1(_6()),fetchImpl:$=fetch,packageVersion:Q=f6,dependencies:G,onMainSlotWritten:z,vault:K}){let U={authorizeBrowser:G?.authorizeBrowser??XH,authorizeHeadless:G?.authorizeHeadless??(()=>$H(Q)),beginAccountLogin:G?.beginAccountLogin??B9,loadAccounts:G?.loadAccounts??k1,mutateAccounts:G?.mutateAccounts??V9,readStoreIds:G?.readStoreIds??x$,openBrowser:G?.openBrowser??eU,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??z4,migrationBlockers:G?.migrationBlockers??(async()=>{let q=await H4({currentVersion:Q});return q.open?[]:q.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},H=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(K&&await K.authority()!=="local")return!0;if((await H()).type!=="missing")return!0;let q=X(),C=U.openAccountPool(q);if((await C.read()).status==="ready")return e$(C);return((await U.loadAccounts(q))?.accounts.length??0)>0},F=async(q)=>{if(await Q5(X().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(t0(await H()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...q}}),!0}))await z?.().catch(()=>{})},Z=(q)=>({begin:async({headless:C,signal:m})=>{if(K&&await K.authority()!=="local")throw Error(K4);let r=await U.beginAccountLogin({version:Q,headless:C,...m?{signal:m}:{}});return{url:r.url,instructions:r.instructions,completion:r.completion.then(async(l)=>{if(K&&await K.authority()!=="local")throw Error(K4);let R0=await q.read(),B0=R0.status==="ready"?R0.rows.find((A0)=>A0.id===g6)?.identity:void 0;if(l.accountId&&B0&&l.accountId===B0)throw Error("that account is already the OpenCode main credential");return{id:l.id,credential:{type:"oauth",refresh:l.refresh,...l.access!==void 0?{access:l.access}:{},...l.expires!==void 0?{expires:l.expires}:{}},...l.accountId!==void 0?{identity:l.accountId}:{},...l.label!==void 0?{label:l.label}:{}}})}},openBrowser:(C)=>U.openBrowser(C)}),N=async(q)=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=q.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let m=await Y8({accessToken:C.access,fetchImpl:$,now:U.now,...q.identity?{accountId:q.identity}:{},accountKey:q.id});return U4(m,U.now(),!0)},j=(q)=>v$({paths:X(),migrated:q,readAuth:H,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),P=(q,C)=>({title:y$,store:GJ(C,{rowLocks:(m)=>G4(q,m)}),...U.terminal?{terminal:U.terminal}:{},login:Z(C),protect:(m,r)=>W9(m,r),extraLocks:o6(q),pollQuota:N,doctor:j(!0),status:async()=>{if(K&&await K.authority()==="host")return[g$];let m=await K?.status();if(K&&await K.authority()!=="local"&&m)return[PJ(K.host,K.name,m.enrollment)];return[`Routing: ${(await U.loadAccounts(q))?.routing?.mode??"main-first"}`,...K?[PJ(K.host,K.name,(await K.status()).enrollment)]:[]]},...K&&!H9()?{extraActions:[v(K)]}:{}}),v=(q)=>{let C=q.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(m)=>{let r=await q.authority();if(r==="host"){m.print(f$);return}if(C){if(r!=="local")await q.disconnect();m.print("Disconnected from the Claustrum vault.");return}if(r!=="local"){m.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}m.print(`Asking the Claustrum vault to enroll ${q.name}…`);let l,R0=await q.waitForApproval({...U.vaultWait,onPending:(B0)=>{let z0=B0.state==="pending"?B0.requestId??B0.retryCode??"":B0.state;if(z0===l)return;l=z0;for(let A0 of r$(q.name,B0))m.print(A0);m.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});m.print(s$(q,R0).text)}}},y=async()=>{let q=await U.migrationBlockers();return t$({title:y$,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...q.length>0?["These processes still hold the move back:",...q.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[a$({checks:j(!1)})],...U.terminal?{terminal:U.terminal}:{}})},I=async(q)=>{let C=X(),m=U.openAccountPool(C);if(K&&await K.authority()!=="local")return U9(P(C,m),K);if(await z9(C,m)===void 0)return y();let r=P(C,m);return K?U9(r,K):Y5(r)},A=(q)=>async()=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=await q();if(C.method!=="auto")return C;return{...C,callback:async()=>{let m=await C.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return m}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:J5({hasCredential:V,openMenu:I,login:A(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:A(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:YH,type:"oauth",authorize:async()=>({url:"",instructions:JH,method:"auto",callback:async()=>{let q=await m$(K.paths,K.name);if(q!=="vault"&&q!=="host")return{type:"failed"};try{let C=JSON.parse(await tU(G5(),"utf8"));if(!C||typeof C!=="object"||Array.isArray(C)||Object.hasOwn(C,"openai"))return{type:"failed"}}catch(C){if(C.code!=="ENOENT")return{type:"failed"}}return{...$5,type:"success"}}})}]:[]]}var QH=new Set(["title","compaction","summary"]);function K5(Y,J,X){if(X!==null&&QH.has(X))return;W5(Y,J)}class EJ{#Y=new WeakMap;record(Y,{turnID:J,turnStartedAt:X}=Y){if(X!==void 0)this.#Y.set(Y,{turnID:J,turnStartedAt:X})}forAuxiliary(Y,J){let X=this.#Y.get(Y)??{turnID:(J?.uuid??h1)(),turnStartedAt:(J?.now??Date.now)()};return{threadID:Y.threadID,windowID:Y.windowID,...X,pinnedEffort:Y.pinnedEffort,effortUpdates:Y.effortUpdates?.map(($)=>({...$}))}}}var AJ={rpcRoot:"openai-auth",directoryPrefix:V5,registrationSessionId:"process"},N9=new Map;function SD(Y,J){if(J?.aborted)return Promise.resolve(!1);if(MJ(Y))return Promise.resolve(!0);return new Promise((X)=>{let $=(K)=>{if(clearTimeout(G),J?.removeEventListener("abort",Q),z.delete($),z.size===0)N9.delete(Y);X(K)},Q=()=>$(!1),G=setTimeout(()=>$(!1),2000),z=N9.get(Y)??new Set;N9.set(Y,z),z.add($),J?.addEventListener("abort",Q,{once:!0})})}function L9(Y,J){U5(AJ,Y,J)}function N5(Y=0,J){let X=H5(AJ,Y,J);if(J!==void 0)for(let $ of N9.get(J)??[])$(!0);return X}function MJ(Y){return B5(AJ,Y)}var N1=U0("commands");function v1(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function j5(Y){return Y.configPath??v1(Y).configPath}async function J8(Y){let J=Y.settingsSnapshot,X=j5(Y);if(!J||y6(X)!=="shared")return;let $=await d4(X);if($?.decision!=="shared")return;let Q=$.install.target;return{snapshot:J,file:Q,writer:J4(T0,{file:Q,log:N1,separateInstall:!1,createMissing:!0})}}async function CJ(Y,J,X){let $=await J8(Y);if(!$){await X();return}try{if(J.setting==="cache_keep_window"){if(await $.snapshot.refresh(),$.snapshot.report().some((Q)=>Q.reason==="invalid-value"&&Q.keyPath[0]===J.setting||Q.reason==="unreadable"||Q.reason==="unparseable"))throw new w1("settings-invalid-value",$.file)}await $.writer.update([J],{host:"opencode"}),await $.snapshot.refresh()}catch(Q){if(Q instanceof w1)throw new n4(Q.code,J9(Q.code));throw Q}}function TJ(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function GH(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),$=Number(J[2]);if(X>23||$>23||X===$)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:$}}var zH="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore 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.";function WH(Y){let J=(X,$,Q)=>CJ(Y,{setting:X,value:$},()=>C1(Y.store(),o6(v1(Y)),(G)=>{let z={...G.cacheKeep??{}};Q(z),G.cacheKeep=z}));return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let $=await J8(Y);await $?.snapshot.refresh();let Q=j9($?$.snapshot.view():await Y.loadAccounts(v1(Y))),G=Q?.enabled===!0,z=Q?.subagents===!0,K=X.status(),U=K.window?TJ(K.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${K.tracked===0?"no sessions":`${K.tracked} session${K.tracked===1?"":"s"}`}`,`Timer ${K.running?"armed":"idle"} · subagents ${z?"on":"off"} · sustain ${K.sustain?"on":"off"}`,`Window ${U}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(K.ttlMs/1000)}s · lead ${Math.round(K.leadMs/1000)}s · idle cap ${Math.round(K.maxIdleWarmMs/60000)}min (subagents ${Math.round(K.maxSubagentIdleMs/60000)}min)`],items:K.targets.map((H)=>({id:H.sessionKey,label:H.sessionKey,group:"Sessions",detail:[H.accountId??"main",`expires in ${Math.ceil((H.cacheExpiresAt-K.generatedAt)/1000)}s`,...H.lastWarmedAt?[`last warm ${Math.ceil((K.generatedAt-H.lastWarmedAt)/1000)}s ago`]:[],...H.backoffUntil&&H.backoffUntil>K.generatedAt?[`backoff ${Math.ceil((H.backoffUntil-K.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:H})=>{let V=H.enabled===!0;if(await J("cache_keep_enabled",V,(F)=>{F.enabled=V}),Y.setCacheKeepEnabled?.(V),V)X.start();else{for(let F of X.status().targets)if(!F9(F.sessionKey,!1))X.remove(F.sessionKey);if(X.status().tracked===0)X.stop()}return N1.info(V?"cachekeep enabled":"cachekeep disabled"),V?`Keep-warm is on. TTL ${Math.round(K.ttlMs/1000)}s, idle cap ${Math.round(K.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:z?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!z}],run:async({values:H})=>{let V=H.subagents===!0;return await J("cache_keep_subagents",V,(F)=>{F.subagents=V}),Y.setCacheKeepSubagents?.(V),`Subagent warming is ${V?"on":"off"}.`}},{id:"sustain",label:K.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!K.sustain}],run:async({values:H})=>{let V=H.sustain===!0;return await J("cache_keep_sustain",V,(F)=>{F.sustain=V}),Y.setCacheKeepSustain?.(V),V?zH:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...K.window?{value:TJ(K.window)}:{}}],run:async({values:H})=>{let V=H.window;if(typeof V!=="string"||V.trim()==="")return await J("cache_keep_window",[],(j)=>{delete j.startHour,delete j.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let F=GH(V);if(!F.ok)return{ok:!1,text:`Invalid window: ${F.reason}`};let{startHour:Z,endHour:N}=F;return await J("cache_keep_window",[{start_hour:Z,end_hour:N}],(j)=>{j.startHour=Z,j.endHour=N}),Y.setCacheKeepWindow?.({startHour:Z,endHour:N}),`Warming limited to ${TJ(F)} local hours.`}}]}}}}var L5=["error","warn","info","debug","trace"];function KH(Y){return{title:"Diagnostics",build:async()=>{let J=j5(Y),X=d4(J)?await K$({configPath:J,snapshot:Y.settingsSnapshot,log:N1}):{lines:[]},$=await J8(Y),Q=T6(J),G=G9(J),K=($?$.snapshot.view():await Y.loadAccounts(v1(Y)).catch(()=>null))?.logging?.level,U=!K||K==="default"?"info":K,H=G?await Z5(Q.dumpDir):void 0,V=H===void 0?"size unavailable":RJ(H),F=Q.dumpMaxBytes===0?"no cap":`${RJ(Q.dumpMaxBytes)} cap`,Z=Y.layoutNotice?.();return{lines:[G?`Dumps on (${V} / ${F})`:"Dumps off",`Dump directory: ${Q.dumpDir}`,`Log level: ${U}`,...Z?[Z]:[],...X.lines],actions:[{id:"dump",label:G?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!G}],run:async({values:N})=>{let j=N.enabled===!0;await CJ(Y,{setting:"request_dumps",value:j},()=>C1(Y.store(),o6(v1(Y)),(v)=>{v.dump={...v.dump??{},enabled:j}}));let P=T$(J);return N1.info(j?"request dump enabled":"request dump disabled"),j?`Request dumps are on, written to ${P.dumpDir}.
2
+
3
+ Body dumps may contain prompt and session content. Turn this off after debugging.`:"Request dumps are off."}},{id:"logging",label:"Set the log level",knobs:[{kind:"choice",id:"level",label:"Level",choices:L5.map((N)=>({value:N,label:N})),value:L5.includes(U)?U:"info"}],run:async({values:N})=>{let j=String(N.level);return await CJ(Y,{setting:"log_level",value:j},()=>C1(Y.store(),o6(v1(Y)),(P)=>{P.logging={...P.logging??{},level:j}})),Z9(j),N1.info("log level changed",{level:j}),`Log level set to ${j}.`}}]}}}}async function UH(Y){let J=await Y.store().read(),X=J.status==="ready"?J.rows:[];return[...new Set(["main",...X.filter(($)=>$.enabled&&$.type==="oauth").map(($)=>$.id)])]}function F5(Y){let J=v1(Y),X=Y.configPath??J.configPath,$=o6(J),Q=Y.settings??(Y.settingsSnapshot&&y6(X)==="shared"?{read:async()=>{let K=await J8(Y);if(!K)throw Error("Shared settings are unavailable");return o4({...K,host:"opencode",log:N1}).read()},update:async(K)=>{let U=await J8(Y);if(!U)throw Error("Shared settings are unavailable");await o4({...U,host:"opencode",log:N1}).update(K)}}:void 0),G=Y.quotaManager&&Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?UJ({configPath:J.configPath,statePath:J.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:zJ(Y.store(),$,X),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>UH(Y)}):void 0,z=Y.beginAccountLogin;return HJ({store:Y.store(),configPath:X,...Q?{settings:Q}:{},...Y.readOnly?{readOnly:!0}:{},...Y.allowAction?{allowAction:Y.allowAction}:{},...Y.unavailableSections?{unavailableSections:Y.unavailableSections}:{},...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:$,rowLocks:(K)=>G4(J,K),migration:Y.migration,...z?{login:{begin:(K)=>z({...K,version:Y.packageVersion}),mainIdentity:async()=>{let K=await Y.store().read();if(K.status!=="ready")return;return K.rows.find((U)=>U.id==="main")?.identity}}}:{},protect:(K,U)=>W9(K,U),...Y.refreshAllQuota?{quotaCheck:async(K)=>{if(K.length===1){let V=Y.store();for(let F of K)await V.requestReading(F);await V.pullsSettled();return}let H=(await Y.refreshAllQuota?.()??[]).filter((V)=>!V.ok);if(H.length>0)throw new n4("quota-check-failed",H.map((V)=>V.permanent?`${V.account}: sign-in no longer accepted — remove and add this account again`:`${V.account}: fetch failed — check again to retry`).join(`
4
+ `))}}:{},cache:WH(Y),diagnostics:KH(Y),extras:[...G?[G]:[],WJ({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[KJ({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function _5(Y){return(J,X="info")=>{N1.info("menu notification",{sessionId:Y,kind:X}),L9({command:W1,notify:{message:J,kind:X}},Y)}}function D5(Y,J){return F5(Y).open({...J!==void 0?{sessionId:J}:{},notify:_5(J)})}function O5(Y,J){return F5(Y).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:_5(J.sessionId)})}function P5(Y){let J=[`## ${Y.title}`];for(let X of Y.sections){J.push("",`### ${X.title}`);for(let $ of X.lines)J.push($);for(let $ of X.items){let Q=$.detail??$.status;J.push(`- ${$.label}${Q?`: ${Q}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
5
+ `)}function E5(Y){if(!Y.enabled||typeof Y.body!=="string")return;let J=Y.headers.has("x-parent-session-id");if(J&&!Y.includeSubagents)return;let X=Y.sessionID??Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!X)return;let $={};for(let Q of["originator","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(Q);if(G)$[Q]=G}return{sessionKey:X,bodyText:Y.body,replayHeaders:$,isSubagent:J}}function A5(Y,J,X=Date.now()){if(!J)return;if(Y.route==="sticky-balanced"){let Q=Y.stickyAssignments?.[m6(J)];if(!Q)return;if(Q.lastSeenAt<X-q5)return;return Q.accountId}let $=Y.activeRouting?.[J];if(!$||$.route!==Y.route)return;return $.activeId}function M5(Y){let J,X=0,$=0,Q=!1,G;return{read(){let z=Y.path(),K=Y.stat(z);if(K&&J?.path===z&&J.mtimeMs===K.mtimeMs&&J.size===K.size)return J.value;if(!K)J=void 0;let U=++X;return Y.read(z).catch(Y.fallback).then((H)=>{if(U>$){if($=U,G=H,Q=!0,K)J={...K,path:z,value:H};return Y.onRead(H),H}return Q?G:H})},invalidate(){J=void 0}}}import{readFileSync as HH}from"node:fs";var BH=60000,VH=15000,Q8=2000,hJ=1e4;async function V4(Y,J){let X,$=await Promise.race([Y.then(()=>!0,()=>!0),new Promise((Q)=>{X=setTimeout(()=>Q(!1),J),X.unref?.()})]);return clearTimeout(X),$}function NH(Y){if(!Y)return;let J=R6(Y);return J?C6(J):void 0}function T5(Y){try{let J=JSON.parse(HH(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return t4(J).migratedAt}catch{return}}function LH(Y){if(Y.type!=="oauth")return!1;return Y.candidate||Y.torn===!0&&Y.enabled}class vJ{listeners=new Set;deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;immediateStore;stores=new Set;disposal;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;limits;retiredLimits=[];lastPull=new Map;quotaPulls=new Map;polled=new Set;pollOutcomes=new Map;disposed=!1;vaultRosterSettled;pollsAwaitVault=!1;constructor(Y){this.deps=Y,this.now=Y.now??Date.now,this.log=Y.log??U0("pool"),this.vaultRosterSettled=Y.vaultFirstRoster===void 0;let J=()=>{this.vaultRosterSettled=!0};Y.vaultFirstRoster?.then(J,J)}async awaitVaultRoster(Y){let J=this.deps.vaultFirstRoster;if(this.vaultRosterSettled||!J)return;await V4(J,Y)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}subscribe(Y){return this.listeners.add(Y),()=>{this.listeners.delete(Y)}}async sidebarView(){let Y=this.deps.paths();if(T5(Y.configPath)===void 0)return{active:!1,rows:[]};let J=await this.storeFor(Y).read();return J.status==="ready"?{active:!0,rows:this.withLocalState(J.rows)}:{active:!1,rows:[]}}changed(){for(let Y of this.listeners)Y()}async current(){if(this.disposed)return this.peek();let Y=this.filesKey();if(this.snapshot.key===Y)return this.peek();let J=this.startRead(Y),X=await $8(J,this.deps.readBudgetMs??D9,()=>this.snapshot);return{active:X.active,rows:X.rows}}async load(){if(this.disposed)return this.peek();if(await this.deps.vaultAuthority?.(),this.disposed)return this.peek();let Y=await this.startRead(this.filesKey());return{active:Y.active,rows:Y.rows}}filesKey(){let Y=this.deps.paths();return`${Y.configPath}|${kJ(Y.configPath)}|${kJ(Y.statePath)}`}storeFor(Y,J=!1){let X=J?this.immediateStore:this.store;if(X?.configPath===Y.configPath&&X.statePath===Y.statePath)return X.store;let $=Q4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:$4,coalesceQuota:!J,now:this.now,pull:(G)=>this.coalescedPull(G),onPullFailure:(G,z)=>{this.pollOutcomes.set(G,{id:G,ok:!1,error:z.message}),this.log.warn("pool quota poll failed",{rowId:G,kind:z.kind,error:z.message})},logger:this.log,...this.deps.store,onStep:async(G,z)=>{if(await this.deps.store?.onStep?.(G,z),z.operation!=="updateSettings"&&G.startsWith("before-")&&this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("Local account writes are disabled while connected to the vault.")}}),Q={configPath:Y.configPath,statePath:Y.statePath,store:$};if(J)this.immediateStore=Q;else this.store=Q;return this.stores.add($),$}startRead(Y){if(this.disposed)return Promise.resolve(this.snapshot);if(this.inflightRead?.key===Y)return this.inflightRead.promise;let J=this.now(),X=this.read(Y,J),$={key:Y,promise:X};this.inflightRead=$;let Q=()=>{if(this.inflightRead===$)this.inflightRead=void 0};return X.then(Q,Q),X}async read(Y,J){let X=this.deps.paths(),$={active:!1,rows:[],key:Y,readAt:J};try{if(T5(X.configPath)!==void 0){let z=await this.storeFor(X).read();if(z.status==="ready")$={active:!0,rows:z.rows,key:Y,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:z.status,...z.status==="error"?{reason:z.reason}:{}})}}catch(G){return this.log.warn("account pool read failed",{error:G instanceof Error?G.message:String(G)}),this.snapshot}if(this.disposed)return this.snapshot;let Q=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...$,rows:this.withLocalState($.rows)},this.changed();if(this.snapshot.active){if(!Q)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(Y){let J=this.now();return Y.map((X)=>{let $=X,Q=this.rotated.get(X.id),G=Q?.credential;if(Q&&Q.credentialEpoch!==X.credentialEpoch)this.rotated.delete(X.id);else if(G?.type==="oauth"&&X.credential?.type==="oauth"){let z=X.credential.lastRefreshedAt??0,K=G.lastRefreshedAt??0;if(z>=K)this.rotated.delete(X.id);else $={...$,credential:G}}return S5($,this.pending,J)})}replaceRow(Y,J){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===Y?J(X):X)},this.changed()}vaultOwned(Y){if(this.deps.vaultMode?.())return!0;return Y.identity!==void 0&&(this.deps.vaultIdentities?.().has(Y.identity)??!1)}pollUnseenRows(){if(this.disposed)return;let Y=this.deps.vaultFirstRoster;if(!this.vaultRosterSettled&&Y&&!this.deps.vaultMode?.()){if(this.pollsAwaitVault)return;this.pollsAwaitVault=!0,V4(Y,this.deps.vaultFirstRosterBackgroundWaitMs??hJ).then((J)=>{if(this.pollsAwaitVault=!1,J)this.pollUnseenRows();else this.log.info("first quota polls skipped: the vault has not read its accounts yet")});return}for(let J of this.snapshot.rows){if(!LH(J)||this.vaultOwned(J))continue;let X=`${J.id}\x00${J.credentialEpoch??0}\x00${J.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading(J.id,!0)}}requestReading(Y,J=!1,X){if(this.disposed||this.deps.vaultMode?.())return;X??=this.poolStore();let $=this.now(),Q=this.lastPull.get(Y);if(!J&&Q!==void 0&&$-Q<(this.deps.pullRetryMs??VH))return X.pullsSettled();return this.lastPull.set(Y,$),X.requestReading(Y),X.pullsSettled()}coalescedPull(Y){let J=JSON.stringify([this.deps.paths().configPath,Y.id,Y.credentialEpoch,Y.identity]),X=this.quotaPulls.get(J);if(X)return X;let $=this.pull(Y).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,$),$}async pull(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("local accounts are not polled while this host is connected to the vault");let J;try{if(J=await this.deps.pullQuota(Y),!J)throw Error("the quota poll returned no reading")}catch($){throw this.pollOutcomes.set(Y.id,{id:Y.id,ok:!1,error:$ instanceof Error?$.message:String($)}),$}this.pollOutcomes.set(Y.id,{id:Y.id,ok:!0});let X=this.snapshot.rows.find(($)=>$.id===Y.id);if(X&&X.credentialEpoch===Y.credentialEpoch&&X.identity===Y.identity)this.applyObservation(X,J);return J}applyObservation(Y,J){w5(this.pending,Y,J),this.replaceRow(Y.id,(X)=>({...X,quota:C5(X.quota,J),needsFirstReading:!1}))}recordSnapshot(Y,J,X,$){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let Q=this.snapshot.rows.find((Z)=>Z.id===Y);if(Q?.type!=="oauth")return;let G=NH(X);if(!(G&&Q.identity?G===Q.identity:B4(Q)?.access===X))return;let K=U4(J,this.now(),$);if(!K)return;if(this.applyObservation(Q,K),Q.credentialEpoch===void 0)return;let U={credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},H=this.storeFor(this.deps.paths()),F=(this.writes.get(Q.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return H.recordQuota(Q.id,U,K)}).catch((Z)=>{this.log.warn("pool quota not recorded",{rowId:Q.id,error:Z instanceof Error?Z.message:String(Z)})});this.writes.set(Q.id,F),F.finally(()=>{if(this.writes.get(Q.id)===F)this.writes.delete(Q.id)})}limitsBindings(){let Y=this.limits?.owner.namespace;if(!Y||!this.snapshot.active||this.deps.vaultMode?.())return[];return this.snapshot.rows.flatMap((J)=>{let X=bJ(Y,J);return X?[X]:[]})}limitsBinding(Y){let J=this.limits?.owner.namespace;return J?bJ(J,Y):void 0}async limitsForRequest(){if(this.disposed)return;let Y=await this.deps.vaultAuthority?.();if(Y!==void 0&&Y!=="local")return;if(this.disposed||this.deps.vaultMode?.())return;let J=await this.load();if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!J.active||this.disposed||this.deps.vaultMode?.())return;let X=this.deps.paths(),$=JSON.stringify([X.configPath,X.statePath]);if(this.limits?.key!==$){if(this.limits)this.retiredLimits.push(this.limits.owner.dispose());this.limits={key:$,owner:_9({source:{kind:"pool",...X,store:this.poolStore()},log:(G)=>this.log.warn(G)})}}let Q=await this.limits.owner.forRequest(!0);return await Q.reloadForBindings(()=>this.limitsBindings()),Q}limitsOwner(){return this.limits?.owner}async prepareTokens(Y,J,X={}){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!this.deps.vaultMode?.())await this.awaitVaultRoster(this.deps.vaultFirstRosterWaitMs??Q8);let $=this.now(),Q=R5(M6(J,this.deps.paths().configPath)),G=[];for(let z of Y){if(!z.candidate||this.vaultOwned(z))continue;let K=B4(z);if(!K)continue;let U=(K.expires??0)-$;if(!(!K.access||!K.expires||U<=Q)||this.refreshBackedOff(z,J,$))continue;let V=this.refresh(z.id);if(X.waitForAll||!K.access||!K.expires||U<=BH)G.push(V)}await Promise.all(G)}refreshBackedOff(Y,J,X=this.now()){let $=B4(Y);if(!$)return!1;let Q=X8($.refresh),G=this.backoff.get(Y.id);if(G&&G.tokenHash===Q&&G.nextRetryAt>X)return!0;let z=J?.accounts.find((K)=>K.id===Y.id);return Boolean(z?.type==="oauth"&&z.corrupt!==!0&&r6(z.lastRefreshError,$.refresh,X))}usableToken(Y,J=this.now()){let X=this.snapshot.rows.find((Q)=>Q.id===Y.id);if(!X?.enabled||!X.candidate||X.type!=="oauth"||X.identity!==Y.identity||X.credentialEpoch!==Y.credentialEpoch||this.vaultOwned(X))return;let $=B4(X);if(!$?.access.trim())return;if(typeof $.expires!=="number"||$.expires<=J)return;return $.access}refresh(Y){let J=this.refreshing.get(Y);if(J)return J;let X=this.runRefresh(Y).finally(()=>{if(this.refreshing.get(Y)===X)this.refreshing.delete(Y)});return this.refreshing.set(Y,X),X}async runRefresh(Y){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;let J=this.deps.paths(),X=this.snapshot.rows.find((z)=>z.id===Y),$=X?B4(X)?.refresh:void 0,Q,G=(z,K)=>{return Q=K.credentialEpoch,this.deps.refreshProvider(z,K)};try{let z=await k5({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},Y,G);if(z.status==="rotated"){this.backoff.delete(Y),this.rotated.set(Y,{credential:z.credential,credentialEpoch:Q}),this.replaceRow(Y,(K)=>K.credentialEpoch!==Q?K:{...K,credential:z.credential,...z.identity!==void 0&&K.identity===void 0?{identity:z.identity}:{}});return}if(z.status==="identity-contradicted"){this.backoff.delete(Y),this.replaceRow(Y,(K)=>({...K,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:Y});return}this.recordRefreshFailure(Y,$,Error(z.reason))}catch(z){this.recordRefreshFailure(Y,$,z)}}recordRefreshFailure(Y,J,X){if(this.log.warn("pool row refresh failed",{rowId:Y,error:X instanceof Error?X.message:String(X)}),!J)return;this.backoff.set(Y,I5(J,X,this.now(),this.backoff.get(Y)))}refreshBackoffFor(Y){return b5(Y,this.backoff,this.now(),(J,X)=>this.usableToken(J,X))}async active(){return(await this.current()).active}poolStore(){return this.storeFor(this.deps.paths())}async refreshDueTokens(Y){let J=await this.current();if(!J.active||this.disposed)return;await this.prepareTokens(J.rows,Y,{waitForAll:!0})}async pollRows(Y,J={}){let X=await this.load();if(!X.active||this.disposed)return[];let $=this.now(),Q=X.rows.filter((z)=>{if(!z.candidate||z.type!=="oauth"||this.vaultOwned(z))return!1;if(J.ids&&!J.ids.includes(z.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let K=xJ(z);return K===void 0||$-K>=J.skipReadWithinMs});if(Q.length===0)return[];await this.prepareTokens(Q,Y,{waitForAll:!0});let G=this.storeFor(this.deps.paths(),J.persistQuota);for(let z of Q)this.pollOutcomes.delete(z.id),this.requestReading(z.id,!0,G);return await G.pullsSettled(),Q.map((z)=>this.pollOutcomes.get(z.id)??{id:z.id,ok:!1,error:"the quota poll did not run"})}async accessFor(Y,J){let X=await this.current();if(!X.active)return;let $=X.rows.find((z)=>z.id===Y);if(!$?.candidate)return;await this.prepareTokens([$],J);let Q=this.snapshot.rows.find((z)=>z.id===Y)??$;if(!Q.candidate)return;let G=this.usableToken(Q);return G?{row:Q,token:G}:void 0}async rowAccess(Y,J){let X=await this.current();if(!X.active)return;let $=X.rows.find((G)=>G.id===Y);if(!$)return{};let Q=await this.accessFor(Y,J);return{row:{id:$.id,type:$.type,enabled:$.enabled,...$.label!==void 0?{label:$.label}:{},...$.identity!==void 0?{identity:$.identity}:{}},...Q?{token:Q.token}:{}}}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await Promise.allSettled([...this.writes.values()]),await Promise.all([...this.retiredLimits,this.limits?.owner.dispose()]),await Promise.all([...this.stores].map((Y)=>Y.close()))})(),this.disposal}async settled(){for(;;){let Y=[...this.writes.values(),...this.refreshing.values(),...this.inflightRead?[this.inflightRead.promise]:[]];if(await Promise.allSettled(Y),await Promise.all([...this.stores].map((J)=>J.pullsSettled())),this.writes.size===0&&this.refreshing.size===0&&!this.inflightRead){await this.disposal;return}}}}async function G8(Y,J){let X=Y-performance.now();if(X<=0)return;let $;return await V4(J().then((Q)=>{$=Q}),X),$}class gJ{options;activity=x5();vaultOwner;disposed=!1;disposal;constructor(Y){this.options=Y}async forRequest(Y=performance.now()+Q8){if(this.disposed)return;let J=this.options.vault.enrolled()?await G8(Y,()=>this.options.vault.authority()):await this.options.vault.authority();if(this.disposed||!J||J==="unreadable")return;if(J==="local")return this.options.pool.limitsForRequest();return G8(Y,()=>this.vaultRequest(Y))}async vaultRequest(Y){if(await this.options.vault.awaitRequestRoster(),this.disposed||performance.now()>=Y)return;let J=await this.options.vault.authority();if(J!=="vault"&&J!=="host")return;if(this.disposed||performance.now()>=Y)return;if(!this.options.vault.snapshot()||!this.options.vault.routes().some(($)=>$.kind==="oauth"))return;this.vaultOwner??=_9({source:{kind:"vault",rosterPath:this.options.vault.paths.rosterPath},log:this.options.log});let X=await this.vaultOwner.forRequest(!0);if(this.disposed||performance.now()>=Y)return;return await X.reloadForBindings(()=>this.ownershipBindings()),X}owner(){return this.options.vault.enrolled()?this.vaultOwner:this.options.pool.limitsOwner()}bindings(){if(this.disposed)return[];let Y=this.options.vault,J=this.vaultOwner;if(Y.enrolled()){if(!J)return[];let X=new Set(Y.routes().filter(($)=>$.kind==="oauth").map(($)=>$.id));return(Y.snapshot()?.rows??[]).flatMap(($)=>X.has($.routeId)?[yJ(J.namespace,$)]:[])}return this.options.pool.limitsBindings()}ownershipBindings(){if(this.disposed)return[];if(!this.options.vault.enrolled())return this.options.pool.limitsBindings();let Y=this.vaultOwner;return Y?(this.options.vault.snapshot()?.rows??[]).filter((J)=>J.credentialType==="oauth").map((J)=>yJ(Y.namespace,J)):[]}accountKey(Y){return this.bindings().find((J)=>J.account.accountId===Y)?.account}marks(){let Y=this.bindings();return Y.length?ZH(this.owner()?.snapshot(),Y):new Map}forget(Y){this.activity.forgetSession(Y)}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await this.vaultOwner?.dispose(),await this.options.pool.dispose()})(),this.disposal}}function ZH(Y,J,X=Date.now()){let $=new Map;for(let Q of J)for(let G of Y?.marks??[]){if(G.key.scope.kind!=="pool"||G.key.window!=="account")continue;if(!e0(Q.account,G.key.account))continue;for(let z of G.entries)if(z.until>X&&z.until>($.get(Q.account.accountId)??0))$.set(Q.account.accountId,z.until)}return $}var p0={};cJ(p0,{toWebSocketUrl:()=>oZ,streamResponsesWebSocket:()=>eZ,parseRateLimitSignal:()=>u1,observeHttpCompletion:()=>T7,normalizeHeaders:()=>rZ,markOversizedFrame:()=>jz,isUpgradeFailure:()=>sZ,isOversizedFrame:()=>aZ,isNonEmittingFrame:()=>_z,isAbortError:()=>M7,connectResponsesWebSocket:()=>tZ,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>E7,RATE_LIMIT_WINDOW:()=>OY,PROTOCOL_HEADER:()=>Nz,OpenAIWebSocket:()=>p0,OVERSIZED_FRAME_MESSAGE:()=>Dz});var jH=Symbol.for("vercel.ai.error"),s6=class Y extends Error{constructor({name:J,message:X,cause:$}){super(X);this[jH]=!0,this.name=J,this.cause=$}static isInstance(J){return Y.hasMarker(J,"vercel.ai.error")}static hasMarker(J,X){let $=Symbol.for(X);return J!=null&&typeof J==="object"&&$ in J&&typeof J[$]==="boolean"&&J[$]===!0}},FH="AI_DecisionUnsupportedQuestionTypeError",OO=`vercel.ai.error.${FH}`;var h5="AI_APICallError",v5=`vercel.ai.error.${h5}`,_H=Symbol.for(v5),y1=class extends s6{constructor({message:Y,url:J,requestBodyValues:X,statusCode:$,responseHeaders:Q,responseBody:G,cause:z,isRetryable:K=$!=null&&($===408||$===409||$===429||$>=500),data:U}){super({name:h5,message:Y,cause:z});this[_H]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=$,this.responseHeaders=Q,this.responseBody=G,this.isRetryable=K,this.data=U}static isInstance(Y){return s6.hasMarker(Y,v5)}},DH="AI_EmptyResponseBodyError",PO=`vercel.ai.error.${DH}`;var OH="AI_DecisionRefusalError",qO=`vercel.ai.error.${OH}`;var PH="AI_ExtractionRefusalError",EO=`vercel.ai.error.${PH}`;var qH="AI_ExtractionUnsupportedFieldTypeError",AO=`vercel.ai.error.${qH}`;var y5="AI_InvalidArgumentError",g5=`vercel.ai.error.${y5}`,EH=Symbol.for(g5),f5=class extends s6{constructor({message:Y,cause:J,argument:X}){super({name:y5,message:Y,cause:J});this[EH]=!0,this.argument=X}static isInstance(Y){return s6.hasMarker(Y,g5)}},AH="AI_InvalidPromptError",MO=`vercel.ai.error.${AH}`;var MH="AI_InvalidResponseDataError",TO=`vercel.ai.error.${MH}`;var TH="AI_JSONParseError",RO=`vercel.ai.error.${TH}`;var RH="AI_LoadAPIKeyError",CO=`vercel.ai.error.${RH}`;var CH="AI_LoadSettingError",wO=`vercel.ai.error.${CH}`;var wH="AI_NoContentGeneratedError",SO=`vercel.ai.error.${wH}`;var SH="AI_NoSuchModelError",IO=`vercel.ai.error.${SH}`;var IH="AI_NoSuchProviderReferenceError",bO=`vercel.ai.error.${IH}`;var bH="AI_TooManyEmbeddingValuesForCallError",kO=`vercel.ai.error.${bH}`;var kH="AI_TypeValidationError",xO=`vercel.ai.error.${kH}`;var xH="AI_UnsupportedFunctionalityError",hO=`vercel.ai.error.${xH}`;var fJ=Object.freeze({status:"aborted"});function O(Y,J,X){function $(K,U){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Y),J(K,U);for(let V in z.prototype)if(!(V in K))Object.defineProperty(K,V,{value:z.prototype[V].bind(K)});K._zod.constr=z,K._zod.def=U}let Q=X?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:Y});function z(K){var U;let H=X?.Parent?new G:this;$(H,K),(U=H._zod).deferred??(U.deferred=[]);for(let V of H._zod.deferred)V();return H}return Object.defineProperty(z,"init",{value:$}),Object.defineProperty(z,Symbol.hasInstance,{value:(K)=>{if(X?.Parent&&K instanceof X.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(z,"name",{value:Y}),z}var hH=Symbol("zod_brand");class a6 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class z8 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var O9={};function Y6(Y){if(Y)Object.assign(O9,Y);return O9}var d={};cJ(d,{unwrapMessage:()=>W8,uint8ArrayToHex:()=>zB,uint8ArrayToBase64url:()=>QB,uint8ArrayToBase64:()=>i5,stringifyPrimitive:()=>A9,shallowClone:()=>c5,safeExtend:()=>tH,required:()=>JB,randomString:()=>dH,propertyKeyTypes:()=>lJ,promiseAllObject:()=>lH,primitiveTypes:()=>u5,prefixIssues:()=>e6,pick:()=>rH,partial:()=>YB,optionalKeys:()=>dJ,omit:()=>sH,objectClone:()=>cH,numKeys:()=>iH,nullish:()=>U8,normalizeParams:()=>p,mergeDefs:()=>Z1,merge:()=>eH,jsonStringifyReplacer:()=>N4,joinValues:()=>P9,issue:()=>Z4,isPlainObject:()=>j1,isObject:()=>g1,hexToUint8Array:()=>GB,getSizableOrigin:()=>l5,getParsedType:()=>nH,getLengthableOrigin:()=>B8,getEnumValues:()=>K8,getElementAtPath:()=>pH,floatSafeRemainder:()=>uJ,finalizeIssue:()=>w6,extend:()=>aH,escapeRegex:()=>t6,esc:()=>q9,defineLazy:()=>G0,createTransparentProxy:()=>oH,cloneDef:()=>uH,clone:()=>J6,cleanRegex:()=>H8,cleanEnum:()=>XB,captureStackTrace:()=>E9,cached:()=>L4,base64urlToUint8Array:()=>$B,base64ToUint8Array:()=>d5,assignProp:()=>L1,assertNotEqual:()=>yH,assertNever:()=>fH,assertIs:()=>gH,assertEqual:()=>vH,assert:()=>mH,allowsEval:()=>pJ,aborted:()=>F1,NUMBER_FORMAT_RANGES:()=>iJ,Class:()=>n5,BIGINT_FORMAT_RANGES:()=>p5});function vH(Y){return Y}function yH(Y){return Y}function gH(Y){}function fH(Y){throw Error()}function mH(Y){}function K8(Y){let J=Object.values(Y).filter(($)=>typeof $==="number");return Object.entries(Y).filter(([$,Q])=>J.indexOf(+$)===-1).map(([$,Q])=>Q)}function P9(Y,J="|"){return Y.map((X)=>A9(X)).join(J)}function N4(Y,J){if(typeof J==="bigint")return J.toString();return J}function L4(Y){return{get value(){{let X=Y();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function U8(Y){return Y===null||Y===void 0}function H8(Y){let J=Y.startsWith("^")?1:0,X=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(J,X)}function uJ(Y,J){let X=(Y.toString().split(".")[1]||"").length,$=J.toString(),Q=($.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test($)){let U=$.match(/\d?e-(\d?)/);if(U?.[1])Q=Number.parseInt(U[1])}let G=X>Q?X:Q,z=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(J.toFixed(G).replace(".",""));return z%K/10**G}var m5=Symbol("evaluating");function G0(Y,J,X){let $=void 0;Object.defineProperty(Y,J,{get(){if($===m5)return;if($===void 0)$=m5,$=X();return $},set(Q){Object.defineProperty(Y,J,{value:Q})},configurable:!0})}function cH(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function L1(Y,J,X){Object.defineProperty(Y,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function Z1(...Y){let J={};for(let X of Y){let $=Object.getOwnPropertyDescriptors(X);Object.assign(J,$)}return Object.defineProperties({},J)}function uH(Y){return Z1(Y._zod.def)}function pH(Y,J){if(!J)return Y;return J.reduce((X,$)=>X?.[$],Y)}function lH(Y){let J=Object.keys(Y),X=J.map(($)=>Y[$]);return Promise.all(X).then(($)=>{let Q={};for(let G=0;G<J.length;G++)Q[J[G]]=$[G];return Q})}function dH(Y=10){let X="";for(let $=0;$<Y;$++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function q9(Y){return JSON.stringify(Y)}var E9="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function g1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var pJ=L4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function j1(Y){if(g1(Y)===!1)return!1;let J=Y.constructor;if(J===void 0)return!0;let X=J.prototype;if(g1(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function c5(Y){if(j1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function iH(Y){let J=0;for(let X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))J++;return J}var nH=(Y)=>{let J=typeof Y;switch(J){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: ${J}`)}},lJ=new Set(["string","number","symbol"]),u5=new Set(["string","number","bigint","boolean","symbol","undefined"]);function t6(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J6(Y,J,X){let $=new Y._zod.constr(J??Y._zod.def);if(!J||X?.parent)$._zod.parent=Y;return $}function p(Y){let J=Y;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function oH(Y){let J;return new Proxy({},{get(X,$,Q){return J??(J=Y()),Reflect.get(J,$,Q)},set(X,$,Q,G){return J??(J=Y()),Reflect.set(J,$,Q,G)},has(X,$){return J??(J=Y()),Reflect.has(J,$)},deleteProperty(X,$){return J??(J=Y()),Reflect.deleteProperty(J,$)},ownKeys(X){return J??(J=Y()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,$){return J??(J=Y()),Reflect.getOwnPropertyDescriptor(J,$)},defineProperty(X,$,Q){return J??(J=Y()),Reflect.defineProperty(J,$,Q)}})}function A9(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function dJ(Y){return Object.keys(Y).filter((J)=>{return Y[J]._zod.optin==="optional"&&Y[J]._zod.optout==="optional"})}var iJ={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]},p5={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rH(Y,J){let X=Y._zod.def,$=Z1(Y._zod.def,{get shape(){let Q={};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;Q[G]=X.shape[G]}return L1(this,"shape",Q),Q},checks:[]});return J6(Y,$)}function sH(Y,J){let X=Y._zod.def,$=Z1(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape};for(let G in J){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;delete Q[G]}return L1(this,"shape",Q),Q},checks:[]});return J6(Y,$)}function aH(Y,J){if(!j1(J))throw Error("Invalid input to extend: expected a plain object");let X=Y._zod.def.checks;if(X&&X.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Z1(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...J};return L1(this,"shape",G),G},checks:[]});return J6(Y,Q)}function tH(Y,J){if(!j1(J))throw Error("Invalid input to safeExtend: expected a plain object");let X={...Y._zod.def,get shape(){let $={...Y._zod.def.shape,...J};return L1(this,"shape",$),$},checks:Y._zod.def.checks};return J6(Y,X)}function eH(Y,J){let X=Z1(Y._zod.def,{get shape(){let $={...Y._zod.def.shape,...J._zod.def.shape};return L1(this,"shape",$),$},get catchall(){return J._zod.def.catchall},checks:[]});return J6(Y,X)}function YB(Y,J,X){let $=Z1(J._zod.def,{get shape(){let Q=J._zod.def.shape,G={...Q};if(X)for(let z in X){if(!(z in Q))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;G[z]=Y?new Y({type:"optional",innerType:Q[z]}):Q[z]}else for(let z in Q)G[z]=Y?new Y({type:"optional",innerType:Q[z]}):Q[z];return L1(this,"shape",G),G},checks:[]});return J6(J,$)}function JB(Y,J,X){let $=Z1(J._zod.def,{get shape(){let Q=J._zod.def.shape,G={...Q};if(X)for(let z in X){if(!(z in G))throw Error(`Unrecognized key: "${z}"`);if(!X[z])continue;G[z]=new Y({type:"nonoptional",innerType:Q[z]})}else for(let z in Q)G[z]=new Y({type:"nonoptional",innerType:Q[z]});return L1(this,"shape",G),G},checks:[]});return J6(J,$)}function F1(Y,J=0){if(Y.aborted===!0)return!0;for(let X=J;X<Y.issues.length;X++)if(Y.issues[X]?.continue!==!0)return!0;return!1}function e6(Y,J){return J.map((X)=>{var $;return($=X).path??($.path=[]),X.path.unshift(Y),X})}function W8(Y){return typeof Y==="string"?Y:Y?.message}function w6(Y,J,X){let $={...Y,path:Y.path??[]};if(!Y.message){let Q=W8(Y.inst?._zod.def?.error?.(Y))??W8(J?.error?.(Y))??W8(X.customError?.(Y))??W8(X.localeError?.(Y))??"Invalid input";$.message=Q}if(delete $.inst,delete $.continue,!J?.reportInput)delete $.input;return $}function l5(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function B8(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function Z4(...Y){let[J,X,$]=Y;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:$};return{...J}}function XB(Y){return Object.entries(Y).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function d5(Y){let J=atob(Y),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}function i5(Y){let J="";for(let X=0;X<Y.length;X++)J+=String.fromCharCode(Y[X]);return btoa(J)}function $B(Y){let J=Y.replace(/-/g,"+").replace(/_/g,"/"),X="=".repeat((4-J.length%4)%4);return d5(J+X)}function QB(Y){return i5(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function GB(Y){let J=Y.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let X=new Uint8Array(J.length/2);for(let $=0;$<J.length;$+=2)X[$/2]=Number.parseInt(J.slice($,$+2),16);return X}function zB(Y){return Array.from(Y).map((J)=>J.toString(16).padStart(2,"0")).join("")}class n5{constructor(...Y){}}var o5=(Y,J)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:J,enumerable:!1}),Y.message=JSON.stringify(J,N4,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},M9=O("$ZodError",o5),V8=O("$ZodError",o5,{Parent:Error});function nJ(Y,J=(X)=>X.message){let X={},$=[];for(let Q of Y.issues)if(Q.path.length>0)X[Q.path[0]]=X[Q.path[0]]||[],X[Q.path[0]].push(J(Q));else $.push(J(Q));return{formErrors:$,fieldErrors:X}}function oJ(Y,J){let X=J||function(G){return G.message},$={_errors:[]},Q=(G)=>{for(let z of G.issues)if(z.code==="invalid_union"&&z.errors.length)z.errors.map((K)=>Q({issues:K}));else if(z.code==="invalid_key")Q({issues:z.issues});else if(z.code==="invalid_element")Q({issues:z.issues});else if(z.path.length===0)$._errors.push(X(z));else{let K=$,U=0;while(U<z.path.length){let H=z.path[U];if(U!==z.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(X(z));K=K[H],U++}}};return Q(Y),$}var N8=(Y)=>(J,X,$,Q)=>{let G=$?Object.assign($,{async:!1}):{async:!1},z=J._zod.run({value:X,issues:[]},G);if(z instanceof Promise)throw new a6;if(z.issues.length){let K=new(Q?.Err??Y)(z.issues.map((U)=>w6(U,G,Y6())));throw E9(K,Q?.callee),K}return z.value},T9=N8(V8),L8=(Y)=>async(J,X,$,Q)=>{let G=$?Object.assign($,{async:!0}):{async:!0},z=J._zod.run({value:X,issues:[]},G);if(z instanceof Promise)z=await z;if(z.issues.length){let K=new(Q?.Err??Y)(z.issues.map((U)=>w6(U,G,Y6())));throw E9(K,Q?.callee),K}return z.value},R9=L8(V8),Z8=(Y)=>(J,X,$)=>{let Q=$?{...$,async:!1}:{async:!1},G=J._zod.run({value:X,issues:[]},Q);if(G instanceof Promise)throw new a6;return G.issues.length?{success:!1,error:new(Y??M9)(G.issues.map((z)=>w6(z,Q,Y6())))}:{success:!0,data:G.value}},f1=Z8(V8),j8=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{async:!0}):{async:!0},G=J._zod.run({value:X,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((z)=>w6(z,Q,Y6())))}:{success:!0,data:G.value}},F8=j8(V8),r5=(Y)=>(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return N8(Y)(J,X,Q)};var s5=(Y)=>(J,X,$)=>{return N8(Y)(J,X,$)};var a5=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return L8(Y)(J,X,Q)};var t5=(Y)=>async(J,X,$)=>{return L8(Y)(J,X,$)};var e5=(Y)=>(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return Z8(Y)(J,X,Q)};var Y2=(Y)=>(J,X,$)=>{return Z8(Y)(J,X,$)};var J2=(Y)=>async(J,X,$)=>{let Q=$?Object.assign($,{direction:"backward"}):{direction:"backward"};return j8(Y)(J,X,Q)};var X2=(Y)=>async(J,X,$)=>{return j8(Y)(J,X,$)};var $2=/^[cC][^\s-]{8,}$/,Q2=/^[0-9a-z]+$/,G2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,z2=/^[0-9a-vA-V]{20}$/,W2=/^[A-Za-z0-9]{27}$/,K2=/^[a-zA-Z0-9_-]{21}$/,U2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var H2=/^([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})$/,rJ=(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 B2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function V2(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var N2=/^(?:(?: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])$/,L2=/^(([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}|:))$/,Z2=/^((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])$/,j2=/^(([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])$/,F2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,sJ=/^[A-Za-z0-9_-]*$/,_2=/^(?=.{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 D2=/^\+(?:[0-9]){6,14}[0-9]$/,O2="(?:(?:\\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])))",P2=new RegExp(`^${O2}$`);function q2(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 E2(Y){return new RegExp(`^${q2(Y)}$`)}function A2(Y){let J=q2({precision:Y.precision}),X=["Z"];if(Y.local)X.push("");if(Y.offset)X.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let $=`${J}(?:${X.join("|")})`;return new RegExp(`^${O2}T(?:${$})$`)}var M2=(Y)=>{let J=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var T2=/^-?\d+$/,R2=/^-?\d+(?:\.\d+)?/,C2=/^(?:true|false)$/i,w2=/^null$/i;var S2=/^[^A-Z]*$/,I2=/^[^a-z]*$/;var k0=O("$ZodCheck",(Y,J)=>{var X;Y._zod??(Y._zod={}),Y._zod.def=J,(X=Y._zod).onattach??(X.onattach=[])}),b2={number:"number",bigint:"bigint",object:"date"},aJ=O("$ZodCheckLessThan",(Y,J)=>{k0.init(Y,J);let X=b2[typeof J.value];Y._zod.onattach.push(($)=>{let Q=$._zod.bag,G=(J.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<G)if(J.inclusive)Q.maximum=J.value;else Q.exclusiveMaximum=J.value}),Y._zod.check=($)=>{if(J.inclusive?$.value<=J.value:$.value<J.value)return;$.issues.push({origin:X,code:"too_big",maximum:J.value,input:$.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),tJ=O("$ZodCheckGreaterThan",(Y,J)=>{k0.init(Y,J);let X=b2[typeof J.value];Y._zod.onattach.push(($)=>{let Q=$._zod.bag,G=(J.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>G)if(J.inclusive)Q.minimum=J.value;else Q.exclusiveMinimum=J.value}),Y._zod.check=($)=>{if(J.inclusive?$.value>=J.value:$.value>J.value)return;$.issues.push({origin:X,code:"too_small",minimum:J.value,input:$.value,inclusive:J.inclusive,inst:Y,continue:!J.abort})}}),k2=O("$ZodCheckMultipleOf",(Y,J)=>{k0.init(Y,J),Y._zod.onattach.push((X)=>{var $;($=X._zod.bag).multipleOf??($.multipleOf=J.value)}),Y._zod.check=(X)=>{if(typeof X.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%J.value===BigInt(0):uJ(X.value,J.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:J.value,input:X.value,inst:Y,continue:!J.abort})}}),x2=O("$ZodCheckNumberFormat",(Y,J)=>{k0.init(Y,J),J.format=J.format||"float64";let X=J.format?.includes("int"),$=X?"int":"number",[Q,G]=iJ[J.format];Y._zod.onattach.push((z)=>{let K=z._zod.bag;if(K.format=J.format,K.minimum=Q,K.maximum=G,X)K.pattern=T2}),Y._zod.check=(z)=>{let K=z.value;if(X){if(!Number.isInteger(K)){z.issues.push({expected:$,format:J.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)z.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:$,continue:!J.abort});else z.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:$,continue:!J.abort});return}}if(K<Q)z.issues.push({origin:"number",input:K,code:"too_small",minimum:Q,inclusive:!0,inst:Y,continue:!J.abort});if(K>G)z.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var h2=O("$ZodCheckMaxLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!U8(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Q)$._zod.bag.maximum=J.maximum}),Y._zod.check=($)=>{let Q=$.value;if(Q.length<=J.maximum)return;let z=B8(Q);$.issues.push({origin:z,code:"too_big",maximum:J.maximum,inclusive:!0,input:Q,inst:Y,continue:!J.abort})}}),v2=O("$ZodCheckMinLength",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!U8(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Q)$._zod.bag.minimum=J.minimum}),Y._zod.check=($)=>{let Q=$.value;if(Q.length>=J.minimum)return;let z=B8(Q);$.issues.push({origin:z,code:"too_small",minimum:J.minimum,inclusive:!0,input:Q,inst:Y,continue:!J.abort})}}),y2=O("$ZodCheckLengthEquals",(Y,J)=>{var X;k0.init(Y,J),(X=Y._zod.def).when??(X.when=($)=>{let Q=$.value;return!U8(Q)&&Q.length!==void 0}),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.minimum=J.length,Q.maximum=J.length,Q.length=J.length}),Y._zod.check=($)=>{let Q=$.value,G=Q.length;if(G===J.length)return;let z=B8(Q),K=G>J.length;$.issues.push({origin:z,...K?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:$.value,inst:Y,continue:!J.abort})}}),_8=O("$ZodCheckStringFormat",(Y,J)=>{var X,$;if(k0.init(Y,J),Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=J.format,J.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(J.pattern)}),J.pattern)(X=Y._zod).check??(X.check=(Q)=>{if(J.pattern.lastIndex=0,J.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:J.format,input:Q.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Y,continue:!J.abort})});else($=Y._zod).check??($.check=()=>{})}),g2=O("$ZodCheckRegex",(Y,J)=>{_8.init(Y,J),Y._zod.check=(X)=>{if(J.pattern.lastIndex=0,J.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:J.pattern.toString(),inst:Y,continue:!J.abort})}}),f2=O("$ZodCheckLowerCase",(Y,J)=>{J.pattern??(J.pattern=S2),_8.init(Y,J)}),m2=O("$ZodCheckUpperCase",(Y,J)=>{J.pattern??(J.pattern=I2),_8.init(Y,J)}),c2=O("$ZodCheckIncludes",(Y,J)=>{k0.init(Y,J);let X=t6(J.includes),$=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=$,Y._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add($)}),Y._zod.check=(Q)=>{if(Q.value.includes(J.includes,J.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:Q.value,inst:Y,continue:!J.abort})}}),u2=O("$ZodCheckStartsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`^${t6(J.prefix)}.*`);J.pattern??(J.pattern=X),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(X)}),Y._zod.check=($)=>{if($.value.startsWith(J.prefix))return;$.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:$.value,inst:Y,continue:!J.abort})}}),p2=O("$ZodCheckEndsWith",(Y,J)=>{k0.init(Y,J);let X=new RegExp(`.*${t6(J.suffix)}$`);J.pattern??(J.pattern=X),Y._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(X)}),Y._zod.check=($)=>{if($.value.endsWith(J.suffix))return;$.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:$.value,inst:Y,continue:!J.abort})}});var l2=O("$ZodCheckOverwrite",(Y,J)=>{k0.init(Y,J),Y._zod.check=(X)=>{X.value=J.tx(X.value)}});class eJ{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 X=Y.split(`
6
+ `).filter((G)=>G),$=Math.min(...X.map((G)=>G.length-G.trimStart().length)),Q=X.map((G)=>G.slice($)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of Q)this.content.push(G)}compile(){let Y=Function,J=this?.args,$=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new Y(...J,$.join(`
7
+ `))}}var i2={major:4,minor:1,patch:8};var Z0=O("$ZodType",(Y,J)=>{var X;Y??(Y={}),Y._zod.def=J,Y._zod.bag=Y._zod.bag||{},Y._zod.version=i2;let $=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))$.unshift(Y);for(let Q of $)for(let G of Q._zod.onattach)G(Y);if($.length===0)(X=Y._zod).deferred??(X.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let Q=(z,K,U)=>{let H=F1(z),V;for(let F of K){if(F._zod.def.when){if(!F._zod.def.when(z))continue}else if(H)continue;let Z=z.issues.length,N=F._zod.check(z);if(N instanceof Promise&&U?.async===!1)throw new a6;if(V||N instanceof Promise)V=(V??Promise.resolve()).then(async()=>{if(await N,z.issues.length===Z)return;if(!H)H=F1(z,Z)});else{if(z.issues.length===Z)continue;if(!H)H=F1(z,Z)}}if(V)return V.then(()=>{return z});return z},G=(z,K,U)=>{if(F1(z))return z.aborted=!0,z;let H=Q(K,$,U);if(H instanceof Promise){if(U.async===!1)throw new a6;return H.then((V)=>Y._zod.parse(V,U))}return Y._zod.parse(H,U)};Y._zod.run=(z,K)=>{if(K.skipChecks)return Y._zod.parse(z,K);if(K.direction==="backward"){let H=Y._zod.parse({value:z.value,issues:[]},{...K,skipChecks:!0});if(H instanceof Promise)return H.then((V)=>{return G(V,z,K)});return G(H,z,K)}let U=Y._zod.parse(z,K);if(U instanceof Promise){if(K.async===!1)throw new a6;return U.then((H)=>Q(H,$,K))}return Q(U,$,K)}}Y["~standard"]={validate:(Q)=>{try{let G=f1(Y,Q);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return F8(Y,Q).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),F4=O("$ZodString",(Y,J)=>{Z0.init(Y,J),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??M2(Y._zod.bag),Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=String(X.value)}catch(Q){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Y}),X}}),O0=O("$ZodStringFormat",(Y,J)=>{_8.init(Y,J),F4.init(Y,J)}),JX=O("$ZodGUID",(Y,J)=>{J.pattern??(J.pattern=H2),O0.init(Y,J)}),XX=O("$ZodUUID",(Y,J)=>{if(J.version){let $={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if($===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=rJ($))}else J.pattern??(J.pattern=rJ());O0.init(Y,J)}),$X=O("$ZodEmail",(Y,J)=>{J.pattern??(J.pattern=B2),O0.init(Y,J)}),QX=O("$ZodURL",(Y,J)=>{O0.init(Y,J),Y._zod.check=(X)=>{try{let $=X.value.trim(),Q=new URL($);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(Q.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_2.source,input:X.value,inst:Y,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:X.value,inst:Y,continue:!J.abort})}if(J.normalize)X.value=Q.href;else X.value=$;return}catch($){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Y,continue:!J.abort})}}}),GX=O("$ZodEmoji",(Y,J)=>{J.pattern??(J.pattern=V2()),O0.init(Y,J)}),zX=O("$ZodNanoID",(Y,J)=>{J.pattern??(J.pattern=K2),O0.init(Y,J)}),WX=O("$ZodCUID",(Y,J)=>{J.pattern??(J.pattern=$2),O0.init(Y,J)}),KX=O("$ZodCUID2",(Y,J)=>{J.pattern??(J.pattern=Q2),O0.init(Y,J)}),UX=O("$ZodULID",(Y,J)=>{J.pattern??(J.pattern=G2),O0.init(Y,J)}),HX=O("$ZodXID",(Y,J)=>{J.pattern??(J.pattern=z2),O0.init(Y,J)}),BX=O("$ZodKSUID",(Y,J)=>{J.pattern??(J.pattern=W2),O0.init(Y,J)}),JQ=O("$ZodISODateTime",(Y,J)=>{J.pattern??(J.pattern=A2(J)),O0.init(Y,J)}),XQ=O("$ZodISODate",(Y,J)=>{J.pattern??(J.pattern=P2),O0.init(Y,J)}),$Q=O("$ZodISOTime",(Y,J)=>{J.pattern??(J.pattern=E2(J)),O0.init(Y,J)}),QQ=O("$ZodISODuration",(Y,J)=>{J.pattern??(J.pattern=U2),O0.init(Y,J)}),VX=O("$ZodIPv4",(Y,J)=>{J.pattern??(J.pattern=N2),O0.init(Y,J),Y._zod.onattach.push((X)=>{let $=X._zod.bag;$.format="ipv4"})}),NX=O("$ZodIPv6",(Y,J)=>{J.pattern??(J.pattern=L2),O0.init(Y,J),Y._zod.onattach.push((X)=>{let $=X._zod.bag;$.format="ipv6"}),Y._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:Y,continue:!J.abort})}}}),LX=O("$ZodCIDRv4",(Y,J)=>{J.pattern??(J.pattern=Z2),O0.init(Y,J)}),ZX=O("$ZodCIDRv6",(Y,J)=>{J.pattern??(J.pattern=j2),O0.init(Y,J),Y._zod.check=(X)=>{let $=X.value.split("/");try{if($.length!==2)throw Error();let[Q,G]=$;if(!G)throw Error();let z=Number(G);if(`${z}`!==G)throw Error();if(z<0||z>128)throw Error();new URL(`http://[${Q}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:Y,continue:!J.abort})}}});function GQ(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var jX=O("$ZodBase64",(Y,J)=>{J.pattern??(J.pattern=F2),O0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),Y._zod.check=(X)=>{if(GQ(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:Y,continue:!J.abort})}});function KB(Y){if(!sJ.test(Y))return!1;let J=Y.replace(/[-_]/g,($)=>$==="-"?"+":"/"),X=J.padEnd(Math.ceil(J.length/4)*4,"=");return GQ(X)}var FX=O("$ZodBase64URL",(Y,J)=>{J.pattern??(J.pattern=sJ),O0.init(Y,J),Y._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),Y._zod.check=(X)=>{if(KB(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:Y,continue:!J.abort})}}),_X=O("$ZodE164",(Y,J)=>{J.pattern??(J.pattern=D2),O0.init(Y,J)});function UB(Y,J=null){try{let X=Y.split(".");if(X.length!==3)return!1;let[$]=X;if(!$)return!1;let Q=JSON.parse(atob($));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(J&&(!("alg"in Q)||Q.alg!==J))return!1;return!0}catch{return!1}}var DX=O("$ZodJWT",(Y,J)=>{O0.init(Y,J),Y._zod.check=(X)=>{if(UB(X.value,J.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:Y,continue:!J.abort})}});var D8=O("$ZodNumber",(Y,J)=>{Z0.init(Y,J),Y._zod.pattern=Y._zod.bag.pattern??R2,Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=Number(X.value)}catch(z){}let Q=X.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return X;let G=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:Q,inst:Y,...G?{received:G}:{}}),X}}),S9=O("$ZodNumber",(Y,J)=>{x2.init(Y,J),D8.init(Y,J)}),I9=O("$ZodBoolean",(Y,J)=>{Z0.init(Y,J),Y._zod.pattern=C2,Y._zod.parse=(X,$)=>{if(J.coerce)try{X.value=Boolean(X.value)}catch(G){}let Q=X.value;if(typeof Q==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:Y}),X}});var OX=O("$ZodNull",(Y,J)=>{Z0.init(Y,J),Y._zod.pattern=w2,Y._zod.values=new Set([null]),Y._zod.parse=(X,$)=>{let Q=X.value;if(Q===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:Q,inst:Y}),X}});var b9=O("$ZodUnknown",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X)=>X}),k9=O("$ZodNever",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X,$)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Y}),X}});function n2(Y,J,X){if(Y.issues.length)J.issues.push(...e6(X,Y.issues));J.value[X]=Y.value}var x9=O("$ZodArray",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value;if(!Array.isArray(Q))return X.issues.push({expected:"array",code:"invalid_type",input:Q,inst:Y}),X;X.value=Array(Q.length);let G=[];for(let z=0;z<Q.length;z++){let K=Q[z],U=J.element._zod.run({value:K,issues:[]},$);if(U instanceof Promise)G.push(U.then((H)=>n2(H,X,z)));else n2(U,X,z)}if(G.length)return Promise.all(G).then(()=>X);return X}});function w9(Y,J,X,$){if(Y.issues.length)J.issues.push(...e6(X,Y.issues));if(Y.value===void 0){if(X in $)J.value[X]=void 0}else J.value[X]=Y.value}function zQ(Y){let J=Object.keys(Y.shape);for(let $ of J)if(!Y.shape?.[$]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${$}": expected a Zod schema`);let X=dJ(Y.shape);return{...Y,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(X)}}function WQ(Y,J,X,$,Q,G){let z=[],K=Q.keySet,U=Q.catchall._zod,H=U.def.type;for(let V of Object.keys(J)){if(K.has(V))continue;if(H==="never"){z.push(V);continue}let F=U.run({value:J[V],issues:[]},$);if(F instanceof Promise)Y.push(F.then((Z)=>w9(Z,X,V,J)));else w9(F,X,V,J)}if(z.length)X.issues.push({code:"unrecognized_keys",keys:z,input:J,inst:G});if(!Y.length)return X;return Promise.all(Y).then(()=>{return X})}var PX=O("$ZodObject",(Y,J)=>{Z0.init(Y,J);let X=L4(()=>zQ(J));G0(Y._zod,"propValues",()=>{let z=J.shape,K={};for(let U in z){let H=z[U]._zod;if(H.values){K[U]??(K[U]=new Set);for(let V of H.values)K[U].add(V)}}return K});let $=g1,Q=J.catchall,G;Y._zod.parse=(z,K)=>{G??(G=X.value);let U=z.value;if(!$(U))return z.issues.push({expected:"object",code:"invalid_type",input:U,inst:Y}),z;z.value={};let H=[],V=G.shape;for(let F of G.keys){let N=V[F]._zod.run({value:U[F],issues:[]},K);if(N instanceof Promise)H.push(N.then((j)=>w9(j,z,F,U)));else w9(N,z,F,U)}if(!Q)return H.length?Promise.all(H).then(()=>z):z;return WQ(H,U,z,K,X.value,Y)}}),KQ=O("$ZodObjectJIT",(Y,J)=>{PX.init(Y,J);let X=Y._zod.parse,$=L4(()=>zQ(J)),Q=(Z)=>{let N=new eJ(["shape","payload","ctx"]),j=$.value,P=(A)=>{let q=q9(A);return`shape[${q}]._zod.run({ value: input[${q}], issues: [] }, ctx)`};N.write("const input = payload.value;");let v=Object.create(null),y=0;for(let A of j.keys)v[A]=`key_${y++}`;N.write("const newResult = {};");for(let A of j.keys){let q=v[A],C=q9(A);N.write(`const ${q} = ${P(A)};`),N.write(`
8
+ if (${q}.issues.length) {
9
+ payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
10
+ ...iss,
11
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
12
+ })));
13
+ }
14
+
15
+
16
+ if (${q}.value === undefined) {
17
+ if (${C} in input) {
18
+ newResult[${C}] = undefined;
19
+ }
20
+ } else {
21
+ newResult[${C}] = ${q}.value;
22
+ }
23
+
24
+ `)}N.write("payload.value = newResult;"),N.write("return payload;");let I=N.compile();return(A,q)=>I(Z,A,q)},G,z=g1,K=!O9.jitless,H=K&&pJ.value,V=J.catchall,F;Y._zod.parse=(Z,N)=>{F??(F=$.value);let j=Z.value;if(!z(j))return Z.issues.push({expected:"object",code:"invalid_type",input:j,inst:Y}),Z;if(K&&H&&N?.async===!1&&N.jitless!==!0){if(!G)G=Q(J.shape);if(Z=G(Z,N),!V)return Z;return WQ([],j,Z,N,F,Y)}return X(Z,N)}});function o2(Y,J,X,$){for(let G of Y)if(G.issues.length===0)return J.value=G.value,J;let Q=Y.filter((G)=>!F1(G));if(Q.length===1)return J.value=Q[0].value,Q[0];return J.issues.push({code:"invalid_union",input:J.value,inst:X,errors:Y.map((G)=>G.issues.map((z)=>w6(z,$,Y6())))}),J}var O8=O("$ZodUnion",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"optin",()=>J.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),G0(Y._zod,"optout",()=>J.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),G0(Y._zod,"values",()=>{if(J.options.every((Q)=>Q._zod.values))return new Set(J.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),G0(Y._zod,"pattern",()=>{if(J.options.every((Q)=>Q._zod.pattern)){let Q=J.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>H8(G.source)).join("|")})$`)}return});let X=J.options.length===1,$=J.options[0]._zod.run;Y._zod.parse=(Q,G)=>{if(X)return $(Q,G);let z=!1,K=[];for(let U of J.options){let H=U._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)K.push(H),z=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!z)return o2(K,Q,Y,G);return Promise.all(K).then((U)=>{return o2(U,Q,Y,G)})}}),h9=O("$ZodDiscriminatedUnion",(Y,J)=>{O8.init(Y,J);let X=Y._zod.parse;G0(Y._zod,"propValues",()=>{let Q={};for(let G of J.options){let z=G._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(G)}"`);for(let[K,U]of Object.entries(z)){if(!Q[K])Q[K]=new Set;for(let H of U)Q[K].add(H)}}return Q});let $=L4(()=>{let Q=J.options,G=new Map;for(let z of Q){let K=z._zod.propValues?.[J.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(z)}"`);for(let U of K){if(G.has(U))throw Error(`Duplicate discriminator value "${String(U)}"`);G.set(U,z)}}return G});Y._zod.parse=(Q,G)=>{let z=Q.value;if(!g1(z))return Q.issues.push({code:"invalid_type",expected:"object",input:z,inst:Y}),Q;let K=$.value.get(z?.[J.discriminator]);if(K)return K._zod.run(Q,G);if(J.unionFallback)return X(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:z,path:[J.discriminator],inst:Y}),Q}}),qX=O("$ZodIntersection",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value,G=J.left._zod.run({value:Q,issues:[]},$),z=J.right._zod.run({value:Q,issues:[]},$);if(G instanceof Promise||z instanceof Promise)return Promise.all([G,z]).then(([U,H])=>{return r2(X,U,H)});return r2(X,G,z)}});function YX(Y,J){if(Y===J)return{valid:!0,data:Y};if(Y instanceof Date&&J instanceof Date&&+Y===+J)return{valid:!0,data:Y};if(j1(Y)&&j1(J)){let X=Object.keys(J),$=Object.keys(Y).filter((G)=>X.indexOf(G)!==-1),Q={...Y,...J};for(let G of $){let z=YX(Y[G],J[G]);if(!z.valid)return{valid:!1,mergeErrorPath:[G,...z.mergeErrorPath]};Q[G]=z.data}return{valid:!0,data:Q}}if(Array.isArray(Y)&&Array.isArray(J)){if(Y.length!==J.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let $=0;$<Y.length;$++){let Q=Y[$],G=J[$],z=YX(Q,G);if(!z.valid)return{valid:!1,mergeErrorPath:[$,...z.mergeErrorPath]};X.push(z.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function r2(Y,J,X){if(J.issues.length)Y.issues.push(...J.issues);if(X.issues.length)Y.issues.push(...X.issues);if(F1(Y))return Y;let $=YX(J.value,X.value);if(!$.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify($.mergeErrorPath)}`);return Y.value=$.data,Y}var v9=O("$ZodRecord",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X,$)=>{let Q=X.value;if(!j1(Q))return X.issues.push({expected:"record",code:"invalid_type",input:Q,inst:Y}),X;let G=[];if(J.keyType._zod.values){let z=J.keyType._zod.values;X.value={};for(let U of z)if(typeof U==="string"||typeof U==="number"||typeof U==="symbol"){let H=J.valueType._zod.run({value:Q[U],issues:[]},$);if(H instanceof Promise)G.push(H.then((V)=>{if(V.issues.length)X.issues.push(...e6(U,V.issues));X.value[U]=V.value}));else{if(H.issues.length)X.issues.push(...e6(U,H.issues));X.value[U]=H.value}}let K;for(let U in Q)if(!z.has(U))K=K??[],K.push(U);if(K&&K.length>0)X.issues.push({code:"unrecognized_keys",input:Q,inst:Y,keys:K})}else{X.value={};for(let z of Reflect.ownKeys(Q)){if(z==="__proto__")continue;let K=J.keyType._zod.run({value:z,issues:[]},$);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((H)=>w6(H,$,Y6())),input:z,path:[z],inst:Y}),X.value[K.value]=K.value;continue}let U=J.valueType._zod.run({value:Q[z],issues:[]},$);if(U instanceof Promise)G.push(U.then((H)=>{if(H.issues.length)X.issues.push(...e6(z,H.issues));X.value[K.value]=H.value}));else{if(U.issues.length)X.issues.push(...e6(z,U.issues));X.value[K.value]=U.value}}}if(G.length)return Promise.all(G).then(()=>X);return X}});var y9=O("$ZodEnum",(Y,J)=>{Z0.init(Y,J);let X=K8(J.entries),$=new Set(X);Y._zod.values=$,Y._zod.pattern=new RegExp(`^(${X.filter((Q)=>lJ.has(typeof Q)).map((Q)=>typeof Q==="string"?t6(Q):Q.toString()).join("|")})$`),Y._zod.parse=(Q,G)=>{let z=Q.value;if($.has(z))return Q;return Q.issues.push({code:"invalid_value",values:X,input:z,inst:Y}),Q}}),g9=O("$ZodLiteral",(Y,J)=>{if(Z0.init(Y,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(J.values),Y._zod.pattern=new RegExp(`^(${J.values.map((X)=>typeof X==="string"?t6(X):X?t6(X.toString()):String(X)).join("|")})$`),Y._zod.parse=(X,$)=>{let Q=X.value;if(Y._zod.values.has(Q))return X;return X.issues.push({code:"invalid_value",values:J.values,input:Q,inst:Y}),X}});var f9=O("$ZodTransform",(Y,J)=>{Z0.init(Y,J),Y._zod.parse=(X,$)=>{if($.direction==="backward")throw new z8(Y.constructor.name);let Q=J.transform(X.value,X);if($.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((z)=>{return X.value=z,X});if(Q instanceof Promise)throw new a6;return X.value=Q,X}});function s2(Y,J){if(Y.issues.length&&J===void 0)return{issues:[],value:void 0};return Y}var m9=O("$ZodOptional",(Y,J)=>{Z0.init(Y,J),Y._zod.optin="optional",Y._zod.optout="optional",G0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),G0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${H8(X.source)})?$`):void 0}),Y._zod.parse=(X,$)=>{if(J.innerType._zod.optin==="optional"){let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>s2(G,X.value));return s2(Q,X.value)}if(X.value===void 0)return X;return J.innerType._zod.run(X,$)}}),EX=O("$ZodNullable",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),G0(Y._zod,"pattern",()=>{let X=J.innerType._zod.pattern;return X?new RegExp(`^(${H8(X.source)}|null)$`):void 0}),G0(Y._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),Y._zod.parse=(X,$)=>{if(X.value===null)return X;return J.innerType._zod.run(X,$)}}),AX=O("$ZodDefault",(Y,J)=>{Z0.init(Y,J),Y._zod.optin="optional",G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);if(X.value===void 0)return X.value=J.defaultValue,X;let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>a2(G,J));return a2(Q,J)}});function a2(Y,J){if(Y.value===void 0)Y.value=J.defaultValue;return Y}var MX=O("$ZodPrefault",(Y,J)=>{Z0.init(Y,J),Y._zod.optin="optional",G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);if(X.value===void 0)X.value=J.defaultValue;return J.innerType._zod.run(X,$)}}),TX=O("$ZodNonOptional",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"values",()=>{let X=J.innerType._zod.values;return X?new Set([...X].filter(($)=>$!==void 0)):void 0}),Y._zod.parse=(X,$)=>{let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>t2(G,Y));return t2(Q,Y)}});function t2(Y,J){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:J});return Y}var RX=O("$ZodCatch",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),G0(Y._zod,"values",()=>J.innerType._zod.values),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>{if(X.value=G.value,G.issues.length)X.value=J.catchValue({...X,error:{issues:G.issues.map((z)=>w6(z,$,Y6()))},input:X.value}),X.issues=[];return X});if(X.value=Q.value,Q.issues.length)X.value=J.catchValue({...X,error:{issues:Q.issues.map((G)=>w6(G,$,Y6()))},input:X.value}),X.issues=[];return X}});var c9=O("$ZodPipe",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"values",()=>J.in._zod.values),G0(Y._zod,"optin",()=>J.in._zod.optin),G0(Y._zod,"optout",()=>J.out._zod.optout),G0(Y._zod,"propValues",()=>J.in._zod.propValues),Y._zod.parse=(X,$)=>{if($.direction==="backward"){let G=J.out._zod.run(X,$);if(G instanceof Promise)return G.then((z)=>C9(z,J.in,$));return C9(G,J.in,$)}let Q=J.in._zod.run(X,$);if(Q instanceof Promise)return Q.then((G)=>C9(G,J.out,$));return C9(Q,J.out,$)}});function C9(Y,J,X){if(Y.issues.length)return Y.aborted=!0,Y;return J._zod.run({value:Y.value,issues:Y.issues},X)}var CX=O("$ZodReadonly",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"propValues",()=>J.innerType._zod.propValues),G0(Y._zod,"values",()=>J.innerType._zod.values),G0(Y._zod,"optin",()=>J.innerType._zod.optin),G0(Y._zod,"optout",()=>J.innerType._zod.optout),Y._zod.parse=(X,$)=>{if($.direction==="backward")return J.innerType._zod.run(X,$);let Q=J.innerType._zod.run(X,$);if(Q instanceof Promise)return Q.then(e2);return e2(Q)}});function e2(Y){return Y.value=Object.freeze(Y.value),Y}var wX=O("$ZodLazy",(Y,J)=>{Z0.init(Y,J),G0(Y._zod,"innerType",()=>J.getter()),G0(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),G0(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),G0(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),G0(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(X,$)=>{return Y._zod.innerType._zod.run(X,$)}}),u9=O("$ZodCustom",(Y,J)=>{k0.init(Y,J),Z0.init(Y,J),Y._zod.parse=(X,$)=>{return X},Y._zod.check=(X)=>{let $=X.value,Q=J.fn($);if(Q instanceof Promise)return Q.then((G)=>YQ(G,X,$,Y));YQ(Q,X,$,Y);return}});function YQ(Y,J,X,$){if(!Y){let Q={code:"custom",input:X,inst:$,path:[...$._zod.def.path??[]],continue:!$._zod.def.abort};if($._zod.def.params)Q.params=$._zod.def.params;J.issues.push(Z4(Q))}}var HB=(Y)=>{let J=typeof Y;switch(J){case"number":return Number.isNaN(Y)?"NaN":"number";case"object":{if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Object.getPrototypeOf(Y)!==Object.prototype&&Y.constructor)return Y.constructor.name}}return J},BB=()=>{let Y={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function J($){return Y[$]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return($)=>{switch($.code){case"invalid_type":return`Invalid input: expected ${$.expected}, received ${HB($.input)}`;case"invalid_value":if($.values.length===1)return`Invalid input: expected ${A9($.values[0])}`;return`Invalid option: expected one of ${P9($.values,"|")}`;case"too_big":{let Q=$.inclusive?"<=":"<",G=J($.origin);if(G)return`Too big: expected ${$.origin??"value"} to have ${Q}${$.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${$.origin??"value"} to be ${Q}${$.maximum.toString()}`}case"too_small":{let Q=$.inclusive?">=":">",G=J($.origin);if(G)return`Too small: expected ${$.origin} to have ${Q}${$.minimum.toString()} ${G.unit}`;return`Too small: expected ${$.origin} to be ${Q}${$.minimum.toString()}`}case"invalid_format":{let Q=$;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${X[Q.format]??$.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${$.divisor}`;case"unrecognized_keys":return`Unrecognized key${$.keys.length>1?"s":""}: ${P9($.keys,", ")}`;case"invalid_key":return`Invalid key in ${$.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${$.origin}`;default:return"Invalid input"}}};function SX(){return{localeError:BB()}}var VB=Symbol("ZodOutput"),NB=Symbol("ZodInput");class p9{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...J){let X=J[0];if(this._map.set(Y,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let J=this._map.get(Y);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete(Y),this}get(Y){let J=Y._zod.parent;if(J){let X={...this.get(J)??{}};delete X.id;let $={...X,...this._map.get(Y)};return Object.keys($).length?$:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function UQ(){return new p9}var _1=UQ();function l9(Y,J){return new Y({type:"string",...p(J)})}function IX(Y,J){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...p(J)})}function d9(Y,J){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...p(J)})}function bX(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...p(J)})}function kX(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...p(J)})}function xX(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...p(J)})}function hX(Y,J){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...p(J)})}function vX(Y,J){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...p(J)})}function yX(Y,J){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...p(J)})}function gX(Y,J){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...p(J)})}function fX(Y,J){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...p(J)})}function mX(Y,J){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...p(J)})}function cX(Y,J){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...p(J)})}function uX(Y,J){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...p(J)})}function pX(Y,J){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...p(J)})}function lX(Y,J){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...p(J)})}function dX(Y,J){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...p(J)})}function iX(Y,J){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...p(J)})}function nX(Y,J){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...p(J)})}function oX(Y,J){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...p(J)})}function rX(Y,J){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...p(J)})}function sX(Y,J){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...p(J)})}function aX(Y,J){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...p(J)})}function HQ(Y,J){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...p(J)})}function BQ(Y,J){return new Y({type:"string",format:"date",check:"string_format",...p(J)})}function VQ(Y,J){return new Y({type:"string",format:"time",check:"string_format",precision:null,...p(J)})}function NQ(Y,J){return new Y({type:"string",format:"duration",check:"string_format",...p(J)})}function i9(Y,J){return new Y({type:"number",checks:[],...p(J)})}function n9(Y,J){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...p(J)})}function o9(Y,J){return new Y({type:"boolean",...p(J)})}function tX(Y,J){return new Y({type:"null",...p(J)})}function r9(Y){return new Y({type:"unknown"})}function s9(Y,J){return new Y({type:"never",...p(J)})}function P8(Y,J){return new aJ({check:"less_than",...p(J),value:Y,inclusive:!1})}function Y1(Y,J){return new aJ({check:"less_than",...p(J),value:Y,inclusive:!0})}function _4(Y,J){return new tJ({check:"greater_than",...p(J),value:Y,inclusive:!1})}function D1(Y,J){return new tJ({check:"greater_than",...p(J),value:Y,inclusive:!0})}function a9(Y){return _4(0,Y)}function t9(Y){return D1(0,Y)}function q8(Y,J){return new k2({check:"multiple_of",...p(J),value:Y})}function E8(Y,J){return new h2({check:"max_length",...p(J),maximum:Y})}function J1(Y,J){return new v2({check:"min_length",...p(J),minimum:Y})}function A8(Y,J){return new y2({check:"length_equals",...p(J),length:Y})}function e9(Y,J){return new g2({check:"string_format",format:"regex",...p(J),pattern:Y})}function YY(Y){return new f2({check:"string_format",format:"lowercase",...p(Y)})}function JY(Y){return new m2({check:"string_format",format:"uppercase",...p(Y)})}function XY(Y,J){return new c2({check:"string_format",format:"includes",...p(J),includes:Y})}function D4(Y,J){return new u2({check:"string_format",format:"starts_with",...p(J),prefix:Y})}function $Y(Y,J){return new p2({check:"string_format",format:"ends_with",...p(J),suffix:Y})}function O1(Y){return new l2({check:"overwrite",tx:Y})}function QY(Y){return O1((J)=>J.normalize(Y))}function GY(){return O1((Y)=>Y.trim())}function zY(){return O1((Y)=>Y.toLowerCase())}function WY(){return O1((Y)=>Y.toUpperCase())}function LQ(Y,J,X){return new Y({type:"array",element:J,...p(X)})}function KY(Y,J,X){let $=p(X);return $.abort??($.abort=!0),new Y({type:"custom",check:"custom",fn:J,...$})}function UY(Y,J,X){return new Y({type:"custom",check:"custom",fn:J,...p(X)})}function eX(Y){let J=LB((X)=>{return X.addIssue=($)=>{if(typeof $==="string")X.issues.push(Z4($,X.value,J._zod.def));else{let Q=$;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=X.value),Q.inst??(Q.inst=J),Q.continue??(Q.continue=!J._zod.def.abort),X.issues.push(Z4(Q))}},Y(X.value,X)});return J}function LB(Y,J){let X=new k0({check:"custom",...p(J)});return X._zod.check=Y,X}class Y7{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??_1,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,J={path:[],schemaPath:[]}){var X;let $=Y._zod.def,Q={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,J.schemaPath.includes(Y))G.cycle=J.path;return G.schema}let z={schema:{},count:1,cycle:void 0,path:J.path};this.seen.set(Y,z);let K=Y._zod.toJSONSchema?.();if(K)z.schema=K;else{let V={...J,schemaPath:[...J.schemaPath,Y],path:J.path},F=Y._zod.parent;if(F)z.ref=F,this.process(F,V),this.seen.get(F).isParent=!0;else{let Z=z.schema;switch($.type){case"string":{let N=Z;N.type="string";let{minimum:j,maximum:P,format:v,patterns:y,contentEncoding:I}=Y._zod.bag;if(typeof j==="number")N.minLength=j;if(typeof P==="number")N.maxLength=P;if(v){if(N.format=Q[v]??v,N.format==="")delete N.format}if(I)N.contentEncoding=I;if(y&&y.size>0){let A=[...y];if(A.length===1)N.pattern=A[0].source;else if(A.length>1)z.schema.allOf=[...A.map((q)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:q.source}))]}break}case"number":{let N=Z,{minimum:j,maximum:P,format:v,multipleOf:y,exclusiveMaximum:I,exclusiveMinimum:A}=Y._zod.bag;if(typeof v==="string"&&v.includes("int"))N.type="integer";else N.type="number";if(typeof A==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=A,N.exclusiveMinimum=!0;else N.exclusiveMinimum=A;if(typeof j==="number"){if(N.minimum=j,typeof A==="number"&&this.target!=="draft-4")if(A>=j)delete N.minimum;else delete N.exclusiveMinimum}if(typeof I==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=I,N.exclusiveMaximum=!0;else N.exclusiveMaximum=I;if(typeof P==="number"){if(N.maximum=P,typeof I==="number"&&this.target!=="draft-4")if(I<=P)delete N.maximum;else delete N.exclusiveMaximum}if(typeof y==="number")N.multipleOf=y;break}case"boolean":{let N=Z;N.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.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":{Z.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let N=Z,{minimum:j,maximum:P}=Y._zod.bag;if(typeof j==="number")N.minItems=j;if(typeof P==="number")N.maxItems=P;N.type="array",N.items=this.process($.element,{...V,path:[...V.path,"items"]});break}case"object":{let N=Z;N.type="object",N.properties={};let j=$.shape;for(let y in j)N.properties[y]=this.process(j[y],{...V,path:[...V.path,"properties",y]});let P=new Set(Object.keys(j)),v=new Set([...P].filter((y)=>{let I=$.shape[y]._zod;if(this.io==="input")return I.optin===void 0;else return I.optout===void 0}));if(v.size>0)N.required=Array.from(v);if($.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!$.catchall){if(this.io==="output")N.additionalProperties=!1}else if($.catchall)N.additionalProperties=this.process($.catchall,{...V,path:[...V.path,"additionalProperties"]});break}case"union":{let N=Z,j=$.options.map((P,v)=>this.process(P,{...V,path:[...V.path,"anyOf",v]}));N.anyOf=j;break}case"intersection":{let N=Z,j=this.process($.left,{...V,path:[...V.path,"allOf",0]}),P=this.process($.right,{...V,path:[...V.path,"allOf",1]}),v=(I)=>("allOf"in I)&&Object.keys(I).length===1,y=[...v(j)?j.allOf:[j],...v(P)?P.allOf:[P]];N.allOf=y;break}case"tuple":{let N=Z;N.type="array";let j=this.target==="draft-2020-12"?"prefixItems":"items",P=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",v=$.items.map((q,C)=>this.process(q,{...V,path:[...V.path,j,C]})),y=$.rest?this.process($.rest,{...V,path:[...V.path,P,...this.target==="openapi-3.0"?[$.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=v,y)N.items=y}else if(this.target==="openapi-3.0"){if(N.items={anyOf:v},y)N.items.anyOf.push(y);if(N.minItems=v.length,!y)N.maxItems=v.length}else if(N.items=v,y)N.additionalItems=y;let{minimum:I,maximum:A}=Y._zod.bag;if(typeof I==="number")N.minItems=I;if(typeof A==="number")N.maxItems=A;break}case"record":{let N=Z;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process($.keyType,{...V,path:[...V.path,"propertyNames"]});N.additionalProperties=this.process($.valueType,{...V,path:[...V.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let N=Z,j=K8($.entries);if(j.every((P)=>typeof P==="number"))N.type="number";if(j.every((P)=>typeof P==="string"))N.type="string";N.enum=j;break}case"literal":{let N=Z,j=[];for(let P of $.values)if(P===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof P==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else j.push(Number(P));else j.push(P);if(j.length===0);else if(j.length===1){let P=j[0];if(N.type=P===null?"null":typeof P,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[P];else N.const=P}else{if(j.every((P)=>typeof P==="number"))N.type="number";if(j.every((P)=>typeof P==="string"))N.type="string";if(j.every((P)=>typeof P==="boolean"))N.type="string";if(j.every((P)=>P===null))N.type="null";N.enum=j}break}case"file":{let N=Z,j={type:"string",format:"binary",contentEncoding:"binary"},{minimum:P,maximum:v,mime:y}=Y._zod.bag;if(P!==void 0)j.minLength=P;if(v!==void 0)j.maxLength=v;if(y)if(y.length===1)j.contentMediaType=y[0],Object.assign(N,j);else N.anyOf=y.map((I)=>{return{...j,contentMediaType:I}});else Object.assign(N,j);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process($.innerType,V);if(this.target==="openapi-3.0")z.ref=$.innerType,Z.nullable=!0;else Z.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process($.innerType,V),z.ref=$.innerType;break}case"success":{let N=Z;N.type="boolean";break}case"default":{this.process($.innerType,V),z.ref=$.innerType,Z.default=JSON.parse(JSON.stringify($.defaultValue));break}case"prefault":{if(this.process($.innerType,V),z.ref=$.innerType,this.io==="input")Z._prefault=JSON.parse(JSON.stringify($.defaultValue));break}case"catch":{this.process($.innerType,V),z.ref=$.innerType;let N;try{N=$.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Z.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=Z,j=Y._zod.pattern;if(!j)throw Error("Pattern not found in template literal");N.type="string",N.pattern=j.source;break}case"pipe":{let N=this.io==="input"?$.in._zod.def.type==="transform"?$.out:$.in:$.out;this.process(N,V),z.ref=N;break}case"readonly":{this.process($.innerType,V),z.ref=$.innerType,Z.readOnly=!0;break}case"promise":{this.process($.innerType,V),z.ref=$.innerType;break}case"optional":{this.process($.innerType,V),z.ref=$.innerType;break}case"lazy":{let N=Y._zod.innerType;this.process(N,V),z.ref=N;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let U=this.metadataRegistry.get(Y);if(U)Object.assign(z.schema,U);if(this.io==="input"&&I0(Y))delete z.schema.examples,delete z.schema.default;if(this.io==="input"&&z.schema._prefault)(X=z.schema).default??(X.default=z.schema._prefault);return delete z.schema._prefault,this.seen.get(Y).schema}emit(Y,J){let X={cycles:J?.cycles??"ref",reused:J?.reused??"inline",external:J?.external??void 0},$=this.seen.get(Y);if(!$)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=(H)=>{let V=this.target==="draft-2020-12"?"$defs":"definitions";if(X.external){let j=X.external.registry.get(H[0])?.id,P=X.external.uri??((y)=>y);if(j)return{ref:P(j)};let v=H[1].defId??H[1].schema.id??`schema${this.counter++}`;return H[1].defId=v,{defId:v,ref:`${P("__shared")}#/${V}/${v}`}}if(H[1]===$)return{ref:"#"};let Z=`${"#"}/${V}/`,N=H[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:Z+N}},G=(H)=>{if(H[1].schema.$ref)return;let V=H[1],{ref:F,defId:Z}=Q(H);if(V.def={...V.schema},Z)V.defId=Z;let N=V.schema;for(let j in N)delete N[j];N.$ref=F};if(X.cycles==="throw")for(let H of this.seen.entries()){let V=H[1];if(V.cycle)throw Error(`Cycle detected: #/${V.cycle?.join("/")}/<root>
25
+
26
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let H of this.seen.entries()){let V=H[1];if(Y===H[0]){G(H);continue}if(X.external){let Z=X.external.registry.get(H[0])?.id;if(Y!==H[0]&&Z){G(H);continue}}if(this.metadataRegistry.get(H[0])?.id){G(H);continue}if(V.cycle){G(H);continue}if(V.count>1){if(X.reused==="ref"){G(H);continue}}}let z=(H,V)=>{let F=this.seen.get(H),Z=F.def??F.schema,N={...Z};if(F.ref===null)return;let j=F.ref;if(F.ref=null,j){z(j,V);let P=this.seen.get(j).schema;if(P.$ref&&(V.target==="draft-7"||V.target==="draft-4"||V.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(P);else Object.assign(Z,P),Object.assign(Z,N)}if(!F.isParent)this.override({zodSchema:H,jsonSchema:Z,path:F.path??[]})};for(let H of[...this.seen.entries()].reverse())z(H[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(X.external?.uri){let H=X.external.registry.get(Y)?.id;if(!H)throw Error("Schema is missing an `id` property");K.$id=X.external.uri(H)}Object.assign(K,$.def);let U=X.external?.defs??{};for(let H of this.seen.entries()){let V=H[1];if(V.def&&V.defId)U[V.defId]=V.def}if(X.external);else if(Object.keys(U).length>0)if(this.target==="draft-2020-12")K.$defs=U;else K.definitions=U;try{return JSON.parse(JSON.stringify(K))}catch(H){throw Error("Error converting schema to JSON.")}}}function J7(Y,J){if(Y instanceof p9){let $=new Y7(J),Q={};for(let K of Y._idmap.entries()){let[U,H]=K;$.process(H)}let G={},z={registry:Y,uri:J?.uri,defs:Q};for(let K of Y._idmap.entries()){let[U,H]=K;G[U]=$.emit(H,{...J,external:z})}if(Object.keys(Q).length>0){let K=$.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:Q}}return{schemas:G}}let X=new Y7(J);return X.process(Y),X.emit(Y,J)}function I0(Y,J){let X=J??{seen:new Set};if(X.seen.has(Y))return!1;X.seen.add(Y);let Q=Y._zod.def;switch(Q.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 I0(Q.element,X);case"object":{for(let G in Q.shape)if(I0(Q.shape[G],X))return!0;return!1}case"union":{for(let G of Q.options)if(I0(G,X))return!0;return!1}case"intersection":return I0(Q.left,X)||I0(Q.right,X);case"tuple":{for(let G of Q.items)if(I0(G,X))return!0;if(Q.rest&&I0(Q.rest,X))return!0;return!1}case"record":return I0(Q.keyType,X)||I0(Q.valueType,X);case"map":return I0(Q.keyType,X)||I0(Q.valueType,X);case"set":return I0(Q.valueType,X);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return I0(Q.innerType,X);case"lazy":return I0(Q.getter(),X);case"default":return I0(Q.innerType,X);case"prefault":return I0(Q.innerType,X);case"custom":return!1;case"transform":return!0;case"pipe":return I0(Q.in,X)||I0(Q.out,X);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${Q.type}`)}var OB=O("ZodISODateTime",(Y,J)=>{JQ.init(Y,J),P0.init(Y,J)});function DQ(Y){return HQ(OB,Y)}var PB=O("ZodISODate",(Y,J)=>{XQ.init(Y,J),P0.init(Y,J)});function OQ(Y){return BQ(PB,Y)}var qB=O("ZodISOTime",(Y,J)=>{$Q.init(Y,J),P0.init(Y,J)});function PQ(Y){return VQ(qB,Y)}var EB=O("ZodISODuration",(Y,J)=>{QQ.init(Y,J),P0.init(Y,J)});function qQ(Y){return NQ(EB,Y)}var EQ=(Y,J)=>{M9.init(Y,J),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(X)=>oJ(Y,X)},flatten:{value:(X)=>nJ(Y,X)},addIssue:{value:(X)=>{Y.issues.push(X),Y.message=JSON.stringify(Y.issues,N4,2)}},addIssues:{value:(X)=>{Y.issues.push(...X),Y.message=JSON.stringify(Y.issues,N4,2)}},isEmpty:{get(){return Y.issues.length===0}}})},PP=O("ZodError",EQ),W6=O("ZodError",EQ,{Parent:Error});var AQ=N8(W6),MQ=L8(W6),TQ=Z8(W6),HY=j8(W6),RQ=r5(W6),CQ=s5(W6),wQ=a5(W6),SQ=t5(W6),IQ=e5(W6),bQ=Y2(W6),kQ=J2(W6),xQ=X2(W6);var q0=O("ZodType",(Y,J)=>{return Z0.init(Y,J),Y.def=J,Y.type=J.type,Object.defineProperty(Y,"_def",{value:J}),Y.check=(...X)=>{return Y.clone({...J,checks:[...J.checks??[],...X.map(($)=>typeof $==="function"?{_zod:{check:$,def:{check:"custom"},onattach:[]}}:$)]})},Y.clone=(X,$)=>J6(Y,X,$),Y.brand=()=>Y,Y.register=(X,$)=>{return X.add(Y,$),Y},Y.parse=(X,$)=>AQ(Y,X,$,{callee:Y.parse}),Y.safeParse=(X,$)=>TQ(Y,X,$),Y.parseAsync=async(X,$)=>MQ(Y,X,$,{callee:Y.parseAsync}),Y.safeParseAsync=async(X,$)=>HY(Y,X,$),Y.spa=Y.safeParseAsync,Y.encode=(X,$)=>RQ(Y,X,$),Y.decode=(X,$)=>CQ(Y,X,$),Y.encodeAsync=async(X,$)=>wQ(Y,X,$),Y.decodeAsync=async(X,$)=>SQ(Y,X,$),Y.safeEncode=(X,$)=>IQ(Y,X,$),Y.safeDecode=(X,$)=>bQ(Y,X,$),Y.safeEncodeAsync=async(X,$)=>kQ(Y,X,$),Y.safeDecodeAsync=async(X,$)=>xQ(Y,X,$),Y.refine=(X,$)=>Y.check(eV(X,$)),Y.superRefine=(X)=>Y.check(YN(X)),Y.overwrite=(X)=>Y.check(O1(X)),Y.optional=()=>yQ(Y),Y.nullable=()=>gQ(Y),Y.nullish=()=>yQ(gQ(Y)),Y.nonoptional=(X)=>iV(Y,X),Y.array=()=>$7(Y),Y.or=(X)=>Q7([Y,X]),Y.and=(X)=>hV(Y,X),Y.transform=(X)=>fQ(Y,mV(X)),Y.default=(X)=>pV(Y,X),Y.prefault=(X)=>dV(Y,X),Y.catch=(X)=>oV(Y,X),Y.pipe=(X)=>fQ(Y,X),Y.readonly=()=>aV(Y),Y.describe=(X)=>{let $=Y.clone();return _1.add($,{description:X}),$},Object.defineProperty(Y,"description",{get(){return _1.get(Y)?.description},configurable:!0}),Y.meta=(...X)=>{if(X.length===0)return _1.get(Y);let $=Y.clone();return _1.add($,X[0]),$},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),mQ=O("_ZodString",(Y,J)=>{F4.init(Y,J),q0.init(Y,J);let X=Y._zod.bag;Y.format=X.format??null,Y.minLength=X.minimum??null,Y.maxLength=X.maximum??null,Y.regex=(...$)=>Y.check(e9(...$)),Y.includes=(...$)=>Y.check(XY(...$)),Y.startsWith=(...$)=>Y.check(D4(...$)),Y.endsWith=(...$)=>Y.check($Y(...$)),Y.min=(...$)=>Y.check(J1(...$)),Y.max=(...$)=>Y.check(E8(...$)),Y.length=(...$)=>Y.check(A8(...$)),Y.nonempty=(...$)=>Y.check(J1(1,...$)),Y.lowercase=($)=>Y.check(YY($)),Y.uppercase=($)=>Y.check(JY($)),Y.trim=()=>Y.check(GY()),Y.normalize=(...$)=>Y.check(QY(...$)),Y.toLowerCase=()=>Y.check(zY()),Y.toUpperCase=()=>Y.check(WY())}),WV=O("ZodString",(Y,J)=>{F4.init(Y,J),mQ.init(Y,J),Y.email=(X)=>Y.check(IX(KV,X)),Y.url=(X)=>Y.check(vX(UV,X)),Y.jwt=(X)=>Y.check(aX(AV,X)),Y.emoji=(X)=>Y.check(yX(HV,X)),Y.guid=(X)=>Y.check(d9(hQ,X)),Y.uuid=(X)=>Y.check(bX(BY,X)),Y.uuidv4=(X)=>Y.check(kX(BY,X)),Y.uuidv6=(X)=>Y.check(xX(BY,X)),Y.uuidv7=(X)=>Y.check(hX(BY,X)),Y.nanoid=(X)=>Y.check(gX(BV,X)),Y.guid=(X)=>Y.check(d9(hQ,X)),Y.cuid=(X)=>Y.check(fX(VV,X)),Y.cuid2=(X)=>Y.check(mX(NV,X)),Y.ulid=(X)=>Y.check(cX(LV,X)),Y.base64=(X)=>Y.check(oX(PV,X)),Y.base64url=(X)=>Y.check(rX(qV,X)),Y.xid=(X)=>Y.check(uX(ZV,X)),Y.ksuid=(X)=>Y.check(pX(jV,X)),Y.ipv4=(X)=>Y.check(lX(FV,X)),Y.ipv6=(X)=>Y.check(dX(_V,X)),Y.cidrv4=(X)=>Y.check(iX(DV,X)),Y.cidrv6=(X)=>Y.check(nX(OV,X)),Y.e164=(X)=>Y.check(sX(EV,X)),Y.datetime=(X)=>Y.check(DQ(X)),Y.date=(X)=>Y.check(OQ(X)),Y.time=(X)=>Y.check(PQ(X)),Y.duration=(X)=>Y.check(qQ(X))});function cQ(Y){return l9(WV,Y)}var P0=O("ZodStringFormat",(Y,J)=>{O0.init(Y,J),mQ.init(Y,J)}),KV=O("ZodEmail",(Y,J)=>{$X.init(Y,J),P0.init(Y,J)});var hQ=O("ZodGUID",(Y,J)=>{JX.init(Y,J),P0.init(Y,J)});var BY=O("ZodUUID",(Y,J)=>{XX.init(Y,J),P0.init(Y,J)});var UV=O("ZodURL",(Y,J)=>{QX.init(Y,J),P0.init(Y,J)});var HV=O("ZodEmoji",(Y,J)=>{GX.init(Y,J),P0.init(Y,J)});var BV=O("ZodNanoID",(Y,J)=>{zX.init(Y,J),P0.init(Y,J)});var VV=O("ZodCUID",(Y,J)=>{WX.init(Y,J),P0.init(Y,J)});var NV=O("ZodCUID2",(Y,J)=>{KX.init(Y,J),P0.init(Y,J)});var LV=O("ZodULID",(Y,J)=>{UX.init(Y,J),P0.init(Y,J)});var ZV=O("ZodXID",(Y,J)=>{HX.init(Y,J),P0.init(Y,J)});var jV=O("ZodKSUID",(Y,J)=>{BX.init(Y,J),P0.init(Y,J)});var FV=O("ZodIPv4",(Y,J)=>{VX.init(Y,J),P0.init(Y,J)});var _V=O("ZodIPv6",(Y,J)=>{NX.init(Y,J),P0.init(Y,J)});var DV=O("ZodCIDRv4",(Y,J)=>{LX.init(Y,J),P0.init(Y,J)});var OV=O("ZodCIDRv6",(Y,J)=>{ZX.init(Y,J),P0.init(Y,J)});var PV=O("ZodBase64",(Y,J)=>{jX.init(Y,J),P0.init(Y,J)});var qV=O("ZodBase64URL",(Y,J)=>{FX.init(Y,J),P0.init(Y,J)});var EV=O("ZodE164",(Y,J)=>{_X.init(Y,J),P0.init(Y,J)});var AV=O("ZodJWT",(Y,J)=>{DX.init(Y,J),P0.init(Y,J)});var uQ=O("ZodNumber",(Y,J)=>{D8.init(Y,J),q0.init(Y,J),Y.gt=($,Q)=>Y.check(_4($,Q)),Y.gte=($,Q)=>Y.check(D1($,Q)),Y.min=($,Q)=>Y.check(D1($,Q)),Y.lt=($,Q)=>Y.check(P8($,Q)),Y.lte=($,Q)=>Y.check(Y1($,Q)),Y.max=($,Q)=>Y.check(Y1($,Q)),Y.int=($)=>Y.check(vQ($)),Y.safe=($)=>Y.check(vQ($)),Y.positive=($)=>Y.check(_4(0,$)),Y.nonnegative=($)=>Y.check(D1(0,$)),Y.negative=($)=>Y.check(P8(0,$)),Y.nonpositive=($)=>Y.check(Y1(0,$)),Y.multipleOf=($,Q)=>Y.check(q8($,Q)),Y.step=($,Q)=>Y.check(q8($,Q)),Y.finite=()=>Y;let X=Y._zod.bag;Y.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Y.isFinite=!0,Y.format=X.format??null});function pQ(Y){return i9(uQ,Y)}var MV=O("ZodNumberFormat",(Y,J)=>{S9.init(Y,J),uQ.init(Y,J)});function vQ(Y){return n9(MV,Y)}var TV=O("ZodBoolean",(Y,J)=>{I9.init(Y,J),q0.init(Y,J)});function lQ(Y){return o9(TV,Y)}var RV=O("ZodNull",(Y,J)=>{OX.init(Y,J),q0.init(Y,J)});function dQ(Y){return tX(RV,Y)}var CV=O("ZodUnknown",(Y,J)=>{b9.init(Y,J),q0.init(Y,J)});function VY(){return r9(CV)}var wV=O("ZodNever",(Y,J)=>{k9.init(Y,J),q0.init(Y,J)});function SV(Y){return s9(wV,Y)}var IV=O("ZodArray",(Y,J)=>{x9.init(Y,J),q0.init(Y,J),Y.element=J.element,Y.min=(X,$)=>Y.check(J1(X,$)),Y.nonempty=(X)=>Y.check(J1(1,X)),Y.max=(X,$)=>Y.check(E8(X,$)),Y.length=(X,$)=>Y.check(A8(X,$)),Y.unwrap=()=>Y.element});function $7(Y,J){return LQ(IV,Y,J)}var bV=O("ZodObject",(Y,J)=>{KQ.init(Y,J),q0.init(Y,J),d.defineLazy(Y,"shape",()=>J.shape),Y.keyof=()=>yV(Object.keys(Y._zod.def.shape)),Y.catchall=(X)=>Y.clone({...Y._zod.def,catchall:X}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:VY()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:SV()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(X)=>{return d.extend(Y,X)},Y.safeExtend=(X)=>{return d.safeExtend(Y,X)},Y.merge=(X)=>d.merge(Y,X),Y.pick=(X)=>d.pick(Y,X),Y.omit=(X)=>d.omit(Y,X),Y.partial=(...X)=>d.partial(aQ,Y,X[0]),Y.required=(...X)=>d.required(tQ,Y,X[0])});function iQ(Y,J){let X={type:"object",get shape(){return d.assignProp(this,"shape",Y?d.objectClone(Y):{}),this.shape},...d.normalizeParams(J)};return new bV(X)}var nQ=O("ZodUnion",(Y,J)=>{O8.init(Y,J),q0.init(Y,J),Y.options=J.options});function Q7(Y,J){return new nQ({type:"union",options:Y,...d.normalizeParams(J)})}var kV=O("ZodDiscriminatedUnion",(Y,J)=>{nQ.init(Y,J),h9.init(Y,J)});function oQ(Y,J,X){return new kV({type:"union",options:J,discriminator:Y,...d.normalizeParams(X)})}var xV=O("ZodIntersection",(Y,J)=>{qX.init(Y,J),q0.init(Y,J)});function hV(Y,J){return new xV({type:"intersection",left:Y,right:J})}var vV=O("ZodRecord",(Y,J)=>{v9.init(Y,J),q0.init(Y,J),Y.keyType=J.keyType,Y.valueType=J.valueType});function rQ(Y,J,X){return new vV({type:"record",keyType:Y,valueType:J,...d.normalizeParams(X)})}var X7=O("ZodEnum",(Y,J)=>{y9.init(Y,J),q0.init(Y,J),Y.enum=J.entries,Y.options=Object.values(J.entries);let X=new Set(Object.keys(J.entries));Y.extract=($,Q)=>{let G={};for(let z of $)if(X.has(z))G[z]=J.entries[z];else throw Error(`Key ${z} not found in enum`);return new X7({...J,checks:[],...d.normalizeParams(Q),entries:G})},Y.exclude=($,Q)=>{let G={...J.entries};for(let z of $)if(X.has(z))delete G[z];else throw Error(`Key ${z} not found in enum`);return new X7({...J,checks:[],...d.normalizeParams(Q),entries:G})}});function yV(Y,J){let X=Array.isArray(Y)?Object.fromEntries(Y.map(($)=>[$,$])):Y;return new X7({type:"enum",entries:X,...d.normalizeParams(J)})}var gV=O("ZodLiteral",(Y,J)=>{g9.init(Y,J),q0.init(Y,J),Y.values=new Set(J.values),Object.defineProperty(Y,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function sQ(Y,J){return new gV({type:"literal",values:Array.isArray(Y)?Y:[Y],...d.normalizeParams(J)})}var fV=O("ZodTransform",(Y,J)=>{f9.init(Y,J),q0.init(Y,J),Y._zod.parse=(X,$)=>{if($.direction==="backward")throw new z8(Y.constructor.name);X.addIssue=(G)=>{if(typeof G==="string")X.issues.push(d.issue(G,X.value,J));else{let z=G;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=X.value),z.inst??(z.inst=Y),X.issues.push(d.issue(z))}};let Q=J.transform(X.value,X);if(Q instanceof Promise)return Q.then((G)=>{return X.value=G,X});return X.value=Q,X}});function mV(Y){return new fV({type:"transform",transform:Y})}var aQ=O("ZodOptional",(Y,J)=>{m9.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function yQ(Y){return new aQ({type:"optional",innerType:Y})}var cV=O("ZodNullable",(Y,J)=>{EX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function gQ(Y){return new cV({type:"nullable",innerType:Y})}var uV=O("ZodDefault",(Y,J)=>{AX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function pV(Y,J){return new uV({type:"default",innerType:Y,get defaultValue(){return typeof J==="function"?J():d.shallowClone(J)}})}var lV=O("ZodPrefault",(Y,J)=>{MX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function dV(Y,J){return new lV({type:"prefault",innerType:Y,get defaultValue(){return typeof J==="function"?J():d.shallowClone(J)}})}var tQ=O("ZodNonOptional",(Y,J)=>{TX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function iV(Y,J){return new tQ({type:"nonoptional",innerType:Y,...d.normalizeParams(J)})}var nV=O("ZodCatch",(Y,J)=>{RX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function oV(Y,J){return new nV({type:"catch",innerType:Y,catchValue:typeof J==="function"?J:()=>J})}var rV=O("ZodPipe",(Y,J)=>{c9.init(Y,J),q0.init(Y,J),Y.in=J.in,Y.out=J.out});function fQ(Y,J){return new rV({type:"pipe",in:Y,out:J})}var sV=O("ZodReadonly",(Y,J)=>{CX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.innerType});function aV(Y){return new sV({type:"readonly",innerType:Y})}var tV=O("ZodLazy",(Y,J)=>{wX.init(Y,J),q0.init(Y,J),Y.unwrap=()=>Y._zod.def.getter()});function eQ(Y){return new tV({type:"lazy",getter:Y})}var G7=O("ZodCustom",(Y,J)=>{u9.init(Y,J),q0.init(Y,J)});function YG(Y,J){return KY(G7,Y??(()=>!0),J)}function eV(Y,J={}){return UY(G7,Y,J)}function YN(Y){return eX(Y)}function JG(Y,J={error:`Input not instance of ${Y.name}`}){let X=new G7({type:"custom",check:"custom",fn:($)=>$ instanceof Y,abort:!0,...d.normalizeParams(J)});return X._zod.bag.Class=Y,X}var QN=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get,GN=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get;function H7(Y){return ArrayBuffer.isView(Y)&&QN.call(Y)==="Uint8Array"}function B7(Y){if(typeof Y!=="object"||Y===null||!("byteLength"in Y))return!1;try{return GN.call(Y),!0}catch{return!1}}function V7(Y=globalThis){if(Y.navigator?.userAgent)return Y.navigator.userAgent.toLowerCase();if(Y.process?.versions?.node)return`node.js/${Y.process.version}`;if(Y.EdgeRuntime)return"vercel-edge";return""}function HG(Y){if(Y==null)return{};let J={};if(Y instanceof Headers)Y.forEach((X,$)=>{J[$.toLowerCase()]=X});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[X,$]of Y)if($!=null)J[X.toLowerCase()]=$}return J}function N7(Y,...J){let X=new Headers(HG(Y)),$=X.get("user-agent")||"";return X.set("user-agent",[$,...J].filter(Boolean).join(" ")),Object.fromEntries(X.entries())}var zN=[{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]}],kP=[...zN,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function NY(Y){try{await Y.body?.cancel()}catch{}}var BG="AI_DownloadError",VG=`vercel.ai.error.${BG}`,WN=Symbol.for(VG),h0=class extends s6{constructor({url:Y,statusCode:J,statusText:X,cause:$,message:Q=$==null?`Failed to download ${Y}: ${J} ${X}`:`Failed to download ${Y}: ${$}`}){super({name:BG,message:Q,cause:$});this[WN]=!0,this.url=Y,this.statusCode=J,this.statusText=X}static isInstance(Y){return s6.hasMarker(Y,VG)}};function KN(Y=globalThis){return Y.window!=null}function K7(Y,J){try{return new URL(Y).origin===new URL(J).origin}catch{return!1}}var UN=["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 NG(Y){let J=new Headers(Y);for(let X of UN)J.delete(X);return J}function HN(Y){let J;try{J=new URL(Y)}catch{throw new h0({url:Y,message:`Invalid URL: ${Y}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new h0({url:Y,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let X=J.hostname.toLowerCase().replace(/\.+$/,"");if(!X)throw new h0({url:Y,message:"URL must have a hostname"});if(X==="localhost"||X.endsWith(".local")||X.endsWith(".localhost")||X.endsWith(".internal"))throw new h0({url:Y,message:`URL with hostname ${X} is not allowed`});if(X.startsWith("[")&&X.endsWith("]")){if(VN(X.slice(1,-1)))throw new h0({url:Y,message:`URL with IPv6 address ${X} is not allowed`});return}if(LG(X)){if(ZG(X))throw new h0({url:Y,message:`URL with IP address ${X} is not allowed`})}}function LG(Y){let J=Y.split(".");if(J.length!==4)return!1;return J.every((X)=>{let $=Number(X);return Number.isInteger($)&&$>=0&&$<=255&&String($)===X})}function ZG(Y){let[J,X,$]=Y.split(".").map(Number);if(J===0)return!0;if(J===10)return!0;if(J===100&&X>=64&&X<=127)return!0;if(J===127)return!0;if(J===169&&X===254)return!0;if(J===172&&X>=16&&X<=31)return!0;if(J===192&&X===0&&$===0)return!0;if(J===192&&X===0&&$===2)return!0;if(J===192&&X===168)return!0;if(J===198&&(X===18||X===19))return!0;if(J===198&&X===51&&$===100)return!0;if(J===203&&X===0&&$===113)return!0;if(J>=224)return!0;return!1}function BN(Y){let J=Y.toLowerCase(),X=J.indexOf("%");if(X!==-1)J=J.slice(0,X);let $=J.split("::");if($.length>2)return null;let Q=(z)=>{if(z==="")return[];let K=[],U=z.split(":");for(let H=0;H<U.length;H++){let V=U[H];if(V.includes(".")){if(H!==U.length-1||!LG(V))return null;let[F,Z,N,j]=V.split(".").map(Number);K.push(F<<8|Z,N<<8|j);continue}if(!/^[0-9a-f]{1,4}$/.test(V))return null;K.push(parseInt(V,16))}return K},G=Q($[0]);if(G===null)return null;if($.length===2){let z=Q($[1]);if(z===null)return null;let K=8-G.length-z.length;if(K<0)return null;return[...G,...Array(K).fill(0),...z]}return G.length===8?G:null}function VN(Y){let J=BN(Y);if(J===null)return!0;let X=($)=>J.slice(0,$).every((Q)=>Q===0);if(X(7)&&(J[7]===0||J[7]===1))return!0;if((J[0]&65024)===64512)return!0;if((J[0]&65472)===65152)return!0;if((J[0]&65472)===65216)return!0;if((J[0]&65280)===65280)return!0;if(J[0]===8193&&J[1]===3512)return!0;if(J[0]===16383&&(J[1]&61440)===0)return!0;if(X(6)||X(5)&&J[5]===65535||X(4)&&J[4]===65535&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===0&&J[3]===0&&J[4]===0&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===1)return ZG(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}var NN=10,LN=new Set([301,302,303,307,308]);async function ZN({url:Y,headers:J,abortSignal:X,maxRedirects:$=NN,fetch:Q,trustedOrigin:G}){let z=J===void 0?void 0:NG(J),K=(H)=>{let V={signal:X,redirect:H};if(z!==void 0)V.headers=new Headers(z);return V},U=Y;for(let H=0;H<=$;H++){if(!(G!==void 0&&K7(U,G)))HN(U);let V=Q??globalThis.fetch,F=await V(U,K("manual"));if(F.type==="opaqueredirect"){if(!KN())throw new h0({url:Y,message:`Redirect from ${U} could not be validated and was blocked`});return await V(U,K("follow"))}let Z=F.headers?.get("location");if(LN.has(F.status)&&Z){NY(F);let N=new URL(Z,U).toString();if(new URL(U).protocol==="https:"&&new URL(N).protocol==="http:")throw new h0({url:Y,message:"Redirect from HTTPS to HTTP was blocked"});if(z!==void 0&&!K7(N,U)){let j=z.get("user-agent");z=new Headers(j==null?void 0:{"user-agent":j})}U=N;continue}return F}throw new h0({url:Y,message:`Too many redirects (max ${$})`})}var jN=new Set(["accept","accept-language","baggage","cache-control","idempotency-key","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","pragma","range","traceparent","tracestate","user-agent","x-correlation-id","x-request-id"]);async function jG({headers:Y,credentialedOrigin:J,untrustedFirstHopHeaders:X,...$}){let Q;if(Y!==void 0){Q=NG(Y);let G=J??$.trustedOrigin;if(G===void 0||!K7($.url,G)){let z=new Set([...jN,...(X??[]).map((K)=>K.toLowerCase())]);Q=new Headers([...Q].filter(([K])=>z.has(K)))}}return ZN({...$,headers:Q})}var L7=2147483648;async function FG({response:Y,url:J,maxBytes:X=L7,onChunk:$}){let Q=Y.headers.get("content-length");if(Q!=null){let F=parseInt(Q,10);if(!isNaN(F)&&F>X)throw await NY(Y),new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes (Content-Length: ${F}).`})}let G=Y.body;if(G==null)return new Uint8Array(0);let z=G.getReader(),K=[],U=0;try{while(!0){let{done:F,value:Z}=await z.read();if(F)break;if(U+=Z.length,U>X)throw new h0({url:J,message:`Download of ${J} exceeded maximum size of ${X} bytes.`});if($!=null){$(Z);continue}K.push(Z.byteLength<Z.buffer.byteLength?new Uint8Array(Z):Z)}}finally{try{await z.cancel()}catch{}finally{z.releaseLock()}}let H=new Uint8Array($!=null?0:U),V=0;for(let F of K)H.set(F,V),V+=F.length;return H}var S0=({prefix:Y,size:J=16,alphabet:X="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:$="-"}={})=>{let Q=()=>{let G=X.length,z=Array(J);for(let K=0;K<J;K++)z[K]=X[Math.random()*G|0];return z.join("")};if(Y==null)return Q;if(X.includes($))throw new f5({argument:"separator",message:`The separator "${$}" must not be part of the alphabet "${X}".`});return()=>`${Y}${$}${Q()}`},_G=S0();function Z7(Y){return globalThis.Buffer?.isBuffer(Y)??!1}function DG(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){let{additionalProperties:X}=Y;Y.additionalProperties=X!=null&&typeof X!=="boolean"?P1(X):!1;let{properties:$}=Y;if($!=null)for(let Q of Object.keys($))$[Q]=P1($[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(P1):P1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(P1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(P1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(P1);let{definitions:J}=Y;if(J!=null)for(let X of Object.keys(J))J[X]=P1(J[X]);return Y}function P1(Y){if(typeof Y==="boolean")return Y;return DG(Y)}var FN=Symbol("Let zodToJsonSchema decide on which parser to use"),XG={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"},_N=(Y)=>typeof Y==="string"?{...XG,name:Y}:{...XG,...Y};function K6(){return{}}function DN(Y,J){let X={type:"array"};if(Y.type?._def&&Y.type?._def?.typeName!=="ZodAny")X.items=L0(Y.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(Y.minLength)X.minItems=Y.minLength.value;if(Y.maxLength)X.maxItems=Y.maxLength.value;if(Y.exactLength)X.minItems=Y.exactLength.value,X.maxItems=Y.exactLength.value;return X}function ON(Y){let J={type:"integer",format:"int64"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function PN(){return{type:"boolean"}}function OG(Y,J){return L0(Y.type._def,J)}var qN=(Y,J)=>{return L0(Y.innerType._def,J)};function PG(Y,J,X){let $=X??J.dateStrategy;if(Array.isArray($))return{anyOf:$.map((Q)=>PG(Y,J,Q))};switch($){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return EN(Y)}}var EN=(Y)=>{let J={type:"integer",format:"unix-time"};for(let X of Y.checks)switch(X.kind){case"min":J.minimum=X.value;break;case"max":J.maximum=X.value}return J};function AN(Y,J){return{...L0(Y.innerType._def,J),default:Y.defaultValue()}}function MN(Y,J){return J.effectStrategy==="input"?L0(Y.schema._def,J):K6()}function TN(Y){return{type:"string",enum:Array.from(Y.values)}}var RN=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function CN(Y,J){let X=[L0(Y.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),L0(Y.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((Q)=>!!Q),$=[];return X.forEach((Q)=>{if(RN(Q))$.push(...Q.allOf);else{let G=Q;if("additionalProperties"in Q&&Q.additionalProperties===!1){let{additionalProperties:z,...K}=Q;G=K}$.push(G)}}),$.length?{allOf:$}:void 0}function wN(Y){let J=typeof Y.value;if(J!=="bigint"&&J!=="number"&&J!=="boolean"&&J!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:J==="bigint"?"integer":J,const:Y.value}}var z7=void 0,S6={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(z7===void 0)z7=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return z7},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 qG(Y,J){let X={type:"string"};if(Y.checks)for(let $ of Y.checks)switch($.kind){case"min":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,$.value):$.value;break;case"max":X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,$.value):$.value;break;case"email":switch(J.emailStrategy){case"format:email":I6(X,"email",$.message,J);break;case"format:idn-email":I6(X,"idn-email",$.message,J);break;case"pattern:zod":o0(X,S6.email,$.message,J)}break;case"url":I6(X,"uri",$.message,J);break;case"uuid":I6(X,"uuid",$.message,J);break;case"regex":o0(X,$.regex,$.message,J);break;case"cuid":o0(X,S6.cuid,$.message,J);break;case"cuid2":o0(X,S6.cuid2,$.message,J);break;case"startsWith":o0(X,RegExp(`^${W7($.value,J)}`),$.message,J);break;case"endsWith":o0(X,RegExp(`${W7($.value,J)}$`),$.message,J);break;case"datetime":I6(X,"date-time",$.message,J);break;case"date":I6(X,"date",$.message,J);break;case"time":I6(X,"time",$.message,J);break;case"duration":I6(X,"duration",$.message,J);break;case"length":X.minLength=typeof X.minLength==="number"?Math.max(X.minLength,$.value):$.value,X.maxLength=typeof X.maxLength==="number"?Math.min(X.maxLength,$.value):$.value;break;case"includes":o0(X,RegExp(W7($.value,J)),$.message,J);break;case"ip":if($.version!=="v6")I6(X,"ipv4",$.message,J);if($.version!=="v4")I6(X,"ipv6",$.message,J);break;case"base64url":o0(X,S6.base64url,$.message,J);break;case"jwt":o0(X,S6.jwt,$.message,J);break;case"cidr":if($.version!=="v6")o0(X,S6.ipv4Cidr,$.message,J);if($.version!=="v4")o0(X,S6.ipv6Cidr,$.message,J);break;case"emoji":o0(X,S6.emoji(),$.message,J);break;case"ulid":o0(X,S6.ulid,$.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":I6(X,"binary",$.message,J);break;case"contentEncoding:base64":X.contentEncoding="base64";break;case"pattern:zod":o0(X,S6.base64,$.message,J)}break;case"nanoid":o0(X,S6.nanoid,$.message,J)}return X}function W7(Y,J){return J.patternStrategy==="escape"?IN(Y):Y}var SN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function IN(Y){let J="";for(let X=0;X<Y.length;X++){if(!SN.has(Y[X]))J+="\\";J+=Y[X]}return J}function I6(Y,J,X,$){if(Y.format||Y.anyOf?.some((Q)=>Q.format)){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:J,...X&&$.errorMessages&&{errorMessage:{format:X}}})}else Y.format=J}function o0(Y,J,X,$){if(Y.pattern||Y.allOf?.some((Q)=>Q.pattern)){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:$G(J,$),...X&&$.errorMessages&&{errorMessage:{pattern:X}}})}else Y.pattern=$G(J,$)}function $G(Y,J){if(!J.applyRegexFlags||!Y.flags)return Y.source;let X={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=X.i?Y.source.toLowerCase():Y.source,Q="",G=!1,z=!1,K=!1;for(let U=0;U<$.length;U++){if(G){Q+=$[U],G=!1;continue}if(X.i){if(z){if($[U].match(/[a-z]/)){if(K)Q+=$[U],Q+=`${$[U-2]}-${$[U]}`.toUpperCase(),K=!1;else if($[U+1]==="-"&&$[U+2]?.match(/[a-z]/))Q+=$[U],K=!0;else Q+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){Q+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(X.m){if($[U]==="^"){Q+=`(^|(?<=[\r
27
+ ]))`;continue}else if($[U]==="$"){Q+=`($|(?=[\r
28
+ ]))`;continue}}if(X.s&&$[U]==="."){Q+=z?`${$[U]}\r
29
+ `:`[${$[U]}\r
30
+ ]`;continue}if(Q+=$[U],$[U]==="\\")G=!0;else if(z&&$[U]==="]")z=!1;else if(!z&&$[U]==="[")z=!0}try{new RegExp(Q)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return Q}function EG(Y,J){let X={type:"object",additionalProperties:L0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(Y.keyType?._def.typeName==="ZodString"&&Y.keyType._def.checks?.length){let{type:$,...Q}=qG(Y.keyType._def,J);return{...X,propertyNames:Q}}else if(Y.keyType?._def.typeName==="ZodEnum")return{...X,propertyNames:{enum:Y.keyType._def.values}};else if(Y.keyType?._def.typeName==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&Y.keyType._def.type._def.checks?.length){let{type:$,...Q}=OG(Y.keyType._def,J);return{...X,propertyNames:Q}}return X}function bN(Y,J){if(J.mapStrategy==="record")return EG(Y,J);return{type:"array",maxItems:125,items:{type:"array",items:[L0(Y.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||K6(),L0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||K6()],minItems:2,maxItems:2}}}function kN(Y){let J=Y.values,X=Object.keys(Y.values).filter((Q)=>{return typeof J[J[Q]]!=="number"}).map((Q)=>J[Q]),$=Array.from(new Set(X.map((Q)=>typeof Q)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:X}}function xN(){return{not:K6()}}function hN(){return{type:"null"}}var U7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vN(Y,J){let X=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(X.every(($)=>($._def.typeName in U7)&&(!$._def.checks||!$._def.checks.length))){let $=X.reduce((Q,G)=>{let z=U7[G._def.typeName];return z&&!Q.includes(z)?[...Q,z]:Q},[]);return{type:$.length>1?$:$[0]}}else if(X.every(($)=>$._def.typeName==="ZodLiteral"&&!$.description)){let $=X.reduce((Q,G)=>{let z=typeof G._def.value;switch(z){case"string":case"number":case"boolean":return[...Q,z];case"bigint":return[...Q,"integer"];case"object":if(G._def.value===null)return[...Q,"null"];default:return Q}},[]);if($.length===X.length){let Q=$.filter((G,z,K)=>K.indexOf(G)===z);return{type:Q.length>1?Q:Q[0],enum:X.reduce((G,z)=>{return G.includes(z._def.value)?G:[...G,z._def.value]},[])}}}else if(X.every(($)=>$._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce(($,Q)=>[...$,...Q._def.values.filter((G)=>!$.includes(G))],[])};return yN(Y,J)}var yN=(Y,J)=>{let X=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map(($,Q)=>L0($._def,{...J,currentPath:[...J.currentPath,"anyOf",`${Q}`]})).filter(($)=>!!$&&(!J.strictUnions||typeof $==="object"&&Object.keys($).length>0));return X.length?{anyOf:X}:void 0};function gN(Y,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[U7[Y.innerType._def.typeName],"null"]};let X=L0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function fN(Y){let J={type:"number"};if(!Y.checks)return J;for(let X of Y.checks)switch(X.kind){case"int":J.type="integer";break;case"min":if(X.inclusive)J.minimum=X.value;else J.exclusiveMinimum=X.value;break;case"max":if(X.inclusive)J.maximum=X.value;else J.exclusiveMaximum=X.value;break;case"multipleOf":J.multipleOf=X.value}return J}function mN(Y,J){let X={type:"object",properties:{}},$=[],Q=Y.shape();for(let z in Q){let K=Q[z];if(K===void 0||K._def===void 0)continue;let U=uN(K),H=L0(K._def,{...J,currentPath:[...J.currentPath,"properties",z],propertyPath:[...J.currentPath,"properties",z]});if(H===void 0)continue;if(X.properties[z]=H,!U)$.push(z)}if($.length)X.required=$;let G=cN(Y,J);if(G!==void 0)X.additionalProperties=G;return X}function cN(Y,J){if(Y.catchall._def.typeName!=="ZodNever")return L0(Y.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function uN(Y){try{return Y.isOptional()}catch{return!0}}var pN=(Y,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return L0(Y.innerType._def,J);let X=L0(Y.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return X?{anyOf:[{not:K6()},X]}:K6()},lN=(Y,J)=>{if(J.pipeStrategy==="input")return L0(Y.in._def,J);else if(J.pipeStrategy==="output")return L0(Y.out._def,J);let X=L0(Y.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]});return{allOf:[X,L0(Y.out._def,{...J,currentPath:[...J.currentPath,"allOf",X?"1":"0"]})].filter(($)=>$!==void 0)}};function dN(Y,J){return L0(Y.type._def,J)}function iN(Y,J){let X={type:"array",uniqueItems:!0,items:L0(Y.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(Y.minSize)X.minItems=Y.minSize.value;if(Y.maxSize)X.maxItems=Y.maxSize.value;return X}function nN(Y,J){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((X,$)=>L0(X._def,{...J,currentPath:[...J.currentPath,"items",`${$}`]})).reduce((X,$)=>$===void 0?X:[...X,$],[]),additionalItems:L0(Y.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((X,$)=>L0(X._def,{...J,currentPath:[...J.currentPath,"items",`${$}`]})).reduce((X,$)=>$===void 0?X:[...X,$],[])}}function oN(){return{not:K6()}}function rN(){return K6()}var sN=(Y,J)=>{return L0(Y.innerType._def,J)},aN=(Y,J,X)=>{switch(J){case"ZodString":return qG(Y,X);case"ZodNumber":return fN(Y);case"ZodObject":return mN(Y,X);case"ZodBigInt":return ON(Y);case"ZodBoolean":return PN();case"ZodDate":return PG(Y,X);case"ZodUndefined":return oN();case"ZodNull":return hN();case"ZodArray":return DN(Y,X);case"ZodUnion":case"ZodDiscriminatedUnion":return vN(Y,X);case"ZodIntersection":return CN(Y,X);case"ZodTuple":return nN(Y,X);case"ZodRecord":return EG(Y,X);case"ZodLiteral":return wN(Y);case"ZodEnum":return TN(Y);case"ZodNativeEnum":return kN(Y);case"ZodNullable":return gN(Y,X);case"ZodOptional":return pN(Y,X);case"ZodMap":return bN(Y,X);case"ZodSet":return iN(Y,X);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return dN(Y,X);case"ZodNaN":case"ZodNever":return xN();case"ZodEffects":return MN(Y,X);case"ZodAny":return K6();case"ZodUnknown":return rN();case"ZodDefault":return AN(Y,X);case"ZodBranded":return OG(Y,X);case"ZodReadonly":return sN(Y,X);case"ZodCatch":return qN(Y,X);case"ZodPipeline":return lN(Y,X);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return(($)=>{return})(J)}},tN=(Y,J)=>{let X=0;for(;X<Y.length&&X<J.length;X++)if(Y[X]!==J[X])break;return[(Y.length-X).toString(),...J.slice(X)].join("/")};function L0(Y,J,X=!1){let $=J.seen.get(Y);if(J.override){let K=J.override?.(Y,J,$,X);if(K!==FN)return K}if($&&!X){let K=eN($,J);if(K!==void 0)return K}let Q={def:Y,path:J.currentPath,jsonSchema:void 0};J.seen.set(Y,Q);let G=aN(Y,Y.typeName,J),z=typeof G==="function"?L0(G(),J):G;if(z)YL(Y,J,z);if(J.postProcess){let K=J.postProcess(z,Y,J);return Q.jsonSchema=z,K}return Q.jsonSchema=z,z}var eN=(Y,J)=>{switch(J.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:tN(J.currentPath,Y.path)};case"none":case"seen":if(Y.path.length<J.currentPath.length&&Y.path.every((X,$)=>J.currentPath[$]===X))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),K6();return J.$refStrategy==="seen"?K6():void 0}},YL=(Y,J,X)=>{if(Y.description)X.description=Y.description;return X},JL=(Y)=>{let J=_N(Y),X=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([$,Q])=>[Q._def,{def:Q._def,path:[...J.basePath,J.definitionPath,$],jsonSchema:void 0}]))}},XL=(Y,J)=>{let X=JL(J),$=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((U,[H,V])=>({...U,[H]:L0(V._def,{...X,currentPath:[...X.basePath,X.definitionPath,H]},!0)??K6()}),{}):void 0,Q=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=L0(Y._def,Q===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,Q]},!1)??K6(),z=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(z!==void 0)G.title=z;let K=Q===void 0?$?{...G,[X.definitionPath]:$}:G:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,Q].join("/"),[X.definitionPath]:{...$,[Q]:G}};return K.$schema="http://json-schema.org/draft-07/schema#",K},$L=Symbol.for("vercel.ai.schema");function j7(Y){let J;return()=>{if(J==null)J=Y();return J}}function LY(Y,{validate:J}={}){return{[$L]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:J}}function QL(Y,J){let X=J?.useReferences??!1;return LY(()=>XL(Y,{$refStrategy:X?"root":"none"}),{validate:async($)=>{let Q=await Y.safeParseAsync($);return Q.success?{success:!0,value:Q.data}:{success:!1,error:Q.error}}})}function GL(Y,J){if(!Y6().localeError)Y6(SX());let X=J?.useReferences??!1;return LY(()=>DG(J7(Y,{target:"draft-7",io:"input",reused:X?"ref":"inline"})),{validate:async($)=>{let Q=await HY(Y,$);return Q.success?{success:!0,value:Q.data}:{success:!1,error:Q.error}}})}function zL(Y){return"_zod"in Y}function ZY(Y,J){if(zL(Y))return GL(Y,J);else return QL(Y,J)}var WL="AI_SerializationError",xP=`vercel.ai.error.${WL}`;var u0=O("ZodMiniType",(Y,J)=>{if(!Y._zod)throw Error("Uninitialized schema in ZodMiniType.");Z0.init(Y,J),Y.def=J,Y.type=J.type,Y.parse=(X,$)=>T9(Y,X,$,{callee:Y.parse}),Y.safeParse=(X,$)=>f1(Y,X,$),Y.parseAsync=async(X,$)=>R9(Y,X,$,{callee:Y.parseAsync}),Y.safeParseAsync=async(X,$)=>F8(Y,X,$),Y.check=(...X)=>{return Y.clone({...J,checks:[...J.checks??[],...X.map(($)=>typeof $==="function"?{_zod:{check:$,def:{check:"custom"},onattach:[]}}:$)]})},Y.clone=(X,$)=>J6(Y,X,$),Y.brand=()=>Y,Y.register=(X,$)=>{return X.add(Y,$),Y}}),UL=O("ZodMiniString",(Y,J)=>{F4.init(Y,J),u0.init(Y,J)});function AG(Y){return l9(UL,Y)}var MG=O("ZodMiniNumber",(Y,J)=>{D8.init(Y,J),u0.init(Y,J)});function TG(Y){return i9(MG,Y)}var HL=O("ZodMiniNumberFormat",(Y,J)=>{S9.init(Y,J),MG.init(Y,J)});function RG(Y){return n9(HL,Y)}var BL=O("ZodMiniBoolean",(Y,J)=>{I9.init(Y,J),u0.init(Y,J)});function CG(Y){return o9(BL,Y)}var VL=O("ZodMiniUnknown",(Y,J)=>{b9.init(Y,J),u0.init(Y,J)});function F7(){return r9(VL)}var NL=O("ZodMiniNever",(Y,J)=>{k9.init(Y,J),u0.init(Y,J)});function wG(Y){return s9(NL,Y)}var LL=O("ZodMiniArray",(Y,J)=>{x9.init(Y,J),u0.init(Y,J)});function SG(Y,J){return new LL({type:"array",element:Y,...d.normalizeParams(J)})}var IG=O("ZodMiniObject",(Y,J)=>{PX.init(Y,J),u0.init(Y,J),d.defineLazy(Y,"shape",()=>J.shape)});function bG(Y,J){let X={type:"object",get shape(){return d.assignProp(this,"shape",{...Y}),this.shape},...d.normalizeParams(J)};return new IG(X)}function kG(Y,J){return new IG({type:"object",get shape(){return d.assignProp(this,"shape",{...Y}),this.shape},catchall:F7(),...d.normalizeParams(J)})}function xG(Y,J){return d.extend(Y,J)}var ZL=O("ZodMiniUnion",(Y,J)=>{O8.init(Y,J),u0.init(Y,J)});function hG(Y,J){return new ZL({type:"union",options:Y,...d.normalizeParams(J)})}var jL=O("ZodMiniDiscriminatedUnion",(Y,J)=>{h9.init(Y,J),u0.init(Y,J)});function vG(Y,J,X){return new jL({type:"union",options:J,discriminator:Y,...d.normalizeParams(X)})}var FL=O("ZodMiniRecord",(Y,J)=>{v9.init(Y,J),u0.init(Y,J)});function yG(Y,J,X){return new FL({type:"record",keyType:Y,valueType:J,...d.normalizeParams(X)})}var _L=O("ZodMiniEnum",(Y,J)=>{y9.init(Y,J),u0.init(Y,J),Y.options=Object.values(J.entries)});function gG(Y,J){let X=Array.isArray(Y)?Object.fromEntries(Y.map(($)=>[$,$])):Y;return new _L({type:"enum",entries:X,...d.normalizeParams(J)})}var DL=O("ZodMiniLiteral",(Y,J)=>{g9.init(Y,J),u0.init(Y,J)});function fG(Y,J){return new DL({type:"literal",values:Array.isArray(Y)?Y:[Y],...d.normalizeParams(J)})}var OL=O("ZodMiniTransform",(Y,J)=>{f9.init(Y,J),u0.init(Y,J)});function mG(Y){return new OL({type:"transform",transform:Y})}var PL=O("ZodMiniOptional",(Y,J)=>{m9.init(Y,J),u0.init(Y,J)});function cG(Y){return new PL({type:"optional",innerType:Y})}var qL=O("ZodMiniPipe",(Y,J)=>{c9.init(Y,J),u0.init(Y,J)});function uG(Y,J){return new qL({type:"pipe",in:Y,out:J})}var pG=O("ZodMiniCustom",(Y,J)=>{u9.init(Y,J),u0.init(Y,J)});function lG(Y,J){return KY(pG,Y??(()=>!0),J)}function dG(Y,J={}){return UY(pG,Y,J)}var hL="AI_InvalidArgumentError",Bq=`vercel.ai.error.${hL}`;var vL="AI_InvalidToolApprovalError",Vq=`vercel.ai.error.${vL}`;var yL="AI_InvalidToolApprovalSignatureError",Nq=`vercel.ai.error.${yL}`;var gL="AI_InvalidToolInputError",Lq=`vercel.ai.error.${gL}`;var fL="AI_ToolCallNotFoundForApprovalError",Zq=`vercel.ai.error.${fL}`;var mL="AI_MissingToolResultsError",jq=`vercel.ai.error.${mL}`;var cL="AI_NoOutputGeneratedError",Fq=`vercel.ai.error.${cL}`;var uL="AI_NoSuchToolError",_q=`vercel.ai.error.${uL}`;var pL="AI_ToolCallRepairError",Dq=`vercel.ai.error.${pL}`;var lL="AI_InvalidDataContentError",Oq=`vercel.ai.error.${lL}`;var dL="AI_InvalidMessageRoleError",Pq=`vercel.ai.error.${dL}`;var iL="AI_RetryError",qq=`vercel.ai.error.${iL}`;var nG="7.0.179",oG=async({url:Y,maxBytes:J,abortSignal:X,fetch:$})=>{let Q=Y.toString();try{let G=N7({},`ai-sdk/${nG}`,V7()),z=await jG({url:Q,headers:G,abortSignal:X,fetch:$});if(!z.ok)throw await NY(z),new h0({url:Q,statusCode:z.status,statusText:z.statusText});return{data:await FG({response:z,url:Q,maxBytes:J??L7}),mediaType:z.headers.get("content-type")??void 0}}catch(G){if(h0.isInstance(G))throw G;throw new h0({url:Q,cause:G})}};var Eq=Symbol("ai-sdk-tool-call-input-schema-input");var eL="AI_InvalidStreamPartError",wA=`vercel.ai.error.${eL}`;var YZ="AI_NoImageGeneratedError",SA=`vercel.ai.error.${YZ}`;var JZ="AI_NoObjectGeneratedError",IA=`vercel.ai.error.${JZ}`;var XZ="AI_NoSpeechGeneratedError",bA=`vercel.ai.error.${XZ}`;var $Z="AI_NoTranscriptGeneratedError",kA=`vercel.ai.error.${$Z}`;var QZ="AI_NoTranslationGeneratedError",xA=`vercel.ai.error.${QZ}`;var GZ="AI_NoVideoGeneratedError",hA=`vercel.ai.error.${GZ}`;var zZ="AI_StreamProviderError",vA=`vercel.ai.error.${zZ}`;var WZ="AI_ToolChoiceViolationError",yA=`vercel.ai.error.${WZ}`;var KZ="AI_UIMessageStreamError",gA=`vercel.ai.error.${KZ}`;var UZ="AI_MessageConversionError",fA=`vercel.ai.error.${UZ}`;var mA=S0({prefix:"steer",size:24});var cA=S0({prefix:"aitxt",size:24}),uA=S0({prefix:"call",size:24});var pA=class extends TransformStream{constructor(){super({transform(Y,J){J.enqueue(`data: ${JSON.stringify(Y)}
31
+
32
+ `)},flush(Y){Y.enqueue(`data: [DONE]
33
+
34
+ `)}})}};var W={NEVER:fJ,array:SG,boolean:CG,custom:lG,discriminatedUnion:vG,enum:gG,extend:xG,int:RG,literal:fG,looseObject:kG,maximum:Y1,minLength:J1,never:wG,nonnegative:t9,number:TG,object:bG,optional:cG,pipe:uG,positive:a9,record:yG,refine:dG,safeParse:f1,startsWith:D4,string:AG,transform:mG,union:hG,unknown:F7},_={array:$7,boolean:lQ,custom:YG,discriminatedUnion:oQ,instanceof:JG,lazy:eQ,literal:sQ,null:dQ,number:pQ,object:iQ,record:rQ,string:cQ,union:Q7,unknown:VY},P4=_.lazy(()=>_.union([_.null(),_.string(),_.number(),_.boolean(),_.record(_.string(),P4.optional()),_.array(P4)])),i=_.record(_.string(),_.record(_.string(),P4.optional()));function aG(Y){return W.object({source:W.discriminatedUnion("sourceType",[W.object({type:W.literal("source"),sourceType:W.literal("url"),id:W.string(),url:W.string(),title:W.optional(W.string()),providerMetadata:W.optional(Y)}),W.object({type:W.literal("source"),sourceType:W.literal("document"),id:W.string(),mediaType:W.string(),title:W.string(),filename:W.optional(W.string()),providerMetadata:W.optional(Y)})]),startIndex:W.optional(W.number().check(W.int()).check(W.nonnegative())),endIndex:W.optional(W.number().check(W.int()).check(W.nonnegative())),citedText:W.optional(W.string())})}var HZ=aG(i),M8=W.record(W.string(),W.optional(P4)),lA=j7(()=>ZY(W.union([W.looseObject({type:W.literal("text-start"),id:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("text-delta"),id:W.string(),delta:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("text-end"),id:W.string(),citations:W.optional(W.array(HZ)),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("error"),errorText:W.string()}),W.looseObject({type:W.literal("tool-input-start"),toolCallId:W.string(),toolName:W.string(),inputEncoding:W.optional(W.enum(["json","text"])),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i),toolMetadata:W.optional(M8),dynamic:W.optional(W.boolean()),title:W.optional(W.string())}),W.looseObject({type:W.literal("tool-input-delta"),toolCallId:W.string(),inputTextDelta:W.string()}),W.looseObject({type:W.literal("tool-input-available"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i),toolMetadata:W.optional(M8),dynamic:W.optional(W.boolean()),title:W.optional(W.string())}),W.looseObject({type:W.literal("tool-input-error"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i),toolMetadata:W.optional(M8),dynamic:W.optional(W.boolean()),errorText:W.string(),title:W.optional(W.string())}),W.looseObject({type:W.literal("tool-approval-request"),approvalId:W.string(),toolCallId:W.string(),approvalDescriptor:W.optional(W.unknown()),inputSchemaInput:W.optional(W.unknown()),reason:W.optional(W.string()),isAutomatic:W.optional(W.boolean()),signature:W.optional(W.string())}),W.looseObject({type:W.literal("tool-approval-response"),approvalId:W.string(),approved:W.boolean(),reason:W.optional(W.string()),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("tool-output-available"),toolCallId:W.string(),output:W.unknown(),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i),toolMetadata:W.optional(M8),dynamic:W.optional(W.boolean()),preliminary:W.optional(W.boolean())}),W.looseObject({type:W.literal("tool-output-error"),toolCallId:W.string(),errorText:W.string(),providerExecuted:W.optional(W.boolean()),providerMetadata:W.optional(i),toolMetadata:W.optional(M8),dynamic:W.optional(W.boolean())}),W.looseObject({type:W.literal("tool-output-denied"),toolCallId:W.string()}),W.looseObject({type:W.literal("reasoning-start"),id:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("reasoning-delta"),id:W.string(),delta:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("reasoning-end"),id:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("custom"),kind:W.pipe(W.string(),W.transform((Y)=>Y)),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.optional(W.string()),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.optional(W.string()),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("file"),url:W.string(),mediaType:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("reasoning-file"),url:W.string(),mediaType:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("steering-message"),id:W.string(),parts:W.array(W.union([W.looseObject({type:W.literal("text"),text:W.string(),providerMetadata:W.optional(i)}),W.looseObject({type:W.literal("file"),mediaType:W.string(),url:W.string(),filename:W.optional(W.string()),providerReference:W.optional(W.record(W.string(),W.string())),providerMetadata:W.optional(i)})]))}),W.looseObject({type:W.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:W.optional(W.string()),data:W.unknown(),transient:W.optional(W.boolean())}),W.looseObject({type:W.literal("start-step")}),W.looseObject({type:W.literal("finish-step")}),W.looseObject({type:W.literal("reset-step")}),W.looseObject({type:W.literal("start"),messageId:W.optional(W.string()),messageMetadata:W.optional(W.unknown())}),W.looseObject({type:W.literal("finish"),finishReason:W.optional(W.enum(["stop","length","content-filter","tool-calls","error","interrupted","other"])),messageMetadata:W.optional(W.unknown())}),W.looseObject({type:W.literal("abort"),reason:W.optional(W.string())}),W.looseObject({type:W.literal("message-metadata"),messageMetadata:W.unknown()})])));var dA=Symbol("streamRetryAttemptBoundary");var iA=S0({prefix:"aitxt",size:24}),nA=S0({prefix:"call",size:24});var oA=S0({prefix:"aitxt",size:24}),rA=S0({prefix:"call",size:24});var sA=Symbol("streamRetryBoundary");var X1=Symbol("invalid");function BZ(Y){let J=[],X=_7(Y,J,new Set);return X===X1?{success:!1,path:J}:{success:!0,value:X}}function _7(Y,J,X){switch(typeof Y){case"string":case"boolean":return Y;case"number":return Number.isFinite(Y)?Y:X1;case"object":{if(Y===null)return Y;if(X.has(Y))return X1;X.add(Y);let $=Array.isArray(Y)?VZ(Y,J,X):NZ(Y,J,X);return X.delete(Y),$}default:return X1}}function VZ(Y,J,X){let $;for(let Q=0;Q<Y.length;Q++){let G=Y[Q];J.push(Q);let z=_7(G,J,X);if(z===X1)return X1;if(J.pop(),$!=null)$.push(z);else if(z!==G)$=Y.slice(0,Q),$.push(z)}return $??Y}function NZ(Y,J,X){if(!LZ(Y)||ZZ(Y))return X1;let $=Object.keys(Y),Q;for(let G=0;G<$.length;G++){let z=$[G];if(z==="__proto__"){Q??=rG(Y,$,G);continue}let K=Y[z],U=K;if(K!==void 0){if(J.push(z),U=_7(K,J,X),U===X1)return X1;J.pop()}if(Q!=null)Q[z]=U;else if(U!==K)Q=rG(Y,$,G),Q[z]=U}return Q??Y}function rG(Y,J,X){let $={};for(let Q=0;Q<X;Q++)$[J[Q]]=Y[J[Q]];return $}function LZ(Y){let J=Y.constructor;if(typeof J!=="function")return!0;let X=J.prototype;return X!==null&&typeof X==="object"&&Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")}function ZZ(Y){let J=Object.getOwnPropertySymbols(Y);for(let X=0;X<J.length;X++)if(Object.prototype.propertyIsEnumerable.call(Y,J[X]))return!0;return!1}var tG=W.pipe(W.unknown(),W.transform((Y,J)=>{let X=BZ(Y);if(!X.success)return J.issues.push({code:"custom",message:"Invalid JSON value. Expected null, a string, a finite number, a boolean, an array, or an object.",input:Y,path:X.path}),W.NEVER;return X.value})),eG=W.custom(),X6=W.pipe(tG,W.record(W.string(),eG)),j0=W.pipe(tG,W.record(W.string(),W.record(W.string(),eG))),sG=W.record(W.string(),W.string()),jZ=aG(j0);function jY(Y){return W.pipe(W.array(W.unknown()),W.transform((J,X)=>{let $=[];for(let[Q,G]of J.entries()){let z=W.safeParse(Y(G),G);if(!z.success){for(let K of z.error.issues)X.issues.push({...K,path:[Q,...K.path]});return W.NEVER}$.push(z.data)}return $}))}var aA=j7(()=>{let Y=W.object({id:W.string(),approved:W.optional(W.never()),descriptor:W.optional(W.unknown()),requestReason:W.optional(W.string()),reason:W.optional(W.never()),isAutomatic:W.optional(W.boolean()),signature:W.optional(W.string()),inputSchemaInput:W.optional(W.unknown())}),J=W.extend(Y,{approved:W.boolean(),reason:W.optional(W.string())}),X=W.extend(J,{approved:W.literal(!0)}),$=W.extend(J,{approved:W.literal(!1)}),Q=W.discriminatedUnion("type",[W.object({type:W.literal("text"),text:W.string(),providerMetadata:W.optional(j0)}),W.object({type:W.literal("file"),mediaType:W.string(),filename:W.optional(W.string()),url:W.string(),providerReference:W.optional(sG),providerMetadata:W.optional(j0)})]),G='Invalid UI message part type. Expected a known part type (for example "text" or "dynamic-tool") or a type starting with "data-" or "tool-".',z=W.discriminatedUnion("type",[W.object({type:W.literal("text"),text:W.string(),citations:W.optional(jY(()=>jZ)),state:W.optional(W.enum(["streaming","done"])),providerMetadata:W.optional(j0)}),W.object({type:W.literal("reasoning"),id:W.optional(W.string()),text:W.string(),state:W.optional(W.enum(["streaming","done"])),providerMetadata:W.optional(j0)}),W.object({type:W.literal("custom"),kind:W.string(),providerMetadata:W.optional(j0)}),W.object({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.optional(W.string()),providerMetadata:W.optional(j0)}),W.object({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.optional(W.string()),providerMetadata:W.optional(j0)}),W.object({type:W.literal("file"),mediaType:W.string(),filename:W.optional(W.string()),url:W.string(),providerReference:W.optional(sG),providerMetadata:W.optional(j0)}),W.object({type:W.literal("reasoning-file"),mediaType:W.string(),url:W.string(),providerMetadata:W.optional(j0)}),W.object({type:W.literal("steering-message"),id:W.string(),parts:jY(()=>Q)}),W.object({type:W.literal("step-start")})],{error:(F)=>F.code==="invalid_union"?'Invalid UI message part type. Expected a known part type (for example "text" or "dynamic-tool") or a type starting with "data-" or "tool-".':void 0}),K=W.object({type:W.string().check(W.startsWith("data-")),id:W.optional(W.string()),data:W.unknown()}),U=W.discriminatedUnion("state",[W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("input-streaming"),input:W.optional(W.unknown()),rawInput:W.optional(W.string()),inputEncoding:W.optional(W.enum(["json","text"])),providerExecuted:W.optional(W.boolean()),callProviderMetadata:W.optional(j0),output:W.optional(W.never()),errorText:W.optional(W.never()),approval:W.optional(W.never())}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("input-available"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:W.optional(W.never())}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:Y}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:J}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-available"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.unknown(),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),resultProviderMetadata:W.optional(j0),preliminary:W.optional(W.boolean()),approval:W.optional(X)}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-error"),input:W.optional(W.unknown()),rawInput:W.optional(W.unknown()),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.string(),callProviderMetadata:W.optional(j0),resultProviderMetadata:W.optional(j0),approval:W.optional(X)}),W.object({type:W.literal("dynamic-tool"),dynamic:W.optional(W.literal(!1)),toolName:W.string(),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-denied"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:$})]),H=W.discriminatedUnion("state",[W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("input-streaming"),providerExecuted:W.optional(W.boolean()),callProviderMetadata:W.optional(j0),input:W.optional(W.unknown()),rawInput:W.optional(W.string()),inputEncoding:W.optional(W.enum(["json","text"])),output:W.optional(W.never()),errorText:W.optional(W.never()),approval:W.optional(W.never())}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("input-available"),providerExecuted:W.optional(W.boolean()),input:W.unknown(),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:W.optional(W.never())}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:Y}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.optional(W.boolean()),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:J}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-available"),providerExecuted:W.optional(W.boolean()),input:W.unknown(),output:W.unknown(),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),resultProviderMetadata:W.optional(j0),preliminary:W.optional(W.boolean()),approval:W.optional(X)}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-error"),providerExecuted:W.optional(W.boolean()),input:W.optional(W.unknown()),rawInput:W.optional(W.unknown()),output:W.optional(W.never()),errorText:W.string(),callProviderMetadata:W.optional(j0),resultProviderMetadata:W.optional(j0),approval:W.optional(X)}),W.object({type:W.string().check(W.startsWith("tool-")),toolCallId:W.string(),title:W.optional(W.string()),toolMetadata:W.optional(X6),state:W.literal("output-denied"),providerExecuted:W.optional(W.boolean()),input:W.unknown(),output:W.optional(W.never()),errorText:W.optional(W.never()),callProviderMetadata:W.optional(j0),approval:$})]),V=W.object({id:W.string(),role:W.enum(["system","user","assistant"]),metadata:W.optional(W.unknown()),parts:jY((F)=>{let Z=F?.type;if(typeof Z==="string"){if(Z.startsWith("data-"))return K;if(Z.startsWith("tool-"))return H;if(Z==="dynamic-tool")return U}return z})}).check((F)=>{let Z=F.value;if(Z.role!=="assistant"&&Z.parts.length===0)F.issues.push({continue:!0,origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Z.parts,path:["parts"],message:"Message must contain at least one part"})});return ZY(jY(()=>V).check(W.minLength(1,"Messages array must not be empty")))});var tA=S0({prefix:"call",size:24});var eA=S0({prefix:"call",size:24});var YM=S0({prefix:"call",size:24});var JM=S0({prefix:"call",size:24});var XM=S0({prefix:"aiobj",size:24});function Yz(Y){let J=({url:X,abortSignal:$})=>oG({url:X,maxBytes:Y?.maxBytes,abortSignal:$,fetch:Y?.fetch});return(X)=>Array.isArray(X)?Promise.all(X.map(($)=>$.isUrlSupportedByModel?null:J($))):J(X)}var $M=S0({prefix:"aiobj",size:24});var QM=S0({prefix:"call",size:24});var GM=Yz();var T8=_.union([_.string(),_.custom(H7,{message:"Must be a Uint8Array"}),_.custom(B7,{message:"Must be an ArrayBuffer"}),_.custom(Z7,{message:"Must be a Buffer"})]),D7=_.record(_.string(),_.string()),Jz=_.object({type:_.literal("text"),text:_.string(),providerOptions:i.optional()}),FZ=_.object({type:_.literal("image"),image:_.union([T8,_.instanceof(URL),D7]),mediaType:_.string().optional(),providerOptions:i.optional()}),Xz=_.discriminatedUnion("type",[_.object({type:_.literal("data"),data:T8}),_.object({type:_.literal("url"),url:_.instanceof(URL)}),_.object({type:_.literal("reference"),reference:D7}),_.object({type:_.literal("text"),text:_.string()})]),_Z=_.discriminatedUnion("type",[_.object({type:_.literal("data"),data:T8}),_.object({type:_.literal("url"),url:_.instanceof(URL)})]),$z=_.object({type:_.literal("file"),data:_.union([Xz,T8,_.instanceof(URL),D7]),filename:_.string().optional(),mediaType:_.string(),providerOptions:i.optional()}),DZ=_.object({type:_.literal("reasoning"),text:_.string(),providerOptions:i.optional()}),OZ=_.object({type:_.literal("custom"),kind:_.string().transform((Y)=>Y),providerOptions:i.optional()}),PZ=_.object({type:_.literal("reasoning-file"),data:_.union([_Z,T8,_.instanceof(URL)]),mediaType:_.string(),providerOptions:i.optional()}),qZ=_.object({type:_.literal("tool-call"),toolCallId:_.string(),toolName:_.string(),input:_.unknown(),providerOptions:i.optional(),providerExecuted:_.boolean().optional()}),EZ=_.discriminatedUnion("type",[_.object({type:_.literal("text"),value:_.string(),providerOptions:i.optional()}),_.object({type:_.literal("json"),value:P4,providerOptions:i.optional()}),_.object({type:_.literal("execution-denied"),reason:_.string().optional(),providerOptions:i.optional()}),_.object({type:_.literal("error-text"),value:_.string(),providerOptions:i.optional()}),_.object({type:_.literal("error-json"),value:P4,providerOptions:i.optional()}),_.object({type:_.literal("content"),value:_.array(_.union([_.object({type:_.literal("text"),text:_.string(),providerOptions:i.optional()}),_.object({type:_.literal("file"),data:Xz,mediaType:_.string(),filename:_.string().optional(),providerOptions:i.optional()}),_.object({type:_.literal("file-data"),data:_.string(),mediaType:_.string(),filename:_.string().optional(),providerOptions:i.optional()}),_.object({type:_.literal("file-url"),url:_.string(),mediaType:_.string().optional(),providerOptions:i.optional()}),_.object({type:_.literal("file-id"),fileId:_.union([_.string(),_.record(_.string(),_.string())]),providerOptions:i.optional()}),_.object({type:_.literal("file-reference"),providerReference:_.record(_.string(),_.string()),providerOptions:i.optional()}),_.object({type:_.literal("image-data"),data:_.string(),mediaType:_.string(),providerOptions:i.optional()}),_.object({type:_.literal("image-url"),url:_.string(),providerOptions:i.optional()}),_.object({type:_.literal("image-file-id"),fileId:_.union([_.string(),_.record(_.string(),_.string())]),providerOptions:i.optional()}),_.object({type:_.literal("image-file-reference"),providerReference:_.record(_.string(),_.string()),providerOptions:i.optional()}),_.object({type:_.literal("custom"),providerOptions:i.optional()})]))})]),Qz=_.object({type:_.literal("tool-result"),toolCallId:_.string(),toolName:_.string(),output:EZ,providerOptions:i.optional()}),AZ=_.object({type:_.literal("tool-approval-request"),approvalId:_.string(),toolCallId:_.string(),reason:_.string().optional(),isAutomatic:_.boolean().optional(),signature:_.string().optional(),inputSchemaInput:_.unknown().optional()}),MZ=_.object({type:_.literal("tool-approval-response"),approvalId:_.string(),approved:_.boolean(),reason:_.string().optional()}),TZ=_.object({role:_.literal("system"),content:_.string(),providerOptions:i.optional()}),RZ=_.object({role:_.literal("user"),content:_.union([_.string(),_.array(_.union([Jz,FZ,$z]))]),providerOptions:i.optional()}),CZ=_.object({role:_.literal("assistant"),content:_.union([_.string(),_.array(_.union([Jz,OZ,$z,DZ,PZ,qZ,Qz,AZ]))]),providerOptions:i.optional()}),wZ=_.object({role:_.literal("tool"),content:_.array(_.union([Qz,MZ])),providerOptions:i.optional()}),zM=_.union([TZ,RZ,CZ,wZ]);var WM=W.object({token:W.string().check(W.refine((Y)=>Y.trim().length>0)),url:W.string().check(W.refine((Y)=>{try{let J=new URL(Y);return(J.protocol==="ws:"||J.protocol==="wss:")&&J.hostname!==""}catch{return!1}})),expiresAt:W.optional(W.number().check(W.positive()).check(W.maximum(Number.MAX_SAFE_INTEGER))),tools:W.optional(W.array(W.object({type:W.literal("function"),name:W.string().check(W.minLength(1)),description:W.optional(W.string()),parameters:W.record(W.string(),W.unknown())})))});var SZ="AI_NoSuchProviderError",KM=`vercel.ai.error.${SZ}`;var UM=S0({prefix:"call",size:24});var HM=S0({prefix:"call",size:24}),BM=Yz();var VM=S0({prefix:"call",size:24});var{dumpCodexRequest:q4,dumpDiagnostic:c1,resetDumpStateForTest:OM}=Gz({enabled:G9,dir:()=>T6().dumpDir,maxBytes:()=>T6().dumpMaxBytes});function R8(Y){let J=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function FY(Y,J,X=!1){let Q=Buffer.from(Y.slice(0,J)).toString("latin1").split(`\r
35
+ `),G=Q[0]??"",z=R8(G);if(z===void 0||z===101)return;let K=Object.fromEntries(Q.slice(1).flatMap((N)=>{let j=N.indexOf(":");return j===-1?[]:[[N.slice(0,j).trim().toLowerCase(),N.slice(j+1).trim()]]})),U=Y.slice(J+4),H=K["content-length"],V=Number(H);if(!X&&(H===void 0||Number.isFinite(V)&&U.length<V))return;let F=Buffer.from(U).toString("utf8"),Z=(()=>{try{let N=JSON.parse(F);return Q0(N)?N:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:z,status_code:z,headers:K,body:F,...Q0(Z?.error)?{error:Z.error}:{}}}var IZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",zz=["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 O7{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,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),$=X.hostname,Q=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,z=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(z).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+IZ));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[Z,N]of Object.entries(J))H[Z.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${$}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let Z of zz)if(H[Z]!==void 0)V.push(`${bZ(Z)}: ${H[Z]}`);for(let[Z,N]of Object.entries(J))if(!zz.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")V.push(`${Z}: ${N}`);let F=`${V.join(`\r
36
+ `)}\r
37
+ \r
38
+ `;try{this.log("connect_start",{host:$,port:Q,tls:X.protocol==="https:"});let Z=globalThis.Bun?.connect;if(!Z)throw Error("Bun.connect is not available");this.socket=await Z({hostname:$,port:Q,tls:X.protocol==="https:"?{serverName:$}:void 0,socket:{open:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(F))},data:(N,j)=>this.onData(j),drain:()=>this.flushWrites(),error:(N,j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let P=j instanceof Error?j.message:String(j);this.log("socket_error",{message:P}),this.emit("error",{message:P})},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(Z){this.readyState=3;let N=Z instanceof Error?Z.message:String(Z);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(Y){if(this.rxBuffer=kZ(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
39
+ \r
40
+ `);if(X===-1)return;let $=J.slice(0,X),Q=$.split(`\r
41
+ `)[0]??"",G=$.match(/sec-websocket-accept:\s*(\S+)/i),z=R8(Q);if(z!==101){if(z===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:Q}),this.emit("error",{message:`WS upgrade failed: ${Q}`});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:Q}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:Q}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
42
+ \r
43
+ `);if(J===-1)return!1;let X=FY(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],$=(J&128)!==0,Q=J&15,G=(X&128)!==0,z=X&127,K=2;if(z===126){if(Y.length<4)return;z=Y[2]<<8|Y[3],K=4}else if(z===127){if(Y.length<10)return;z=0;for(let H=0;H<8;H++)z=z*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+z)return;let U=Y.slice(K,K+z);this.rxBuffer=Y.slice(K+z),this.handleFrame($,Q,U)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let Q=1005,G="";if(X.length>=2)Q=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:Q,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:Q,reason:G}),this.emitClose(Q,G);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let $=xZ(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let Q=Buffer.from($).toString("utf-8");this.emit("message",{data:Q})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,$=crypto.getRandomValues(new Uint8Array(4)),Q;if(X<126)Q=[128|Y,128|X];else if(X<65536)Q=[128|Y,254,X>>8&255,X&255];else{Q=[128|Y,255];for(let K=7;K>=0;K--)Q.push(X/2**(8*K)&255)}let G=new Uint8Array(X);for(let K=0;K<X;K++)G[K]=J[K]^$[K%4];let z=new Uint8Array(Q.length+4+X);z.set(Q,0),z.set($,Q.length),z.set(G,Q.length+4);try{this.enqueueWrite(z)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let J=this.writeQueue[0],X=Y.write(J);if(X<J.length){this.writeQueue[0]=J.slice(X),this.log("write_backpressure",{written:X,remaining:J.length-X});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,J){return c1({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function bZ(Y){return Y}function kZ(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function xZ(Y){let J=0;for(let Q of Y)J+=Q.length;let X=new Uint8Array(J),$=0;for(let Q of Y)X.set(Q,$),$+=Q.length;return X}import{connect as hZ}from"node:net";import{connect as vZ}from"node:tls";var yZ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Wz=["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 P7{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,J,X){this.url=Y,this.sessionID=X?.sessionID,this.connect(Y,J)}addEventListener(Y,J,X){this.listeners[Y]?.add(J)}removeEventListener(Y,J){this.listeners[Y]?.delete(J)}peerClose;closeEmitted=!1;emitClose(Y,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:Y,reason:J})}emit(Y,J){for(let X of[...this.listeners[Y]??[]])try{X(J)}catch{}}async connect(Y,J){let X=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),$=X.hostname,Q=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,z=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(z).toString("base64"),U=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+yZ));this.expectedAccept=Buffer.from(new Uint8Array(U)).toString("base64");let H={};for(let[Z,N]of Object.entries(J))H[Z.toLowerCase()]=N;let V=[`GET ${G} HTTP/1.1`,`Host: ${$}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let Z of Wz)if(H[Z]!==void 0)V.push(`${gZ(Z)}: ${H[Z]}`);for(let[Z,N]of Object.entries(J))if(!Wz.includes(Z.toLowerCase())&&Z.toLowerCase()!=="content-length")V.push(`${Z}: ${N}`);let F=`${V.join(`\r
44
+ `)}\r
45
+ \r
46
+ `;try{this.log("connect_start",{host:$,port:Q,tls:X.protocol==="https:"});let Z=()=>{this.socket?.write(F)},N=X.protocol==="https:"?vZ({host:$,port:Q,servername:$},Z):hZ({host:$,port:Q},Z);this.socket=N,N.on("data",(j)=>{this.onData(typeof j==="string"?Buffer.from(j,"binary"):j)}),N.on("error",(j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let P=j instanceof Error?j.message:String(j);this.log("socket_error",{message:P}),this.emit("error",{message:P})}),N.on("close",(j)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:j}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(Z){this.readyState=3,this.log("connect_exception",{message:Z instanceof Error?Z.message:String(Z)}),this.emit("error",{message:Z instanceof Error?Z.message:String(Z)})}}onData(Y){if(this.rxBuffer=fZ(this.rxBuffer,Y),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),X=J.indexOf(`\r
47
+ \r
48
+ `);if(X===-1)return;let $=J.slice(0,X),Q=$.split(`\r
49
+ `)[0]??"",G=$.match(/sec-websocket-accept:\s*(\S+)/i),z=R8(Q);if(z!==101){if(z===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:Q}),this.emit("error",{message:`WS upgrade failed: ${Q}`});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:Q}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:Q}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
50
+ \r
51
+ `);if(J===-1)return!1;let X=FY(this.rxBuffer,J,Y);if(!X)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:X.status,partial:Y}),this.emit("error",X),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let J=Y[0],X=Y[1],$=(J&128)!==0,Q=J&15,G=(X&128)!==0,z=X&127,K=2;if(z===126){if(Y.length<4)return;z=Y[2]<<8|Y[3],K=4}else if(z===127){if(Y.length<10)return;z=0;for(let H=0;H<8;H++)z=z*256+Y[2+H];K=10}if(G)K+=4;if(Y.length<K+z)return;let U=Y.slice(K,K+z);this.rxBuffer=Y.slice(K+z),this.handleFrame($,Q,U)}}handleFrame(Y,J,X){if(J===9){this.writeFrame(10,X);return}if(J===10)return;if(J===8){let Q=1005,G="";if(X.length>=2)Q=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:Q,reason:G};try{this.socket?.end()}catch{}this.log("close_frame",{code:Q,reason:G}),this.emitClose(Q,G);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[X];else if(J===0)this.fragChunks.push(X);if(!Y)return;let $=mZ(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let Q=Buffer.from($).toString("utf-8");this.emit("message",{data:Q})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,J){let X=J.length,$=crypto.getRandomValues(new Uint8Array(4)),Q;if(X<126)Q=[128|Y,128|X];else if(X<65536)Q=[128|Y,254,X>>8&255,X&255];else{Q=[128|Y,255];for(let K=7;K>=0;K--)Q.push(X/2**(8*K)&255)}let G=new Uint8Array(X);for(let K=0;K<X;K++)G[K]=J[K]^$[K%4];let z=new Uint8Array(Q.length+4+X);z.set(Q,0),z.set($,Q.length),z.set(G,Q.length+4);try{this.socket?.write(z)}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,J){return c1({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...J})}}function gZ(Y){return Y}function fZ(Y,J){let X=new Uint8Array(Y.length+J.length);return X.set(Y,0),X.set(J,Y.length),X}function mZ(Y){let J=0;for(let Q of Y)J+=Q.length;let X=new Uint8Array(J),$=0;for(let Q of Y)X.set(Q,$),$+=Q.length;return X}function cZ(){return typeof globalThis.Bun?.connect==="function"}var Kz=cZ()?O7:P7;class $6 extends y1{name="ProviderResponseStreamError";constructor(Y,J){super({message:Y,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}function _Y(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function uZ(Y){let J=_Y("NO_PROXY");if(!J)return!1;let X=Y.hostname.toLowerCase(),$=J.split(",").map((Q)=>Q.trim().toLowerCase()).filter(Boolean);for(let Q of $){if(Q==="*")return!0;if(Q.startsWith(".")){if(X===Q.slice(1)||X.endsWith(Q))return!0}else if(X===Q||X.endsWith(`.${Q}`))return!0}return!1}function pZ(Y){let J=new URL(Y);if(uZ(J))return;if(J.protocol==="http:")return _Y("HTTP_PROXY");if(J.protocol==="https:")return _Y("HTTPS_PROXY")??_Y("HTTP_PROXY");return}var Uz={getProxyForUrl:pZ};var lZ=U0("quota"),q1=U0("transport"),Nz="responses_websockets=2026-02-06",Hz=["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"],dZ=new Set([m1,"x-opencode-title"]);function iZ(Y){let J=new Map;for(let $ of Object.keys(Y))J.set($.toLowerCase(),$);let X={};for(let $ of Hz){let Q=J.get($),G=Q===void 0?void 0:Y[Q];if(Q!==void 0&&G!==void 0)X[Q]=G}for(let[$,Q]of Object.entries(Y))if(!Hz.includes($.toLowerCase()))X[$]=Q;return X}function nZ(Y){let J={};for(let[X,$]of Object.entries(Y)){if(dZ.has(X.toLowerCase()))continue;J[X]=$}return J}function oZ(Y){return Y.replace(/^http/,"ws")}function rZ(Y){let J={};if(!Y)return J;if(Y instanceof Headers)return Y.forEach((X,$)=>{J[$.toLowerCase()]=X}),J;if(Array.isArray(Y)){for(let[X,$]of Y)J[X.toLowerCase()]=$;return J}for(let[X,$]of Object.entries(Y))if($!=null)J[X.toLowerCase()]=String($);return J}function M7(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var Lz=new WeakSet;function sZ(Y){return typeof Y==="object"&&Y!==null&&Lz.has(Y)}var Zz=new WeakSet;function aZ(Y){return typeof Y==="object"&&Y!==null&&Zz.has(Y)}function jz(Y){return Zz.add(Y),Y}function Bz(Y,J){let X=Error(Y,J===void 0?void 0:{cause:J});return Lz.add(X),X}function tZ(Y){return new Promise((J,X)=>{if(Y.signal?.aborted){X(q7(Y.signal));return}let $={...Y.headers,"openai-beta":Y.headers["openai-beta"]??Nz},Q=$[m1]??$["session-id"];delete $["content-length"],$=iZ(nZ($));let G=typeof Bun>"u"?void 0:Uz.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),z=!0,K=Y.rawWebSocket?new Kz(Y.url,$,{sessionID:Q}):new globalThis.WebSocket(Y.url,{headers:$,...G?{proxy:G}:{},perMessageDeflate:z}),U=Y.timeout?setTimeout(()=>{H(),K.close(),X(Error("WebSocket connect timed out"))},Y.timeout):void 0;function H(){if(U)clearTimeout(U);K.removeEventListener("open",V),K.removeEventListener("error",F),K.removeEventListener("close",Z),Y.signal?.removeEventListener("abort",N)}function V(){H(),J(K)}function F(j){H(),X(Bz(E4(j),j))}function Z(j){H(),X(Bz(Oz("WebSocket closed before open",j.code,j.reason)))}function N(){H(),K.close(),X(q7(Y.signal))}K.addEventListener("open",V,{once:!0}),K.addEventListener("error",F,{once:!0}),K.addEventListener("close",Z,{once:!0}),Y.signal?.addEventListener("abort",N,{once:!0})})}function eZ(Y){let J=new TextEncoder,X=Y.socket,$,Q=()=>{},G=!1,z=0,K=!1,U=!1,H,V=[],F=12,Z=[],N=typeof Y.body.previous_response_id==="string"?Y.body.previous_response_id:void 0,j=typeof Y.body.prompt_cache_key==="string"?Y.body.prompt_cache_key:void 0,P={sessionID:Y.sessionID,codexSessionID:j},v,y=0,I,A=new Set,q={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function C(){if(H)clearTimeout(H);Q(),Y.signal?.removeEventListener("abort",G1)}function m(w=X){w.close()}function r(){C(),$?.enqueue(J.encode(`data: [DONE]
52
+
53
+ `)),$?.close()}function l(w){A0(w,w)}function R0(){if(!U)return"none";if(q.other)return"other";if(q.finished)return q.reasoningItemIds.size>0?"other":"finished-calls";return q.addedItemIds.size>0?"unfinished-calls":"none"}function B0(){$?.enqueue(J.encode(`data: ${JSON.stringify(Wj)}
54
+
55
+ `)),r()}function z0(w){let N0={...P,openingFrameTypes:V,openingItemTypes:Z,responseID:v,previousResponseID:N,hasContinuation:N!==void 0,framesSinceCreated:y,msSinceLastFrame:I===void 0?void 0:Date.now()-I},c=R0();if(c==="finished-calls"){if(G)return;q1.warn("stream failed after finished function calls only; ended as completed",{reason:w.message,emittedOutput:!0,outputShape:c,...N0}),G=!0,C(),Y.onConnectionInvalid?.(w),B0();return}if(c==="other"){let t=E7;q1.warn("stream failed after output; not retried",{reason:w.message,emittedOutput:!0,outputShape:c,...N0}),A0(Error(t,{cause:w}),new $6(t,{cause:w}));return}let F0=q.reasoningItemIds.size;q1.warn(c==="unfinished-calls"?"stream failed after unfinished function calls only; retryable":F0>0?"stream failed after reasoning without text only; retryable":"stream failed before output; retryable",{reason:w.message,emittedOutput:U,outputShape:c,emptyReasoningItems:F0,...N0}),l(w)}function A0(w,N0){if(G)return;G=!0,C(),Y.onConnectionInvalid?.(N0),$?.error(w)}function f(w){if(G)return;if(!Y.idleTimeout)return;if(H)clearTimeout(H);H=setTimeout(()=>z0(new $6(w)),Y.idleTimeout)}async function V0(w){if(G)return;if(typeof w.data!=="string"){z0(new $6("Unexpected binary WebSocket frame"));return}let N0=w.data,c=(()=>{try{let W0=JSON.parse(N0);return typeof W0==="object"&&W0!==null?W0:void 0}catch{return}})();if(c?.type==="codex.rate_limits"){lZ.debug("codex.rate_limits frame received",{pid:process.pid}),f("idle timeout waiting for websocket");let W0=DY(c);Y.onQuota?.(W0,c);return}let F0=R0(),t=F0==="none"||F0==="unfinished-calls"?u1(c):void 0;if(t&&c){G=!0,C(),Y.onRateLimitReached?.(t.window,t.resetAt),Y.onTerminal?.(c),Y.onFirstEvent?.(),$?.error(new $6(`OpenAI account rate limit reached at admission (${t.window})`));return}if(c?.type==="error"&&Y.onRetryableTerminal){if(Q(),H)clearTimeout(H);H=void 0;try{let W0=await Y.onRetryableTerminal(c);if(G){if(W0)m(W0);return}if(W0){p6(W0);return}}catch(W0){z0(new $6(W0 instanceof Error?W0.message:String(W0),{cause:W0}));return}}let _0=Xj(c,N0);if(_0&&c){if(!K)Y.onFirstEvent?.(_0);G=!0,C(),Y.onTerminal?.(c);let W0=new y1({message:_0.message,url:X.url,requestBodyValues:Y.body,statusCode:_0.status,responseHeaders:_0.headers,responseBody:_0.body}),E0=R0();if(E0==="none"||E0==="unfinished-calls"){if(E0==="unfinished-calls")q1.warn("protocol error after unfinished function calls only; surfaced as before output",{...P,status:_0.status,reason:_0.message,outputShape:E0,responseID:v,previousResponseID:N});$?.error(W0);return}if(q1.warn(E0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...P,status:_0.status,reason:_0.message,outputShape:E0,responseID:v,previousResponseID:N}),E0==="finished-calls"){B0();return}$?.error(Error(E7,{cause:W0}));return}if(Q0(c)&&c.type==="response.failed"){let W0=Q0(c.response)?c.response.failed:void 0,E0=Q0(W0)?W0.rate_limit_reached_type:void 0;if(typeof E0==="string"){G=!0,C(),Y.onRateLimitReached?.(E0),Y.onTerminal?.(c);let H6=R0();if(H6!=="none")q1.warn(H6==="other"?"rate limit reached after output; ended without retry":H6==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...P,outputShape:H6,responseID:v,previousResponseID:N});if(H6==="none"||H6==="unfinished-calls")Y.onFirstEvent?.(),$?.error(new $6(`OpenAI account rate limit reached mid-stream (${E0})`));else if(H6==="finished-calls")B0();else r();return}}if(!c){if(!K)Y.onFirstEvent?.();f("idle timeout waiting for websocket");return}if(Yj(c,A),!K)Y.onFirstEvent?.();if($?.enqueue(J.encode(`${N0.split(/\r?\n/).map((W0)=>`data: ${W0}`).join(`
56
+ `)}
57
+
58
+ `)),K=!0,I=Date.now(),v!==void 0)y++;if(V.length<F)V.push(String(c.type));if(c.type==="response.output_item.added"&&Z.length<F)Z.push(Q0(c.item)?String(c.item.type):"unknown");if(c.type==="response.created")v=Gj(c),q1.debug("response created",{...P,responseID:v,previousResponseID:N,hasContinuation:N!==void 0});if(!_z(c.type))U=!0,zj(c,q);if(f("idle timeout waiting for websocket"),c.type==="response.completed"||c.type==="response.done"){if(G=!0,c.type==="response.completed")A7(c.response,"websocket","opencode1",{warm:!1,chained:"previous_response_id"in Y.body});Jj(c,A),Y.onComplete?.(c,A),Y.onTerminal?.(c),r();return}if(c.type==="response.failed"||c.type==="response.incomplete"||c.type==="error")G=!0,Y.onTerminal?.(c),r()}function b(w){z0(new $6(E4(w),{cause:w}))}function Q1(w){if(G)return;let N0=w.code===1009,c=new $6(N0?Dz:Oz("WebSocket closed before response.completed",w.code,w.reason),{retryable:!N0});if(N0)q1.warn("websocket peer refused the request size",{...P,requestBytes:z,reason:w.reason.toString()});z0(N0?jz(c):c)}function G1(){let w=q7(Y.signal);if(G)return;G=!0,C(),m(),Y.onAbort?.(w),$?.error(w)}function o1(w){if(G)return;G=!0,C(),m(),Y.onAbort?.($j(w))}function p6(w){Q(),X=w,X.addEventListener("message",V0),X.addEventListener("error",b,{once:!0}),X.addEventListener("close",Q1,{once:!0}),Q=()=>{X.removeEventListener("message",V0),X.removeEventListener("error",b),X.removeEventListener("close",Q1)};let{background:N0,...c}=Y.body;f("idle timeout sending websocket request");try{let F0=JSON.stringify({type:"response.create",...c});z=F0.length,X.send(F0),f("idle timeout waiting for websocket")}catch(F0){if(G)return;l(new $6(F0 instanceof Error?F0.message:String(F0),{cause:F0}))}}return new Response(new ReadableStream({start(w){if($=w,Y.signal?.addEventListener("abort",G1,{once:!0}),Y.signal?.aborted){G1();return}p6(X)},cancel(w){o1(w)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function Yj(Y,J){if(Y.type!=="response.output_item.done")return;if(!Q0(Y.item))return;Fz(Y.item,J)}function Jj(Y,J){let X=Y.response;if(!Q0(X)||!Array.isArray(X.output))return;for(let $ of X.output)if(Q0($))Fz($,J)}function Fz(Y,J){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let X=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(X)J.add(X)}function Xj(Y,J){if(Y?.type!=="error")return;let X=Y.status??Y.status_code;if(typeof X!=="number"||X>=200&&X<300)return;return{status:X,headers:Q0(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([$,Q])=>typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"?[[$,String(Q)]]:[])):void 0,body:J,message:Q0(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${X}`}}function u1(Y,J=Date.now()){if(typeof Y==="string")try{return u1(JSON.parse(Y),J)}catch{return}if(!Q0(Y))return;let X=u1(Y.cause,J);if(X)return X;let $=u1(Y.body,J);if($)return $;let Q=Q0(Y.error)?Y.error:Y,G=typeof Q.type==="string"?Q.type:void 0,z=Y.status??Y.status_code;if(G!=="usage_limit_reached"&&z!==429)return;let{resets_at:K,resets_in_seconds:U}=Q,H=typeof K==="number"&&Number.isFinite(K)&&K>0?K*1000:typeof U==="number"&&Number.isFinite(U)&&U>0?J+U*1000:void 0,V=typeof Q.code==="string"?Q.code:void 0;return{window:G??V??OY,resetAt:H}}var OY="rate_limit";function $j(Y){if(M7(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function q7(Y){let J=Y?.reason;if(M7(J))return J;if(Qj(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function Qj(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function Gj(Y){let J=Y.response;if(!Q0(J))return;return typeof J.id==="string"?J.id:void 0}function zj(Y,J){let X=Q0(Y.item)?Y.item:void 0;switch(Y.type){case"response.output_item.added":if(X?.type==="function_call"&&typeof X.id==="string"){J.addedItemIds.add(X.id);return}if(Vz(X)&&typeof X?.id==="string"){J.reasoningItemIds.add(X.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof Y.item_id==="string"&&J.addedItemIds.has(Y.item_id))return;break;case"response.output_item.done":if(X?.type==="function_call"&&X.status==="completed"&&typeof X.id==="string"&&typeof X.call_id==="string"&&typeof X.name==="string"&&typeof X.arguments==="string"){J.finished=!0;return}if(Vz(X)&&typeof X?.id==="string"&&J.reasoningItemIds.has(X.id))return;break}J.other=!0}function Vz(Y){if(Y?.type!=="reasoning")return!1;let J=(X)=>X===void 0||X===null||Array.isArray(X)&&X.length===0;return J(Y.summary)&&J(Y.content)}var Wj={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function _z(Y){return Y==="response.created"||Y==="response.in_progress"||Y.startsWith("codex.")}var E7="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.",Dz="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 Oz(Y,J,X){let $=[`code ${J}`];if(X.length>0)$.push(X.toString());return`${Y} (${$.join(": ")})`}function T7(Y,J,X){if(!Y.ok)return Y;if(!Y.body)return X?.onReadEnd?.(),Y;let $=Y.headers.get("content-type")?.includes("text/event-stream");if(!$&&!X?.onReadEnd)return Y;let Q=Y.body.getReader(),G=new TextDecoder,z="",K=!1,U=!1,H=!1,V=(F)=>{z+=F;for(;;){let Z=/\r?\n\r?\n/.exec(z);if(!Z||Z.index===void 0)break;let N=z.slice(0,Z.index);if(z=z.slice(Z.index+Z[0].length),H){H=!1;continue}let j=N.split(/\r?\n/).filter((P)=>P.startsWith("data:")).map((P)=>P.slice(5).trimStart()).join(`
59
+ `);if(!j||j==="[DONE]")continue;try{let P=JSON.parse(j);if(P.type==="codex.rate_limits")X?.onRateLimits?.(P);if(P.type==="response.completed"&&!K)K=!0,A7(P.response,"http","opencode1");if(P.type==="response.failed"||P.type==="response.incomplete"||P.type==="error")U=!0}catch{U=!0}}if(z.length>1048576)z=z.slice(-1),H=!0,U=!0};return new Response(new ReadableStream({async pull(F){try{let Z=await Q.read();if(Z.done){if($)V(G.decode()),J(K&&!U);if(!U&&(!$||!z.trim()))X?.onReadEnd?.();F.close()}else{if($)V(G.decode(Z.value,{stream:!0}));F.enqueue(Z.value)}}catch(Z){F.error(Z)}},cancel(F){return Q.cancel(F)}}),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function Pz(Y){let J=Y.get("retry-after");if(J===null)return;let X=J.trim()?Number(J):NaN;return Number.isFinite(X)&&X>=0?X*1000:void 0}function Kj(Y,J,X){let $;try{$=JSON.parse(Y)}catch{}let Q=u1({...$&&typeof $==="object"?$:{},status:429},X)??{window:OY};if(Q.resetAt!==void 0)return{parsed:Q,retryAfterMs:Math.max(0,Q.resetAt-X),resetSource:"provider"};let G=Pz(J);if(G===void 0)return{parsed:Q};return{parsed:{...Q,resetAt:X+G},retryAfterMs:G,resetSource:"retry-after"}}var qz=new WeakMap;function Ez(Y){return qz.get(Y)}function Az(Y){let J=!1;return{observe(X){return J=Y.classifyLimits&&X.status===429,T7(X,($)=>{if($)Y.onComplete()},{onReadEnd:Y.onCleanRead,onRateLimits:($)=>{Y.onQuota(DY($),$)}})},async finish(X){if(J&&X.status===429){let $=await X.clone().text().catch(()=>""),Q=Date.now(),G=Kj($,X.headers,Q);qz.set(X,{body:$,limit:G,observedAt:Q}),Y.onLimit?.(G,Q)}return X}}}var Mz=60000,R7=900000,Uj={set(Y,J){let X=setTimeout(Y,J);return X.unref?.(),X},clear(Y){clearTimeout(Y)}};function Hj(Y){return Y.status==="completed"||Y.status==="already-migrated"||Y.status==="nothing-to-import"||Y.status==="ambiguous"}function Tz(Y){return Y.status==="deferred"||Y.status==="retry"||Y.status==="error"}function Rz(Y){let J=Y.log??U0("pool-migration"),X=Y.timers??Uj,$=Y.random??Math.random,Q=Y.migrate??PY,G=Y.adopt??qY,z=Y.fence??(()=>H4({currentVersion:Y.version})),K=!1,U=new AbortController,H=!1,V=!1,F=0,Z,N=Promise.resolve(),j,P,v,y=!1;function I(){if(y)return;y=!0,J.warn(W4,{reason:"placeholder-without-main"})}let A=()=>({paths:Y.paths(),slot:Y.slot,log:J,...Y.runDeps,signal:U.signal});function q(f){let V0=N.then(f).catch((b)=>{J.warn("account pool background run failed",{error:b instanceof Error?b.message:String(b)})});return N=V0,V0}function C(f){if(H)return;if(Z!==void 0)X.clear(Z);Z=X.set(()=>{Z=void 0,q(z0)},f)}function m(){let f=Math.min(Mz*2**Math.min(F,10),R7);return F++,r(f)}let r=(f)=>Math.round(f*(1-0.2*$()));async function l(){if(!await Y.paused?.())return!1;return C(r(Mz)),!0}async function R0(){if(H||await l()||H)return;let f;try{f=await Q({...A(),fence:z})}catch(V0){J.warn("account pool migration failed; it will be tried again",{error:V0 instanceof Error?V0.message:String(V0)}),C(m());return}if(f.status==="refused"){if(f.reason==="placeholder-without-main")I();C(r(R7));return}if(Hj(f)){if(V=!0,F=0,f.status==="completed")J.info("account pool migration completed",{rowId:f.rowId});await B0();return}if(Tz(f)){if(f.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:f});C(m())}}async function B0(){if(H||await l()||H)return;let f;try{let V0=await z();if(H)return;if(!V0.open){let b=JSON.stringify(V0.blockers);if(b!==v)v=b,J.info("host login adoption waits for older plugin versions",{blockers:V0.blockers});C(m());return}f=await G(A())}catch(V0){J.warn("adopting the host login into the account pool failed",{error:V0 instanceof Error?V0.message:String(V0)}),C(m());return}if(f.status==="not-migrated")return;if(f.status==="slot-read-only")return;if(V=!0,f.status==="completed")J.info("host login adopted into the account pool",{rowId:f.rowId,operation:f.operation});if(Tz(f)){J.warn("host login adoption will be tried again",{outcome:f}),C(m());return}if(F=0,V)C(r(R7))}async function z0(){if(H)return;if(V)await B0();else await R0()}function A0(){if(j)return j;let f=q(async()=>{if(j=void 0,!H)if(V)await B0();else await R0()});return j=f,f}return{start(){if(K||H)return;K=!0,q(R0)},requestAdoption:A0,noticePlaceholderWithoutMain:I,noticeRealSlot(f){if(!V||H||f===P)return;P=f,A0()},dispose(){if(H=!0,U.abort(),Z!==void 0)X.clear(Z);Z=void 0},idle:async()=>{for(;;){let f=N;if(await f,f===N)return}},migrated:()=>V}}var i1={"missing-main":"Request refused locally: this setup has no main login in its account store. Sign in with opencode auth login.","no-accounts":"Request refused locally: no eligible account is configured. Sign in with opencode auth login.",unusable:"Request refused locally: no usable account credential. Sign in with opencode auth login.",...xz};function x7(Y){return Y!==void 0&&kz.includes(Y)}function h7(Y){try{let J=JSON.parse(Y.body??"{}");return typeof J.model==="string"?J.model:""}catch{return""}}function v7(Y){return Y.sessionId&&(Y.requestKind===void 0?Y.sessionId:JSON.stringify([Y.sessionId,Y.requestKind]))}function y7(Y,J,X,$){let Q=C8(Y,J);return J.flatMap((G)=>{let z=Y.limitPolicy?.accountKey(G.id);if(!z)return[];let K=$?.id===G.id?$.reading:U6(G.quota),U=pz(X&&e0(X.account,z)?X:void 0,K,Q.now),H=Q.rateLimitMarks.get(G.id),V=Q.refreshBackoff.get(G.id),F=[...H&&H>Q.now?[{kind:"hard",until:H}]:[],...V&&V>Q.now?[{kind:"cooldown",until:V}]:[]],Z=c6(K,Y.storage,G.id===b6?void 0:G.id,Q.now)&&!!(K?.primary||K?.secondary)&&!Sz(MY(p1(G.quota)?G.quota:void 0),Q.now)&&(!G.row||!!Y.source.usableToken(G.row));return[{account:z,admitted:Z,placementEligible:Z,ready:Z&&!F.length&&!U.length,blockers:F,confirmedBlockers:U}]})}function g7(Y,J){let X=Y.now();return{phase:"after-limit",host:"opencode1",hostPhase:"request",now:X,clockNow:X,sessionId:Y.sessionId??"",requestScope:{kind:"pool"},history:Iz({requestId:Y.sessionId??"request",originalUrl:"https://api.openai.com/v1/responses",clockNow:X}),delivery:{owned:!0,attributable:!0,replayable:Y.replayable},candidates:J}}function f7(Y,J,X=!1){let $=nz({decision:J,now:Y.now(),host:"opencode1",maxSameAccountWait:X?void 0:Y.storage?.routing?.maxSameAccountWait});if($.kind!=="http")throw Error("Expected an OC1 HTTP quota refusal");return new Response($.body,{status:$.status,headers:$.headers})}async function oz(Y,J,X,$,Q,G){let z=Y.limitPolicy;if(!z||!Y.replayable||$==="ordered"&&!S7(Y.storage).includes(X.status)||$==="sticky"&&![401,403,429].includes(X.status))return{confirmed:!1};let K=G;if(!K)return{confirmed:!1};let U=EY(Y),H=U.find((q)=>q.id===J.id),V={...U6(H?.quota),...l1(X.headers)},F=Ez(X),Z=X.status===429?uz({account:K,status:X.status,headers:F?void 0:X.headers,body:F?.body??await X.clone().text(),now:F?.observedAt??Y.now(),reading:V}):void 0,N=Z&&F?.limit.retryAfterMs!==void 0?{...Z,retryAfterMs:F.limit.retryAfterMs,...F.limit.resetSource==="retry-after"?{retryAfterSource:"retry-after"}:{}}:Z,j=y7(Y,U,N,{id:J.id,reading:V}),P=j.find((q)=>e0(q.account,K)),v=Q&&j.find((q)=>q.account.accountId===Q),y=z.currentAccountKey(),I=(z.decide??k7)({...g7(Y,j),attempted:K,status:X.status,signal:N,affinity:$==="sticky"?"sticky":"none",...v?{selection:{account:v.account,pin:"preserve"}}:{},hold:P&&Y.sessionId&&!Y.suppressHold&&y&&e0(y,P.account)?b7({candidate:P,status:X.status,activity:z.activity(),now:Y.now(),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait}):void 0},{mode:$,fallbackOn:Y.storage?.fallbackOn}),A=v7(Y);if(I?.action==="hold"&&Y.sessionId&&A){if(z.pending.set(A,{sessionId:Y.sessionId,accountKey:K,model:h7(Y),target:I.target,checkpoint:I.checkpoint,decidedAt:Y.now(),decision:I}),z.pending.size>256){let q=z.pending.keys().next().value;if(q)z.pending.delete(q)}return X.body?.cancel().catch(()=>{}),{hold:f7(Y,I),confirmed:!0}}return{confirmed:!!P?.confirmedBlockers?.length&&X.status===429}}async function Bj(Y,J){let{limitPolicy:X,sessionId:$}=Y,Q=v7(Y),G=Q&&X?.pending.get(Q);if(!G||!X||!$||!Q)return;let z=y7(Y,J),K=z.find((j)=>e0(j.account,G.accountKey)),U=new Map(G.checkpoint.blockers.map((j)=>[j.window,{...j,confirmed:!0,confirmedByReading:!1,observedAt:G.decidedAt,provenance:"provider"}]));for(let j of K?.confirmedBlockers??[])U.set(j.window,j);let H=K&&b7({candidate:{...K,confirmedBlockers:[...U.values()]},activity:X.activity(),now:Y.now(),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait});X.pending.delete(Q);let V=X.currentAccountKey();if(!Y.replayable||h7(Y)!==G.model||!V||!e0(V,G.accountKey)||!K?.admitted||!H||H.maxWaitMs<=0||Y.now()>H.cacheExpiresAt||G.target>Math.min(H.cacheExpiresAt,Y.now()+H.maxWaitMs))return;if(Y.now()<G.target)return X.pending.set(Q,G),{response:f7(Y,{...G.decision,delayMs:G.target-Y.now(),retryAfterMs:G.target-Y.now()}),servedId:K.account.accountId};let F=(X.decide??k7)({...g7(Y,z.map((j)=>j===K?{...j,confirmedBlockers:[...U.values()]}:j)),phase:"pre-send",attempted:K.account,hold:H,wake:{target:G.target,checkpoint:G.checkpoint,kind:"hold"}},{mode:"sticky"});if(F?.action!=="retain"||F.reason!=="wait-elapsed")return;let Z=J.find((j)=>j.id===K.account.accountId),N=Z&&await AY(Y,Z);return N&&Z?{response:N,servedId:Z.id}:void 0}function Vj(Y,J,X){if(!Y.limitPolicy||!["quota-exhausted","killswitch","mid-stream-rate-limit"].includes(X.reason))return;let $=Y.limitPolicy,Q=Y.now(),G=$.owner(),z=J.flatMap((U)=>{let H=$.accountKey(U.id);if(!H)return[];return[{account:H,reading:U6(U.quota),floors:d1(Y.storage)?U1(Y.storage,U.id===b6?void 0:U.id):void 0,marks:G?.snapshot()?.marks.filter((V)=>V.key.window==="account"&&V.key.scope.kind==="pool"&&e0(V.key.account,H)).flatMap((V)=>V.entries.map((F)=>({until:F.until,evidenceAt:F.evidenceAt})))}]}),K=dz({accounts:z,now:Q,effectiveModel:h7(Y),maxSameAccountWait:Y.storage?.routing?.maxSameAccountWait,waitForReset:lz(Y.waitForReset,Y.primary,Y.sessionId),activity:$.activity(),currentAccountKey:$.currentAccountKey(),provenance:G?.provenance});return f7(Y,iz({...g7(Y,y7(Y,J)),phase:"pre-send"},z.length?K:{...K,messageKey:X.reason==="killswitch"?"killswitch":X.reason==="quota-exhausted"?"quota":"timed-mark"}),K.scan?.waitForReset!==void 0)}function Nj(Y,J,X,$=new Set,Q=_6()){let G=M6(J,Q);return Y.filter((z)=>{if(!z.enabled||!z.candidate||z.type!=="oauth")return!1;if(z.credential?.type!=="oauth")return!1;if(c0(z.credential))return!1;if(z.identity!==void 0&&$.has(z.identity))return!1;if(z.id===b6)return!0;if(bz(J,{accountId:z.identity}))return!1;return I7(U6(z.quota),G,X)})}function EY(Y){let J=Y.vault;return[...(J?[]:Nj(Y.source.peek().rows,Y.storage,Y.now(),void 0,Y.configPath)).map(($)=>({id:$.id,kind:"oauth",...$.identity!==void 0?{identity:$.identity}:{},...$.quota!==void 0?{quota:$.quota}:{},row:$})),...(J?.routes()??[]).filter(($)=>I7(U6($.quota),Y.storage,Y.now())).map(($)=>({id:$.id,kind:$.kind,...$.identity!==void 0?{identity:$.identity}:{},...$.quota!==void 0?{quota:$.quota}:{}}))]}function Lj(Y){return Y.flatMap((J)=>J.row?[J.row]:[])}function C8(Y,J){let X=Y.now(),$=w8(J,Y.storage,X),Q=J.map((U)=>({id:U.id,kind:U.kind,...p1(U.quota)?{quota:U.quota}:{}})),G=Lj(J),z=new Set(J.filter((U)=>!U.row).map((U)=>U.id)),K=Y.rateLimitMarks();for(let[U,H]of Y.vault?.rateLimitMarks?.()??[])if(z.has(U)&&H>X)K.set(U,H);return{rows:Q,now:X,rateLimitMarks:K,refreshBackoff:Y.source.refreshBackoffFor(G),killswitch:$,requestPull:(U)=>z.has(U)?Y.vault?.requestReading(U):Y.source.requestReading(U)}}function Cz(Y){let J=Y.find((X)=>X.id===b6);return{main:J?U6(J.quota):void 0,fallbacks:Y.filter((X)=>X.id!==b6).map((X)=>{let $=U6(X.quota);return{accountId:X.id,...$?{quota:$}:{}}})}}async function AY(Y,J){if(J.row){let X=Y.source.usableToken(J.row);if(!X)return;let $=await Y.send(J,X);return Y.recordQuota($,J,X),$}return Y.vault?.send(J.id,async(X,$)=>{let Q=await Y.send(J,X,$);return Y.recordQuota(Q,J,X,$),Q})}async function rz(Y){let J=Y.configPath??_6(),X=M6(Y.storage,J);if(Y={...Y,storage:X,mode:y6(J)==="shared"?X.routing?.mode??"main-first":Y.mode},Y.vault)await Y.vault.awaitRoster();else await Y.source.current(),await Y.source.prepareTokens(Y.source.peek().rows,Y.storage);let $=EY(Y),Q=Y.replayable===!1&&$.some((H)=>H.id===b6)?$.filter((H)=>H.id===b6):$,G=yz(C8(Y,Q));if(G)await G,$=EY(Y);let z=v7(Y),K=z&&Y.limitPolicy?.pending.has(z),U=await Bj(Y,$);if(U)return U;if(K)Y={...Y,suppressHold:!0};if(Y.mode==="sticky-balanced"&&Y.sessionId&&Y.replayable&&Y.body!==void 0){let H=await Zj(Y,$,Y.sessionId,Y.body);if(H)return H;return wz(Y,$)}return wz(Y,$)}async function wz(Y,J){let X=vz(Y.mode),$=C8(Y,J),Q=gz({...$,placement:X,mainId:Y.vault?Y.mode==="sticky-balanced"?null:hz(Y.vault.routes()):void 0,replayable:Y.replayable});if(Q.kind==="block")return Y.log.debug("pool admission blocked the request",{pid:process.pid,reason:Q.block.reason}),{response:Vj(Y,J,Q.block)??Y.blocked(Q.block,Cz(J),Y.vault?J.length===0?Y.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:b6};if(Q.lastPath)Y.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:Q.order});let G=new Map(J.map((Z)=>[Z.id,Z])),z=Q.order,K=S7(Y.storage),U=[],H=new Set,V,F=!1;for(;;){let Z=C7(z.filter((I)=>!H.has(I)),U,K),N=Z===void 0?void 0:G.get(Z);if(!N)break;let j=Y.limitPolicy?.accountKey(N.id),P;try{P=await AY(Y,N)}catch(I){if(Y.isAbort(I)||!V||Y.mode==="fallback-first")throw I;return Y.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:N.id}),V}if(!P){if(!N.row)F=!0;H.add(N.id);continue}V?.response.body?.cancel().catch(()=>{}),V={response:P,servedId:N.id},U.push({id:N.id,status:P.status});let v=C7(z.filter((I)=>!H.has(I)),U,K),y=await oz(Y,N,P,"ordered",v,j);if(y.hold)return{response:y.hold,servedId:N.id}}if(V)return sz(Y,$,V.servedId),V;return{response:Y.blocked({reason:"no-credential"},Cz(J),F?"vault-refused":Y.vault?"vault-empty":"unusable"),servedId:b6}}async function Zj(Y,J,X,$){let Q=Buffer.byteLength($,"utf8"),G=new Map(J.map((A)=>[A.id,A])),z=C8(Y,J),K=w7(z),U={requestBytes:Q,reservePercent:(A)=>U1(Y.storage,A===b6?void 0:A),resetCredits:Y.resetCredits,onEmptyWeightedSet:()=>{Y.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},H=(A,q)=>(C,m)=>{let r=new Set(C);return Y.placePin({sessionId:X,requestBytes:Q,now:A.now,validPinnedAccountIds:A.rows.map((l)=>l.id).filter((l)=>!q.excluded.has(l)),excludeAccountIds:C,quotaCheckedAtByAccount:Object.fromEntries(A.rows.map((l)=>[l.id,q.projections.get(l.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((l)=>[l.id,l.identity])),select:(l)=>fz(A,U,r,l),persist:m})},V=H(z,K),F=V([],!0);if(!F)return;let Z=F.accountId,N=(A)=>{let q=V([Z],!0);if(!q)return!1;return Y.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:Z,toAccountId:q.accountId,reason:A}),Z=q.accountId,!0},j=mz(z,U,Z);if(j.kind==="none")return;if(j.kind==="move"){if(!N(j.reason)&&j.reason==="killswitch")return}else if(j.kind==="detour"){let A=V([Z],!1);if(!A)return;Y.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:Z,servedAccountId:A.accountId}),Z=A.accountId}let P=G.get(Z);if(!P)return;let v=Y.limitPolicy?.accountKey(P.id),y=await AY(Y,P);if(!y)return;let I=await oz(Y,P,y,"sticky",void 0,v);if(I.hold)return{response:I.hold,servedId:P.id};if(y.status===401||y.status===403||y.status===429){let A=EY(Y);z=C8(Y,A),K=w7(z),V=H(z,K);let q=cz(z,K,Z,y.status);if(q.action==="migrate"||I.confirmed){let C=Z;if(N(I.confirmed?"exhausted":q.reason)&&Z!==C){let m=A.find((l)=>l.id===Z),r=m?await AY(Y,m):void 0;if(m&&r){let l=y;y=r,l.body?.cancel().catch(()=>{}),P=m}else Z=C}}}return sz(Y,z,P.id),{response:y,servedId:P.id}}function sz(Y,J,X){let $=Y.log.info;Y.creditsServing?.served(J,X,$?{info:(Q,G)=>$.call(Y.log,Q,G)}:void 0)}var jj=new Map([["needs_reauth","needs sign-in"],["retired","turned off in vault"],["corrupt","unavailable"]]);function Fj(Y){if(!p1(Y))return;let J=Y.budget;if(J?.kind!=="reading")return;let{kind:X,checkedAt:$,...Q}=J;return Q}function m7(Y,J){let X=U6(Y),$=Fj(Y),Q=p1(Y)?Y.credits:void 0;if(!X&&!$&&!Q)return null;let G=p1(Y)?MY(Y).checkedAt:void 0;return{...G!==void 0?{checkedAt:G}:{},...X?.primary?{primary:X.primary}:{},...X?.secondary?{secondary:X.secondary}:{},...$?{spendControl:$}:{},...J!==void 0?{resetCreditsAvailable:J}:{},...Q?{credits:{...Q}}:{}}}function tz(Y,J,X,$){let Q=Y??[],G=w8(Q.map((z)=>({id:z.routeId,quota:z.quota})),{version:1,accounts:[],...X},$);return{main:{quota:null,killed:!1},fallbacks:[],vaultDiscovered:Y!==void 0,vaultAccounts:Q.map((z)=>{let K=z.quota?.counters?.resetCredits?.value;return{id:z.routeId,credentialId:z.credentialId,label:az(z),...z.accountIdentity!==void 0?{accountId:z.accountIdentity}:{},quota:m7(z.quota,K),killed:G.get(z.routeId)===!1,enabled:z.enabled,routable:J.has(z.routeId),...z.state!=="active"||z.stale||z.enabled&&!J.has(z.routeId)?{vaultState:jj.get(z.state)??"unavailable"}:{},...K!==void 0?{resetCredits:K}:{}}}),route:X?.routing?.mode??"main-first",lastUpdated:$}}function ez(Y,J,X,$=()=>{return}){let Q=w8(Y,{version:1,accounts:[],...J},X),G=Y.find((K)=>K.id===g6),z=G?$(G.id):void 0;return{main:{quota:G?m7(G.quota,z):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:Q.get(g6)===!1,...z!==void 0?{resetCredits:z}:{}},fallbacks:Y.filter((K)=>K.id!==g6&&K.enabled).map((K)=>{let U=$(K.id);return{id:K.id,label:K.label,...K.identity!==void 0?{accountId:K.identity}:{},quota:m7(K.quota,U),killed:Q.get(K.id)===!1,enabled:!0,...U!==void 0?{resetCredits:U}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:X,accountPool:!0}}async function XW(Y){let J=Y.log??U0("settings"),X=YW({host:"opencode",paths:Y.paths??x1(),logger:J}),$=await G$({install:X,log:J,record:(z)=>JW({configPath:X.configIdentity,settings:z,version:Y.version})});if($.decision!=="shared")return{authority:$};let Q=J4(T0,{file:$.install.target,log:J,separateInstall:!1,createMissing:!0}),G=await N$({handle:Q,file:$.install.target,host:"opencode"});return c7(G.get("log_level"),"startup"),G.onChange(()=>{c7(G.get("log_level"),"refresh")}),{authority:$,handle:Q,snapshot:G}}import{resolve as TY}from"node:path";import{resolveClaustrumConnectionPath as $W}from"@cortexkit/claustrum-client";var QW=U0("vault"),_j=60000,Dj=240000,KW=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),UW=globalThis,RY=UW[KW]??new Map;UW[KW]=RY;function Oj(Y){if(!Y||typeof Y!=="object")return!1;let J=Y;return J.protocol===1&&J.holders instanceof Set&&typeof J.firstRoster?.resolve==="function"&&J.firstRoster.promise instanceof Promise&&typeof J.started==="boolean"&&typeof J.vault?.awaitRequestRoster==="function"&&typeof J.vault?.grantReach==="function"&&typeof J.vault?.reorder==="function"}function HW(Y,J){let X=Boolean(Y.connectScoped||Y.connectEnrollment),$=TY(Y.stateDir),Q=H9()?"host":TY((Y.connectionFile??$W)()),G=JSON.stringify([GW,Y.host,$,Q,TY(J.configPath),TY(J.statePath)]),z={reservedRouteIds:Y.reservedRouteIds??(()=>[])},K=RY,U=RY.get(G);if(!X&&U!==void 0&&!Oj(U)){let N=RY;N.compatibleV1??=new Map,K=N.compatibleV1}let H=X?void 0:K.get(G);if(!H){let N=new Set;if(H={protocol:1,vault:new zW({...Y,stateDir:$,connectionFile:()=>Q==="host"?(Y.connectionFile??$W)():Q,reservedRouteIds:()=>new Set([...N].flatMap((P)=>[...P.reservedRouteIds()])),afterDisconnect:async()=>{await Y.afterDisconnect?.();try{await WW($)}catch(P){QW.warn("could not remove the old vault enrollment state",{error:P instanceof Error?P.message:String(P)})}}}),holders:N,firstRoster:Promise.withResolvers(),started:!1},!X)K.set(G,H)}H.holders.add(z);let V=H,F=!1,Z;return{vault:V.vault,firstRoster:V.firstRoster.promise,start(){if(F||V.started)return;V.started=!0;let N=async()=>{try{if(V.holders.size&&await V.vault.authority()!=="local")await V.vault.pollStale(Dj)}catch(P){QW.warn("vault background quota poll failed",{error:P instanceof Error?P.message:String(P)})}};V.vault.start(),V.vault.firstRoster().finally(()=>{V.firstRoster.resolve(),N()}),V.quotaPoll=setInterval(N,_j),V.quotaPoll.unref?.()},release(){if(F)return Z;if(F=!0,V.holders.delete(z),V.holders.size!==0)return;if(V.quotaPoll)clearInterval(V.quotaPoll);if(Z=typeof V.vault.dispose==="function"?V.vault.dispose():Promise.resolve(V.vault.close()),V.firstRoster.resolve(),!X&&K.get(G)===V)K.delete(G);return Z}}}var ZW=900000,Pj=0.016666666666666666,BW=0.000001;function p7(Y,J){for(let X of[Y?.primary?.checkedAt,Y?.checkedAt,J])if(typeof X==="number"&&Number.isFinite(X))return X;return}function l7(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let J=p7(Y.quota,Y.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||Y.now-J>ZW)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let X=u7(Y.quota).sort((Q,G)=>{let z=Q.windowMs,K=G.windowMs,U=typeof z==="number"&&Number.isFinite(z),H=typeof K==="number"&&Number.isFinite(K);if(U!==H)return U?-1:1;if(U&&H)return K-z;return 0});for(let{key:Q,window:G}of X)if(Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}};let $=LW(Y.quota,Y.now);if($)return{action:"migrate",reason:"exhausted",resetsAt:$.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 VW(Y,J,X){let $=Math.max(0,Y.remainingPercent-J);if($<=0)return 0;if(!Y.resetsAt)return $;let Q=Date.parse(Y.resetsAt);if(!Number.isFinite(Q)||Q<=X)return $;let G=Math.max((Q-X)/3600000,Pj);return $/G}function NW(Y,J){if(Y<J)return-1;if(Y>J)return 1;return 0}function qj(Y,J){if(!Y.quota)return;let X=p7(Y.quota,Y.quotaCheckedAt);if(X===void 0||J-X>ZW)return;let $=u7(Y.quota).map(({key:K,window:U})=>{return VW(U,Y.reservePercent[K]??0,J)}),Q=Y.quota.spendControl,G=Q?.remainingPercent;if(typeof G==="number"&&Number.isFinite(G))$.push(VW({remainingPercent:G,resetsAt:Q?.resetsAt},0,J));let z=$.length>0?Math.min(...$):0;return z>0?{candidate:Y,quotaCheckedAt:X,weight:z}:void 0}function jW(Y){let J=Y.candidates.filter((Q)=>Q.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(J.length===0)return;let X=J.map((Q)=>qj(Q,Y.now)).filter((Q)=>Q!==void 0);if(X.length>0){X.sort((G,z)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,BW),U=((Y.pendingBytes.get(z.candidate.accountId)??0)+Y.requestBytes)/Math.max(z.weight,BW);return K-U||G.candidate.configuredOrder-z.candidate.configuredOrder||NW(G.candidate.accountId,z.candidate.accountId)});let Q=X[0];if(Q)return{accountId:Q.candidate.accountId,quotaCheckedAt:Q.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let $=[...J].sort((Q,G)=>{let z=(Q.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-z||Q.configuredOrder-G.configuredOrder||NW(Q.accountId,G.accountId)})[0];if(!$)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:$.accountId,quotaCheckedAt:p7($.quota,$.quotaCheckedAt),source:"mode-fallback"}}import{readFile as Ej}from"node:fs/promises";import{homedir as Aj}from"node:os";import{join as FW}from"node:path";var Mj="https://models.dev/api.json",Tj="OPENCODE_OPENAI_AUTH_MODELS_CACHE",Rj="OPENCODE_MODELS_PATH",Cj="OPENCODE_DISABLE_MODELS_FETCH",wj=1e4,Sj=300000;function E1(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function _W(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function d7(Y){let{input:J,output:X}=Y;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;let $=_W(Y.cache_read),Q=_W(Y.cache_write);if($===null||Q===null)return null;return{input:J,output:X,cache:{read:$,write:Q}}}function Ij(Y){let J=E1(Y);if(!J)return null;let X=d7(J);if(!X)return null;let $=X;if(Array.isArray(J.tiers)){let z=[];for(let K of J.tiers){let U=E1(K);if(!U)continue;let H=E1(U.tier),V=H?.size;if(H?.type!=="context")continue;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)continue;let F=d7(U);if(!F)continue;z.push({...F,tier:{type:"context",size:V}})}if(z.length>0)$.tiers=z}let Q=E1(J.context_over_200k),G=Q?d7(Q):null;if(G)$.experimentalOver200K=G;return $}function DW(Y){let J=E1(Y),X=E1(J?.openai),$=E1(X?.models);if(!$)return null;let Q={};for(let[G,z]of Object.entries($)){let K=E1(z),U=Ij(K?.cost);if(U)Q[G]=U}return Object.keys(Q).length>0?Q:null}function bj(){let Y=process.env[Tj]?.trim();if(Y)return Y;let J=process.env[Rj]?.trim();if(J)return J;let X=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||FW(Aj(),".cache");return FW(X,"opencode","models.json")}function kj(){let Y=process.env[Cj]?.toLowerCase();return Y==="true"||Y==="1"}async function xj(){try{let Y=DW(JSON.parse(await Ej(bj(),"utf8")));if(Y)return Y}catch{}if(kj())return null;try{let Y=await fetch(Mj,{signal:AbortSignal.timeout(wj)});if(!Y.ok)return null;return DW(await Y.json())}catch{return null}}var A4;function OW(){let Y=Date.now();if(A4&&A4.expiresAt>Y)return A4.promise;let J={expiresAt:Y+Sj,promise:xj()};return A4=J,J.promise.then((X)=>{if(X===null&&A4===J)A4=void 0}),J.promise}function M4(Y){return typeof Y==="object"&&Y!==null}function hj(Y){if(Array.isArray(Y))return Y;if(M4(Y)&&Array.isArray(Y.data))return Y.data;return[]}function vj(Y){if(!M4(Y)||!M4(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function PW(Y){if(!M4(Y)||!M4(Y.info))return null;let J=Y.info,X=M4(J.model)?J.model:void 0,$=typeof J.agent==="string"?J.agent:void 0,Q=typeof X?.providerID==="string"?X.providerID:typeof J.providerID==="string"?J.providerID:void 0,G=typeof X?.modelID==="string"?X.modelID:typeof J.modelID==="string"?J.modelID:void 0,z=typeof X?.variant==="string"?X.variant:typeof J.variant==="string"?J.variant:void 0;if(!$&&(!Q||!G)&&!z)return null;let K={};if($)K.agent=$;if(Q&&G)K.model={providerID:Q,modelID:G};if(z)K.variant=z;return K}function qW(Y,J){return{agent:Y.agent??J.agent,model:Y.model??J.model,variant:Y.variant??J.variant}}function EW(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function AW(Y,J){if(!Y||!J)return null;let X=Y;if(typeof X.session?.messages!=="function")return null;let $=[];try{$=hj(await Promise.resolve(X.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if($.length===0)return null;let Q={};for(let G=$.length-1;G>=0;G--){if(vj($[G])!=="assistant")continue;let z=PW($[G]);if(!z)continue;if(Q=qW(Q,z),EW(Q))return Q}for(let G=$.length-1;G>=0;G--){let z=PW($[G]);if(!z)continue;if(Q=qW(Q,z),EW(Q))return Q}if(!Q.agent&&!Q.model&&!Q.variant)return null;return Q}class S8 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 v0 extends Error{code;constructor(Y,J){super(J);this.name="ResetTargetResolutionError",this.code=Y}}function i7(Y,J,X,$,Q){let G=(M6(X,Q).refresh?.refreshBeforeExpiryMinutes??240)*60000;return!Y||!J||J-$<=G}function MW(Y,J){let X=Y==="main",$=J.row,Q=()=>new v0("token_unavailable",X?"Main OpenAI account has no usable access token.":`Fallback account ${Y} has no usable access token.`);if(!$){if(X)throw Q();throw new v0("unknown_account",`Fallback account ${Y} was not found.`)}if(!$.enabled)throw new v0("disabled_account",`${X?"Main":"Fallback"} account ${Y} is disabled.`);if($.type!=="oauth")throw new v0("non_oauth_account",`${X?"Main":"Fallback"} account ${Y} is not an OAuth account.`);if(!J.token)throw Q();let G=R6(J.token);return{accountKey:Y,label:X?"Main account":$.label??Y,accessToken:J.token,chatgptAccountId:$.identity??(G?C6(G):void 0)}}function n7(Y){async function J(){let X=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),$=I1(X);if(!X||!$||c0($))throw new v0("token_unavailable","Main OpenAI account has no usable access token.");let Q=$;if(i7(Q.access,Q.expires,X,Y.now(),Y.accountStoragePath))Q=await(Y.refreshPoolMainRow??Y.refreshFallbackAccount)(Q,X);if(!Q.access)throw new v0("token_unavailable","Main OpenAI account has no usable access token.");let G=R6(Q.access);return{accountKey:"main",label:"Main account",accessToken:Q.access,chatgptAccountId:Q.accountId??(G?C6(G):void 0)}}return async(X)=>{let $=await Y.poolAccess?.(X);if($)return MW(X,$);if(X==="main"){let V=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),F=await Y.getAuth();if(t0(F))return J();if(F.type!=="oauth")throw new v0("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(i7(F.access,F.expires,V,Y.now(),Y.accountStoragePath))try{F={type:"oauth",...await Y.refreshMainWithLease()}}catch(P){if(P instanceof V1)return J();throw P}if(!F.access)throw new v0("token_unavailable","Main OpenAI account has no usable access token.");let Z=R6(F.access),N=Z?C6(Z):void 0,j=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath});return{accountKey:X,label:"Main account",accessToken:F.access,chatgptAccountId:N??j?.mainAccountId}}let Q=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),G=Q?.accounts.find((V)=>V.id===X);if(!Q||!G)throw new v0("unknown_account",`Fallback account ${X} was not found.`);if(G.enabled===!1)throw new v0("disabled_account",`Fallback account ${X} is disabled.`);if(!n0(G))throw new v0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);let z=()=>new v0("token_unavailable",`Fallback account ${X} has no usable access token.`);if(c0(G))throw z();let K=G;if(i7(K.access,K.expires,Q,Y.now(),Y.accountStoragePath))K=await Y.refreshFallbackAccount(K,Q);if(!K.access)throw z();let U=await Y.loadAccounts({configPath:Y.accountStoragePath,statePath:Y.accountStatePath}),H=U?.accounts.find((V)=>V.id===X);if(!U||!H)throw new v0("unknown_account",`Fallback account ${X} was not found.`);if(H.enabled===!1)throw new v0("disabled_account",`Fallback account ${X} is disabled.`);if(!n0(H))throw new v0("non_oauth_account",`Fallback account ${X} is not an OAuth account.`);return{accountKey:X,label:K.label??X,accessToken:K.access,chatgptAccountId:H.accountId}}}function o7(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function CY(Y){return Y instanceof S8}var yj=U0("rpc"),wW="__openaiAuthRpcServers";async function SW(Y){let J=await TW({...Y,isManagedDir:CW,log:yj,drain:(X,$)=>Y.drain(X,$),apply:async(X)=>await Y.apply(X)});try{return await RW(Y.dir,{port:J.port,token:J.token,pid:process.pid},{secureDir:Y.secureDir}),J}catch(X){throw await J.stop(),X}}function r7(Y,J){return Y.find((X)=>X.enabled!==!1&&n0(X)&&(X.id===J||X.accountId===J))}function SY(Y,J){if(!J)return Y;let X={...Y};for(let $ of["resetCreditsAvailable","resetCreditsApplicable"]){let Q=J[$];if(X[$]===void 0&&Q!==void 0)X[$]=Q}if(X.spendControl===void 0&&X.spendControlCleared!==!0&&J.spendControl!==void 0)X.spendControl=J.spendControl;if(X.credits===void 0&&J.credits!==void 0)X.credits=J.credits;return X}function wY(Y,J){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:J}}function IY(Y,J,X=Date.now(),$=J.mainAccountId){let Q=Y.getMain(),G=Q?.quota;return{main:{quota:G?{...G,checkedAt:Q.checkedAt,primary:wY(G.primary,Q.checkedAt),secondary:wY(G.secondary,Q.checkedAt)}:null,...typeof $==="string"?{mainAccountId:$}:{},killed:!c6(G,J,void 0,X),...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((z)=>z.enabled).map((z)=>{let K=Y.getFallback(z.id),U=K?.quota;return{id:z.id,label:z.label,accountId:K?.accountId??z.accountId,quota:U?{...U,checkedAt:K.checkedAt,primary:wY(U.primary,K.checkedAt),secondary:wY(U.secondary,K.checkedAt)}:null,killed:!c6(U,J,z.id,X),enabled:!0,...U?.resetCreditsAvailable!==void 0?{resetCredits:U.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:X}}function gj(Y,J,X,$=Date.now()){return{...IY(Y,J,$),activeId:X}}function bY(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}var u6={};cJ(u6,{withoutInternalHeaders:()=>rW,sanitizeHttpFallbackBody:()=>hW,orderCodexBody:()=>b8,hasWebSocketResponsesLiteMetadata:()=>xW,createWebSocketFetch:()=>lj,applyTurnId:()=>pW,advanceTurn:()=>t7,TITLE_HEADER:()=>a7,QUOTA_ACCOUNT_HEADER:()=>hY,OpenAIWebSocketPool:()=>u6,CODEX_BODY_KEY_ORDER:()=>kW});import{createHash as fj}from"node:crypto";var a7="x-opencode-title",hY="x-openai-auth-quota-account",s7=new Set([a7,m1,hY,"x-opencode-session"]),mj=15000,cj=300000,uj=3300000,IW="websocket_connection_limit_reached";function pj(Y){let J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"",X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",$=J?`acct:${J}`:`tok:${X}`;return fj("sha256").update($).digest("hex").slice(0,12)}function lj(Y){let J=Y?.httpFetch??globalThis.fetch,X=new Map,$=Y?.connectTimeout??mj,Q=Y?.idleTimeout??cj,G=Y?.maxConnectionAge??uj,z=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,U=Y?.rawWebSocket??!1,H=Y?.onQuota,V=Y?.onRateLimitReached,F=setInterval(()=>P(),Math.min(Q,60000));if(typeof F==="object"&&"unref"in F&&typeof F.unref==="function")F.unref();function Z(I,A,q,C){if(!A||!q)return q;t7(I,bW(A),void 0,C);let m=new Headers(q.headers),r=m.get("x-codex-turn-metadata");if(!r)return q;let l=lW(r,I.turnID,I.turnStartedAt);if(!l)return q;return m.set("x-codex-turn-metadata",l),{...q,headers:m}}async function N(I,A,q){let C=I instanceof URL?I.toString():typeof I==="string"?I:I.url,m=p0.normalizeHeaders(A?.headers),r=typeof m[hY]==="string"?m[hY]:void 0,l=q?.kind==="auxiliary",R0=(t)=>{if(q?.kind!=="primary")return;let{turnID:_0,turnStartedAt:W0}=t??{};q.record(_0!==void 0&&W0!==void 0?{turnID:_0,turnStartedAt:W0}:void 0)},B0=async(t,_0,W0)=>{R0(W0);let E0=await J(t,_0);return Y?.onHttpResponse?.(E0,r)??E0},z0=rW(A),A0=vW(z0);if(A?.method!=="POST"||!new URL(C).pathname.endsWith("/responses"))return B0(I,A0);let f=(()=>{try{if(typeof A?.body!=="string")return;let t=JSON.parse(A.body);return typeof t==="object"&&t!==null?t:void 0}catch{return}})();if(!f?.stream)return B0(I,A0);if(m[a7]==="true")return B0(I,A0);let V0=m[m1]??m["x-session-affinity"]??m["session-id"],b=V0;if(!V0)return B0(I,A0);let Q1=p0.normalizeHeaders(z0?.headers),G1=pj(Q1),o1=`${V0}:${G1}:${l?`auxiliary:${q.agent}`:"conversation"}`,p6=V?(t,_0)=>V(t,r,_0):void 0,w=X.get(o1)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};X.set(o1,w);let N0=bW(f),c,F0=()=>l?B0(I,A0):B0(I,Z(w,f,A0,c),w);if(w.fallback||w.busy)return F0();w.busy=!0,w.lastUsedAt=Date.now();try{c=T4(w,N0);let t=p0.normalizeHeaders(z0?.headers),_0=typeof t.authorization==="string"&&t.authorization.startsWith("Bearer ")?t.authorization.slice(7):"",W0=typeof t["chatgpt-account-id"]==="string"?t["chatgpt-account-id"]:void 0,E0=H?(g,s)=>H(g,_0,r,W0,s):void 0,H6=!w.socket&&!w.continuation?ej(t):t;if(w.socket=await oj(w,Y?.url??C,H6,$,G,U,A?.signal),XF(w,N0,c))await rj(w,N0,Q,{signal:A?.signal??void 0,sessionID:b,url:Y?.url??C,headers:z0?.headers,onRateLimitReached:p6});let Q6=()=>{},C4=()=>{},y8=new Promise((g,s)=>{Q6=g,C4=s}),w4=JF(w,N0,c),S4=b8(l?w4:pW(w,w4,N0,c)),{turnID:pY,turnStartedAt:lY}=w,dY=typeof S4.previous_response_id==="string";await q4({sessionID:b,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(S4),url:Y?.url??C,method:z0?.method,headers:z0?.headers}),R0({turnID:pY,turnStartedAt:lY});let I4=p0.streamResponsesWebSocket({socket:w.socket,body:S4,sessionID:b??void 0,idleTimeout:Q,signal:A?.signal??void 0,onQuota:E0,onRateLimitReached:p6,onFirstEvent:(g)=>Q6(g??!0),onComplete:(g,s)=>{Y?.onComplete?.(g,r);let X0=mW(g);c1({component:"ws-pool",event:"main_completed",sessionID:b,responseID:fW(g),usage:X0}),uW(w,N0,g,s,dY,c)},onTerminal:(g)=>{if(w.busy=!1,w.lastUsedAt=Date.now(),w.streamFailures=0,g.type!=="response.completed"&&g.type!=="response.done")w.continuation=void 0,$1(w)},onConnectionInvalid:(g)=>{if(w.busy=!1,w.lastUsedAt=Date.now(),p0.isOversizedFrame(g))w.fallback=!0;if(!w.fallback)j(w);w.continuation=void 0,$1(w),Q6(!1)},onAbort:(g)=>{w.busy=!1,w.lastUsedAt=Date.now(),w.streamFailures=0,w.continuation=void 0,$1(w),C4(g)},onRetryableTerminal:async(g)=>{let s=gW(g);if(!s)return;throw w.fallback=!0,s}}),k=await dj(y8,K);if(k!==!1){if(k===!0||k.status<200||k.status>599)return I4;return new Response(k.body,{status:k.status,headers:{"content-type":"application/json",...k.headers}})}if(!w.fallback)return ij(I4,F0);return F0()}catch(t){if(w.busy=!1,w.lastUsedAt=Date.now(),p0.isAbortError(t))throw w.streamFailures=0,w.continuation=void 0,$1(w),t;let _0=p0.parseRateLimitSignal(t);if(_0)p6?.(_0.window,_0.resetAt);if(p0.isUpgradeFailure(t)&&!U)w.fallback=!0;if(j(w),w.continuation=void 0,$1(w),w.fallback)return F0();return nj(new $6(t instanceof Error?t.message:String(t),{cause:t}))}}function j(I){if(I.streamFailures++,I.streamFailures>z)I.fallback=!0}function P(){let I=Date.now();for(let[A,q]of X){if(q.busy)continue;if(I-q.lastUsedAt<Q)continue;$1(q),X.delete(A)}}function v(){clearInterval(F);for(let I of X.values())$1(I);X.clear()}function y(I){let A=`${I}:`;for(let[q,C]of X){if(!q.startsWith(A))continue;$1(C),X.delete(q)}}return Object.assign(N,{close:v,remove:y})}function gW(Y){if(Y.type!=="error"||!Q0(Y.error)||Y.error.code!==IW)return;return Error(typeof Y.error.message==="string"?Y.error.message:IW)}async function dj(Y,J){if(J<=0)return!1;return new Promise((X,$)=>{let Q=setTimeout(()=>X(!1),J);Y.then((G)=>{clearTimeout(Q),X(G)},(G)=>{clearTimeout(Q),$(G)})})}function ij(Y,J){let X=Y.body;if(!X)return Y;let $=!1,Q=new ReadableStream({async start(G){let z=X.getReader(),K=async(U)=>{while(!0){let{done:H,value:V}=await U.read();if(H)return;if(V&&V.length>0)$=!0,G.enqueue(V)}};try{await K(z),G.close()}catch(U){if($||!p0.isOversizedFrame(U)){G.error(U);return}try{let H=await J();if(!H.ok){G.error(new $6(`HTTP fallback after an oversized WebSocket frame failed with ${H.status}`));return}if(H.body)await K(H.body.getReader());G.close()}catch(H){G.error(H)}}},cancel(G){X.cancel(G)}});return new Response(Q,{status:Y.status,headers:Y.headers})}function nj(Y){return new Response(new ReadableStream({start(J){J.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function oj(Y,J,X,$,Q,G,z){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<Q)return Y.socket;$1(Y);let K=await p0.connectResponsesWebSocket({url:p0.toWebSocketUrl(J),headers:X,timeout:$,rawWebSocket:G,signal:z??void 0});return Y.connectedAt=Date.now(),K}function $1(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function rj(Y,J,X,$){if(!Y.socket||!Array.isArray(J.input)||J.input.length===0)return;let Q=aj(J);await q4({sessionID:$.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(Q),url:$.url,method:"POST",headers:$.headers});let G=p0.streamResponsesWebSocket({socket:Y.socket,body:Q,sessionID:$.sessionID,idleTimeout:X,signal:$.signal,onRateLimitReached:$.onRateLimitReached,onComplete:(z,K)=>{c1({component:"ws-pool",event:"prewarm_completed",sessionID:$.sessionID,responseID:fW(z),usage:mW(z)}),uW(Y,Q,z,K,!1,{input:I8([]),signature:nW(Q),priorInputs:new Map})},onTerminal:(z)=>{if(z.type!=="response.completed"&&z.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0},onRetryableTerminal:async(z)=>{let K=gW(z);if(!K)return;throw Y.fallback=!0,K}});await sj(G)}function fW(Y){let J=Y.response;if(!Q0(J))return;return typeof J.id==="string"?J.id:void 0}function mW(Y){let J=Y.response;if(!Q0(J))return;return Q0(J.usage)?J.usage:void 0}async function sj(Y){let J=Y.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function aj(Y){return b8({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:tj(Y.client_metadata)})}function cW(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 tj(Y){if(!Q0(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let J=JSON.parse(Y["x-codex-turn-metadata"]);if(!Q0(J))return Y;return{...Y,"x-codex-turn-metadata":cW(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function ej(Y){let J=Y["x-codex-turn-metadata"];if(!J)return Y;try{let X=JSON.parse(J);if(!Q0(X))return Y;return{...Y,"x-codex-turn-metadata":cW(X)}}catch{return Y}}function bW(Y){let J={...Y};if(Array.isArray(Y.input))J.input=Y.input.map(YF);return J}function YF(Y){if(!Q0(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 uW(Y,J,X,$,Q,G=T4(Y,J)){let z=X.response,K=Q0(z)&&typeof z.id==="string"?z.id:void 0;if(!K||!Array.isArray(J.input)){Y.continuation=void 0;return}let U=Q?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of $)U.add(H);Y.continuation={responseID:K,input:J.input,signature:G.signature,canonical:kY(G.input),finalizedCallIds:U}}function t7(Y,J,X=J,$=T4(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){let Q=Array.isArray(J.input)?J.input:[],G=Array.isArray(X.input)?X.input:Q,z=$.signature,K=Y.turnInput&&Y.turnSignature===z?xY(dW($,Y.turnInput),$.input):void 0,U=K===void 0?Q:G.slice(K);if(U.length>0&&U.some(iW)||!Y.turnID)Y.turnID=h1(),Y.turnStartedAt=Date.now();Y.turnInput=G.slice(),$.priorInputs.set(Y.turnInput,$.input),Y.turnSignature=z,Y.turnCanonical=kY($.input)}function pW(Y,J,X=J,$=T4(Y,{...X,input:Array.isArray(X.input)?X.input:J.input})){t7(Y,J,X,$);let Q=J.client_metadata;if(!Q0(Q)||typeof Q["x-codex-turn-metadata"]!=="string")return J;let G=lW(Q["x-codex-turn-metadata"],Y.turnID,Y.turnStartedAt);if(!G)return J;return{...J,client_metadata:{...Q,"x-codex-turn-metadata":G}}}function lW(Y,J,X){let $;try{$=JSON.parse(Y)}catch{return}if(!Q0($))return;return JSON.stringify({session_id:$.session_id,thread_id:$.thread_id,thread_source:$.thread_source,turn_id:J,sandbox:$.sandbox,turn_started_at_unix_ms:X,request_kind:"turn",window_id:$.window_id})}function T4(Y,J){let X=Array.isArray(J.input)?J.input:[],$=new Map;if(Y.turnInput&&Y.turnCanonical)$.set(Y.turnInput,Y.turnCanonical);if(Y.continuation?.canonical)$.set(Y.continuation.input,Y.continuation.canonical);let Q=I8(X,Y.turnCanonical??Y.continuation?.canonical);return $.set(X,Q),{input:Q,signature:nW(J),priorInputs:$}}function dW(Y,J){let X=Y.priorInputs.get(J);if(!X){for(let[$,Q]of Y.priorInputs)if($.length===J.length&&$.every((G,z)=>G===J[z])){X=Q;break}X??=I8(J),Y.priorInputs.set(J,X)}return X}function JF(Y,J,X=T4(Y,J)){let $=Array.isArray(J.input)?J.input:void 0;if(!$||!Y.continuation)return J;if(Y.continuation.signature!==X.signature)return Y.continuation=void 0,J;if(!oW(Y.continuation,X))return Y.continuation=void 0,J;if(Y.continuation.input.length===0)return{...J,previous_response_id:Y.continuation.responseID};let Q=$.slice(Y.continuation.input.length),G=$F(Q,Y.continuation.finalizedCallIds);if(G.length===0)return J;return{...J,previous_response_id:Y.continuation.responseID,input:G}}function XF(Y,J,X=T4(Y,J)){let $=Array.isArray(J.input)?J.input:void 0;if(!Y.continuation)return!0;if(!$)return!1;if(!oW(Y.continuation,X))return!0;return $.slice(Y.continuation.input.length).some(iW)}function iW(Y){if(!Q0(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function $F(Y,J){return Y.filter((X)=>{if(!Q0(X))return!0;if(typeof X.type==="string"&&X.type.endsWith("_output"))return!0;if(X.type==="function_call_output"||X.type==="custom_tool_call_output")return!0;if(X.type==="function_call"||X.type==="custom_tool_call"){let $=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;return $?!J.has($):!0}if(X.type==="message")return X.role!=="assistant";if(typeof X.role==="string")return X.role!=="assistant";return!1})}function nW(Y){return yW(QF(Object.fromEntries(Object.entries(Y).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function QF(Y){if(!Q0(Y.client_metadata))return Y;let J=Object.fromEntries(Object.entries(Y.client_metadata).filter(([X])=>X!=="x-codex-turn-metadata"&&X!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:J}}function oW(Y,J){if(Y.input.length>=J.input.texts.length)return!1;return xY(dW(J,Y.input),J.input)!==void 0}function rW(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let J=new Headers(Y.headers);for(let X of s7)J.delete(X);return{...Y,headers:J}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((J)=>!s7.has(J[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([J])=>!s7.has(J.toLowerCase())))}}var zF="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.",WF="opencode-oauth-dummy-key",WC=()=>e4,KF=120000,UF=90000,HF=4000,sW=50,aW=3,BF=25,VF=60000,NF=2000,LF="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",K3=!1,uY;function KC(){return uY}function UC(){K3=!1,uY=void 0}var tW=U0("models"),eW=!1,YK=!1;function JK(){throw Error(LF)}async function ZF(Y,J={}){let X=J.paths??x1(_6());if(DJ(X.configPath)){await C1(z4(X),J.holdsMainRefreshLock?void 0:o6(X),($)=>{if(J.canWrite&&!J.canWrite())throw Error(i1["vault-refused"]);Y($)});return}await V9(($)=>{return Y($),$},X,{canWrite:J.canWrite})}var tK=null;function HC(){return tK}function jF(Y){return Math.floor(Math.random()*Y)}var FF=!0;function _F(Y,J,X){let $=Y.get(J);if($)return $;let Q=h1(),G={threadID:Q,turnID:h1(),windowID:`${Q}:0`};return Y.set(J,G),X?.(),G}function J3(){return wK("opencode1")}function X3(Y,J){if(J?.headers!==void 0)return new Headers(J.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function $3(Y,J){if(!(Y instanceof Request))return J;let X=new Request(Y,J),$=X.method.toUpperCase(),Q=$==="GET"||$==="HEAD"||X.body===null?void 0:await X.text();return{method:X.method,headers:new Headers(X.headers),body:Q,signal:X.signal,cache:X.cache,credentials:X.credentials,integrity:X.integrity,keepalive:X.keepalive,mode:X.mode,redirect:X.redirect,referrer:X.referrer,referrerPolicy:X.referrerPolicy}}async function DF(Y,J={}){await aK({version:f6,...J.runtimeLayout});let X=_6(),$=await XW({version:f6}),Q=x1(X),G=$.snapshot?E$(X,$.snapshot):void 0,z=(k)=>M6(k,X),K=(k)=>k===null?null:z(k),U=async(k)=>K(await k1(k)),H=async(k)=>K(await BK(k));class V extends LK{async load(){return K(await super.load())}}let F=T6(X);J={...J,experimentalWebSockets:J.experimentalWebSockets??F.webSockets,responsesLite:J.responsesLite??F.responsesLite};let Z=J.codexApiEndpoint??F.codexApiEndpoint,N=crypto.randomUUID(),j=kK(J3()),P=new EJ,v=()=>hK(J3(),j),y=!1,I=!1,A=[],q=null,C=bK(Y.client),m=new Map,r=new Map,l,R0=!1,B0,z0=new Map,A0,f,V0=HW({host:"opencode",stateDir:J.vault?.stateDir??ZK(Q.statePath),reservedRouteIds:()=>N0?.peek().rows.map((k)=>k.id)??[],...J.vault?.connectionFile?{connectionFile:J.vault.connectionFile}:{},...J.vault?.connectScoped?{connectScoped:J.vault.connectScoped}:{},...J.vault?.connectEnrollment?{connectEnrollment:J.vault.connectEnrollment}:{},...J.vault?.pollIntervalMs!==void 0?{pollIntervalMs:J.vault.pollIntervalMs}:{},...J.vault?.now?{now:J.vault.now}:{},...J.vault?.setTimeoutImpl?{setTimeoutImpl:J.vault.setTimeoutImpl}:{},...J.vault?.clearTimeoutImpl?{clearTimeoutImpl:J.vault.clearTimeoutImpl}:{},fetchImpl:()=>fetch},Q),b=V0.vault;await b.authority();let Q1=V0.firstRoster,G1=Promise.withResolvers(),o1=Promise.race([Q1,G1.promise]),p6=J.vault?.firstRosterWaitMs??hJ,w,N0,c,F0=new Map,t=new Map,_0=(k)=>{for(let[g,s]of t)if(s.sessionId===k)t.delete(g)},{enabled:W0,...E0}=J.poolMigration??{},H6=W0??FF;if(H6&&"reason"in C)(E0.log??U0("pool")).warn("account pool migration is off for this OpenCode client",{reason:C.reason});let Q6=H6&&"slot"in C?Rz({paths:()=>Q,slot:C.slot,version:f6,...E0,runDeps:{vaultServes:()=>b.serves(),...E0.runDeps},paused:async()=>await b.authority()!=="local",migrate:async(k)=>{let g=await(E0.migrate??PY)(k);return N0?.load(),g},adopt:async(k)=>{if(!await V4(o1,p6))return{status:"retry",reason:"vault-roster-pending"};let g=await(E0.adopt??qY)(k);return N0?.load(),g}}):void 0,C4=(k,g="")=>k?async()=>{let s=await k();return{url:s.url,instructions:s.instructions??g,method:"auto",callback:async()=>{try{let X0=await s.tokens;return{type:"success",refresh:X0.refresh_token,access:X0.access_token,expires:Date.now()+(X0.expires_in??3600)*1000,accountId:b1(X0)}}finally{s.cleanup?.()}}}}:void 0,y8=new PK(J.backgroundQuota),w4,S4=z5({client:Y.client,getAuth:async()=>w4?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:C4(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:C4(J.login.authorize.headless)}:{}},vault:b,onMainSlotWritten:async()=>{await Q6?.requestAdoption()}}),pY=(k)=>async(g)=>{let s=await k(g);if(s.method!=="auto")return s;return{...s,callback:async()=>{let X0=await s.callback();if(X0.type==="success"&&"refresh"in X0)lY(X0.refresh);return X0}}};async function lY(k){if(!Q6||!("slot"in C))return;let g=J.login?.sleep??((s)=>Bun.sleep(s));for(let s=0;s<5000;s+=100){try{let X0=await C.slot.get({path:{id:"openai"}});if(Q0(X0)&&X0.refresh===k){await Q6.requestAdoption();return}}catch{}await g(100)}}let dY=S4.map((k)=>k.type==="oauth"?{...k,authorize:pY(k.authorize)}:k);async function I4(k,g){let s=Y.client.session;if(typeof s?.promptAsync==="function"){let X0=await AW(Y.client,k),l0={noReply:!0,parts:[{type:"text",text:g,ignored:!0}]};if(X0?.agent)l0.agent=X0.agent;if(X0?.model)l0.model=X0.model;if(X0?.variant)l0.variant=X0.variant;await s.promptAsync({path:{id:k},body:l0});return}}return{async dispose(){G?.(),$.snapshot?.dispose(),await $8(xK(J3()),NF,()=>{return}),await c?.dispose(),await V0.release(),Q6?.dispose(),await N0?.dispose(),y8.stop(),f?.stop(),l?.stopBackgroundRefresh(),l=void 0;for(let s of A)s.close();A.length=0;let k=globalThis;for(let[s,X0]of m)if(k.__openaiAuthCacheKeepManagers?.get(s)===X0)X0.stop(),k.__openaiAuthCacheKeepManagers.delete(s);m.clear();for(let s of r.values())await s.release().catch(()=>{});r.clear();let g=w;w=void 0,await(await g)?.release()},async event(k){if(k.event.type!=="session.deleted")return;let g=k.event.properties.info;if(c?.forget(g.id),_0(g.id),F0.delete(g.id),q?.cacheKeepManager?.remove(g.id),j.delete(g.id))v();let s=m6(g.id);if(z0.delete(s),f?.cancel(`pin:${s}`),B0){let X0=await b.authority()!=="local"?b.routes().map((l0)=>({id:l0.id})):(await U(Q))?.accounts;await uK(g.id,X0,B0).catch(()=>{})}for(let X0 of A)X0.remove(g.id)},provider:{id:"openai",async models(k,g){if(g.auth?.type!=="oauth")return k.models;let s=await b.authority()!=="local"?await H(Q):await U(Q),X0=!s||HK(z(s)),l0=X0?null:await OW();if(!X0&&l0&&!eW)eW=!0,tW.debug("restoring OAuth model costs from models.dev catalog");if(!X0&&!l0&&!YK)YK=!0,tW.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(k.models).filter(([,z1])=>z1.options.reasoningMode!=="pro"&&U3(z1.api.id)).map(([z1,r0])=>{let y0=B3(r0.id),r1=y0?k.models[y0]?.variants:void 0;return[z1,{...r0,...r1?{variants:{...r1,...r0.variants}}:{},cost:X0?{input:0,output:0,cache:{read:0,write:0}}:l0?.[r0.api.id]??l0?.[z1]??r0.cost,limit:H3(r0.id)??r0.limit}]}))}},auth:{provider:"openai",async loader(k){await b.authority(),w4=k,w??=rK({version:f6,logger:U0("heartbeat")}),await w,Q6?.start();let g=await k();if(g.type!=="oauth")return G1.resolve(),{};let s=W3(g).kind==="tombstone";V0.start();let X0=Y.directory?await CK(Y.directory):void 0,l0=X0?.dir??X;async function z1(B,L={}){if(await b.authority()!=="local")return;return ZF(B,{...L,paths:Q,canWrite:()=>!b.enrolled()})}let r0=await b.authority()!=="local";if(!s&&!r0)await NK({type:"oauth",access:g.access??"",refresh:g.refresh??"",expires:g.expires??0},Q);let y0=await(r0?H(Q):U(Q)).catch(async(B)=>{if(await b.authority()!=="local")return null;throw Error(`OpenAI auth store at ${X} is corrupt or unreadable: ${B instanceof Error?B.message:String(B)}. Fix or remove it to continue.`,{cause:B})});if(!r0&&await fY(Q,g)){if(Q6)Q6.noticePlaceholderWithoutMain();else if(!R0)R0=!0,U0("pool-migration").warn(W4,{reason:"placeholder-without-main"})}let r1=y0,V3=!r0,iY=M5({path:()=>X,stat:(B)=>{try{let L=GF(B);return{mtimeMs:L.mtimeMs,size:L.size}}catch{return}},read:()=>U(Q),fallback:async(B)=>{if(await b.authority()!=="local")return H(Q);throw B},onRead:(B)=>{r1=B,V3=!0}});function nY(){let B=iY.read();return B instanceof Promise?B.then(K):K(B)}async function N3(){if(!V3)return nY();return $8(Promise.resolve(nY()),D9,()=>K(r1))}function g8(){iY.invalidate()}if(y0&&g.access&&!s&&!r0){let B=b1({id_token:"",access_token:g.access,refresh_token:g.refresh??""});if(B&&B!==y0.mainAccountId)await z1((L)=>{L.mainAccountId=B}),y0.mainAccountId=B,g8()}let oY=z(y0).logging?.level;if(oY&&typeof oY==="string")Z9(oY);let b4=U0("transport"),B6=U0("quota"),f8=U0("refresh"),k6=U0("accounts"),eK=new FK;b4.info("codex auth loader ready",{codexApiEndpoint:Z,transport:T6(X).rawWebSocket?"raw-websocket":T6(X).webSockets?"websocket":"http"});let e=new UK({storage:z(y0),configPath:X,fetchQuotaFn:void 0}),k4,x4=0;await c?.dispose(),await N0?.dispose();let C0=new vJ({paths:()=>Q,refreshProvider:async(B)=>{let L=await k8({refreshToken:B.refresh,fetchImpl:fetch,now:Date.now}),D=b1({id_token:"",access_token:L.access,refresh_token:L.refresh});return{...L,...D?{identity:D}:{}}},pullQuota:async(B)=>{let L=B.credential;if(L.type!=="oauth"||!L.access)throw Error("the row holds no access token to poll with");let D=await Y8({accessToken:L.access,fetchImpl:fetch,now:Date.now,...B.identity?{accountId:B.identity}:{},accountKey:B.id,logger:B6}),M=Date.now(),E={quota:D,refreshAfter:M+300000,checkedAt:M};if(B.id==="main")e.setMain(L.access,E,B.identity,!0);else e.setFallback(B.id,E,L.access,!0,B.identity);return U4(D,M,!0)},vaultIdentities:()=>b.identities(),vaultMode:()=>b.enrolled(),vaultAuthority:()=>b.authority(),vaultFirstRoster:Q1,vaultFirstRosterBackgroundWaitMs:p6,log:U0("pool")});if(N0=C0,!r0)await C0.load();c=new gJ({pool:C0,vault:b,log:(B)=>B6.warn(B)});let d0=c,L3=new Map,rY=(B)=>{let L=F0.get(B),D=L&&(d0.accountKey(L.accountId)??L3.get(L.accountId));return L&&D&&e0(L,D)?D:void 0},V6=new V({paths:Q,refreshFn:async(B)=>{if(await b.authority()!=="local")throw Error(i1["vault-refused"]);return k8({refreshToken:B.refreshToken,fetchImpl:B.fetchImpl,now:B.now})},quotaManager:e,canWrite:()=>!b.enrolled(),onFallbackStorageChanged:g8,backgroundRefreshPaused:async()=>b.enrolled()||await C0.active()});if(y0&&y0.accounts.length>0)V6.startBackgroundRefresh();function sY(B){if(c0(B))return;return B.access||void 0}function m8(B={}){let{readSidebarState:L,respectBackoff:D,skipFresherThanMs:M}=B;return{getAuth:k,codexRefreshFn:k8,refreshMainWithLease:M3,fallbackManager:V6,quotaManager:e,loadAccounts:U,writeSidebarState:(E)=>x6(E),client:Y.client,fetchImpl:fetch,now:Date.now,paths:Q,readSidebarState:L??(()=>yK(s0)),storageMainAccountId:y0?.mainAccountId,isOAuthAccountFn:n0,whamFn:Y8,...D===void 0?{}:{respectBackoff:D},...M===void 0?{}:{skipFresherThanMs:M}}}async function Z3(B){return(await C0.pollRows(await U(Q),B?{ids:B}:{})).map((D)=>({account:D.id,ok:D.ok,...D.error!==void 0?{error:D.error}:{}}))}async function j3(B){return C0.accessFor(B,await U(Q))}let F3=U0("cachekeep"),c8=j9(z(y0)),_3=c8?.enabled===!0,D3=c8?.subagents===!0,O3=c8?.sustain===!0,P3=SJ({...z(y0),cachekeep:c8}),u8;async function YU(B){await new Promise((L)=>setTimeout(L,B))}async function JU(B){let L;for(let D=1;D<=aW;D++){if(await b.authority()!=="local")throw Error(i1["vault-refused"]);try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:B.refresh,access:B.access,expires:B.expires}});return}catch(M){if(L=M,D<aW)await YU(BF*D)}}throw new S8(L)}async function p8(B){await z1((L)=>{L.refresh=L.refresh??{},B(L)},{holdsMainRefreshLock:!0}),g8()}async function aY(B){let L=Date.now()+HF;while(Date.now()<L){await new Promise((E)=>setTimeout(E,sW+jF(sW)));let D=await k();if(t0(D))throw new V1;if(D.type!=="oauth"||!D.access)continue;if((D.access!==B.access||D.refresh!==B.refresh||(D.expires??0)>(B.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return f8.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??B.refresh??"",expires:D.expires??0}}return null}function q3(B){if(t0(B))throw new V1;if(B.type!=="oauth")throw Error("not oauth");if(c0(B))throw new WK;if(!B.refresh)throw Error("Token refresh failed: missing refresh token");return B.refresh}async function tY(){if(!u8)u8=(async()=>{let B=await k(),L=q3(B);if(B.type!=="oauth")throw Error("not oauth");let D=X8(L),M=await k1(Q),E=M?.refresh?.mainLastRefreshError;if(E&&r6(E,L,Date.now()))throw Error(Q3(E,Date.now()));if(M?.refresh?.mainRefreshLeaseUntil&&M.refresh.mainRefreshLeaseUntil>Date.now()&&M.refresh.mainRefreshLeaseTokenHash===D){let T=await aY(B);if(T)return T;throw Error("Codex OAuth refresh is already in progress")}let S=await XK({name:e4,ttlMs:KF,path:X,renew:!0});if(!S){let T=await aY(B);if(T)return T;throw Error("Codex OAuth refresh is already in progress")}let R;try{let T=await k(),o=q3(T);if(T.type!=="oauth")throw Error("not oauth");if(o!==L){if(T.access&&(T.expires??0)>Date.now())return f8.debug("main token rotated while awaiting the lock",{pid:process.pid}),await S.release().catch(()=>{}),{access:T.access,refresh:o,expires:T.expires??0};let D0=(await k1(Q))?.refresh?.mainLastRefreshError;if(D0&&r6(D0,o,Date.now()))throw Error(Q3(D0,Date.now()))}R={...T,refresh:o}}catch(T){throw await S.release().catch(()=>{}),T}await IK(Q,R.refresh,R.access!==void 0?{slotAccess:R.access}:{}).catch(()=>!1);let h=X8(R.refresh),x=crypto.randomUUID(),u=h;try{await p8((Y0)=>{if(SK(X,R.refresh))throw new z3;Y0.refresh=Y0.refresh??{},Y0.refresh.mainRefreshLeaseId=x,Y0.refresh.mainRefreshLeaseUntil=Date.now()+UF,Y0.refresh.mainRefreshLeaseTokenHash=h});let T=await k1(Q);if(T?.refresh?.mainRefreshLeaseId!==x||T.refresh.mainRefreshLeaseTokenHash!==h)throw Error("Codex OAuth refresh is already in progress");if(await b.authority()!=="local")throw Error(i1["vault-refused"]);let o=await k8({refreshToken:R.refresh,fetchImpl:fetch,now:Date.now});return await JU(o),await p8((Y0)=>{if(Y0.refresh=Y0.refresh??{},Y0.refresh.mainLastRefreshError=void 0,Y0.refresh.mainRefreshLeaseId===x)Y0.refresh.mainRefreshLeaseId=void 0,Y0.refresh.mainRefreshLeaseUntil=void 0,Y0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),u=void 0,o}catch(T){if(!(T instanceof z3)){if(!CY(T))await p8((o)=>{o.refresh=o.refresh??{},o.refresh.mainLastRefreshError=GK({error:T,now:Date.now(),refreshToken:R.refresh,previous:o.refresh.mainLastRefreshError})}).catch(()=>{});throw T}}finally{if(u)await p8((T)=>{if(T.refresh?.mainRefreshLeaseId===x&&T.refresh.mainRefreshLeaseTokenHash===u)T.refresh.mainRefreshLeaseId=void 0,T.refresh.mainRefreshLeaseUntil=void 0,T.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S.release().catch(()=>{})}let $0=await aY(R);if($0)return $0;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{u8=void 0});return u8}function E3(B){return R$({storage:B,now:Date.now,refreshAccount:(L,D)=>V6.refreshAccount(L,D,{asPoolMain:!0}),warn:(L,D)=>f8.warn(L,{pid:process.pid,...D})})}async function A3(){let B=await E3(await U(Q));if(!B)throw Error("The main OpenAI account has no usable token in the account pool");return{access:B.token,refresh:B.account.refresh,expires:B.account.expires??0}}async function M3(){try{return await tY()}catch(B){if(B instanceof V1)return A3();throw B}}let T3=globalThis,eY=T3.__openaiAuthCacheKeepManagers??new Map;T3.__openaiAuthCacheKeepManagers=eY,eY.get(l0)?.stop();let l8=IJ({fetchImpl:fetch,vault:b,activity:{store:d0.activity,accountKey:({target:B})=>{let L=rY(B.meta.routingSessionId??B.sessionKey);return L?.accountId===B.accountId?L:void 0}},getMainToken:async()=>{if(await b.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await C0.active()){let L=await j3("main");if(!L)throw Error("main pool row has no usable token");return{token:L.token,identity:L.row.identity}}let B=await k();if(await b.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(t0(B))return(await A3()).access;if(B.type!=="oauth")throw Error("not oauth");if(!B.access||(B.expires??0)<Date.now())try{return(await M3()).access}catch(L){if(CY(L))throw L;if(B.access)return B.access;throw Error("main token refresh failed")}return B.access},refreshFallback:async(B)=>{if(await b.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await C0.active()){let R=await j3(B);if(!R)throw Error(`no access token for ${B}`);return{token:R.token,identity:R.row.identity}}let L=await N3(),D=L?r7(L.accounts,B):void 0;if(!D)throw Error(`fallback account ${B} not found`);let M=L??{version:1,accounts:[D]},E=c0(D)?D:await V6.refreshAccount(D,M),S=sY(E);if(!S)throw Error(`no access token for ${B}`);return{token:S}},codexResponsesUrl:Z,activeAccount:async(B)=>A5(n1(await A1.read(),z0),B),logger:F3,now:Date.now,getWindow:()=>P3,getSustain:()=>O3});eY.set(l0,l8),m.set(l0,l8);function s1(B,L,D,M,E=!1){try{XU(B,L,D,M,E)}catch(S){B6.warn("quota push failed",{pid:process.pid,accountId:D??"main",error:E4(S)})}}function XU(B,L,D,M,E){if(Object.keys(B).length===0&&!E)return;let S=Date.now(),R=B,h={quota:R,refreshAfter:S+300000,checkedAt:S},x;if(D&&D!=="main"){let $0=L?R6(L):null,T=$0?C6($0):void 0,o=e.peekFallbackForPolicy(D)?.quota,Y0=SY(R,o);h={...h,quota:Y0},e.setFallback(D,h,L,E,T)}else{if(x=M,!x&&L){let o=R6(L);x=o?C6(o):void 0}if(x&&k4&&x!==k4){B6.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:x,currentMainIdentity:k4});return}let $0=e.peekMainForPolicy(x)?.quota,T=SY(R,$0);h={...h,quota:T},e.setMain(L,h,x,E)}B6.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:h.quota}),C0.recordSnapshot(D&&D!=="main"?D:"main",B,L,E);let u=Boolean(D&&D!=="main");l6.enqueue("machine-state","quota",()=>x6(e,u?void 0:x))}function YJ(B,L=!1){if(L)return b.enrolled()?U6(b.routes().find((D)=>D.id===B)?.quota):U6(C0.peek().rows.find((D)=>D.id===B)?.quota);return B==="main"?e.peekMainForPolicy()?.quota:e.peekFallbackForPolicy(B)?.quota}function $U(B,L,D){let M=YJ(B);return KK(M,L,Date.now(),VF,D)}let a1=new Map;function R3(){if(!b.enrolled())return;l6.enqueue("machine-state","quota",()=>x6(e))}function C3(B,L,D,M,E,S){if(D&&E){b.reportUsage(D,{frame:S},E),b.recordSnapshot(D,B,!0,E).then(R3);return}s1(B,L,D,!D||D==="main"?M:void 0,!0)}let h4=J.experimentalWebSockets?u6.createWebSocketFetch({httpFetch:fetch,rawWebSocket:T6(X).rawWebSocket,onQuota:(B,L,D,M,E)=>{let S=D?a1.get(D):void 0;C3(B,L,S?.id??D,M,S?.receipt,E)},onRateLimitReached:(B,L,D)=>{if(!L)B6.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:B});let M=L?a1.get(L):void 0;if(!M&&L?.startsWith("stream:"))return;let E=M?.id??L??"main";if(M)M.limited=!0;if(M?.migrated){let{owner:R,probe:h}=M;if(!R)return;if(!h||R.registry!==h.registry){R.dropSignal();return}let x=Date.now(),{command:u,provenance:$0}=G3({binding:h.binding,baseRevision:h.baseRevision,producerId:N,operationId:e7(),parsed:{window:B,resetAt:D},reading:YJ(E,!0),now:x,observedAt:x,evidenceAt:x});R.enqueue(u,$0);return}let S=$U(E,B,D);e.markRateLimited(E,S),B6.debug("mid-stream rate limit mark",{pid:process.pid,accountId:E,window:B})},onComplete:(B,L)=>{if(B.type==="response.completed"&&L)a1.get(L)?.complete()},onHttpResponse:(B,L)=>{return(L?a1.get(L):void 0)?.observeHttp(B)??B}}):void 0;if(h4)A.push(h4),y=!0;let s0=vK();B0=s0;async function x6(B,L){if(b.enrolled()){iY.invalidate();let R=await H(Q);await mY(tz(b.snapshot()?.rows,new Set(b.routes().map((h)=>h.id)),z(R),Date.now()),s0,{canWrite:()=>b.enrolled()});return}let D=nY(),M=D instanceof Promise?await D.catch(()=>r1):D,E=L??M?.mainAccountId,S=await C0.current();if(S.active){await mY(ez(S.rows,z(M),Date.now(),(R)=>(R==="main"?B.getMain():B.getFallback(R))?.quota?.resetCreditsAvailable),s0,{canWrite:()=>!b.enrolled()});return}if(!M)return;await mY(IY(B,M,Date.now(),E),s0,{canWrite:()=>!b.enrolled()})}let A1=iK(s0);A1.read(),f?.stop();let l6=oK({logger:b4,onWritten:()=>A1.refreshInBackground()});if(f=l6,A0!==s0)z0.clear(),A0=s0;function JJ(B,L,D,M,E,S,R=!1){let h={vaultMode:R,canWrite:()=>b.enrolled()===R},x={activeId:D,route:M,updatedAt:Date.now()};if(!B){l6.enqueue("routing:legacy","routing",()=>cK(x,s0,h));return}if(l6.enqueue(`routing:${B}`,"routing",()=>cY({sessionId:B,...x},E,s0,h)),!L||L===B)return;if(M==="sticky-balanced"){let u=S.stickyAssignments?.[m6(L)]?.accountId,$0=E===void 0||u==="main"||E.some((T)=>T.enabled!==!1&&T.id===u);if(!u||!$0)return;l6.enqueue(`routing:${L}`,"routing",()=>cY({sessionId:L,activeId:u,route:M,updatedAt:Date.now()},E,s0,h));return}l6.enqueue(`routing:${L}`,"routing",()=>cY({sessionId:L,...x},E,s0,h))}l?.stopBackgroundRefresh(),l=V6;let v4=Q,w3=$.authority.install.target,QU=$.snapshot&&w3?{settingsSnapshot:$.snapshot,settings:o4({file:w3,host:"opencode",snapshot:$.snapshot,log:U0("settings")})}:{};if(q=tK={configPath:X,...QU,accountStoragePath:v4.configPath,accountStatePath:v4.statePath,packageVersion:f6,layoutNotice:sK,quotaManager:e,loadAccounts:U,beginAccountLogin:B9,store:()=>z4(v4),migration:async()=>{if(await z9(v4,z4(v4))!==void 0)return{migrated:!0};let B=await(E0.fence??(()=>H4({currentVersion:f6})))();return{migrated:!1,blockers:B.open?[]:B.blockers.map((L)=>({pid:L.pid,version:L.version}))}},afterWrite:()=>C0.load(),vault:b,resolveResetTarget:n7({getAuth:k,refreshMainWithLease:tY,refreshFallbackAccount:(B,L)=>V6.refreshAccount(B,L),refreshPoolMainRow:(B,L)=>V6.refreshAccount(B,L,{asPoolMain:!0}),poolAccess:async(B)=>C0.rowAccess(B,await U(Q)),loadAccounts:U,accountStoragePath:X,accountStatePath:Q.statePath,now:Date.now}),...o7(),cacheKeepManager:l8,setCacheKeepEnabled:(B)=>{_3=B},setCacheKeepSubagents:(B)=>{D3=B},setCacheKeepSustain:(B)=>{O3=B},setCacheKeepWindow:(B)=>{P3=B},clearStickyRouting:async(B)=>{d0.forget(B),_0(B),F0.delete(B);let L=m6(B),D=z0.delete(L);return l6.cancel(`pin:${L}`),await dK(B,s0)||D},getStickyRouting:async(B)=>mK(n1(await A1.read(),z0),B),refreshSidebar:async()=>{g8(),await x6(e)},refreshAllQuota:async()=>{if(await b.authority(),b.enrolled()){let B=await b.pollStale(0);return await x6(e),B.map((L)=>({account:L.id,ok:L.ok,...L.error!==void 0?{error:L.error}:{}}))}if(await C0.active()){let[B,L]=await Promise.all([Z3(),b.pollStale(0)]);return await x6(e),[...B,...L.map((D)=>({account:D.id,ok:D.ok,...D.error!==void 0?{error:D.error}:{}}))]}return gY(m8())},refreshResetTargetQuota:async(B)=>{if(await b.authority(),b.enrolled())return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await C0.active()){let[D]=await Z3([B]);return D??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}return(await gY(m8({respectBackoff:!1}),{accountKey:B})).find((D)=>D.account===B)??{account:B,ok:!1,error:"targeted quota refresh returned no result"}}},X0){let B=X0;try{let L=await QK(wW,B.dir,()=>SW({dir:B.dir,secureDir:B.secureDir,sweepRoot:B.sweepRoot,drain:N5,apply:async(D)=>{let M=$K(D);if(!M)throw Error("not an /openai apply request");return O5(q,M)}}));r.set(B.dir,L)}catch{}}async function t1(B,L,D,M,E="main",S,R,h,x=!1,u){if(!D.trim())throw b4.warn("refusing to send a request with no access token",{account:E,accountId:M}),Error(zF);if(!S&&await b.authority()!=="local")return Response.json({error:{message:i1["vault-refused"]}},{status:400});let $0=X3(B,L);if($0.delete("x-api-key"),$0.delete("api-key"),$0.set("authorization",`Bearer ${D}`),M)$0.set("ChatGPT-Account-Id",M);$0.set(u6.QUOTA_ACCOUNT_HEADER,E);let T=bY($0),o=$0.get(v8)??void 0,Y0=o&&["title","compaction","summary","generate"].includes(o)?o:$0.get(u6.TITLE_HEADER)==="true"?"title":void 0,D0=T?_F(j,T,v):void 0,G6=B instanceof URL?B:new URL(typeof B==="string"?B:B.url),D6=G6.pathname.includes("/v1/responses")||G6.pathname.includes("/chat/completions")?new URL(Z):G6,M1=Boolean(h4&&G6.pathname.endsWith("/responses")),N6=qJ({applyEffort:K5,init:{...L,headers:$0},headers:$0,metadata:Y0&&D0?P.forAuxiliary(D0):D0,installationID:N,websocket:M1,skipTurnUpdate:Y0!==void 0,responsesLite:J.responsesLite??!1,dumpSessionID:T}),d6=D0&&{turnID:D0.turnID,turnStartedAt:D0.turnStartedAt},g0=N6.init;if(R){let a=()=>{if(!h)return!0;let h6=d0.accountKey(E);return Boolean(h6&&e0(h.account,h6))};if(!a())return S?new Response(vY(yY(b),b.name),{status:401}):d8(null,"quota-unknown");let J0=()=>R.beforeDispatch(h,()=>d0.ownershipBindings(),E),H0=u===void 0?await J0():await G8(u,J0),K0=a()?H0?.status:"absent";if(K0!=="ready")return K0==="absent"&&S?new Response(vY(yY(b),b.name),{status:401}):d8(null,"quota-unknown")}let x0=x?d0.owner():void 0,n=R?x0?.observe(h):void 0,M0=h?.account??(!x?RK(TK(X,Q.statePath),{kind:"legacy",id:E,verifiedIdentity:M}):void 0);if(!x&&M0)L3.set(E,M0);let w0=T&&M0&&typeof g0?.body==="string"?{sessionId:T,accountKey:M0,dispatchedAt:Date.now(),ttlMs:wJ(g0.body)}:void 0;if(T)F0.delete(T);if(w0){if(F0.set(w0.sessionId,w0.accountKey),F0.size>256){let a=F0.keys().next().value;if(a)F0.delete(a)}}function O6(a){if(L?.signal?.aborted||Z6.limited||!w0)return;qK(d0.activity,w0,rY(w0.sessionId),a==="ws"?{kind:a,event:"response.completed",aborted:!1}:{kind:a,completed:!0,failed:!1,aborted:!1})}let L6=Az({classifyLimits:x,onComplete:()=>O6("http"),onCleanRead:n?.evidence&&(()=>{if(!(L?.signal??(B instanceof Request?B.signal:void 0))?.aborted)x0?.afterProbe(n,!0,Z6.limited)}),onQuota:(a,J0)=>{let H0=h&&d0.accountKey(E);if(h&&!S&&(!H0||!e0(h.account,H0)))return;C3(a,D,E,M,S,J0)},onLimit:x0&&((a,J0)=>{if(!n||x0.registry!==n.registry){x0.dropSignal();return}let H0=d0.accountKey(E),{command:K0,provenance:h6}=G3({binding:n.binding,baseRevision:n.baseRevision,producerId:N,operationId:e7(),parsed:a.parsed,reading:H0&&e0(n.binding.account,H0)?YJ(E,!0):void 0,now:J0,observedAt:J0,evidenceAt:J0,resetSource:a.resetSource});x0.enqueue(K0,h6)})}),f0=async(a)=>L6.finish(await AK(a,D,"event-stream")),Z6={id:E,receipt:S,migrated:x,owner:x0,probe:n,limited:!1,observeHttp:L6.observe,complete:()=>{if(L?.signal?.aborted||Z6.limited)return;O6("ws"),x0?.afterProbe(n,!0,Z6.limited)}},f4=F9(T??"",_3),P6=new Headers(g0?.headers),j6=E5({enabled:!["title","compaction","summary"].includes(o??""),includeSubagents:D3,headers:P6,body:g0?.body,sessionID:T}),i6=(a)=>EK(a,j6&&o?T:void 0);if(f4)F3.trace("cachekeep headers",{pid:process.pid,hasParent:P6.has("x-parent-session-id"),sessionKey:j6?.sessionKey,captured:Boolean(j6),affinity:P6.get("x-session-affinity"),opencodeSession:P6.get("x-opencode-session"),sessionId:P6.get("session-id")});let m4=()=>{if(!f4||!j6)return;let a=P6.get("chatgpt-account-id")??void 0;l8.track({sessionKey:j6.sessionKey,bodyText:j6.bodyText,accountId:E,isSubagent:j6.isSubagent,meta:{replayHeaders:j6.replayHeaders,chatgptAccountId:a,...a===void 0?{effectiveAccountId:MK(D)}:{},routingSessionId:T}})};if(h4&&M1){b4.debug("WS transport",{pid:process.pid,pathname:G6.pathname,accountId:E}),m4();let a=`stream:${e7()}`;a1.set(a,Z6);let J0=new Headers(g0?.headers);J0.set(u6.QUOTA_ACCOUNT_HEADER,a);let H0=()=>a1.delete(a);try{let K0=await h4(D6,{...g0,headers:J0},Y0?{kind:"auxiliary",agent:Y0}:{kind:"primary",record:(b0)=>{if(D0)P.record(D0,b0??d6)}});if(!K0.body)return H0(),i6(await L6.finish(K0));let h6=K0.body.getReader();return i6(await f0(new Response(new ReadableStream({async pull(b0){try{let T1=await h6.read();if(T1.done)H0(),b0.close();else b0.enqueue(T1.value)}catch(T1){H0(),b0.error(h8(T1,D))}},cancel(b0){return H0(),h6.cancel(b0)}}),{status:K0.status,statusText:K0.statusText,headers:K0.headers})))}catch(K0){throw H0(),h8(K0,D)}}if(D0&&!Y0)P.record(D0,d6);let F6=u6.withoutInternalHeaders(g0);if(typeof F6?.body!=="string")try{return await f0(L6.observe(await fetch(D6,F6)))}catch(a){throw h8(a,D)}m4(),b4.debug("HTTP transport",{pid:process.pid,pathname:G6.pathname,accountId:E});try{let a=await fetch(D6,F6);return await q4({sessionID:T,transport:"http",phase:"http",bodyText:F6.body,accountId:E,url:D6.toString(),method:F6.method,headers:F6.headers,status:a.status}),i6(await f0(L6.observe(a)))}catch(a){throw await q4({sessionID:T,transport:"http",phase:"http",bodyText:F6.body,accountId:E,url:D6.toString(),method:F6.method,headers:F6.headers,error:a instanceof Error?a.message:String(a)}),h8(a,D)}}function y4(B,L){if((L?.method??(B instanceof Request?B.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof L?.body!=="string")return!1;try{let M=B instanceof URL?B.toString():typeof B==="string"?B:B.url;return new URL(M).pathname.endsWith("/responses")}catch{return!1}}function GU(B){return e.peekMainForPolicy(B)?.quota}function S3(B,L){for(let D of[B?.primary?.checkedAt,B?.secondary?.checkedAt,B?.checkedAt,L])if(typeof D==="number"&&Number.isFinite(D))return D;return}function g4(B,L,D,M,E){let S=S3(B,L),R=S3(D),h=M===E&&D!=null&&(B===void 0||R!==void 0&&(S===void 0||R>S));return{quota:h?D:B,quotaCheckedAt:h?R:S,source:h?"file":"memory"}}function I3(B,L,D,M,E){let S=B?.quota,R=g4(S,B?.checkedAt,L,M,E),h=R.source,x=R.quota;if(!fK(x,D))return{exhausted:!1};let u=gK(x,D);if(!u)return{exhausted:!1};return{exhausted:!0,source:h,...u}}function b3(B,L){B6.debug("admission skip: exhausted account",{accountId:B,source:L.source,resetsAt:L.resetsAt})}function d8(B,L="killswitch",D,M){let E=Date.now(),S=M?M.main:e.getMain()?.quota,R=M?M.fallbacks:(B?.accounts??[]).filter((T)=>T.enabled!==!1&&n0(T)).map((T)=>({accountId:T.id,quota:e.getFallback(T.id)?.quota})),h=VK(S,R,E,z(B));if(L==="quota-unknown")h=jK;else if(L==="quota-exhausted"&&D!==void 0)h=Math.max(1,Math.ceil((D-E)/1000));else if(L==="mid-stream-rate-limit"&&D!==void 0){let T=Math.max(1,Math.ceil((D-E)/1000));h=Math.min(h,T)}let x=Math.floor(h/60),u=h%60,$0=L==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${x}m ${u}s.`:L==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${x}m ${u}s.`:L==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${x}m ${u}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${x}m ${u}s.`;return new Response(JSON.stringify({error:{message:$0,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(h)}})}function XJ(B){let L=B?.resetCreditsAvailable;return typeof L==="number"&&Number.isFinite(L)?L:void 0}async function zU(B){let L=z(B.storage),D=d1(L),M=Date.now(),E=e.peekMainForPolicy(B.mainAccountIdentity),S=g4(E?.quota,E?.checkedAt,B.sidebarState.main.quota,B.sidebarState.main.mainAccountId,B.mainAccountIdentity),R=D?c6(E?.quota,L,void 0,M):void 0,h=B.mainUnavailable?[]:[{accountId:"main",wireAccountId:B.mainAccountIdentity,access:B.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:U1(L),configuredOrder:0,resetCreditsApplicable:XJ(S.quota),killswitchPasses:R}],x=await V6.getUsableFallbackAccounts(B.storage);if(!B.storage)return h;for(let u of x){let $0=sY(u);if(!$0)continue;let T=B.sidebarState.fallbacks.find((G6)=>G6.id===u.id),o=e.peekFallbackForPolicy(u.id,u.accountId),Y0=g4(o?.quota,o?.checkedAt,T?.quota,T?.accountId,u.accountId),D0=D?c6(o?.quota,L,u.id,M):void 0;h.push({accountId:u.id,wireAccountId:u.accountId,access:$0,keepwarmAccountKey:u.id,fallback:u,quota:Y0.quota,quotaCheckedAt:Y0.quotaCheckedAt,reservePercent:U1(L,u.id),configuredOrder:h.length,resetCreditsApplicable:XJ(Y0.quota),killswitchPasses:D0})}return h}function k3(B,L,D,M,E){let S=d1(z(E))?B.killswitchPasses:void 0;if(B.accountId==="main"){let u=e.peekMainForPolicy(B.wireAccountId),$0=g4(u?.quota,u?.checkedAt,L.main.quota,L.main.mainAccountId,B.wireAccountId);return l7({quota:$0.quota,quotaCheckedAt:$0.quotaCheckedAt,status:D,now:M,killswitchPasses:S})}let R=L.fallbacks.find((u)=>u.id===B.accountId),h=e.peekFallbackForPolicy(B.accountId,B.wireAccountId),x=g4(h?.quota,h?.checkedAt,R?.quota,R?.accountId,B.wireAccountId);return l7({quota:x.quota,quotaCheckedAt:x.quotaCheckedAt,status:D,now:M,killswitchPasses:S})}function WU(B){return B.accountId==="main"?"main":B.keepwarmAccountKey}function x3(B){return e.isRateLimited(WU(B))}function $J(B){let L=B.candidates.filter((S)=>!x3(S)),D=new Map(L.map((S)=>[S.accountId,S])),M=new Set(B.excludeAccountIds),E=h3({vaultMode:!1,sessionId:B.sessionId,requestBytes:B.requestBytes,sidebarSnapshot:B.sidebarSnapshot,now:B.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:B.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(L.map((S)=>[S.accountId,S.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(L.map((S)=>[S.accountId,S.wireAccountId])),select:(S)=>{let R=L.filter((h)=>!M.has(h.accountId));if(R.length===0)return;return jW({candidates:R,pendingBytes:S,requestBytes:B.requestBytes,now:B.now,onEmptyWeightedSet:()=>{k6.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return E?D.get(E.accountId):void 0}function h3(B){let L=void 0,D=B.validPinnedAccountIds,M=pK(n1(B.sidebarSnapshot,z0),{sessionId:B.sessionId,requestBytes:B.requestBytes,now:B.now,validPinnedAccountIds:D,excludeAccountIds:B.excludeAccountIds,quotaCheckedAtByAccount:B.quotaCheckedAtByAccount,wireAccountIdByAccount:B.wireAccountIdByAccount,choose:(S)=>{let R=B.select(S);if(!R)return;return L={accountId:R.accountId,source:R.source,pendingBytes:S.get(R.accountId)??0},R}}),E=M.assignment;if(!B.persist)return E;if(L&&E?.accountId===L.accountId)k6.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:m6(B.sessionId),accountId:L.accountId,source:L.source,requestBytes:B.requestBytes,pendingBytes:L.pendingBytes});if(E&&M.next!==void 0){let S=B.vaultMode,R=m6(B.sessionId),h=nK(z0,R,E);l6.enqueue(`pin:${R}`,"sticky-pin",async()=>{await lK({sessionId:B.sessionId,assignment:E,validPinnedAccountIds:D},s0,{vaultMode:S,canWrite:()=>b.enrolled()===S}),h.persistedAt=Date.now()})}return E}async function KU(B,L){let D=await V6.getUsableFallbackAccounts(B),M=[];if(!B)return{current:[],retained:[],skipped:[]};for(let T of D){let o=sY(T);if(!o)continue;M.push({access:o,accountId:T.accountId,keepwarmAccountKey:T.id,quotaAccountId:T.id,fallback:T})}let E=M.filter((T)=>!e.isRateLimited(T.quotaAccountId)),S=z(B),R=d1(S)?E.filter((T)=>c6(e.peekFallbackForPolicy(T.quotaAccountId,T.accountId)?.quota,S,T.quotaAccountId,Date.now())):E,h=new Map(L.fallbacks.map((T)=>[T.id,{quota:T.quota,accountId:T.accountId}])),x=[],u=[],$0=Date.now();for(let T of R){let o=h.get(T.quotaAccountId),Y0=I3(e.peekFallbackForPolicy(T.quotaAccountId,T.accountId),o?.quota,$0,o?.accountId,T.accountId);if(Y0.exhausted)u.push({candidate:T,decision:Y0});else x.push(T)}return{current:R,retained:x,skipped:u}}function v3(B,L){if(B.retained.length===0&&!L)return B.current;for(let{candidate:D,decision:M}of B.skipped)b3(D.quotaAccountId,M);return B.retained}function y3(B,L){try{let D=l1(B.headers);s1(D,L.access,L.quotaAccountId,void 0,R4(B.headers))}catch{}}async function UU(B,L,D,M){for(let E of M){let S;try{S=await t1(B,L,E.access,E.accountId,E.keepwarmAccountKey)}catch(R){if((R instanceof Error||R instanceof DOMException)&&R.name==="AbortError")throw R;if(L?.signal?.aborted)throw R;throw k6.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:E.quotaAccountId}),R}if(!x8(S.status,z(D)))return V6.markUsed(E.fallback),{response:S,accessToken:E.access,quotaAccountId:E.quotaAccountId,activeId:E.keepwarmAccountKey};y3(S,E),S.body?.cancel().catch(()=>{})}return}async function HU(B,L,D,M,E){if(!y4(B,L))return{response:D};if(!E.length)return{response:D};let S=D,R;for(let h of E){let x;try{x=await t1(B,L,h.access,h.accountId,h.keepwarmAccountKey)}catch(u){if((u instanceof Error||u instanceof DOMException)&&u.name==="AbortError")throw u;if(L?.signal?.aborted)throw u;return k6.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:h.quotaAccountId}),{response:S,...R}}if(S.body?.cancel().catch(()=>{}),S=x,R={accessToken:h.access,accountId:h.quotaAccountId},!x8(x.status,z(M)))return V6.markUsed(h.fallback),{response:x,...R};y3(x,h)}return{response:S,...R}}if(y0){let B=[];for(let L of y0.accounts)if(n0(L))B.push(L);e.seedFallbacksFromAccounts(B)}if(!K3)if(K3=!0,x6(e).catch(()=>{}),Q1.then(()=>b.enrolled()?x6(e):void 0).catch(()=>{}),!b.enrolled()&&!await C0.active())uY=gY(m8({respectBackoff:!0})).catch((B)=>B6.warn("boot quota seed failed",{pid:process.pid,error:E4(B)}));else uY=Promise.resolve();y8.start(async()=>{if(await b.authority(),b.enrolled()){await x6(e);return}if(await C0.active()){let D=await OK(C0,await U(Q),()=>_K(X));if(D.length>0)await x6(e);let M=D.filter((E)=>!E.ok);if(M.length>0)B6.warn("background pool quota poll completed with failures",{pid:process.pid,failures:M});return}let L=(await DK(m8({readSidebarState:async()=>(await A1.read()).state}))).filter((D)=>!D.ok);if(L.length>0)B6.warn("background quota refresh completed with failures",{pid:process.pid,failures:L})},(B)=>{B6.warn("background quota refresh failed",{pid:process.pid,error:B instanceof Error?B.message:String(B)})});async function QJ(B,L,D,M,E,S){let R=performance.now()+Q8,h=await d0.forRequest(R),x=b.enrolled(),u=x?R:void 0,$0=d0.bindings(),T=z(D).routing?.mode??"main-first",o=x?void 0:C0.peek().rows.find((n)=>n.id==="main"),Y0=!o&&!x?await k():void 0,D0=!o&&Y0?.type==="oauth"&&c0(Y0),G6=!o&&!x&&await fY(Q,Y0);if(S===x4)k4=o?.identity;let D6=await A1.get(),M1=X3(B,L).get(v8),N6=M1&&!["title","compaction","summary"].includes(M1)&&typeof L?.body==="string"?(()=>{try{return typeof JSON.parse(L.body).model==="string"?"primary":"auxiliary"}catch{return"auxiliary"}})():"auxiliary",d6=new URL(B instanceof Request?B.url:String(B)).pathname,{response:g0,servedId:x0}=await rz({configPath:X,source:C0,rateLimitMarks:()=>d0.marks(),limitPolicy:{pending:t,accountKey:(n)=>d0.accountKey(n),activity:()=>M?d0.activity.get(M):void 0,currentAccountKey:()=>M?rY(M):void 0,owner:()=>d0.owner()},...x?{vault:{routes:()=>b.routes(),awaitRoster:async()=>{if(u!==void 0)await G8(u,()=>b.awaitRequestRoster())},noRouteCause:()=>yY(b),send:(n,M0)=>b.send(n,M0,{site:"model",...L?.signal?{signal:L.signal}:{}}),requestReading:(n)=>b.requestReading(n)}}:{},storage:D,mode:T,sessionId:M,requestKind:JSON.stringify([d6,N6]),primary:N6==="primary",waitForReset:z(D).waitForReset,body:typeof L?.body==="string"?L.body:void 0,replayable:y4(B,L),now:Date.now,send:(n,M0,w0)=>t1(B,L,M0,n.identity,n.id,w0,h,$0.find((O6)=>O6.account.accountId===n.id),!0,u),recordQuota:(n,M0,w0,O6)=>{try{let L6=l1(n.headers),f0=R4(n.headers);if(!M0.row){if(O6)b.reportUsage(M0.id,{headers:n.headers},O6),b.recordSnapshot(M0.id,L6,f0,O6).then(R3);return}s1(L6,w0,M0.id==="main"?void 0:M0.id,M0.id==="main"?M0.identity:void 0,f0)}catch{}},placePin:(n)=>h3({...n,sidebarSnapshot:D6,vaultMode:x}),blocked:(n,M0,w0)=>{if(n.reason==="no-credential"){if(G6&&!x7(w0))throw Error(W4);return new Response(x7(w0)?vY(w0,b.name):i1[D0?"missing-main":w0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return d8(D,n.reason,n.resetAtMs,M0)},resetCredits:(n)=>XJ(n==="main"?e.peekMainForPolicy(o?.identity)?.quota:e.peekFallbackForPolicy(n)?.quota),isAbort:(n)=>(n instanceof Error||n instanceof DOMException)&&n.name==="AbortError"||Boolean(L?.signal?.aborted),creditsServing:eK,log:k6});return JJ(M,E,x0,T,x?b.routes().map((n)=>({id:n.id})):D?.accounts,n1(D6,z0),x),g0}return I=!0,{apiKey:WF,async fetch(B,L){let D=await b.authority(),M=X3(B,L),E=bY(M),S=M.get("x-parent-session-id")?.trim()||void 0,R=D!=="local"?await H(Q):await N3(),h=z(R);if(D!=="local")return L=await $3(B,L),QJ(B,L,R,E,S,++x4);let x=await k();if(await b.authority()!=="local")return L=await $3(B,L),QJ(B,L,R,E,S,++x4);let u=++x4;if(x.type!=="oauth")return M.delete(v8),fetch(B,{...L,headers:M});L=await $3(B,L);let $0=(await C0.current()).active;if(t0(x)&&$0)return QJ(B,L,R,E,S,u);if($0)b.assertHostSlot(x);let T="",o=!1,Y0,D0=t0(x);if(Q6?.migrated()&&!D0&&x.refresh?.trim()&&W3(x).kind==="real")Q6.noticeRealSlot(x.refresh);let G6=async(J0=R)=>{if(D0=!0,Y0=await E3(J0),Y0)T=Y0.token;else T="",o=!0,k6.warn("main account in the pool has no usable token",{pid:process.pid})};if(D0)await G6();else if(c0(x))o=!0;else{if(!x.access||(x.expires??0)<Date.now()){f8.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(x.access),expiresInMs:x.expires?x.expires-Date.now():void 0});try{let J0=await tY();x.access=J0.access,x.refresh=J0.refresh,x.expires=J0.expires}catch(J0){if(CY(J0))throw J0;if(J0 instanceof V1)await G6(await U(Q))}}if(!D0)T=x.access??""}let D6=D0?OJ(R):R,M1=x,N6=Y0?.account.accountId??(D0?void 0:M1.accountId)??(T?C6(R6(T)??{}):void 0);if(u===x4)k4=N6;let d6=h.routing?.mode??"main-first",g0=await A1.get(),x0=g0.state;if(d6==="sticky-balanced"&&E&&y4(B,L)&&typeof L?.body==="string"){let J0=Buffer.byteLength(L.body,"utf8"),H0=await zU({storage:D6,sidebarState:x0,primaryAccess:T,mainAccountIdentity:N6,mainUnavailable:o}),K0=$J({sessionId:E,requestBytes:J0,candidates:H0,sidebarSnapshot:g0,now:Date.now()});if(K0){let h6=x3(K0)?{action:"migrate",reason:"exhausted"}:k3(K0,x0,void 0,Date.now(),R);if(h6.action==="migrate"){let z6=$J({sessionId:E,requestBytes:J0,candidates:H0,sidebarSnapshot:g0,excludeAccountIds:[K0.accountId],now:Date.now()});if(z6)k6.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:m6(E),fromAccountId:K0.accountId,toAccountId:z6.accountId,reason:h6.reason}),K0=z6}let b0=await t1(B,L,K0.access,K0.wireAccountId,K0.keepwarmAccountKey),T1=(z6,R1)=>{try{let BU=l1(z6.headers);s1(BU,R1.access,R1.accountId==="main"?void 0:R1.accountId,R1.accountId==="main"?R1.wireAccountId:void 0,R4(z6.headers))}catch{}};T1(b0,K0);let g3=k3(K0,x0,b0.status,Date.now(),R);if((b0.status===401||b0.status===403||b0.status===429)&&g3.action==="migrate"){let z6=$J({sessionId:E,requestBytes:J0,candidates:H0,sidebarSnapshot:g0,excludeAccountIds:[K0.accountId],now:Date.now()});if(z6){k6.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:m6(E),fromAccountId:K0.accountId,toAccountId:z6.accountId,reason:g3.reason});let R1=b0;b0=await t1(B,L,z6.access,z6.wireAccountId,z6.keepwarmAccountKey),R1.body?.cancel().catch(()=>{}),K0=z6,T1(b0,K0)}}if(K0.fallback&&!x8(b0.status,h))V6.markUsed(K0.fallback);return JJ(E,S,K0.accountId,d6,R?.accounts,n1(g0,z0)),b0}}let n=I3(e.peekMainForPolicy(N6),x0.main.quota,Date.now(),x0.main.mainAccountId,N6),M0=d1(h)&&!c6(GU(N6),h,void 0,Date.now()),w0=e.isRateLimited("main"),O6,L6=()=>{return O6??=KU(D6,x0),O6},f0,Z6,f4=!1,P6;if(d6==="fallback-first"&&y4(B,L)){f4=!0;let J0=await L6();P6=v3(J0,!M0&&!w0&&!n.exhausted);let H0=await UU(B,L,R,P6);if(H0)f0=H0.response,Z6={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!f0){let J0=n.exhausted&&y4(B,L)&&(await L6()).retained.length>0;if(M0||w0||J0){let H0=M0?"killswitch":w0?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&n.exhausted)b3("main",n);k6.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),f0=d8(R,H0,H0==="quota-exhausted"&&n.exhausted?n.resetAtMs:w0?e.rateLimitedUntil("main"):void 0)}else f0=o?new Response(null,{status:401}):await t1(B,L,T,N6,"main")}let j6=Boolean(Z6),i6=f0,m4=Z6?.accessToken??T,F6=Z6?.accountId,a=Z6?.activeId??"main";if(!Z6&&!f4&&x8(f0.status,h)){k6.debug("reactive fallback triggered",{pid:process.pid,status:f0.status}),P6??=v3(await L6(),!1);let J0=await HU(B,L,f0,R,P6),H0=J0.response;if(H0!==f0){if(j6=!0,i6=H0,m4=J0.accessToken??T,F6=J0.accountId,J0.accountId)a=J0.accountId}}if(D0&&o&&!j6&&await fY(Q,await k()))throw Error(W4);try{let J0=l1(i6.headers);if(j6)s1(J0,m4,F6,void 0,R4(i6.headers));else s1(J0,T,void 0,N6,R4(i6.headers))}catch{}return JJ(E,S,a,d6,R?.accounts,n1(g0,z0)),i6}}},methods:dY},"chat.headers":async(k,g)=>{if(k.model.providerID!=="openai")return;if(g.headers.originator="opencode",g.headers["User-Agent"]=`${zK(f6)} (${Y3.platform()} ${Y3.release()}; ${Y3.arch()})`,g.headers["session-id"]=k.sessionID,I)g.headers[v8]=k.agent;if(y&&k.agent==="title")g.headers[u6.TITLE_HEADER]="true"},"chat.params":async(k,g)=>{if(k.model.providerID!=="openai")return;g.maxOutputTokens=void 0},config:async(k)=>{U0("commands").info("registering commands",{existing:Object.keys(k.command??{}).length,pid:process.pid}),k.command={...k.command??{},[W1]:{template:W1,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(k)=>{if(U0("commands").info("command hook entered",{command:k.command,hasCmdCtx:q!==null,pid:process.pid}),k.command!==W1)return;if(!q)U0("commands").warn("command rejected: context not loaded",{command:k.command,pid:process.pid}),await I4(k.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),JK();let g=await D5(q,k.sessionID);if(MJ(k.sessionID))L9(g,k.sessionID);else await I4(k.sessionID,P5(g.menu));JK()}}}var OF=async(Y)=>{return DF(Y)},BC={id:"cortexkit-openai-auth",server:OF};
60
+ export{o4 as d,_6 as e,E$ as f,M6 as g,G9 as h,T6 as i,DJ as j,W4 as k,EJ as l,SD as m,L9 as n,N5 as o,D5 as p,O5 as q,Q8 as r,hJ as s,V4 as t,vJ as u,gJ as v,q4 as w,u1 as x,OY as y,_z as z,Pz as A,Rz as B,Nj as C,tz as D,ez as E,XW as F,HW as G,S8 as H,v0 as I,MW as J,n7 as K,o7 as L,wW as M,SW as N,r7 as O,SY as P,IY as Q,gj as R,bY as S,zF as T,WC as U,KF as V,UF as W,KC as X,UC as Y,HC as Z,FF as _,DF as $,OF as aa,BC as ba};