@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,237 @@
1
+ import {
2
+ findPoolMainRow,
3
+ isPoolMainPlaceholder,
4
+ isShieldedMainRow
5
+ } from "./dbc61cd405941828-accounts.js";
6
+ import { formatRefreshBackoffMessage, refreshBackoffActive } from "./134b008900698fe0-backoff.js";
7
+ import { createLogger } from "./d669d72c40e9e116-logger.js";
8
+ import { isTombstoned } from "./4593a4d71edf69fd-tombstone.js";
9
+ import { errorMessage } from "./f37fcefc7aedbf25-error.js";
10
+ const log = createLogger("quota");
11
+ export const TOMBSTONED_ACCOUNT_ERROR = "the account holds a tombstone from the removed vault custody, not a credential";
12
+ function isUnauthorized(error) {
13
+ return error?.status === 401;
14
+ }
15
+ export async function refreshAllQuota(deps, options = {}) {
16
+ const whamFn = deps.whamFn;
17
+ if (!whamFn)
18
+ throw Error("whamFn is required for refreshAllQuota");
19
+ const results = [], logger = deps.logger ?? log, recordOutcome = (result) => {
20
+ results.push(result);
21
+ const payload = {
22
+ pid: process.pid,
23
+ accountId: result.account,
24
+ status: result.ok ? "ok" : "error",
25
+ ...result.error ? { error: result.error } : {}
26
+ };
27
+ if (result.ok)
28
+ logger.debug("quota refresh succeeded", payload);
29
+ else
30
+ logger.warn("quota refresh failed", payload);
31
+ }, freshnessMs = deps.skipFresherThanMs;
32
+ let quotaUpdated = !1, sharedSidebarState;
33
+ if (freshnessMs !== void 0)
34
+ try {
35
+ sharedSidebarState = await deps.readSidebarState();
36
+ } catch {}
37
+ const sharedFallbacks = new Map(sharedSidebarState?.fallbacks.map((account) => [account.id, account]) ?? []), isFresh = (...checkedAts) => freshnessMs !== void 0 && checkedAts.some((checkedAt) => typeof checkedAt === "number" && Number.isFinite(checkedAt) && checkedAt <= deps.now() && deps.now() - checkedAt < freshnessMs), storage = await deps.loadAccounts(deps.paths).catch(() => {
38
+ return;
39
+ }), liveMainAccountId = storage?.mainAccountId ?? deps.storageMainAccountId;
40
+ let poolMainRow;
41
+ if (!options.accountKey || options.accountKey === "main")
42
+ try {
43
+ let auth = await deps.getAuth();
44
+ if (isPoolMainPlaceholder(auth)) {
45
+ poolMainRow = findPoolMainRow(storage);
46
+ if (!poolMainRow)
47
+ recordOutcome({
48
+ account: "main",
49
+ ok: !1,
50
+ error: isTombstoned(auth) ? TOMBSTONED_ACCOUNT_ERROR : "main account row is missing from the account pool"
51
+ });
52
+ } else if (auth.type === "oauth") {
53
+ const sharedMainQuota = sharedSidebarState && liveMainAccountId !== void 0 && sharedSidebarState.main.mainAccountId === liveMainAccountId ? sharedSidebarState.main.quota : void 0;
54
+ if (isFresh(deps.quotaManager.peekMainForPolicy(liveMainAccountId)?.checkedAt, sharedMainQuota?.primary?.checkedAt, sharedMainQuota?.secondary?.checkedAt, sharedMainQuota?.checkedAt))
55
+ recordOutcome({ account: "main", ok: !0 });
56
+ else {
57
+ if (!auth.access || (auth.expires ?? 0) < deps.now()) {
58
+ const tokens = await deps.refreshMainWithLease();
59
+ auth = { ...auth, access: tokens.access, expires: tokens.expires };
60
+ }
61
+ if (auth.access)
62
+ if (deps.respectBackoff && deps.quotaManager.isBackedOff())
63
+ recordOutcome({ account: "main", ok: !0 });
64
+ else {
65
+ const snap = await whamFn({
66
+ accessToken: auth.access,
67
+ fetchImpl: deps.fetchImpl,
68
+ now: deps.now,
69
+ accountId: liveMainAccountId,
70
+ accountKey: "main"
71
+ });
72
+ deps.quotaManager.setMain(auth.access, {
73
+ quota: snap,
74
+ refreshAfter: deps.now() + 300000,
75
+ checkedAt: deps.now()
76
+ }, liveMainAccountId, !0);
77
+ quotaUpdated = !0;
78
+ recordOutcome({ account: "main", ok: !0 });
79
+ }
80
+ else if (!results.some((result) => result.account === "main"))
81
+ recordOutcome({
82
+ account: "main",
83
+ ok: !1,
84
+ error: "no access token"
85
+ });
86
+ }
87
+ } else
88
+ recordOutcome({
89
+ account: "main",
90
+ ok: !1,
91
+ error: "auth type is not oauth"
92
+ });
93
+ } catch (e) {
94
+ recordOutcome({
95
+ account: "main",
96
+ ok: !1,
97
+ error: errorMessage(e)
98
+ });
99
+ }
100
+ if (storage)
101
+ for (const acct of storage.accounts) {
102
+ const asMain = poolMainRow !== void 0 && acct === poolMainRow;
103
+ if (!asMain && options.accountKey && (options.accountKey === "main" || acct.id !== options.accountKey))
104
+ continue;
105
+ if (!asMain && deps.isOAuthAccountFn(acct) && isShieldedMainRow(storage, acct)) {
106
+ if (options.accountKey)
107
+ recordOutcome({
108
+ account: acct.id,
109
+ ok: !1,
110
+ error: "account holds the main credential while the main slot is live"
111
+ });
112
+ continue;
113
+ }
114
+ const mainIdentity = asMain ? acct.accountId ?? liveMainAccountId : void 0, storeReading = (entry, token, accountId) => {
115
+ if (asMain)
116
+ deps.quotaManager.setMain(token, entry, mainIdentity, !0);
117
+ else
118
+ deps.quotaManager.setFallback(acct.id, entry, token, !0, accountId);
119
+ };
120
+ if (acct.enabled === !1 || !deps.isOAuthAccountFn(acct)) {
121
+ if (options.accountKey)
122
+ recordOutcome({
123
+ account: acct.id,
124
+ ok: !1,
125
+ error: "account is not an enabled OAuth fallback"
126
+ });
127
+ continue;
128
+ }
129
+ try {
130
+ const sharedFb = sharedFallbacks.get(acct.id), currentAccountId = acct.accountId, sharedFbQuota = asMain ? sharedSidebarState && mainIdentity !== void 0 && sharedSidebarState.main.mainAccountId === mainIdentity ? sharedSidebarState.main.quota : void 0 : sharedFb && currentAccountId !== void 0 && sharedFb.accountId === currentAccountId ? sharedFb.quota : void 0;
131
+ if (isFresh(asMain ? deps.quotaManager.peekMainForPolicy(mainIdentity)?.checkedAt : deps.quotaManager.peekFallbackForPolicy(acct.id, currentAccountId)?.checkedAt, sharedFbQuota?.primary?.checkedAt, sharedFbQuota?.secondary?.checkedAt, sharedFbQuota?.checkedAt)) {
132
+ recordOutcome({ account: acct.id, ok: !0 });
133
+ continue;
134
+ }
135
+ if (deps.respectBackoff && (asMain ? deps.quotaManager.isBackedOff() : deps.quotaManager.isFallbackBackedOff(acct.id, acct.access))) {
136
+ recordOutcome({ account: acct.id, ok: !0 });
137
+ continue;
138
+ }
139
+ const armedRefreshError = acct.lastRefreshError;
140
+ if (refreshBackoffActive(armedRefreshError, acct.refresh, deps.now())) {
141
+ recordOutcome({
142
+ account: acct.id,
143
+ ok: !1,
144
+ error: formatRefreshBackoffMessage(armedRefreshError, deps.now()),
145
+ permanent: !0
146
+ });
147
+ continue;
148
+ }
149
+ if (isTombstoned(acct)) {
150
+ recordOutcome({
151
+ account: acct.id,
152
+ ok: !1,
153
+ error: TOMBSTONED_ACCOUNT_ERROR
154
+ });
155
+ continue;
156
+ }
157
+ let refreshed;
158
+ try {
159
+ refreshed = asMain ? await deps.fallbackManager.refreshAccount(acct, storage, {
160
+ asPoolMain: !0
161
+ }) : await deps.fallbackManager.refreshAccount(acct, storage);
162
+ } catch (refreshError) {
163
+ log.warn("fallback token refresh failed during quota poll", {
164
+ pid: process.pid,
165
+ accountId: acct.id,
166
+ error: errorMessage(refreshError)
167
+ });
168
+ refreshed = acct;
169
+ }
170
+ if (!refreshed.access || (refreshed.expires ?? 0) < deps.now()) {
171
+ recordOutcome({
172
+ account: acct.id,
173
+ ok: !1,
174
+ error: "no usable access token"
175
+ });
176
+ continue;
177
+ }
178
+ let snap;
179
+ try {
180
+ snap = await whamFn({
181
+ accessToken: refreshed.access,
182
+ fetchImpl: deps.fetchImpl,
183
+ now: deps.now,
184
+ accountId: refreshed.accountId,
185
+ accountKey: acct.id
186
+ });
187
+ } catch (quotaError) {
188
+ if (!isUnauthorized(quotaError))
189
+ throw quotaError;
190
+ log.warn("quota endpoint rejected the token; forcing a refresh", {
191
+ pid: process.pid,
192
+ accountId: acct.id
193
+ });
194
+ refreshed = await deps.fallbackManager.refreshAccount(acct, storage, asMain ? { force: !0, asPoolMain: !0 } : { force: !0 });
195
+ if (!refreshed.access) {
196
+ recordOutcome({
197
+ account: acct.id,
198
+ ok: !1,
199
+ error: "no usable access token after forced refresh"
200
+ });
201
+ continue;
202
+ }
203
+ snap = await whamFn({
204
+ accessToken: refreshed.access,
205
+ fetchImpl: deps.fetchImpl,
206
+ now: deps.now,
207
+ accountId: refreshed.accountId,
208
+ accountKey: acct.id
209
+ });
210
+ }
211
+ storeReading({
212
+ quota: snap,
213
+ refreshAfter: deps.now() + 300000,
214
+ checkedAt: deps.now()
215
+ }, refreshed.access, refreshed.accountId);
216
+ quotaUpdated = !0;
217
+ recordOutcome({ account: acct.id, ok: !0 });
218
+ } catch (e) {
219
+ recordOutcome({
220
+ account: acct.id,
221
+ ok: !1,
222
+ error: errorMessage(e)
223
+ });
224
+ }
225
+ }
226
+ if (options.accountKey && options.accountKey !== "main" && !results.some((result) => result.account === options.accountKey))
227
+ results.push({
228
+ account: options.accountKey,
229
+ ok: !1,
230
+ error: "account not found"
231
+ });
232
+ if (freshnessMs === void 0 || quotaUpdated) {
233
+ const freshStorage = await deps.loadAccounts(deps.paths);
234
+ await deps.writeSidebarState(deps.quotaManager, freshStorage);
235
+ }
236
+ return results;
237
+ }
@@ -0,0 +1,11 @@
1
+ import { isRecord } from "./775431e21f469203-record.js";
2
+ export function stableStringify(value) {
3
+ return JSON.stringify(stable(value)) ?? "undefined";
4
+ }
5
+ function stable(value) {
6
+ if (Array.isArray(value))
7
+ return value.map(stable);
8
+ if (!isRecord(value))
9
+ return value;
10
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]));
11
+ }
@@ -0,0 +1,10 @@
1
+ /** Pass only reason, status and retryAfterMs to the existing OpenCode 2 adapter. */
2
+ export function toOpenCode2LimitSignal(signal) {
3
+ return {
4
+ reason: signal.reason,
5
+ ...(signal.status === undefined ? {} : { status: signal.status }),
6
+ ...(signal.retryAfterMs === undefined
7
+ ? {}
8
+ : { retryAfterMs: signal.retryAfterMs }),
9
+ };
10
+ }
@@ -0,0 +1,107 @@
1
+ export const ANTIGRAVITY_FAILURE_LADDER = Object.freeze({
2
+ kind: 'failure-ladder',
3
+ mergeLaw: 'max-until',
4
+ hintFloorMs: 2000,
5
+ quotaSteps: Object.freeze([60000, 300000, 1800000, 7200000]),
6
+ byKind: Object.freeze({ 'rate-limit': 30000 }),
7
+ byReason: Object.freeze({ 'server-error': 20000, unknown: 60000 }),
8
+ capacity: Object.freeze({ baseMs: 45000, spreadMs: 15000 }),
9
+ defaultMs: 60000,
10
+ });
11
+ function accountKey(account) {
12
+ return JSON.stringify([
13
+ account.namespace,
14
+ account.accountId,
15
+ account.incarnation,
16
+ ]);
17
+ }
18
+ /** Feed committed marker events, not repeated reducer evaluations, into history. */
19
+ export function reduceFailureHistory(history, event, ttlMs = 3600000) {
20
+ const next = new Map(history);
21
+ const key = accountKey(event.account);
22
+ if (event.type === 'success') {
23
+ next.delete(key);
24
+ }
25
+ else {
26
+ const previous = history.get(key);
27
+ const count = !previous || event.at - previous.lastFailureAt > ttlMs
28
+ ? 1
29
+ : previous.count + 1;
30
+ next.set(key, { count, lastFailureAt: event.at });
31
+ }
32
+ return next;
33
+ }
34
+ function ladderMs(signal, axes, history) {
35
+ const hint = signal.retryAfterMs;
36
+ if (hint !== undefined && Number.isFinite(hint) && hint > 0) {
37
+ return Math.max(axes.hintFloorMs, hint);
38
+ }
39
+ const reasonDuration = Object.hasOwn(axes.byReason, signal.reason)
40
+ ? axes.byReason[signal.reason]
41
+ : undefined;
42
+ if (reasonDuration !== undefined)
43
+ return reasonDuration;
44
+ if (signal.kind === 'quota-exhausted') {
45
+ const count = history.failures?.get(accountKey(signal.account))?.count ?? 1;
46
+ const index = Math.min(axes.quotaSteps.length - 1, Math.max(0, count - 1));
47
+ const step = axes.quotaSteps[index];
48
+ if (step !== undefined)
49
+ return step;
50
+ }
51
+ const duration = axes.byKind[signal.kind];
52
+ if (duration !== undefined)
53
+ return duration;
54
+ if (signal.kind === 'capacity') {
55
+ return (axes.capacity.baseMs +
56
+ (2 * (history.random ?? 0.5) - 1) * axes.capacity.spreadMs);
57
+ }
58
+ return axes.defaultMs;
59
+ }
60
+ /** No clocks, random draws, state updates or I/O occur while producing a mark. */
61
+ export function markFromSignal(signal, axes, history) {
62
+ if (!signal || axes.kind === 'off')
63
+ return undefined;
64
+ if (axes.kind === 'hint' && axes.ignoredKinds?.includes(signal.kind))
65
+ return undefined;
66
+ let until;
67
+ switch (axes.kind) {
68
+ case 'failure-ladder':
69
+ until = history.now + ladderMs(signal, axes, history);
70
+ break;
71
+ case 'hint': {
72
+ const hint = signal.retryAfterMs;
73
+ const clock = axes.hintClock === 'signal' ? signal.observedAt : history.now;
74
+ const usable = hint !== undefined &&
75
+ Number.isFinite(hint) &&
76
+ (hint > 0 || (hint === 0 && axes.zero === 'accept')) &&
77
+ Number.isFinite(clock + Math.max(axes.minimumMs, hint));
78
+ until = usable
79
+ ? clock + Math.max(axes.minimumMs, hint)
80
+ : history.now + (axes.defaultMsByKind?.[signal.kind] ?? axes.defaultMs);
81
+ break;
82
+ }
83
+ case 'reset': {
84
+ const resets = signal.windows
85
+ .map((window) => window.resetAt)
86
+ .filter((reset) => reset !== undefined &&
87
+ Number.isFinite(reset) &&
88
+ reset > history.now);
89
+ until = resets.length ? Math.max(...resets) : history.now + axes.defaultMs;
90
+ break;
91
+ }
92
+ }
93
+ return Number.isFinite(until)
94
+ ? {
95
+ scope: signal.scope,
96
+ until,
97
+ mergeLaw: axes.mergeLaw,
98
+ ...(axes.kind === 'hint' &&
99
+ axes.causes?.some((cause) => cause === signal.kind)
100
+ ? { cause: signal.kind }
101
+ : {}),
102
+ }
103
+ : undefined;
104
+ }
105
+ export function markIsActive(mark, now) {
106
+ return now < mark.until;
107
+ }
@@ -0,0 +1,3 @@
1
+ export function isRecord(input) {
2
+ return typeof input === "object" && input !== null && !Array.isArray(input);
3
+ }
@@ -0,0 +1,47 @@
1
+ // The OpenCode v1 side of the account menu.
2
+ //
3
+ // `opencode auth login` calls an OAuth method's `authorize(inputs?)` and then
4
+ // awaits the returned result's `callback()`; a success there is stored as the
5
+ // provider's credential. `inputs` is passed only by the CLI, never by the TUI,
6
+ // which is what lets the CLI path open a menu while the TUI keeps signing in
7
+ // as before. The types here are structural copies of the host's
8
+ // `AuthOAuthResult` so the library does not depend on the host's package.
9
+ /**
10
+ * The result to hand back after the menu has run, whatever the action did.
11
+ *
12
+ * The host's result type has no top-level "done, store nothing": every
13
+ * result ends in a callback whose success the host files as the provider's
14
+ * own credential. An account added, re-authenticated or repaired from the
15
+ * menu is already stored by the plugin, and storing it again in the host's
16
+ * slot would make an extra account the provider's main credential. A failed
17
+ * callback is the only result that stores nothing, so the operator sees
18
+ * "Failed to authorize" after every menu action; that line is expected.
19
+ */
20
+ export function menuCompletedResult() {
21
+ return {
22
+ url: '',
23
+ instructions: '',
24
+ method: 'auto',
25
+ callback: async () => ({ type: 'failed' }),
26
+ };
27
+ }
28
+ /** Whether `authorize` was called by `opencode auth login` rather than the TUI. */
29
+ export function isCliAuthorize(inputs) {
30
+ return inputs !== undefined;
31
+ }
32
+ /**
33
+ * Builds an OAuth method's `authorize`: the TUI and a first CLI login get
34
+ * the plugin's normal login; a CLI login on a machine with a credential gets
35
+ * the menu, then the failed result described at `menuCompletedResult`. The
36
+ * TUI path never runs `hasCredential`, so it reads nothing it did not before.
37
+ */
38
+ export function menuAuthorize(options) {
39
+ return async (inputs) => {
40
+ if (!isCliAuthorize(inputs))
41
+ return options.login();
42
+ if (!(await options.hasCredential()))
43
+ return options.login(inputs);
44
+ await options.openMenu(inputs);
45
+ return menuCompletedResult();
46
+ };
47
+ }
@@ -0,0 +1,47 @@
1
+ import { sameAccount } from "./f6d728f5e601f98b-request-history.js";
2
+ /**
3
+ * Snapshot exhaustion blockers only. A wait caused by a minimum-remaining quota
4
+ * threshold supplies no windows: elapsed time cannot prove renewed headroom.
5
+ */
6
+ export function waitCheckpoint(accountKey, decidedAt, windows) {
7
+ return {
8
+ accountKey: { ...accountKey },
9
+ decidedAt,
10
+ blockers: windows
11
+ .filter((window) => window.confirmed && Number.isFinite(window.resetAt))
12
+ .map((window) => ({
13
+ window: window.window,
14
+ resetAt: window.resetAt,
15
+ })),
16
+ };
17
+ }
18
+ /**
19
+ * Match exhaustion evidence for one wake dispatch, without refreshing quota.
20
+ * The caller must still check admission, other blockers and any cache bound.
21
+ */
22
+ export function liftedWindowsForWake(wake, account, windows, now) {
23
+ const { checkpoint, target } = wake;
24
+ if (!sameAccount(account, checkpoint.accountKey) ||
25
+ !Number.isFinite(target) ||
26
+ !Number.isFinite(checkpoint.decidedAt) ||
27
+ target < checkpoint.decidedAt ||
28
+ !Number.isFinite(now) ||
29
+ now < target)
30
+ return [];
31
+ const canLift = (window) => {
32
+ const resetAt = window.resetAt;
33
+ return (window.confirmed &&
34
+ resetAt !== undefined &&
35
+ Number.isFinite(resetAt) &&
36
+ resetAt <= target &&
37
+ checkpoint.blockers.some((blocker) => blocker.window === window.window &&
38
+ Number.isFinite(blocker.resetAt) &&
39
+ resetAt <= blocker.resetAt));
40
+ };
41
+ return windows
42
+ .filter((window) => canLift(window) &&
43
+ windows
44
+ .filter((other) => other.confirmed && other.window === window.window)
45
+ .every(canLift))
46
+ .map((window) => window.window);
47
+ }
@@ -0,0 +1,159 @@
1
+ import { ANSI, parseKeys, truncateAnsi } from "./054118b2705fdc20-ansi.js";
2
+ import { isInteractive } from "./ea56007991dbf068-terminal.js";
3
+ /** How long a lone Escape byte waits for the rest of an arrow-key sequence. */
4
+ const ESCAPE_TIMEOUT_MS = 50;
5
+ function colorCode(color) {
6
+ if (color === 'red')
7
+ return ANSI.red;
8
+ if (color === 'cyan')
9
+ return ANSI.cyan;
10
+ return '';
11
+ }
12
+ /**
13
+ * Render a bounded, keyboard-only terminal selector without a prompt
14
+ * dependency. Resolves the chosen value, or null on Escape, Ctrl-C, a signal,
15
+ * or a terminal that refuses raw mode.
16
+ */
17
+ export async function select(terminal, items, options) {
18
+ if (!isInteractive(terminal))
19
+ throw new Error('Interactive select requires a TTY terminal');
20
+ if (items.length === 0)
21
+ throw new Error('No menu items provided');
22
+ const { input: stdin, output: stdout, signals } = terminal;
23
+ let cursor = 0;
24
+ let escapeTimeout = null;
25
+ let cleaned = false;
26
+ let renderedLines = 0;
27
+ const render = () => {
28
+ const columns = stdout.columns ?? 80;
29
+ const rows = stdout.rows ?? 24;
30
+ const previousLines = renderedLines;
31
+ if (options.clearScreen) {
32
+ stdout.write(ANSI.clearScreen + ANSI.moveTo(1, 1));
33
+ }
34
+ else if (previousLines > 0) {
35
+ stdout.write(ANSI.up(previousLines));
36
+ }
37
+ let lines = 0;
38
+ const writeLine = (line) => {
39
+ stdout.write(`${ANSI.clearLine}${line}\n`);
40
+ lines += 1;
41
+ };
42
+ const extraLines = options.lines ?? [];
43
+ const headerLines = 1 +
44
+ (options.subtitle ? 3 : 0) +
45
+ extraLines.length +
46
+ (extraLines.length ? 1 : 0);
47
+ const maxVisible = Math.max(1, Math.min(items.length, rows - headerLines - 2 - 1));
48
+ const windowStart = Math.max(0, Math.min(cursor - Math.floor(maxVisible / 2), Math.max(0, items.length - maxVisible)));
49
+ const visibleItems = items.slice(windowStart, windowStart + maxVisible);
50
+ writeLine(`${ANSI.dim}┌ ${ANSI.reset}${truncateAnsi(options.message, Math.max(1, columns - 4))}`);
51
+ if (options.subtitle) {
52
+ writeLine(`${ANSI.dim}│${ANSI.reset}`);
53
+ writeLine(`${ANSI.cyan}◆${ANSI.reset} ${truncateAnsi(options.subtitle, Math.max(1, columns - 4))}`);
54
+ writeLine('');
55
+ }
56
+ for (const line of extraLines) {
57
+ writeLine(`${ANSI.cyan}│${ANSI.reset} ${truncateAnsi(line, Math.max(1, columns - 4))}`);
58
+ }
59
+ if (extraLines.length)
60
+ writeLine(`${ANSI.cyan}│${ANSI.reset}`);
61
+ for (let offset = 0; offset < visibleItems.length; offset++) {
62
+ const item = visibleItems[offset];
63
+ if (!item)
64
+ continue;
65
+ const selected = windowStart + offset === cursor;
66
+ const color = colorCode(item.color);
67
+ let label = color
68
+ ? `${selected ? '' : ANSI.dim}${color}${item.label}${ANSI.reset}`
69
+ : selected
70
+ ? item.label
71
+ : `${ANSI.dim}${item.label}${ANSI.reset}`;
72
+ if (item.hint)
73
+ label += ` ${ANSI.dim}${item.hint}${ANSI.reset}`;
74
+ label = truncateAnsi(label, Math.max(1, columns - 8));
75
+ writeLine(selected
76
+ ? `${ANSI.cyan}│${ANSI.reset} ${ANSI.green}●${ANSI.reset} ${label}`
77
+ : `${ANSI.cyan}│${ANSI.reset} ${ANSI.dim}○${ANSI.reset} ${label}`);
78
+ }
79
+ const windowHint = visibleItems.length < items.length
80
+ ? ` (${windowStart + 1}-${windowStart + visibleItems.length}/${items.length})`
81
+ : '';
82
+ writeLine(`${ANSI.cyan}│${ANSI.reset} ${ANSI.dim}${truncateAnsi(`Up/Down to select | Enter: confirm | Esc: back${windowHint}`, Math.max(1, columns - 6))}${ANSI.reset}`);
83
+ writeLine(`${ANSI.cyan}└${ANSI.reset}`);
84
+ for (let extra = lines; extra < previousLines; extra++)
85
+ writeLine('');
86
+ renderedLines = lines;
87
+ };
88
+ return new Promise((resolve) => {
89
+ const wasRaw = stdin.isRaw ?? false;
90
+ const cleanup = () => {
91
+ if (cleaned)
92
+ return;
93
+ cleaned = true;
94
+ if (escapeTimeout)
95
+ clearTimeout(escapeTimeout);
96
+ stdin.removeListener('data', onKey);
97
+ try {
98
+ stdin.setRawMode(wasRaw);
99
+ stdin.pause();
100
+ stdout.write(ANSI.show);
101
+ }
102
+ catch { }
103
+ signals?.removeListener('SIGINT', onSignal);
104
+ signals?.removeListener('SIGTERM', onSignal);
105
+ };
106
+ const finish = (value) => {
107
+ cleanup();
108
+ resolve(value);
109
+ };
110
+ const onSignal = () => finish(null);
111
+ const onKey = (data) => {
112
+ for (const key of parseKeys(data)) {
113
+ if (cleaned)
114
+ break;
115
+ if (escapeTimeout) {
116
+ clearTimeout(escapeTimeout);
117
+ escapeTimeout = null;
118
+ }
119
+ switch (key) {
120
+ case 'up':
121
+ cursor = (cursor - 1 + items.length) % items.length;
122
+ render();
123
+ break;
124
+ case 'down':
125
+ cursor = (cursor + 1) % items.length;
126
+ render();
127
+ break;
128
+ case 'enter':
129
+ finish(items[cursor]?.value ?? null);
130
+ break;
131
+ case 'escape':
132
+ finish(null);
133
+ break;
134
+ case 'escape-start':
135
+ // A bare Escape byte is also the start of an arrow-key sequence
136
+ // that may arrive split across reads; only a lone one cancels.
137
+ escapeTimeout = setTimeout(() => finish(null), ESCAPE_TIMEOUT_MS);
138
+ break;
139
+ default:
140
+ break;
141
+ }
142
+ }
143
+ };
144
+ signals?.once('SIGINT', onSignal);
145
+ signals?.once('SIGTERM', onSignal);
146
+ try {
147
+ stdin.setRawMode(true);
148
+ }
149
+ catch {
150
+ cleanup();
151
+ resolve(null);
152
+ return;
153
+ }
154
+ stdin.resume();
155
+ stdout.write(ANSI.hide);
156
+ render();
157
+ stdin.on('data', onKey);
158
+ });
159
+ }