@cortexkit/opencode-antigravity-auth 1.1.0 → 2.0.1

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 (379) hide show
  1. package/README.md +225 -569
  2. package/dist/cli.js +4017 -0
  3. package/dist/cli.js.map +7 -0
  4. package/dist/index.d.ts +1 -3
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +20742 -14586
  7. package/dist/index.js.map +4 -4
  8. package/dist/src/antigravity/oauth.d.ts +1 -1
  9. package/dist/src/antigravity/oauth.js +1 -1
  10. package/dist/src/cli.d.ts +21 -0
  11. package/dist/src/cli.d.ts.map +1 -0
  12. package/dist/src/cli.js +237 -0
  13. package/dist/src/cli.js.map +1 -0
  14. package/dist/src/constants.d.ts +1 -1
  15. package/dist/src/constants.js +1 -1
  16. package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -1
  17. package/dist/src/hooks/auto-update-checker/cache.js +13 -13
  18. package/dist/src/hooks/auto-update-checker/cache.js.map +1 -1
  19. package/dist/src/hooks/auto-update-checker/checker.d.ts +1 -1
  20. package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -1
  21. package/dist/src/hooks/auto-update-checker/checker.js +75 -51
  22. package/dist/src/hooks/auto-update-checker/checker.js.map +1 -1
  23. package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -1
  24. package/dist/src/hooks/auto-update-checker/constants.js +12 -12
  25. package/dist/src/hooks/auto-update-checker/constants.js.map +1 -1
  26. package/dist/src/hooks/auto-update-checker/index.d.ts +6 -6
  27. package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -1
  28. package/dist/src/hooks/auto-update-checker/index.js +17 -17
  29. package/dist/src/hooks/auto-update-checker/index.js.map +1 -1
  30. package/dist/src/hooks/auto-update-checker/logging.js +2 -2
  31. package/dist/src/hooks/auto-update-checker/logging.js.map +1 -1
  32. package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -1
  33. package/dist/src/plugin/account-access.d.ts +99 -0
  34. package/dist/src/plugin/account-access.d.ts.map +1 -0
  35. package/dist/src/plugin/account-access.js +480 -0
  36. package/dist/src/plugin/account-access.js.map +1 -0
  37. package/dist/src/plugin/account-command-oauth.d.ts +34 -0
  38. package/dist/src/plugin/account-command-oauth.d.ts.map +1 -0
  39. package/dist/src/plugin/account-command-oauth.js +156 -0
  40. package/dist/src/plugin/account-command-oauth.js.map +1 -0
  41. package/dist/src/plugin/accounts.d.ts +7 -256
  42. package/dist/src/plugin/accounts.d.ts.map +1 -1
  43. package/dist/src/plugin/accounts.js +31 -1367
  44. package/dist/src/plugin/accounts.js.map +1 -1
  45. package/dist/src/plugin/agy-request-metadata.d.ts +1 -1
  46. package/dist/src/plugin/agy-request-metadata.js +1 -1
  47. package/dist/src/plugin/agy-transport.d.ts +1 -1
  48. package/dist/src/plugin/agy-transport.js +1 -1
  49. package/dist/src/plugin/auth-doctor.d.ts +6 -6
  50. package/dist/src/plugin/auth-doctor.d.ts.map +1 -1
  51. package/dist/src/plugin/auth-doctor.js +74 -66
  52. package/dist/src/plugin/auth-doctor.js.map +1 -1
  53. package/dist/src/plugin/auth-drift.d.ts +4 -4
  54. package/dist/src/plugin/auth-drift.d.ts.map +1 -1
  55. package/dist/src/plugin/auth-drift.js +15 -15
  56. package/dist/src/plugin/auth-drift.js.map +1 -1
  57. package/dist/src/plugin/auth-loader.d.ts +50 -0
  58. package/dist/src/plugin/auth-loader.d.ts.map +1 -0
  59. package/dist/src/plugin/auth-loader.js +225 -0
  60. package/dist/src/plugin/auth-loader.js.map +1 -0
  61. package/dist/src/plugin/auth.d.ts +1 -1
  62. package/dist/src/plugin/auth.js +1 -1
  63. package/dist/src/plugin/background-quota-refresh.d.ts +146 -0
  64. package/dist/src/plugin/background-quota-refresh.d.ts.map +1 -0
  65. package/dist/src/plugin/background-quota-refresh.js +347 -0
  66. package/dist/src/plugin/background-quota-refresh.js.map +1 -0
  67. package/dist/src/plugin/cache/index.d.ts +1 -1
  68. package/dist/src/plugin/cache/index.d.ts.map +1 -1
  69. package/dist/src/plugin/cache/index.js +1 -1
  70. package/dist/src/plugin/cache/index.js.map +1 -1
  71. package/dist/src/plugin/cache/signature-cache.d.ts +1 -1
  72. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -1
  73. package/dist/src/plugin/cache/signature-cache.js +23 -24
  74. package/dist/src/plugin/cache/signature-cache.js.map +1 -1
  75. package/dist/src/plugin/cache.d.ts +6 -5
  76. package/dist/src/plugin/cache.d.ts.map +1 -1
  77. package/dist/src/plugin/cache.js +21 -7
  78. package/dist/src/plugin/cache.js.map +1 -1
  79. package/dist/src/plugin/catalog.d.ts +23 -0
  80. package/dist/src/plugin/catalog.d.ts.map +1 -0
  81. package/dist/src/plugin/catalog.js +60 -0
  82. package/dist/src/plugin/catalog.js.map +1 -0
  83. package/dist/src/plugin/cli.d.ts +7 -7
  84. package/dist/src/plugin/cli.d.ts.map +1 -1
  85. package/dist/src/plugin/cli.js +62 -55
  86. package/dist/src/plugin/cli.js.map +1 -1
  87. package/dist/src/plugin/command-data.d.ts +329 -0
  88. package/dist/src/plugin/command-data.d.ts.map +1 -0
  89. package/dist/src/plugin/command-data.js +517 -0
  90. package/dist/src/plugin/command-data.js.map +1 -0
  91. package/dist/src/plugin/commands.d.ts +154 -0
  92. package/dist/src/plugin/commands.d.ts.map +1 -0
  93. package/dist/src/plugin/commands.js +746 -0
  94. package/dist/src/plugin/commands.js.map +1 -0
  95. package/dist/src/plugin/config/index.d.ts +2 -2
  96. package/dist/src/plugin/config/index.d.ts.map +1 -1
  97. package/dist/src/plugin/config/index.js +2 -2
  98. package/dist/src/plugin/config/index.js.map +1 -1
  99. package/dist/src/plugin/config/loader.d.ts +1 -1
  100. package/dist/src/plugin/config/loader.d.ts.map +1 -1
  101. package/dist/src/plugin/config/loader.js +18 -16
  102. package/dist/src/plugin/config/loader.js.map +1 -1
  103. package/dist/src/plugin/config/models.d.ts +2 -2
  104. package/dist/src/plugin/config/models.d.ts.map +1 -1
  105. package/dist/src/plugin/config/models.js +1 -1
  106. package/dist/src/plugin/config/models.js.map +1 -1
  107. package/dist/src/plugin/config/operator-settings-schema.d.ts +29 -0
  108. package/dist/src/plugin/config/operator-settings-schema.d.ts.map +1 -0
  109. package/dist/src/plugin/config/operator-settings-schema.js +28 -0
  110. package/dist/src/plugin/config/operator-settings-schema.js.map +1 -0
  111. package/dist/src/plugin/config/schema.d.ts +23 -2
  112. package/dist/src/plugin/config/schema.d.ts.map +1 -1
  113. package/dist/src/plugin/config/schema.js +109 -25
  114. package/dist/src/plugin/config/schema.js.map +1 -1
  115. package/dist/src/plugin/config/updater.d.ts.map +1 -1
  116. package/dist/src/plugin/config/updater.js +15 -15
  117. package/dist/src/plugin/config/updater.js.map +1 -1
  118. package/dist/src/plugin/config/writer.d.ts +34 -0
  119. package/dist/src/plugin/config/writer.d.ts.map +1 -0
  120. package/dist/src/plugin/config/writer.js +81 -0
  121. package/dist/src/plugin/config/writer.js.map +1 -0
  122. package/dist/src/plugin/core/streaming/index.d.ts +1 -1
  123. package/dist/src/plugin/core/streaming/index.d.ts.map +1 -1
  124. package/dist/src/plugin/core/streaming/index.js +1 -1
  125. package/dist/src/plugin/core/streaming/index.js.map +1 -1
  126. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  127. package/dist/src/plugin/core/streaming/transformer.js +85 -44
  128. package/dist/src/plugin/core/streaming/transformer.js.map +1 -1
  129. package/dist/src/plugin/core/streaming/types.d.ts.map +1 -1
  130. package/dist/src/plugin/debug.d.ts +10 -3
  131. package/dist/src/plugin/debug.d.ts.map +1 -1
  132. package/dist/src/plugin/debug.js +110 -47
  133. package/dist/src/plugin/debug.js.map +1 -1
  134. package/dist/src/plugin/dependencies.d.ts +129 -0
  135. package/dist/src/plugin/dependencies.d.ts.map +1 -0
  136. package/dist/src/plugin/dependencies.js +107 -0
  137. package/dist/src/plugin/dependencies.js.map +1 -0
  138. package/dist/src/plugin/errors.d.ts +27 -0
  139. package/dist/src/plugin/errors.d.ts.map +1 -1
  140. package/dist/src/plugin/errors.js +29 -3
  141. package/dist/src/plugin/errors.js.map +1 -1
  142. package/dist/src/plugin/event-handler.d.ts +53 -0
  143. package/dist/src/plugin/event-handler.d.ts.map +1 -0
  144. package/dist/src/plugin/event-handler.js +101 -0
  145. package/dist/src/plugin/event-handler.js.map +1 -0
  146. package/dist/src/plugin/fetch/retry-state.d.ts +61 -0
  147. package/dist/src/plugin/fetch/retry-state.d.ts.map +1 -0
  148. package/dist/src/plugin/fetch/retry-state.js +248 -0
  149. package/dist/src/plugin/fetch/retry-state.js.map +1 -0
  150. package/dist/src/plugin/fetch/warmup.d.ts +30 -0
  151. package/dist/src/plugin/fetch/warmup.d.ts.map +1 -0
  152. package/dist/src/plugin/fetch/warmup.js +76 -0
  153. package/dist/src/plugin/fetch/warmup.js.map +1 -0
  154. package/dist/src/plugin/fetch-interceptor.d.ts +59 -0
  155. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -0
  156. package/dist/src/plugin/fetch-interceptor.js +1399 -0
  157. package/dist/src/plugin/fetch-interceptor.js.map +1 -0
  158. package/dist/src/plugin/fetch-routing.d.ts +26 -0
  159. package/dist/src/plugin/fetch-routing.d.ts.map +1 -0
  160. package/dist/src/plugin/fetch-routing.js +99 -0
  161. package/dist/src/plugin/fetch-routing.js.map +1 -0
  162. package/dist/src/plugin/fingerprint.d.ts +1 -1
  163. package/dist/src/plugin/fingerprint.js +1 -1
  164. package/dist/src/plugin/gemini-dump.d.ts +5 -5
  165. package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
  166. package/dist/src/plugin/gemini-dump.js +109 -55
  167. package/dist/src/plugin/gemini-dump.js.map +1 -1
  168. package/dist/src/plugin/google-search-tool.d.ts +9 -0
  169. package/dist/src/plugin/google-search-tool.d.ts.map +1 -0
  170. package/dist/src/plugin/google-search-tool.js +56 -0
  171. package/dist/src/plugin/google-search-tool.js.map +1 -0
  172. package/dist/src/plugin/image-saver.d.ts.map +1 -1
  173. package/dist/src/plugin/image-saver.js +16 -16
  174. package/dist/src/plugin/image-saver.js.map +1 -1
  175. package/dist/src/plugin/index.d.ts +30 -0
  176. package/dist/src/plugin/index.d.ts.map +1 -0
  177. package/dist/src/plugin/index.js +411 -0
  178. package/dist/src/plugin/index.js.map +1 -0
  179. package/dist/src/plugin/killswitch.d.ts +94 -0
  180. package/dist/src/plugin/killswitch.d.ts.map +1 -0
  181. package/dist/src/plugin/killswitch.js +197 -0
  182. package/dist/src/plugin/killswitch.js.map +1 -0
  183. package/dist/src/plugin/lifecycle.d.ts +40 -0
  184. package/dist/src/plugin/lifecycle.d.ts.map +1 -0
  185. package/dist/src/plugin/lifecycle.js +73 -0
  186. package/dist/src/plugin/lifecycle.js.map +1 -0
  187. package/dist/src/plugin/logger.d.ts +10 -1
  188. package/dist/src/plugin/logger.d.ts.map +1 -1
  189. package/dist/src/plugin/logger.js +38 -12
  190. package/dist/src/plugin/logger.js.map +1 -1
  191. package/dist/src/plugin/logging-utils.d.ts +35 -1
  192. package/dist/src/plugin/logging-utils.d.ts.map +1 -1
  193. package/dist/src/plugin/logging-utils.js +98 -15
  194. package/dist/src/plugin/logging-utils.js.map +1 -1
  195. package/dist/src/plugin/model-registry.d.ts +1 -1
  196. package/dist/src/plugin/model-registry.js +1 -1
  197. package/dist/src/plugin/oauth-login.d.ts +22 -0
  198. package/dist/src/plugin/oauth-login.d.ts.map +1 -0
  199. package/dist/src/plugin/oauth-login.js +37 -0
  200. package/dist/src/plugin/oauth-login.js.map +1 -0
  201. package/dist/src/plugin/oauth-methods.d.ts +42 -0
  202. package/dist/src/plugin/oauth-methods.d.ts.map +1 -0
  203. package/dist/src/plugin/oauth-methods.js +1276 -0
  204. package/dist/src/plugin/oauth-methods.js.map +1 -0
  205. package/dist/src/plugin/operator-settings.d.ts +40 -0
  206. package/dist/src/plugin/operator-settings.d.ts.map +1 -0
  207. package/dist/src/plugin/operator-settings.js +148 -0
  208. package/dist/src/plugin/operator-settings.js.map +1 -0
  209. package/dist/src/plugin/persist-account-pool.d.ts +37 -0
  210. package/dist/src/plugin/persist-account-pool.d.ts.map +1 -0
  211. package/dist/src/plugin/persist-account-pool.js +142 -0
  212. package/dist/src/plugin/persist-account-pool.js.map +1 -0
  213. package/dist/src/plugin/project.d.ts +1 -1
  214. package/dist/src/plugin/project.js +1 -1
  215. package/dist/src/plugin/prompt-context.d.ts.map +1 -1
  216. package/dist/src/plugin/prompt-context.js +11 -11
  217. package/dist/src/plugin/prompt-context.js.map +1 -1
  218. package/dist/src/plugin/quota.d.ts +138 -41
  219. package/dist/src/plugin/quota.d.ts.map +1 -1
  220. package/dist/src/plugin/quota.js +417 -285
  221. package/dist/src/plugin/quota.js.map +1 -1
  222. package/dist/src/plugin/recovery/constants.d.ts.map +1 -1
  223. package/dist/src/plugin/recovery/constants.js +24 -15
  224. package/dist/src/plugin/recovery/constants.js.map +1 -1
  225. package/dist/src/plugin/recovery/index.d.ts +3 -3
  226. package/dist/src/plugin/recovery/index.d.ts.map +1 -1
  227. package/dist/src/plugin/recovery/index.js +3 -3
  228. package/dist/src/plugin/recovery/index.js.map +1 -1
  229. package/dist/src/plugin/recovery/storage.d.ts +1 -1
  230. package/dist/src/plugin/recovery/storage.d.ts.map +1 -1
  231. package/dist/src/plugin/recovery/storage.js +31 -39
  232. package/dist/src/plugin/recovery/storage.js.map +1 -1
  233. package/dist/src/plugin/recovery/types.d.ts +12 -12
  234. package/dist/src/plugin/recovery/types.d.ts.map +1 -1
  235. package/dist/src/plugin/recovery.d.ts +3 -3
  236. package/dist/src/plugin/recovery.d.ts.map +1 -1
  237. package/dist/src/plugin/recovery.js +62 -58
  238. package/dist/src/plugin/recovery.js.map +1 -1
  239. package/dist/src/plugin/refresh-queue.d.ts +5 -2
  240. package/dist/src/plugin/refresh-queue.d.ts.map +1 -1
  241. package/dist/src/plugin/refresh-queue.js +37 -15
  242. package/dist/src/plugin/refresh-queue.js.map +1 -1
  243. package/dist/src/plugin/request-helpers.d.ts +1 -1
  244. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  245. package/dist/src/plugin/request-helpers.js +451 -352
  246. package/dist/src/plugin/request-helpers.js.map +1 -1
  247. package/dist/src/plugin/request.d.ts +7 -7
  248. package/dist/src/plugin/request.d.ts.map +1 -1
  249. package/dist/src/plugin/request.js +622 -384
  250. package/dist/src/plugin/request.js.map +1 -1
  251. package/dist/src/plugin/rotation.d.ts +1 -168
  252. package/dist/src/plugin/rotation.d.ts.map +1 -1
  253. package/dist/src/plugin/rotation.js +1 -327
  254. package/dist/src/plugin/rotation.js.map +1 -1
  255. package/dist/src/plugin/search.d.ts.map +1 -1
  256. package/dist/src/plugin/search.js +39 -35
  257. package/dist/src/plugin/search.js.map +1 -1
  258. package/dist/src/plugin/server.d.ts +1 -1
  259. package/dist/src/plugin/server.d.ts.map +1 -1
  260. package/dist/src/plugin/server.js +42 -37
  261. package/dist/src/plugin/server.js.map +1 -1
  262. package/dist/src/plugin/session-context.d.ts +2 -1
  263. package/dist/src/plugin/session-context.d.ts.map +1 -1
  264. package/dist/src/plugin/session-context.js +11 -7
  265. package/dist/src/plugin/session-context.js.map +1 -1
  266. package/dist/src/plugin/storage.d.ts +59 -120
  267. package/dist/src/plugin/storage.d.ts.map +1 -1
  268. package/dist/src/plugin/storage.js +140 -485
  269. package/dist/src/plugin/storage.js.map +1 -1
  270. package/dist/src/plugin/stores/signature-store.d.ts.map +1 -1
  271. package/dist/src/plugin/stores/signature-store.js.map +1 -1
  272. package/dist/src/plugin/thinking-recovery.d.ts.map +1 -1
  273. package/dist/src/plugin/thinking-recovery.js +35 -33
  274. package/dist/src/plugin/thinking-recovery.js.map +1 -1
  275. package/dist/src/plugin/token.d.ts +2 -2
  276. package/dist/src/plugin/token.d.ts.map +1 -1
  277. package/dist/src/plugin/token.js +30 -21
  278. package/dist/src/plugin/token.js.map +1 -1
  279. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +1 -1
  280. package/dist/src/plugin/transform/cross-model-sanitizer.js +1 -1
  281. package/dist/src/plugin/transform/index.d.ts +1 -1
  282. package/dist/src/plugin/transform/index.js +1 -1
  283. package/dist/src/plugin/transform/model-resolver.d.ts +1 -1
  284. package/dist/src/plugin/transform/model-resolver.js +1 -1
  285. package/dist/src/plugin/transform/types.d.ts +1 -1
  286. package/dist/src/plugin/transform/types.js +1 -1
  287. package/dist/src/plugin/types.d.ts +25 -69
  288. package/dist/src/plugin/types.d.ts.map +1 -1
  289. package/dist/src/plugin/ui/ansi.d.ts.map +1 -1
  290. package/dist/src/plugin/ui/ansi.js.map +1 -1
  291. package/dist/src/plugin/ui/auth-menu.d.ts +1 -1
  292. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -1
  293. package/dist/src/plugin/ui/auth-menu.js +84 -35
  294. package/dist/src/plugin/ui/auth-menu.js.map +1 -1
  295. package/dist/src/plugin/ui/confirm.d.ts.map +1 -1
  296. package/dist/src/plugin/ui/confirm.js.map +1 -1
  297. package/dist/src/plugin/ui/model-status.d.ts +3 -3
  298. package/dist/src/plugin/ui/model-status.d.ts.map +1 -1
  299. package/dist/src/plugin/ui/model-status.js +3 -3
  300. package/dist/src/plugin/ui/model-status.js.map +1 -1
  301. package/dist/src/plugin/ui/quota-status.d.ts +4 -4
  302. package/dist/src/plugin/ui/quota-status.d.ts.map +1 -1
  303. package/dist/src/plugin/ui/quota-status.js +49 -49
  304. package/dist/src/plugin/ui/quota-status.js.map +1 -1
  305. package/dist/src/plugin/ui/select.d.ts.map +1 -1
  306. package/dist/src/plugin/ui/select.js +22 -12
  307. package/dist/src/plugin/ui/select.js.map +1 -1
  308. package/dist/src/plugin/version.d.ts +1 -1
  309. package/dist/src/plugin/version.js +1 -1
  310. package/dist/src/rpc/notifications.d.ts +6 -0
  311. package/dist/src/rpc/notifications.d.ts.map +1 -0
  312. package/dist/src/rpc/notifications.js +46 -0
  313. package/dist/src/rpc/notifications.js.map +1 -0
  314. package/dist/src/rpc/port-file.d.ts +13 -0
  315. package/dist/src/rpc/port-file.d.ts.map +1 -0
  316. package/dist/src/rpc/port-file.js +109 -0
  317. package/dist/src/rpc/port-file.js.map +1 -0
  318. package/dist/src/rpc/protocol.d.ts +22 -0
  319. package/dist/src/rpc/protocol.d.ts.map +1 -0
  320. package/dist/src/rpc/protocol.js +1 -0
  321. package/dist/src/rpc/protocol.js.map +1 -0
  322. package/dist/src/rpc/rpc-client.d.ts +10 -0
  323. package/dist/src/rpc/rpc-client.d.ts.map +1 -0
  324. package/dist/src/rpc/rpc-client.js +58 -0
  325. package/dist/src/rpc/rpc-client.js.map +1 -0
  326. package/dist/src/rpc/rpc-dir.d.ts +4 -0
  327. package/dist/src/rpc/rpc-dir.d.ts.map +1 -0
  328. package/dist/src/rpc/rpc-dir.js +19 -0
  329. package/dist/src/rpc/rpc-dir.js.map +1 -0
  330. package/dist/src/rpc/rpc-server.d.ts +13 -0
  331. package/dist/src/rpc/rpc-server.d.ts.map +1 -0
  332. package/dist/src/rpc/rpc-server.js +231 -0
  333. package/dist/src/rpc/rpc-server.js.map +1 -0
  334. package/dist/src/sidebar-state.d.ts +357 -0
  335. package/dist/src/sidebar-state.d.ts.map +1 -0
  336. package/dist/src/sidebar-state.js +680 -0
  337. package/dist/src/sidebar-state.js.map +1 -0
  338. package/dist/src/tui/command-dialogs.d.ts +61 -0
  339. package/dist/src/tui/command-dialogs.d.ts.map +1 -0
  340. package/dist/src/tui/command-dialogs.js +595 -0
  341. package/dist/src/tui/command-dialogs.js.map +1 -0
  342. package/dist/src/tui/file-logger.d.ts +41 -0
  343. package/dist/src/tui/file-logger.d.ts.map +1 -0
  344. package/dist/src/tui/file-logger.js +114 -0
  345. package/dist/src/tui/file-logger.js.map +1 -0
  346. package/dist/src/tui-preferences.d.ts +40 -0
  347. package/dist/src/tui-preferences.d.ts.map +1 -0
  348. package/dist/src/tui-preferences.js +328 -0
  349. package/dist/src/tui-preferences.js.map +1 -0
  350. package/dist/src/tui.d.ts +68 -0
  351. package/dist/src/tui.d.ts.map +1 -0
  352. package/dist/src/tui.js +697 -0
  353. package/dist/src/tui.js.map +1 -0
  354. package/package.json +46 -22
  355. package/src/plugin/command-data.ts +931 -0
  356. package/src/rpc/port-file.ts +143 -0
  357. package/src/rpc/protocol.ts +31 -0
  358. package/src/rpc/rpc-client.ts +102 -0
  359. package/src/rpc/rpc-dir.ts +24 -0
  360. package/src/sidebar-state.ts +991 -0
  361. package/src/tui/command-dialogs.tsx +832 -0
  362. package/src/tui/entry.mjs +74 -0
  363. package/src/tui/file-logger.ts +145 -0
  364. package/src/tui-compiled/plugin/command-data.ts +931 -0
  365. package/src/tui-compiled/rpc/port-file.ts +143 -0
  366. package/src/tui-compiled/rpc/protocol.ts +31 -0
  367. package/src/tui-compiled/rpc/rpc-client.ts +102 -0
  368. package/src/tui-compiled/rpc/rpc-dir.ts +24 -0
  369. package/src/tui-compiled/sidebar-state.ts +991 -0
  370. package/src/tui-compiled/tui/command-dialogs.tsx +779 -0
  371. package/src/tui-compiled/tui/file-logger.ts +145 -0
  372. package/src/tui-compiled/tui-preferences.ts +416 -0
  373. package/src/tui-compiled/tui.tsx +1193 -0
  374. package/src/tui-preferences.ts +416 -0
  375. package/src/tui.tsx +1171 -0
  376. package/dist/src/plugin.d.ts +0 -48
  377. package/dist/src/plugin.d.ts.map +0 -1
  378. package/dist/src/plugin.js +0 -3311
  379. package/dist/src/plugin.js.map +0 -1
@@ -0,0 +1,680 @@
1
+ /**
2
+ * Sidebar state contract for the OpenTUI sidebar.
3
+ *
4
+ * This module is the read-only seam between the long-running plugin and the
5
+ * Solid/OpenTUI sidebar tree. It deliberately does NOT import account storage,
6
+ * the account manager, OAuth code, or any other privileged host-side module:
7
+ * the TUI is rendered inside the host's terminal and a single stray import
8
+ * could leak credentials or pull a heavy manager into the render path.
9
+ *
10
+ * The plugin writes a redacted snapshot to the file resolved by
11
+ * `getSidebarStateFile()` and the TUI polls it. The contract version is `1`:
12
+ * any future field that the TUI cannot understand must be ignored, and any
13
+ * broken/missing file must collapse to `DEFAULT_SIDEBAR_STATE`.
14
+ *
15
+ * ## Writer surface
16
+ *
17
+ * The plugin-side writers live here too so the read and write halves of the
18
+ * contract evolve together. They are imported by the plugin (auth-loader,
19
+ * quota, fetch-interceptor, event-handler, commands) but never invoked from
20
+ * the TUI's compiled tree — that tree only calls the readers, so the
21
+ * heavyweight core imports below never run inside the host's render path.
22
+ *
23
+ * Every disk mutation follows the same recipe:
24
+ *
25
+ * 1. Serialize through `sidebarWriteChain` so concurrent in-process calls
26
+ * never interleave merges against the same file.
27
+ * 2. Acquire Task 7's `acquireFencedFileLock` with bounded retry+jitter
28
+ * (≤2s). A live cross-process holder that does not release in time
29
+ * surfaces as `SidebarStateLockContentionError`.
30
+ * 3. Re-read and normalize the on-disk state while holding the lock.
31
+ * 4. Merge the new machine or routing payload against the re-read state.
32
+ * 5. `assertOwned()` + `writeJsonAtomic` with mode 0o600, then release.
33
+ *
34
+ * The merge step is deterministic: machine fields adopt only when the new
35
+ * `checkedAt` is ≥ the on-disk one, `routingAuthoritative` is sticky-true,
36
+ * and `activeRouting` is merged independently and pruned to the freshest
37
+ * 100 entries within 24h.
38
+ */
39
+ import { mkdirSync, readFileSync } from 'node:fs';
40
+ import { homedir } from 'node:os';
41
+ import { dirname, join } from 'node:path';
42
+ // Subpath imports (not the barrel): this file ships into the TUI's
43
+ // compiled tree, and the barrel re-exports account/OAuth/quota modules
44
+ // that must never execute inside the host's render path.
45
+ import { writeJsonAtomic } from '@cortexkit/antigravity-auth-core/atomic-write';
46
+ import { acquireFencedFileLock, } from '@cortexkit/antigravity-auth-core/file-lock';
47
+ import { xdgState } from 'xdg-basedir';
48
+ export const SIDEBAR_STATE_VERSION = 1;
49
+ export const DEFAULT_SIDEBAR_STATE = {
50
+ version: SIDEBAR_STATE_VERSION,
51
+ checkedAt: 0,
52
+ accounts: [],
53
+ activeRouting: {},
54
+ routingAuthoritative: false,
55
+ };
56
+ export const SIDEBAR_STATE_ENV = 'ANTIGRAVITY_AUTH_SIDEBAR_STATE_FILE';
57
+ const SIDEBAR_STATE_DIR = 'cortexkit/antigravity-auth';
58
+ const SIDEBAR_STATE_FILENAME = 'sidebar-state.json';
59
+ /** Active routing entries older than this are dropped on every merge. */
60
+ const ACTIVE_ROUTING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
61
+ /** Active routing map is capped at this many newest entries. */
62
+ const ACTIVE_ROUTING_MAX_ENTRIES = 100;
63
+ const SIDEBAR_LOCK_NAME = 'sidebar';
64
+ const SIDEBAR_LOCK_TTL_MS = 10_000;
65
+ const SIDEBAR_LOCK_TIMEOUT_MS = 2_000;
66
+ const SIDEBAR_LOCK_RETRY_BASE_MS = 25;
67
+ const SIDEBAR_LOCK_RETRY_CAP_MS = 75;
68
+ const SIDEBAR_LOCK_JITTER_MS = 25;
69
+ const SIDEBAR_STATE_DIR_MODE = 0o700;
70
+ const SIDEBAR_STATE_FILE_MODE = 0o600;
71
+ /**
72
+ * Thrown by every writer when the cross-process lock cannot be acquired
73
+ * within `SIDEBAR_LOCK_TIMEOUT_MS`. The caller decides whether to surface
74
+ * a toast, drop the write, or retry the next tick.
75
+ */
76
+ export class SidebarStateLockContentionError extends Error {
77
+ details;
78
+ constructor(stateFile, timeoutMs) {
79
+ super(`Could not acquire sidebar-state lock at ${stateFile} within ${timeoutMs}ms`);
80
+ this.name = 'SidebarStateLockContentionError';
81
+ this.details = { stateFile, timeoutMs };
82
+ }
83
+ }
84
+ let sidebarMergeHooks = null;
85
+ /**
86
+ * Install (or clear with `null`) the deterministic race hooks. Tests use
87
+ * these to inject interleavings; production callers leave them unset. The
88
+ * module-level state means a test must reset hooks in its own `afterEach`
89
+ * to avoid bleeding into the next test.
90
+ */
91
+ export function setSidebarMergeHooks(hooks) {
92
+ sidebarMergeHooks = hooks;
93
+ }
94
+ async function emitMergeStep(step) {
95
+ await sidebarMergeHooks?.onStep?.(step);
96
+ }
97
+ /**
98
+ * Resolve the on-disk path the plugin writes to and the TUI reads from.
99
+ *
100
+ * - `ANTIGRAVITY_AUTH_SIDEBAR_STATE_FILE` wins when set (tests, packaged
101
+ * installers, and any user override).
102
+ * - Otherwise fall back to the XDG state directory, mirroring the path
103
+ * conventions used elsewhere in the project.
104
+ */
105
+ export function getSidebarStateFile() {
106
+ const override = process.env[SIDEBAR_STATE_ENV];
107
+ if (override && override.trim().length > 0)
108
+ return override;
109
+ const base = xdgState ?? join(homedir(), '.local', 'state');
110
+ return join(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
111
+ }
112
+ /**
113
+ * Read and normalize the sidebar state file. Returns the default state when
114
+ * the file is missing, unreadable, malformed, or schema-incompatible — the TUI
115
+ * must never throw out of `readSidebarState()`, the panel just shows
116
+ * "Awaiting Antigravity state" and the next poll retries.
117
+ *
118
+ * The read is sync on purpose: the TUI polls on a 2-second timer and the file
119
+ * is tiny (a handful of accounts); an async read here would just add race
120
+ * surface area against Solid's reactive render cycle.
121
+ */
122
+ export function readSidebarState(path = getSidebarStateFile()) {
123
+ let raw;
124
+ try {
125
+ raw = readFileSync(path, 'utf-8');
126
+ }
127
+ catch {
128
+ return { ...DEFAULT_SIDEBAR_STATE };
129
+ }
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(raw);
133
+ }
134
+ catch {
135
+ return { ...DEFAULT_SIDEBAR_STATE, lastError: 'malformed-json' };
136
+ }
137
+ return normalizeSidebarState(parsed);
138
+ }
139
+ function normalizeSidebarState(input) {
140
+ if (!isObject(input)) {
141
+ return { ...DEFAULT_SIDEBAR_STATE, lastError: 'shape' };
142
+ }
143
+ const record = input;
144
+ const version = record.version;
145
+ if (version !== SIDEBAR_STATE_VERSION) {
146
+ return {
147
+ ...DEFAULT_SIDEBAR_STATE,
148
+ lastError: `unsupported-version:${stringifySafe(version)}`,
149
+ };
150
+ }
151
+ const accountsRaw = record.accounts;
152
+ const accounts = Array.isArray(accountsRaw)
153
+ ? accountsRaw
154
+ .map((entry) => normalizeAccount(entry))
155
+ .filter((entry) => entry !== null)
156
+ : [];
157
+ const routingRaw = record.activeRouting;
158
+ const activeRouting = {};
159
+ if (isObject(routingRaw)) {
160
+ for (const [sessionId, entry] of Object.entries(routingRaw)) {
161
+ const normalized = normalizeRouting(entry);
162
+ if (normalized)
163
+ activeRouting[sessionId] = normalized;
164
+ }
165
+ }
166
+ const checkedAt = toFiniteNumber(record.checkedAt);
167
+ const routingAuthoritative = record.routingAuthoritative === true;
168
+ const quotaBackoffUntil = toFiniteNumber(record.quotaBackoffUntil);
169
+ const lastError = typeof record.lastError === 'string' ? record.lastError : undefined;
170
+ return {
171
+ version: SIDEBAR_STATE_VERSION,
172
+ checkedAt: checkedAt ?? 0,
173
+ accounts,
174
+ activeRouting,
175
+ routingAuthoritative,
176
+ quotaBackoffUntil: quotaBackoffUntil ?? undefined,
177
+ lastError,
178
+ };
179
+ }
180
+ function normalizeAccount(input) {
181
+ if (!isObject(input))
182
+ return null;
183
+ const record = input;
184
+ const id = typeof record.id === 'string' ? record.id : null;
185
+ const label = typeof record.label === 'string' ? record.label : null;
186
+ if (!id || !label)
187
+ return null;
188
+ const enabled = record.enabled !== false;
189
+ const health = clampNumber(toFiniteNumber(record.health), 0, 100);
190
+ const current = record.current === true;
191
+ const cooldownUntil = toFiniteNumber(record.cooldownUntil) ?? undefined;
192
+ const quotaRaw = record.quota;
193
+ const quota = {};
194
+ if (isObject(quotaRaw)) {
195
+ for (const key of ['gemini', 'non-gemini']) {
196
+ const entry = quotaRaw[key];
197
+ const normalized = normalizeQuota(entry);
198
+ if (normalized)
199
+ quota[key] = normalized;
200
+ }
201
+ }
202
+ const tier = normalizeTier(record.tier);
203
+ return {
204
+ id,
205
+ label,
206
+ enabled,
207
+ health,
208
+ current,
209
+ cooldownUntil,
210
+ quota,
211
+ ...(tier !== undefined ? { tier } : {}),
212
+ };
213
+ }
214
+ function normalizeTier(input) {
215
+ if (!isObject(input))
216
+ return undefined;
217
+ const record = input;
218
+ const id = typeof record.id === 'string' && record.id.length > 0 ? record.id : null;
219
+ const capturedAt = toFiniteNumber(record.capturedAt);
220
+ if (!id || capturedAt === null)
221
+ return undefined;
222
+ const paidId = typeof record.paidId === 'string' && record.paidId.length > 0
223
+ ? record.paidId
224
+ : undefined;
225
+ return { id, ...(paidId ? { paidId } : {}), capturedAt };
226
+ }
227
+ function normalizeQuota(input) {
228
+ if (!isObject(input))
229
+ return null;
230
+ const record = input;
231
+ const remaining = toFiniteNumber(record.remainingPercent);
232
+ if (remaining === null)
233
+ return null;
234
+ const resetAt = toFiniteNumber(record.resetAt) ?? undefined;
235
+ // Tolerant: deserialize windows array if present; drop malformed entries.
236
+ const windowsRaw = record.windows;
237
+ let windows;
238
+ if (Array.isArray(windowsRaw)) {
239
+ const parsed = windowsRaw
240
+ .filter(isObject)
241
+ .map((w) => {
242
+ const win = w.window;
243
+ const rp = toFiniteNumber(w.remainingPercent);
244
+ const ra = toFiniteNumber(w.resetAt);
245
+ if ((win !== 'weekly' && win !== '5h') || rp === null)
246
+ return null;
247
+ return {
248
+ window: win,
249
+ remainingPercent: clampNumber(rp, 0, 100),
250
+ resetAt: ra ?? undefined,
251
+ };
252
+ })
253
+ .filter((v) => v !== null);
254
+ if (parsed.length > 0)
255
+ windows = parsed;
256
+ }
257
+ return {
258
+ remainingPercent: clampNumber(remaining, 0, 100),
259
+ resetAt,
260
+ windows,
261
+ };
262
+ }
263
+ function normalizeRouting(input) {
264
+ if (!isObject(input))
265
+ return null;
266
+ const record = input;
267
+ const accountId = typeof record.accountId === 'string' ? record.accountId : null;
268
+ const modelFamily = record.modelFamily;
269
+ const headerStyle = record.headerStyle;
270
+ const strategy = record.strategy;
271
+ const updatedAt = toFiniteNumber(record.updatedAt) ?? 0;
272
+ if (!accountId ||
273
+ (modelFamily !== 'claude' && modelFamily !== 'gemini') ||
274
+ (headerStyle !== 'antigravity' && headerStyle !== 'gemini-cli')) {
275
+ return null;
276
+ }
277
+ return {
278
+ accountId,
279
+ modelFamily,
280
+ headerStyle,
281
+ strategy: strategy === 'sticky' ||
282
+ strategy === 'round-robin' ||
283
+ strategy === 'hybrid'
284
+ ? strategy
285
+ : undefined,
286
+ updatedAt,
287
+ };
288
+ }
289
+ function isObject(value) {
290
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
291
+ }
292
+ function toFiniteNumber(value) {
293
+ if (typeof value === 'number' && Number.isFinite(value))
294
+ return value;
295
+ if (typeof value === 'string') {
296
+ const parsed = Number(value);
297
+ return Number.isFinite(parsed) ? parsed : null;
298
+ }
299
+ return null;
300
+ }
301
+ function clampNumber(value, min, max) {
302
+ if (value === null)
303
+ return min;
304
+ if (value < min)
305
+ return min;
306
+ if (value > max)
307
+ return max;
308
+ return value;
309
+ }
310
+ function stringifySafe(value) {
311
+ if (typeof value === 'string')
312
+ return value;
313
+ try {
314
+ return JSON.stringify(value) ?? 'unknown';
315
+ }
316
+ catch {
317
+ return 'unknown';
318
+ }
319
+ }
320
+ /**
321
+ * Ensure the parent directory for the sidebar state file exists. Convenience
322
+ * helper used by writers (tests, plugins) — the TUI itself does not write.
323
+ */
324
+ export function ensureSidebarStateDir(path = getSidebarStateFile()) {
325
+ mkdirSync(dirname(path), { recursive: true, mode: SIDEBAR_STATE_DIR_MODE });
326
+ }
327
+ /**
328
+ * Drop active-routing entries older than 24h and cap the map at the freshest
329
+ * 100. Pure helper exposed for unit testing; the writers call it on every
330
+ * merge so the on-disk map never grows without bound.
331
+ */
332
+ export function pruneActiveRouting(map, now) {
333
+ const cutoff = now - ACTIVE_ROUTING_MAX_AGE_MS;
334
+ const filtered = [];
335
+ for (const [sessionId, entry] of Object.entries(map)) {
336
+ if (entry.updatedAt >= cutoff) {
337
+ filtered.push([sessionId, entry]);
338
+ }
339
+ }
340
+ filtered.sort((a, b) => b[1].updatedAt - a[1].updatedAt);
341
+ if (filtered.length <= ACTIVE_ROUTING_MAX_ENTRIES) {
342
+ return Object.fromEntries(filtered);
343
+ }
344
+ return Object.fromEntries(filtered.slice(0, ACTIVE_ROUTING_MAX_ENTRIES));
345
+ }
346
+ /**
347
+ * Build a `{ id, capturedAt }` tier object from account fields, or `undefined`
348
+ * when either field is absent. Centralised so every producer (index.ts,
349
+ * background-quota-refresh.ts, command-data.ts) uses the same guard and the
350
+ * same shape -- the same pattern shipped as inline literals across three files
351
+ * and produced six missed-field bugs; one helper ends that.
352
+ */
353
+ export function toCapturedTier(account) {
354
+ return account.capturedTierId !== undefined &&
355
+ account.capturedTierAt !== undefined
356
+ ? {
357
+ id: account.capturedTierId,
358
+ ...(account.capturedPaidTierId !== undefined
359
+ ? { paidId: account.capturedPaidTierId }
360
+ : {}),
361
+ capturedAt: account.capturedTierAt,
362
+ }
363
+ : undefined;
364
+ }
365
+ /**
366
+ * Map pre-pool legacy quota keys to the current two-pool schema at read time.
367
+ *
368
+ * Legacy mappings (empirically settled from burn tests):
369
+ * `gemini-pro` + `gemini-flash` → `gemini`
370
+ * `claude` + `gpt-oss` → `non-gemini`
371
+ *
372
+ * Where multiple legacy keys collapse into one pool the MIN remainingFraction
373
+ * and earliest resetTime are used (most-constrained-first, matching the
374
+ * window-level rule). No `windows` arrays are invented for migrated entries;
375
+ * the single aggregate bar is the correct render for pre-window snapshots.
376
+ *
377
+ * Non-legacy keys that are already canonical (`gemini`, `non-gemini`) are
378
+ * carried through unchanged. The next real quota refresh overwrites any
379
+ * migrated snapshot with authoritative data.
380
+ */
381
+ export function normalizeLegacyCachedQuota(raw) {
382
+ if (!raw)
383
+ return raw;
384
+ // Pool already carries current keys — fast path when no legacy keys present.
385
+ const hasLegacy = 'gemini-pro' in raw ||
386
+ 'gemini-flash' in raw ||
387
+ 'claude' in raw ||
388
+ 'gpt-oss' in raw;
389
+ if (!hasLegacy)
390
+ return raw;
391
+ // Pick the earlier of two ISO reset timestamps, preferring a defined
392
+ // value over undefined. Extracted so both branches of minFraction use
393
+ // the same merge rather than the previous asymmetry where the a-wins
394
+ // branch dropped b's possibly-earlier resetTime.
395
+ const earlierResetTime = (a, b) => {
396
+ if (!a)
397
+ return b;
398
+ if (!b)
399
+ return a;
400
+ return a < b ? a : b;
401
+ };
402
+ const minFraction = (a, b) => {
403
+ if (!a)
404
+ return b;
405
+ if (!b)
406
+ return a;
407
+ const fa = a.remainingFraction ?? 1;
408
+ const fb = b.remainingFraction ?? 1;
409
+ const winner = fa <= fb ? a : b;
410
+ const loser = fa <= fb ? b : a;
411
+ // Always merge to the earliest resetTime regardless of which pool wins
412
+ // the fraction comparison — an earlier window expiry from the loser
413
+ // pool must not be silently dropped.
414
+ return {
415
+ ...winner,
416
+ resetTime: earlierResetTime(winner.resetTime, loser.resetTime),
417
+ };
418
+ };
419
+ const gemini = minFraction(raw.gemini, minFraction(raw['gemini-pro'], raw['gemini-flash'])) ?? raw.gemini;
420
+ const nonGemini = minFraction(raw['non-gemini'], minFraction(raw.claude, raw['gpt-oss'])) ?? raw['non-gemini'];
421
+ return {
422
+ ...(gemini !== undefined ? { gemini } : {}),
423
+ ...(nonGemini !== undefined ? { 'non-gemini': nonGemini } : {}),
424
+ };
425
+ }
426
+ /**
427
+ * Project a raw cachedQuota pool entry into the sidebar-safe shape.
428
+ *
429
+ * Centralized seam — every producer (quota.ts pushSidebarQuotaSnapshot,
430
+ * auth-loader.ts materializer, command-data.ts writeSidebar) routes
431
+ * through here so the `windows` array is never dropped by an inline
432
+ * `{ remainingFraction, resetTime }` literal.
433
+ *
434
+ * Tolerant: returns `undefined` when the source is missing or the
435
+ * `remainingFraction` is not a finite number. Legacy entries without
436
+ * `windows` produce `{ remainingPercent, resetAt }` only — the TUI's
437
+ * legacy path then renders a single bar.
438
+ */
439
+ export function projectQuotaPoolForSidebar(source) {
440
+ const fraction = source.remainingFraction;
441
+ if (typeof fraction !== 'number' || !Number.isFinite(fraction))
442
+ return undefined;
443
+ const remainingPercent = clampNumber(Math.round(fraction * 100), 0, 100);
444
+ let resetAt;
445
+ if (typeof source.resetTime === 'string' && source.resetTime.length > 0) {
446
+ const parsed = Date.parse(source.resetTime);
447
+ if (Number.isFinite(parsed))
448
+ resetAt = parsed;
449
+ }
450
+ const windows = source.windows?.length
451
+ ? source.windows.map((w) => ({
452
+ window: w.window,
453
+ remainingPercent: clampNumber(Math.round(w.remainingFraction * 100), 0, 100),
454
+ resetAt: typeof w.resetTime === 'string' && w.resetTime.length > 0
455
+ ? (() => {
456
+ const parsed = Date.parse(w.resetTime);
457
+ return Number.isFinite(parsed) ? parsed : undefined;
458
+ })()
459
+ : undefined,
460
+ }))
461
+ : undefined;
462
+ return { remainingPercent, resetAt, windows };
463
+ }
464
+ /**
465
+ * Returns `true` when an account at `index` is the active account for
466
+ * at least one model family. Two accounts CAN both be current — one
467
+ * serving claude, one serving gemini — so this must not collapse to one.
468
+ */
469
+ export function isAccountCurrent(index, activeIndexByFamily) {
470
+ return (index === activeIndexByFamily.claude || index === activeIndexByFamily.gemini);
471
+ }
472
+ /**
473
+ * Convert a live account snapshot into the redacted shape the TUI renders.
474
+ * The redacted `SidebarAccountState` carries no email, refresh token, access
475
+ * token, project ID, fingerprint, OAuth profile name, or other personal or
476
+ * credential-shaped fields. Display labels are generated ordinal account names.
477
+ */
478
+ export function redactAccountForSidebar(source) {
479
+ const id = `acct-${source.index}`;
480
+ const label = `Account ${source.index + 1}`;
481
+ const enabled = source.enabled !== false;
482
+ const current = source.current === true;
483
+ const cooldownUntil = typeof source.coolingDownUntil === 'number' &&
484
+ Number.isFinite(source.coolingDownUntil)
485
+ ? source.coolingDownUntil
486
+ : undefined;
487
+ const health = clampNumber(typeof source.healthScore === 'number' ? source.healthScore : 100, 0, 100);
488
+ const quota = {};
489
+ // Stamp mismatch: the persisted quota snapshot was captured for a
490
+ // different account than the one currently at this index. Drop the
491
+ // stale cache rather than rendering the wrong account's quota
492
+ // percentages. Mirrors `toCommandAccountRow` in command-data.
493
+ const staleCachedQuota = typeof source.cachedQuotaAccountId === 'string' &&
494
+ typeof source.currentQuotaAccountId === 'string' &&
495
+ source.cachedQuotaAccountId !== source.currentQuotaAccountId;
496
+ // Normalize legacy per-pool keys to the current two-pool schema before
497
+ // reading. This is non-destructive: the next real quota refresh will
498
+ // overwrite the migrated snapshot with authoritative data.
499
+ const cached = staleCachedQuota
500
+ ? undefined
501
+ : normalizeLegacyCachedQuota(source.cachedQuota);
502
+ if (cached) {
503
+ for (const key of ['gemini', 'non-gemini']) {
504
+ const entry = cached[key];
505
+ if (!entry)
506
+ continue;
507
+ const projected = projectQuotaPoolForSidebar(entry);
508
+ if (projected)
509
+ quota[key] = projected;
510
+ }
511
+ }
512
+ return {
513
+ id,
514
+ label,
515
+ enabled,
516
+ health,
517
+ current,
518
+ cooldownUntil,
519
+ quota,
520
+ // Tier is plan metadata, not PII — it passes the redaction boundary.
521
+ ...(source.tier !== undefined ? { tier: source.tier } : {}),
522
+ };
523
+ }
524
+ /**
525
+ * Build a `SidebarMachineState` from a list of live account snapshots.
526
+ * Convenience for the auth-loader / quota writer call sites that already
527
+ * hold an array of accounts and want to push a single snapshot.
528
+ */
529
+ export function buildSidebarMachineStateFromAccounts(accounts, options = {}) {
530
+ return {
531
+ checkedAt: options.checkedAt ?? Date.now(),
532
+ accounts: accounts.map((entry) => redactAccountForSidebar(entry)),
533
+ quotaBackoffUntil: options.quotaBackoffUntil,
534
+ lastError: options.lastError,
535
+ routingAuthoritative: options.routingAuthoritative,
536
+ };
537
+ }
538
+ let sidebarWriteChain = Promise.resolve();
539
+ function enqueueSidebarWrite(work) {
540
+ // Always run `work` regardless of whether the prior link resolved or
541
+ // rejected — a failed write must not poison the chain for the next caller.
542
+ const next = sidebarWriteChain.then(work, work);
543
+ sidebarWriteChain = next.then(() => undefined, () => undefined);
544
+ return next;
545
+ }
546
+ /**
547
+ * Wait for any in-flight sidebar state write to drain. The plugin lifecycle
548
+ * calls this during `dispose()` so the file logger and RPC server are torn
549
+ * down only after every queued write has either landed or thrown.
550
+ */
551
+ export function drainSidebarWrites() {
552
+ return sidebarWriteChain;
553
+ }
554
+ async function sleep(ms) {
555
+ await new Promise((resolve) => setTimeout(resolve, ms));
556
+ }
557
+ async function acquireSidebarLockWithRetry(stateFile) {
558
+ const start = Date.now();
559
+ let attempt = 0;
560
+ while (true) {
561
+ await emitMergeStep('await-lock');
562
+ const lock = await acquireFencedFileLock({
563
+ path: stateFile,
564
+ name: SIDEBAR_LOCK_NAME,
565
+ ttlMs: SIDEBAR_LOCK_TTL_MS,
566
+ renew: true,
567
+ });
568
+ if (lock) {
569
+ await emitMergeStep('acquired-lock');
570
+ return lock;
571
+ }
572
+ const elapsed = Date.now() - start;
573
+ if (elapsed >= SIDEBAR_LOCK_TIMEOUT_MS) {
574
+ throw new SidebarStateLockContentionError(stateFile, SIDEBAR_LOCK_TIMEOUT_MS);
575
+ }
576
+ const backoff = Math.min(SIDEBAR_LOCK_RETRY_CAP_MS, SIDEBAR_LOCK_RETRY_BASE_MS + attempt * 10);
577
+ const jitter = Math.floor(Math.random() * SIDEBAR_LOCK_JITTER_MS);
578
+ await sleep(backoff + jitter);
579
+ attempt++;
580
+ }
581
+ }
582
+ async function performSidebarWrite(stateFile, merge) {
583
+ await enqueueSidebarWrite(async () => {
584
+ ensureSidebarStateDir(stateFile);
585
+ const lock = await acquireSidebarLockWithRetry(stateFile);
586
+ try {
587
+ await lock.assertOwned();
588
+ const existing = readSidebarState(stateFile);
589
+ await emitMergeStep('read-state');
590
+ const merged = merge(existing);
591
+ await emitMergeStep('merged-state');
592
+ await writeJsonAtomic(stateFile, merged);
593
+ // `writeJsonAtomic` stages a tmp file with mode 0o600 and renames onto
594
+ // the target; POSIX rename replaces the inode so the new file inherits
595
+ // the staged mode bits. Windows ignores POSIX modes so the assertion
596
+ // in tests is best-effort there.
597
+ await emitMergeStep('wrote-state');
598
+ }
599
+ finally {
600
+ await lock.release().catch(() => { });
601
+ }
602
+ });
603
+ }
604
+ /**
605
+ * Merge a new machine-state payload against the on-disk state.
606
+ *
607
+ * Stale writes (new `checkedAt` < existing) are dropped — only newer/equal
608
+ * `checkedAt` may replace machine fields. The merge preserves
609
+ * `routingAuthoritative: true` once it is true (sticky-true), keeps the
610
+ * existing `activeRouting` intact (routing is merged via its own writer),
611
+ * and prunes any expired routing entries as a side effect.
612
+ */
613
+ function mergeMachineState(existing, next) {
614
+ if (next.checkedAt < existing.checkedAt) {
615
+ return {
616
+ ...existing,
617
+ activeRouting: pruneActiveRouting(existing.activeRouting, Date.now()),
618
+ };
619
+ }
620
+ return {
621
+ version: SIDEBAR_STATE_VERSION,
622
+ checkedAt: next.checkedAt,
623
+ accounts: next.accounts,
624
+ quotaBackoffUntil: next.quotaBackoffUntil,
625
+ lastError: next.lastError,
626
+ routingAuthoritative: existing.routingAuthoritative === true ||
627
+ next.routingAuthoritative === true,
628
+ // Symmetric with the stale-write branch: every machine-write merge
629
+ // re-prunes activeRouting so a long-running TUI session eventually
630
+ // drops dead routes even when no fresh routing upsert lands. Cheap
631
+ // (a single Object.entries + sort over ≤100 entries) and bounded.
632
+ activeRouting: pruneActiveRouting(existing.activeRouting, Date.now()),
633
+ };
634
+ }
635
+ /**
636
+ * Upsert a single session's active routing entry. The fetch interceptor calls
637
+ * this with `authoritative: true` after every final route selection; the
638
+ * `accountId`/`modelFamily`/`headerStyle` fields are already redacted by the
639
+ * caller (the writer never sees token or project fields).
640
+ */
641
+ export async function upsertSidebarActiveRouting(sessionId, entry, options = {}) {
642
+ const stateFile = options.stateFile ?? getSidebarStateFile();
643
+ await performSidebarWrite(stateFile, (existing) => {
644
+ const activeRouting = { ...existing.activeRouting, [sessionId]: entry };
645
+ return {
646
+ ...existing,
647
+ routingAuthoritative: options.authoritative === true ? true : existing.routingAuthoritative,
648
+ activeRouting: pruneActiveRouting(activeRouting, Date.now()),
649
+ };
650
+ });
651
+ }
652
+ /**
653
+ * Remove one session's active routing entry. The event handler calls this
654
+ * when a session is deleted so the sidebar does not retain dead routes.
655
+ */
656
+ export async function removeSidebarActiveRouting(sessionId, options = {}) {
657
+ const stateFile = options.stateFile ?? getSidebarStateFile();
658
+ await performSidebarWrite(stateFile, (existing) => {
659
+ if (!(sessionId in existing.activeRouting)) {
660
+ return existing;
661
+ }
662
+ const activeRouting = { ...existing.activeRouting };
663
+ delete activeRouting[sessionId];
664
+ return {
665
+ ...existing,
666
+ activeRouting,
667
+ };
668
+ });
669
+ }
670
+ /**
671
+ * Write a new machine-state snapshot. The fetch interceptor and quota
672
+ * manager call this after each refresh; auth-loader calls it after the
673
+ * account pool is materialized.
674
+ */
675
+ export async function setSidebarMachineState(next, options = {}) {
676
+ const stateFile = options.stateFile ?? getSidebarStateFile();
677
+ await performSidebarWrite(stateFile, (existing) => mergeMachineState(existing, next));
678
+ }
679
+ void SIDEBAR_STATE_FILE_MODE;
680
+ //# sourceMappingURL=sidebar-state.js.map