cartethyia 2.6.7 → 2.7.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 (335) hide show
  1. package/.env.example +1 -7
  2. package/README.md +25 -2
  3. package/dist/dashboard/assets/{BannedPage-Dskhyp0l.js → BannedPage-D-J75hBM.js} +1 -1
  4. package/dist/dashboard/assets/BannedPage-D-J75hBM.js.gz +0 -0
  5. package/dist/dashboard/assets/{CliToolDetailPage--SJhk7qQ.js → CliToolDetailPage-CVe6RaBH.js} +1 -1
  6. package/dist/dashboard/assets/CliToolDetailPage-CVe6RaBH.js.gz +0 -0
  7. package/dist/dashboard/assets/{CliToolsPage-C203VT-c.js → CliToolsPage-Dd8ZSamp.js} +1 -1
  8. package/dist/dashboard/assets/CliToolsPage-Dd8ZSamp.js.gz +0 -0
  9. package/dist/dashboard/assets/{CombosPage-BcS7kGG1.js → CombosPage-QoJ6foxo.js} +1 -1
  10. package/dist/dashboard/assets/CombosPage-QoJ6foxo.js.gz +0 -0
  11. package/dist/dashboard/assets/ConsoleLogPage-DpNRay4C.js +1 -0
  12. package/dist/dashboard/assets/ConsoleLogPage-DpNRay4C.js.gz +0 -0
  13. package/dist/dashboard/assets/{CustomizationPage-uujbBYwC.js → CustomizationPage-CKUFTcW4.js} +1 -1
  14. package/dist/dashboard/assets/CustomizationPage-CKUFTcW4.js.gz +0 -0
  15. package/dist/dashboard/assets/HealthEventsModal-CzSLiDzr.js +1 -0
  16. package/dist/dashboard/assets/HealthEventsModal-CzSLiDzr.js.gz +0 -0
  17. package/dist/dashboard/assets/LoginPage-DubdQcvX.js +1 -0
  18. package/dist/dashboard/assets/LoginPage-DubdQcvX.js.gz +0 -0
  19. package/dist/dashboard/assets/{ModelPicker-CA1kLs45.js → ModelPicker-BH8Tehdi.js} +1 -1
  20. package/dist/dashboard/assets/ModelPicker-BH8Tehdi.js.gz +0 -0
  21. package/dist/dashboard/assets/OverviewPage-DuWzAQFL.js +1 -0
  22. package/dist/dashboard/assets/OverviewPage-DuWzAQFL.js.gz +0 -0
  23. package/dist/dashboard/assets/ProviderDetailPage-BKEKe2Fm.js +4 -0
  24. package/dist/dashboard/assets/ProviderDetailPage-BKEKe2Fm.js.gz +0 -0
  25. package/dist/dashboard/assets/ProviderIcon-FB6yS4v1.js +1 -0
  26. package/dist/dashboard/assets/ProviderIcon-FB6yS4v1.js.gz +0 -0
  27. package/dist/dashboard/assets/ProvidersPage-Bwotu8UJ.js +1 -0
  28. package/dist/dashboard/assets/ProvidersPage-Bwotu8UJ.js.gz +0 -0
  29. package/dist/dashboard/assets/ProxyPage-D7hpWbg9.js +9 -0
  30. package/dist/dashboard/assets/ProxyPage-D7hpWbg9.js.gz +0 -0
  31. package/dist/dashboard/assets/{QuotaPage-BueSWX5D.js → QuotaPage-ATpaxrbl.js} +1 -1
  32. package/dist/dashboard/assets/QuotaPage-ATpaxrbl.js.gz +0 -0
  33. package/dist/dashboard/assets/SettingsPage-CETophpx.js +1 -0
  34. package/dist/dashboard/assets/SettingsPage-CETophpx.js.gz +0 -0
  35. package/dist/dashboard/assets/SetupPage-BdgECjqq.js +1 -0
  36. package/dist/dashboard/assets/SetupPage-BdgECjqq.js.gz +0 -0
  37. package/dist/dashboard/assets/{SortableList-DrKeMcGN.js → SortableList-CAK-EN9z.js} +1 -1
  38. package/dist/dashboard/assets/SortableList-CAK-EN9z.js.gz +0 -0
  39. package/dist/dashboard/assets/{StudioPage-qjuYtccc.js → StudioPage-B7W2_RhT.js} +3 -3
  40. package/dist/dashboard/assets/StudioPage-B7W2_RhT.js.gz +0 -0
  41. package/dist/dashboard/assets/UsagePage-6T4EFDjW.js +56 -0
  42. package/dist/dashboard/assets/UsagePage-6T4EFDjW.js.gz +0 -0
  43. package/dist/dashboard/assets/{api-keys-C23S9sgp.js → api-keys-CUi6UXsR.js} +1 -1
  44. package/dist/dashboard/assets/api-keys-CUi6UXsR.js.gz +0 -0
  45. package/dist/dashboard/assets/app-KvsUJUMF.css +2 -0
  46. package/dist/dashboard/assets/app-KvsUJUMF.css.gz +0 -0
  47. package/dist/dashboard/assets/{assert-DU6qrMA_.js → assert-67xXH5rf.js} +1 -1
  48. package/dist/dashboard/assets/assert-67xXH5rf.js.gz +0 -0
  49. package/dist/dashboard/assets/{badge-Bkz_-RrM.js → badge-DC2L43Mj.js} +1 -1
  50. package/dist/dashboard/assets/badge-DC2L43Mj.js.gz +0 -0
  51. package/dist/dashboard/assets/{banner-C-7y3VKV.js → banner-BBVcb0J3.js} +1 -1
  52. package/dist/dashboard/assets/banner-BBVcb0J3.js.gz +0 -0
  53. package/dist/dashboard/assets/{card-BOPBuBzD.js → card-Cca1XC6G.js} +1 -1
  54. package/dist/dashboard/assets/card-Cca1XC6G.js.gz +0 -0
  55. package/dist/dashboard/assets/{cli-tools-BaFUuFFF.js → cli-tools-KvsWa1Jl.js} +1 -1
  56. package/dist/dashboard/assets/cli-tools-KvsWa1Jl.js.gz +0 -0
  57. package/dist/dashboard/assets/{clipboard-button-e-Mlk0FH.js → clipboard-button-DUzEbynq.js} +1 -1
  58. package/dist/dashboard/assets/clipboard-button-DUzEbynq.js.gz +0 -0
  59. package/dist/dashboard/assets/{dialog-Iec_ywbD.js → dialog-DFvWhwTa.js} +1 -1
  60. package/dist/dashboard/assets/dialog-DFvWhwTa.js.gz +0 -0
  61. package/dist/dashboard/assets/{drawer-Bs8MIIHc.js → drawer-CFM2sMX1.js} +1 -1
  62. package/dist/dashboard/assets/drawer-CFM2sMX1.js.gz +0 -0
  63. package/dist/dashboard/assets/{entry-DOddwoc0.js → entry-BLBLxX0h.js} +3 -3
  64. package/dist/dashboard/assets/entry-BLBLxX0h.js.gz +0 -0
  65. package/dist/dashboard/assets/{entry-DcobaKFu.js → entry-Bqy8RFvM.js} +1 -1
  66. package/dist/dashboard/assets/entry-Bqy8RFvM.js.gz +0 -0
  67. package/dist/dashboard/assets/{entry-BRszm4_Z.js → entry-_xHo5x6r.js} +1 -1
  68. package/dist/dashboard/assets/entry-_xHo5x6r.js.gz +0 -0
  69. package/dist/dashboard/assets/formatters-mpBPqAQ8.js +1 -0
  70. package/dist/dashboard/assets/formatters-mpBPqAQ8.js.gz +0 -0
  71. package/dist/dashboard/assets/{github-badge-BuDsrsPn.js → github-badge-C9e8Ts7e.js} +1 -1
  72. package/dist/dashboard/assets/github-badge-C9e8Ts7e.js.gz +0 -0
  73. package/dist/dashboard/assets/{index-BeLRhsmt.js → index-D6QzEC_n.js} +2 -2
  74. package/dist/dashboard/assets/index-D6QzEC_n.js.gz +0 -0
  75. package/dist/dashboard/assets/{inline-DToMICwl.js → inline-BFUcvllj.js} +1 -1
  76. package/dist/dashboard/assets/inline-BFUcvllj.js.gz +0 -0
  77. package/dist/dashboard/assets/{input-WlyHWeG2.js → input-C_ILAvBb.js} +1 -1
  78. package/dist/dashboard/assets/input-C_ILAvBb.js.gz +0 -0
  79. package/dist/dashboard/assets/{layout-DaJ5baJr.js → layout-CBIyT6Rt.js} +1 -1
  80. package/dist/dashboard/assets/layout-CBIyT6Rt.js.gz +0 -0
  81. package/dist/dashboard/assets/{list-row-B3oSK13z.js → list-row-ebJ_-Nsb.js} +1 -1
  82. package/dist/dashboard/assets/list-row-ebJ_-Nsb.js.gz +0 -0
  83. package/dist/dashboard/assets/{live-ta6GMb-8.js → live-D0mm--ME.js} +1 -1
  84. package/dist/dashboard/assets/live-D0mm--ME.js.gz +0 -0
  85. package/dist/dashboard/assets/minimize-2-D-MN8W8a.js +1 -0
  86. package/dist/dashboard/assets/minimize-2-D-MN8W8a.js.gz +0 -0
  87. package/dist/dashboard/assets/{mutation-g_fduiNw.js → mutation-sMD965oO.js} +1 -1
  88. package/dist/dashboard/assets/mutation-sMD965oO.js.gz +0 -0
  89. package/dist/dashboard/assets/{numbers-Dulqgys5.js → numbers-BO9dKaFr.js} +1 -1
  90. package/dist/dashboard/assets/numbers-BO9dKaFr.js.gz +0 -0
  91. package/dist/dashboard/assets/providers/inception.svg +5 -0
  92. package/dist/dashboard/assets/providers/inception.svg.gz +0 -0
  93. package/dist/dashboard/assets/{query-keys-UETqfytp.js → query-keys-CfL_Zdoh.js} +1 -1
  94. package/dist/dashboard/assets/query-keys-CfL_Zdoh.js.gz +0 -0
  95. package/dist/dashboard/assets/{routing-BPUo-W8d.js → routing-BnIpi1IJ.js} +1 -1
  96. package/dist/dashboard/assets/routing-BnIpi1IJ.js.gz +0 -0
  97. package/dist/dashboard/assets/{select-BfZ3SCTM.js → select-Cj5Nw43g.js} +1 -1
  98. package/dist/dashboard/assets/select-Cj5Nw43g.js.gz +0 -0
  99. package/dist/dashboard/assets/settings-BAFhDgX8.js +1 -0
  100. package/dist/dashboard/assets/settings-BAFhDgX8.js.gz +0 -0
  101. package/dist/dashboard/assets/{stack-B1w5BM0u.js → stack-EMrOMt4I.js} +1 -1
  102. package/dist/dashboard/assets/stack-EMrOMt4I.js.gz +0 -0
  103. package/dist/dashboard/assets/{state-DhZBfWgx.js → state-CWoo7ty5.js} +1 -1
  104. package/dist/dashboard/assets/state-CWoo7ty5.js.gz +0 -0
  105. package/dist/dashboard/assets/{switch-yD7D99Lg.js → switch-CCjT6IkF.js} +1 -1
  106. package/dist/dashboard/assets/switch-CCjT6IkF.js.gz +0 -0
  107. package/dist/dashboard/assets/{useMutation-EDFRkn1i.js → useMutation-DjkLHUcE.js} +1 -1
  108. package/dist/dashboard/assets/useMutation-DjkLHUcE.js.gz +0 -0
  109. package/dist/dashboard/index.html +1 -1
  110. package/dist/dashboard/index.html.gz +0 -0
  111. package/dist/dashboard/precompressed-assets.json +55 -54
  112. package/migrations/full-postgres/0024_add_pool_provider_cooldowns.sql +12 -0
  113. package/migrations/full-postgres/0025_add_pool_random_strategy.sql +3 -0
  114. package/migrations/lite-sqlite3/0024_add_pool_provider_cooldowns.sql +12 -0
  115. package/migrations/lite-sqlite3/0025_add_pool_random_strategy.sql +20 -0
  116. package/package.json +1 -1
  117. package/scripts/cli/console-menu.ts +5 -2
  118. package/scripts/cli/tray.ts +21 -6
  119. package/src/boot/app.ts +24 -62
  120. package/src/boot/dependencies.ts +732 -750
  121. package/src/config/cooldowns.ts +16 -0
  122. package/src/config/providers.ts +13 -1
  123. package/src/config/resources.ts +13 -80
  124. package/src/config/security.ts +2 -38
  125. package/src/config/spec.ts +16 -23
  126. package/src/console/console-router.ts +7 -7
  127. package/src/console/domain-registration.ts +19 -12
  128. package/src/console/providers/catalog/catalog-projections.ts +2 -6
  129. package/src/console/providers/catalog/contracts.ts +19 -0
  130. package/src/console/providers/catalog/provider-operations.ts +38 -0
  131. package/src/console/providers/catalog/routes.ts +14 -0
  132. package/src/console/providers/catalog/store-helpers.ts +326 -0
  133. package/src/console/providers/catalog/store.ts +1292 -1563
  134. package/src/console/quota/account-quota-global.ts +2 -2
  135. package/src/console/quota/account-quota-shared.ts +1 -1
  136. package/src/console/quota/account-quota-tenant.ts +35 -12
  137. package/src/console/quota/quota-view.ts +2 -2
  138. package/src/console/remote-support/contracts.ts +3 -1
  139. package/src/console/remote-support/service.ts +115 -6
  140. package/src/console/routing/pools/contracts.ts +41 -1
  141. package/src/console/routing/pools/operations.ts +183 -4
  142. package/src/console/routing/pools/relay-deploy.ts +17 -4
  143. package/src/console/routing/pools/routes.ts +30 -0
  144. package/src/console/routing/pools/store.ts +98 -8
  145. package/src/main.ts +16 -2
  146. package/src/network/outbound-fetch.ts +226 -365
  147. package/src/network/pool/agent.ts +8 -0
  148. package/src/network/pool/pool-state.ts +7 -0
  149. package/src/network/pool/selector.ts +110 -2
  150. package/src/network/pool-cooldown-store.ts +252 -0
  151. package/src/network/pool-health-machine.ts +5 -3
  152. package/src/network/pool-health.ts +36 -9
  153. package/src/observability/event-query.ts +57 -0
  154. package/src/observability/metrics.ts +15 -5
  155. package/src/observability/runtime-metrics.ts +30 -15
  156. package/src/persistence/health-event-flush.ts +2 -0
  157. package/src/persistence/schema.ts +19 -0
  158. package/src/persistence/usage-flush.ts +8 -3
  159. package/src/protocol/canonical-model.ts +1 -1
  160. package/src/protocol/dsml.ts +377 -0
  161. package/src/protocol/gateway-error.ts +0 -1
  162. package/src/{providers/provider-reasoning.ts → protocol/reasoning.ts} +10 -9
  163. package/src/protocol/request/chat.ts +7 -7
  164. package/src/protocol/request/codex.ts +2 -2
  165. package/src/protocol/request/gemini.ts +1 -1
  166. package/src/protocol/request/messages.ts +6 -6
  167. package/src/protocol/request/responses.ts +7 -7
  168. package/src/protocol/response/dsml.ts +12 -133
  169. package/src/{transport → protocol}/translation/attachment-integrity.ts +2 -2
  170. package/src/{transport → protocol}/translation/cache-controls.ts +1 -1
  171. package/src/{transport → protocol}/translation/capabilities.ts +2 -2
  172. package/src/{transport → protocol}/translation/normalize.ts +1 -1
  173. package/src/{transport → protocol}/translation/quirks.ts +1 -1
  174. package/src/{transport → protocol}/translation/search.ts +1 -1
  175. package/src/{transport → protocol}/translation/thinking.ts +23 -1
  176. package/src/{transport → protocol}/translation/tool-id.ts +1 -1
  177. package/src/{transport → protocol}/translation/tool-repair.ts +2 -2
  178. package/src/protocol/upstream-parsing.ts +176 -0
  179. package/src/providers/adapters/compatible-adapter.ts +11 -2
  180. package/src/providers/authentication/oauth-refresh-service.ts +9 -5
  181. package/src/providers/default-registry.ts +21 -5
  182. package/src/providers/discovery/probe-phases.ts +16 -3
  183. package/src/providers/discovery/probing-service.ts +4 -1
  184. package/src/providers/integrations/anthropic.ts +1 -1
  185. package/src/providers/integrations/buddy/buddy-catalog-shared.ts +1 -4
  186. package/src/providers/integrations/buddy/buddy-chat-shared.ts +141 -8
  187. package/src/providers/integrations/buddy/buddy-checkin.ts +5 -1
  188. package/src/providers/integrations/buddy/buddy-growth-shared.ts +0 -82
  189. package/src/providers/integrations/buddy/buddy-identity.ts +25 -0
  190. package/src/providers/integrations/buddy/buddy-server-tools.ts +240 -0
  191. package/src/providers/integrations/buddy/codebuddy/cn-catalog.ts +36 -0
  192. package/src/providers/integrations/buddy/codebuddy/cn-provider.ts +6 -31
  193. package/src/providers/integrations/buddy/codebuddy/provider.ts +2 -0
  194. package/src/providers/integrations/buddy/codebuddy/shared.ts +19 -4
  195. package/src/providers/integrations/buddy/turing-device-token.ts +262 -0
  196. package/src/providers/integrations/buddy/workbuddy/provider.ts +2 -0
  197. package/src/providers/integrations/buddy/workbuddy/shared.ts +56 -3
  198. package/src/providers/integrations/claude/claude.ts +1 -1
  199. package/src/providers/integrations/cloudflareai/cloudflareai.ts +1 -1
  200. package/src/providers/integrations/codex/codex-errors.ts +1 -1
  201. package/src/providers/integrations/codex/codex.ts +1 -1
  202. package/src/providers/integrations/commandcode/commandcode.ts +134 -104
  203. package/src/providers/integrations/commandcode/discovery.ts +6 -5
  204. package/src/providers/integrations/factory/factory.ts +1 -1
  205. package/src/providers/integrations/github/github.ts +1 -1
  206. package/src/providers/integrations/grok/grok.ts +1 -1
  207. package/src/providers/integrations/inception/provider.ts +91 -0
  208. package/src/providers/integrations/inferhub.ts +1 -1
  209. package/src/providers/integrations/kiro/kiro-request.ts +1 -1
  210. package/src/providers/integrations/mistral.ts +193 -19
  211. package/src/providers/integrations/opencode/fingerprint.ts +19 -2
  212. package/src/providers/integrations/opencode/prompt.ts +111 -0
  213. package/src/providers/integrations/opencode/provider.ts +101 -23
  214. package/src/providers/integrations/opencode/tool-definitions.ts +4 -4
  215. package/src/providers/integrations/qoder/qoder-checkin.ts +303 -0
  216. package/src/providers/integrations/qoder/qoder.ts +1641 -884
  217. package/src/providers/integrations/shared/install-id.ts +2 -1
  218. package/src/providers/integrations/trae/trae-cache.ts +110 -0
  219. package/src/providers/integrations/trae/trae-oauth.ts +29 -4
  220. package/src/providers/integrations/trae/trae-protocol.ts +2 -1
  221. package/src/providers/integrations/trae/trae.ts +106 -23
  222. package/src/providers/operations/account-error-classification.ts +1660 -0
  223. package/src/providers/operations/account-health-service.ts +621 -2097
  224. package/src/providers/operations/account-reset-service.ts +2 -0
  225. package/src/providers/provider-contracts.ts +0 -2
  226. package/src/providers/provider-metadata.ts +25 -4
  227. package/src/providers/provider-probe.ts +2 -2
  228. package/src/{console → providers}/quota/cache.ts +1 -1
  229. package/src/{console → providers}/quota/refresh.ts +5 -5
  230. package/src/security/abuse.ts +17 -0
  231. package/src/transport/dispatch/attempt-finalize.ts +114 -12
  232. package/src/transport/dispatch/attempt-loop.ts +3 -0
  233. package/src/transport/dispatch/empty-stream.ts +224 -217
  234. package/src/transport/dispatch/generation.ts +37 -55
  235. package/src/transport/dispatch/handler-deps.ts +32 -0
  236. package/src/transport/dispatch/leases.ts +9 -4
  237. package/src/transport/dispatch/proxy-request.ts +6 -30
  238. package/src/transport/dispatch/responses-compact.ts +22 -43
  239. package/src/transport/dispatch/streaming/finalize.ts +3 -0
  240. package/src/transport/dispatch/streaming/stream.ts +0 -8
  241. package/src/transport/dispatch/systemone.ts +22 -42
  242. package/src/transport/dispatch/token-count.ts +23 -39
  243. package/src/transport/dispatch/upstream.ts +1 -3
  244. package/src/transport/dispatch/websearch.ts +22 -41
  245. package/src/transport/failure-policy.ts +59 -178
  246. package/src/transport/guards/abuse-guard.ts +10 -0
  247. package/src/transport/guards/auth-guard.ts +0 -18
  248. package/src/transport/guards/error-lifecycle.ts +1 -1
  249. package/src/transport/guards/pipeline.ts +0 -6
  250. package/src/transport/guards/request-context.ts +18 -91
  251. package/src/transport/request/degradation.ts +20 -1
  252. package/src/transport/request/inflight.ts +4 -95
  253. package/src/transport/request/preparer.ts +6 -6
  254. package/src/transport/request/state.ts +66 -38
  255. package/src/transport/request/tenant-preferences.ts +1 -1
  256. package/src/transport/routing/route-catalog.ts +41 -31
  257. package/src/transport/routing/router.ts +2 -2
  258. package/src/transport/surface/messages/parse.ts +1 -1
  259. package/src/workers/buddy-growth-tasks.ts +346 -425
  260. package/src/workers/daily-checkin.ts +17 -6
  261. package/src/workers/quota-refresh-sweep.ts +2 -2
  262. package/src/workers/scheduler.ts +17 -1
  263. package/dist/dashboard/assets/BannedPage-Dskhyp0l.js.gz +0 -0
  264. package/dist/dashboard/assets/CliToolDetailPage--SJhk7qQ.js.gz +0 -0
  265. package/dist/dashboard/assets/CliToolsPage-C203VT-c.js.gz +0 -0
  266. package/dist/dashboard/assets/CombosPage-BcS7kGG1.js.gz +0 -0
  267. package/dist/dashboard/assets/ConsoleLogPage-ChmiSLwO.js +0 -1
  268. package/dist/dashboard/assets/ConsoleLogPage-ChmiSLwO.js.gz +0 -0
  269. package/dist/dashboard/assets/CustomizationPage-uujbBYwC.js.gz +0 -0
  270. package/dist/dashboard/assets/HealthEventsModal-fKAWd-OQ.js +0 -1
  271. package/dist/dashboard/assets/HealthEventsModal-fKAWd-OQ.js.gz +0 -0
  272. package/dist/dashboard/assets/LoginPage-DoOUthbG.js +0 -1
  273. package/dist/dashboard/assets/LoginPage-DoOUthbG.js.gz +0 -0
  274. package/dist/dashboard/assets/ModelPicker-CA1kLs45.js.gz +0 -0
  275. package/dist/dashboard/assets/OverviewPage-C5Z-UBz1.js +0 -1
  276. package/dist/dashboard/assets/OverviewPage-C5Z-UBz1.js.gz +0 -0
  277. package/dist/dashboard/assets/ProviderDetailPage-CFu1qGcT.js +0 -3
  278. package/dist/dashboard/assets/ProviderDetailPage-CFu1qGcT.js.gz +0 -0
  279. package/dist/dashboard/assets/ProviderIcon-CmfzxpVM.js +0 -1
  280. package/dist/dashboard/assets/ProviderIcon-CmfzxpVM.js.gz +0 -0
  281. package/dist/dashboard/assets/ProvidersPage-CnlJZbxF.js +0 -1
  282. package/dist/dashboard/assets/ProvidersPage-CnlJZbxF.js.gz +0 -0
  283. package/dist/dashboard/assets/ProxyPage-B9mBTweh.js +0 -7
  284. package/dist/dashboard/assets/ProxyPage-B9mBTweh.js.gz +0 -0
  285. package/dist/dashboard/assets/QuotaPage-BueSWX5D.js.gz +0 -0
  286. package/dist/dashboard/assets/SettingsPage-B0x00MVY.js +0 -1
  287. package/dist/dashboard/assets/SettingsPage-B0x00MVY.js.gz +0 -0
  288. package/dist/dashboard/assets/SetupPage-DQ9oDRpi.js +0 -1
  289. package/dist/dashboard/assets/SetupPage-DQ9oDRpi.js.gz +0 -0
  290. package/dist/dashboard/assets/SortableList-DrKeMcGN.js.gz +0 -0
  291. package/dist/dashboard/assets/StudioPage-qjuYtccc.js.gz +0 -0
  292. package/dist/dashboard/assets/UsagePage-Be7aNviQ.js +0 -56
  293. package/dist/dashboard/assets/UsagePage-Be7aNviQ.js.gz +0 -0
  294. package/dist/dashboard/assets/api-keys-C23S9sgp.js.gz +0 -0
  295. package/dist/dashboard/assets/app-BUSiYL6F.css +0 -2
  296. package/dist/dashboard/assets/app-BUSiYL6F.css.gz +0 -0
  297. package/dist/dashboard/assets/assert-DU6qrMA_.js.gz +0 -0
  298. package/dist/dashboard/assets/badge-Bkz_-RrM.js.gz +0 -0
  299. package/dist/dashboard/assets/banner-C-7y3VKV.js.gz +0 -0
  300. package/dist/dashboard/assets/card-BOPBuBzD.js.gz +0 -0
  301. package/dist/dashboard/assets/cli-tools-BaFUuFFF.js.gz +0 -0
  302. package/dist/dashboard/assets/clipboard-button-e-Mlk0FH.js.gz +0 -0
  303. package/dist/dashboard/assets/cog-CdWhsajs.js +0 -1
  304. package/dist/dashboard/assets/cog-CdWhsajs.js.gz +0 -0
  305. package/dist/dashboard/assets/dialog-Iec_ywbD.js.gz +0 -0
  306. package/dist/dashboard/assets/drawer-Bs8MIIHc.js.gz +0 -0
  307. package/dist/dashboard/assets/entry-BRszm4_Z.js.gz +0 -0
  308. package/dist/dashboard/assets/entry-DOddwoc0.js.gz +0 -0
  309. package/dist/dashboard/assets/entry-DcobaKFu.js.gz +0 -0
  310. package/dist/dashboard/assets/github-badge-BuDsrsPn.js.gz +0 -0
  311. package/dist/dashboard/assets/index-BeLRhsmt.js.gz +0 -0
  312. package/dist/dashboard/assets/inline-DToMICwl.js.gz +0 -0
  313. package/dist/dashboard/assets/input-WlyHWeG2.js.gz +0 -0
  314. package/dist/dashboard/assets/layout-DaJ5baJr.js.gz +0 -0
  315. package/dist/dashboard/assets/list-row-B3oSK13z.js.gz +0 -0
  316. package/dist/dashboard/assets/live-ta6GMb-8.js.gz +0 -0
  317. package/dist/dashboard/assets/model-bans-BmYTmbAk.js +0 -1
  318. package/dist/dashboard/assets/model-bans-BmYTmbAk.js.gz +0 -0
  319. package/dist/dashboard/assets/mutation-g_fduiNw.js.gz +0 -0
  320. package/dist/dashboard/assets/numbers-Dulqgys5.js.gz +0 -0
  321. package/dist/dashboard/assets/query-keys-UETqfytp.js.gz +0 -0
  322. package/dist/dashboard/assets/routing-BPUo-W8d.js.gz +0 -0
  323. package/dist/dashboard/assets/select-BfZ3SCTM.js.gz +0 -0
  324. package/dist/dashboard/assets/settings--3hxSyry.js +0 -1
  325. package/dist/dashboard/assets/settings--3hxSyry.js.gz +0 -0
  326. package/dist/dashboard/assets/stack-B1w5BM0u.js.gz +0 -0
  327. package/dist/dashboard/assets/state-DhZBfWgx.js.gz +0 -0
  328. package/dist/dashboard/assets/switch-yD7D99Lg.js.gz +0 -0
  329. package/dist/dashboard/assets/useMutation-EDFRkn1i.js.gz +0 -0
  330. package/src/console/admin/model-abuse/contracts.ts +0 -38
  331. package/src/console/admin/model-abuse/routes.ts +0 -97
  332. package/src/security/model-abuse.ts +0 -704
  333. package/src/transport/guards/concurrency-guard.ts +0 -125
  334. /package/dist/dashboard/assets/{app-MdVfwraB.js → app-BaWd0puM.js} +0 -0
  335. /package/dist/dashboard/assets/{app-MdVfwraB.js.gz → app-BaWd0puM.js.gz} +0 -0
@@ -1,750 +1,732 @@
1
-
2
- import { assertPoolFitsServerCapacity, bootDatabase, ensureMigrated } from "../persistence/boot";
3
- import { poolMaxFromEnv } from "../persistence/db-pg";
4
- import type { CartethyiaDatabase } from "../persistence/db-handle";
5
- import { resolveRedisBackend, resolveRedisClient } from "../persistence/redis";
6
- import { resolveProcessTopology, type ProcessTopology } from "../config/runtime";
7
- import { createRedisMaintenanceLeaseStore } from "../workers/maintenance-lease";
8
- import { resolveDbMode } from "../persistence/db-mode";
9
- import type { RedisClient } from "../persistence/redis";
10
- import {
11
- bundledModelCatalog,
12
- liveProviderUpstreamHosts,
13
- markCatalogSeeded,
14
- refreshActiveProviderCatalogs,
15
- registerByokProviders,
16
- retireUnbundledProviders,
17
- seedBundledProviders,
18
- } from "../providers/operations/provider-catalog-service";
19
- import type { BundledProviderCatalog } from "../providers/operations/provider-catalog-service";
20
- import { createDefaultProviderRegistry } from "../providers/default-registry";
21
- import { OAuthRefreshService, loadDueOAuthAccounts, reconcileStaticTokenAccounts } from "../providers/authentication/oauth-refresh-service";
22
- import type { OAuthTokenRefresher } from "../providers/authentication/oauth-refresh-service";
23
- import { oauthRefreshSweep } from "../workers/oauth-refresh-sweep";
24
- import { accountIdentitySweep } from "../workers/account-identity-sweep";
25
- import { pushStructuredConsoleLog } from "../observability/log-ring";
26
- import { seedBundledModels } from "../providers/operations/provider-catalog-seeder";
27
- import { createDatabaseSnapshotBuilder } from "../transport/routing/route-catalog";
28
- import { DrizzleProviderCatalogStore } from "../console/providers/catalog/store";
29
- import { InMemoryRouteSnapshotService } from "../transport/routing/route-model";
30
- import { RoutingEngine } from "../transport/routing/router";
31
- import { RedisAdmissionController } from "../transport/routing/admission";
32
- import { ApiKeyAdmissionService } from "../security/admission/service";
33
- import { InMemoryAdmissionCounterStore } from "../security/admission/in-memory-store";
34
- import { RedisAdmissionCounterStore } from "../security/admission/redis-store";
35
- import { sweepLeases } from "../security/admission/lease-sweep";
36
- import { DrizzleApiKeyStore } from "../persistence/stores/api-key-store";
37
- import { UsageFlushBuffer } from "../persistence/usage-flush";
38
- import { setPendingUsageSource } from "../security/api-key-auth";
39
- import { HealthEventFlushBuffer, setHealthEventBuffer } from "../persistence/health-event-flush";
40
- import { subscribePeerSettingsRevisions } from "../persistence/settings-revision";
41
- import { deleteExpiredSessions } from "../console/auth/session-service";
42
- import { InMemoryIpAbuseStore, IpAbuseProtectionService, RedisIpAbuseStore } from "../security/abuse";
43
- import {
44
- InMemoryModelAbuseStore,
45
- ModelStrikeService,
46
- RedisModelAbuseStore,
47
- } from "../security/model-abuse";
48
- import { checkReadiness } from "../persistence/readiness";
49
- import { ProxyRequestPreparer } from "../transport/request/preparer";
50
- import { DrizzleNetworkPoolLoader } from "../network/pool/loader";
51
- import {
52
- PoolAgentResolver,
53
- ValidatedNetworkBindingFactory,
54
- } from "../network/pool/resolver";
55
- import { NetworkPoolSelector } from "../network/pool/selector";
56
- import { ScheduledTaskRegistry } from "../workers/scheduler";
57
- import { quotaRefreshSweep } from "../workers/quota-refresh-sweep";
58
- import { markProviderApiKeyCredential } from "../console/quota/account-quota-shared";
59
- import { dailyCheckinEgressForPass } from "../workers/daily-checkin";
60
- import {
61
- buddyAdoptTask,
62
- buddyActivityReportTask,
63
- buddyLotteryTask,
64
- buddyRedeemTask,
65
- buddyStreakTask,
66
- buddyTravelTask,
67
- buddyTrialTask,
68
- syncBuddyUsage,
69
- } from "../workers/buddy-growth-tasks";
70
- import { createAccountSecretResolver } from "../providers/operations/provider-credential-service";
71
- import { quotaCacheSize } from "../console/quota/cache";
72
- import { modelCatalogCacheSize } from "../providers/operations/model-catalog-cache";
73
- import { preferencesReaderFor } from "../persistence/tenant-preferences";
74
- import { sweepExpiredCooldowns } from "../providers/operations/account-health-service";
75
- import { DrizzleTelemetryStore } from "../persistence/stores/telemetry-store";
76
- import { TelemetryPayloadCapture } from "../observability/payload-capture";
77
- import { sweepExpiredPoolCooldowns } from "../network/pool-health-machine";
78
- import { TelemetryBatchBuffer } from "../observability/telemetry-buffer";
79
- import { RuntimeMetricsSampler } from "../observability/runtime-metrics";
80
- import {
81
- resolveIpRateLimit,
82
- resolveModelBanMaxTtlMs,
83
- resolveModelBanTtlMs,
84
- resolveModelStrikeThreshold,
85
- resolveModelStrikeWindowMs,
86
- } from "../config/security";
87
- import { resolveSsrfPolicy, resolveTrustedProxyBoundary } from "../config/network";
88
- import type { TrustedProxyBoundary } from "../config/network";
89
- import { resolveTelemetryRetentionDays } from "../config/telemetry";
90
- import { resolveConcurrencyTolerance } from "../config/resources";
91
- import { CONFIG_SPEC, readInt, readList } from "../config/spec";
92
- import type { ProviderAdapter } from "../providers/provider-contracts";
93
- import type { ProviderRegistry } from "../providers/provider-registry";
94
- import type { ByokUpstreamHost } from "../providers/operations/provider-catalog-service";
95
- import type { ReadinessCheckResult } from "../persistence/readiness";
96
- import { log } from "../observability/logger";
97
- import { refreshProviderClientVersions } from "../providers/operations/client-versions";
98
-
99
-
100
- export interface ProductionDeps {
101
- db: CartethyiaDatabase;
102
- redis: RedisClient | undefined;
103
- snapshotService: InMemoryRouteSnapshotService;
104
- /** Live routing admission snapshot scoped to one provider/tenant for console reads. */
105
- readRoutingAccountInflight: (
106
- providerId: string,
107
- tenantId: string | null,
108
- ) => Promise<readonly { accountId: string; inflight: number }[]>;
109
- /** On-demand adapter resolution keeps heavy providers out of the boot path. */
110
- resolveProviderAdapter: (providerId: string) => Promise<ProviderAdapter | undefined>;
111
- bundledModelCatalog: BundledProviderCatalog;
112
- /** Live lookup of a provider's SSRF-validated upstream host. */
113
- byokUpstreamHosts: { readonly get: (providerId: string) => ByokUpstreamHost | undefined };
114
- proxyPreparer: ProxyRequestPreparer;
115
- networkBindingFactory: ValidatedNetworkBindingFactory;
116
- ipAbuseProtection: IpAbuseProtectionService;
117
- readiness: () => Promise<ReadinessCheckResult>;
118
- scheduledTasks: ScheduledTaskRegistry;
119
- poolAgentResolver: PoolAgentResolver;
120
- poolSelector: NetworkPoolSelector;
121
- telemetryBuffer: TelemetryBatchBuffer;
122
- usageFlush: UsageFlushBuffer;
123
- healthEventFlush: HealthEventFlushBuffer;
124
- trustedProxyBoundary: TrustedProxyBoundary;
125
- providerRegistry: ProviderRegistry;
126
- resolveOAuthRefresher: (providerId: string) => Promise<OAuthTokenRefresher | undefined>;
127
- oauthRefreshService: OAuthRefreshService;
128
- admissionService: ApiKeyAdmissionService;
129
- /** Graduated strikes for repeated invalid-model requests. */
130
- modelStrikes: ModelStrikeService;
131
- /** Memory sampler; in-flight source is bound once the request store exists. */
132
- runtimeMetricsSampler: RuntimeMetricsSampler;
133
- }
134
-
135
- /**
136
- * Pause between accounts in the OAuth refresh sweep. The token endpoints
137
- * rate-limit a burst of refreshes even at low concurrency.
138
- */
139
- const OAUTH_REFRESH_INTER_ITEM_DELAY_MS = 1_500;
140
-
141
- /**
142
- * Client identities are refreshed out of band so provider dispatch never waits
143
- * on npm/provider version endpoints. Resolver TTLs deduplicate the sources.
144
- */
145
- // Matched to the resolver's own 30 min cache TTL: a shorter interval makes
146
- // every second pass a pure cache read that cannot discover anything new.
147
- const CLIENT_VERSION_MONITOR_INTERVAL_MS = 30 * 60_000;
148
- const CLIENT_VERSION_INITIAL_DELAY_MS = 10_000;
149
-
150
- /** Bound on the boot-time Redis probe: a start must fail, not hang. */
151
- const REDIS_PROBE_TIMEOUT_MS = 2_000;
152
-
153
- async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
154
- const { promise: timeout, reject } = Promise.withResolvers<never>();
155
- const timer = setTimeout(() => reject(new Error("timeout")), ms);
156
- try {
157
- return await Promise.race([promise, timeout]);
158
- } finally {
159
- clearTimeout(timer);
160
- }
161
- }
162
-
163
- /** Bounded Redis reachability probe: fails rather than hangs. */
164
- async function redisIsReachable(): Promise<boolean> {
165
- const client = resolveRedisClient();
166
- if (!client) return false;
167
- try {
168
- const result = await withTimeout(client.ping(), REDIS_PROBE_TIMEOUT_MS);
169
- return result === "PONG";
170
- } catch {
171
- return false;
172
- }
173
- }
174
-
175
- /**
176
- * Refuses to start a multi-process deployment whose shared state is not
177
- * actually shared.
178
- *
179
- * Every process shares one port via `SO_REUSEPORT`, so the kernel balances
180
- * across them — and each process keeps its own in-memory admission counters,
181
- * quota cache, and cooldown map. Those are only correct when they live in
182
- * Redis. Starting anyway does not fail loudly; it enforces every per-key limit
183
- * N times over, which then reads as "the limit did not work".
184
- *
185
- * Redis is checked by PING with a hard bound, not merely for being configured:
186
- * a configured-but-unreachable Redis is the failure mode that matters, and an
187
- * unbounded connect at boot would hang the start instead of failing it.
188
- */
189
- async function assertMultiProcessPreconditions(
190
- topology: ProcessTopology,
191
- redisReachable: () => Promise<boolean>,
192
- ): Promise<void> {
193
- if (!topology.multiProcess) return;
194
- if (process.platform !== "linux") {
195
- throw Object.assign(
196
- new Error(
197
- `CARTETHYIA_PROCESS_COUNT=${topology.count} requires Linux (SO_REUSEPORT); ` +
198
- `this process is on ${process.platform}`,
199
- ),
200
- { code: "multi_process_unsupported_platform" },
201
- );
202
- }
203
- if (resolveDbMode() !== "full") {
204
- throw Object.assign(
205
- new Error(
206
- `CARTETHYIA_PROCESS_COUNT=${topology.count} requires CARTETHYIA_DB_MODE=full (PostgreSQL); ` +
207
- "two processes on one SQLite file corrupt it — there is no cross-process lock in the driver",
208
- ),
209
- { code: "multi_process_requires_postgres" },
210
- );
211
- }
212
- const reachable = await redisReachable();
213
- if (!reachable) {
214
- throw Object.assign(
215
- new Error(
216
- `CARTETHYIA_PROCESS_COUNT=${topology.count} requires a REACHABLE Redis: admission counters, ` +
217
- "quotas, and cooldowns are per-process without one, so every per-key limit would be " +
218
- `enforced ${topology.count} times over`,
219
- ),
220
- { code: "multi_process_requires_redis" },
221
- );
222
- }
223
- }
224
-
225
- export async function buildProductionDeps(): Promise<ProductionDeps> {
226
- const startupStartedAt = performance.now();
227
- const startupMemoryBefore = process.memoryUsage();
228
- // Resolved first and validated before any connection is opened: a
229
- // half-configured multi-process deploy that starts anyway looks healthy
230
- // until a per-key limit is enforced N times over.
231
- const topology = resolveProcessTopology();
232
- await assertMultiProcessPreconditions(topology, redisIsReachable);
233
- const handle = await measureStartupPhase("database-connect", bootDatabase);
234
- const db = handle.db;
235
- // One rule, no mode flag: REDIS_URL set → shared client, unset → memory.
236
- const redis = resolveRedisClient();
237
- const ssrfPolicy = resolveSsrfPolicy();
238
- await measureStartupPhase("database-migrations", async () => {
239
- await ensureMigrated();
240
- // Pool sizing is an external-server concern; the embedded backend has no
241
- // connection budget to fit into.
242
- if (handle.kind === "pg") await assertPoolFitsServerCapacity(poolMaxFromEnv(), topology.count);
243
- });
244
- await measureStartupPhase("provider-seed", () => seedBundledProviders(db));
245
- // Boot-only: retire global rows for providers the bundle has dropped, so a
246
- // retired provider cannot linger as a card the console can no longer delete.
247
- // Kept off the test harness path, which shares one database across suites and
248
- // installs its own global fixtures.
249
- await measureStartupPhase("retired-provider-cleanup", () => retireUnbundledProviders(db));
250
- const registry = createDefaultProviderRegistry();
251
- // Live view, not a snapshot: custom providers registered after boot (or
252
- // edited from the console) must resolve their SSRF binding immediately.
253
- const byokUpstreamHosts = liveProviderUpstreamHosts(registry);
254
- await measureStartupPhase("byok-registration", () =>
255
- registerByokProviders(registry, db, ssrfPolicy),
256
- );
257
- const bundledCatalog = await measureStartupPhase("bundled-model-catalog", () =>
258
- bundledModelCatalog(registry),
259
- );
260
- await measureStartupPhase("bundled-model-seed", () =>
261
- seedBundledModels(db, bundledCatalog.modelsByProvider),
262
- );
263
- // The boot seed above is unconditional, so record it: the snapshot builder's
264
- // first rebuild would otherwise re-seed an identical catalog.
265
- markCatalogSeeded();
266
- const snapshotService = new InMemoryRouteSnapshotService(
267
- createDatabaseSnapshotBuilder(db, () => refreshActiveProviderCatalogs(db, registry)),
268
- );
269
- const routingEngine = new RoutingEngine(
270
- redis ? new RedisAdmissionController(redis) : undefined,
271
- redis,
272
- );
273
- const readRoutingAccountInflight = async (
274
- providerId: string,
275
- tenantId: string | null,
276
- ): Promise<readonly { accountId: string; inflight: number }[]> => {
277
- if (providerId === "" || tenantId === null) return [];
278
- const accounts = await new DrizzleProviderCatalogStore(db, {
279
- telemetryBuffer,
280
- bundledModelCatalog: bundledCatalog,
281
- providerRegistry: registry,
282
- outboundFetchFor: async () => ({ fetch: networkBindingFactory.fetch(undefined, tenantId) }),
283
- snapshotInvalidator: snapshotService,
284
- }).listAccounts(tenantId, providerId);
285
- const owned = new Set(accounts.map((account) => account.id));
286
- // Scoped read: only the provider's own candidates for this tenant are
287
- // queried, so the console read costs one exact MGET over the accounts it
288
- // is about to report on — not a fleet-wide `KEYS` scan whose cost is the
289
- // size of every bucket every process ever wrote.
290
- const routeSnapshot = await snapshotService.getSnapshot();
291
- const ownedCandidates = routeSnapshot.candidates.filter(
292
- (candidate) =>
293
- candidate.provider_id === providerId &&
294
- candidate.provider_account_id !== undefined &&
295
- owned.has(candidate.provider_account_id),
296
- );
297
- const snapshot = await routingEngine.accountInflightSnapshot(ownedCandidates);
298
- const totals = new Map<string, number>();
299
- for (const [bucket, count] of snapshot) {
300
- const accountId = bucket.slice(bucket.lastIndexOf(":") + 1);
301
- if (!owned.has(accountId)) continue;
302
- totals.set(accountId, (totals.get(accountId) ?? 0) + count);
303
- }
304
- return [...totals].map(([accountId, inflight]) => ({ accountId, inflight }));
305
- };
306
- // Peer processes' settings mutations arrive here. Subscribed once for the
307
- // process: the revision counter is process-global, and the handler only
308
- // moves it forward.
309
- subscribePeerSettingsRevisions();
310
- const usageFlush = new UsageFlushBuffer(db);
311
- // Auth reads lifetime usage to seed the admission counter. The persisted
312
- // value lags by up to one flush interval, so hand it the in-flight deltas
313
- // too — otherwise the seed is systematically under what has actually been
314
- // spent, worst exactly when the key is busiest.
315
- setPendingUsageSource((apiKeyId) => usageFlush.pendingFor(apiKeyId));
316
- // Health audit rows are append-only and read by nobody in dispatch, so they
317
- // are buffered out of the request. The status write they accompany stays
318
- // synchronous — routing reads it.
319
- const healthEventFlush = new HealthEventFlushBuffer(db);
320
- setHealthEventBuffer(healthEventFlush);
321
- const admissionStore = redis
322
- ? new RedisAdmissionCounterStore(redis)
323
- : new InMemoryAdmissionCounterStore();
324
- const admissionService = new ApiKeyAdmissionService(
325
- admissionStore,
326
- undefined,
327
- // The per-tenant concurrency cap is a `console_settings` preference, read
328
- // on every admitted request. Reading it directly cost one Postgres round
329
- // trip per request (multiplied by each failover candidate); the shared
330
- // revision-keyed reader answers from memory and converges the moment an
331
- // operator saves, because `DrizzleRuntimeSettingsStore.update` bumps the
332
- // revision every cached key embeds.
333
- (tenantId) =>
334
- preferencesReaderFor(db)
335
- .readPreferences(tenantId)
336
- .then((prefs) => prefs?.tenantConcurrencyLimit ?? null),
337
- ({ apiKeyId, delta }) => {
338
- // Coalesced: one UPDATE per key per flush instead of one per request.
339
- // The admission counter is the live total; this only persists it.
340
- usageFlush.enqueue(apiKeyId, delta);
341
- return Promise.resolve();
342
- },
343
- // Fresh lifetime reader — invoked by the store only when it is about to
344
- // seed a missing `admission:lifetime:<id>` counter, so the ≤3s-stale auth
345
- // snapshot value cannot freeze a low baseline in place. Family total: the
346
- // row plus every child (share recipients admit under the parent id).
347
- async (apiKeyId) => {
348
- const store = new DrizzleApiKeyStore(db);
349
- const row = await store.findActiveById(apiKeyId);
350
- if (!row) return undefined;
351
- const children = await store.sumChildrenConsumed(apiKeyId);
352
- return (row.lifetimeTokensConsumed ?? 0) + children;
353
- },
354
- // Slack above every key's concurrency limit. A tenant preference an
355
- // operator sets in the runtime settings modal, falling back to the
356
- // deployment default so an unset row does not silently lose the allowance.
357
- (tenantId) =>
358
- preferencesReaderFor(db)
359
- .readPreferences(tenantId)
360
- .then((prefs) => prefs?.concurrencyTolerance ?? resolveConcurrencyTolerance()),
361
- );
362
- const ipStore = redis
363
- ? new RedisIpAbuseStore(redis)
364
- : new InMemoryIpAbuseStore();
365
- const ipAbuseProtection = new IpAbuseProtectionService(ipStore, undefined, {
366
- maxRequestsPerWindow: resolveIpRateLimit(),
367
- });
368
- // Graduated model-abuse strikes: a client that keeps requesting models
369
- // outside its access is warned, then banned. Redis-backed when available so
370
- // the ban survives a restart and is shared across instances; in-memory
371
- // otherwise, where a restart clears it.
372
- const modelAbuseStore = redis ? new RedisModelAbuseStore(redis) : new InMemoryModelAbuseStore();
373
- const modelStrikes = new ModelStrikeService(modelAbuseStore, {
374
- threshold: resolveModelStrikeThreshold(),
375
- windowMs: resolveModelStrikeWindowMs(),
376
- banTtlMs: resolveModelBanTtlMs(),
377
- maxBanTtlMs: resolveModelBanMaxTtlMs(),
378
- });
379
- const readiness = () => checkReadiness(db, redis, resolveRedisBackend(redis));
380
- // One list covers every periodic task: a small deployment can cut the
381
- // heaviest sweeps (quota refresh, OAuth refresh, client-version polling)
382
- // without the codebase growing a flag per task.
383
- // Leases coordinate the SHARED sweeps across processes. Absent Redis there is
384
- // nothing to coordinate with, and the registry's local one-at-a-time rule is
385
- // the correct (and only) guard.
386
- const scheduledTasks = new ScheduledTaskRegistry(
387
- readList("CARTETHYIA_DISABLED_TASKS", CONFIG_SPEC.CARTETHYIA_DISABLED_TASKS) ?? [],
388
- {
389
- ...(redis ? { lease: createRedisMaintenanceLeaseStore(redis) } : {}),
390
- },
391
- );
392
- if (redis) {
393
- scheduledTasks.register({
394
- name: "lease-sweep",
395
- intervalMs: 30_000,
396
- run: () => sweepLeases(redis),
397
- });
398
- }
399
- scheduledTasks.register({
400
- name: "account-health-sweep",
401
- intervalMs: 30_000,
402
- // Recovers cooldowns deployment-wide and invalidates the shared snapshot.
403
- shared: true,
404
- run: async () => {
405
- const recovered = await sweepExpiredCooldowns(db);
406
- const poolRecovered = await sweepExpiredPoolCooldowns(db);
407
- if (recovered > 0 || poolRecovered > 0) await snapshotService.invalidate();
408
- },
409
- });
410
- const payloadCapture = new TelemetryPayloadCapture(db);
411
- const telemetryStore = new DrizzleTelemetryStore(db);
412
- scheduledTasks.register({
413
- name: "telemetry-payload-cleanup",
414
- intervalMs: 15 * 60_000,
415
- // Deletes payload frames for every tenant: two passes over the same
416
- // batches is duplicated work, not speedup.
417
- shared: true,
418
- run: () => payloadCapture.cleanupExpired(),
419
- });
420
- scheduledTasks.register({
421
- name: "console-session-sweep",
422
- // Sessions live 48 h, so an hourly sweep deleted nothing 47 times out of
423
- // 48 — each pass a full scan of the session table for rows that cannot yet
424
- // be expired. Half the session lifetime is the point where a pass can
425
- // actually find work, and still leaves a full grace period after it.
426
- intervalMs: 12 * 60 * 60_000,
427
- shared: true,
428
- run: () => deleteExpiredSessions(db),
429
- });
430
- scheduledTasks.register({
431
- name: "telemetry-retention",
432
- intervalMs: 6 * 60 * 60_000,
433
- // Retention deletes rows and files for the whole deployment; a second
434
- // concurrent pass would churn the same batches.
435
- shared: true,
436
- run: () =>
437
- telemetryStore.pruneTelemetry(
438
- new Date(Date.now() - resolveTelemetryRetentionDays() * 24 * 60 * 60_000),
439
- ),
440
- });
441
- const telemetryBuffer = new TelemetryBatchBuffer(db);
442
- const poolSelector = new NetworkPoolSelector(redis);
443
- const poolAgentResolver = new PoolAgentResolver(
444
- new DrizzleNetworkPoolLoader(db),
445
- { ssrfPolicy, db },
446
- );
447
- const networkBindingFactory = new ValidatedNetworkBindingFactory(
448
- ssrfPolicy,
449
- undefined,
450
- poolAgentResolver,
451
- );
452
- // Runtime gauges (memory + bounded-collection sizes) sampled on the shared
453
- // maintenance cadence. The sampler reads live sizes through closures so the
454
- // observability layer never holds direct references to routing/pool state.
455
- const runtimeMetricsSampler = new RuntimeMetricsSampler({
456
- routingRoundRobinEntries: () => routingEngine.roundRobinEntries(),
457
- ipAbuseKeys: () => (ipStore instanceof InMemoryIpAbuseStore ? ipStore.keyCount() : 0),
458
- quotaCacheEntries: () => quotaCacheSize(),
459
- modelCatalogEntries: () => modelCatalogCacheSize(),
460
- // Late-bound via bindInFlight once the request state store exists.
461
- inFlight: () => 0,
462
- // The buffer is built below; the closure keeps the sampler from holding a
463
- // reference during construction.
464
- telemetryBacklog: () => telemetryBuffer?.snapshot(),
465
- });
466
- // One sample NOW, not on the first tick. The headroom guard reads
467
- // `memorySnapshot()` on every gateway request and treats `undefined` as
468
- // "unknown" — so without this the guard would spend its first interval
469
- // (seconds, at the configured cadence) unable to shed at all, which is
470
- // exactly the window a cold start is most likely to be short of memory.
471
- runtimeMetricsSampler.sample();
472
- scheduledTasks.register({
473
- name: "runtime-metrics",
474
- intervalMs: readInt(
475
- "CARTETHYIA_RUNTIME_METRICS_INTERVAL_MS",
476
- CONFIG_SPEC.CARTETHYIA_RUNTIME_METRICS_INTERVAL_MS,
477
- ),
478
- run: () => runtimeMetricsSampler.sample(),
479
- });
480
- scheduledTasks.register({
481
- name: "pool-agent-sweep",
482
- // `resolveAgent` already self-sweeps every 30 s, so a 1 min timer adds a
483
- // second pass that almost always finds nothing to release. 5 min is well
484
- // inside the idle timeout this exists to enforce, and outside the path
485
- // that already runs.
486
- intervalMs: 5 * 60_000,
487
- run: () => poolAgentResolver.sweepIdleAgents(),
488
- });
489
- const oauthRefreshService = new OAuthRefreshService(db);
490
- // Converge accounts parked on a dead refresh grant: an account whose stored
491
- // access token is still usable becomes a static token (and returns to
492
- // rotation) instead of staying disabled for re-auth.
493
- await measureStartupPhase("static-token-reconciliation", () =>
494
- reconcileStaticTokenAccounts(db),
495
- );
496
- // Fills in the identity a batch import deliberately skipped, so a paste of
497
- // many credentials is one instant write and the email/label arrive shortly
498
- // after rather than blocking the import. Purely CPU on an already-stored
499
- // credential — no upstream call — so it runs often and cheaply.
500
- scheduledTasks.register({
501
- name: "account-enrichment-sweep",
502
- // Converges via `identity_checked_at`: once every stored credential has
503
- // been parsed, the listing query returns nothing — a 30 s timer would run
504
- // that empty query forever, two million times a year. 10 min is still
505
- // instant for the case that matters (a batch import, where the label and
506
- // email show up on the next tick) and costs nothing when idle.
507
- intervalMs: 10 * 60_000,
508
- run: () => accountIdentitySweep({ db }),
509
- });
510
- scheduledTasks.register({
511
- name: "oauth-refresh-sweep",
512
- intervalMs: 60_000,
513
- run: () =>
514
- oauthRefreshSweep({
515
- loadDueAccounts: () => loadDueOAuthAccounts(db),
516
- refreshService: oauthRefreshService,
517
- resolveRefresher: (providerId) => registry.resolveRefresher(providerId),
518
- // Sequential with a pause between accounts: the OAuth token endpoints
519
- // rate-limit a burst of refreshes, and a pass over a handful of
520
- // accounts must not look like one. Per-account outcomes are already
521
- // pushed to the Console Log ring by `OAuthRefreshService`; this only
522
- // covers an error that escaped before reaching it.
523
- interItemDelayMs: OAUTH_REFRESH_INTER_ITEM_DELAY_MS,
524
- onAccountError: (accountId, providerId, error) => {
525
- log.error(
526
- `[oauth-refresh] account=${accountId} provider=${providerId} failed:`,
527
- error as Error,
528
- );
529
- pushStructuredConsoleLog("error", "OAuth refresh sweep: account failed", {
530
- event: "token_refresh",
531
- accountId,
532
- providerId,
533
- errorCode: "refresh_sweep_failed",
534
- });
535
- },
536
- }),
537
- });
538
-
539
- // Client versions are monitor-only metadata; let the listener settle before
540
- // starting their external fetches. The scheduled task keeps the cache warm.
541
- scheduledTasks.register({
542
- name: "client-version-monitor",
543
- intervalMs: CLIENT_VERSION_MONITOR_INTERVAL_MS,
544
- initialDelayMs: CLIENT_VERSION_INITIAL_DELAY_MS,
545
- run: refreshProviderClientVersions,
546
- });
547
-
548
- const quotaResolveCredential = createAccountSecretResolver({
549
- db,
550
- resolveRefresher: (providerId) => registry.resolveRefresher(providerId),
551
- refreshService: oauthRefreshService,
552
- });
553
- // Keeps every account's cached quota warm so opening the Quota page is a
554
- // cache read. Without this the only refreshes are user-triggered, so the
555
- // first open after an expiry always blocks on the provider.
556
- //
557
- // It also carries the daily check-in ride-along: each account refreshed
558
- // here gets its once-per-day WorkBuddy/CodeBuddy credit grant claimed in
559
- // the same pass (one attempt per account per day, guarded by a day
560
- // marker), so no second timer duplicates the credential resolution.
561
- //
562
- // Registered in **every** mode, not only when Redis is present: gating it on
563
- // Redis would cost Lite proactive quota warming and the check-in ride-along
564
- // above that claims the once-per-day WorkBuddy/CodeBuddy credit grant. The
565
- // whole sweep chain accepts `RedisClient | undefined` and falls back to the
566
- // in-process TTL cache and an in-process day marker, so Redis is an
567
- // optimization here rather than a precondition — which is exactly what
568
- // Lite is for.
569
- scheduledTasks.register({
570
- name: "quota-refresh-sweep",
571
- intervalMs: 60_000,
572
- // Staggered off the oauth/lease/health ticks so the three sweeps that
573
- // strike providerAccounts do not land together every minute.
574
- initialDelayMs: 20_000,
575
- run: () =>
576
- quotaRefreshSweep({
577
- db,
578
- redis,
579
- providerRegistry: registry,
580
- resolveCredential: quotaResolveCredential,
581
- snapshotInvalidator: snapshotService,
582
- // Without this the sweep hands each collector the raw stored secret.
583
- // For `cline` that means an `sk_...` key reaching the OAuth branch,
584
- // which prepends `workos:` and is refused with "please make sure
585
- // you're using the latest version of Cline and re-authenticate" — so
586
- // every sweep cools a working account with `quota_fetch_failed` while
587
- // the same account refreshes fine from the console, which binds the
588
- // same marker through `createQuotaRefreshDeps`.
589
- markApiKeyCredential: markProviderApiKeyCredential,
590
- // Below the 60 s interval: a budget longer than the tick guarantees
591
- // skip/burst under load instead of steady progress.
592
- passBudgetMs: 45_000,
593
- // The check-in ride-along rotates egress per account: each account
594
- // gets the next active pool in its tenant's rotation so check-ins
595
- // spread across IPs instead of sharing one direct egress. No pool
596
- // (or an unreadable pool table) falls back to direct egress, and a
597
- // tenant never borrows another tenant's pool.
598
- checkinFetcherFor: dailyCheckinEgressForPass({ db, networkBindingFactory }),
599
- // Per-account lines and the pass summary are emitted by the sweep
600
- // itself at `info` level, so they survive the production LOG_LEVEL.
601
- // `onTick` is left for tests.
602
- }),
603
- });
604
- // The buddy growth/credit tasks: one per upstream capability, each
605
- // independently switchable with `CARTETHYIA_DISABLED_TASKS`. Every one of
606
- // them is a credit gain the account is entitled to, and none of them can mark
607
- // an account unhealthy — a growth endpoint that 404s is a display miss, not a
608
- // dispatch failure.
609
- //
610
- // Daily, not hourly: each claim is once per account per day and is
611
- // ledger-guarded, so at an hourly cadence 23 of every 24 passes are a full
612
- // scan of active accounts plus a ledger read per account that resolves to
613
- // nothing. Once a day is the shortest interval where a pass can still find
614
- // work, which is the only reason to run at all.
615
- const buddyTaskDeps = {
616
- db,
617
- resolveCredential: quotaResolveCredential,
618
- fetcher: fetch,
619
- // Spread across accounts so a pass does not look like a burst to the
620
- // upstream's risk gate.
621
- interAccountDelayMs: 800,
622
- };
623
- scheduledTasks.register({
624
- name: "buddy-streak",
625
- intervalMs: 24 * 60 * 60_000,
626
- initialDelayMs: 5 * 60_000,
627
- run: () => buddyStreakTask(buddyTaskDeps),
628
- });
629
- scheduledTasks.register({
630
- name: "buddy-redeem",
631
- intervalMs: 24 * 60 * 60_000,
632
- initialDelayMs: 8 * 60_000,
633
- run: () => buddyRedeemTask(buddyTaskDeps),
634
- });
635
- scheduledTasks.register({
636
- name: "buddy-lottery",
637
- intervalMs: 24 * 60 * 60_000,
638
- initialDelayMs: 11 * 60_000,
639
- run: () => buddyLotteryTask(buddyTaskDeps),
640
- });
641
- scheduledTasks.register({
642
- name: "buddy-travel",
643
- intervalMs: 24 * 60 * 60_000,
644
- initialDelayMs: 14 * 60_000,
645
- run: () => buddyTravelTask(buddyTaskDeps),
646
- });
647
- scheduledTasks.register({
648
- name: "buddy-adopt",
649
- intervalMs: 24 * 60 * 60_000,
650
- initialDelayMs: 17 * 60_000,
651
- run: () => buddyAdoptTask(buddyTaskDeps),
652
- });
653
- scheduledTasks.register({
654
- name: "buddy-trial",
655
- intervalMs: 24 * 60 * 60_000,
656
- initialDelayMs: 20 * 60_000,
657
- run: () => buddyTrialTask(buddyTaskDeps),
658
- });
659
- // Growth-activity report: the `/v2/report` batch that lights the login streak
660
- // and scores the daily growth event. Once a day with its own ledger — it used
661
- // to ride the quota sweep with no marker of its own, so its eight POSTs ran
662
- // every minute.
663
- scheduledTasks.register({
664
- name: "buddy-activity-report",
665
- intervalMs: 24 * 60 * 60_000,
666
- initialDelayMs: 15 * 60 * 60_000,
667
- run: () => buddyActivityReportTask(buddyTaskDeps),
668
- });
669
- // Real credit deductions, stored so the console renders a figure the upstream
670
- // actually reported. Six-hourly: the upstream's own window is 30 days, so a
671
- // day's number does not change intraday.
672
- scheduledTasks.register({
673
- name: "buddy-usage-sync",
674
- intervalMs: 6 * 60 * 60_000,
675
- initialDelayMs: 23 * 60_000,
676
- run: () => syncBuddyUsage(buddyTaskDeps),
677
- });
678
- // The scheduled tasks are registered here but started by the caller once the
679
- // listener is actually serving (`main.ts`). Starting them inside this builder
680
- // would let the first tick — the lease sweep, the health sweep — run against
681
- // a process that has not begun accepting traffic yet.
682
- const deps: ProductionDeps = {
683
- db,
684
- redis,
685
- snapshotService,
686
- readRoutingAccountInflight,
687
- resolveProviderAdapter: (providerId) => registry.resolve(providerId),
688
- bundledModelCatalog: bundledCatalog,
689
- byokUpstreamHosts,
690
- proxyPreparer: new ProxyRequestPreparer({
691
- snapshotService,
692
- routingEngine,
693
- admissionService,
694
- }),
695
- networkBindingFactory,
696
- ipAbuseProtection,
697
- modelStrikes,
698
- readiness,
699
- scheduledTasks,
700
- poolAgentResolver,
701
- telemetryBuffer,
702
- usageFlush,
703
- healthEventFlush,
704
- poolSelector,
705
- admissionService,
706
- trustedProxyBoundary: resolveTrustedProxyBoundary(),
707
- providerRegistry: registry,
708
- resolveOAuthRefresher: (providerId) => registry.resolveRefresher(providerId),
709
- oauthRefreshService,
710
- runtimeMetricsSampler,
711
- };
712
- const startupMemoryAfter = process.memoryUsage();
713
- log.info(
714
- `[startup] phase=dependencies-ready elapsed_ms=${Math.round(performance.now() - startupStartedAt)} ` +
715
- `rss_mb=${toMiB(startupMemoryAfter.rss)} ` +
716
- `rss_delta_mb=${toMiB(startupMemoryAfter.rss - startupMemoryBefore.rss)} ` +
717
- `heap_used_mb=${toMiB(startupMemoryAfter.heapUsed)} ` +
718
- `heap_delta_mb=${toMiB(startupMemoryAfter.heapUsed - startupMemoryBefore.heapUsed)}`,
719
- );
720
- return deps;
721
- }
722
-
723
- async function measureStartupPhase<T>(name: string, operation: () => Promise<T>): Promise<T> {
724
- const startedAt = performance.now();
725
- const before = process.memoryUsage();
726
- log.info(
727
- `[startup] phase=${name} status=started rss_mb=${toMiB(before.rss)} heap_used_mb=${toMiB(before.heapUsed)}`,
728
- );
729
- try {
730
- const result = await operation();
731
- const after = process.memoryUsage();
732
- log.info(
733
- `[startup] phase=${name} status=completed elapsed_ms=${Math.round(performance.now() - startedAt)} ` +
734
- `rss_mb=${toMiB(after.rss)} rss_delta_mb=${toMiB(after.rss - before.rss)} ` +
735
- `heap_used_mb=${toMiB(after.heapUsed)} heap_delta_mb=${toMiB(after.heapUsed - before.heapUsed)} ` +
736
- `external_mb=${toMiB(after.external)}`,
737
- );
738
- return result;
739
- } catch (error) {
740
- log.error(
741
- `[startup] phase=${name} status=failed elapsed_ms=${Math.round(performance.now() - startedAt)}`,
742
- error instanceof Error ? error : new Error(String(error)),
743
- );
744
- throw error;
745
- }
746
- }
747
-
748
- function toMiB(bytes: number): string {
749
- return (bytes / 1024 / 1024).toFixed(1);
750
- }
1
+
2
+ import { assertPoolFitsServerCapacity, bootDatabase, ensureMigrated } from "../persistence/boot";
3
+ import { poolMaxFromEnv } from "../persistence/db-pg";
4
+ import type { CartethyiaDatabase } from "../persistence/db-handle";
5
+ import { resolveRedisBackend, resolveRedisClient } from "../persistence/redis";
6
+ import { resolveProcessTopology, type ProcessTopology } from "../config/runtime";
7
+ import { createRedisMaintenanceLeaseStore } from "../workers/maintenance-lease";
8
+ import { resolveDbMode } from "../persistence/db-mode";
9
+ import type { RedisClient } from "../persistence/redis";
10
+ import {
11
+ bundledModelCatalog,
12
+ liveProviderUpstreamHosts,
13
+ markCatalogSeeded,
14
+ refreshActiveProviderCatalogs,
15
+ registerByokProviders,
16
+ retireUnbundledProviders,
17
+ seedBundledProviders,
18
+ } from "../providers/operations/provider-catalog-service";
19
+ import type { BundledProviderCatalog } from "../providers/operations/provider-catalog-service";
20
+ import { createDefaultProviderRegistry } from "../providers/default-registry";
21
+ import { OAuthRefreshService, loadDueOAuthAccounts, reconcileStaticTokenAccounts } from "../providers/authentication/oauth-refresh-service";
22
+ import type { OAuthTokenRefresher } from "../providers/authentication/oauth-refresh-service";
23
+ import { oauthRefreshSweep } from "../workers/oauth-refresh-sweep";
24
+ import { accountIdentitySweep } from "../workers/account-identity-sweep";
25
+ import { pushStructuredConsoleLog } from "../observability/log-ring";
26
+ import { seedBundledModels } from "../providers/operations/provider-catalog-seeder";
27
+ import { createDatabaseSnapshotBuilder } from "../transport/routing/route-catalog";
28
+ import { DrizzleProviderCatalogStore } from "../console/providers/catalog/store";
29
+ import { InMemoryRouteSnapshotService } from "../transport/routing/route-model";
30
+ import { RoutingEngine } from "../transport/routing/router";
31
+ import { RedisAdmissionController } from "../transport/routing/admission";
32
+ import { ApiKeyAdmissionService } from "../security/admission/service";
33
+ import { InMemoryAdmissionCounterStore } from "../security/admission/in-memory-store";
34
+ import { RedisAdmissionCounterStore } from "../security/admission/redis-store";
35
+ import { sweepLeases } from "../security/admission/lease-sweep";
36
+ import { DrizzleApiKeyStore } from "../persistence/stores/api-key-store";
37
+ import { UsageFlushBuffer } from "../persistence/usage-flush";
38
+ import { setPendingUsageSource } from "../security/api-key-auth";
39
+ import { HealthEventFlushBuffer, setHealthEventBuffer } from "../persistence/health-event-flush";
40
+ import { subscribePeerSettingsRevisions } from "../persistence/settings-revision";
41
+ import { deleteExpiredSessions } from "../console/auth/session-service";
42
+ import { InMemoryIpAbuseStore, IpAbuseProtectionService, RedisIpAbuseStore } from "../security/abuse";
43
+ import { checkReadiness } from "../persistence/readiness";
44
+ import { ProxyRequestPreparer } from "../transport/request/preparer";
45
+ import { DrizzleNetworkPoolLoader } from "../network/pool/loader";
46
+ import {
47
+ PoolAgentResolver,
48
+ ValidatedNetworkBindingFactory,
49
+ } from "../network/pool/resolver";
50
+ import { NetworkPoolSelector } from "../network/pool/selector";
51
+ import { restorePoolProbeVerdicts, restoreProviderCooldownMarkers } from "../network/pool-cooldown-store";
52
+ import { ScheduledTaskRegistry } from "../workers/scheduler";
53
+ import { quotaRefreshSweep } from "../workers/quota-refresh-sweep";
54
+ import { markProviderApiKeyCredential } from "../console/quota/account-quota-shared";
55
+ import { dailyCheckinEgressForPass } from "../workers/daily-checkin";
56
+ import {
57
+ buddyAdoptTask,
58
+ buddyActivityReportTask,
59
+ buddyStreakTask,
60
+ syncBuddyUsage,
61
+ } from "../workers/buddy-growth-tasks";
62
+ import { createAccountSecretResolver } from "../providers/operations/provider-credential-service";
63
+ import { quotaCacheSize } from "../providers/quota/cache";
64
+ import { modelCatalogCacheSize } from "../providers/operations/model-catalog-cache";
65
+ import { preferencesReaderFor } from "../persistence/tenant-preferences";
66
+ import { sweepExpiredCooldowns } from "../providers/operations/account-health-service";
67
+ import { DrizzleTelemetryStore } from "../persistence/stores/telemetry-store";
68
+ import { TelemetryPayloadCapture } from "../observability/payload-capture";
69
+ import { sweepExpiredPoolCooldowns } from "../network/pool-health-machine";
70
+ import { TelemetryBatchBuffer } from "../observability/telemetry-buffer";
71
+ import { RuntimeMetricsSampler } from "../observability/runtime-metrics";
72
+ import {
73
+ resolveIpRateLimit,
74
+ } from "../config/security";
75
+ import { resolveSsrfPolicy, resolveTrustedProxyBoundary } from "../config/network";
76
+ import type { TrustedProxyBoundary } from "../config/network";
77
+ import { resolveTelemetryRetentionDays } from "../config/telemetry";
78
+ import { resolveConcurrencyTolerance } from "../config/resources";
79
+ import { CONFIG_SPEC, readInt, readList } from "../config/spec";
80
+ import type { ProviderAdapter } from "../providers/provider-contracts";
81
+ import type { ProviderRegistry } from "../providers/provider-registry";
82
+ import type { ByokUpstreamHost } from "../providers/operations/provider-catalog-service";
83
+ import type { ReadinessCheckResult } from "../persistence/readiness";
84
+ import { log } from "../observability/logger";
85
+ import { refreshProviderClientVersions } from "../providers/operations/client-versions";
86
+
87
+
88
+ export interface ProductionDeps {
89
+ db: CartethyiaDatabase;
90
+ redis: RedisClient | undefined;
91
+ snapshotService: InMemoryRouteSnapshotService;
92
+ /** Live routing admission snapshot scoped to one provider/tenant for console reads. */
93
+ readRoutingAccountInflight: (
94
+ providerId: string,
95
+ tenantId: string | null,
96
+ ) => Promise<readonly { accountId: string; inflight: number }[]>;
97
+ /** On-demand adapter resolution keeps heavy providers out of the boot path. */
98
+ resolveProviderAdapter: (providerId: string) => Promise<ProviderAdapter | undefined>;
99
+ bundledModelCatalog: BundledProviderCatalog;
100
+ /** Live lookup of a provider's SSRF-validated upstream host. */
101
+ byokUpstreamHosts: { readonly get: (providerId: string) => ByokUpstreamHost | undefined };
102
+ proxyPreparer: ProxyRequestPreparer;
103
+ networkBindingFactory: ValidatedNetworkBindingFactory;
104
+ ipAbuseProtection: IpAbuseProtectionService;
105
+ readiness: () => Promise<ReadinessCheckResult>;
106
+ scheduledTasks: ScheduledTaskRegistry;
107
+ poolAgentResolver: PoolAgentResolver;
108
+ poolSelector: NetworkPoolSelector;
109
+ telemetryBuffer: TelemetryBatchBuffer;
110
+ usageFlush: UsageFlushBuffer;
111
+ healthEventFlush: HealthEventFlushBuffer;
112
+ trustedProxyBoundary: TrustedProxyBoundary;
113
+ providerRegistry: ProviderRegistry;
114
+ resolveOAuthRefresher: (providerId: string) => Promise<OAuthTokenRefresher | undefined>;
115
+ oauthRefreshService: OAuthRefreshService;
116
+ admissionService: ApiKeyAdmissionService;
117
+ /** Graduated strikes for repeated invalid-model requests. */
118
+ /** Memory sampler; in-flight source is bound once the request store exists. */
119
+ runtimeMetricsSampler: RuntimeMetricsSampler;
120
+ }
121
+
122
+ /**
123
+ * Pause between accounts in the OAuth refresh sweep. The token endpoints
124
+ * rate-limit a burst of refreshes even at low concurrency.
125
+ */
126
+ const OAUTH_REFRESH_INTER_ITEM_DELAY_MS = 1_500;
127
+
128
+ /**
129
+ * Client identities are refreshed out of band so provider dispatch never waits
130
+ * on npm/provider version endpoints. Resolver TTLs deduplicate the sources.
131
+ */
132
+ // Matched to the resolver's own 30 min cache TTL: a shorter interval makes
133
+ // every second pass a pure cache read that cannot discover anything new.
134
+ const CLIENT_VERSION_MONITOR_INTERVAL_MS = 30 * 60_000;
135
+ const CLIENT_VERSION_INITIAL_DELAY_MS = 10_000;
136
+
137
+ /** Bound on the boot-time Redis probe: a start must fail, not hang. */
138
+ const REDIS_PROBE_TIMEOUT_MS = 2_000;
139
+
140
+ async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
141
+ const { promise: timeout, reject } = Promise.withResolvers<never>();
142
+ const timer = setTimeout(() => reject(new Error("timeout")), ms);
143
+ try {
144
+ return await Promise.race([promise, timeout]);
145
+ } finally {
146
+ clearTimeout(timer);
147
+ }
148
+ }
149
+
150
+ /** Bounded Redis reachability probe: fails rather than hangs. */
151
+ async function redisIsReachable(): Promise<boolean> {
152
+ const client = resolveRedisClient();
153
+ if (!client) return false;
154
+ try {
155
+ const result = await withTimeout(client.ping(), REDIS_PROBE_TIMEOUT_MS);
156
+ return result === "PONG";
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Refuses to start a multi-process deployment whose shared state is not
164
+ * actually shared.
165
+ *
166
+ * Every process shares one port via `SO_REUSEPORT`, so the kernel balances
167
+ * across them — and each process keeps its own in-memory admission counters,
168
+ * quota cache, and cooldown map. Those are only correct when they live in
169
+ * Redis. Starting anyway does not fail loudly; it enforces every per-key limit
170
+ * N times over, which then reads as "the limit did not work".
171
+ *
172
+ * Redis is checked by PING with a hard bound, not merely for being configured:
173
+ * a configured-but-unreachable Redis is the failure mode that matters, and an
174
+ * unbounded connect at boot would hang the start instead of failing it.
175
+ */
176
+ async function assertMultiProcessPreconditions(
177
+ topology: ProcessTopology,
178
+ redisReachable: () => Promise<boolean>,
179
+ ): Promise<void> {
180
+ if (!topology.multiProcess) return;
181
+ if (process.platform !== "linux") {
182
+ throw Object.assign(
183
+ new Error(
184
+ `CARTETHYIA_PROCESS_COUNT=${topology.count} requires Linux (SO_REUSEPORT); ` +
185
+ `this process is on ${process.platform}`,
186
+ ),
187
+ { code: "multi_process_unsupported_platform" },
188
+ );
189
+ }
190
+ if (resolveDbMode() !== "full") {
191
+ throw Object.assign(
192
+ new Error(
193
+ `CARTETHYIA_PROCESS_COUNT=${topology.count} requires CARTETHYIA_DB_MODE=full (PostgreSQL); ` +
194
+ "two processes on one SQLite file corrupt it — there is no cross-process lock in the driver",
195
+ ),
196
+ { code: "multi_process_requires_postgres" },
197
+ );
198
+ }
199
+ const reachable = await redisReachable();
200
+ if (!reachable) {
201
+ throw Object.assign(
202
+ new Error(
203
+ `CARTETHYIA_PROCESS_COUNT=${topology.count} requires a REACHABLE Redis: admission counters, ` +
204
+ "quotas, and cooldowns are per-process without one, so every per-key limit would be " +
205
+ `enforced ${topology.count} times over`,
206
+ ),
207
+ { code: "multi_process_requires_redis" },
208
+ );
209
+ }
210
+ }
211
+
212
+ export async function buildProductionDeps(): Promise<ProductionDeps> {
213
+ const startupStartedAt = performance.now();
214
+ const startupMemoryBefore = process.memoryUsage();
215
+ // Resolved first and validated before any connection is opened: a
216
+ // half-configured multi-process deploy that starts anyway looks healthy
217
+ // until a per-key limit is enforced N times over.
218
+ const topology = resolveProcessTopology();
219
+ await assertMultiProcessPreconditions(topology, redisIsReachable);
220
+ const handle = await measureStartupPhase("database-connect", bootDatabase);
221
+ const db = handle.db;
222
+ // One rule, no mode flag: REDIS_URL set → shared client, unset → memory.
223
+ const redis = resolveRedisClient();
224
+ const ssrfPolicy = resolveSsrfPolicy();
225
+ await measureStartupPhase("database-migrations", async () => {
226
+ await ensureMigrated();
227
+ // Pool sizing is an external-server concern; the embedded backend has no
228
+ // connection budget to fit into.
229
+ if (handle.kind === "pg") await assertPoolFitsServerCapacity(poolMaxFromEnv(), topology.count);
230
+ });
231
+ await measureStartupPhase("provider-seed", () => seedBundledProviders(db));
232
+ // Boot-only: retire global rows for providers the bundle has dropped, so a
233
+ // retired provider cannot linger as a card the console can no longer delete.
234
+ // Kept off the test harness path, which shares one database across suites and
235
+ // installs its own global fixtures.
236
+ await measureStartupPhase("retired-provider-cleanup", () => retireUnbundledProviders(db));
237
+ const registry = createDefaultProviderRegistry();
238
+ // Live view, not a snapshot: custom providers registered after boot (or
239
+ // edited from the console) must resolve their SSRF binding immediately.
240
+ const byokUpstreamHosts = liveProviderUpstreamHosts(registry);
241
+ await measureStartupPhase("byok-registration", () =>
242
+ registerByokProviders(registry, db, ssrfPolicy),
243
+ );
244
+ const bundledCatalog = await measureStartupPhase("bundled-model-catalog", () =>
245
+ bundledModelCatalog(registry),
246
+ );
247
+ await measureStartupPhase("bundled-model-seed", () =>
248
+ seedBundledModels(db, bundledCatalog.modelsByProvider),
249
+ );
250
+ // The boot seed above is unconditional, so record it: the snapshot builder's
251
+ // first rebuild would otherwise re-seed an identical catalog.
252
+ markCatalogSeeded();
253
+ const snapshotService = new InMemoryRouteSnapshotService(
254
+ createDatabaseSnapshotBuilder(db, () => refreshActiveProviderCatalogs(db, registry)),
255
+ );
256
+ const routingEngine = new RoutingEngine(
257
+ redis ? new RedisAdmissionController(redis) : undefined,
258
+ redis,
259
+ );
260
+ // Peer processes' settings mutations arrive here. Subscribed once for the
261
+ // process: the revision counter is process-global, and the handler only
262
+ // moves it forward.
263
+ subscribePeerSettingsRevisions();
264
+ const usageFlush = new UsageFlushBuffer(db);
265
+ // Auth reads lifetime usage to seed the admission counter. The persisted
266
+ // value lags by up to one flush interval, so hand it the in-flight deltas
267
+ // too — otherwise the seed is systematically under what has actually been
268
+ // spent, worst exactly when the key is busiest.
269
+ setPendingUsageSource((apiKeyId) => usageFlush.pendingFor(apiKeyId));
270
+ // Health audit rows are append-only and read by nobody in dispatch, so they
271
+ // are buffered out of the request. The status write they accompany stays
272
+ // synchronous — routing reads it.
273
+ const healthEventFlush = new HealthEventFlushBuffer(db);
274
+ setHealthEventBuffer(healthEventFlush);
275
+ const admissionStore = redis
276
+ ? new RedisAdmissionCounterStore(redis)
277
+ : new InMemoryAdmissionCounterStore();
278
+ const admissionService = new ApiKeyAdmissionService(
279
+ admissionStore,
280
+ undefined,
281
+ // The per-tenant concurrency cap is a `console_settings` preference, read
282
+ // on every admitted request. Reading it directly cost one Postgres round
283
+ // trip per request (multiplied by each failover candidate); the shared
284
+ // revision-keyed reader answers from memory and converges the moment an
285
+ // operator saves, because `DrizzleRuntimeSettingsStore.update` bumps the
286
+ // revision every cached key embeds.
287
+ (tenantId) =>
288
+ preferencesReaderFor(db)
289
+ .readPreferences(tenantId)
290
+ .then((prefs) => prefs?.tenantConcurrencyLimit ?? null),
291
+ ({ apiKeyId, delta }) => {
292
+ // Coalesced: one UPDATE per key per flush instead of one per request.
293
+ // The admission counter is the live total; this only persists it.
294
+ usageFlush.enqueue(apiKeyId, delta);
295
+ return Promise.resolve();
296
+ },
297
+ // Fresh lifetime reader — invoked by the store only when it is about to
298
+ // seed a missing `admission:lifetime:<id>` counter, so the ≤3s-stale auth
299
+ // snapshot value cannot freeze a low baseline in place. Family total: the
300
+ // row plus every child (share recipients admit under the parent id).
301
+ async (apiKeyId) => {
302
+ const store = new DrizzleApiKeyStore(db);
303
+ const row = await store.findActiveById(apiKeyId);
304
+ if (!row) return undefined;
305
+ const children = await store.sumChildrenConsumed(apiKeyId);
306
+ return (row.lifetimeTokensConsumed ?? 0) + children;
307
+ },
308
+ // Slack above every key's concurrency limit. A tenant preference an
309
+ // operator sets in the runtime settings modal, falling back to the
310
+ // deployment default so an unset row does not silently lose the allowance.
311
+ (tenantId) =>
312
+ preferencesReaderFor(db)
313
+ .readPreferences(tenantId)
314
+ .then((prefs) => prefs?.concurrencyTolerance ?? resolveConcurrencyTolerance()),
315
+ );
316
+ const ipStore = redis
317
+ ? new RedisIpAbuseStore(redis)
318
+ : new InMemoryIpAbuseStore();
319
+ const ipAbuseProtection = new IpAbuseProtectionService(ipStore, undefined, {
320
+ maxRequestsPerWindow: resolveIpRateLimit(),
321
+ });
322
+
323
+ const readiness = () => checkReadiness(db, redis, resolveRedisBackend(redis));
324
+ // One list covers every periodic task: a small deployment can cut the
325
+ // heaviest sweeps (quota refresh, OAuth refresh, client-version polling)
326
+ // without the codebase growing a flag per task.
327
+ // Leases coordinate the SHARED sweeps across processes. Absent Redis there is
328
+ // nothing to coordinate with, and the registry's local one-at-a-time rule is
329
+ // the correct (and only) guard.
330
+ const scheduledTasks = new ScheduledTaskRegistry(
331
+ readList("CARTETHYIA_DISABLED_TASKS", CONFIG_SPEC.CARTETHYIA_DISABLED_TASKS) ?? [],
332
+ {
333
+ ...(redis ? { lease: createRedisMaintenanceLeaseStore(redis) } : {}),
334
+ },
335
+ );
336
+ if (redis) {
337
+ scheduledTasks.register({
338
+ name: "lease-sweep",
339
+ intervalMs: 30_000,
340
+ run: () => sweepLeases(redis),
341
+ });
342
+ }
343
+ scheduledTasks.register({
344
+ name: "account-health-sweep",
345
+ intervalMs: 30_000,
346
+ // Offsets the pass from lease-sweep and runtime-metrics, which share the
347
+ // same cadence: under the registry's single-flight gate, aligned ticks
348
+ // make the 30s tasks skip each other when one runs long.
349
+ initialDelayMs: 5_000,
350
+ // Recovers cooldowns deployment-wide and invalidates the shared snapshot.
351
+ shared: true,
352
+ run: async () => {
353
+ const recovered = await sweepExpiredCooldowns(db);
354
+ const poolRecovered = await sweepExpiredPoolCooldowns(db);
355
+ if (recovered > 0 || poolRecovered > 0) await snapshotService.invalidate();
356
+ },
357
+ });
358
+ const payloadCapture = new TelemetryPayloadCapture(db);
359
+ const telemetryStore = new DrizzleTelemetryStore(db);
360
+ scheduledTasks.register({
361
+ name: "telemetry-payload-cleanup",
362
+ intervalMs: 15 * 60_000,
363
+ // Deletes payload frames for every tenant: two passes over the same
364
+ // batches is duplicated work, not speedup.
365
+ shared: true,
366
+ run: () => payloadCapture.cleanupExpired(),
367
+ });
368
+ scheduledTasks.register({
369
+ name: "console-session-sweep",
370
+ // Sessions live 48 h, so an hourly sweep deleted nothing 47 times out of
371
+ // 48 — each pass a full scan of the session table for rows that cannot yet
372
+ // be expired. Half the session lifetime is the point where a pass can
373
+ // actually find work, and still leaves a full grace period after it.
374
+ intervalMs: 12 * 60 * 60_000,
375
+ shared: true,
376
+ run: () => deleteExpiredSessions(db),
377
+ });
378
+ scheduledTasks.register({
379
+ name: "telemetry-retention",
380
+ intervalMs: 6 * 60 * 60_000,
381
+ // Retention deletes rows and files for the whole deployment; a second
382
+ // concurrent pass would churn the same batches.
383
+ shared: true,
384
+ run: () =>
385
+ telemetryStore.pruneTelemetry(
386
+ new Date(Date.now() - resolveTelemetryRetentionDays() * 24 * 60 * 60_000),
387
+ ),
388
+ });
389
+ const telemetryBuffer = new TelemetryBatchBuffer(db);
390
+ const poolSelector = new NetworkPoolSelector(redis);
391
+ // Replay the provider cooldown markers the previous process recorded
392
+ // (`network_pools.provider_cooldowns`). Without this a restart made dispatch
393
+ // forget every egress the upstream was still refusing: the flags are
394
+ // process-local otherwise, so the pool re-entered rotation and took 429s the
395
+ // first request after boot re-discovered. Expired entries are dropped by the
396
+ // restore itself. Best-effort: a failed read leaves selection matching what
397
+ // a fresh deployment would do.
398
+ try {
399
+ const restored = await restoreProviderCooldownMarkers(poolSelector, db);
400
+ const replayed = await restorePoolProbeVerdicts(poolSelector, db);
401
+ if (restored > 0 || replayed > 0) {
402
+ log.info("[pool-selector] restored provider cooldown state", { mirrored: restored, probeVerdictsApplied: replayed });
403
+ }
404
+ } catch (error) {
405
+ log.warn("[pool-selector] provider cooldown restore failed", { error: String(error) });
406
+ }
407
+ const poolAgentResolver = new PoolAgentResolver(
408
+ new DrizzleNetworkPoolLoader(db),
409
+ { ssrfPolicy, db },
410
+ );
411
+ const networkBindingFactory = new ValidatedNetworkBindingFactory(
412
+ ssrfPolicy,
413
+ undefined,
414
+ poolAgentResolver,
415
+ );
416
+ // The account-inflight reader the console queries. It lives after the deps
417
+ // it closes over (telemetry buffer, binding factory), so the closure never
418
+ // touches a TDZ binding; it also reuses one catalog store per tenant instead
419
+ // of constructing a fresh store object on every console read.
420
+ let lastInflightTenant = "";
421
+ let lastInflightStore: DrizzleProviderCatalogStore | undefined;
422
+ const readRoutingAccountInflight = async (
423
+ providerId: string,
424
+ tenantId: string | null,
425
+ ): Promise<readonly { accountId: string; inflight: number }[]> => {
426
+ if (providerId === "" || tenantId === null) return [];
427
+ if (tenantId !== lastInflightTenant || lastInflightStore === undefined) {
428
+ lastInflightStore = new DrizzleProviderCatalogStore(db, {
429
+ telemetryBuffer,
430
+ bundledModelCatalog: bundledCatalog,
431
+ providerRegistry: registry,
432
+ outboundFetchFor: async () => ({ fetch: networkBindingFactory.fetch(undefined, tenantId) }),
433
+ snapshotInvalidator: snapshotService,
434
+ });
435
+ lastInflightTenant = tenantId;
436
+ }
437
+ const accounts = await lastInflightStore.listAccounts(tenantId, providerId);
438
+ const owned = new Set(accounts.map((account) => account.id));
439
+ // Scoped read: only the provider's own candidates for this tenant are
440
+ // queried, so the console read costs one exact MGET over the accounts it
441
+ // is about to report on — not a fleet-wide `KEYS` scan whose cost is the
442
+ // size of every bucket every process ever wrote.
443
+ const routeSnapshot = await snapshotService.getSnapshot();
444
+ const ownedCandidates = routeSnapshot.candidates.filter(
445
+ (candidate) =>
446
+ candidate.provider_id === providerId &&
447
+ candidate.provider_account_id !== undefined &&
448
+ owned.has(candidate.provider_account_id),
449
+ );
450
+ const snapshot = await routingEngine.accountInflightSnapshot(ownedCandidates);
451
+ const totals = new Map<string, number>();
452
+ for (const [bucket, count] of snapshot) {
453
+ const accountId = bucket.slice(bucket.lastIndexOf(":") + 1);
454
+ if (!owned.has(accountId)) continue;
455
+ totals.set(accountId, (totals.get(accountId) ?? 0) + count);
456
+ }
457
+ return [...totals].map(([accountId, inflight]) => ({ accountId, inflight }));
458
+ };
459
+ // Runtime gauges (memory + bounded-collection sizes) sampled on the shared
460
+ // maintenance cadence. The sampler reads live sizes through closures so the
461
+ // observability layer never holds direct references to routing/pool state.
462
+ const runtimeMetricsSampler = new RuntimeMetricsSampler({
463
+ routingRoundRobinEntries: () => routingEngine.roundRobinEntries(),
464
+ ipAbuseKeys: () => (ipStore instanceof InMemoryIpAbuseStore ? ipStore.keyCount() : 0),
465
+ quotaCacheEntries: () => quotaCacheSize(),
466
+ modelCatalogEntries: () => modelCatalogCacheSize(),
467
+ // Late-bound via bindInFlight once the request state store exists.
468
+ inFlight: () => 0,
469
+ // The buffer is built below; the closure keeps the sampler from holding a
470
+ // reference during construction.
471
+ telemetryBacklog: () => telemetryBuffer?.snapshot(),
472
+ });
473
+ // One sample NOW, not on the first tick. The headroom guard reads
474
+ // `memorySnapshot()` on every gateway request and treats `undefined` as
475
+ // "unknown" — so without this the guard would spend its first interval
476
+ // (seconds, at the configured cadence) unable to shed at all, which is
477
+ // exactly the window a cold start is most likely to be short of memory.
478
+ runtimeMetricsSampler.sample();
479
+ scheduledTasks.register({
480
+ name: "runtime-metrics",
481
+ intervalMs: readInt(
482
+ "CARTETHYIA_RUNTIME_METRICS_INTERVAL_MS",
483
+ CONFIG_SPEC.CARTETHYIA_RUNTIME_METRICS_INTERVAL_MS,
484
+ ),
485
+ run: () => runtimeMetricsSampler.sample(),
486
+ });
487
+ scheduledTasks.register({
488
+ name: "pool-agent-sweep",
489
+ // `resolveAgent` already self-sweeps every 30 s, so a 1 min timer adds a
490
+ // second pass that almost always finds nothing to release. 5 min is well
491
+ // inside the idle timeout this exists to enforce, and outside the path
492
+ // that already runs.
493
+ intervalMs: 5 * 60_000,
494
+ run: () => poolAgentResolver.sweepIdleAgents(),
495
+ });
496
+ const oauthRefreshService = new OAuthRefreshService(db);
497
+ // Converge accounts parked on a dead refresh grant: an account whose stored
498
+ // access token is still usable becomes a static token (and returns to
499
+ // rotation) instead of staying disabled for re-auth.
500
+ await measureStartupPhase("static-token-reconciliation", () =>
501
+ reconcileStaticTokenAccounts(db),
502
+ );
503
+ // Fills in the identity a batch import deliberately skipped, so a paste of
504
+ // many credentials is one instant write and the email/label arrive shortly
505
+ // after rather than blocking the import. Purely CPU on an already-stored
506
+ // credential — no upstream call — so it runs often and cheaply.
507
+ scheduledTasks.register({
508
+ name: "account-enrichment-sweep",
509
+ // Converges via `identity_checked_at`: once every stored credential has
510
+ // been parsed, the listing query returns nothing — a 30 s timer would run
511
+ // that empty query forever, two million times a year. 10 min is still
512
+ // instant for the case that matters (a batch import, where the label and
513
+ // email show up on the next tick) and costs nothing when idle.
514
+ intervalMs: 10 * 60_000,
515
+ run: () => accountIdentitySweep({ db }),
516
+ });
517
+ scheduledTasks.register({
518
+ name: "oauth-refresh-sweep",
519
+ intervalMs: 60_000,
520
+ run: () =>
521
+ oauthRefreshSweep({
522
+ loadDueAccounts: () => loadDueOAuthAccounts(db),
523
+ refreshService: oauthRefreshService,
524
+ resolveRefresher: (providerId) => registry.resolveRefresher(providerId),
525
+ // Sequential with a pause between accounts: the OAuth token endpoints
526
+ // rate-limit a burst of refreshes, and a pass over a handful of
527
+ // accounts must not look like one. Per-account outcomes are already
528
+ // pushed to the Console Log ring by `OAuthRefreshService`; this only
529
+ // covers an error that escaped before reaching it.
530
+ interItemDelayMs: OAUTH_REFRESH_INTER_ITEM_DELAY_MS,
531
+ onAccountError: (accountId, providerId, error) => {
532
+ log.error(
533
+ `[oauth-refresh] account=${accountId} provider=${providerId} failed:`,
534
+ error as Error,
535
+ );
536
+ pushStructuredConsoleLog("error", "OAuth refresh sweep: account failed", {
537
+ event: "token_refresh",
538
+ accountId,
539
+ providerId,
540
+ errorCode: "refresh_sweep_failed",
541
+ });
542
+ },
543
+ }),
544
+ });
545
+
546
+ // Client versions are monitor-only metadata; let the listener settle before
547
+ // starting their external fetches. The scheduled task keeps the cache warm.
548
+ scheduledTasks.register({
549
+ name: "client-version-monitor",
550
+ intervalMs: CLIENT_VERSION_MONITOR_INTERVAL_MS,
551
+ initialDelayMs: CLIENT_VERSION_INITIAL_DELAY_MS,
552
+ run: refreshProviderClientVersions,
553
+ });
554
+
555
+ const quotaResolveCredential = createAccountSecretResolver({
556
+ db,
557
+ resolveRefresher: (providerId) => registry.resolveRefresher(providerId),
558
+ refreshService: oauthRefreshService,
559
+ });
560
+ // Keeps every account's cached quota warm so opening the Quota page is a
561
+ // cache read. Without this the only refreshes are user-triggered, so the
562
+ // first open after an expiry always blocks on the provider.
563
+ //
564
+ // It also carries the daily check-in ride-along: each account refreshed
565
+ // here gets its once-per-day WorkBuddy/CodeBuddy credit grant claimed in
566
+ // the same pass (one attempt per account per day, guarded by a day
567
+ // marker), so no second timer duplicates the credential resolution.
568
+ //
569
+ // Registered in **every** mode, not only when Redis is present: gating it on
570
+ // Redis would cost Lite proactive quota warming and the check-in ride-along
571
+ // above that claims the once-per-day WorkBuddy/CodeBuddy credit grant. The
572
+ // whole sweep chain accepts `RedisClient | undefined` and falls back to the
573
+ // in-process TTL cache and an in-process day marker, so Redis is an
574
+ // optimization here rather than a precondition — which is exactly what
575
+ // Lite is for.
576
+ scheduledTasks.register({
577
+ name: "quota-refresh-sweep",
578
+ intervalMs: 60_000,
579
+ // Staggered off the oauth/lease/health ticks so the three sweeps that
580
+ // strike providerAccounts do not land together every minute.
581
+ initialDelayMs: 20_000,
582
+ run: () =>
583
+ quotaRefreshSweep({
584
+ db,
585
+ redis,
586
+ providerRegistry: registry,
587
+ resolveCredential: quotaResolveCredential,
588
+ snapshotInvalidator: snapshotService,
589
+ // Without this the sweep hands each collector the raw stored secret.
590
+ // For `cline` that means an `sk_...` key reaching the OAuth branch,
591
+ // which prepends `workos:` and is refused with "please make sure
592
+ // you're using the latest version of Cline and re-authenticate" — so
593
+ // every sweep cools a working account with `quota_fetch_failed` while
594
+ // the same account refreshes fine from the console, which binds the
595
+ // same marker through `createQuotaRefreshDeps`.
596
+ markApiKeyCredential: markProviderApiKeyCredential,
597
+ // Below the 60 s interval: a budget longer than the tick guarantees
598
+ // skip/burst under load instead of steady progress.
599
+ passBudgetMs: 45_000,
600
+ // The check-in ride-along rotates egress per account: each account
601
+ // gets the next active pool in its tenant's rotation so check-ins
602
+ // spread across IPs instead of sharing one direct egress. No pool
603
+ // (or an unreadable pool table) falls back to direct egress, and a
604
+ // tenant never borrows another tenant's pool.
605
+ checkinFetcherFor: dailyCheckinEgressForPass({ db, networkBindingFactory }),
606
+ // Per-account lines and the pass summary are emitted by the sweep
607
+ // itself at `info` level, so they survive the production LOG_LEVEL.
608
+ // `onTick` is left for tests.
609
+ }),
610
+ });
611
+ // The buddy growth/credit tasks: one per upstream capability, each
612
+ // independently switchable with `CARTETHYIA_DISABLED_TASKS`. Every one of
613
+ // them is a credit gain the account is entitled to, and none of them can mark
614
+ // an account unhealthy — a growth endpoint that 404s is a display miss, not a
615
+ // dispatch failure.
616
+ //
617
+ // Daily, not hourly: each claim is once per account per day and is
618
+ // ledger-guarded, so at an hourly cadence 23 of every 24 passes are a full
619
+ // scan of active accounts plus a ledger read per account that resolves to
620
+ // nothing. Once a day is the shortest interval where a pass can still find
621
+ // work, which is the only reason to run at all.
622
+ const buddyTaskDeps = {
623
+ db,
624
+ resolveCredential: quotaResolveCredential,
625
+ fetcher: fetch,
626
+ // Spread across accounts so a pass does not look like a burst to the
627
+ // upstream's risk gate.
628
+ interAccountDelayMs: 800,
629
+ };
630
+ scheduledTasks.register({
631
+ name: "buddy-streak",
632
+ intervalMs: 24 * 60 * 60_000,
633
+ initialDelayMs: 5 * 60_000,
634
+ run: () => buddyStreakTask(buddyTaskDeps),
635
+ });
636
+ scheduledTasks.register({
637
+ name: "buddy-adopt",
638
+ intervalMs: 24 * 60 * 60_000,
639
+ initialDelayMs: 17 * 60_000,
640
+ run: () => buddyAdoptTask(buddyTaskDeps),
641
+ });
642
+ // Growth-activity report: the `/v2/report` batch that lights the login streak
643
+ // and scores the daily growth event. Once a day with its own ledger — it used
644
+ // to ride the quota sweep with no marker of its own, so its eight POSTs ran
645
+ // every minute.
646
+ scheduledTasks.register({
647
+ name: "buddy-activity-report",
648
+ intervalMs: 24 * 60 * 60_000,
649
+ initialDelayMs: 15 * 60 * 60_000,
650
+ run: () => buddyActivityReportTask(buddyTaskDeps),
651
+ });
652
+ // Real credit deductions, stored so the console renders a figure the upstream
653
+ // actually reported. Six-hourly: the upstream's own window is 30 days, so a
654
+ // day's number does not change intraday.
655
+ scheduledTasks.register({
656
+ name: "buddy-usage-sync",
657
+ intervalMs: 6 * 60 * 60_000,
658
+ initialDelayMs: 23 * 60_000,
659
+ run: () => syncBuddyUsage(buddyTaskDeps),
660
+ });
661
+ // The scheduled tasks are registered here but started by the caller once the
662
+ // listener is actually serving (`main.ts`). Starting them inside this builder
663
+ // would let the first tick — the lease sweep, the health sweep — run against
664
+ // a process that has not begun accepting traffic yet.
665
+ const deps: ProductionDeps = {
666
+ db,
667
+ redis,
668
+ snapshotService,
669
+ readRoutingAccountInflight,
670
+ resolveProviderAdapter: (providerId) => registry.resolve(providerId),
671
+ bundledModelCatalog: bundledCatalog,
672
+ byokUpstreamHosts,
673
+ proxyPreparer: new ProxyRequestPreparer({
674
+ snapshotService,
675
+ routingEngine,
676
+ admissionService,
677
+ }),
678
+ networkBindingFactory,
679
+ ipAbuseProtection,
680
+ readiness,
681
+ scheduledTasks,
682
+ poolAgentResolver,
683
+ telemetryBuffer,
684
+ usageFlush,
685
+ healthEventFlush,
686
+ poolSelector,
687
+ admissionService,
688
+ trustedProxyBoundary: resolveTrustedProxyBoundary(),
689
+ providerRegistry: registry,
690
+ resolveOAuthRefresher: (providerId) => registry.resolveRefresher(providerId),
691
+ oauthRefreshService,
692
+ runtimeMetricsSampler,
693
+ };
694
+ const startupMemoryAfter = process.memoryUsage();
695
+ log.info(
696
+ `[startup] phase=dependencies-ready elapsed_ms=${Math.round(performance.now() - startupStartedAt)} ` +
697
+ `rss_mb=${toMiB(startupMemoryAfter.rss)} ` +
698
+ `rss_delta_mb=${toMiB(startupMemoryAfter.rss - startupMemoryBefore.rss)} ` +
699
+ `heap_used_mb=${toMiB(startupMemoryAfter.heapUsed)} ` +
700
+ `heap_delta_mb=${toMiB(startupMemoryAfter.heapUsed - startupMemoryBefore.heapUsed)}`,
701
+ );
702
+ return deps;
703
+ }
704
+
705
+ async function measureStartupPhase<T>(name: string, operation: () => Promise<T>): Promise<T> {
706
+ const startedAt = performance.now();
707
+ const before = process.memoryUsage();
708
+ log.info(
709
+ `[startup] phase=${name} status=started rss_mb=${toMiB(before.rss)} heap_used_mb=${toMiB(before.heapUsed)}`,
710
+ );
711
+ try {
712
+ const result = await operation();
713
+ const after = process.memoryUsage();
714
+ log.info(
715
+ `[startup] phase=${name} status=completed elapsed_ms=${Math.round(performance.now() - startedAt)} ` +
716
+ `rss_mb=${toMiB(after.rss)} rss_delta_mb=${toMiB(after.rss - before.rss)} ` +
717
+ `heap_used_mb=${toMiB(after.heapUsed)} heap_delta_mb=${toMiB(after.heapUsed - before.heapUsed)} ` +
718
+ `external_mb=${toMiB(after.external)}`,
719
+ );
720
+ return result;
721
+ } catch (error) {
722
+ log.error(
723
+ `[startup] phase=${name} status=failed elapsed_ms=${Math.round(performance.now() - startedAt)}`,
724
+ error instanceof Error ? error : new Error(String(error)),
725
+ );
726
+ throw error;
727
+ }
728
+ }
729
+
730
+ function toMiB(bytes: number): string {
731
+ return (bytes / 1024 / 1024).toFixed(1);
732
+ }