@cortexkit/opencode-openai-auth 1.23.1 → 1.23.3

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 (226) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/{index-7hy72nfy.js → index-9kges8jy.js} +2 -2
  3. package/dist/index-ekt6aq17.js +60 -0
  4. package/dist/index-nd2ks7er.js +2 -0
  5. package/dist/{index-p81hxfe6.js → index-vf4nn20q.js} +1 -1
  6. package/dist/{index-bd18sfjj.js → index-x00sxt2w.js} +10 -10
  7. package/dist/{index-3ya2s179.js → index-xkngfyvc.js} +1 -1
  8. package/dist/index.d.ts +3 -2
  9. package/dist/index.js +1 -1
  10. package/dist/{runtime-layout-B07ApQZL.d.ts → internal-DacVgEWs.d.ts} +86 -663
  11. package/dist/rpc/port-file.js +1 -1
  12. package/dist/runtime-layout-Dcbj_Rq3.d.ts +650 -0
  13. package/dist/{sidebar-state--OTpRzFd.d.ts → sidebar-state-L--CdbLi.d.ts} +4 -15
  14. package/dist/sidebar-state.d.ts +1 -1
  15. package/dist/sidebar-state.js +1 -1
  16. package/dist/tui.d.ts +5 -2
  17. package/dist/v2/server.d.ts +2 -1
  18. package/dist/v2/server.js +4 -4
  19. package/package.json +1 -1
  20. package/src/tui-compiled/raw/shared/054118b2705fdc20-ansi.js +98 -0
  21. package/src/tui-compiled/raw/shared/0895e780489c494d-window.js +33 -0
  22. package/src/tui-compiled/raw/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  23. package/src/tui-compiled/raw/shared/0c9533222cb4380c-namespace.js +224 -0
  24. package/src/tui-compiled/raw/shared/112607e46a5b5f58-accounts.js +393 -0
  25. package/src/tui-compiled/raw/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  26. package/src/tui-compiled/raw/shared/1547bd74f4214d2d-index.js +28 -0
  27. package/src/tui-compiled/raw/shared/1567207f323dc733-codex-http.js +44 -0
  28. package/src/tui-compiled/raw/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  29. package/src/tui-compiled/raw/shared/18df43cab4563acf-families.js +149 -0
  30. package/src/tui-compiled/raw/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  31. package/src/tui-compiled/raw/shared/1afd446e190ef85c-vault-messages.js +12 -0
  32. package/src/tui-compiled/raw/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  33. package/src/tui-compiled/raw/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  34. package/src/tui-compiled/raw/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  35. package/src/tui-compiled/raw/shared/22b2bce42f2d6806-handle.js +10 -0
  36. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  37. package/src/tui-compiled/raw/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  38. package/src/tui-compiled/raw/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  39. package/src/tui-compiled/raw/shared/2bb681e99c2721d7-registry.js +538 -0
  40. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +13 -20
  41. package/src/tui-compiled/raw/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  42. package/src/tui-compiled/raw/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  43. package/src/tui-compiled/raw/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  44. package/src/tui-compiled/raw/shared/3b31b36bf0877602-wording.js +120 -0
  45. package/src/tui-compiled/raw/shared/3c4c1a2d3fc92726-failure.js +59 -0
  46. package/src/tui-compiled/raw/shared/3dfe71eec6e0487d-presets.js +240 -0
  47. package/src/tui-compiled/raw/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  48. package/src/tui-compiled/raw/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  49. package/src/tui-compiled/raw/shared/4adf46e07e025363-axes.js +7 -0
  50. package/src/tui-compiled/raw/shared/4ba847b77580b1eb-confirm.js +21 -0
  51. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +48 -36
  52. package/src/tui-compiled/raw/shared/5018d4665e969588-limit-policy.js +159 -0
  53. package/src/tui-compiled/raw/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  54. package/src/tui-compiled/raw/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  55. package/src/tui-compiled/raw/shared/5d806e1a305d14f5-commands.js +879 -0
  56. package/src/tui-compiled/raw/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  57. package/src/tui-compiled/raw/shared/63c1ee7e70e85e8d-vault.js +1 -0
  58. package/src/tui-compiled/raw/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  59. package/src/tui-compiled/raw/shared/66937534c260d20b-stable-json.js +11 -0
  60. package/src/tui-compiled/raw/shared/7056acef1b021f19-bridge.js +10 -0
  61. package/src/tui-compiled/raw/shared/72d2ca42883809b4-marker.js +107 -0
  62. package/src/tui-compiled/raw/shared/775431e21f469203-record.js +3 -0
  63. package/src/tui-compiled/raw/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  64. package/src/tui-compiled/raw/shared/7b2a0471b29e4f5e-wake.js +47 -0
  65. package/src/tui-compiled/raw/shared/7b5d6afff4ff32b9-select.js +159 -0
  66. package/src/tui-compiled/raw/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  67. package/src/tui-compiled/raw/shared/7c98bde36aad4819-input-transformations.js +34 -0
  68. package/src/tui-compiled/raw/shared/7fb0418303f20a10-index.js +3 -0
  69. package/src/tui-compiled/raw/shared/806e12ccbad34388-pi-wait.js +51 -0
  70. package/src/tui-compiled/raw/shared/81ae201b724cac14-menu.js +73 -0
  71. package/src/tui-compiled/raw/shared/8349ed25dc629e97-scope.js +10 -0
  72. package/src/tui-compiled/raw/shared/86da3379973780b9-limit-provenance.js +60 -0
  73. package/src/tui-compiled/raw/shared/8aba66ed486d30a7-decide.js +425 -0
  74. package/src/tui-compiled/raw/shared/8c0c8df25a5dca1f-manager.js +735 -0
  75. package/src/tui-compiled/raw/shared/8c42bbec02f59636-vault-routing.js +212 -0
  76. package/src/tui-compiled/raw/shared/8ca6175bfae53e13-envelope.js +123 -0
  77. package/src/tui-compiled/raw/shared/8d0245e41049d83f-header-classifier.js +121 -0
  78. package/src/tui-compiled/raw/shared/9c162809179c7560-login.js +89 -0
  79. package/src/tui-compiled/raw/shared/a1f495296a4b756f-frame-turn.js +72 -0
  80. package/src/tui-compiled/raw/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  81. package/src/tui-compiled/raw/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  82. package/src/tui-compiled/raw/shared/adc5eeb5a8d28280-persistence.js +9 -0
  83. package/src/tui-compiled/raw/shared/b301c79e6378d1fb-vault.js +678 -0
  84. package/src/tui-compiled/raw/shared/b3c11de5f36e617a-reset.js +44 -0
  85. package/src/tui-compiled/raw/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  86. package/src/tui-compiled/raw/shared/bd4aef685681048c-duration.js +20 -0
  87. package/src/tui-compiled/raw/shared/bd5977eca210d2b8-index.js +662 -0
  88. package/src/tui-compiled/raw/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  89. package/src/tui-compiled/raw/shared/c66495424ad84aee-hold.js +25 -0
  90. package/src/tui-compiled/raw/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  91. package/src/tui-compiled/raw/shared/c9340fb545c4e5de-internal.js +73 -0
  92. package/src/tui-compiled/raw/shared/c954c6447b7b9b64-activity.js +52 -0
  93. package/src/tui-compiled/raw/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  94. package/src/tui-compiled/raw/shared/cec39ccddab4fe9c-labels.js +11 -0
  95. package/src/tui-compiled/raw/shared/cef0f2346957e83c-index.js +552 -0
  96. package/src/tui-compiled/raw/shared/cf7dedf24f902d68-dump-size.js +41 -0
  97. package/src/tui-compiled/raw/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  98. package/src/tui-compiled/raw/shared/d5b268767d330507-doctor.js +81 -0
  99. package/src/tui-compiled/raw/shared/d7ac5ca41f49121b-index.js +12 -0
  100. package/src/tui-compiled/raw/shared/d7fa77560855dee2-jitter.js +9 -0
  101. package/src/tui-compiled/raw/shared/de7f7d8803624369-path.js +31 -0
  102. package/src/tui-compiled/raw/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  103. package/src/tui-compiled/raw/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  104. package/src/tui-compiled/raw/shared/e2ae081583adfce3-dump.js +80 -0
  105. package/src/tui-compiled/raw/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  106. package/src/tui-compiled/raw/shared/e5229952fc12f647-codex-models.js +34 -0
  107. package/src/tui-compiled/raw/shared/e8fda84e90176436-uuid-v7.js +13 -0
  108. package/src/tui-compiled/raw/shared/ea56007991dbf068-terminal.js +19 -0
  109. package/src/tui-compiled/raw/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  110. package/src/tui-compiled/raw/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  111. package/src/tui-compiled/raw/shared/f1012265b3a768c7-merge-laws.js +31 -0
  112. package/src/tui-compiled/raw/shared/f2ca864fe967415a-cache-policy.js +198 -0
  113. package/src/tui-compiled/raw/shared/f317a4740f9d76f8-identity.js +21 -0
  114. package/src/tui-compiled/raw/shared/f607353c4126272a-routing-wait.js +19 -0
  115. package/src/tui-compiled/raw/shared/f6189f5c9aee31eb-decision.js +55 -0
  116. package/src/tui-compiled/raw/shared/f6d728f5e601f98b-request-history.js +120 -0
  117. package/src/tui-compiled/raw/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  118. package/src/tui-compiled/raw/shared/fda579e5a0a54165-codex-effort.js +60 -0
  119. package/src/tui-compiled/raw/sidebar-state.js +54 -4
  120. package/src/tui-compiled/raw/tui/v2-dialog.js +1 -1
  121. package/src/tui-compiled/raw/tui.tsx +27 -5
  122. package/src/tui-compiled/runtime/shared/054118b2705fdc20-ansi.js +98 -0
  123. package/src/tui-compiled/runtime/shared/0895e780489c494d-window.js +33 -0
  124. package/src/tui-compiled/runtime/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  125. package/src/tui-compiled/runtime/shared/0c9533222cb4380c-namespace.js +224 -0
  126. package/src/tui-compiled/runtime/shared/112607e46a5b5f58-accounts.js +393 -0
  127. package/src/tui-compiled/runtime/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  128. package/src/tui-compiled/runtime/shared/1547bd74f4214d2d-index.js +28 -0
  129. package/src/tui-compiled/runtime/shared/1567207f323dc733-codex-http.js +44 -0
  130. package/src/tui-compiled/runtime/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  131. package/src/tui-compiled/runtime/shared/18df43cab4563acf-families.js +149 -0
  132. package/src/tui-compiled/runtime/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  133. package/src/tui-compiled/runtime/shared/1afd446e190ef85c-vault-messages.js +12 -0
  134. package/src/tui-compiled/runtime/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  135. package/src/tui-compiled/runtime/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  136. package/src/tui-compiled/runtime/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  137. package/src/tui-compiled/runtime/shared/22b2bce42f2d6806-handle.js +10 -0
  138. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  139. package/src/tui-compiled/runtime/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  140. package/src/tui-compiled/runtime/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  141. package/src/tui-compiled/runtime/shared/2bb681e99c2721d7-registry.js +538 -0
  142. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +13 -20
  143. package/src/tui-compiled/runtime/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  144. package/src/tui-compiled/runtime/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  145. package/src/tui-compiled/runtime/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  146. package/src/tui-compiled/runtime/shared/3b31b36bf0877602-wording.js +120 -0
  147. package/src/tui-compiled/runtime/shared/3c4c1a2d3fc92726-failure.js +59 -0
  148. package/src/tui-compiled/runtime/shared/3dfe71eec6e0487d-presets.js +240 -0
  149. package/src/tui-compiled/runtime/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  150. package/src/tui-compiled/runtime/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  151. package/src/tui-compiled/runtime/shared/4adf46e07e025363-axes.js +7 -0
  152. package/src/tui-compiled/runtime/shared/4ba847b77580b1eb-confirm.js +21 -0
  153. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +48 -36
  154. package/src/tui-compiled/runtime/shared/5018d4665e969588-limit-policy.js +159 -0
  155. package/src/tui-compiled/runtime/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  156. package/src/tui-compiled/runtime/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  157. package/src/tui-compiled/runtime/shared/5d806e1a305d14f5-commands.js +879 -0
  158. package/src/tui-compiled/runtime/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  159. package/src/tui-compiled/runtime/shared/63c1ee7e70e85e8d-vault.js +1 -0
  160. package/src/tui-compiled/runtime/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  161. package/src/tui-compiled/runtime/shared/66937534c260d20b-stable-json.js +11 -0
  162. package/src/tui-compiled/runtime/shared/7056acef1b021f19-bridge.js +10 -0
  163. package/src/tui-compiled/runtime/shared/72d2ca42883809b4-marker.js +107 -0
  164. package/src/tui-compiled/runtime/shared/775431e21f469203-record.js +3 -0
  165. package/src/tui-compiled/runtime/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  166. package/src/tui-compiled/runtime/shared/7b2a0471b29e4f5e-wake.js +47 -0
  167. package/src/tui-compiled/runtime/shared/7b5d6afff4ff32b9-select.js +159 -0
  168. package/src/tui-compiled/runtime/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  169. package/src/tui-compiled/runtime/shared/7c98bde36aad4819-input-transformations.js +34 -0
  170. package/src/tui-compiled/runtime/shared/7fb0418303f20a10-index.js +3 -0
  171. package/src/tui-compiled/runtime/shared/806e12ccbad34388-pi-wait.js +51 -0
  172. package/src/tui-compiled/runtime/shared/81ae201b724cac14-menu.js +73 -0
  173. package/src/tui-compiled/runtime/shared/8349ed25dc629e97-scope.js +10 -0
  174. package/src/tui-compiled/runtime/shared/86da3379973780b9-limit-provenance.js +60 -0
  175. package/src/tui-compiled/runtime/shared/8aba66ed486d30a7-decide.js +425 -0
  176. package/src/tui-compiled/runtime/shared/8c0c8df25a5dca1f-manager.js +735 -0
  177. package/src/tui-compiled/runtime/shared/8c42bbec02f59636-vault-routing.js +212 -0
  178. package/src/tui-compiled/runtime/shared/8ca6175bfae53e13-envelope.js +123 -0
  179. package/src/tui-compiled/runtime/shared/8d0245e41049d83f-header-classifier.js +121 -0
  180. package/src/tui-compiled/runtime/shared/9c162809179c7560-login.js +89 -0
  181. package/src/tui-compiled/runtime/shared/a1f495296a4b756f-frame-turn.js +72 -0
  182. package/src/tui-compiled/runtime/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  183. package/src/tui-compiled/runtime/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  184. package/src/tui-compiled/runtime/shared/adc5eeb5a8d28280-persistence.js +9 -0
  185. package/src/tui-compiled/runtime/shared/b301c79e6378d1fb-vault.js +678 -0
  186. package/src/tui-compiled/runtime/shared/b3c11de5f36e617a-reset.js +44 -0
  187. package/src/tui-compiled/runtime/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  188. package/src/tui-compiled/runtime/shared/bd4aef685681048c-duration.js +20 -0
  189. package/src/tui-compiled/runtime/shared/bd5977eca210d2b8-index.js +662 -0
  190. package/src/tui-compiled/runtime/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  191. package/src/tui-compiled/runtime/shared/c66495424ad84aee-hold.js +25 -0
  192. package/src/tui-compiled/runtime/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  193. package/src/tui-compiled/runtime/shared/c9340fb545c4e5de-internal.js +73 -0
  194. package/src/tui-compiled/runtime/shared/c954c6447b7b9b64-activity.js +52 -0
  195. package/src/tui-compiled/runtime/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  196. package/src/tui-compiled/runtime/shared/cec39ccddab4fe9c-labels.js +11 -0
  197. package/src/tui-compiled/runtime/shared/cef0f2346957e83c-index.js +552 -0
  198. package/src/tui-compiled/runtime/shared/cf7dedf24f902d68-dump-size.js +41 -0
  199. package/src/tui-compiled/runtime/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  200. package/src/tui-compiled/runtime/shared/d5b268767d330507-doctor.js +81 -0
  201. package/src/tui-compiled/runtime/shared/d7ac5ca41f49121b-index.js +12 -0
  202. package/src/tui-compiled/runtime/shared/d7fa77560855dee2-jitter.js +9 -0
  203. package/src/tui-compiled/runtime/shared/de7f7d8803624369-path.js +31 -0
  204. package/src/tui-compiled/runtime/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  205. package/src/tui-compiled/runtime/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  206. package/src/tui-compiled/runtime/shared/e2ae081583adfce3-dump.js +80 -0
  207. package/src/tui-compiled/runtime/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  208. package/src/tui-compiled/runtime/shared/e5229952fc12f647-codex-models.js +34 -0
  209. package/src/tui-compiled/runtime/shared/e8fda84e90176436-uuid-v7.js +13 -0
  210. package/src/tui-compiled/runtime/shared/ea56007991dbf068-terminal.js +19 -0
  211. package/src/tui-compiled/runtime/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  212. package/src/tui-compiled/runtime/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  213. package/src/tui-compiled/runtime/shared/f1012265b3a768c7-merge-laws.js +31 -0
  214. package/src/tui-compiled/runtime/shared/f2ca864fe967415a-cache-policy.js +198 -0
  215. package/src/tui-compiled/runtime/shared/f317a4740f9d76f8-identity.js +21 -0
  216. package/src/tui-compiled/runtime/shared/f607353c4126272a-routing-wait.js +19 -0
  217. package/src/tui-compiled/runtime/shared/f6189f5c9aee31eb-decision.js +55 -0
  218. package/src/tui-compiled/runtime/shared/f6d728f5e601f98b-request-history.js +120 -0
  219. package/src/tui-compiled/runtime/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  220. package/src/tui-compiled/runtime/shared/fda579e5a0a54165-codex-effort.js +60 -0
  221. package/src/tui-compiled/runtime/sidebar-state.js +54 -4
  222. package/src/tui-compiled/runtime/tui/v2-dialog.js +1 -1
  223. package/src/tui-compiled/runtime/tui.js +11 -4
  224. package/dist/index-0p8r7cpy.js +0 -60
  225. package/dist/index-px1t650b.js +0 -2
  226. package/dist/map-D5PHhv4z.d.ts +0 -72
@@ -0,0 +1,879 @@
1
+ import { VAULT_HOST_STATUS } from "./e8d3c8da776ef9cd-index.js";
2
+ import {
3
+ CommandError,
4
+ createCommandMenu
5
+ } from "./dbef697d1df1cd84-index.js";
6
+ import {
7
+ DEFAULT_KILLSWITCH_THRESHOLDS,
8
+ getKillswitchThresholdsForAccount,
9
+ isSafeResetAccountKey,
10
+ KILLSWITCH_FLOORS_SCHEMA
11
+ } from "./dbc61cd405941828-accounts.js";
12
+ import { createLogger } from "./d669d72c40e9e116-logger.js";
13
+ import { whamUsageFn } from "./85512cc5263ba259-provider.js";
14
+ import {
15
+ countEligibleResetCredits,
16
+ evaluateResetPrecondition,
17
+ listResetCredits,
18
+ ResetCreditError,
19
+ ResetRedemptionError,
20
+ resetWindowIsExhausted,
21
+ runResetCreditRedemption,
22
+ selectCreditToSpend
23
+ } from "./e44ba1b3a9903f5d-reset-credits.js";
24
+ import { getSettingsDecision } from "./9865a4fa45882c6f-settings-decisions.js";
25
+ import { isRecord } from "./775431e21f469203-record.js";
26
+ import {
27
+ vaultApprovalInstructions,
28
+ vaultConnectOutcome,
29
+ vaultEnrollmentLine
30
+ } from "./b301c79e6378d1fb-vault.js";
31
+ import {
32
+ VAULT_LOCAL_ACTION_REFUSAL,
33
+ vaultAccountName
34
+ } from "./aa7fb10d77a2cccd-vault-account-menu.js";
35
+ import {
36
+ createVaultCommandMenu,
37
+ menuStore,
38
+ withQuotaSectionCredits
39
+ } from "./c6a67b836bd5afcd-vault-command-menu.js";
40
+ import { vaultEmptyAccessHint } from "./1afd446e190ef85c-vault-messages.js";
41
+ export const OPENAI_COMMAND_NAME = "openai", OPENAI_MENU_TITLE = "OpenAI accounts";
42
+ const MAIN_ROW_ID = "main", MAIN_ACCOUNT_REFUSAL = "that account is already your main account, so it was not added again", log = createLogger("commands"), PROTOTYPE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
43
+ export function killswitchInFloors(block, rosterIds) {
44
+ const legacy = {
45
+ version: 1,
46
+ accounts: [],
47
+ killswitch: block
48
+ }, named = isRecord(block.accounts) ? Object.keys(block.accounts) : [], accounts = {};
49
+ for (const id of new Set([MAIN_ROW_ID, ...rosterIds, ...named])) {
50
+ if (PROTOTYPE_KEYS.has(id))
51
+ continue;
52
+ const floors = getKillswitchThresholdsForAccount(legacy, id === MAIN_ROW_ID ? void 0 : id);
53
+ accounts[id] = { primary: floors.primary, secondary: floors.secondary };
54
+ }
55
+ const fallback = getKillswitchThresholdsForAccount(legacy, void 0), next = { ...block };
56
+ delete next.main;
57
+ next.accounts = accounts;
58
+ next.defaults = { primary: fallback.primary, secondary: fallback.secondary };
59
+ next.schema = KILLSWITCH_FLOORS_SCHEMA;
60
+ return next;
61
+ }
62
+ export function killswitchWithDefaultFloors(block, rosterIds) {
63
+ const accounts = isRecord(block.accounts) ? { ...block.accounts } : {};
64
+ for (const id of new Set([MAIN_ROW_ID, ...rosterIds])) {
65
+ if (PROTOTYPE_KEYS.has(id) || Object.hasOwn(accounts, id))
66
+ continue;
67
+ accounts[id] = {
68
+ primary: DEFAULT_KILLSWITCH_THRESHOLDS.primary,
69
+ secondary: DEFAULT_KILLSWITCH_THRESHOLDS.secondary
70
+ };
71
+ }
72
+ const defaults = isRecord(block.defaults) ? block.defaults : {
73
+ primary: DEFAULT_KILLSWITCH_THRESHOLDS.primary,
74
+ secondary: DEFAULT_KILLSWITCH_THRESHOLDS.secondary
75
+ };
76
+ return { ...block, accounts, defaults, schema: KILLSWITCH_FLOORS_SCHEMA };
77
+ }
78
+ export function migrateLegacySettings(settings, rosterIds) {
79
+ let changed = !1;
80
+ if (isRecord(settings.cachekeep)) {
81
+ settings.cacheKeep = {
82
+ ...settings.cachekeep,
83
+ ...isRecord(settings.cacheKeep) ? settings.cacheKeep : {}
84
+ };
85
+ delete settings.cachekeep;
86
+ changed = !0;
87
+ }
88
+ const killswitch = settings.killswitch;
89
+ if (isRecord(killswitch) && killswitch.schema !== KILLSWITCH_FLOORS_SCHEMA) {
90
+ settings.killswitch = killswitchInFloors(killswitch, rosterIds);
91
+ changed = !0;
92
+ }
93
+ return changed;
94
+ }
95
+ async function rosterIdsOf(store) {
96
+ const load = await store.read();
97
+ return load.status === "ready" ? load.rows.map((row) => row.id) : [];
98
+ }
99
+ export function withSettingsMigration(store, configPath) {
100
+ if (configPath && getSettingsDecision(configPath) === "shared")
101
+ return store;
102
+ const readSettings = async () => {
103
+ const read = await store.readSettings();
104
+ if (read.status === "error")
105
+ return read;
106
+ const settings = structuredClone(read.settings);
107
+ migrateLegacySettings(settings, await rosterIdsOf(store));
108
+ return { ...read, settings };
109
+ }, updateSettings = async (mutator, options) => {
110
+ const ids = await rosterIdsOf(store);
111
+ return store.updateSettings(async (settings) => {
112
+ migrateLegacySettings(settings, ids);
113
+ const next = await mutator(settings) ?? settings;
114
+ if (isRecord(next.killswitch) && next.killswitch.schema !== KILLSWITCH_FLOORS_SCHEMA)
115
+ next.killswitch = killswitchWithDefaultFloors(next.killswitch, ids);
116
+ return next;
117
+ }, options);
118
+ };
119
+ return new Proxy(store, {
120
+ get(target, property) {
121
+ if (property === "readSettings")
122
+ return readSettings;
123
+ if (property === "updateSettings")
124
+ return updateSettings;
125
+ const value = Reflect.get(target, property, target);
126
+ return typeof value === "function" ? value.bind(target) : value;
127
+ }
128
+ });
129
+ }
130
+ export function withAccountRules(store, rules) {
131
+ const locksFor = (id, given) => rules.rowLocks ? rules.rowLocks(id) : given, withLocks = (id, options) => {
132
+ const extraLocks = locksFor(id, options?.extraLocks);
133
+ return { ...options ?? {}, ...extraLocks ? { extraLocks } : {} };
134
+ }, replace = (id, credential, identity, options) => store.replace(id, credential, identity, withLocks(id, options)), members = {
135
+ add: async (input, options) => {
136
+ const load = await store.read(), oauth = (load.status === "ready" ? load.rows : []).filter((row) => row.type === "oauth" && !row.invalid), sameAccount = input.identity ? oauth.find((row) => row.identity === input.identity) : void 0;
137
+ if (sameAccount?.id === MAIN_ROW_ID)
138
+ throw new CommandError("main-account", MAIN_ACCOUNT_REFUSAL);
139
+ const existing = sameAccount ?? oauth.find((row) => row.id === input.id && row.id !== MAIN_ROW_ID);
140
+ if (!existing || input.credential.type !== "oauth")
141
+ return store.add(input, options);
142
+ const replaced = await replace(existing.id, input.credential, input.identity !== void 0 ? { identity: input.identity } : {}, options?.extraLocks ? { extraLocks: options.extraLocks } : void 0);
143
+ log.info("account signed in again", { id: existing.id });
144
+ return {
145
+ id: replaced.id,
146
+ outcome: "rotated",
147
+ credential: replaced.credential,
148
+ credentialEpoch: replaced.credentialEpoch
149
+ };
150
+ },
151
+ replace,
152
+ enable: (id, options) => store.enable(id, withLocks(id, options)),
153
+ disable: (id, reason, options) => store.disable(id, reason, withLocks(id, options)),
154
+ remove: (id, options) => store.remove(id, withLocks(id, options))
155
+ };
156
+ return new Proxy(store, {
157
+ get(target, property) {
158
+ if (Object.hasOwn(members, property))
159
+ return members[property];
160
+ const value = Reflect.get(target, property, target);
161
+ return typeof value === "function" ? value.bind(target) : value;
162
+ }
163
+ });
164
+ }
165
+ export async function writeSettings(store, extraLocks, edit) {
166
+ await withSettingsMigration(store).updateSettings((settings) => {
167
+ edit(settings);
168
+ return;
169
+ }, extraLocks ? { extraLocks } : {});
170
+ }
171
+ const POOL_OWNED = ["version", "accounts", "commonAuthPool"];
172
+ export function settingsMutateAccounts(store, extraLocks, configPath) {
173
+ return async (mutate) => {
174
+ let view;
175
+ await withSettingsMigration(store, configPath).updateSettings((settings) => {
176
+ const current = {
177
+ ...settings,
178
+ version: 1,
179
+ accounts: []
180
+ }, next = mutate(current) ?? current;
181
+ view = next;
182
+ const out = { ...next };
183
+ for (const key of POOL_OWNED)
184
+ delete out[key];
185
+ return out;
186
+ }, extraLocks ? { extraLocks } : {});
187
+ if (!view)
188
+ throw Error("the settings write did not run");
189
+ return view;
190
+ };
191
+ }
192
+ export const MIGRATION_NOTICE_SECTION_ID = "migration";
193
+ export function migrationNoticeMenu(blockers) {
194
+ const lines = [
195
+ "Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",
196
+ blockers.length > 0 ? "These processes still hold the move back:" : "No running process holds the move back."
197
+ ], menu = {
198
+ command: OPENAI_COMMAND_NAME,
199
+ title: OPENAI_MENU_TITLE,
200
+ sections: [
201
+ {
202
+ id: MIGRATION_NOTICE_SECTION_ID,
203
+ slot: "extra",
204
+ title: "Accounts are moving",
205
+ lines,
206
+ items: blockers.map((blocker, index) => ({
207
+ id: `blocker-${index}`,
208
+ label: blocker.pid === "unknown" ? "processes that could not be read" : `pid ${blocker.pid}`,
209
+ detail: `version ${blocker.version}`,
210
+ actions: []
211
+ })),
212
+ actions: []
213
+ }
214
+ ]
215
+ };
216
+ return scrubMenu(menu);
217
+ }
218
+ const CREDENTIAL_KEYS = new Set([
219
+ "access",
220
+ "refresh",
221
+ "apikey",
222
+ "authheader",
223
+ "password",
224
+ "credential",
225
+ "credentials"
226
+ ]);
227
+ function isCredentialKey(key) {
228
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
229
+ if (CREDENTIAL_KEYS.has(normalized))
230
+ return !0;
231
+ return normalized.endsWith("token") || normalized.endsWith("key") || normalized.endsWith("secret");
232
+ }
233
+ export function scrubKnobs(value, path, found) {
234
+ if (Array.isArray(value))
235
+ return value.map((entry, index) => scrubKnobs(entry, `${path}[${index}]`, found));
236
+ if (!isRecord(value))
237
+ return value;
238
+ const result = {};
239
+ for (const [key, entry] of Object.entries(value)) {
240
+ if (isCredentialKey(key)) {
241
+ found.push(`${path}.${key}`);
242
+ continue;
243
+ }
244
+ result[key] = scrubKnobs(entry, `${path}.${key}`, found);
245
+ }
246
+ return result;
247
+ }
248
+ function scrubMenu(menu) {
249
+ const found = [], scrubbed = scrubKnobs(menu, "menu", found);
250
+ if (found.length > 0)
251
+ log.warn("credential-shaped field stripped before RPC", { fields: found });
252
+ return scrubbed;
253
+ }
254
+ export function loginAddInput(account) {
255
+ return {
256
+ id: account.id,
257
+ credential: {
258
+ type: "oauth",
259
+ refresh: account.refresh,
260
+ ...account.access !== void 0 ? { access: account.access } : {},
261
+ ...account.expires !== void 0 ? { expires: account.expires } : {}
262
+ },
263
+ ...account.accountId !== void 0 ? { identity: account.accountId } : {},
264
+ ...account.label !== void 0 ? { label: account.label } : {}
265
+ };
266
+ }
267
+ export function menuLogin(deps, vault) {
268
+ return {
269
+ label: "Add account",
270
+ knobs: [
271
+ { kind: "text", id: "label", label: "Label (optional)" },
272
+ {
273
+ kind: "toggle",
274
+ id: "headless",
275
+ label: "Sign in with a device code (no browser on this machine)",
276
+ value: !1
277
+ }
278
+ ],
279
+ run: async (values) => {
280
+ const label = typeof values.label === "string" && values.label.trim().length > 0 ? values.label.trim() : void 0, headless = values.headless === !0, flow = await deps.begin({
281
+ ...label !== void 0 ? { label } : {},
282
+ headless
283
+ }), message = headless ? `Open this verification URL:
284
+
285
+ ${flow.url}
286
+
287
+ Then enter the code: ${flow.instructions.match(/Enter code: (.+)/)?.[1] ?? flow.instructions}
288
+
289
+ The account is added when you finish.` : `Open this URL and complete sign-in:
290
+
291
+ ${flow.url}
292
+
293
+ ${flow.instructions}
294
+
295
+ The account is added when you finish.`, completion = flow.completion.then(async (account) => {
296
+ if (vault && await vault.authority() !== "local")
297
+ throw new CommandError("vault-local-action", VAULT_LOCAL_ACTION_REFUSAL);
298
+ const main = await deps.mainIdentity?.();
299
+ if (account.id === MAIN_ROW_ID || account.accountId && main && account.accountId === main) {
300
+ log.warn("account add rejected (main identity)", { id: account.id });
301
+ throw new CommandError("main-account", MAIN_ACCOUNT_REFUSAL);
302
+ }
303
+ log.info("account added", { id: account.id });
304
+ return loginAddInput(account);
305
+ });
306
+ return { status: "pending", message, completion };
307
+ }
308
+ };
309
+ }
310
+ export function sessionSection(deps) {
311
+ return {
312
+ id: "session",
313
+ title: "This session",
314
+ build: async (invocation) => {
315
+ const sessionId = invocation.sessionId;
316
+ if (!sessionId)
317
+ return { lines: ["No current session"] };
318
+ const pin = await deps.getPin?.(sessionId);
319
+ return {
320
+ lines: [pin ? `Pinned to ${pin}` : "No sticky pin"],
321
+ actions: deps.clearPin ? [
322
+ {
323
+ id: "clear-pin",
324
+ label: "Clear this session's pin",
325
+ description: "The next request may still choose the same account.",
326
+ run: async ({ invocation: current }) => {
327
+ if (!current.sessionId)
328
+ return "No current session.";
329
+ await deps.clearPin?.(current.sessionId);
330
+ log.info("routing session pin cleared");
331
+ return "This session's pin was cleared. The next request may choose the same account if it remains the best selection.";
332
+ }
333
+ }
334
+ ] : []
335
+ };
336
+ }
337
+ };
338
+ }
339
+ export function vaultSection(deps) {
340
+ const { vault } = deps;
341
+ return {
342
+ id: "vault",
343
+ title: "Vault",
344
+ build: async () => {
345
+ const status = await vault.status(), name = status.enrollment.state === "approved" ? status.enrollment.approvedName ?? status.name : status.name, authority = await vault.authority(), hosted = authority === "host", connected = authority !== "local", routing = vault.routes().length;
346
+ return {
347
+ lines: [
348
+ hosted ? VAULT_HOST_STATUS : connected ? status.discovered ? `Connected \xB7 ${status.accounts.length} account${status.accounts.length === 1 ? "" : "s"}` : "Connected \xB7 waiting for the vault's first answer" : status.enrollment.state === "idle" ? "Not connected" : `Enrollment ${status.enrollment.state}`,
349
+ ...!hosted ? [
350
+ vaultEnrollmentLine(status.host, status.name, status.enrollment),
351
+ ...vaultApprovalInstructions(status.name, status.enrollment)
352
+ ] : [],
353
+ ...connected && status.discovered ? [
354
+ status.accounts.length === 0 ? vaultEmptyAccessHint(name, vault.grantReach()) : `The vault serves ${status.accounts.length} OpenAI account${status.accounts.length === 1 ? "" : "s"}; ${routing} can route now.`
355
+ ] : [],
356
+ ...connected && vault.snapshot()?.complete === !1 ? [
357
+ "The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."
358
+ ] : [],
359
+ ...status.lastError ? [`Last error: ${status.lastError}`] : []
360
+ ],
361
+ items: status.accounts.map((row) => ({
362
+ id: row.routeId,
363
+ label: vaultAccountName(row),
364
+ group: "Accounts",
365
+ status: row.enabled ? row.state : "disabled",
366
+ detail: [
367
+ row.credentialType === "api_key" ? "API key" : "login",
368
+ row.state === "active" ? "active" : `vault state ${row.state}`,
369
+ row.enabled ? "enabled" : "disabled here"
370
+ ].join(", "),
371
+ actions: [
372
+ row.enabled ? {
373
+ id: "disable",
374
+ label: "Disable on this host",
375
+ description: "It stays in the vault and in this list, and is never sent from this host until enabled again.",
376
+ run: async () => {
377
+ await vault.decline(row.routeId);
378
+ await deps.changed?.();
379
+ return `${vaultAccountName(row)} is disabled on this host.`;
380
+ }
381
+ } : {
382
+ id: "enable",
383
+ label: "Enable on this host",
384
+ run: async () => {
385
+ await vault.accept(row.routeId);
386
+ await deps.changed?.();
387
+ return `${vaultAccountName(row)} is enabled on this host.`;
388
+ }
389
+ }
390
+ ]
391
+ })),
392
+ actions: hosted ? [] : connected ? [
393
+ {
394
+ id: "disconnect",
395
+ label: "Disconnect",
396
+ description: "Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",
397
+ confirm: "Disconnect from the vault? Connecting again needs a new approval with `ck`.",
398
+ run: async () => {
399
+ const enrollment = (await vault.status().catch(() => {
400
+ return;
401
+ }))?.enrollment, name = enrollment?.state === "approved" ? enrollment.approvedName ?? vault.name : vault.name, revoke = enrollment && enrollment.state !== "blocked" ? `Run \`ck auth enroll revoke --name ${name}\` to revoke it in the vault too.` : "Run ck auth enroll list to find this host's enrollment name, then ck auth enroll revoke --name <name>.";
402
+ await vault.disconnect();
403
+ await deps.changed?.();
404
+ return `Disconnected: ${name} no longer reads from the vault. ${revoke}`;
405
+ }
406
+ }
407
+ ] : [
408
+ {
409
+ id: "connect",
410
+ label: "Connect",
411
+ description: "Asks the vault to enroll this host; you approve the request with `ck`.",
412
+ run: async ({ invocation }) => {
413
+ const step = await vault.connectStep();
414
+ if (step.state !== "pending" && step.state !== "busy") {
415
+ await deps.changed?.();
416
+ return vaultConnectOutcome(vault, step);
417
+ }
418
+ vault.waitForApproval(deps.wait).then(async (final) => {
419
+ await deps.changed?.();
420
+ const outcome = vaultConnectOutcome(vault, final);
421
+ invocation.notify(outcome.text, outcome.ok ? "info" : "warning");
422
+ }).catch((error) => {
423
+ invocation.notify(`Connecting to the vault failed: ${error instanceof Error ? error.message : String(error)}`, "error");
424
+ });
425
+ return {
426
+ ok: !0,
427
+ text: [
428
+ ...vaultApprovalInstructions(vault.name, step),
429
+ "Waiting for the approval; you are told here when it lands."
430
+ ].join(`
431
+ `)
432
+ };
433
+ }
434
+ }
435
+ ]
436
+ };
437
+ }
438
+ };
439
+ }
440
+ async function spendResetCredit(deps, accountKey, retry) {
441
+ if (!isSafeResetAccountKey(accountKey))
442
+ return resetResultPayload(accountKey, "invalid_account_key", "That account cannot take a reset credit.");
443
+ let expected;
444
+ try {
445
+ const saved = (await deps.loadAccounts({
446
+ configPath: deps.configPath,
447
+ statePath: deps.statePath
448
+ }))?.reset?.[accountKey];
449
+ if (retry || saved && Object.hasOwn(saved, "inFlight"))
450
+ expected = (await deps.resolveResetTarget(accountKey)).chatgptAccountId;
451
+ else {
452
+ const preview = await buildResetPreviewRow(accountKey, deps);
453
+ if (!preview.eligible)
454
+ return resetResultPayload(accountKey, "not_eligible", renderResetConfirm(preview));
455
+ expected = preview.chatgptAccountId;
456
+ }
457
+ if (!expected)
458
+ return resetResultPayload(accountKey, "not_eligible", "Cannot reset: stable ChatGPT account identity unavailable.");
459
+ log.info("reset redemption decision", { accountKey, retry });
460
+ const result = await runResetCreditRedemption({
461
+ configPath: deps.configPath,
462
+ statePath: deps.statePath,
463
+ mutateAccountsFn: deps.mutateAccounts,
464
+ loadAccountsFn: deps.loadAccounts,
465
+ now: deps.now,
466
+ randomUUID: deps.randomUUID,
467
+ fetchImpl: deps.fetchImpl,
468
+ resolveTarget: deps.resolveResetTarget,
469
+ fetchUsage: (target) => whamUsageFn({
470
+ accessToken: target.accessToken,
471
+ fetchImpl: deps.fetchImpl,
472
+ now: deps.now,
473
+ accountId: target.chatgptAccountId
474
+ }),
475
+ hasActiveRateLimitMark: (key) => deps.quotaManager.isRateLimited(key)
476
+ }, { accountKey, expectedChatgptAccountId: expected, retry });
477
+ log.info("reset redemption outcome", {
478
+ accountKey,
479
+ code: result.outcome.kind
480
+ });
481
+ return renderResetCoordinatorResult(result, deps, expected);
482
+ } catch (error) {
483
+ const outcome = resetErrorPayload(accountKey, error, expected);
484
+ log.info("reset redemption outcome", { accountKey, code: outcome.code });
485
+ return outcome;
486
+ }
487
+ }
488
+ export function resetCreditsSection(deps) {
489
+ return {
490
+ id: "reset",
491
+ title: "Reset credits",
492
+ build: async () => ({
493
+ lines: ["Restore exhausted quota"],
494
+ items: (await deps.accountKeys()).map((accountKey) => ({
495
+ id: accountKey,
496
+ group: "Accounts",
497
+ label: accountKey === MAIN_ROW_ID ? "Main account" : accountKey,
498
+ actions: [
499
+ {
500
+ id: "preview",
501
+ label: "Preview",
502
+ description: "Fetch the account's current quota and reset credits before spending a credit.",
503
+ run: async () => {
504
+ const row = await buildResetPreviewRow(accountKey, deps);
505
+ return {
506
+ ok: row.eligible,
507
+ text: `${resetRowDetail(row)}
508
+
509
+ ${renderResetConfirm(row)}`
510
+ };
511
+ }
512
+ },
513
+ {
514
+ id: "spend",
515
+ label: "Spend a reset credit",
516
+ irreversible: !0,
517
+ confirm: "Spend one reset credit on this account? Its eligibility is checked again first, and nothing is spent when it is not eligible.",
518
+ run: async () => {
519
+ const { ok, text } = await spendResetCredit(deps, accountKey, !1);
520
+ return { ok, text };
521
+ }
522
+ },
523
+ {
524
+ id: "retry",
525
+ label: "Retry the last redemption",
526
+ irreversible: !0,
527
+ confirm: "Retry the last redemption? A retry within five minutes reuses the same request and credit identifiers.",
528
+ run: async () => {
529
+ const { ok, text } = await spendResetCredit(deps, accountKey, !0);
530
+ return { ok, text };
531
+ }
532
+ }
533
+ ]
534
+ }))
535
+ })
536
+ };
537
+ }
538
+ export const ORDERED_VARIANTS = [
539
+ { value: "main-first", label: "Main first" },
540
+ { value: "fallback-first", label: "Fallback first" }
541
+ ], FLOOR_LABELS = ["primary", "secondary"];
542
+ export function createOpenAiMenu(options) {
543
+ const unavailable = new Set(options.unavailableSections), unavailableSection = (title) => ({
544
+ title,
545
+ build: async () => ({ lines: ["Not available on OpenCode 2 yet."] })
546
+ }), extras = [...options.extras ?? []];
547
+ if (unavailable.has("reset")) {
548
+ const reset = { id: "reset", ...unavailableSection("Reset credits") }, index = extras.findIndex((section) => section.id === "reset");
549
+ if (index < 0)
550
+ extras.unshift(reset);
551
+ else
552
+ extras[index] = reset;
553
+ }
554
+ const menuOptions = {
555
+ command: OPENAI_COMMAND_NAME,
556
+ title: OPENAI_MENU_TITLE,
557
+ store: menuStore(withSettingsMigration(withAccountRules(options.store, {
558
+ ...options.rowLocks ? { rowLocks: options.rowLocks } : {}
559
+ }), options.configPath)),
560
+ ...options.settings ? { settings: options.settings } : {},
561
+ ...options.extraLocks ? { extraLocks: options.extraLocks } : {},
562
+ accounts: {
563
+ ...options.login ? { login: menuLogin(options.login, options.vault) } : {},
564
+ ...options.protect ? { protect: options.protect } : {},
565
+ ...options.describeIdentity ? { describeIdentity: options.describeIdentity } : {}
566
+ },
567
+ quota: options.quotaCheck ? { check: options.quotaCheck } : {},
568
+ routing: {
569
+ orderedVariants: ORDERED_VARIANTS,
570
+ formerMainId: MAIN_ROW_ID,
571
+ sameAccountWait: !0
572
+ },
573
+ limits: { labels: FLOOR_LABELS },
574
+ ...unavailable.has("cache") ? { cache: unavailableSection("Cache") } : options.cache ? { cache: options.cache } : {},
575
+ ...unavailable.has("diagnostics") ? { diagnostics: unavailableSection("Diagnostics") } : options.diagnostics ? { diagnostics: options.diagnostics } : {},
576
+ extras,
577
+ ...options.logger ? { logger: options.logger } : {},
578
+ ...options.now ? { now: options.now } : {}
579
+ }, menu = options.vault ? createVaultCommandMenu(menuOptions, options.vault, {
580
+ refresh: !options.readOnly,
581
+ ...options.readOnly ? {
582
+ refuseApply: {
583
+ code: "unavailable",
584
+ text: "Not available on OpenCode 2 yet."
585
+ }
586
+ } : {}
587
+ }) : createCommandMenu(menuOptions), refusedMenu = options.vault ? createVaultCommandMenu(menuOptions, options.vault, {
588
+ refresh: !1,
589
+ refuseApply: {
590
+ code: "unavailable",
591
+ text: "Not available on OpenCode 2 yet."
592
+ }
593
+ }) : void 0, own = (invocation) => {
594
+ const { sessionId } = invocation, notify = invocation.notify.bind(invocation);
595
+ return { ...sessionId !== void 0 ? { sessionId } : {}, notify };
596
+ }, withLocalCredits = async (payload) => {
597
+ if (options.vault && await options.vault.authority() !== "local")
598
+ return payload;
599
+ const load = await options.store.read().catch(() => {
600
+ return;
601
+ });
602
+ if (load?.status !== "ready")
603
+ return payload;
604
+ return {
605
+ ...payload,
606
+ menu: withQuotaSectionCredits(payload.menu, new Map(load.rows.map((row) => [row.id, row.quota])))
607
+ };
608
+ };
609
+ return {
610
+ command: OPENAI_COMMAND_NAME,
611
+ async open(invocation) {
612
+ const context = own(invocation), state = options.vault && await options.vault.authority() !== "local" ? void 0 : await options.migration?.();
613
+ if (state && !state.migrated)
614
+ return {
615
+ command: OPENAI_COMMAND_NAME,
616
+ menu: migrationNoticeMenu(state.blockers)
617
+ };
618
+ const payload = await menu.open(context);
619
+ return withLocalCredits({ ...payload, menu: scrubMenu(payload.menu) });
620
+ },
621
+ async apply(request, invocation) {
622
+ const context = own(invocation), state = options.vault && await options.vault.authority() !== "local" ? void 0 : await options.migration?.();
623
+ if (state && !state.migrated)
624
+ return {
625
+ command: OPENAI_COMMAND_NAME,
626
+ ok: !1,
627
+ text: "Nothing was changed: the accounts have not moved to the new layout yet.",
628
+ menu: migrationNoticeMenu(state.blockers)
629
+ };
630
+ if (options.readOnly && options.vault)
631
+ return menu.apply(request, context);
632
+ if (options.readOnly || options.allowAction && !options.allowAction(request) || unavailable.has(request.sectionId)) {
633
+ if (refusedMenu)
634
+ return refusedMenu.apply(request, context);
635
+ return {
636
+ ...await menu.open(context),
637
+ ok: !1,
638
+ code: "unavailable",
639
+ text: "Not available on OpenCode 2 yet."
640
+ };
641
+ }
642
+ const result = await menu.apply(request, context);
643
+ if (result.ok)
644
+ await options.afterApply?.();
645
+ return withLocalCredits({ ...result, menu: scrubMenu(result.menu) });
646
+ }
647
+ };
648
+ }
649
+ function resetUsedPercent(snapshot) {
650
+ const values = [
651
+ snapshot.primary?.usedPercent,
652
+ snapshot.secondary?.usedPercent
653
+ ].filter((value) => value !== void 0);
654
+ return values.length > 0 ? Math.max(...values) : void 0;
655
+ }
656
+ function resetWindowTime(snapshot, now) {
657
+ const windows = [snapshot.primary, snapshot.secondary].filter((window) => window !== void 0), liveExhausted = windows.filter((window) => resetWindowIsExhausted(window, now));
658
+ return (liveExhausted.length > 0 ? liveExhausted : windows).sort((left, right) => right.usedPercent - left.usedPercent)[0]?.resetsAt;
659
+ }
660
+ function resetSnapshotIsHealthy(snapshot, now) {
661
+ if (!snapshot)
662
+ return !1;
663
+ const windows = [snapshot.primary, snapshot.secondary].filter((window) => window !== void 0);
664
+ if (windows.length === 0)
665
+ return !1;
666
+ return windows.every((window) => !resetWindowIsExhausted(window, now));
667
+ }
668
+ async function buildResetPreviewRow(accountKey, ctx) {
669
+ let target;
670
+ try {
671
+ target = await ctx.resolveResetTarget(accountKey);
672
+ const wireAccountId = target.accountKey === "main" ? void 0 : target.chatgptAccountId, [quota, credits] = await Promise.all([
673
+ whamUsageFn({
674
+ accessToken: target.accessToken,
675
+ fetchImpl: ctx.fetchImpl,
676
+ now: ctx.now,
677
+ accountId: target.chatgptAccountId
678
+ }),
679
+ listResetCredits(ctx.fetchImpl, target.accessToken, wireAccountId)
680
+ ]), selectedCredit = selectCreditToSpend(credits.credits), eligibleCreditCount = countEligibleResetCredits(credits.credits), availableCount = credits.availableCount ?? quota.resetCreditsAvailable ?? (eligibleCreditCount > 0 ? eligibleCreditCount : void 0), applicableAvailableCount = quota.resetCreditsApplicable, precondition = evaluateResetPrecondition(quota, ctx.quotaManager.isRateLimited(accountKey), ctx.now());
681
+ let reason;
682
+ if (!target.chatgptAccountId)
683
+ reason = "stable ChatGPT account identity unavailable";
684
+ else if (!precondition.ok)
685
+ reason = precondition.reason;
686
+ else if (!selectedCredit)
687
+ reason = "no eligible credit";
688
+ return {
689
+ accountKey: target.accountKey,
690
+ label: target.label,
691
+ chatgptAccountId: target.chatgptAccountId,
692
+ usedPercent: resetUsedPercent(quota),
693
+ resetTime: resetWindowTime(quota, ctx.now()),
694
+ availableCount,
695
+ applicableAvailableCount,
696
+ eligible: reason === void 0,
697
+ reason,
698
+ selectedCreditId: selectedCredit?.id,
699
+ selectedCreditExpiresAt: selectedCredit?.expiresAt
700
+ };
701
+ } catch (error) {
702
+ if (error?.status === 401)
703
+ await target?.onAuthFailure?.(401);
704
+ log.warn("reset preview row failed", {
705
+ accountKey,
706
+ error: error?.message ?? String(error)
707
+ });
708
+ return {
709
+ accountKey,
710
+ label: accountKey === "main" ? "Main account" : accountKey,
711
+ eligible: !1,
712
+ reason: error?.message ?? String(error)
713
+ };
714
+ }
715
+ }
716
+ function resetRowDetail(row) {
717
+ const usage = row.usedPercent === void 0 ? "quota unavailable" : `${row.usedPercent}% used`, credits = row.availableCount === void 0 ? "credits unavailable" : `${row.applicableAvailableCount === void 0 ? "?" : row.applicableAvailableCount}/${row.availableCount} applicable/available`, status = row.eligible ? `eligible \xB7 credit ${row.selectedCreditId} expires ${row.selectedCreditExpiresAt}` : row.reason;
718
+ return `${usage}; ${credits}; ${status}`;
719
+ }
720
+ function renderResetConfirm(row) {
721
+ const lines = [
722
+ "## Confirm reset credit",
723
+ "",
724
+ `Account: **${row.label}** (\`${row.accountKey}\`)`,
725
+ `Current quota: **${row.usedPercent ?? "unknown"}% used**`,
726
+ `Credit: **Spend 1 of ${row.availableCount ?? "unknown"}**`,
727
+ `Credit expires: **${row.selectedCreditExpiresAt ?? "unavailable"}**`,
728
+ `Quota resets: **${row.resetTime ?? "unavailable"}**`,
729
+ ""
730
+ ];
731
+ if ((row.availableCount ?? 0) > 0 && row.applicableAvailableCount === 0) {
732
+ lines.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit.");
733
+ lines.push("");
734
+ }
735
+ if (row.eligible && row.chatgptAccountId)
736
+ lines.push('Eligible: choose "Spend a reset credit" to redeem one.');
737
+ else
738
+ lines.push(`Cannot reset: **${row.reason ?? "not eligible"}**`);
739
+ return lines.join(`
740
+ `);
741
+ }
742
+ function resetResultPayload(accountKey, code, text, details = {}) {
743
+ if (Object.keys(details).length > 0)
744
+ log.debug("reset step details", { accountKey, code, ...details });
745
+ return {
746
+ ok: code === "reset" || code === "already_redeemed",
747
+ code,
748
+ text
749
+ };
750
+ }
751
+ function resetErrorPayload(accountKey, error, boundChatgptAccountId) {
752
+ if (error instanceof ResetRedemptionError) {
753
+ const messages = {
754
+ identity_mismatch: "The account identity changed before redemption. Reopen the reset account list.",
755
+ pair_identity_mismatch: "Nothing was sent: the saved redemption was started while this account was signed in as a different ChatGPT account. Sign this account back in as that ChatGPT account and retry, or wait until five minutes after the saved redemption started and spend a new credit.",
756
+ invalid_account_key: "The selected account key is reserved. Reopen the reset account list.",
757
+ cooldown_active: "This account just reset \u2014 re-checking quota. Wait for the cooldown before another redemption.",
758
+ expired_unreconciled: "The previous attempt outcome is unknown \u2014 retry replays the same identifiers, or wait until quota reflects the earlier attempt.",
759
+ retry_without_inflight: "There is no active reset redemption to retry. Reopen the account list.",
760
+ not_exhausted: "No credit was spent: the fresh account state is not exhausted.",
761
+ no_eligible_credit: "No credit was spent: no eligible credit was returned."
762
+ };
763
+ return resetResultPayload(accountKey, error.kind, `## Reset credit
764
+
765
+ ${messages[error.kind]}
766
+
767
+ Code: \`${error.kind}\``, {
768
+ cooldownUntil: error.cooldownUntil,
769
+ ...error.kind === "expired_unreconciled" ? {
770
+ chatgptAccountId: boundChatgptAccountId,
771
+ retryGuidance: "Retry replays the same request and credit identifiers from the previous attempt."
772
+ } : {}
773
+ });
774
+ }
775
+ const identityCode = error?.code;
776
+ if (identityCode === "unknown_account" || identityCode === "disabled_account" || identityCode === "non_oauth_account" || identityCode === "token_unavailable")
777
+ return resetResultPayload(accountKey, identityCode, `## Reset credit
778
+
779
+ ${{
780
+ unknown_account: "Account unavailable: the selected account no longer exists. Reopen the reset account list.",
781
+ disabled_account: "Account unavailable: the selected account is disabled. Reopen the reset account list.",
782
+ non_oauth_account: "Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",
783
+ token_unavailable: "Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."
784
+ }[identityCode]}
785
+
786
+ Code: \`${identityCode}\``);
787
+ if (error instanceof ResetCreditError)
788
+ return resetResultPayload(accountKey, error.kind, `## Reset credit
789
+
790
+ No redemption was attempted: reset credit availability could not be loaded.
791
+
792
+ Code: \`${error.kind}\``);
793
+ log.warn("reset command failed before a known result", {
794
+ accountKey,
795
+ error: error?.message ?? String(error)
796
+ });
797
+ return resetResultPayload(accountKey, "error", `## Reset credit
798
+
799
+ The reset request failed before a known result: internal command failure \u2014 see plugin log.`);
800
+ }
801
+ export async function renderResetCoordinatorResult(result, ctx, boundChatgptAccountId) {
802
+ const { accountKey } = result.target, code = result.outcome.kind;
803
+ if (result.finalizeStateWriteFailed)
804
+ return resetResultPayload(accountKey, code, `## Reset credit result
805
+
806
+ Account: **${result.target.label}** (\`${accountKey}\`)
807
+
808
+ The server outcome recorded as \`${code}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`, {
809
+ stateWriteFailed: !0,
810
+ retryGuidance: result.retrySafety,
811
+ chatgptAccountId: boundChatgptAccountId
812
+ });
813
+ if (code === "reset" || code === "already_redeemed") {
814
+ let refresh = {
815
+ account: accountKey,
816
+ ok: !1,
817
+ error: "targeted quota refresh did not complete"
818
+ };
819
+ try {
820
+ refresh = await ctx.refreshResetTargetQuota(accountKey);
821
+ } catch (error) {
822
+ refresh.error = error?.message ?? String(error);
823
+ }
824
+ const refreshFailed = !refresh.ok && refresh.error !== void 0;
825
+ if (refreshFailed)
826
+ log.warn("reset quota re-check failed", {
827
+ accountKey,
828
+ error: refresh.error
829
+ });
830
+ const entry = accountKey === "main" ? ctx.quotaManager.getMain() : ctx.quotaManager.getFallback(accountKey), verifiedFresh = refresh.ok && resetSnapshotIsHealthy(entry?.quota, ctx.now()), remainingCredits = entry?.quota.resetCreditsApplicable, verification = verifiedFresh ? "Post-verification: **window fresh**." : `Post-verification: **window not yet refreshed** (server code \`${code}\`).`, refreshDiagnostic = refreshFailed ? `
831
+
832
+ quota re-check failed \u2014 see log.` : "";
833
+ return resetResultPayload(accountKey, code, `## Reset credit result
834
+
835
+ Account: **${result.target.label}** (\`${accountKey}\`)
836
+
837
+ Code: \`${code}\`
838
+
839
+ ${verification}${refreshDiagnostic}${remainingCredits === void 0 ? "" : `
840
+
841
+ Remaining applicable credits: **${remainingCredits}**`}`, {
842
+ verifiedFresh,
843
+ afterUsedPercent: resetUsedPercent(entry?.quota ?? {}),
844
+ remainingCredits
845
+ });
846
+ }
847
+ if (code === "ambiguous_local")
848
+ return resetResultPayload(accountKey, code, `## Reset credit result
849
+
850
+ Account: **${result.target.label}** (\`${accountKey}\`)
851
+
852
+ Code: \`${code}\`
853
+
854
+ ${result.retrySafety}`, { retryGuidance: result.retrySafety });
855
+ if (code === "ambiguous" || code === "http_error") {
856
+ const refused = result.refused ? ' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.' : "";
857
+ return resetResultPayload(accountKey, code, `## Reset credit result
858
+
859
+ Account: **${result.target.label}** (\`${accountKey}\`)
860
+
861
+ The redemption outcome is unknown (\`${code}\`).
862
+
863
+ Retry with "Retry the last redemption" on this account. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.${refused}`, {
864
+ retryGuidance: result.retrySafety,
865
+ chatgptAccountId: boundChatgptAccountId
866
+ });
867
+ }
868
+ const meanings = {
869
+ nothing_to_reset: "The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",
870
+ no_credit: "The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."
871
+ };
872
+ return resetResultPayload(accountKey, code, `## Reset credit result
873
+
874
+ Account: **${result.target.label}** (\`${accountKey}\`)
875
+
876
+ Code: \`${code}\`
877
+
878
+ ${meanings[code] ?? "The server returned a no-op result. No reset was confirmed."}`);
879
+ }