@cortexkit/opencode-openai-auth 1.23.1 → 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 (226) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/{index-7hy72nfy.js → index-by5wfvqm.js} +2 -2
  3. package/dist/index-nd2ks7er.js +2 -0
  4. package/dist/index-t876xhkr.js +60 -0
  5. package/dist/{index-p81hxfe6.js → index-v8w8j1wx.js} +1 -1
  6. package/dist/{index-3ya2s179.js → index-v8wrmhyp.js} +1 -1
  7. package/dist/{index-bd18sfjj.js → index-x00sxt2w.js} +10 -10
  8. package/dist/index.d.ts +3 -2
  9. package/dist/index.js +1 -1
  10. package/dist/{runtime-layout-B07ApQZL.d.ts → internal-DacVgEWs.d.ts} +86 -663
  11. package/dist/rpc/port-file.js +1 -1
  12. package/dist/runtime-layout-Dcbj_Rq3.d.ts +650 -0
  13. package/dist/{sidebar-state--OTpRzFd.d.ts → sidebar-state-L--CdbLi.d.ts} +4 -15
  14. package/dist/sidebar-state.d.ts +1 -1
  15. package/dist/sidebar-state.js +1 -1
  16. package/dist/tui.d.ts +5 -2
  17. package/dist/v2/server.d.ts +2 -1
  18. package/dist/v2/server.js +4 -4
  19. package/package.json +1 -1
  20. package/src/tui-compiled/raw/shared/054118b2705fdc20-ansi.js +98 -0
  21. package/src/tui-compiled/raw/shared/0895e780489c494d-window.js +33 -0
  22. package/src/tui-compiled/raw/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  23. package/src/tui-compiled/raw/shared/0c9533222cb4380c-namespace.js +224 -0
  24. package/src/tui-compiled/raw/shared/112607e46a5b5f58-accounts.js +393 -0
  25. package/src/tui-compiled/raw/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  26. package/src/tui-compiled/raw/shared/1547bd74f4214d2d-index.js +28 -0
  27. package/src/tui-compiled/raw/shared/1567207f323dc733-codex-http.js +44 -0
  28. package/src/tui-compiled/raw/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  29. package/src/tui-compiled/raw/shared/18df43cab4563acf-families.js +149 -0
  30. package/src/tui-compiled/raw/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  31. package/src/tui-compiled/raw/shared/1afd446e190ef85c-vault-messages.js +12 -0
  32. package/src/tui-compiled/raw/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  33. package/src/tui-compiled/raw/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  34. package/src/tui-compiled/raw/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  35. package/src/tui-compiled/raw/shared/22b2bce42f2d6806-handle.js +10 -0
  36. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  37. package/src/tui-compiled/raw/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  38. package/src/tui-compiled/raw/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  39. package/src/tui-compiled/raw/shared/2bb681e99c2721d7-registry.js +538 -0
  40. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +13 -20
  41. package/src/tui-compiled/raw/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  42. package/src/tui-compiled/raw/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  43. package/src/tui-compiled/raw/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  44. package/src/tui-compiled/raw/shared/3b31b36bf0877602-wording.js +120 -0
  45. package/src/tui-compiled/raw/shared/3c4c1a2d3fc92726-failure.js +59 -0
  46. package/src/tui-compiled/raw/shared/3dfe71eec6e0487d-presets.js +240 -0
  47. package/src/tui-compiled/raw/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  48. package/src/tui-compiled/raw/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  49. package/src/tui-compiled/raw/shared/4adf46e07e025363-axes.js +7 -0
  50. package/src/tui-compiled/raw/shared/4ba847b77580b1eb-confirm.js +21 -0
  51. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +48 -36
  52. package/src/tui-compiled/raw/shared/5018d4665e969588-limit-policy.js +159 -0
  53. package/src/tui-compiled/raw/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  54. package/src/tui-compiled/raw/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  55. package/src/tui-compiled/raw/shared/5d806e1a305d14f5-commands.js +879 -0
  56. package/src/tui-compiled/raw/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  57. package/src/tui-compiled/raw/shared/63c1ee7e70e85e8d-vault.js +1 -0
  58. package/src/tui-compiled/raw/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  59. package/src/tui-compiled/raw/shared/66937534c260d20b-stable-json.js +11 -0
  60. package/src/tui-compiled/raw/shared/7056acef1b021f19-bridge.js +10 -0
  61. package/src/tui-compiled/raw/shared/72d2ca42883809b4-marker.js +107 -0
  62. package/src/tui-compiled/raw/shared/775431e21f469203-record.js +3 -0
  63. package/src/tui-compiled/raw/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  64. package/src/tui-compiled/raw/shared/7b2a0471b29e4f5e-wake.js +47 -0
  65. package/src/tui-compiled/raw/shared/7b5d6afff4ff32b9-select.js +159 -0
  66. package/src/tui-compiled/raw/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  67. package/src/tui-compiled/raw/shared/7c98bde36aad4819-input-transformations.js +34 -0
  68. package/src/tui-compiled/raw/shared/7fb0418303f20a10-index.js +3 -0
  69. package/src/tui-compiled/raw/shared/806e12ccbad34388-pi-wait.js +51 -0
  70. package/src/tui-compiled/raw/shared/81ae201b724cac14-menu.js +73 -0
  71. package/src/tui-compiled/raw/shared/8349ed25dc629e97-scope.js +10 -0
  72. package/src/tui-compiled/raw/shared/86da3379973780b9-limit-provenance.js +60 -0
  73. package/src/tui-compiled/raw/shared/8aba66ed486d30a7-decide.js +425 -0
  74. package/src/tui-compiled/raw/shared/8c0c8df25a5dca1f-manager.js +735 -0
  75. package/src/tui-compiled/raw/shared/8c42bbec02f59636-vault-routing.js +212 -0
  76. package/src/tui-compiled/raw/shared/8ca6175bfae53e13-envelope.js +123 -0
  77. package/src/tui-compiled/raw/shared/8d0245e41049d83f-header-classifier.js +121 -0
  78. package/src/tui-compiled/raw/shared/9c162809179c7560-login.js +89 -0
  79. package/src/tui-compiled/raw/shared/a1f495296a4b756f-frame-turn.js +72 -0
  80. package/src/tui-compiled/raw/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  81. package/src/tui-compiled/raw/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  82. package/src/tui-compiled/raw/shared/adc5eeb5a8d28280-persistence.js +9 -0
  83. package/src/tui-compiled/raw/shared/b301c79e6378d1fb-vault.js +678 -0
  84. package/src/tui-compiled/raw/shared/b3c11de5f36e617a-reset.js +44 -0
  85. package/src/tui-compiled/raw/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  86. package/src/tui-compiled/raw/shared/bd4aef685681048c-duration.js +20 -0
  87. package/src/tui-compiled/raw/shared/bd5977eca210d2b8-index.js +662 -0
  88. package/src/tui-compiled/raw/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  89. package/src/tui-compiled/raw/shared/c66495424ad84aee-hold.js +25 -0
  90. package/src/tui-compiled/raw/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  91. package/src/tui-compiled/raw/shared/c9340fb545c4e5de-internal.js +73 -0
  92. package/src/tui-compiled/raw/shared/c954c6447b7b9b64-activity.js +52 -0
  93. package/src/tui-compiled/raw/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  94. package/src/tui-compiled/raw/shared/cec39ccddab4fe9c-labels.js +11 -0
  95. package/src/tui-compiled/raw/shared/cef0f2346957e83c-index.js +552 -0
  96. package/src/tui-compiled/raw/shared/cf7dedf24f902d68-dump-size.js +41 -0
  97. package/src/tui-compiled/raw/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  98. package/src/tui-compiled/raw/shared/d5b268767d330507-doctor.js +81 -0
  99. package/src/tui-compiled/raw/shared/d7ac5ca41f49121b-index.js +12 -0
  100. package/src/tui-compiled/raw/shared/d7fa77560855dee2-jitter.js +9 -0
  101. package/src/tui-compiled/raw/shared/de7f7d8803624369-path.js +31 -0
  102. package/src/tui-compiled/raw/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  103. package/src/tui-compiled/raw/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  104. package/src/tui-compiled/raw/shared/e2ae081583adfce3-dump.js +80 -0
  105. package/src/tui-compiled/raw/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  106. package/src/tui-compiled/raw/shared/e5229952fc12f647-codex-models.js +34 -0
  107. package/src/tui-compiled/raw/shared/e8fda84e90176436-uuid-v7.js +13 -0
  108. package/src/tui-compiled/raw/shared/ea56007991dbf068-terminal.js +19 -0
  109. package/src/tui-compiled/raw/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  110. package/src/tui-compiled/raw/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  111. package/src/tui-compiled/raw/shared/f1012265b3a768c7-merge-laws.js +31 -0
  112. package/src/tui-compiled/raw/shared/f2ca864fe967415a-cache-policy.js +198 -0
  113. package/src/tui-compiled/raw/shared/f317a4740f9d76f8-identity.js +21 -0
  114. package/src/tui-compiled/raw/shared/f607353c4126272a-routing-wait.js +19 -0
  115. package/src/tui-compiled/raw/shared/f6189f5c9aee31eb-decision.js +55 -0
  116. package/src/tui-compiled/raw/shared/f6d728f5e601f98b-request-history.js +120 -0
  117. package/src/tui-compiled/raw/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  118. package/src/tui-compiled/raw/shared/fda579e5a0a54165-codex-effort.js +60 -0
  119. package/src/tui-compiled/raw/sidebar-state.js +54 -4
  120. package/src/tui-compiled/raw/tui/v2-dialog.js +1 -1
  121. package/src/tui-compiled/raw/tui.tsx +27 -5
  122. package/src/tui-compiled/runtime/shared/054118b2705fdc20-ansi.js +98 -0
  123. package/src/tui-compiled/runtime/shared/0895e780489c494d-window.js +33 -0
  124. package/src/tui-compiled/runtime/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
  125. package/src/tui-compiled/runtime/shared/0c9533222cb4380c-namespace.js +224 -0
  126. package/src/tui-compiled/runtime/shared/112607e46a5b5f58-accounts.js +393 -0
  127. package/src/tui-compiled/runtime/shared/136fa4abe48ad69d-cachekeep.js +411 -0
  128. package/src/tui-compiled/runtime/shared/1547bd74f4214d2d-index.js +28 -0
  129. package/src/tui-compiled/runtime/shared/1567207f323dc733-codex-http.js +44 -0
  130. package/src/tui-compiled/runtime/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
  131. package/src/tui-compiled/runtime/shared/18df43cab4563acf-families.js +149 -0
  132. package/src/tui-compiled/runtime/shared/1a4c289eec261e04-codex-instructions.js +59 -0
  133. package/src/tui-compiled/runtime/shared/1afd446e190ef85c-vault-messages.js +12 -0
  134. package/src/tui-compiled/runtime/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
  135. package/src/tui-compiled/runtime/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
  136. package/src/tui-compiled/runtime/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
  137. package/src/tui-compiled/runtime/shared/22b2bce42f2d6806-handle.js +10 -0
  138. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
  139. package/src/tui-compiled/runtime/shared/26055d4e5ad5e71f-codex-request.js +198 -0
  140. package/src/tui-compiled/runtime/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
  141. package/src/tui-compiled/runtime/shared/2bb681e99c2721d7-registry.js +538 -0
  142. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +13 -20
  143. package/src/tui-compiled/runtime/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
  144. package/src/tui-compiled/runtime/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
  145. package/src/tui-compiled/runtime/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
  146. package/src/tui-compiled/runtime/shared/3b31b36bf0877602-wording.js +120 -0
  147. package/src/tui-compiled/runtime/shared/3c4c1a2d3fc92726-failure.js +59 -0
  148. package/src/tui-compiled/runtime/shared/3dfe71eec6e0487d-presets.js +240 -0
  149. package/src/tui-compiled/runtime/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
  150. package/src/tui-compiled/runtime/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
  151. package/src/tui-compiled/runtime/shared/4adf46e07e025363-axes.js +7 -0
  152. package/src/tui-compiled/runtime/shared/4ba847b77580b1eb-confirm.js +21 -0
  153. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +48 -36
  154. package/src/tui-compiled/runtime/shared/5018d4665e969588-limit-policy.js +159 -0
  155. package/src/tui-compiled/runtime/shared/595bdf3fff13ba79-limit-identity.js +49 -0
  156. package/src/tui-compiled/runtime/shared/59def9e82b61204a-session-cache-activity.js +35 -0
  157. package/src/tui-compiled/runtime/shared/5d806e1a305d14f5-commands.js +879 -0
  158. package/src/tui-compiled/runtime/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
  159. package/src/tui-compiled/runtime/shared/63c1ee7e70e85e8d-vault.js +1 -0
  160. package/src/tui-compiled/runtime/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
  161. package/src/tui-compiled/runtime/shared/66937534c260d20b-stable-json.js +11 -0
  162. package/src/tui-compiled/runtime/shared/7056acef1b021f19-bridge.js +10 -0
  163. package/src/tui-compiled/runtime/shared/72d2ca42883809b4-marker.js +107 -0
  164. package/src/tui-compiled/runtime/shared/775431e21f469203-record.js +3 -0
  165. package/src/tui-compiled/runtime/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
  166. package/src/tui-compiled/runtime/shared/7b2a0471b29e4f5e-wake.js +47 -0
  167. package/src/tui-compiled/runtime/shared/7b5d6afff4ff32b9-select.js +159 -0
  168. package/src/tui-compiled/runtime/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
  169. package/src/tui-compiled/runtime/shared/7c98bde36aad4819-input-transformations.js +34 -0
  170. package/src/tui-compiled/runtime/shared/7fb0418303f20a10-index.js +3 -0
  171. package/src/tui-compiled/runtime/shared/806e12ccbad34388-pi-wait.js +51 -0
  172. package/src/tui-compiled/runtime/shared/81ae201b724cac14-menu.js +73 -0
  173. package/src/tui-compiled/runtime/shared/8349ed25dc629e97-scope.js +10 -0
  174. package/src/tui-compiled/runtime/shared/86da3379973780b9-limit-provenance.js +60 -0
  175. package/src/tui-compiled/runtime/shared/8aba66ed486d30a7-decide.js +425 -0
  176. package/src/tui-compiled/runtime/shared/8c0c8df25a5dca1f-manager.js +735 -0
  177. package/src/tui-compiled/runtime/shared/8c42bbec02f59636-vault-routing.js +212 -0
  178. package/src/tui-compiled/runtime/shared/8ca6175bfae53e13-envelope.js +123 -0
  179. package/src/tui-compiled/runtime/shared/8d0245e41049d83f-header-classifier.js +121 -0
  180. package/src/tui-compiled/runtime/shared/9c162809179c7560-login.js +89 -0
  181. package/src/tui-compiled/runtime/shared/a1f495296a4b756f-frame-turn.js +72 -0
  182. package/src/tui-compiled/runtime/shared/a37138dcbd893f55-hold-bounds.js +5 -0
  183. package/src/tui-compiled/runtime/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
  184. package/src/tui-compiled/runtime/shared/adc5eeb5a8d28280-persistence.js +9 -0
  185. package/src/tui-compiled/runtime/shared/b301c79e6378d1fb-vault.js +678 -0
  186. package/src/tui-compiled/runtime/shared/b3c11de5f36e617a-reset.js +44 -0
  187. package/src/tui-compiled/runtime/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
  188. package/src/tui-compiled/runtime/shared/bd4aef685681048c-duration.js +20 -0
  189. package/src/tui-compiled/runtime/shared/bd5977eca210d2b8-index.js +662 -0
  190. package/src/tui-compiled/runtime/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
  191. package/src/tui-compiled/runtime/shared/c66495424ad84aee-hold.js +25 -0
  192. package/src/tui-compiled/runtime/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
  193. package/src/tui-compiled/runtime/shared/c9340fb545c4e5de-internal.js +73 -0
  194. package/src/tui-compiled/runtime/shared/c954c6447b7b9b64-activity.js +52 -0
  195. package/src/tui-compiled/runtime/shared/cba8b0aee46b8526-codex-lite.js +85 -0
  196. package/src/tui-compiled/runtime/shared/cec39ccddab4fe9c-labels.js +11 -0
  197. package/src/tui-compiled/runtime/shared/cef0f2346957e83c-index.js +552 -0
  198. package/src/tui-compiled/runtime/shared/cf7dedf24f902d68-dump-size.js +41 -0
  199. package/src/tui-compiled/runtime/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
  200. package/src/tui-compiled/runtime/shared/d5b268767d330507-doctor.js +81 -0
  201. package/src/tui-compiled/runtime/shared/d7ac5ca41f49121b-index.js +12 -0
  202. package/src/tui-compiled/runtime/shared/d7fa77560855dee2-jitter.js +9 -0
  203. package/src/tui-compiled/runtime/shared/de7f7d8803624369-path.js +31 -0
  204. package/src/tui-compiled/runtime/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
  205. package/src/tui-compiled/runtime/shared/e26c2bb5722ab047-routing-hold.js +23 -0
  206. package/src/tui-compiled/runtime/shared/e2ae081583adfce3-dump.js +80 -0
  207. package/src/tui-compiled/runtime/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
  208. package/src/tui-compiled/runtime/shared/e5229952fc12f647-codex-models.js +34 -0
  209. package/src/tui-compiled/runtime/shared/e8fda84e90176436-uuid-v7.js +13 -0
  210. package/src/tui-compiled/runtime/shared/ea56007991dbf068-terminal.js +19 -0
  211. package/src/tui-compiled/runtime/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
  212. package/src/tui-compiled/runtime/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
  213. package/src/tui-compiled/runtime/shared/f1012265b3a768c7-merge-laws.js +31 -0
  214. package/src/tui-compiled/runtime/shared/f2ca864fe967415a-cache-policy.js +198 -0
  215. package/src/tui-compiled/runtime/shared/f317a4740f9d76f8-identity.js +21 -0
  216. package/src/tui-compiled/runtime/shared/f607353c4126272a-routing-wait.js +19 -0
  217. package/src/tui-compiled/runtime/shared/f6189f5c9aee31eb-decision.js +55 -0
  218. package/src/tui-compiled/runtime/shared/f6d728f5e601f98b-request-history.js +120 -0
  219. package/src/tui-compiled/runtime/shared/f981e6b15fb76cdb-codex-body.js +28 -0
  220. package/src/tui-compiled/runtime/shared/fda579e5a0a54165-codex-effort.js +60 -0
  221. package/src/tui-compiled/runtime/sidebar-state.js +54 -4
  222. package/src/tui-compiled/runtime/tui/v2-dialog.js +1 -1
  223. package/src/tui-compiled/runtime/tui.js +11 -4
  224. package/dist/index-0p8r7cpy.js +0 -60
  225. package/dist/index-px1t650b.js +0 -2
  226. package/dist/map-D5PHhv4z.d.ts +0 -72
@@ -0,0 +1,735 @@
1
+ import { combineAbortSignals } from "./6371b24a0573d79e-any-signal.js";
2
+ import { decideCacheKeep } from "./f6189f5c9aee31eb-decision.js";
3
+ import { classifyFailure } from "./3c4c1a2d3fc92726-failure.js";
4
+ import { isWithinCacheKeepWindow } from "./0895e780489c494d-window.js";
5
+ const DEFAULT_TTL_MS = 5 * 60_000;
6
+ const DEFAULT_MAX_IDLE_WARM_MS = 60 * 60_000;
7
+ const DEFAULT_MAX_SUBAGENT_IDLE_MS = 30 * 60_000;
8
+ const DEFAULT_TICK_INTERVAL_MS = 60_000;
9
+ const DEFAULT_MAX_TARGETS = 32;
10
+ const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
11
+ const DEFAULT_WARM_TIMEOUT_MS = 30_000;
12
+ const DEFAULT_BACKOFF_MS = 10 * 60_000;
13
+ const TRANSIENT_RETRY_STEP_MS = 20_000;
14
+ const TRANSIENT_RETRY_MAX_MS = 60_000;
15
+ const EXPIRY_SAFETY_MS = 5_000;
16
+ function positive(value, fallback) {
17
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
18
+ ? value
19
+ : fallback;
20
+ }
21
+ /**
22
+ * Keeps idle prompt caches warm: one target per session holding the latest
23
+ * request body, replayed just before the provider's cache would expire.
24
+ *
25
+ * Without a session plan, bounds act in this order: a target retires once its last confirmed
26
+ * cache lifetime ends (`cacheExpiresAt`, set by its capture or its last
27
+ * successful warm), whatever else holds, because replaying a history whose
28
+ * cache has expired rebuilds a cold cache instead of keeping a warm one
29
+ * alive; the clock window gates capture and warming (targets captured earlier
30
+ * survive outside it until their lifetime ends); idle caps prune a target its
31
+ * session stopped using (`sustain` lifts only the main-session idle cap, not
32
+ * the lifetime); the target-count and byte caps evict the least recently
33
+ * touched target; a per-target warm cap retires short-lived sessions; and a
34
+ * failed warm backs that target off without touching the others. Default
35
+ * transient retries use 20/40/60-second delays, clipped to the last safe start
36
+ * (expiry minus the warm timeout and 5 seconds). Only default-policy retries
37
+ * observe that deadline: first attempts and explicit backoff policies retain
38
+ * their existing lead-time scheduling, bounded by the cache lifetime.
39
+ * Session plans use the shared decision rule and one-shot due timers instead;
40
+ * only unpriced auto keeps the legacy idle and profile warm bounds. Lifetime,
41
+ * target-count, byte and LRU bounds apply to every target.
42
+ */
43
+ export class CacheKeepManager {
44
+ targets = new Map();
45
+ lastDropReasons = new Map();
46
+ adapter;
47
+ now;
48
+ log;
49
+ ttlMs;
50
+ leadMs;
51
+ planLeadMs;
52
+ maxIdleWarmMs;
53
+ maxSubagentIdleMs;
54
+ tickIntervalMs;
55
+ maxTargets;
56
+ maxBytes;
57
+ warmTimeoutMs;
58
+ backoff;
59
+ getWindow;
60
+ getSustain;
61
+ setIntervalImpl;
62
+ clearIntervalImpl;
63
+ timer = null;
64
+ startedAt = null;
65
+ totalBytes = 0;
66
+ tickPromise = null;
67
+ disposed = false;
68
+ planWarningLogged = false;
69
+ abortController = new AbortController();
70
+ constructor(options) {
71
+ this.adapter = options.adapter;
72
+ this.now = options.now;
73
+ this.log = options.logger;
74
+ this.ttlMs = positive(options.ttlMs, DEFAULT_TTL_MS);
75
+ this.tickIntervalMs = positive(options.tickIntervalMs, DEFAULT_TICK_INTERVAL_MS);
76
+ // One tick of slack so a target that becomes due between ticks is still
77
+ // warmed before its cache expires.
78
+ this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15_000);
79
+ this.planLeadMs = options.planLeadMs;
80
+ this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
81
+ this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
82
+ this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
83
+ this.maxBytes = positive(options.maxBytes, DEFAULT_MAX_BYTES);
84
+ this.warmTimeoutMs = positive(options.warmTimeoutMs, DEFAULT_WARM_TIMEOUT_MS);
85
+ this.backoff = options.backoffMs;
86
+ this.getWindow = options.getWindow;
87
+ this.getSustain = options.getSustain;
88
+ this.setIntervalImpl = options.setIntervalImpl ?? globalThis.setInterval;
89
+ this.clearIntervalImpl =
90
+ options.clearIntervalImpl ?? globalThis.clearInterval;
91
+ }
92
+ /**
93
+ * Capture a session's latest request. The freshest body replaces the
94
+ * previous one and restarts its cache clock, idle clock and warm count.
95
+ * Arms the timer.
96
+ */
97
+ track(input) {
98
+ const { sessionKey, bodyText } = input;
99
+ const previous = this.targets.get(sessionKey);
100
+ const plan = this.readPlan(sessionKey);
101
+ if (!plan && previous?.plan) {
102
+ this.drop(sessionKey, 'session-ended');
103
+ return { tracked: false, reason: 'session-ended' };
104
+ }
105
+ if (plan?.mode === 'off') {
106
+ this.drop(sessionKey, 'unsupported');
107
+ return { tracked: false, reason: 'unsupported' };
108
+ }
109
+ this.pruneStale(plan ? sessionKey : undefined);
110
+ const bodyBytes = Buffer.byteLength(bodyText, 'utf8');
111
+ if (bodyBytes > this.maxBytes) {
112
+ this.log?.debug('cachekeep track skipped (body exceeds maxBytes)', {
113
+ sessionKey,
114
+ bodyBytes,
115
+ maxBytes: this.maxBytes,
116
+ });
117
+ return { tracked: false, reason: 'body-exceeds-max-bytes' };
118
+ }
119
+ const window = this.getWindow?.();
120
+ if (!plan &&
121
+ window &&
122
+ !isWithinCacheKeepWindow(window, new Date(this.now()))) {
123
+ this.log?.debug('cachekeep track skipped (outside window)', {
124
+ sessionKey,
125
+ startHour: window.startHour,
126
+ endHour: window.endHour,
127
+ });
128
+ return { tracked: false, reason: 'outside-window' };
129
+ }
130
+ // Delete before re-adding so a retracked session is also the most recent
131
+ // in insertion order.
132
+ const hasWarmed = this.targets.get(sessionKey)?.hasWarmed ?? false;
133
+ this.drop(sessionKey, null);
134
+ while (this.targets.size >= this.maxTargets ||
135
+ (this.totalBytes + bodyBytes > this.maxBytes && this.targets.size > 0)) {
136
+ const evictKey = this.leastRecentlyTouched();
137
+ if (evictKey === undefined)
138
+ break;
139
+ this.log?.debug('cachekeep evicted least recently used target', {
140
+ sessionKey: evictKey,
141
+ });
142
+ this.drop(evictKey, 'evicted');
143
+ }
144
+ const isSubagent = input.isSubagent === true;
145
+ const accountId = input.accountId || undefined;
146
+ const profile = this.adapter.profile?.({
147
+ bodyText,
148
+ isSubagent,
149
+ accountId,
150
+ meta: input.meta,
151
+ });
152
+ const ttlMs = positive(profile?.ttlMs, this.ttlMs);
153
+ const now = this.now();
154
+ const target = {
155
+ plan,
156
+ warmCostSoFar: 0,
157
+ hasWarmed,
158
+ bodyText,
159
+ bodyBytes,
160
+ accountId,
161
+ isSubagent,
162
+ meta: input.meta,
163
+ ttlMs,
164
+ maxWarms: profile?.maxWarms !== undefined && profile.maxWarms > 0
165
+ ? Math.floor(profile.maxWarms)
166
+ : undefined,
167
+ maxIdleMs: profile?.maxIdleMs !== undefined
168
+ ? positive(profile.maxIdleMs, this.idleDefault(isSubagent))
169
+ : undefined,
170
+ cacheExpiresAt: now + ttlMs,
171
+ lastRealRequestAt: now,
172
+ failures: 0,
173
+ warmCount: 0,
174
+ };
175
+ this.targets.set(sessionKey, target);
176
+ this.lastDropReasons.delete(sessionKey);
177
+ this.totalBytes += bodyBytes;
178
+ this.log?.debug('cachekeep captured target', { sessionKey, accountId });
179
+ this.start();
180
+ if (plan)
181
+ this.planDecision(sessionKey, target);
182
+ return { tracked: true };
183
+ }
184
+ /** Forget a session, e.g. when the host deletes it. */
185
+ remove(sessionKey) {
186
+ if (this.drop(sessionKey)) {
187
+ this.log?.debug('cachekeep removed target', { sessionKey });
188
+ }
189
+ }
190
+ start() {
191
+ this.disposed = false;
192
+ if (this.timer)
193
+ return;
194
+ this.startedAt = this.now();
195
+ this.timer = this.setIntervalImpl(() => {
196
+ void this.tick().catch((error) => {
197
+ this.log?.warn('cachekeep tick failed', classifyFailure(error, 'send'));
198
+ });
199
+ }, this.tickIntervalMs);
200
+ if (typeof this.timer === 'object' && 'unref' in this.timer) {
201
+ this.timer.unref();
202
+ }
203
+ this.log?.debug('cachekeep started', {
204
+ ttlMs: this.ttlMs,
205
+ leadMs: this.leadMs,
206
+ maxIdleWarmMs: this.maxIdleWarmMs,
207
+ });
208
+ }
209
+ /** Disarm, abort any warm in flight and forget every target. */
210
+ stop() {
211
+ this.disposed = true;
212
+ this.abortController.abort();
213
+ this.abortController = new AbortController();
214
+ if (this.timer) {
215
+ this.clearIntervalImpl(this.timer);
216
+ this.timer = null;
217
+ }
218
+ this.startedAt = null;
219
+ for (const sessionKey of this.targets.keys())
220
+ this.drop(sessionKey, 'stopped');
221
+ this.totalBytes = 0;
222
+ this.log?.debug('cachekeep stopped');
223
+ }
224
+ /**
225
+ * Read whether a session is armed, without I/O or callbacks. Stop reasons
226
+ * include manager-internal values: plugins must filter them through
227
+ * isCacheWarmStopReason for billing, leaving unknown reasons out, not guessing.
228
+ */
229
+ warming(sessionKey) {
230
+ try {
231
+ if (this.targets.has(sessionKey))
232
+ return { on: true };
233
+ const stopReason = this.lastDropReasons.get(sessionKey);
234
+ return { on: false, ...(stopReason !== undefined ? { stopReason } : {}) };
235
+ }
236
+ catch {
237
+ return { on: false };
238
+ }
239
+ }
240
+ /** A snapshot without captured bodies, which can hold prompt content. */
241
+ status() {
242
+ const window = this.getWindow?.();
243
+ return {
244
+ running: this.timer !== null,
245
+ tracked: this.targets.size,
246
+ totalBytes: this.totalBytes,
247
+ generatedAt: this.now(),
248
+ startedAt: this.startedAt,
249
+ ttlMs: this.ttlMs,
250
+ leadMs: this.leadMs,
251
+ maxIdleWarmMs: this.maxIdleWarmMs,
252
+ maxSubagentIdleMs: this.maxSubagentIdleMs,
253
+ sustain: this.getSustain?.() === true,
254
+ ...(window ? { window } : {}),
255
+ targets: [...this.targets].map(([sessionKey, target]) => ({
256
+ sessionKey,
257
+ ...(target.plan ? { mode: target.plan.mode } : {}),
258
+ accountId: target.accountId,
259
+ isSubagent: target.isSubagent,
260
+ cacheExpiresAt: target.cacheExpiresAt,
261
+ lastRealRequestAt: target.lastRealRequestAt,
262
+ ...(target.lastWarmedAt !== undefined
263
+ ? { lastWarmedAt: target.lastWarmedAt }
264
+ : {}),
265
+ ...(target.backoffUntil !== undefined
266
+ ? { backoffUntil: target.backoffUntil }
267
+ : {}),
268
+ failures: target.failures,
269
+ warmCount: target.warmCount,
270
+ ttlMs: target.ttlMs,
271
+ bodyBytes: target.bodyBytes,
272
+ })),
273
+ };
274
+ }
275
+ /**
276
+ * Prune, then warm every target within `leadMs` of expiry that is not
277
+ * backing off. Overlapping calls share the tick already running, so a slow
278
+ * warm never stacks a second send for the same target.
279
+ */
280
+ tick() {
281
+ if (this.tickPromise)
282
+ return this.tickPromise;
283
+ const run = this.runTick().finally(() => {
284
+ if (this.tickPromise === run)
285
+ this.tickPromise = null;
286
+ });
287
+ this.tickPromise = run;
288
+ return run;
289
+ }
290
+ async runTick() {
291
+ this.pruneStale();
292
+ // Outside the window nothing fires, but captured targets stay until
293
+ // their cache lifetime ends, so one still alive when the window reopens
294
+ // is warmed again.
295
+ const window = this.getWindow?.();
296
+ const outsideWindow = window && !isWithinCacheKeepWindow(window, new Date(this.now()));
297
+ for (const [sessionKey, target] of [...this.targets]) {
298
+ if (this.disposed)
299
+ return;
300
+ if (this.targets.get(sessionKey) !== target)
301
+ continue;
302
+ if (!this.refreshPlan(sessionKey, target))
303
+ continue;
304
+ const now = this.now();
305
+ if (target.plan) {
306
+ const decision = this.planDecision(sessionKey, target);
307
+ if (decision.action !== 'warm')
308
+ continue;
309
+ if (target.backoffUntil !== undefined && now < target.backoffUntil) {
310
+ this.schedulePlan(sessionKey, target, target.backoffUntil);
311
+ continue;
312
+ }
313
+ }
314
+ else {
315
+ if (outsideWindow)
316
+ continue;
317
+ if (target.cacheExpiresAt > now + this.leadMs)
318
+ continue;
319
+ }
320
+ if (target.backoffUntil !== undefined && now < target.backoffUntil) {
321
+ continue;
322
+ }
323
+ if (!this.canRetry(target))
324
+ continue;
325
+ await this.warm(sessionKey, target);
326
+ }
327
+ }
328
+ /**
329
+ * Retires `target` when its last confirmed cache lifetime has ended; true
330
+ * when it did. Called before every send, since earlier warms in the same
331
+ * tick, the adapter's account lookup and body build all take time.
332
+ */
333
+ retireIfExpired(sessionKey, target) {
334
+ if (this.now() < target.cacheExpiresAt)
335
+ return false;
336
+ this.log?.debug('cachekeep retired target (cache lifetime ended)', {
337
+ sessionKey,
338
+ accountId: target.accountId,
339
+ cacheExpiresAt: target.cacheExpiresAt,
340
+ failures: target.failures,
341
+ });
342
+ this.drop(sessionKey, target.plan ? 'deadline-missed' : 'expired');
343
+ return true;
344
+ }
345
+ isCurrent(sessionKey, target) {
346
+ return !this.disposed && this.targets.get(sessionKey) === target;
347
+ }
348
+ view(sessionKey, target) {
349
+ return {
350
+ sessionKey,
351
+ accountId: target.accountId,
352
+ bodyText: target.bodyText,
353
+ isSubagent: target.isSubagent,
354
+ meta: target.meta,
355
+ warmCount: target.warmCount,
356
+ ttlMs: target.ttlMs,
357
+ };
358
+ }
359
+ readPlan(sessionKey) {
360
+ try {
361
+ return this.adapter.plan?.(sessionKey);
362
+ }
363
+ catch {
364
+ if (!this.planWarningLogged) {
365
+ this.planWarningLogged = true;
366
+ this.log?.warn('cachekeep plan unavailable');
367
+ }
368
+ return undefined;
369
+ }
370
+ }
371
+ refreshPlan(sessionKey, target) {
372
+ const plan = this.readPlan(sessionKey);
373
+ if (!plan && target.plan) {
374
+ this.drop(sessionKey, 'session-ended');
375
+ return false;
376
+ }
377
+ target.plan = plan;
378
+ if (plan?.mode === 'off') {
379
+ this.drop(sessionKey, 'unsupported');
380
+ return false;
381
+ }
382
+ return true;
383
+ }
384
+ usesLegacyBounds(target) {
385
+ return !target.plan || (target.plan.mode === 'auto' && !target.plan.costs);
386
+ }
387
+ planDecision(sessionKey, target) {
388
+ const plan = target.plan;
389
+ if (!plan)
390
+ return { action: 'stop', reason: 'session-ended' };
391
+ if (this.usesLegacyBounds(target)) {
392
+ if (this.retireIfIdle(sessionKey, target, this.getSustain?.() === true)) {
393
+ return { action: 'stop', reason: 'idle' };
394
+ }
395
+ if (target.maxWarms !== undefined &&
396
+ target.warmCount >= target.maxWarms) {
397
+ this.drop(sessionKey, 'count-cap');
398
+ return { action: 'stop', reason: 'count-cap' };
399
+ }
400
+ }
401
+ const decision = plan.mode === 'hours' && !plan.hours
402
+ ? { action: 'stop', reason: 'unsupported' }
403
+ : decideCacheKeep({
404
+ ...(plan.mode === 'hours'
405
+ ? { mode: plan.mode, hours: plan.hours }
406
+ : { mode: plan.mode }),
407
+ now: this.now(),
408
+ ttlMs: target.ttlMs,
409
+ ...(this.planLeadMs !== undefined
410
+ ? { leadMs: this.planLeadMs }
411
+ : {}),
412
+ lastRealRequestAt: target.lastRealRequestAt,
413
+ lastWarmAt: target.lastWarmedAt,
414
+ warmsSinceLastRealRequest: target.warmCount,
415
+ ...(plan.costs
416
+ ? {
417
+ warmCostSoFar: target.warmCostSoFar,
418
+ nextWarmCost: plan.costs.nextWarm,
419
+ rewriteCost: plan.costs.rewrite,
420
+ }
421
+ : {}),
422
+ });
423
+ if (decision.action === 'stop')
424
+ this.drop(sessionKey, decision.reason);
425
+ else if (decision.action === 'wait') {
426
+ this.schedulePlan(sessionKey, target, Math.max(decision.until, target.backoffUntil ?? 0));
427
+ }
428
+ else
429
+ this.clearPlanTimer(target);
430
+ return decision;
431
+ }
432
+ clearPlanTimer(target) {
433
+ if (target.planTimer === undefined)
434
+ return;
435
+ this.clearIntervalImpl(target.planTimer);
436
+ target.planTimer = undefined;
437
+ target.planDueAt = undefined;
438
+ }
439
+ schedulePlan(sessionKey, target, until) {
440
+ if (target.planTimer !== undefined && target.planDueAt === until)
441
+ return;
442
+ this.clearPlanTimer(target);
443
+ target.planDueAt = until;
444
+ // Clear the injected interval before dispatch to make it a one-shot, just
445
+ // like retries. Waiting for an in-flight tick prevents a lost wake-up.
446
+ target.planTimer = this.setIntervalImpl(() => {
447
+ this.clearPlanTimer(target);
448
+ return (async () => {
449
+ await this.tickPromise;
450
+ if (this.isCurrent(sessionKey, target))
451
+ await this.tick();
452
+ })().catch((error) => {
453
+ this.log?.warn('cachekeep tick failed', classifyFailure(error, 'send'));
454
+ });
455
+ }, Math.max(0, until - this.now()));
456
+ if (typeof target.planTimer === 'object' && 'unref' in target.planTimer) {
457
+ target.planTimer.unref();
458
+ }
459
+ }
460
+ report(callback) {
461
+ try {
462
+ void Promise.resolve(callback()).catch(() => {
463
+ this.log?.debug('cachekeep report failed');
464
+ });
465
+ }
466
+ catch {
467
+ this.log?.debug('cachekeep report failed');
468
+ }
469
+ }
470
+ fail(sessionKey, target, message, failure, transient = false, status) {
471
+ if (!this.isCurrent(sessionKey, target))
472
+ return;
473
+ target.failures += 1;
474
+ const now = this.now();
475
+ let delay = typeof this.backoff === 'function'
476
+ ? this.backoff({ sessionKey, failures: target.failures })
477
+ : (this.backoff ?? DEFAULT_BACKOFF_MS);
478
+ const deadline = this.lastRetryStart(target);
479
+ const fastRetry = this.backoff === undefined && transient && now < deadline;
480
+ if (fastRetry) {
481
+ delay = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
482
+ }
483
+ target.backoffUntil =
484
+ now + (Number.isFinite(delay) && delay > 0 ? delay : 0);
485
+ this.clearRetry(target);
486
+ if (fastRetry)
487
+ this.scheduleRetry(sessionKey, target, delay);
488
+ else if (target.plan) {
489
+ this.schedulePlan(sessionKey, target, target.backoffUntil);
490
+ }
491
+ this.log?.warn(message, {
492
+ sessionKey,
493
+ accountId: target.accountId,
494
+ failures: target.failures,
495
+ backoffUntil: target.backoffUntil,
496
+ ...failure,
497
+ ...(status !== undefined && { status }),
498
+ });
499
+ }
500
+ lastRetryStart(target) {
501
+ return target.cacheExpiresAt - this.warmTimeoutMs - EXPIRY_SAFETY_MS;
502
+ }
503
+ canRetry(target) {
504
+ return (this.backoff !== undefined ||
505
+ target.failures === 0 ||
506
+ this.now() <= this.lastRetryStart(target));
507
+ }
508
+ clearRetry(target) {
509
+ if (target.retryTimer === undefined)
510
+ return;
511
+ this.clearIntervalImpl(target.retryTimer);
512
+ target.retryTimer = undefined;
513
+ }
514
+ scheduleRetry(sessionKey, target, delay) {
515
+ // Use the same injected timer pair as the regular tick, but clear this
516
+ // interval before dispatch so it acts as a one-shot retry timer.
517
+ target.retryTimer = this.setIntervalImpl(() => {
518
+ this.clearRetry(target);
519
+ return (async () => {
520
+ // A different target can still be warming. Wait for that tick before
521
+ // rechecking eligibility, rather than losing this wake-up to coalescing.
522
+ await this.tickPromise;
523
+ if (this.isCurrent(sessionKey, target))
524
+ await this.tick();
525
+ })().catch((error) => {
526
+ this.log?.warn('cachekeep tick failed', classifyFailure(error, 'send'));
527
+ });
528
+ }, delay);
529
+ if (typeof target.retryTimer === 'object' && 'unref' in target.retryTimer) {
530
+ target.retryTimer.unref();
531
+ }
532
+ }
533
+ async warm(sessionKey, target) {
534
+ if (this.retireIfExpired(sessionKey, target))
535
+ return;
536
+ if (!this.canRetry(target))
537
+ return;
538
+ this.clearRetry(target);
539
+ const view = this.view(sessionKey, target);
540
+ if (this.adapter.activeAccount) {
541
+ let active;
542
+ try {
543
+ active = await this.adapter.activeAccount(sessionKey, view);
544
+ }
545
+ catch (error) {
546
+ this.fail(sessionKey, target, 'cachekeep skip (active account unknown)', classifyFailure(error, 'authorization'), true);
547
+ return;
548
+ }
549
+ if (!this.isCurrent(sessionKey, target))
550
+ return;
551
+ if (active !== undefined && active !== target.accountId) {
552
+ this.log?.debug('cachekeep dropped target (session changed account)', {
553
+ sessionKey,
554
+ accountId: target.accountId,
555
+ activeAccountId: active,
556
+ });
557
+ this.drop(sessionKey, 'account-changed');
558
+ return;
559
+ }
560
+ }
561
+ let body;
562
+ try {
563
+ body = await this.adapter.buildBody(view);
564
+ }
565
+ catch (error) {
566
+ this.fail(sessionKey, target, 'cachekeep skip (replay body unbuildable)', classifyFailure(error, 'authorization'));
567
+ return;
568
+ }
569
+ if (!this.isCurrent(sessionKey, target))
570
+ return;
571
+ if (this.retireIfExpired(sessionKey, target))
572
+ return;
573
+ if (!this.canRetry(target))
574
+ return;
575
+ if (!this.refreshPlan(sessionKey, target))
576
+ return;
577
+ if (target.plan &&
578
+ this.planDecision(sessionKey, target).action !== 'warm') {
579
+ return;
580
+ }
581
+ const nextWarmCost = target.plan?.costs?.nextWarm ?? 0;
582
+ const combined = combineAbortSignals([
583
+ AbortSignal.timeout(this.warmTimeoutMs),
584
+ this.abortController.signal,
585
+ ]);
586
+ const signal = combined.signal;
587
+ let response;
588
+ let text = '';
589
+ let stage = 'send';
590
+ let status;
591
+ try {
592
+ response = await this.adapter.send({ target: view, body, signal });
593
+ stage = 'response';
594
+ status = response.status;
595
+ // Drain the body to release the connection and let the adapter read usage.
596
+ text = await response.text();
597
+ }
598
+ catch (error) {
599
+ this.fail(sessionKey, target, 'cachekeep failed', classifyFailure(error, stage, status), status === undefined ||
600
+ (status >= 200 && status < 300) ||
601
+ status === 408 ||
602
+ status === 429 ||
603
+ status >= 500, status);
604
+ return;
605
+ }
606
+ finally {
607
+ combined.dispose();
608
+ }
609
+ if (!this.isCurrent(sessionKey, target))
610
+ return;
611
+ if (!response.ok) {
612
+ this.fail(sessionKey, target, 'cachekeep failed', classifyFailure(undefined, 'response', response.status), response.status === 408 ||
613
+ response.status === 429 ||
614
+ response.status >= 500, response.status);
615
+ return;
616
+ }
617
+ let usage;
618
+ try {
619
+ usage = this.adapter.readUsage?.({ target: view, response, text });
620
+ }
621
+ catch {
622
+ // Usage is for the log line only and must never fail a warm that worked.
623
+ }
624
+ const now = this.now();
625
+ // Reading usage can retire or replace the target. Log the served request
626
+ // either way, but only count a warm for the target that was replayed.
627
+ const current = this.isCurrent(sessionKey, target);
628
+ if (current) {
629
+ target.cacheExpiresAt = now + target.ttlMs;
630
+ target.lastWarmedAt = now;
631
+ target.backoffUntil = undefined;
632
+ this.clearRetry(target);
633
+ target.failures = 0;
634
+ target.warmCount += 1;
635
+ target.hasWarmed = true;
636
+ target.warmCostSoFar += nextWarmCost;
637
+ if (this.adapter.onWarmed) {
638
+ this.report(() => this.adapter.onWarmed?.(sessionKey, { at: now }));
639
+ }
640
+ }
641
+ this.log?.debug('cachekeep fired', {
642
+ sessionKey,
643
+ accountId: target.accountId,
644
+ warmCount: target.warmCount,
645
+ ...usage,
646
+ });
647
+ if (!current)
648
+ return;
649
+ if (this.usesLegacyBounds(target) &&
650
+ target.maxWarms !== undefined &&
651
+ target.warmCount >= target.maxWarms) {
652
+ this.log?.debug('cachekeep retired target (warm cap reached)', {
653
+ sessionKey,
654
+ warmCount: target.warmCount,
655
+ });
656
+ this.drop(sessionKey, 'count-cap');
657
+ }
658
+ if (target.plan && this.isCurrent(sessionKey, target)) {
659
+ if (this.refreshPlan(sessionKey, target))
660
+ this.planDecision(sessionKey, target);
661
+ }
662
+ }
663
+ idleDefault(isSubagent) {
664
+ return isSubagent ? this.maxSubagentIdleMs : this.maxIdleWarmMs;
665
+ }
666
+ pruneStale(skipSessionKey) {
667
+ const now = this.now();
668
+ const sustain = this.getSustain?.() === true;
669
+ for (const [sessionKey, target] of [...this.targets]) {
670
+ if (sessionKey === skipSessionKey)
671
+ continue;
672
+ if (this.retireIfExpired(sessionKey, target))
673
+ continue;
674
+ if (!this.refreshPlan(sessionKey, target))
675
+ continue;
676
+ if (!this.usesLegacyBounds(target))
677
+ continue;
678
+ this.retireIfIdle(sessionKey, target, sustain, now);
679
+ }
680
+ }
681
+ retireIfIdle(sessionKey, target, sustain, now = this.now()) {
682
+ // Sustain exempts main sessions from the idle cap only; the lifetime,
683
+ // window, count, byte and warm caps still apply to them.
684
+ if (sustain && !target.isSubagent)
685
+ return false;
686
+ const maxIdleMs = target.maxIdleMs ?? this.idleDefault(target.isSubagent);
687
+ if (target.lastRealRequestAt >= now - maxIdleMs)
688
+ return false;
689
+ this.log?.debug('cachekeep pruned idle target', {
690
+ sessionKey,
691
+ accountId: target.accountId,
692
+ lastRealRequestAt: target.lastRealRequestAt,
693
+ maxIdleMs,
694
+ });
695
+ this.drop(sessionKey, 'idle');
696
+ return true;
697
+ }
698
+ leastRecentlyTouched() {
699
+ let evictKey;
700
+ let evictTouchedAt = Number.POSITIVE_INFINITY;
701
+ for (const [key, target] of this.targets) {
702
+ // A warm counts as a touch, so a session kept warm outlives one whose
703
+ // only activity is an older real request.
704
+ const touchedAt = Math.max(target.lastRealRequestAt, target.lastWarmedAt ?? 0);
705
+ if (touchedAt < evictTouchedAt) {
706
+ evictKey = key;
707
+ evictTouchedAt = touchedAt;
708
+ }
709
+ }
710
+ return evictKey;
711
+ }
712
+ drop(sessionKey, reason = 'session-ended') {
713
+ const target = this.targets.get(sessionKey);
714
+ if (!target)
715
+ return false;
716
+ this.clearRetry(target);
717
+ this.clearPlanTimer(target);
718
+ this.totalBytes -= target.bodyBytes;
719
+ this.targets.delete(sessionKey);
720
+ if (reason !== null) {
721
+ this.lastDropReasons.delete(sessionKey);
722
+ this.lastDropReasons.set(sessionKey, reason);
723
+ while (this.lastDropReasons.size > this.maxTargets * 4) {
724
+ const oldest = this.lastDropReasons.keys().next();
725
+ if (oldest.done)
726
+ break;
727
+ this.lastDropReasons.delete(oldest.value);
728
+ }
729
+ }
730
+ if (reason !== null && target.hasWarmed && this.adapter.onWarmStopped) {
731
+ this.report(() => this.adapter.onWarmStopped?.(sessionKey, { at: this.now(), reason }));
732
+ }
733
+ return true;
734
+ }
735
+ }