@cortexkit/opencode-openai-auth 1.23.0 → 1.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{index-897br01q.js → index-49ncs7dr.js} +1 -1
  3. package/dist/{index-s7dwe5n8.js → index-by5wfvqm.js} +20 -20
  4. package/dist/{index-bbrpg1ms.js → index-drm4dk5y.js} +1 -1
  5. package/dist/index-nd2ks7er.js +2 -0
  6. package/dist/index-t876xhkr.js +60 -0
  7. package/dist/{index-fasy4end.js → index-td4g5dc9.js} +1 -1
  8. package/dist/{index-7hcv94as.js → index-v8w8j1wx.js} +1 -1
  9. package/dist/{index-r31f36mn.js → index-v8wrmhyp.js} +1 -1
  10. package/dist/{index-bpx4spyr.js → index-wjp3q15r.js} +1 -1
  11. package/dist/{index-f340dq90.js → index-x00sxt2w.js} +10 -10
  12. package/dist/index.d.ts +4 -3
  13. package/dist/index.js +1 -1
  14. package/dist/{runtime-layout-B07ApQZL.d.ts → internal-DacVgEWs.d.ts} +86 -663
  15. package/dist/rpc/port-file.js +1 -1
  16. package/dist/rpc/protocol.js +1 -1
  17. package/dist/rpc/rpc-client.js +1 -1
  18. package/dist/runtime-layout-Dcbj_Rq3.d.ts +650 -0
  19. package/dist/{sidebar-state--OTpRzFd.d.ts → sidebar-state-L--CdbLi.d.ts} +4 -15
  20. package/dist/sidebar-state.d.ts +1 -1
  21. package/dist/sidebar-state.js +1 -1
  22. package/dist/tui-preferences.js +1 -1
  23. package/dist/tui.d.ts +5 -2
  24. package/dist/v2/server.d.ts +2 -1
  25. package/dist/v2/server.js +4 -4
  26. package/package.json +6 -6
  27. package/src/tui-compiled/raw/shared/054118b2705fdc20-ansi.js +98 -0
  28. package/src/tui-compiled/raw/shared/0895e780489c494d-window.js +33 -0
  29. package/src/tui-compiled/raw/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  30. package/src/tui-compiled/raw/shared/0c9533222cb4380c-namespace.js +224 -0
  31. package/src/tui-compiled/raw/shared/112607e46a5b5f58-accounts.js +393 -0
  32. package/src/tui-compiled/raw/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  33. package/src/tui-compiled/raw/shared/1547bd74f4214d2d-index.js +28 -0
  34. package/src/tui-compiled/raw/shared/1567207f323dc733-codex-http.js +44 -0
  35. package/src/tui-compiled/raw/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  36. package/src/tui-compiled/raw/shared/18df43cab4563acf-families.js +149 -0
  37. package/src/tui-compiled/raw/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  38. package/src/tui-compiled/raw/shared/1afd446e190ef85c-vault-messages.js +12 -0
  39. package/src/tui-compiled/raw/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  40. package/src/tui-compiled/raw/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  41. package/src/tui-compiled/raw/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  42. package/src/tui-compiled/raw/shared/22b2bce42f2d6806-handle.js +10 -0
  43. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  44. package/src/tui-compiled/raw/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  45. package/src/tui-compiled/raw/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  46. package/src/tui-compiled/raw/shared/2bb681e99c2721d7-registry.js +538 -0
  47. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +13 -20
  48. package/src/tui-compiled/raw/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  49. package/src/tui-compiled/raw/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  50. package/src/tui-compiled/raw/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  51. package/src/tui-compiled/raw/shared/3b31b36bf0877602-wording.js +120 -0
  52. package/src/tui-compiled/raw/shared/3c4c1a2d3fc92726-failure.js +59 -0
  53. package/src/tui-compiled/raw/shared/3dfe71eec6e0487d-presets.js +240 -0
  54. package/src/tui-compiled/raw/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  55. package/src/tui-compiled/raw/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  56. package/src/tui-compiled/raw/shared/4adf46e07e025363-axes.js +7 -0
  57. package/src/tui-compiled/raw/shared/4ba847b77580b1eb-confirm.js +21 -0
  58. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +48 -36
  59. package/src/tui-compiled/raw/shared/5018d4665e969588-limit-policy.js +159 -0
  60. package/src/tui-compiled/raw/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  61. package/src/tui-compiled/raw/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  62. package/src/tui-compiled/raw/shared/5d806e1a305d14f5-commands.js +879 -0
  63. package/src/tui-compiled/raw/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  64. package/src/tui-compiled/raw/shared/63c1ee7e70e85e8d-vault.js +1 -0
  65. package/src/tui-compiled/raw/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  66. package/src/tui-compiled/raw/shared/66937534c260d20b-stable-json.js +11 -0
  67. package/src/tui-compiled/raw/shared/7056acef1b021f19-bridge.js +10 -0
  68. package/src/tui-compiled/raw/shared/72d2ca42883809b4-marker.js +107 -0
  69. package/src/tui-compiled/raw/shared/775431e21f469203-record.js +3 -0
  70. package/src/tui-compiled/raw/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  71. package/src/tui-compiled/raw/shared/7b2a0471b29e4f5e-wake.js +47 -0
  72. package/src/tui-compiled/raw/shared/7b5d6afff4ff32b9-select.js +159 -0
  73. package/src/tui-compiled/raw/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  74. package/src/tui-compiled/raw/shared/7c98bde36aad4819-input-transformations.js +34 -0
  75. package/src/tui-compiled/raw/shared/7fb0418303f20a10-index.js +3 -0
  76. package/src/tui-compiled/raw/shared/806e12ccbad34388-pi-wait.js +51 -0
  77. package/src/tui-compiled/raw/shared/81ae201b724cac14-menu.js +73 -0
  78. package/src/tui-compiled/raw/shared/8349ed25dc629e97-scope.js +10 -0
  79. package/src/tui-compiled/raw/shared/86da3379973780b9-limit-provenance.js +60 -0
  80. package/src/tui-compiled/raw/shared/8aba66ed486d30a7-decide.js +425 -0
  81. package/src/tui-compiled/raw/shared/8c0c8df25a5dca1f-manager.js +735 -0
  82. package/src/tui-compiled/raw/shared/8c42bbec02f59636-vault-routing.js +212 -0
  83. package/src/tui-compiled/raw/shared/8ca6175bfae53e13-envelope.js +123 -0
  84. package/src/tui-compiled/raw/shared/8d0245e41049d83f-header-classifier.js +121 -0
  85. package/src/tui-compiled/raw/shared/9c162809179c7560-login.js +89 -0
  86. package/src/tui-compiled/raw/shared/a1f495296a4b756f-frame-turn.js +72 -0
  87. package/src/tui-compiled/raw/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  88. package/src/tui-compiled/raw/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  89. package/src/tui-compiled/raw/shared/adc5eeb5a8d28280-persistence.js +9 -0
  90. package/src/tui-compiled/raw/shared/b301c79e6378d1fb-vault.js +678 -0
  91. package/src/tui-compiled/raw/shared/b3c11de5f36e617a-reset.js +44 -0
  92. package/src/tui-compiled/raw/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  93. package/src/tui-compiled/raw/shared/bd4aef685681048c-duration.js +20 -0
  94. package/src/tui-compiled/raw/shared/bd5977eca210d2b8-index.js +662 -0
  95. package/src/tui-compiled/raw/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  96. package/src/tui-compiled/raw/shared/c66495424ad84aee-hold.js +25 -0
  97. package/src/tui-compiled/raw/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  98. package/src/tui-compiled/raw/shared/c9340fb545c4e5de-internal.js +73 -0
  99. package/src/tui-compiled/raw/shared/c954c6447b7b9b64-activity.js +52 -0
  100. package/src/tui-compiled/raw/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  101. package/src/tui-compiled/raw/shared/cec39ccddab4fe9c-labels.js +11 -0
  102. package/src/tui-compiled/raw/shared/cef0f2346957e83c-index.js +552 -0
  103. package/src/tui-compiled/raw/shared/cf7dedf24f902d68-dump-size.js +41 -0
  104. package/src/tui-compiled/raw/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  105. package/src/tui-compiled/raw/shared/d5b268767d330507-doctor.js +81 -0
  106. package/src/tui-compiled/raw/shared/d7ac5ca41f49121b-index.js +12 -0
  107. package/src/tui-compiled/raw/shared/d7fa77560855dee2-jitter.js +9 -0
  108. package/src/tui-compiled/raw/shared/de7f7d8803624369-path.js +31 -0
  109. package/src/tui-compiled/raw/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  110. package/src/tui-compiled/raw/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  111. package/src/tui-compiled/raw/shared/e2ae081583adfce3-dump.js +80 -0
  112. package/src/tui-compiled/raw/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  113. package/src/tui-compiled/raw/shared/e5229952fc12f647-codex-models.js +34 -0
  114. package/src/tui-compiled/raw/shared/e8fda84e90176436-uuid-v7.js +13 -0
  115. package/src/tui-compiled/raw/shared/ea56007991dbf068-terminal.js +19 -0
  116. package/src/tui-compiled/raw/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  117. package/src/tui-compiled/raw/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  118. package/src/tui-compiled/raw/shared/f1012265b3a768c7-merge-laws.js +31 -0
  119. package/src/tui-compiled/raw/shared/f2ca864fe967415a-cache-policy.js +198 -0
  120. package/src/tui-compiled/raw/shared/f317a4740f9d76f8-identity.js +21 -0
  121. package/src/tui-compiled/raw/shared/f607353c4126272a-routing-wait.js +19 -0
  122. package/src/tui-compiled/raw/shared/f6189f5c9aee31eb-decision.js +55 -0
  123. package/src/tui-compiled/raw/shared/f6d728f5e601f98b-request-history.js +120 -0
  124. package/src/tui-compiled/raw/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  125. package/src/tui-compiled/raw/shared/fda579e5a0a54165-codex-effort.js +60 -0
  126. package/src/tui-compiled/raw/sidebar-state.js +54 -4
  127. package/src/tui-compiled/raw/tui/v2-dialog.js +1 -1
  128. package/src/tui-compiled/raw/tui.tsx +27 -5
  129. package/src/tui-compiled/runtime/shared/054118b2705fdc20-ansi.js +98 -0
  130. package/src/tui-compiled/runtime/shared/0895e780489c494d-window.js +33 -0
  131. package/src/tui-compiled/runtime/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  132. package/src/tui-compiled/runtime/shared/0c9533222cb4380c-namespace.js +224 -0
  133. package/src/tui-compiled/runtime/shared/112607e46a5b5f58-accounts.js +393 -0
  134. package/src/tui-compiled/runtime/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  135. package/src/tui-compiled/runtime/shared/1547bd74f4214d2d-index.js +28 -0
  136. package/src/tui-compiled/runtime/shared/1567207f323dc733-codex-http.js +44 -0
  137. package/src/tui-compiled/runtime/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  138. package/src/tui-compiled/runtime/shared/18df43cab4563acf-families.js +149 -0
  139. package/src/tui-compiled/runtime/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  140. package/src/tui-compiled/runtime/shared/1afd446e190ef85c-vault-messages.js +12 -0
  141. package/src/tui-compiled/runtime/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  142. package/src/tui-compiled/runtime/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  143. package/src/tui-compiled/runtime/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  144. package/src/tui-compiled/runtime/shared/22b2bce42f2d6806-handle.js +10 -0
  145. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  146. package/src/tui-compiled/runtime/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  147. package/src/tui-compiled/runtime/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  148. package/src/tui-compiled/runtime/shared/2bb681e99c2721d7-registry.js +538 -0
  149. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +13 -20
  150. package/src/tui-compiled/runtime/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  151. package/src/tui-compiled/runtime/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  152. package/src/tui-compiled/runtime/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  153. package/src/tui-compiled/runtime/shared/3b31b36bf0877602-wording.js +120 -0
  154. package/src/tui-compiled/runtime/shared/3c4c1a2d3fc92726-failure.js +59 -0
  155. package/src/tui-compiled/runtime/shared/3dfe71eec6e0487d-presets.js +240 -0
  156. package/src/tui-compiled/runtime/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  157. package/src/tui-compiled/runtime/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  158. package/src/tui-compiled/runtime/shared/4adf46e07e025363-axes.js +7 -0
  159. package/src/tui-compiled/runtime/shared/4ba847b77580b1eb-confirm.js +21 -0
  160. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +48 -36
  161. package/src/tui-compiled/runtime/shared/5018d4665e969588-limit-policy.js +159 -0
  162. package/src/tui-compiled/runtime/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  163. package/src/tui-compiled/runtime/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  164. package/src/tui-compiled/runtime/shared/5d806e1a305d14f5-commands.js +879 -0
  165. package/src/tui-compiled/runtime/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  166. package/src/tui-compiled/runtime/shared/63c1ee7e70e85e8d-vault.js +1 -0
  167. package/src/tui-compiled/runtime/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  168. package/src/tui-compiled/runtime/shared/66937534c260d20b-stable-json.js +11 -0
  169. package/src/tui-compiled/runtime/shared/7056acef1b021f19-bridge.js +10 -0
  170. package/src/tui-compiled/runtime/shared/72d2ca42883809b4-marker.js +107 -0
  171. package/src/tui-compiled/runtime/shared/775431e21f469203-record.js +3 -0
  172. package/src/tui-compiled/runtime/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  173. package/src/tui-compiled/runtime/shared/7b2a0471b29e4f5e-wake.js +47 -0
  174. package/src/tui-compiled/runtime/shared/7b5d6afff4ff32b9-select.js +159 -0
  175. package/src/tui-compiled/runtime/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  176. package/src/tui-compiled/runtime/shared/7c98bde36aad4819-input-transformations.js +34 -0
  177. package/src/tui-compiled/runtime/shared/7fb0418303f20a10-index.js +3 -0
  178. package/src/tui-compiled/runtime/shared/806e12ccbad34388-pi-wait.js +51 -0
  179. package/src/tui-compiled/runtime/shared/81ae201b724cac14-menu.js +73 -0
  180. package/src/tui-compiled/runtime/shared/8349ed25dc629e97-scope.js +10 -0
  181. package/src/tui-compiled/runtime/shared/86da3379973780b9-limit-provenance.js +60 -0
  182. package/src/tui-compiled/runtime/shared/8aba66ed486d30a7-decide.js +425 -0
  183. package/src/tui-compiled/runtime/shared/8c0c8df25a5dca1f-manager.js +735 -0
  184. package/src/tui-compiled/runtime/shared/8c42bbec02f59636-vault-routing.js +212 -0
  185. package/src/tui-compiled/runtime/shared/8ca6175bfae53e13-envelope.js +123 -0
  186. package/src/tui-compiled/runtime/shared/8d0245e41049d83f-header-classifier.js +121 -0
  187. package/src/tui-compiled/runtime/shared/9c162809179c7560-login.js +89 -0
  188. package/src/tui-compiled/runtime/shared/a1f495296a4b756f-frame-turn.js +72 -0
  189. package/src/tui-compiled/runtime/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  190. package/src/tui-compiled/runtime/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  191. package/src/tui-compiled/runtime/shared/adc5eeb5a8d28280-persistence.js +9 -0
  192. package/src/tui-compiled/runtime/shared/b301c79e6378d1fb-vault.js +678 -0
  193. package/src/tui-compiled/runtime/shared/b3c11de5f36e617a-reset.js +44 -0
  194. package/src/tui-compiled/runtime/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  195. package/src/tui-compiled/runtime/shared/bd4aef685681048c-duration.js +20 -0
  196. package/src/tui-compiled/runtime/shared/bd5977eca210d2b8-index.js +662 -0
  197. package/src/tui-compiled/runtime/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  198. package/src/tui-compiled/runtime/shared/c66495424ad84aee-hold.js +25 -0
  199. package/src/tui-compiled/runtime/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  200. package/src/tui-compiled/runtime/shared/c9340fb545c4e5de-internal.js +73 -0
  201. package/src/tui-compiled/runtime/shared/c954c6447b7b9b64-activity.js +52 -0
  202. package/src/tui-compiled/runtime/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  203. package/src/tui-compiled/runtime/shared/cec39ccddab4fe9c-labels.js +11 -0
  204. package/src/tui-compiled/runtime/shared/cef0f2346957e83c-index.js +552 -0
  205. package/src/tui-compiled/runtime/shared/cf7dedf24f902d68-dump-size.js +41 -0
  206. package/src/tui-compiled/runtime/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  207. package/src/tui-compiled/runtime/shared/d5b268767d330507-doctor.js +81 -0
  208. package/src/tui-compiled/runtime/shared/d7ac5ca41f49121b-index.js +12 -0
  209. package/src/tui-compiled/runtime/shared/d7fa77560855dee2-jitter.js +9 -0
  210. package/src/tui-compiled/runtime/shared/de7f7d8803624369-path.js +31 -0
  211. package/src/tui-compiled/runtime/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  212. package/src/tui-compiled/runtime/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  213. package/src/tui-compiled/runtime/shared/e2ae081583adfce3-dump.js +80 -0
  214. package/src/tui-compiled/runtime/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  215. package/src/tui-compiled/runtime/shared/e5229952fc12f647-codex-models.js +34 -0
  216. package/src/tui-compiled/runtime/shared/e8fda84e90176436-uuid-v7.js +13 -0
  217. package/src/tui-compiled/runtime/shared/ea56007991dbf068-terminal.js +19 -0
  218. package/src/tui-compiled/runtime/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  219. package/src/tui-compiled/runtime/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  220. package/src/tui-compiled/runtime/shared/f1012265b3a768c7-merge-laws.js +31 -0
  221. package/src/tui-compiled/runtime/shared/f2ca864fe967415a-cache-policy.js +198 -0
  222. package/src/tui-compiled/runtime/shared/f317a4740f9d76f8-identity.js +21 -0
  223. package/src/tui-compiled/runtime/shared/f607353c4126272a-routing-wait.js +19 -0
  224. package/src/tui-compiled/runtime/shared/f6189f5c9aee31eb-decision.js +55 -0
  225. package/src/tui-compiled/runtime/shared/f6d728f5e601f98b-request-history.js +120 -0
  226. package/src/tui-compiled/runtime/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  227. package/src/tui-compiled/runtime/shared/fda579e5a0a54165-codex-effort.js +60 -0
  228. package/src/tui-compiled/runtime/sidebar-state.js +54 -4
  229. package/src/tui-compiled/runtime/tui/v2-dialog.js +1 -1
  230. package/src/tui-compiled/runtime/tui.js +11 -4
  231. package/dist/index-2z4dbnsf.js +0 -60
  232. package/dist/index-x25m9spd.js +0 -2
  233. package/dist/map-D5PHhv4z.d.ts +0 -72
  234. /package/dist/{index-sx9jjkry.js → index-4ktepxn1.js} +0 -0
@@ -0,0 +1,552 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { chmod, lstat, mkdir, open, readdir, rename, unlink, writeFile, } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { createPrivateBytes, ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
5
+ import { createRedactor } from "./d319517e3ea6ad70-redact.js";
6
+ const PREVIOUS_BODY_LIMIT = 100;
7
+ const UNKNOWN_SESSION = 'session-unknown';
8
+ const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
9
+ const DEFAULT_SWEEP_MIN_AGE_MS = 60 * 1000;
10
+ const DEFAULT_PARTIAL_STALE_MS = 10 * 60 * 1000;
11
+ /**
12
+ * The suffixes of the files one dump writes. A dump's files share the name
13
+ * before the suffix, which is how the sweep groups them.
14
+ */
15
+ const ARTIFACT_SUFFIX = /\.(body|meta|request|response)\.json$/;
16
+ /**
17
+ * A dump id: the ISO time with `:` and `.` replaced, the pid, a counter of
18
+ * at least six digits, then the sanitised session, channel and phase. Only
19
+ * names of this shape are swept, so a plugin may point dumps at a directory
20
+ * that also holds other files.
21
+ */
22
+ const ARTIFACT_ID = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/;
23
+ /** A response staging file: the final name, a random nonce, `.partial`. */
24
+ const PARTIAL_SUFFIX = /\.[a-f0-9]{24}\.partial$/;
25
+ function artifactGroup(name) {
26
+ const stem = name.replace(ARTIFACT_SUFFIX, '');
27
+ if (stem === name || !ARTIFACT_ID.test(stem))
28
+ return undefined;
29
+ return stem;
30
+ }
31
+ function isPartialName(name) {
32
+ const finalName = name.replace(PARTIAL_SUFFIX, '');
33
+ return finalName !== name && artifactGroup(finalName) !== undefined;
34
+ }
35
+ /**
36
+ * Hold the dump artifacts in `dir` to `maxBytes`. Only file names a dumper
37
+ * writes are counted or removed, so unrelated files in a directory the user
38
+ * chose survive. A dump's files are evicted together, oldest dump first by
39
+ * its newest file, because a body without its metadata (or the reverse) is no
40
+ * use to anyone. Dumps younger than `minAgeMs`, caller-listed `protectedPaths`
41
+ * (such as a just-written dump) and symlinks are kept, and a symlinked directory
42
+ * is refused outright. Response staging
43
+ * files left by a crash are reclaimed once stale, even under the cap.
44
+ * Cleanup is best-effort, but Windows refuses an unverified private directory.
45
+ */
46
+ export async function sweepDumpDirectory(options) {
47
+ const { dir, maxBytes } = options;
48
+ const now = options.now ?? Date.now();
49
+ const minAgeMs = options.minAgeMs ?? DEFAULT_SWEEP_MIN_AGE_MS;
50
+ const partialStaleMs = options.partialStaleMs ?? DEFAULT_PARTIAL_STALE_MS;
51
+ const empty = { removed: 0, freedBytes: 0 };
52
+ if (!(maxBytes > 0))
53
+ return empty;
54
+ try {
55
+ if (windowsPrivateFiles)
56
+ await verifyPrivate(dir, 'directory');
57
+ if ((await lstat(dir)).isSymbolicLink())
58
+ return empty;
59
+ const protectedPaths = new Set((options.protectedPaths ?? []).map((path) => resolve(path)));
60
+ const entries = await readdir(dir, { withFileTypes: true });
61
+ const files = [];
62
+ await Promise.all(entries.map(async (entry) => {
63
+ if (!entry.isFile())
64
+ return;
65
+ const partial = isPartialName(entry.name);
66
+ const group = partial ? undefined : artifactGroup(entry.name);
67
+ if (!partial && group === undefined)
68
+ return;
69
+ const path = join(dir, entry.name);
70
+ try {
71
+ const stats = await lstat(path);
72
+ if (!stats.isFile())
73
+ return;
74
+ files.push({ path, size: stats.size, mtimeMs: stats.mtimeMs, group });
75
+ }
76
+ catch {
77
+ // Another process removed it between the listing and the stat.
78
+ }
79
+ }));
80
+ let total = files.reduce((sum, file) => sum + file.size, 0);
81
+ let removed = 0;
82
+ let freedBytes = 0;
83
+ const remove = async (file) => {
84
+ try {
85
+ await unlink(file.path);
86
+ total -= file.size;
87
+ freedBytes += file.size;
88
+ removed += 1;
89
+ }
90
+ catch {
91
+ // Best-effort: what cannot be removed now is tried again next sweep.
92
+ }
93
+ };
94
+ // A staging file is never a usable dump, so a stale one goes whatever
95
+ // the total; a fresh one may still be renamed into place.
96
+ for (const file of files) {
97
+ if (file.group !== undefined)
98
+ continue;
99
+ if (protectedPaths.has(resolve(file.path)))
100
+ continue;
101
+ if (now - file.mtimeMs < partialStaleMs)
102
+ continue;
103
+ await remove(file);
104
+ }
105
+ const groups = new Map();
106
+ for (const file of files) {
107
+ if (file.group === undefined)
108
+ continue;
109
+ const group = groups.get(file.group) ?? { files: [], newest: 0 };
110
+ group.files.push(file);
111
+ group.newest = Math.max(group.newest, file.mtimeMs);
112
+ groups.set(file.group, group);
113
+ }
114
+ const oldestFirst = [...groups.entries()].sort(([leftName, left], [rightName, right]) => left.newest - right.newest || leftName.localeCompare(rightName));
115
+ for (const [, group] of oldestFirst) {
116
+ if (total <= maxBytes)
117
+ break;
118
+ if (now - group.newest < minAgeMs)
119
+ continue;
120
+ if (group.files.some((file) => protectedPaths.has(resolve(file.path))))
121
+ continue;
122
+ for (const file of group.files)
123
+ await remove(file);
124
+ }
125
+ if (removed > 0) {
126
+ options.logger?.debug('removed old dump files', { removed, freedBytes });
127
+ }
128
+ return { removed, freedBytes };
129
+ }
130
+ catch (error) {
131
+ if (error instanceof PrivateFileError &&
132
+ error.code === 'ERR_PRIVATE_FILES_SECURITY')
133
+ throw error;
134
+ return empty;
135
+ }
136
+ }
137
+ /**
138
+ * Replace `path` through a staging file created exclusively next to it, so a
139
+ * reader never sees half a file and a symlink planted at a predictable
140
+ * staging name is never followed.
141
+ */
142
+ async function replaceFile(path, text, stageName) {
143
+ if (windowsPrivateFiles) {
144
+ return writePrivateAtomic(path, text, {
145
+ stagePath: `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`,
146
+ });
147
+ }
148
+ for (let attempt = 0;; attempt += 1) {
149
+ const staging = `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`;
150
+ let created = false;
151
+ let handle;
152
+ try {
153
+ handle = await open(staging, 'wx', 0o600);
154
+ created = true;
155
+ await handle.writeFile(text, 'utf8');
156
+ await handle.chmod(0o600);
157
+ await handle.close();
158
+ handle = undefined;
159
+ await rename(staging, path);
160
+ return;
161
+ }
162
+ catch (error) {
163
+ await handle?.close().catch(() => { });
164
+ if (created)
165
+ await unlink(staging).catch(() => { });
166
+ const code = error.code;
167
+ if (code === 'EEXIST' && attempt === 0)
168
+ continue;
169
+ throw error;
170
+ }
171
+ }
172
+ }
173
+ function shortSession(session) {
174
+ return session.length <= 16 ? session : `${session.slice(0, 12)}…`;
175
+ }
176
+ function fileSegment(value, fallback) {
177
+ const normalized = value
178
+ .trim()
179
+ .replace(/[^a-zA-Z0-9._-]+/g, '-')
180
+ .replace(/^-+|-+$/g, '');
181
+ if (!normalized)
182
+ return fallback;
183
+ return normalized.slice(0, 80);
184
+ }
185
+ function hashText(value) {
186
+ return createHash('sha256').update(value).digest('hex');
187
+ }
188
+ function normalizeKey(key) {
189
+ return key.toLowerCase().replace(/[-_]/g, '');
190
+ }
191
+ function isRecord(value) {
192
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
193
+ }
194
+ /**
195
+ * Where two bodies first and last differ, in string offsets into the dumped
196
+ * (redacted) text. Offsets count UTF-16 units, as the plugins' cache analysis
197
+ * always has.
198
+ */
199
+ export function diffDumpBodies(previous, current) {
200
+ if (previous === undefined)
201
+ return null;
202
+ if (previous === current) {
203
+ return {
204
+ changed: false,
205
+ firstByte: -1,
206
+ lastPreviousByte: -1,
207
+ lastCurrentByte: -1,
208
+ previousBytes: previous.length,
209
+ currentBytes: current.length,
210
+ };
211
+ }
212
+ let firstByte = 0;
213
+ while (firstByte < previous.length &&
214
+ firstByte < current.length &&
215
+ previous[firstByte] === current[firstByte]) {
216
+ firstByte++;
217
+ }
218
+ let previousTail = previous.length - 1;
219
+ let currentTail = current.length - 1;
220
+ while (previousTail >= firstByte &&
221
+ currentTail >= firstByte &&
222
+ previous[previousTail] === current[currentTail]) {
223
+ previousTail--;
224
+ currentTail--;
225
+ }
226
+ return {
227
+ changed: true,
228
+ firstByte,
229
+ lastPreviousByte: previousTail,
230
+ lastCurrentByte: currentTail,
231
+ changedPreviousBytes: previousTail - firstByte + 1,
232
+ changedCurrentBytes: currentTail - firstByte + 1,
233
+ previousBytes: previous.length,
234
+ currentBytes: current.length,
235
+ };
236
+ }
237
+ // Shared by every dumper in the process. A plugin may create one dumper per
238
+ // project, and two of them writing the same session in the same millisecond
239
+ // would otherwise both number their dump 1 and pick the same file name; the
240
+ // exclusive create then drops the second dump.
241
+ let processDumpCounter = 0;
242
+ export function createDumper(options) {
243
+ let enabled = options.enabled === true;
244
+ const pid = options.pid ?? process.pid;
245
+ const now = options.now ?? Date.now;
246
+ const log = options.logger;
247
+ const extraKeys = new Set((options.secretKeys ?? []).map(normalizeKey));
248
+ const redactor = createRedactor({
249
+ extraSecretKeys: (normalized) => extraKeys.has(normalized),
250
+ extraValuePatterns: [...(options.secretPatterns ?? [])],
251
+ });
252
+ const schemaKeys = new Set(options.schemaKeys ?? ['tools']);
253
+ /**
254
+ * Last dumped (redacted) body per baseline key, in memory for this process.
255
+ * A key missing here, on its first dump or after eviction, is looked up on
256
+ * disk.
257
+ */
258
+ const previousBodies = new Map();
259
+ const resolveDir = () => typeof options.dir === 'function' ? options.dir() : options.dir;
260
+ /** The mask for a secret key name, or undefined for an ordinary key. */
261
+ function maskFor(key) {
262
+ // The shared redactor masks a secret key whatever its value, so probing it
263
+ // with null answers "is this key a secret" without duplicating its rules.
264
+ const masked = redactor.redact({ [key]: null })[key];
265
+ return masked === null ? undefined : masked;
266
+ }
267
+ /**
268
+ * Redact by key name and scrub token-shaped strings, except below a schema
269
+ * key, where only strings are scrubbed: a tool parameter named `api_key`
270
+ * declares what the tool accepts, and masking that node would leave a
271
+ * schema that no longer parses. Key order is kept because dumps are diffed
272
+ * against each other.
273
+ */
274
+ function scrub(value) {
275
+ if (Array.isArray(value))
276
+ return value.map(scrub);
277
+ if (isRecord(value)) {
278
+ const out = {};
279
+ for (const [key, entry] of Object.entries(value)) {
280
+ const mask = maskFor(key);
281
+ if (schemaKeys.has(key))
282
+ out[key] = redactor.redactStrings(entry);
283
+ else if (mask !== undefined)
284
+ out[key] = mask;
285
+ else
286
+ out[key] = scrub(entry);
287
+ }
288
+ return out;
289
+ }
290
+ return redactor.redactStrings(value);
291
+ }
292
+ function scrubBody(bodyText) {
293
+ let parsed;
294
+ try {
295
+ parsed = JSON.parse(bodyText);
296
+ }
297
+ catch {
298
+ // Not JSON: no keys to judge, but token-shaped strings still go.
299
+ return {
300
+ text: redactor.redactStrings(bodyText),
301
+ parsed: undefined,
302
+ };
303
+ }
304
+ const scrubbed = scrub(parsed);
305
+ const scrubbedText = JSON.stringify(scrubbed);
306
+ // Nothing redacted: keep the original bytes, whitespace included, so the
307
+ // dump is exactly what was sent.
308
+ const text = JSON.stringify(parsed) === scrubbedText ? bodyText : scrubbedText;
309
+ return { text, parsed: isRecord(scrubbed) ? scrubbed : undefined };
310
+ }
311
+ /**
312
+ * The newest earlier dump of this baseline key, read back from the dump
313
+ * directory. The in-memory baseline dies with the process, and the first
314
+ * request after a restart is the one most likely to break the prompt cache,
315
+ * so it is the one whose diff matters most. Reading the dumps themselves
316
+ * needs no extra state, and clearing the directory clears the baseline with
317
+ * it. Any failure is no baseline.
318
+ */
319
+ async function recoverBaseline(dir, session, channel, baselineKey) {
320
+ const marker = `-${fileSegment(session, UNKNOWN_SESSION)}-${fileSegment(channel, 'channel')}`;
321
+ let names;
322
+ try {
323
+ names = await readdir(dir);
324
+ }
325
+ catch {
326
+ return undefined;
327
+ }
328
+ // Names start with an ISO timestamp, so reverse lexicographic order is
329
+ // newest first. The metadata's key decides the match: a filename segment
330
+ // is truncated and sanitised, so two sessions can share one.
331
+ const candidates = names
332
+ .filter((name) => name.endsWith('.meta.json') && name.includes(marker))
333
+ .sort()
334
+ .reverse();
335
+ for (const name of candidates) {
336
+ try {
337
+ const metadata = JSON.parse(await readPrivateText(join(dir, name), windowsPrivateFiles));
338
+ if (metadata?.baselineKey !== baselineKey)
339
+ continue;
340
+ return await readPrivateText(join(dir, name.replace(/\.meta\.json$/, '.body.json')), windowsPrivateFiles);
341
+ }
342
+ catch (error) {
343
+ if (error instanceof PrivateFileError &&
344
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
345
+ throw error;
346
+ // A file removed or half-written by another process: try the next.
347
+ }
348
+ }
349
+ return undefined;
350
+ }
351
+ function remember(key, text) {
352
+ if (!previousBodies.has(key)) {
353
+ while (previousBodies.size >= PREVIOUS_BODY_LIMIT) {
354
+ const oldest = previousBodies.keys().next().value;
355
+ if (oldest === undefined)
356
+ break;
357
+ previousBodies.delete(oldest);
358
+ }
359
+ }
360
+ previousBodies.set(key, text);
361
+ }
362
+ async function dump(input) {
363
+ if (!enabled)
364
+ return undefined;
365
+ const counter = ++processDumpCounter;
366
+ const session = input.session?.trim() || UNKNOWN_SESSION;
367
+ const dir = resolveDir();
368
+ const createdAt = new Date(now()).toISOString();
369
+ // The pid makes names unique across processes: each process starts its
370
+ // counter at zero, so two processes dumping the same session in the same
371
+ // millisecond into a shared directory would otherwise pick the same name.
372
+ const id = [
373
+ createdAt.replace(/[:.]/g, '-'),
374
+ String(pid),
375
+ String(counter).padStart(6, '0'),
376
+ fileSegment(session, UNKNOWN_SESSION),
377
+ fileSegment(input.channel, 'channel'),
378
+ ...(input.phase ? [fileSegment(input.phase, 'phase')] : []),
379
+ ].join('-');
380
+ const prefix = join(dir, id);
381
+ const files = {
382
+ body: `${prefix}.body.json`,
383
+ metadata: `${prefix}.meta.json`,
384
+ request: `${prefix}.request.json`,
385
+ };
386
+ // Hashed so the metadata identifies the baseline without spelling out the
387
+ // full session id.
388
+ const baselineKey = hashText(`${input.channel}\u0000${session}`);
389
+ try {
390
+ if (windowsPrivateFiles)
391
+ await ensurePrivateDirectory(dir);
392
+ else {
393
+ await mkdir(dir, { recursive: true, mode: 0o700 });
394
+ // mkdir's mode does not apply to a directory that already exists.
395
+ await chmod(dir, 0o700);
396
+ }
397
+ let previous = previousBodies.get(baselineKey);
398
+ let baselineSource = previous === undefined ? undefined : 'memory';
399
+ if (previous === undefined) {
400
+ previous = await recoverBaseline(dir, session, input.channel, baselineKey);
401
+ if (previous !== undefined)
402
+ baselineSource = 'disk';
403
+ }
404
+ const body = scrubBody(input.bodyText);
405
+ const metadata = {
406
+ id,
407
+ createdAt,
408
+ pid,
409
+ session: shortSession(session),
410
+ channel: input.channel,
411
+ ...(input.phase ? { phase: input.phase } : {}),
412
+ accountId: input.accountId,
413
+ status: input.status,
414
+ error: input.error === undefined
415
+ ? undefined
416
+ : redactor.redactStrings(input.error),
417
+ baselineKey,
418
+ bodyBytes: Buffer.byteLength(input.bodyText, 'utf8'),
419
+ bodyHash: hashText(input.bodyText),
420
+ // Diffed on the redacted text that lands in the body file, so offsets
421
+ // index the file an operator can open, and a baseline read back from
422
+ // disk (also redacted) compares like with like.
423
+ diff: diffDumpBodies(previous, body.text),
424
+ baselineSource,
425
+ body: body.parsed
426
+ ? { parseable: true, ...options.summarize?.(body.parsed) }
427
+ : { parseable: false },
428
+ ...(input.meta ? { extra: scrub(input.meta) } : {}),
429
+ files,
430
+ };
431
+ const request = scrub({
432
+ url: input.url,
433
+ method: input.method,
434
+ accountId: input.accountId,
435
+ headers: input.headers === undefined
436
+ ? undefined
437
+ : Object.fromEntries(new Headers(input.headers).entries()),
438
+ });
439
+ // `wx`: a name collision fails loudly instead of overwriting a dump.
440
+ const write = (path, text) => windowsPrivateFiles
441
+ ? createPrivateBytes(path, text)
442
+ : writeFile(path, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
443
+ const writes = [
444
+ [files.body, body.text],
445
+ [files.metadata, `${JSON.stringify(metadata, null, 2)}\n`],
446
+ [files.request, `${JSON.stringify(request, null, 2)}\n`],
447
+ ];
448
+ // Settle every write before judging the group, so a cleanup never
449
+ // races a write that is still in flight.
450
+ const settled = await Promise.allSettled(writes.map(([path, text]) => write(path, text)));
451
+ const failed = settled.find((result) => result.status === 'rejected');
452
+ if (failed) {
453
+ if (options.cleanupFailedDumps)
454
+ await removeGroup(writes, settled);
455
+ throw failed.reason;
456
+ }
457
+ remember(baselineKey, body.text);
458
+ log?.debug('dumped request', {
459
+ id,
460
+ session: shortSession(session),
461
+ body: files.body,
462
+ });
463
+ scheduleSweep(dir, Object.values(files));
464
+ return { id, files, responseFile: `${prefix}.response.json` };
465
+ }
466
+ catch (error) {
467
+ if (error instanceof PrivateFileError &&
468
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
469
+ throw error;
470
+ log?.warn('request dump failed', {
471
+ session: shortSession(session),
472
+ error: error instanceof Error ? error.message : String(error),
473
+ });
474
+ return undefined;
475
+ }
476
+ }
477
+ /**
478
+ * Remove what a failed dump wrote. A write that failed with EEXIST found
479
+ * someone else's file at that name and must leave it; any other failure
480
+ * either created nothing or left a partial file of this dump.
481
+ */
482
+ async function removeGroup(writes, settled) {
483
+ await Promise.all(writes.map(async ([path], index) => {
484
+ const result = settled[index];
485
+ if (result?.status === 'rejected' &&
486
+ result.reason?.code === 'EEXIST') {
487
+ return;
488
+ }
489
+ await unlink(path).catch(() => { });
490
+ }));
491
+ }
492
+ const maxBytes = options.maxBytes ?? 0;
493
+ const sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
494
+ // Zero, so the first dump of a process sweeps whatever earlier processes
495
+ // left behind.
496
+ let lastSweepAt = 0;
497
+ function sweepOptions(dir, protectedPaths) {
498
+ return {
499
+ dir,
500
+ maxBytes,
501
+ protectedPaths,
502
+ now: now(),
503
+ minAgeMs: options.sweepMinAgeMs,
504
+ partialStaleMs: options.partialStaleMs,
505
+ logger: log,
506
+ };
507
+ }
508
+ /** Sweep in the background, off the request path, at most once per interval. */
509
+ function scheduleSweep(dir, protectedPaths) {
510
+ if (!(maxBytes > 0))
511
+ return;
512
+ const at = now();
513
+ if (at - lastSweepAt < sweepIntervalMs)
514
+ return;
515
+ lastSweepAt = at;
516
+ void sweepDumpDirectory(sweepOptions(dir, protectedPaths));
517
+ }
518
+ async function dumpResponse(result, input) {
519
+ if (!result)
520
+ return undefined;
521
+ const artifact = scrub({
522
+ status: input.status,
523
+ requestId: input.requestId,
524
+ usage: input.usage,
525
+ ...input.fields,
526
+ complete: input.complete ?? true,
527
+ });
528
+ try {
529
+ await replaceFile(result.responseFile, `${JSON.stringify(artifact, null, 2)}\n`, options.stageName);
530
+ return result.responseFile;
531
+ }
532
+ catch (error) {
533
+ if (error instanceof PrivateFileError &&
534
+ (windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
535
+ throw error;
536
+ log?.warn('response dump failed', {
537
+ id: result.id,
538
+ error: error instanceof Error ? error.message : String(error),
539
+ });
540
+ return undefined;
541
+ }
542
+ }
543
+ return {
544
+ isEnabled: () => enabled,
545
+ setEnabled: (value) => {
546
+ enabled = value;
547
+ },
548
+ dump,
549
+ dumpResponse,
550
+ sweep: (protectedPaths) => sweepDumpDirectory(sweepOptions(resolveDir(), protectedPaths)),
551
+ };
552
+ }
@@ -0,0 +1,41 @@
1
+ import { lstat, opendir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ export async function getDumpDirectorySize(dir) {
4
+ try {
5
+ if (!(await lstat(dir)).isDirectory())
6
+ return;
7
+ let bytes = 0, failed = !1, pending = [];
8
+ const measure = async (name) => {
9
+ try {
10
+ const file = await lstat(join(dir, name));
11
+ if (file.isFile())
12
+ bytes += file.size;
13
+ } catch (error) {
14
+ if (error.code !== "ENOENT")
15
+ failed = !0;
16
+ }
17
+ };
18
+ for await (const entry of await opendir(dir)) {
19
+ if (!entry.isFile())
20
+ continue;
21
+ pending.push(measure(entry.name));
22
+ if (pending.length === 32) {
23
+ await Promise.all(pending);
24
+ pending = [];
25
+ }
26
+ }
27
+ await Promise.all(pending);
28
+ return failed ? void 0 : bytes;
29
+ } catch (error) {
30
+ return error.code === "ENOENT" ? 0 : void 0;
31
+ }
32
+ }
33
+ export function formatDumpBytes(bytes) {
34
+ const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
35
+ let unit = 0, value = bytes;
36
+ while (value >= 1024 && unit < units.length - 1) {
37
+ value /= 1024;
38
+ unit++;
39
+ }
40
+ return `${Number(value.toFixed(1))} ${units[unit]}`;
41
+ }
@@ -0,0 +1,107 @@
1
+ import { acquireRefreshFileLock } from "./ec971142548df90e-index.js";
2
+ import {
3
+ refreshAllQuota
4
+ } from "./6545ab7f757314b7-refresh-all-quota.js";
5
+ export const BACKGROUND_QUOTA_REFRESH_INTERVAL_MS = 300000, BACKGROUND_QUOTA_REFRESH_JITTER_MS = 30000, BACKGROUND_QUOTA_FRESHNESS_MS = 240000, BACKGROUND_QUOTA_REFRESH_LOCK_NAME = "bg-quota-refresh", BACKGROUND_QUOTA_REFRESH_LOCK_TTL_MS = 120000;
6
+ export function acquireBackgroundRefreshLock(configPath, overrides) {
7
+ return acquireRefreshFileLock({
8
+ name: BACKGROUND_QUOTA_REFRESH_LOCK_NAME,
9
+ ttlMs: BACKGROUND_QUOTA_REFRESH_LOCK_TTL_MS,
10
+ path: configPath,
11
+ renew: !0,
12
+ ...overrides
13
+ });
14
+ }
15
+ export function refreshQuotaInBackground(deps, refreshFn = refreshAllQuota, acquireLock = () => acquireBackgroundRefreshLock(deps.paths.configPath)) {
16
+ return claimBackgroundRefresh(deps, refreshFn, acquireLock);
17
+ }
18
+ function claimBackgroundRefresh(deps, refreshFn, acquireLock) {
19
+ return runUnderBackgroundLease(async () => refreshFn({
20
+ ...deps,
21
+ respectBackoff: !0,
22
+ skipFresherThanMs: BACKGROUND_QUOTA_FRESHNESS_MS
23
+ }), acquireLock, []);
24
+ }
25
+ export async function runUnderBackgroundLease(run, acquireLock, skipped, { failOpen = !0 } = {}) {
26
+ let lock;
27
+ try {
28
+ lock = await acquireLock();
29
+ } catch (error) {
30
+ if (!failOpen)
31
+ throw error;
32
+ lock = void 0;
33
+ }
34
+ if (lock === null)
35
+ return skipped;
36
+ try {
37
+ return await run();
38
+ } finally {
39
+ await lock?.release().catch(() => {});
40
+ }
41
+ }
42
+ export function refreshPoolInBackground(source, storage, acquireLock, canPoll) {
43
+ return runUnderBackgroundLease(async () => {
44
+ if (canPoll && !await canPoll())
45
+ return [];
46
+ await source.refreshDueTokens(storage);
47
+ if (canPoll && !await canPoll())
48
+ return [];
49
+ return source.pollRows(storage, {
50
+ skipReadWithinMs: BACKGROUND_QUOTA_FRESHNESS_MS,
51
+ persistQuota: !0
52
+ });
53
+ }, acquireLock, [], { failOpen: !canPoll });
54
+ }
55
+
56
+ export class BackgroundQuotaRefresh {
57
+ setIntervalFn;
58
+ clearIntervalFn;
59
+ random;
60
+ onError;
61
+ run;
62
+ timer;
63
+ tickPromise;
64
+ stopped = !1;
65
+ constructor(options = {}) {
66
+ this.setIntervalFn = options.setIntervalFn ?? setInterval;
67
+ this.clearIntervalFn = options.clearIntervalFn ?? clearInterval;
68
+ this.random = options.random ?? Math.random;
69
+ this.onError = options.onError;
70
+ }
71
+ start(run, onError = this.onError) {
72
+ this.run = run;
73
+ this.onError = onError;
74
+ this.stopped = !1;
75
+ if (this.timer)
76
+ return;
77
+ const jitter = Math.round((this.random() * 2 - 1) * BACKGROUND_QUOTA_REFRESH_JITTER_MS);
78
+ this.timer = this.setIntervalFn(() => {
79
+ const currentRun = this.run;
80
+ if (this.stopped || !currentRun || this.tickPromise)
81
+ return;
82
+ const tickPromise = currentRun().catch((error) => {
83
+ try {
84
+ this.onError?.(error);
85
+ } catch {}
86
+ }).finally(() => {
87
+ if (this.tickPromise === tickPromise)
88
+ this.tickPromise = void 0;
89
+ });
90
+ this.tickPromise = tickPromise;
91
+ return tickPromise;
92
+ }, BACKGROUND_QUOTA_REFRESH_INTERVAL_MS + jitter);
93
+ if ("unref" in this.timer)
94
+ this.timer.unref();
95
+ }
96
+ stop() {
97
+ this.stopped = !0;
98
+ this.run = void 0;
99
+ if (!this.timer)
100
+ return;
101
+ this.clearIntervalFn(this.timer);
102
+ this.timer = void 0;
103
+ }
104
+ isStopped() {
105
+ return this.stopped;
106
+ }
107
+ }