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,1563 +1,1292 @@
1
- // Drizzle-backed provider, account, model, routing, and API-key repositories.
2
- import { and, asc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
3
- import { ConsoleDomainError } from "../../shared/errors";
4
- import { parseCustomProviderId, isBundledProviderId } from "../../../providers/provider-contracts";
5
- import {
6
- asRecord,
7
- firstNonEmptyString as firstString,
8
- tryParseJson as safeParseJson,
9
- } from "../../../shared/coerce";
10
- import type { ModelDefinition } from "../../../providers/provider-model-definition";
11
- import type { ProviderRegistry } from "../../../providers/provider-registry";
12
- import { BUNDLED_PROVIDER_MODULES } from "../../../providers/default-registry";
13
- import { modelsDevCatalog } from "../../../providers/discovery/models-dev-catalog";
14
- import { globalOrOwnedBy, ownedByOnly } from "../../../persistence/tenant-scope";
15
- import { nextSortIndex, reorderSortIndex } from "../../../persistence/sort-order";
16
- import type { CartethyiaDatabase } from "../../../persistence/db-handle";
17
- import { buddyTaskLedger, models, providerAccounts, providerOauthStates, providers, telemetryUsageTotals, tenantDisabledModels } from "../../../persistence/schema";
18
- import { breakdownTelemetry } from "../../../observability/event-query";
19
- import type { WireFamily } from "../../../protocol/canonical-model";
20
- import { listAccountHealthEvents, recoverAccount, deleteAccountHealthEvents, type AccountHealthEventRecord } from "../../../providers/operations/account-health-service";
21
- import { invalidateCredentialCache } from "../../../providers/operations/provider-credential-service";
22
- import { encryptCredential, hashSecret } from "../../../security/crypto";
23
- import type { TelemetryBatchBuffer } from "../../../observability/telemetry-buffer";
24
- import { bumpCatalogRevision, type BundledProviderCatalog } from "../../../providers/operations/provider-catalog-service";
25
- import type { AccountInflightReading, BuddyGrowthTaskLedgerEntry, ByokConnectionTestRequest, ByokConnectionTestResult, CreateProviderAccountBatchItemResult, CreateProviderAccountBatchResult, CreateProviderAccountRequest, CredentialMode, ModelCatalogEntry, ProbeAllAccountsResult, ProbeAllModelsResult, ProbeModelRequest, ProbeModelResult, ProviderAccountResponse, ProviderAccountTokenUsage, ProviderCatalogStore, ProviderRecord, SetModelEnabledRequest, UpdateModelMetadataRequest, UpdateProviderAccountRequest, ModelMetadataOverride } from "./contracts";
26
- import { isServiceKind, validateCompatibilityProfile } from "./contracts";
27
- import { ProviderProbingService, type ProbeOutboundResolver } from "../../../providers/discovery/probing-service";
28
- import {
29
- applyModelMetadataOverride,
30
- FALLBACK_CONTEXT_LIMIT,
31
- FALLBACK_OUTPUT_LIMIT,
32
- resolveManualModelMetadata,
33
- } from "../../../providers/provider-model-definition";
34
- import { isUniqueViolation } from "../../../persistence/boot";
35
- import { DEFAULT_ENDPOINT_BY_WIRE_FAMILY, endpointPathForProviderModel, mapProviderRow } from "./catalog-projections";
36
- import { pushStructuredConsoleLog } from "../../../observability/log-ring";
37
- import { decodeJwtPayload } from "../../../providers/authentication/oauth-flow-store";
38
-
39
- /** Real Drizzle-backed provider and model catalog repository. */
40
-
41
- /** Field names a pasted OAuth credential may carry its access token under. */
42
- const OAUTH_ACCESS_FIELDS = ["accessToken", "access_token", "access", "token"] as const;
43
- /** Field names a pasted OAuth credential may carry its refresh token under. */
44
- const OAUTH_REFRESH_FIELDS = ["refreshToken", "refresh_token", "refresh"] as const;
45
-
46
- /** Parses an expiry field that may be an ISO string, an epoch ms, or epoch seconds. */
47
- function parseExpiry(value: unknown): Date | undefined {
48
- if (typeof value === "number" && Number.isFinite(value)) {
49
- // Heuristic: a 10-digit value is epoch seconds, a 13-digit value is ms.
50
- const ms = value < 1e12 ? value * 1000 : value;
51
- const date = new Date(ms);
52
- return Number.isFinite(date.getTime()) ? date : undefined;
53
- }
54
- if (typeof value === "string" && value.trim().length > 0) {
55
- const asNumber = Number(value);
56
- if (Number.isFinite(asNumber)) return parseExpiry(asNumber);
57
- const date = new Date(value);
58
- return Number.isFinite(date.getTime()) ? date : undefined;
59
- }
60
- return undefined;
61
- }
62
- /**
63
- * Reads the two claims a static token's own payload can answer: when it stops
64
- * working, and who issued it.
65
- *
66
- * The issuer is kept because a static JWT carries no other hint of its origin:
67
- * an operator who pasted one from the wrong surface has nothing in the console
68
- * to check it against, and several issuers accept the same token shape.
69
- */
70
- function parseJwtCredential(
71
- raw: string,
72
- ): { readonly expiresAt?: Date; readonly issuer?: string } | undefined {
73
- const payload = decodeJwtPayload(raw.trim());
74
- if (payload === undefined) return undefined;
75
- const expiresAt = parseExpiry(payload["exp"]);
76
- const iss = payload["iss"];
77
- const issuer = typeof iss === "string" && iss.trim().length > 0 ? iss.trim() : undefined;
78
- return {
79
- ...(expiresAt === undefined ? {} : { expiresAt }),
80
- ...(issuer === undefined ? {} : { issuer }),
81
- };
82
- }
83
-
84
- /**
85
- * Splits a pasted OAuth credential into its access token, refresh token, and
86
- * expiry.
87
- *
88
- * The console accepts either a bare access token or the JSON export a client
89
- * produces (`{accessToken, refreshToken, expiresAt, …}`, possibly nested under
90
- * `data`). A bare token has no refresh token — the account can be dispatched
91
- * with it but cannot be refreshed, so the caller stores it as a static
92
- * API credential instead of sending the access token to a refresh endpoint.
93
- */
94
- /**
95
- * Middle segment of an auto-generated account label, from how the credential
96
- * was actually detected.
97
- *
98
- * Only the two kinds that arrive with no name of their own are named here. An
99
- * OAuth paste carries its own identity in `authState` (the account it was
100
- * exported from), so it keeps whatever the export or the operator supplied —
101
- * generating a name for it would overwrite an identity that was already there.
102
- * An unrecognized mode falls back to `key`, matching the mode it is stored as.
103
- */
104
- export function accountLabelKindSegment(credentialMode: CredentialMode): string {
105
- return credentialMode === "jwt" ? "jwt" : "key";
106
- }
107
-
108
- /**
109
- * First unused `dcint-key-N` / `dcint-jwt-N` label for one provider.
110
- *
111
- * Polished tokens and plain JWTs are the credentials that arrive nameless: an
112
- * operator pastes several into one provider and every row came out as
113
- * "<providerId> account", so five accounts were five identical labels and the
114
- * list could not tell them apart — which account failed, or is cooling, was
115
- * unreadable.
116
- *
117
- * Numbering runs per kind, so the first JWT is `jwt-1` rather than inheriting
118
- * whatever number the api_key rows reached (`jwt-3` with no `jwt-1` reads as
119
- * two missing accounts). Counting is case-insensitive on the whole label, so a
120
- * hand-typed `DCINT-KEY-2` still reserves its number.
121
- *
122
- * Pure, so the numbering can be pinned without a database.
123
- */
124
- export function nextGeneratedAccountLabel(
125
- providerId: string,
126
- credentialMode: CredentialMode,
127
- existingLabels: readonly string[],
128
- ): string {
129
- const kind = accountLabelKindSegment(credentialMode);
130
- const prefix = `${providerId}-${kind}-`;
131
- const taken = new Set(
132
- existingLabels.map((label) => label.trim().toLowerCase()),
133
- );
134
- for (let n = 1; ; n += 1) {
135
- const candidate = `${prefix}${n}`;
136
- if (!taken.has(candidate.toLowerCase())) return candidate;
137
- }
138
- }
139
-
140
- export function parsePastedOAuthCredential(raw: string): {
141
- readonly accessToken: string;
142
- readonly refreshToken: string;
143
- readonly expiresAt: Date | undefined;
144
- /**
145
- * Non-secret account configuration the export carried — the profile the
146
- * account is bound to, how it authenticates, the region it was minted in.
147
- * Empty for a bare token, which carries none.
148
- */
149
- readonly authState: Readonly<Record<string, unknown>>;
150
- } {
151
- let record: Record<string, unknown> | undefined;
152
- try {
153
- const parsed = JSON.parse(raw) as unknown;
154
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
155
- record = parsed as Record<string, unknown>;
156
- }
157
- } catch {
158
- record = undefined;
159
- }
160
- if (record === undefined) {
161
- // Bare token: it is the access token, and there is no refresh token.
162
- const jwt = parseJwtCredential(raw);
163
- return {
164
- accessToken: raw,
165
- refreshToken: raw,
166
- expiresAt: jwt?.expiresAt,
167
- authState: {},
168
- };
169
- }
170
- // A nested `data` object is unwrapped the same way the dashboard's parser does.
171
- const nested =
172
- record["data"] !== null && typeof record["data"] === "object" && !Array.isArray(record["data"])
173
- ? (record["data"] as Record<string, unknown>)
174
- : undefined;
175
- const accessToken =
176
- firstString(record, OAUTH_ACCESS_FIELDS) ??
177
- (nested ? firstString(nested, OAUTH_ACCESS_FIELDS) : undefined) ??
178
- raw;
179
- const refreshToken =
180
- firstString(record, OAUTH_REFRESH_FIELDS) ??
181
- (nested ? firstString(nested, OAUTH_REFRESH_FIELDS) : undefined) ??
182
- accessToken;
183
- const expiresAt =
184
- parseExpiry(
185
- record["expiresAt"] ??
186
- record["expires_at"] ??
187
- (nested ? (nested["expiresAt"] ?? nested["expires_at"]) : undefined) ??
188
- record["expires"] ??
189
- (nested ? nested["expires"] : undefined),
190
- ) ?? parseJwtCredential(accessToken)?.expiresAt;
191
- return { accessToken, refreshToken, expiresAt, authState: pastedAuthState(record, nested) };
192
- }
193
-
194
- /**
195
- * The account configuration a pasted export carries beside its tokens.
196
- *
197
- * Kiro refuses a generation request that omits the profile the account is bound
198
- * to, and exports from older installs carry that profile under a different key.
199
- * Reading neither is how an imported account probes with no
200
- * profile and is answered `400 profileArn is required`.
201
- */
202
- function pastedAuthState(
203
- record: Record<string, unknown>,
204
- nested: Record<string, unknown> | undefined,
205
- ): Readonly<Record<string, unknown>> {
206
- const sources = [record, nested, asRecord(record["providerSpecificData"]), asRecord(record["authState"]), asRecord(nested?.["authState"])];
207
- const profileArn = firstStringFrom(sources, ["profileArn", "profile_arn"]);
208
- const authMethod = firstStringFrom(sources, ["authMethod", "auth_method"]);
209
- const region = firstStringFrom(sources, ["region"]);
210
- return {
211
- ...(profileArn === undefined ? {} : { profileArn }),
212
- ...(authMethod === undefined ? {} : { authMethod }),
213
- ...(region === undefined ? {} : { region }),
214
- };
215
- }
216
-
217
- /**
218
- * Adds or removes the `image` input modality on a stored modalities blob.
219
- *
220
- * The blob is a JSON string whose shape varies by source (bundled seed,
221
- * discovery, manual add), so it is normalized rather than pattern-matched: an
222
- * unparseable blob is replaced with the minimal text shape rather than left to
223
- * corrupt capability preflight.
224
- */
225
- export function withImageModality(stored: string | null | undefined, image: boolean): string {
226
- const parsed = asRecord(safeParseJson(stored));
227
- const input = Array.isArray(parsed?.input)
228
- ? (parsed.input as unknown[]).filter((m): m is string => typeof m === "string")
229
- : ["text"];
230
- const output = Array.isArray(parsed?.output)
231
- ? (parsed.output as unknown[]).filter((m): m is string => typeof m === "string")
232
- : ["text"];
233
- const nextInput = image
234
- ? Array.from(new Set([...input, "image"]))
235
- : input.filter((m) => m !== "image");
236
- return JSON.stringify({
237
- ...(parsed ?? {}),
238
- input: nextInput.length > 0 ? nextInput : ["text"],
239
- output: output.length > 0 ? output : ["text"],
240
- });
241
- }
242
-
243
- /** Normalizes a text column read as `unknown` back to a string or null. */
244
- function asStoredText(value: unknown): string | null {
245
- return typeof value === "string" ? value : null;
246
- }
247
-
248
- function firstStringFrom(
249
- sources: readonly (Record<string, unknown> | undefined)[],
250
- fields: readonly string[],
251
- ): string | undefined {
252
- for (const source of sources) {
253
- if (source === undefined) continue;
254
- const value = firstString(source, fields);
255
- if (value !== undefined) return value;
256
- }
257
- return undefined;
258
- }
259
-
260
- /**
261
- * The account's still-active per-model backoffs, or `undefined` when none are.
262
- *
263
- * Expired entries are dropped rather than returned: the sweep that clears them
264
- * runs on a timer, so between the deadline passing and the sweep a raw read
265
- * would report a cooldown that is not in force.
266
- */
267
- function liveModelCooldowns(
268
- raw: unknown,
269
- ): { modelCooldowns: Record<string, string> } | undefined {
270
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return undefined;
271
- const now = Date.now();
272
- const live: Record<string, string> = {};
273
- for (const [modelId, value] of Object.entries(raw as Record<string, unknown>)) {
274
- if (typeof value !== "string") continue;
275
- const at = new Date(value).getTime();
276
- if (Number.isFinite(at) && at > now) live[modelId] = value;
277
- }
278
- return Object.keys(live).length > 0 ? { modelCooldowns: live } : undefined;
279
- }
280
-
281
-
282
- /**
283
- * Projects one persisted `models` row into the console's catalog entry.
284
- *
285
- * `disabled` is resolved by the caller (from `tenant_disabled_models`), because
286
- * the bulk read has to look it up across every provider at once while the
287
- * single-provider read looks it up for one; the projection itself is identical
288
- * either way, so it lives here rather than being written twice.
289
- *
290
- * Exported so a test can pin the unsized-model substitution without a database:
291
- * which rows get the fallback, and that they are the same rows marked estimated.
292
- */
293
- export function mapModelRow(
294
- row: typeof models.$inferSelect,
295
- disabled: boolean,
296
- ): ModelCatalogEntry {
297
- const modalities =
298
- row.modalities && typeof row.modalities === "object"
299
- ? (row.modalities as { input?: unknown; output?: unknown })
300
- : undefined;
301
- const inputModalities = Array.isArray(modalities?.input) ? modalities.input : [];
302
- const outputModalities = Array.isArray(modalities?.output) ? modalities.output : [];
303
- // Nothing filed this model — not its own row, not the base catalog under this
304
- // provider's id, not a majority across the catalog's other resellers. The
305
- // fallback is substituted here rather than persisted: the stored `null` is the
306
- // honest record of what upstream said, and substituting at the write would
307
- // make a guess indistinguishable from a measurement on the next read. The
308
- // marker rides along so the card can say which one it is showing.
309
- const unfiled =
310
- row.contextLimit === null &&
311
- modelsDevCatalog.resolve(row.providerId, row.modelId) === undefined &&
312
- modelsDevCatalog.majorityFor(row.modelId) === undefined;
313
- return {
314
- modelId: row.modelId,
315
- route: row.endpointPath,
316
- provider: row.providerId,
317
- wireFamily: row.wireFamily,
318
- serviceKind: row.serviceKind,
319
- enabled: disabled ? false : row.enabled,
320
- // A fetched model that published no context size read `n/a ctx · n/a out`
321
- // while still being routable — a working model that looked unusable. These
322
- // rows get the same ceilings a manual add is offered, flagged as estimated.
323
- contextLimit: unfiled ? FALLBACK_CONTEXT_LIMIT : row.contextLimit,
324
- outputLimit: unfiled ? FALLBACK_OUTPUT_LIMIT : row.outputLimit,
325
- reasoning: row.reasoning,
326
- toolCall: row.toolCall,
327
- vision: inputModalities.includes("image"),
328
- document: inputModalities.includes("document"),
329
- audio: inputModalities.includes("audio"),
330
- mediaGeneration: outputModalities.includes("image"),
331
- cost: row.cost as ModelCatalogEntry["cost"],
332
- source: row.source,
333
- ...(unfiled ? { limitsEstimated: true } : {}),
334
- // Three-valued on the wire as it is in the column: only a row that claims
335
- // `true` is pro-only. Absence means nobody established the tier, and the
336
- // surface must render that as unknown rather than as free.
337
- ...(row.proOnly === true ? { proOnly: true } : {}),
338
- // Same three-valued rule, from the provider's own directory. Qoder states
339
- // `is_free` per row, so a plan change moves the pill without a code change.
340
- ...(row.freeTier === true ? { freeTier: true } : {}),
341
- sourceUpdatedAt: row.sourceUpdatedAt?.toISOString() ?? null,
342
- } satisfies ModelCatalogEntry;
343
- }
344
-
345
- export class DrizzleProviderCatalogStore implements ProviderCatalogStore {
346
- private readonly probing: ProviderProbingService;
347
- private readonly bundledModelCatalog: ReadonlyMap<string, readonly ModelDefinition[]>;
348
- private readonly providerRegistry: ProviderRegistry;
349
-
350
- private readonly readAccountInflight:
351
- | ((
352
- providerId: string,
353
- tenantId: string,
354
- ) => Promise<readonly AccountInflightReading[]>)
355
- | undefined;
356
-
357
- constructor(
358
- private readonly db: CartethyiaDatabase,
359
- options: {
360
- readonly telemetryBuffer: TelemetryBatchBuffer;
361
- readonly bundledModelCatalog: BundledProviderCatalog;
362
- readonly providerRegistry: ProviderRegistry;
363
- readonly outboundFetchFor: ProbeOutboundResolver;
364
- readonly snapshotInvalidator: { invalidate(): unknown };
365
- readonly readAccountInflight?:
366
- | ((
367
- providerId: string,
368
- tenantId: string,
369
- ) => Promise<readonly AccountInflightReading[]>)
370
- | undefined;
371
- },
372
- ) {
373
- this.bundledModelCatalog = options.bundledModelCatalog.modelsByProvider;
374
- this.providerRegistry = options.providerRegistry;
375
- this.readAccountInflight = options.readAccountInflight;
376
- this.probing = new ProviderProbingService({
377
- db,
378
- telemetryBuffer: options.telemetryBuffer,
379
- defaultEndpoints: DEFAULT_ENDPOINT_BY_WIRE_FAMILY,
380
- bundledModelCatalog: this.bundledModelCatalog,
381
- outboundFetchFor: options.outboundFetchFor,
382
- snapshotInvalidator: options.snapshotInvalidator,
383
- providerRegistry: options.providerRegistry,
384
- });
385
- }
386
- async list(tenantId: string): Promise<readonly ProviderRecord[]> {
387
- const bundledIds = BUNDLED_PROVIDER_MODULES.map((provider) => provider.id);
388
- const rows = await this.db
389
- .select()
390
- .from(providers)
391
- .where(
392
- and(
393
- globalOrOwnedBy(providers.tenantId, tenantId),
394
- or(inArray(providers.id, bundledIds), eq(providers.tenantId, tenantId)),
395
- ),
396
- )
397
- .orderBy(asc(providers.id));
398
- return rows.map((row) => mapProviderRow(row, this.providerRegistry));
399
- }
400
- async get(tenantId: string, providerId: string): Promise<ProviderRecord | undefined> {
401
- const rows = await this.db
402
- .select()
403
- .from(providers)
404
- .where(
405
- and(
406
- eq(providers.id, providerId),
407
- globalOrOwnedBy(providers.tenantId, tenantId),
408
- ),
409
- )
410
- .limit(1);
411
- const row = rows[0];
412
- return row ? mapProviderRow(row, this.providerRegistry) : undefined;
413
- }
414
- async create(record: ProviderRecord): Promise<void> {
415
- if (isBundledProviderId(record.providerId))
416
- throw new ConsoleDomainError(
417
- "provider_is_builtin",
418
- 403,
419
- "Built-in provider cannot be created",
420
- );
421
- parseCustomProviderId(record.providerId);
422
- if (record.compatibilityProfile) validateCompatibilityProfile(record.compatibilityProfile);
423
- await this.db.insert(providers).values({
424
- id: record.providerId,
425
- tenantId: record.tenantId ?? null,
426
- enabled: record.enabled,
427
- ...(record.wireFamilyDefault ? { wireFamilyDefault: record.wireFamilyDefault } : {}),
428
- capabilityProfile: record.capabilityProfile ?? null,
429
- baseUrl: record.baseUrl ?? null,
430
- compatibilityProfile: record.compatibilityProfile ?? null,
431
- });
432
- }
433
- async update(
434
- tenantId: string,
435
- providerId: string,
436
- patch: Partial<ProviderRecord>,
437
- ): Promise<ProviderRecord | undefined> {
438
- if (isBundledProviderId(providerId))
439
- throw new ConsoleDomainError(
440
- "provider_is_builtin",
441
- 403,
442
- "Built-in provider cannot be updated",
443
- );
444
- if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
445
- const set: Partial<typeof providers.$inferInsert> = {};
446
- if (patch.enabled !== undefined) set.enabled = patch.enabled;
447
- if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
448
- if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
449
- if (patch.compatibilityProfile !== undefined)
450
- set.compatibilityProfile = patch.compatibilityProfile;
451
- const rows =
452
- Object.keys(set).length > 0
453
- ? await this.db
454
- .update(providers)
455
- .set(set)
456
- .where(
457
- and(
458
- eq(providers.id, providerId),
459
- ownedByOnly(providers.tenantId, tenantId),
460
- ),
461
- )
462
- .returning()
463
- : await this.db
464
- .select()
465
- .from(providers)
466
- .where(
467
- and(
468
- eq(providers.id, providerId),
469
- ownedByOnly(providers.tenantId, tenantId),
470
- ),
471
- );
472
- const row = rows[0];
473
- return row ? mapProviderRow(row, this.providerRegistry) : undefined;
474
- }
475
- async delete(tenantId: string, providerId: string): Promise<boolean> {
476
- if (isBundledProviderId(providerId))
477
- throw new ConsoleDomainError(
478
- "provider_is_builtin",
479
- 403,
480
- "Built-in provider cannot be deleted",
481
- );
482
- // Custom-provider rows own their models, accounts, disabled-model flags,
483
- // and routing preferences: deleting the parent cascades all of them
484
- // (models/provider_accounts/provider_oauth_states via provider FK,
485
- // health_events via account FK, tenant_disabled_models and
486
- // provider_routing_settings via provider FK) in one atomic DELETE.
487
- const deleted = await this.db
488
- .delete(providers)
489
- .where(and(eq(providers.id, providerId), ownedByOnly(providers.tenantId, tenantId)))
490
- .returning({ id: providers.id });
491
- if (deleted.length === 0) return false;
492
- this.providerRegistry.unregister(providerId);
493
- // The provider left the registry, so the compiled catalog is now missing it
494
- // — the snapshot's re-seed is gated on that revision, and a delete that did
495
- // not bump it would leave the provider's model rows behind.
496
- bumpCatalogRevision();
497
- return true;
498
- }
499
- async updateGlobal(
500
- providerId: string,
501
- patch: Partial<ProviderRecord>,
502
- ): Promise<ProviderRecord | undefined> {
503
- const isBuiltin = isBundledProviderId(providerId);
504
- if (isBuiltin && Object.keys(patch).some((field) => field !== "enabled")) {
505
- throw new ConsoleDomainError(
506
- "provider_is_builtin",
507
- 403,
508
- "Built-in providers only support enable/disable",
509
- );
510
- }
511
- if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
512
- const set: Partial<typeof providers.$inferInsert> = {};
513
- if (patch.enabled !== undefined) set.enabled = patch.enabled;
514
- if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
515
- if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
516
- if (patch.compatibilityProfile !== undefined) {
517
- set.compatibilityProfile = patch.compatibilityProfile;
518
- }
519
- const rows =
520
- Object.keys(set).length > 0
521
- ? await this.db
522
- .update(providers)
523
- .set(set)
524
- .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
525
- .returning()
526
- : await this.db
527
- .select()
528
- .from(providers)
529
- .where(and(eq(providers.id, providerId), isNull(providers.tenantId)));
530
- const row = rows[0];
531
- return row ? mapProviderRow(row, this.providerRegistry) : undefined;
532
- }
533
-
534
- async deleteGlobal(providerId: string): Promise<boolean> {
535
- if (isBundledProviderId(providerId)) {
536
- throw new ConsoleDomainError(
537
- "provider_is_builtin",
538
- 403,
539
- "Built-in provider cannot be deleted",
540
- );
541
- }
542
- const rows = await this.db
543
- .delete(providers)
544
- .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
545
- .returning({ id: providers.id });
546
- return rows.length > 0;
547
- }
548
- async listModels(tenantId: string, providerId: string): Promise<readonly ModelCatalogEntry[]> {
549
- const byProvider = await this.listModelsForTenant(tenantId, providerId);
550
- return byProvider.get(providerId) ?? [];
551
- }
552
-
553
- /**
554
- * Every enabled-and-disabled model row the tenant can see, grouped by
555
- * provider. One pair of statements for the whole tenant instead of a pair per
556
- * provider.
557
- *
558
- * The per-provider `listModels` shape costs two queries per call, so a caller
559
- * that needs every provider's models — the flat catalog the picker renders —
560
- * issued `2 * providers + 2` statements, growing with the bundled catalog.
561
- * Grouping here makes it constant: one disabled-model read and one models
562
- * join, regardless of provider count. `providerId` narrows it to a single
563
- * provider for callers that already know which one they want.
564
- */
565
- async listModelsForTenant(
566
- tenantId: string,
567
- providerId?: string,
568
- ): Promise<Map<string, readonly ModelCatalogEntry[]>> {
569
- const disabled = await this.db
570
- .select({
571
- providerId: tenantDisabledModels.providerId,
572
- modelId: tenantDisabledModels.modelId,
573
- endpointPath: tenantDisabledModels.endpointPath,
574
- })
575
- .from(tenantDisabledModels)
576
- .where(
577
- providerId === undefined
578
- ? eq(tenantDisabledModels.tenantId, tenantId)
579
- : and(
580
- eq(tenantDisabledModels.tenantId, tenantId),
581
- eq(tenantDisabledModels.providerId, providerId),
582
- ),
583
- );
584
- const disabledKeys = new Set(
585
- disabled.map((d) => `${d.providerId}::${d.modelId}::${d.endpointPath}`),
586
- );
587
- const dbRows = await this.db
588
- .select({ model: models })
589
- .from(models)
590
- .innerJoin(providers, eq(models.providerId, providers.id))
591
- .where(
592
- and(
593
- ...(providerId === undefined ? [] : [eq(models.providerId, providerId)]),
594
- globalOrOwnedBy(providers.tenantId, tenantId),
595
- ),
596
- );
597
- const grouped = new Map<string, ModelCatalogEntry[]>();
598
- for (const { model: row } of dbRows) {
599
- const isDisabled = disabledKeys.has(
600
- `${row.providerId}::${row.modelId}::${row.endpointPath}`,
601
- );
602
- const list = grouped.get(row.providerId) ?? [];
603
- list.push(mapModelRow(row, isDisabled));
604
- grouped.set(row.providerId, list);
605
- }
606
- return grouped;
607
- }
608
- async registerModels(
609
- tenantId: string,
610
- providerId: string,
611
- modelIds: readonly string[],
612
- wireFamily?: string,
613
- metadata?: ModelMetadataOverride,
614
- ): Promise<void> {
615
- const owner = await this.db
616
- .select({
617
- id: providers.id,
618
- baseUrl: providers.baseUrl,
619
- compatibilityProfile: providers.compatibilityProfile,
620
- })
621
- .from(providers)
622
- .where(and(eq(providers.id, providerId), globalOrOwnedBy(providers.tenantId, tenantId)))
623
- .limit(1);
624
- if (!owner[0]) {
625
- throw new ConsoleDomainError("provider_not_found", 404, `Provider ${providerId} not found`);
626
- }
627
- const family = (wireFamily ?? "chat") as WireFamily;
628
- // Static endpoint from the provider's own bundled catalog via the probing
629
- // service (the same startup-built map this store is constructed with).
630
- // Without this, bundled providers on versioned bases (cline) get the
631
- // generic `/v1/…` default, which joins into an unreachable path and every
632
- // probe/dispatch 404s.
633
- const staticEndpoint = await this.probing.resolveStaticEndpoint(providerId, family);
634
- const endpointPath = endpointPathForProviderModel(
635
- family,
636
- owner[0].compatibilityProfile,
637
- staticEndpoint === undefined ? undefined : { [family]: staticEndpoint },
638
- );
639
- if (modelIds.length === 0) return;
640
- // Single multi-row insert and upsert of the capability flags so a
641
- // re-registration repairs a row whose `tool_call` (and `reasoning`) was
642
- // seeded false — a manual add persists schema defaults, which capability
643
- // preflight reads as "route cannot use tools" and silently strips `tools`
644
- // from every request. `enabled` stays operator-owned; `source` is refreshed
645
- // to `manual`.
646
- await this.db
647
- .insert(models)
648
- .values(
649
- modelIds.map((modelId) => ({
650
- providerId,
651
- modelId,
652
- wireFamily: family,
653
- endpointPath,
654
- ...applyModelMetadataOverride(
655
- resolveManualModelMetadata(providerId, modelId),
656
- metadata,
657
- ),
658
- source: "manual",
659
- sourceUpdatedAt: new Date(),
660
- enabled: true,
661
- })),
662
- )
663
- .onConflictDoUpdate({
664
- target: [models.providerId, models.modelId, models.endpointPath],
665
- set: {
666
- wireFamily: sql`excluded.wire_family`,
667
- contextLimit: sql`excluded.context_limit`,
668
- outputLimit: sql`excluded.output_limit`,
669
- modalities: sql`excluded.modalities`,
670
- reasoning: sql`excluded.reasoning`,
671
- toolCall: sql`excluded.tool_call`,
672
- source: sql`'manual'`,
673
- sourceUpdatedAt: sql`excluded.source_updated_at`,
674
- },
675
- });
676
- }
677
-
678
- /**
679
- * One-shot connectivity probe and model discovery live in
680
- * `services/provider-probing.ts` — the store only forwards so the domain
681
- * `ProviderCatalogStore` interface is unchanged.
682
- */
683
- async probeModel(
684
- tenantId: string,
685
- providerId: string,
686
- request: ProbeModelRequest,
687
- ): Promise<ProbeModelResult> {
688
- return this.probing.probeModel(tenantId, providerId, request);
689
- }
690
-
691
- /** Ad-hoc BYOK connectivity test; delegates to the shared probing service. */
692
- async testByokConnection(
693
- tenantId: string,
694
- request: ByokConnectionTestRequest,
695
- ): Promise<ByokConnectionTestResult> {
696
- return this.probing.testByokConnection(tenantId, request);
697
- }
698
-
699
- /**
700
- * Batched provider-wide probe: the first registered model runs sequentially
701
- * (warms OAuth token / connection pools), the rest run concurrently bounded
702
- * to 5. Registered model ids come from this store's own catalog read.
703
- */
704
- async probeAllModels(tenantId: string, providerId: string): Promise<ProbeAllModelsResult> {
705
- const entries = await this.listModels(tenantId, providerId);
706
- const requests = entries.map((entry) => ({
707
- modelId: entry.modelId,
708
- route: entry.route,
709
- serviceKind: isServiceKind(entry.serviceKind) ? entry.serviceKind : ("llm" as const),
710
- }));
711
- const uniqueRequests = requests.filter(
712
- (request, index, all) =>
713
- all.findIndex(
714
- (candidate) =>
715
- candidate.modelId === request.modelId &&
716
- candidate.route === request.route &&
717
- candidate.serviceKind === request.serviceKind,
718
- ) === index,
719
- );
720
- return this.probing.probeAllModels(tenantId, providerId, uniqueRequests);
721
- }
722
- async probeAllAccounts(
723
- tenantId: string,
724
- providerId: string,
725
- request: ProbeModelRequest,
726
- ): Promise<ProbeAllAccountsResult> {
727
- return this.probing.probeAllAccounts(tenantId, providerId, request);
728
- }
729
- /** Toggles a persisted model's routing eligibility. */
730
- async setModelEnabled(
731
- tenantId: string,
732
- providerId: string,
733
- request: SetModelEnabledRequest,
734
- ): Promise<boolean> {
735
- // Tenant-owned (BYOK) model: toggle the shared row directly.
736
- const owned = await this.db
737
- .select({ id: models.id })
738
- .from(models)
739
- .innerJoin(providers, eq(models.providerId, providers.id))
740
- .where(
741
- and(
742
- eq(models.providerId, providerId),
743
- eq(models.modelId, request.modelId),
744
- eq(models.endpointPath, request.route),
745
- ownedByOnly(providers.tenantId, tenantId),
746
- ),
747
- )
748
- .limit(1);
749
- const ownedTarget = owned[0];
750
- if (ownedTarget) {
751
- await this.db
752
- .update(models)
753
- .set({ enabled: request.enabled })
754
- .where(eq(models.id, ownedTarget.id));
755
- return true;
756
- }
757
-
758
- // Global/built-in model: tenants cannot mutate the shared row, so record
759
- // (or clear) a tenant-scoped disable in `tenantDisabledModels`.
760
- const global = await this.db
761
- .select({ id: models.id })
762
- .from(models)
763
- .innerJoin(providers, eq(models.providerId, providers.id))
764
- .where(
765
- and(
766
- eq(models.providerId, providerId),
767
- eq(models.modelId, request.modelId),
768
- eq(models.endpointPath, request.route),
769
- isNull(providers.tenantId),
770
- ),
771
- )
772
- .limit(1);
773
- if (global[0] === undefined) return false;
774
- if (request.enabled) {
775
- await this.db
776
- .delete(tenantDisabledModels)
777
- .where(
778
- and(
779
- eq(tenantDisabledModels.tenantId, tenantId),
780
- eq(tenantDisabledModels.providerId, providerId),
781
- eq(tenantDisabledModels.modelId, request.modelId),
782
- eq(tenantDisabledModels.endpointPath, request.route),
783
- ),
784
- );
785
- return true;
786
- }
787
- await this.db
788
- .insert(tenantDisabledModels)
789
- .values({
790
- tenantId,
791
- providerId,
792
- modelId: request.modelId,
793
- endpointPath: request.route,
794
- })
795
- .onConflictDoNothing({
796
- target: [
797
- tenantDisabledModels.tenantId,
798
- tenantDisabledModels.providerId,
799
- tenantDisabledModels.modelId,
800
- tenantDisabledModels.endpointPath,
801
- ],
802
- });
803
- return true;
804
- }
805
-
806
- /**
807
- * Updates one model's limits and capability flags.
808
- *
809
- * Two row kinds are writable. A tenant-owned (BYOK) row is updated directly.
810
- * A model belonging to a *global* provider row is also updated directly:
811
- * bundled providers are seeded once with `tenant_id IS NULL` and `providers.id`
812
- * is the primary key, so a bundled provider can only ever have that one row —
813
- * there is no tenant-scoped row to edit instead. Auto-fetched rows
814
- * (`discovered` / `auto_free`) live on exactly those providers, which is why
815
- * the previous `ownedByOnly` filter answered `not_found` for every model the
816
- * operator had just fetched and could not be edited at all.
817
- *
818
- * A global `builtin` row is rejected: it is re-seeded from the bundle on every
819
- * boot, so an edit there would be silently reverted, and `deleteModel` refuses
820
- * it for the same reason.
821
- *
822
- * Absent override fields leave the stored value untouched — an edit that only
823
- * sets the context ceiling must not reset the capability flags.
824
- */
825
- async updateModelMetadata(
826
- tenantId: string,
827
- providerId: string,
828
- request: UpdateModelMetadataRequest,
829
- ): Promise<boolean> {
830
- const findRow = (ownership: SQL) =>
831
- this.db
832
- .select({ id: models.id, modalities: models.modalities, source: models.source })
833
- .from(models)
834
- .innerJoin(providers, eq(models.providerId, providers.id))
835
- .where(
836
- and(
837
- eq(models.providerId, providerId),
838
- eq(models.modelId, request.modelId),
839
- eq(models.endpointPath, request.route),
840
- ownership,
841
- ),
842
- )
843
- .limit(1);
844
- const owned = await findRow(ownedByOnly(providers.tenantId, tenantId));
845
- let row = owned[0];
846
- if (row === undefined) {
847
- const global = await findRow(isNull(providers.tenantId));
848
- const candidate = global[0];
849
- if (candidate === undefined) return false;
850
- if (candidate.source === "builtin") {
851
- throw new ConsoleDomainError(
852
- "builtin_model_immutable",
853
- 403,
854
- `Built-in model ${providerId}/${request.modelId} cannot be edited — the bundle re-seeds it on every boot`,
855
- );
856
- }
857
- row = candidate;
858
- }
859
-
860
- const override = request.metadata;
861
- const set: Record<string, unknown> = { sourceUpdatedAt: new Date() };
862
- if (override?.contextLimit !== undefined) set.contextLimit = override.contextLimit;
863
- if (override?.outputLimit !== undefined) set.outputLimit = override.outputLimit;
864
- // Passthrough grants every capability and cannot be partly revoked by a
865
- // per-flag field: the point of the flag is that the operator does not know
866
- // which capabilities the model has, so an explicit `false` alongside it is
867
- // either stale or a mistake.
868
- if (override?.passthrough === true) {
869
- set.reasoning = true;
870
- set.toolCall = true;
871
- set.modalities = withImageModality(asStoredText(row.modalities), true);
872
- } else {
873
- if (override?.reasoning !== undefined) set.reasoning = override.reasoning;
874
- if (override?.toolCall !== undefined) set.toolCall = override.toolCall;
875
- if (override?.image !== undefined)
876
- set.modalities = withImageModality(asStoredText(row.modalities), override.image);
877
- }
878
- await this.db.update(models).set(set).where(eq(models.id, row.id));
879
- return true;
880
- }
881
-
882
- async deleteModel(
883
- tenantId: string,
884
- providerId: string,
885
- request: SetModelEnabledRequest,
886
- ): Promise<boolean> {
887
- const owned = await this.db
888
- .select({ id: models.id })
889
- .from(models)
890
- .innerJoin(providers, eq(models.providerId, providers.id))
891
- .where(
892
- and(
893
- eq(models.providerId, providerId),
894
- eq(models.modelId, request.modelId),
895
- eq(models.endpointPath, request.route),
896
- ownedByOnly(providers.tenantId, tenantId),
897
- ),
898
- )
899
- .limit(1);
900
- const target = owned[0];
901
- if (target) {
902
- const rows = await this.db
903
- .delete(models)
904
- .where(eq(models.id, target.id))
905
- .returning({ id: models.id });
906
- return rows.length > 0;
907
- }
908
- const global = await this.db
909
- .select({ id: models.id, source: models.source })
910
- .from(models)
911
- .innerJoin(providers, eq(models.providerId, providers.id))
912
- .where(
913
- and(
914
- eq(models.providerId, providerId),
915
- eq(models.modelId, request.modelId),
916
- eq(models.endpointPath, request.route),
917
- isNull(providers.tenantId),
918
- ),
919
- )
920
- .limit(1);
921
- if (!global[0]) return false;
922
- // Built-in models are immutable catalog: tenants can only disable them
923
- // (via tenantDisabledModels), never delete the shared row.
924
- if (global[0].source === "builtin") {
925
- throw new ConsoleDomainError(
926
- "builtin_model_immutable",
927
- 403,
928
- `Built-in model ${providerId}/${request.modelId} cannot be deleted — disable it instead`,
929
- );
930
- }
931
- const rows = await this.db
932
- .delete(models)
933
- .where(eq(models.id, global[0].id))
934
- .returning({ id: models.id });
935
- await this.db
936
- .delete(tenantDisabledModels)
937
- .where(
938
- and(
939
- eq(tenantDisabledModels.tenantId, tenantId),
940
- eq(tenantDisabledModels.providerId, providerId),
941
- eq(tenantDisabledModels.modelId, request.modelId),
942
- eq(tenantDisabledModels.endpointPath, request.route),
943
- ),
944
- );
945
- return rows.length > 0;
946
- }
947
-
948
- private async accountsWithUsage(
949
- tenantId: string,
950
- rows: readonly (typeof providerAccounts.$inferSelect)[],
951
- ): Promise<readonly ProviderAccountResponse[]> {
952
- if (rows.length === 0) return [];
953
- const todayStart = new Date();
954
- todayStart.setUTCHours(0, 0, 0, 0);
955
- const accountIds = rows.map((row) => row.id);
956
- // Today's per-account usage is one GROUP BY, not a read of every event
957
- // since midnight. `breakdownTelemetry("account")` is capped at 100 groups;
958
- // a page of accounts never exceeds it, and the lookup below is by id, so a
959
- // group that fell outside the cap simply reads as "no usage today" — the
960
- // same value an account with no traffic gets.
961
- const todayGroups = await breakdownTelemetry(this.db, tenantId, "account", todayStart);
962
- const todayByAccount = new Map(
963
- todayGroups.map((group) => [
964
- group.key,
965
- {
966
- requests: group.requests,
967
- errors: group.errors,
968
- inputTokens: group.inputTokens,
969
- outputTokens: group.outputTokens,
970
- },
971
- ]),
972
- );
973
- const [lifetimeRows] = await Promise.all([
974
- this.db
975
- .select()
976
- .from(telemetryUsageTotals)
977
- .where(
978
- and(
979
- eq(telemetryUsageTotals.tenantId, tenantId),
980
- eq(telemetryUsageTotals.identityType, "account"),
981
- inArray(telemetryUsageTotals.entityId, accountIds),
982
- ),
983
- ),
984
- ]);
985
- const lifetimeByAccount = new Map(lifetimeRows.map((row) => [row.entityId, row]));
986
- const mapUsage = (row: {
987
- readonly requests: number | string | null;
988
- readonly errors: number | string | null;
989
- readonly inputTokens: number | string | null;
990
- readonly outputTokens: number | string | null;
991
- } | undefined): ProviderAccountTokenUsage => {
992
- const inputTokens = Number(row?.inputTokens ?? 0);
993
- const outputTokens = Number(row?.outputTokens ?? 0);
994
- return {
995
- requests: Number(row?.requests ?? 0),
996
- errors: Number(row?.errors ?? 0),
997
- inputTokens,
998
- outputTokens,
999
- totalTokens: inputTokens + outputTokens,
1000
- };
1001
- };
1002
- const first = rows[0];
1003
- const inflightByAccount = await this.accountInflightFor(tenantId, first?.providerId);
1004
- return rows.map((row) => {
1005
- const inflight = inflightByAccount.get(row.id);
1006
- return this.mapAccount(row, {
1007
- today: mapUsage(todayByAccount.get(row.id)),
1008
- allTime: mapUsage(lifetimeByAccount.get(row.id)),
1009
- ...(inflight === undefined ? {} : { inflight }),
1010
- });
1011
- });
1012
- }
1013
-
1014
- private async accountInflightFor(
1015
- tenantId: string,
1016
- providerId: string | undefined,
1017
- ): Promise<Map<string, number>> {
1018
- const readings = new Map<string, number>();
1019
- if (!this.readAccountInflight || !providerId) return readings;
1020
- const rows = await this.readAccountInflight(providerId, tenantId);
1021
- for (const row of rows) {
1022
- if (typeof row.accountId !== "string" || !Number.isFinite(row.inflight)) continue;
1023
- readings.set(row.accountId, Math.max(0, Math.floor(row.inflight)));
1024
- }
1025
- return readings;
1026
- }
1027
-
1028
- /**
1029
- * Next free list position for a new account in this provider's list.
1030
- *
1031
- * Scoped to (provider, tenant) because the list is per provider: a tenant
1032
- * with accounts under two providers must not have the second provider's
1033
- * first account land at a high index.
1034
- */
1035
- /**
1036
- * Labels already in use for one provider, for numbering a generated name.
1037
- *
1038
- * Scoped to this provider and tenant: `dcint-key-1` and `other-key-1` belong
1039
- * to different providers and must not collide with each other.
1040
- */
1041
- private async generateAccountLabel(
1042
- db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1043
- providerId: string,
1044
- tenantId: string,
1045
- credentialMode: CredentialMode,
1046
- ): Promise<string> {
1047
- const rows = await db
1048
- .select({ label: providerAccounts.label })
1049
- .from(providerAccounts)
1050
- .where(
1051
- and(
1052
- eq(providerAccounts.providerId, providerId),
1053
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1054
- ),
1055
- );
1056
- return nextGeneratedAccountLabel(
1057
- providerId,
1058
- credentialMode,
1059
- rows.map((row) => row.label).filter((label): label is string => typeof label === "string"),
1060
- );
1061
- }
1062
-
1063
- private async nextAccountSortIndex(
1064
- db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1065
- providerId: string,
1066
- tenantId: string,
1067
- ): Promise<number> {
1068
- return nextSortIndex(
1069
- db,
1070
- { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
1071
- and(
1072
- eq(providerAccounts.providerId, providerId),
1073
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1074
- ),
1075
- );
1076
- }
1077
-
1078
- /** Rewrites one provider's account order; `accountIds` is the full order. */
1079
- async reorderAccounts(
1080
- tenantId: string,
1081
- providerId: string,
1082
- accountIds: readonly string[],
1083
- ): Promise<void> {
1084
- await reorderSortIndex(
1085
- this.db,
1086
- { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
1087
- and(
1088
- eq(providerAccounts.providerId, providerId),
1089
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1090
- ),
1091
- accountIds,
1092
- );
1093
- }
1094
-
1095
- async listAccounts(
1096
- tenantId: string,
1097
- providerId: string,
1098
- ): Promise<readonly ProviderAccountResponse[]> {
1099
- const rows = await this.db
1100
- .select()
1101
- .from(providerAccounts)
1102
- .where(
1103
- and(
1104
- eq(providerAccounts.providerId, providerId),
1105
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1106
- ),
1107
- )
1108
- // Stable list position, not `created_at`: two accounts created in the
1109
- // same millisecond could swap between loads. `id` breaks a tie so the
1110
- // order is total even before a reorder assigns distinct indices.
1111
- .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
1112
- return this.accountsWithUsage(tenantId, rows);
1113
- }
1114
-
1115
- async listAllAccounts(tenantId: string): Promise<readonly ProviderAccountResponse[]> {
1116
- const rows = await this.db
1117
- .select()
1118
- .from(providerAccounts)
1119
- .where(globalOrOwnedBy(providerAccounts.tenantId, tenantId))
1120
- .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
1121
- return this.accountsWithUsage(tenantId, rows);
1122
- }
1123
-
1124
- async createAccount(
1125
- tenantId: string,
1126
- providerId: string,
1127
- request: CreateProviderAccountRequest,
1128
- existingTx?: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1129
- includeUsage = true,
1130
- sortIndexOverride?: number,
1131
- ): Promise<ProviderAccountResponse> {
1132
- // Callers inside an existing transaction pass it in so the account lands in
1133
- // that unit of work (the batch path); otherwise this opens its own.
1134
- const run = async (
1135
- tx: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1136
- ): Promise<ProviderAccountResponse> => {
1137
- let effectiveSecret = request.secret;
1138
- let effectiveCredentialKind = request.credentialKind;
1139
- const requestedCredentialMode: CredentialMode = request.credentialMode ?? "auto";
1140
- let effectiveCredentialMode: CredentialMode = requestedCredentialMode;
1141
- let tokenExpiresAt: Date | undefined;
1142
- let jwtIssuer: string | undefined;
1143
- let oauthRefreshCiphertext: Buffer | undefined;
1144
- let oauthExpiresAt: Date | undefined;
1145
- let oauthHasRefreshToken = false;
1146
- let pastedAuthState: Readonly<Record<string, unknown>> = {};
1147
-
1148
- if (
1149
- (request.credentialKind === "oauth" || request.credentialKind === "api_key") &&
1150
- request.secret.trim().length > 0
1151
- ) {
1152
- const trimmed = request.secret.trim();
1153
- const parts = parsePastedOAuthCredential(trimmed);
1154
- pastedAuthState = parts.authState;
1155
- const hasRefreshToken = parts.refreshToken !== parts.accessToken;
1156
- const parsedJwt =
1157
- requestedCredentialMode === "api_key"
1158
- ? undefined
1159
- : parseJwtCredential(parts.accessToken);
1160
- if (requestedCredentialMode === "jwt" && parsedJwt === undefined) {
1161
- throw new ConsoleDomainError(
1162
- "invalid_request",
1163
- 400,
1164
- "credentialMode jwt requires a valid three-part JWT",
1165
- );
1166
- }
1167
- if (requestedCredentialMode === "api_key") {
1168
- effectiveSecret = parts.accessToken;
1169
- effectiveCredentialKind = "api_key";
1170
- effectiveCredentialMode = "api_key";
1171
- } else if (
1172
- parsedJwt !== undefined &&
1173
- (requestedCredentialMode === "jwt" || !hasRefreshToken)
1174
- ) {
1175
- effectiveSecret = parts.accessToken;
1176
- effectiveCredentialKind = "api_key";
1177
- effectiveCredentialMode = "jwt";
1178
- tokenExpiresAt = parsedJwt.expiresAt;
1179
- // Kept alongside the expiry: the console shows who issued a static
1180
- // token, and the secret itself is never readable after this point.
1181
- jwtIssuer = parsedJwt.issuer;
1182
- } else if (request.credentialKind === "oauth" || hasRefreshToken) {
1183
- effectiveSecret = parts.accessToken;
1184
- effectiveCredentialKind = hasRefreshToken ? "oauth" : "api_key";
1185
- effectiveCredentialMode = hasRefreshToken ? "auto" : "api_key";
1186
- if (hasRefreshToken) {
1187
- oauthRefreshCiphertext = encryptCredential(parts.refreshToken);
1188
- oauthHasRefreshToken = true;
1189
- }
1190
- oauthExpiresAt = parts.expiresAt;
1191
- } else {
1192
- effectiveCredentialMode = "api_key";
1193
- }
1194
- }
1195
-
1196
- // Append to the end of this provider's list rather than relying on
1197
- // creation time, so a new account never displaces existing positions.
1198
- const credentialFingerprint =
1199
- effectiveCredentialKind === "none" || effectiveSecret.length === 0
1200
- ? undefined
1201
- : hashSecret(effectiveSecret);
1202
- const accountAuthState = {
1203
- ...pastedAuthState,
1204
- ...(request.authState ?? {}),
1205
- credentialMode: effectiveCredentialMode,
1206
- ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt: tokenExpiresAt.toISOString() }),
1207
- ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
1208
- };
1209
- const nextSortIndex =
1210
- sortIndexOverride ?? (await this.nextAccountSortIndex(tx, providerId, tenantId));
1211
- // Read existing labels only when one has to be generated: a named
1212
- // account costs no extra query, and this is the path a large batch
1213
- // paste walks once per row.
1214
- const label =
1215
- request.label ??
1216
- (await this.generateAccountLabel(tx, providerId, tenantId, effectiveCredentialMode));
1217
- const rows = await tx
1218
- .insert(providerAccounts)
1219
- .values({
1220
- providerId,
1221
- tenantId,
1222
- sortIndex: nextSortIndex,
1223
- label,
1224
- credentialCiphertext: encryptCredential(effectiveSecret),
1225
- ...(credentialFingerprint ? { credentialFingerprint } : {}),
1226
- credentialKind: effectiveCredentialKind,
1227
- status: "active",
1228
- authState: accountAuthState,
1229
- // An OAuth account pasted without a refresh token is a *static*
1230
- // token: the pasted value is a bearer token used exactly as issued
1231
- // and there is no refresh grant to run. Flag it as static so the
1232
- // console reads it as an informational "static token" rather than
1233
- // "re-login required" — the token is still valid and dispatchable —
1234
- // and so the refresh sweep skips it instead of retrying a refresh
1235
- // that can never succeed.
1236
- ...(effectiveCredentialKind === "oauth" && !oauthHasRefreshToken || effectiveCredentialMode === "jwt"
1237
- ? { staticToken: true }
1238
- : {}),
1239
- })
1240
- .returning();
1241
- const row = rows[0];
1242
- if (!row) throw new Error("failed to create provider account");
1243
-
1244
- if (effectiveCredentialKind === "oauth") {
1245
- await tx.insert(providerOauthStates).values({
1246
- providerAccountId: row.id,
1247
- ...(oauthRefreshCiphertext ? { refreshCiphertext: oauthRefreshCiphertext } : {}),
1248
- expiresAt: oauthExpiresAt ?? null,
1249
- });
1250
- }
1251
- if (request.credentialKind === "oauth" && !oauthHasRefreshToken) {
1252
- pushStructuredConsoleLog(
1253
- "info",
1254
- "OAuth access token stored as a static API credential; it will not be refreshed",
1255
- {
1256
- event: "token_refresh",
1257
- providerId,
1258
- accountId: row.id,
1259
- errorCode: "static_token",
1260
- },
1261
- );
1262
- }
1263
-
1264
- if (!includeUsage) {
1265
- const emptyUsage = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };
1266
- return this.mapAccount(row, { today: emptyUsage, allTime: emptyUsage });
1267
- }
1268
- const [account] = await this.accountsWithUsage(tenantId, [row]);
1269
- if (!account) throw new Error("created provider account could not be mapped");
1270
- return account;
1271
- };
1272
-
1273
- try {
1274
- if (existingTx !== undefined) {
1275
- return await run(existingTx);
1276
- }
1277
- return await this.db.transaction(run);
1278
- } catch (error) {
1279
- if (isUniqueViolation(error)) {
1280
- throw new ConsoleDomainError(
1281
- "provider_account_duplicate",
1282
- 409,
1283
- "A provider account with this credential already exists",
1284
- );
1285
- }
1286
- throw error;
1287
- }
1288
- }
1289
-
1290
- /**
1291
- * Creates many accounts in one round-trip.
1292
- *
1293
- * The whole batch shares one transaction, so a paste of 40 credentials costs
1294
- * one connection checkout rather than 40. Each item is created through the
1295
- * same `createAccount` path the single route uses — there is no second
1296
- * implementation of credential detection to drift.
1297
- *
1298
- * Items are created sequentially inside that transaction: the unique
1299
- * credential fingerprint makes two identical pastes collide, and a nested
1300
- * transaction per item keeps that collision from aborting the whole batch.
1301
- * Outcomes are reported per index, so a partial paste still lands the
1302
- * accounts that were fine — an operator fixing one bad line should not have
1303
- * to re-import 39.
1304
- */
1305
- async createAccountBatch(
1306
- tenantId: string,
1307
- providerId: string,
1308
- requests: readonly CreateProviderAccountRequest[],
1309
- ): Promise<CreateProviderAccountBatchResult> {
1310
- if (requests.length === 0) {
1311
- return { created: 0, failed: 0, results: [] };
1312
- }
1313
- const results: CreateProviderAccountBatchItemResult[] = [];
1314
- let created = 0;
1315
- let failed = 0;
1316
-
1317
- await this.db.transaction(async (tx) => {
1318
- let nextSortIndex = await this.nextAccountSortIndex(tx, providerId, tenantId);
1319
- for (const [index, request] of requests.entries()) {
1320
- try {
1321
- // A nested transaction acts as a savepoint: a duplicate-fingerprint
1322
- // violation rolls back only this item, not the accounts before it.
1323
- const account = await tx.transaction(async (inner) =>
1324
- this.createAccount(tenantId, providerId, request, inner, false, nextSortIndex),
1325
- );
1326
- created += 1;
1327
- nextSortIndex += 1;
1328
- results.push({ index, ok: true, ...(account ? { account } : {}) });
1329
- } catch (error) {
1330
- failed += 1;
1331
- results.push({
1332
- index,
1333
- ok: false,
1334
- error: error instanceof Error ? error.message : String(error),
1335
- code: error instanceof ConsoleDomainError ? error.code : "create_failed",
1336
- });
1337
- }
1338
- }
1339
- });
1340
-
1341
- return { created, failed, results };
1342
- }
1343
-
1344
- async updateAccount(
1345
- tenantId: string,
1346
- providerId: string,
1347
- accountId: string,
1348
- patch: UpdateProviderAccountRequest,
1349
- ): Promise<ProviderAccountResponse | undefined> {
1350
- const set: Partial<typeof providerAccounts.$inferInsert> = {};
1351
- if (patch.label !== undefined) set.label = patch.label;
1352
- if (patch.secret !== undefined) {
1353
- set.credentialCiphertext = encryptCredential(patch.secret);
1354
- set.credentialFingerprint =
1355
- patch.secret.length === 0 ? null : hashSecret(patch.secret);
1356
- }
1357
- if (patch.status !== undefined) set.status = patch.status;
1358
- // Toggling the static-token flag: turning it on declares the credential is
1359
- // used as issued and never refreshed, so any stale re-auth flag is cleared —
1360
- // the operator has said the account is fine, and the pill must stop reading
1361
- // "Re-login required". Turning it off returns the account to normal OAuth
1362
- // refresh handling; the sweep picks it up again on its next pass.
1363
- if (patch.staticToken !== undefined) {
1364
- set.staticToken = patch.staticToken;
1365
- if (patch.staticToken) {
1366
- set.lastError = null;
1367
- set.lastErrorCategory = null;
1368
- set.lastErrorAt = null;
1369
- }
1370
- }
1371
- // Status toggles are not recovery: preserve the health machine's evidence
1372
- // until the operator uses Recover or replaces the rejected credential.
1373
- const clearsFailureState = patch.secret !== undefined && patch.secret.length > 0;
1374
- if (clearsFailureState) {
1375
- set.consecutiveFailures = 0;
1376
- set.cooldownUntil = null;
1377
- set.modelCooldowns = {};
1378
- set.lastError = null;
1379
- set.lastErrorCategory = null;
1380
- set.lastErrorAt = null;
1381
- }
1382
- const where = and(
1383
- eq(providerAccounts.id, accountId),
1384
- eq(providerAccounts.providerId, providerId),
1385
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1386
- );
1387
- try {
1388
- const rows =
1389
- Object.keys(set).length > 0
1390
- ? await this.db.update(providerAccounts).set(set).where(where).returning()
1391
- : await this.db.select().from(providerAccounts).where(where);
1392
- const row = rows[0];
1393
- if (!row) return undefined;
1394
- // Secret/status mutation: drop any cached credential so the next
1395
- // attempt decrypts the new ciphertext (or refuses a disabled account).
1396
- if (patch.secret !== undefined || patch.status !== undefined) {
1397
- invalidateCredentialCache(accountId);
1398
- }
1399
- const [account] = await this.accountsWithUsage(tenantId, [row]);
1400
- return account;
1401
- } catch (error) {
1402
- if (isUniqueViolation(error)) {
1403
- throw new ConsoleDomainError(
1404
- "provider_account_duplicate",
1405
- 409,
1406
- "A provider account with this credential already exists",
1407
- );
1408
- }
1409
- throw error;
1410
- }
1411
- }
1412
-
1413
- private mapAccount(
1414
- row: typeof providerAccounts.$inferSelect,
1415
- usage: {
1416
- readonly today: ProviderAccountTokenUsage;
1417
- readonly allTime: ProviderAccountTokenUsage;
1418
- readonly inflight?: number | undefined;
1419
- },
1420
- ): ProviderAccountResponse {
1421
- const authState =
1422
- row.authState !== null && typeof row.authState === "object" && !Array.isArray(row.authState)
1423
- ? (row.authState as Record<string, unknown>)
1424
- : undefined;
1425
- const rawCredentialMode = authState?.["credentialMode"];
1426
- const credentialMode: CredentialMode | undefined =
1427
- rawCredentialMode === "auto" || rawCredentialMode === "jwt" || rawCredentialMode === "api_key"
1428
- ? rawCredentialMode
1429
- : undefined;
1430
- const tokenExpiresAt =
1431
- typeof authState?.["tokenExpiresAt"] === "string" ? authState["tokenExpiresAt"] : undefined;
1432
- const jwtIssuer =
1433
- typeof authState?.["jwtIssuer"] === "string" ? authState["jwtIssuer"] : undefined;
1434
- return {
1435
- id: row.id,
1436
- providerId: row.providerId,
1437
- tenantId: row.tenantId,
1438
- label: row.label,
1439
- credentialKind: row.credentialKind,
1440
- ...(credentialMode === undefined ? {} : { credentialMode }),
1441
- ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt }),
1442
- ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
1443
- status: row.status,
1444
- ...(usage.inflight === undefined ? {} : { inflight: usage.inflight }),
1445
- usageToday: usage.today,
1446
- usageAllTime: usage.allTime,
1447
- consecutiveFailures: row.consecutiveFailures,
1448
- ...(row.lastSuccessAt ? { lastSuccessAt: row.lastSuccessAt.toISOString() } : {}),
1449
- ...(row.lastError ? { lastError: row.lastError } : {}),
1450
- ...(row.lastErrorCategory ? { lastErrorCategory: row.lastErrorCategory } : {}),
1451
- ...(row.lastErrorAt ? { lastErrorAt: row.lastErrorAt.toISOString() } : {}),
1452
- ...(row.cooldownUntil ? { cooldownUntil: row.cooldownUntil.toISOString() } : {}),
1453
- ...(liveModelCooldowns(row.modelCooldowns) ?? {}),
1454
- ...(row.lastRecoveredAt ? { lastRecoveredAt: row.lastRecoveredAt.toISOString() } : {}),
1455
- createdAt: row.createdAt.toISOString(),
1456
- sortIndex: row.sortIndex,
1457
- ...(row.staticToken ? { staticToken: true } : {}),
1458
- };
1459
- }
1460
-
1461
- async listAccountHealthEvents(
1462
- tenantId: string,
1463
- providerId: string,
1464
- accountId: string,
1465
- ): Promise<readonly AccountHealthEventRecord[]> {
1466
- const owned = await this.db
1467
- .select({ id: providerAccounts.id })
1468
- .from(providerAccounts)
1469
- .where(
1470
- and(
1471
- eq(providerAccounts.id, accountId),
1472
- eq(providerAccounts.providerId, providerId),
1473
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1474
- ),
1475
- )
1476
- .limit(1);
1477
- if (owned.length === 0) return [];
1478
- return listAccountHealthEvents(this.db, accountId);
1479
- }
1480
-
1481
- /** Deletes one account's stored health & error rows, for the modal's purge. */
1482
- async purgeAccountHealthEvents(
1483
- tenantId: string,
1484
- providerId: string,
1485
- accountId: string,
1486
- ): Promise<number> {
1487
- const owned = await this.db
1488
- .select({ id: providerAccounts.id })
1489
- .from(providerAccounts)
1490
- .where(
1491
- and(
1492
- eq(providerAccounts.id, accountId),
1493
- eq(providerAccounts.providerId, providerId),
1494
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1495
- ),
1496
- )
1497
- .limit(1);
1498
- if (owned.length === 0) return 0;
1499
- return deleteAccountHealthEvents(this.db, accountId);
1500
- }
1501
- async listBuddyGrowthTasks(
1502
- tenantId: string,
1503
- providerId: string,
1504
- accountId: string,
1505
- dayKey: string,
1506
- ): Promise<readonly BuddyGrowthTaskLedgerEntry[]> {
1507
- const owned = await this.db
1508
- .select({ id: providerAccounts.id })
1509
- .from(providerAccounts)
1510
- .where(
1511
- and(
1512
- eq(providerAccounts.id, accountId),
1513
- eq(providerAccounts.providerId, providerId),
1514
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1515
- ),
1516
- )
1517
- .limit(1);
1518
- if (owned.length === 0) return [];
1519
- const rows = await this.db
1520
- .select({
1521
- accountId: buddyTaskLedger.accountId,
1522
- task: buddyTaskLedger.task,
1523
- claimedAt: buddyTaskLedger.claimedAt,
1524
- })
1525
- .from(buddyTaskLedger)
1526
- .where(
1527
- and(
1528
- eq(buddyTaskLedger.accountId, accountId),
1529
- eq(buddyTaskLedger.dayKey, dayKey),
1530
- ),
1531
- );
1532
- return rows.map((row) => ({
1533
- accountId: row.accountId,
1534
- task: row.task,
1535
- claimedAt: row.claimedAt.toISOString(),
1536
- }));
1537
- }
1538
-
1539
- async recoverAccount(
1540
- tenantId: string,
1541
- providerId: string,
1542
- accountId: string,
1543
- ): Promise<boolean> {
1544
- const owned = await this.db
1545
- .select({ id: providerAccounts.id })
1546
- .from(providerAccounts)
1547
- .where(
1548
- and(
1549
- eq(providerAccounts.id, accountId),
1550
- eq(providerAccounts.providerId, providerId),
1551
- globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1552
- ),
1553
- )
1554
- .limit(1);
1555
- if (owned.length === 0) return false;
1556
- return recoverAccount(this.db, accountId, "manual_operator_recovery");
1557
- }
1558
-
1559
-
1560
- async syncModels(tenantId: string, providerId: string): Promise<{ synced: number }> {
1561
- return this.probing.syncModels(tenantId, providerId);
1562
- }
1563
- }
1
+ // Drizzle-backed provider, account, model, routing, and API-key repositories.
2
+ import { and, asc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
3
+ import { ConsoleDomainError } from "../../shared/errors";
4
+ import { parseCustomProviderId, isBundledProviderId } from "../../../providers/provider-contracts";
5
+ import type { ModelDefinition } from "../../../providers/provider-model-definition";
6
+ import type { ProviderRegistry } from "../../../providers/provider-registry";
7
+ import { BUNDLED_PROVIDER_MODULES } from "../../../providers/default-registry";
8
+ import { globalOrOwnedBy, ownedByOnly } from "../../../persistence/tenant-scope";
9
+ import { nextSortIndex, reorderSortIndex } from "../../../persistence/sort-order";
10
+ import type { CartethyiaDatabase } from "../../../persistence/db-handle";
11
+ import { buddyTaskLedger, models, providerAccounts, providerOauthStates, providers, telemetryUsageTotals, tenantDisabledModels } from "../../../persistence/schema";
12
+ import { breakdownTelemetry } from "../../../observability/event-query";
13
+ import type { WireFamily } from "../../../protocol/canonical-model";
14
+ import { listAccountHealthEvents, recoverAccount, deleteAccountHealthEvents, type AccountHealthEventRecord } from "../../../providers/operations/account-health-service";
15
+ import { invalidateCredentialCache } from "../../../providers/operations/provider-credential-service";
16
+ import { encryptCredential, hashSecret } from "../../../security/crypto";
17
+ import type { TelemetryBatchBuffer } from "../../../observability/telemetry-buffer";
18
+ import { bumpCatalogRevision, type BundledProviderCatalog } from "../../../providers/operations/provider-catalog-service";
19
+ import type { AccountInflightReading, BuddyGrowthTaskLedgerEntry, ByokConnectionTestRequest, ByokConnectionTestResult, CreateProviderAccountBatchItemResult, CreateProviderAccountBatchResult, CreateProviderAccountRequest, CredentialMode, ModelCatalogEntry, ProbeAllAccountsResult, ProbeAllModelsResult, ProbeModelRequest, ProbeModelResult, ProviderAccountResponse, ProviderAccountTokenUsage, ProviderCatalogStore, ProviderRecord, SetModelEnabledRequest, UpdateModelMetadataRequest, UpdateProviderAccountRequest, ModelMetadataOverride } from "./contracts";
20
+ import { isServiceKind, validateCompatibilityProfile } from "./contracts";
21
+ import { ProviderProbingService, type ProbeOutboundResolver } from "../../../providers/discovery/probing-service";
22
+ import {
23
+ applyModelMetadataOverride,
24
+ resolveManualModelMetadata,
25
+ } from "../../../providers/provider-model-definition";
26
+ import { isUniqueViolation } from "../../../persistence/boot";
27
+ import { DEFAULT_ENDPOINT_BY_WIRE_FAMILY, endpointPathForProviderModel, mapProviderRow } from "./catalog-projections";
28
+ import { pushStructuredConsoleLog } from "../../../observability/log-ring";
29
+
30
+ /** Real Drizzle-backed provider and model catalog repository. */
31
+
32
+ import {
33
+ asStoredText,
34
+ liveModelCooldowns,
35
+ mapModelRow,
36
+ nextGeneratedAccountLabel,
37
+ parseJwtCredential,
38
+ parsePastedOAuthCredential,
39
+ withImageModality,
40
+ } from "./store-helpers";
41
+
42
+ export {
43
+ accountLabelKindSegment,
44
+ mapModelRow,
45
+ nextGeneratedAccountLabel,
46
+ withImageModality,
47
+ } from "./store-helpers";
48
+
49
+ export class DrizzleProviderCatalogStore implements ProviderCatalogStore {
50
+ private readonly probing: ProviderProbingService;
51
+ private readonly bundledModelCatalog: ReadonlyMap<string, readonly ModelDefinition[]>;
52
+ private readonly providerRegistry: ProviderRegistry;
53
+
54
+ private readonly readAccountInflight:
55
+ | ((
56
+ providerId: string,
57
+ tenantId: string,
58
+ ) => Promise<readonly AccountInflightReading[]>)
59
+ | undefined;
60
+
61
+ constructor(
62
+ private readonly db: CartethyiaDatabase,
63
+ options: {
64
+ readonly telemetryBuffer: TelemetryBatchBuffer;
65
+ readonly bundledModelCatalog: BundledProviderCatalog;
66
+ readonly providerRegistry: ProviderRegistry;
67
+ readonly outboundFetchFor: ProbeOutboundResolver;
68
+ readonly snapshotInvalidator: { invalidate(): unknown };
69
+ readonly readAccountInflight?:
70
+ | ((
71
+ providerId: string,
72
+ tenantId: string,
73
+ ) => Promise<readonly AccountInflightReading[]>)
74
+ | undefined;
75
+ },
76
+ ) {
77
+ this.bundledModelCatalog = options.bundledModelCatalog.modelsByProvider;
78
+ this.providerRegistry = options.providerRegistry;
79
+ this.readAccountInflight = options.readAccountInflight;
80
+ this.probing = new ProviderProbingService({
81
+ db,
82
+ telemetryBuffer: options.telemetryBuffer,
83
+ defaultEndpoints: DEFAULT_ENDPOINT_BY_WIRE_FAMILY,
84
+ bundledModelCatalog: this.bundledModelCatalog,
85
+ outboundFetchFor: options.outboundFetchFor,
86
+ snapshotInvalidator: options.snapshotInvalidator,
87
+ providerRegistry: options.providerRegistry,
88
+ });
89
+ }
90
+ async list(tenantId: string): Promise<readonly ProviderRecord[]> {
91
+ const bundledIds = BUNDLED_PROVIDER_MODULES.map((provider) => provider.id);
92
+ const rows = await this.db
93
+ .select()
94
+ .from(providers)
95
+ .where(
96
+ and(
97
+ globalOrOwnedBy(providers.tenantId, tenantId),
98
+ or(inArray(providers.id, bundledIds), eq(providers.tenantId, tenantId)),
99
+ ),
100
+ )
101
+ .orderBy(asc(providers.id));
102
+ return rows.map((row) => mapProviderRow(row, this.providerRegistry));
103
+ }
104
+ async get(tenantId: string, providerId: string): Promise<ProviderRecord | undefined> {
105
+ const rows = await this.db
106
+ .select()
107
+ .from(providers)
108
+ .where(
109
+ and(
110
+ eq(providers.id, providerId),
111
+ globalOrOwnedBy(providers.tenantId, tenantId),
112
+ ),
113
+ )
114
+ .limit(1);
115
+ const row = rows[0];
116
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
117
+ }
118
+ async create(record: ProviderRecord): Promise<void> {
119
+ if (isBundledProviderId(record.providerId))
120
+ throw new ConsoleDomainError(
121
+ "provider_is_builtin",
122
+ 403,
123
+ "Built-in provider cannot be created",
124
+ );
125
+ parseCustomProviderId(record.providerId);
126
+ if (record.compatibilityProfile) validateCompatibilityProfile(record.compatibilityProfile);
127
+ await this.db.insert(providers).values({
128
+ id: record.providerId,
129
+ tenantId: record.tenantId ?? null,
130
+ enabled: record.enabled,
131
+ ...(record.wireFamilyDefault ? { wireFamilyDefault: record.wireFamilyDefault } : {}),
132
+ capabilityProfile: record.capabilityProfile ?? null,
133
+ baseUrl: record.baseUrl ?? null,
134
+ compatibilityProfile: record.compatibilityProfile ?? null,
135
+ });
136
+ }
137
+ async update(
138
+ tenantId: string,
139
+ providerId: string,
140
+ patch: Partial<ProviderRecord>,
141
+ ): Promise<ProviderRecord | undefined> {
142
+ if (isBundledProviderId(providerId))
143
+ throw new ConsoleDomainError(
144
+ "provider_is_builtin",
145
+ 403,
146
+ "Built-in provider cannot be updated",
147
+ );
148
+ if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
149
+ const set: Partial<typeof providers.$inferInsert> = {};
150
+ if (patch.enabled !== undefined) set.enabled = patch.enabled;
151
+ if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
152
+ if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
153
+ if (patch.compatibilityProfile !== undefined)
154
+ set.compatibilityProfile = patch.compatibilityProfile;
155
+ const rows =
156
+ Object.keys(set).length > 0
157
+ ? await this.db
158
+ .update(providers)
159
+ .set(set)
160
+ .where(
161
+ and(
162
+ eq(providers.id, providerId),
163
+ ownedByOnly(providers.tenantId, tenantId),
164
+ ),
165
+ )
166
+ .returning()
167
+ : await this.db
168
+ .select()
169
+ .from(providers)
170
+ .where(
171
+ and(
172
+ eq(providers.id, providerId),
173
+ ownedByOnly(providers.tenantId, tenantId),
174
+ ),
175
+ );
176
+ const row = rows[0];
177
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
178
+ }
179
+ async delete(tenantId: string, providerId: string): Promise<boolean> {
180
+ if (isBundledProviderId(providerId))
181
+ throw new ConsoleDomainError(
182
+ "provider_is_builtin",
183
+ 403,
184
+ "Built-in provider cannot be deleted",
185
+ );
186
+ // Custom-provider rows own their models, accounts, disabled-model flags,
187
+ // and routing preferences: deleting the parent cascades all of them
188
+ // (models/provider_accounts/provider_oauth_states via provider FK,
189
+ // health_events via account FK, tenant_disabled_models and
190
+ // provider_routing_settings via provider FK) in one atomic DELETE.
191
+ const deleted = await this.db
192
+ .delete(providers)
193
+ .where(and(eq(providers.id, providerId), ownedByOnly(providers.tenantId, tenantId)))
194
+ .returning({ id: providers.id });
195
+ if (deleted.length === 0) return false;
196
+ this.providerRegistry.unregister(providerId);
197
+ // The provider left the registry, so the compiled catalog is now missing it
198
+ // — the snapshot's re-seed is gated on that revision, and a delete that did
199
+ // not bump it would leave the provider's model rows behind.
200
+ bumpCatalogRevision();
201
+ return true;
202
+ }
203
+ async updateGlobal(
204
+ providerId: string,
205
+ patch: Partial<ProviderRecord>,
206
+ ): Promise<ProviderRecord | undefined> {
207
+ const isBuiltin = isBundledProviderId(providerId);
208
+ if (isBuiltin && Object.keys(patch).some((field) => field !== "enabled")) {
209
+ throw new ConsoleDomainError(
210
+ "provider_is_builtin",
211
+ 403,
212
+ "Built-in providers only support enable/disable",
213
+ );
214
+ }
215
+ if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
216
+ const set: Partial<typeof providers.$inferInsert> = {};
217
+ if (patch.enabled !== undefined) set.enabled = patch.enabled;
218
+ if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
219
+ if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
220
+ if (patch.compatibilityProfile !== undefined) {
221
+ set.compatibilityProfile = patch.compatibilityProfile;
222
+ }
223
+ const rows =
224
+ Object.keys(set).length > 0
225
+ ? await this.db
226
+ .update(providers)
227
+ .set(set)
228
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
229
+ .returning()
230
+ : await this.db
231
+ .select()
232
+ .from(providers)
233
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)));
234
+ const row = rows[0];
235
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
236
+ }
237
+
238
+ async deleteGlobal(providerId: string): Promise<boolean> {
239
+ if (isBundledProviderId(providerId)) {
240
+ throw new ConsoleDomainError(
241
+ "provider_is_builtin",
242
+ 403,
243
+ "Built-in provider cannot be deleted",
244
+ );
245
+ }
246
+ const rows = await this.db
247
+ .delete(providers)
248
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
249
+ .returning({ id: providers.id });
250
+ return rows.length > 0;
251
+ }
252
+ async listModels(tenantId: string, providerId: string): Promise<readonly ModelCatalogEntry[]> {
253
+ const byProvider = await this.listModelsForTenant(tenantId, providerId);
254
+ return byProvider.get(providerId) ?? [];
255
+ }
256
+
257
+ /**
258
+ * Every enabled-and-disabled model row the tenant can see, grouped by
259
+ * provider. One pair of statements for the whole tenant instead of a pair per
260
+ * provider.
261
+ *
262
+ * The per-provider `listModels` shape costs two queries per call, so a caller
263
+ * that needs every provider's models — the flat catalog the picker renders —
264
+ * issued `2 * providers + 2` statements, growing with the bundled catalog.
265
+ * Grouping here makes it constant: one disabled-model read and one models
266
+ * join, regardless of provider count. `providerId` narrows it to a single
267
+ * provider for callers that already know which one they want.
268
+ */
269
+ async listModelsForTenant(
270
+ tenantId: string,
271
+ providerId?: string,
272
+ ): Promise<Map<string, readonly ModelCatalogEntry[]>> {
273
+ const disabled = await this.db
274
+ .select({
275
+ providerId: tenantDisabledModels.providerId,
276
+ modelId: tenantDisabledModels.modelId,
277
+ endpointPath: tenantDisabledModels.endpointPath,
278
+ })
279
+ .from(tenantDisabledModels)
280
+ .where(
281
+ providerId === undefined
282
+ ? eq(tenantDisabledModels.tenantId, tenantId)
283
+ : and(
284
+ eq(tenantDisabledModels.tenantId, tenantId),
285
+ eq(tenantDisabledModels.providerId, providerId),
286
+ ),
287
+ );
288
+ const disabledKeys = new Set(
289
+ disabled.map((d) => `${d.providerId}::${d.modelId}::${d.endpointPath}`),
290
+ );
291
+ const dbRows = await this.db
292
+ .select({ model: models })
293
+ .from(models)
294
+ .innerJoin(providers, eq(models.providerId, providers.id))
295
+ .where(
296
+ and(
297
+ ...(providerId === undefined ? [] : [eq(models.providerId, providerId)]),
298
+ globalOrOwnedBy(providers.tenantId, tenantId),
299
+ ),
300
+ );
301
+ const grouped = new Map<string, ModelCatalogEntry[]>();
302
+ for (const { model: row } of dbRows) {
303
+ const isDisabled = disabledKeys.has(
304
+ `${row.providerId}::${row.modelId}::${row.endpointPath}`,
305
+ );
306
+ const list = grouped.get(row.providerId) ?? [];
307
+ list.push(mapModelRow(row, isDisabled));
308
+ grouped.set(row.providerId, list);
309
+ }
310
+ return grouped;
311
+ }
312
+ async registerModels(
313
+ tenantId: string,
314
+ providerId: string,
315
+ modelIds: readonly string[],
316
+ wireFamily?: string,
317
+ metadata?: ModelMetadataOverride,
318
+ ): Promise<void> {
319
+ const owner = await this.db
320
+ .select({
321
+ id: providers.id,
322
+ baseUrl: providers.baseUrl,
323
+ compatibilityProfile: providers.compatibilityProfile,
324
+ })
325
+ .from(providers)
326
+ .where(and(eq(providers.id, providerId), globalOrOwnedBy(providers.tenantId, tenantId)))
327
+ .limit(1);
328
+ if (!owner[0]) {
329
+ throw new ConsoleDomainError("provider_not_found", 404, `Provider ${providerId} not found`);
330
+ }
331
+ const family = (wireFamily ?? "chat") as WireFamily;
332
+ // Static endpoint from the provider's own bundled catalog via the probing
333
+ // service (the same startup-built map this store is constructed with).
334
+ // Without this, bundled providers on versioned bases (cline) get the
335
+ // generic `/v1/…` default, which joins into an unreachable path and every
336
+ // probe/dispatch 404s.
337
+ const staticEndpoint = await this.probing.resolveStaticEndpoint(providerId, family);
338
+ const endpointPath = endpointPathForProviderModel(
339
+ family,
340
+ owner[0].compatibilityProfile,
341
+ staticEndpoint === undefined ? undefined : { [family]: staticEndpoint },
342
+ );
343
+ if (modelIds.length === 0) return;
344
+ // Single multi-row insert and upsert of the capability flags so a
345
+ // re-registration repairs a row whose `tool_call` (and `reasoning`) was
346
+ // seeded false — a manual add persists schema defaults, which capability
347
+ // preflight reads as "route cannot use tools" and silently strips `tools`
348
+ // from every request. `enabled` stays operator-owned; `source` is refreshed
349
+ // to `manual`.
350
+ await this.db
351
+ .insert(models)
352
+ .values(
353
+ modelIds.map((modelId) => ({
354
+ providerId,
355
+ modelId,
356
+ wireFamily: family,
357
+ endpointPath,
358
+ ...applyModelMetadataOverride(
359
+ resolveManualModelMetadata(providerId, modelId),
360
+ metadata,
361
+ ),
362
+ source: "manual",
363
+ sourceUpdatedAt: new Date(),
364
+ enabled: true,
365
+ })),
366
+ )
367
+ .onConflictDoUpdate({
368
+ target: [models.providerId, models.modelId, models.endpointPath],
369
+ set: {
370
+ wireFamily: sql`excluded.wire_family`,
371
+ contextLimit: sql`excluded.context_limit`,
372
+ outputLimit: sql`excluded.output_limit`,
373
+ modalities: sql`excluded.modalities`,
374
+ reasoning: sql`excluded.reasoning`,
375
+ toolCall: sql`excluded.tool_call`,
376
+ source: sql`'manual'`,
377
+ sourceUpdatedAt: sql`excluded.source_updated_at`,
378
+ },
379
+ });
380
+ }
381
+
382
+ /**
383
+ * One-shot connectivity probe and model discovery live in
384
+ * `services/provider-probing.ts` — the store only forwards so the domain
385
+ * `ProviderCatalogStore` interface is unchanged.
386
+ */
387
+ async probeModel(
388
+ tenantId: string,
389
+ providerId: string,
390
+ request: ProbeModelRequest,
391
+ ): Promise<ProbeModelResult> {
392
+ return this.probing.probeModel(tenantId, providerId, request);
393
+ }
394
+
395
+ /** Ad-hoc BYOK connectivity test; delegates to the shared probing service. */
396
+ async testByokConnection(
397
+ tenantId: string,
398
+ request: ByokConnectionTestRequest,
399
+ ): Promise<ByokConnectionTestResult> {
400
+ return this.probing.testByokConnection(tenantId, request);
401
+ }
402
+
403
+ /**
404
+ * Batched provider-wide probe: the first registered model runs sequentially
405
+ * (warms OAuth token / connection pools), the rest run concurrently bounded
406
+ * to 5. Registered model ids come from this store's own catalog read.
407
+ */
408
+ async probeAllModels(tenantId: string, providerId: string): Promise<ProbeAllModelsResult> {
409
+ const entries = await this.listModels(tenantId, providerId);
410
+ const requests = entries.map((entry) => ({
411
+ modelId: entry.modelId,
412
+ route: entry.route,
413
+ serviceKind: isServiceKind(entry.serviceKind) ? entry.serviceKind : ("llm" as const),
414
+ }));
415
+ const uniqueRequests = requests.filter(
416
+ (request, index, all) =>
417
+ all.findIndex(
418
+ (candidate) =>
419
+ candidate.modelId === request.modelId &&
420
+ candidate.route === request.route &&
421
+ candidate.serviceKind === request.serviceKind,
422
+ ) === index,
423
+ );
424
+ return this.probing.probeAllModels(tenantId, providerId, uniqueRequests);
425
+ }
426
+ async probeAllAccounts(
427
+ tenantId: string,
428
+ providerId: string,
429
+ request: ProbeModelRequest,
430
+ ): Promise<ProbeAllAccountsResult> {
431
+ return this.probing.probeAllAccounts(tenantId, providerId, request);
432
+ }
433
+ /** Toggles a persisted model's routing eligibility. */
434
+ async setModelEnabled(
435
+ tenantId: string,
436
+ providerId: string,
437
+ request: SetModelEnabledRequest,
438
+ ): Promise<boolean> {
439
+ // Tenant-owned (BYOK) model: toggle the shared row directly.
440
+ const owned = await this.db
441
+ .select({ id: models.id })
442
+ .from(models)
443
+ .innerJoin(providers, eq(models.providerId, providers.id))
444
+ .where(
445
+ and(
446
+ eq(models.providerId, providerId),
447
+ eq(models.modelId, request.modelId),
448
+ eq(models.endpointPath, request.route),
449
+ ownedByOnly(providers.tenantId, tenantId),
450
+ ),
451
+ )
452
+ .limit(1);
453
+ const ownedTarget = owned[0];
454
+ if (ownedTarget) {
455
+ await this.db
456
+ .update(models)
457
+ .set({ enabled: request.enabled })
458
+ .where(eq(models.id, ownedTarget.id));
459
+ return true;
460
+ }
461
+
462
+ // Global/built-in model: tenants cannot mutate the shared row, so record
463
+ // (or clear) a tenant-scoped disable in `tenantDisabledModels`.
464
+ const global = await this.db
465
+ .select({ id: models.id })
466
+ .from(models)
467
+ .innerJoin(providers, eq(models.providerId, providers.id))
468
+ .where(
469
+ and(
470
+ eq(models.providerId, providerId),
471
+ eq(models.modelId, request.modelId),
472
+ eq(models.endpointPath, request.route),
473
+ isNull(providers.tenantId),
474
+ ),
475
+ )
476
+ .limit(1);
477
+ if (global[0] === undefined) return false;
478
+ if (request.enabled) {
479
+ await this.db
480
+ .delete(tenantDisabledModels)
481
+ .where(
482
+ and(
483
+ eq(tenantDisabledModels.tenantId, tenantId),
484
+ eq(tenantDisabledModels.providerId, providerId),
485
+ eq(tenantDisabledModels.modelId, request.modelId),
486
+ eq(tenantDisabledModels.endpointPath, request.route),
487
+ ),
488
+ );
489
+ return true;
490
+ }
491
+ await this.db
492
+ .insert(tenantDisabledModels)
493
+ .values({
494
+ tenantId,
495
+ providerId,
496
+ modelId: request.modelId,
497
+ endpointPath: request.route,
498
+ })
499
+ .onConflictDoNothing({
500
+ target: [
501
+ tenantDisabledModels.tenantId,
502
+ tenantDisabledModels.providerId,
503
+ tenantDisabledModels.modelId,
504
+ tenantDisabledModels.endpointPath,
505
+ ],
506
+ });
507
+ return true;
508
+ }
509
+
510
+ /**
511
+ * Updates one model's limits and capability flags.
512
+ *
513
+ * Two row kinds are writable. A tenant-owned (BYOK) row is updated directly.
514
+ * A model belonging to a *global* provider row is also updated directly:
515
+ * bundled providers are seeded once with `tenant_id IS NULL` and `providers.id`
516
+ * is the primary key, so a bundled provider can only ever have that one row —
517
+ * there is no tenant-scoped row to edit instead. Auto-fetched rows
518
+ * (`discovered` / `auto_free`) live on exactly those providers, which is why
519
+ * the previous `ownedByOnly` filter answered `not_found` for every model the
520
+ * operator had just fetched and could not be edited at all.
521
+ *
522
+ * A global `builtin` row is rejected: it is re-seeded from the bundle on every
523
+ * boot, so an edit there would be silently reverted, and `deleteModel` refuses
524
+ * it for the same reason.
525
+ *
526
+ * Absent override fields leave the stored value untouched — an edit that only
527
+ * sets the context ceiling must not reset the capability flags.
528
+ */
529
+ async updateModelMetadata(
530
+ tenantId: string,
531
+ providerId: string,
532
+ request: UpdateModelMetadataRequest,
533
+ ): Promise<boolean> {
534
+ const findRow = (ownership: SQL) =>
535
+ this.db
536
+ .select({ id: models.id, modalities: models.modalities, source: models.source })
537
+ .from(models)
538
+ .innerJoin(providers, eq(models.providerId, providers.id))
539
+ .where(
540
+ and(
541
+ eq(models.providerId, providerId),
542
+ eq(models.modelId, request.modelId),
543
+ eq(models.endpointPath, request.route),
544
+ ownership,
545
+ ),
546
+ )
547
+ .limit(1);
548
+ const owned = await findRow(ownedByOnly(providers.tenantId, tenantId));
549
+ let row = owned[0];
550
+ if (row === undefined) {
551
+ const global = await findRow(isNull(providers.tenantId));
552
+ const candidate = global[0];
553
+ if (candidate === undefined) return false;
554
+ if (candidate.source === "builtin") {
555
+ throw new ConsoleDomainError(
556
+ "builtin_model_immutable",
557
+ 403,
558
+ `Built-in model ${providerId}/${request.modelId} cannot be edited — the bundle re-seeds it on every boot`,
559
+ );
560
+ }
561
+ row = candidate;
562
+ }
563
+
564
+ const override = request.metadata;
565
+ const set: Record<string, unknown> = { sourceUpdatedAt: new Date() };
566
+ if (override?.contextLimit !== undefined) set.contextLimit = override.contextLimit;
567
+ if (override?.outputLimit !== undefined) set.outputLimit = override.outputLimit;
568
+ // Passthrough grants every capability and cannot be partly revoked by a
569
+ // per-flag field: the point of the flag is that the operator does not know
570
+ // which capabilities the model has, so an explicit `false` alongside it is
571
+ // either stale or a mistake.
572
+ if (override?.passthrough === true) {
573
+ set.reasoning = true;
574
+ set.toolCall = true;
575
+ set.modalities = withImageModality(asStoredText(row.modalities), true);
576
+ } else {
577
+ if (override?.reasoning !== undefined) set.reasoning = override.reasoning;
578
+ if (override?.toolCall !== undefined) set.toolCall = override.toolCall;
579
+ if (override?.image !== undefined)
580
+ set.modalities = withImageModality(asStoredText(row.modalities), override.image);
581
+ }
582
+ await this.db.update(models).set(set).where(eq(models.id, row.id));
583
+ return true;
584
+ }
585
+
586
+ async deleteModel(
587
+ tenantId: string,
588
+ providerId: string,
589
+ request: SetModelEnabledRequest,
590
+ ): Promise<boolean> {
591
+ const owned = await this.db
592
+ .select({ id: models.id })
593
+ .from(models)
594
+ .innerJoin(providers, eq(models.providerId, providers.id))
595
+ .where(
596
+ and(
597
+ eq(models.providerId, providerId),
598
+ eq(models.modelId, request.modelId),
599
+ eq(models.endpointPath, request.route),
600
+ ownedByOnly(providers.tenantId, tenantId),
601
+ ),
602
+ )
603
+ .limit(1);
604
+ const target = owned[0];
605
+ if (target) {
606
+ const rows = await this.db
607
+ .delete(models)
608
+ .where(eq(models.id, target.id))
609
+ .returning({ id: models.id });
610
+ return rows.length > 0;
611
+ }
612
+ const global = await this.db
613
+ .select({ id: models.id, source: models.source })
614
+ .from(models)
615
+ .innerJoin(providers, eq(models.providerId, providers.id))
616
+ .where(
617
+ and(
618
+ eq(models.providerId, providerId),
619
+ eq(models.modelId, request.modelId),
620
+ eq(models.endpointPath, request.route),
621
+ isNull(providers.tenantId),
622
+ ),
623
+ )
624
+ .limit(1);
625
+ if (!global[0]) return false;
626
+ // Built-in models are immutable catalog: tenants can only disable them
627
+ // (via tenantDisabledModels), never delete the shared row.
628
+ if (global[0].source === "builtin") {
629
+ throw new ConsoleDomainError(
630
+ "builtin_model_immutable",
631
+ 403,
632
+ `Built-in model ${providerId}/${request.modelId} cannot be deleted — disable it instead`,
633
+ );
634
+ }
635
+ const rows = await this.db
636
+ .delete(models)
637
+ .where(eq(models.id, global[0].id))
638
+ .returning({ id: models.id });
639
+ await this.db
640
+ .delete(tenantDisabledModels)
641
+ .where(
642
+ and(
643
+ eq(tenantDisabledModels.tenantId, tenantId),
644
+ eq(tenantDisabledModels.providerId, providerId),
645
+ eq(tenantDisabledModels.modelId, request.modelId),
646
+ eq(tenantDisabledModels.endpointPath, request.route),
647
+ ),
648
+ );
649
+ return rows.length > 0;
650
+ }
651
+
652
+ private async accountsWithUsage(
653
+ tenantId: string,
654
+ rows: readonly (typeof providerAccounts.$inferSelect)[],
655
+ ): Promise<readonly ProviderAccountResponse[]> {
656
+ if (rows.length === 0) return [];
657
+ const todayStart = new Date();
658
+ todayStart.setUTCHours(0, 0, 0, 0);
659
+ const accountIds = rows.map((row) => row.id);
660
+ // Today's per-account usage is one GROUP BY, not a read of every event
661
+ // since midnight. `breakdownTelemetry("account")` is capped at 100 groups;
662
+ // a page of accounts never exceeds it, and the lookup below is by id, so a
663
+ // group that fell outside the cap simply reads as "no usage today" — the
664
+ // same value an account with no traffic gets.
665
+ const todayGroups = await breakdownTelemetry(this.db, tenantId, "account", todayStart);
666
+ const todayByAccount = new Map(
667
+ todayGroups.map((group) => [
668
+ group.key,
669
+ {
670
+ requests: group.requests,
671
+ errors: group.errors,
672
+ inputTokens: group.inputTokens,
673
+ outputTokens: group.outputTokens,
674
+ },
675
+ ]),
676
+ );
677
+ const [lifetimeRows] = await Promise.all([
678
+ this.db
679
+ .select()
680
+ .from(telemetryUsageTotals)
681
+ .where(
682
+ and(
683
+ eq(telemetryUsageTotals.tenantId, tenantId),
684
+ eq(telemetryUsageTotals.identityType, "account"),
685
+ inArray(telemetryUsageTotals.entityId, accountIds),
686
+ ),
687
+ ),
688
+ ]);
689
+ const lifetimeByAccount = new Map(lifetimeRows.map((row) => [row.entityId, row]));
690
+ const mapUsage = (row: {
691
+ readonly requests: number | string | null;
692
+ readonly errors: number | string | null;
693
+ readonly inputTokens: number | string | null;
694
+ readonly outputTokens: number | string | null;
695
+ } | undefined): ProviderAccountTokenUsage => {
696
+ const inputTokens = Number(row?.inputTokens ?? 0);
697
+ const outputTokens = Number(row?.outputTokens ?? 0);
698
+ return {
699
+ requests: Number(row?.requests ?? 0),
700
+ errors: Number(row?.errors ?? 0),
701
+ inputTokens,
702
+ outputTokens,
703
+ totalTokens: inputTokens + outputTokens,
704
+ };
705
+ };
706
+ const first = rows[0];
707
+ const inflightByAccount = await this.accountInflightFor(tenantId, first?.providerId);
708
+ return rows.map((row) => {
709
+ const inflight = inflightByAccount.get(row.id);
710
+ return this.mapAccount(row, {
711
+ today: mapUsage(todayByAccount.get(row.id)),
712
+ allTime: mapUsage(lifetimeByAccount.get(row.id)),
713
+ ...(inflight === undefined ? {} : { inflight }),
714
+ });
715
+ });
716
+ }
717
+
718
+ private async accountInflightFor(
719
+ tenantId: string,
720
+ providerId: string | undefined,
721
+ ): Promise<Map<string, number>> {
722
+ const readings = new Map<string, number>();
723
+ if (!this.readAccountInflight || !providerId) return readings;
724
+ const rows = await this.readAccountInflight(providerId, tenantId);
725
+ for (const row of rows) {
726
+ if (typeof row.accountId !== "string" || !Number.isFinite(row.inflight)) continue;
727
+ readings.set(row.accountId, Math.max(0, Math.floor(row.inflight)));
728
+ }
729
+ return readings;
730
+ }
731
+
732
+ /**
733
+ * Next free list position for a new account in this provider's list.
734
+ *
735
+ * Scoped to (provider, tenant) because the list is per provider: a tenant
736
+ * with accounts under two providers must not have the second provider's
737
+ * first account land at a high index.
738
+ */
739
+ /**
740
+ * Labels already in use for one provider, for numbering a generated name.
741
+ *
742
+ * Scoped to this provider and tenant: `dcint-key-1` and `other-key-1` belong
743
+ * to different providers and must not collide with each other.
744
+ */
745
+ private async generateAccountLabel(
746
+ db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
747
+ providerId: string,
748
+ tenantId: string,
749
+ credentialMode: CredentialMode,
750
+ ): Promise<string> {
751
+ const rows = await db
752
+ .select({ label: providerAccounts.label })
753
+ .from(providerAccounts)
754
+ .where(
755
+ and(
756
+ eq(providerAccounts.providerId, providerId),
757
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
758
+ ),
759
+ );
760
+ return nextGeneratedAccountLabel(
761
+ providerId,
762
+ credentialMode,
763
+ rows.map((row) => row.label).filter((label): label is string => typeof label === "string"),
764
+ );
765
+ }
766
+
767
+ private async nextAccountSortIndex(
768
+ db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
769
+ providerId: string,
770
+ tenantId: string,
771
+ ): Promise<number> {
772
+ return nextSortIndex(
773
+ db,
774
+ { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
775
+ and(
776
+ eq(providerAccounts.providerId, providerId),
777
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
778
+ ),
779
+ );
780
+ }
781
+
782
+ /** Rewrites one provider's account order; `accountIds` is the full order. */
783
+ async reorderAccounts(
784
+ tenantId: string,
785
+ providerId: string,
786
+ accountIds: readonly string[],
787
+ ): Promise<void> {
788
+ await reorderSortIndex(
789
+ this.db,
790
+ { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
791
+ and(
792
+ eq(providerAccounts.providerId, providerId),
793
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
794
+ ),
795
+ accountIds,
796
+ );
797
+ }
798
+
799
+ async listAccountAuthStates(
800
+ tenantId: string,
801
+ providerId: string,
802
+ accountIds: readonly string[],
803
+ ): Promise<Readonly<Record<string, Readonly<Record<string, unknown>>>>> {
804
+ if (accountIds.length === 0) return {};
805
+ const rows = await this.db
806
+ .select({ id: providerAccounts.id, authState: providerAccounts.authState })
807
+ .from(providerAccounts)
808
+ .where(
809
+ and(
810
+ eq(providerAccounts.providerId, providerId),
811
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
812
+ inArray(providerAccounts.id, accountIds),
813
+ ),
814
+ );
815
+ const out: Record<string, Readonly<Record<string, unknown>>> = {};
816
+ for (const row of rows) {
817
+ if (row.authState !== null && typeof row.authState === "object" && !Array.isArray(row.authState)) {
818
+ out[row.id] = row.authState as Record<string, unknown>;
819
+ }
820
+ }
821
+ return out;
822
+ }
823
+
824
+ async listAccounts(
825
+ tenantId: string,
826
+ providerId: string,
827
+ ): Promise<readonly ProviderAccountResponse[]> {
828
+ const rows = await this.db
829
+ .select()
830
+ .from(providerAccounts)
831
+ .where(
832
+ and(
833
+ eq(providerAccounts.providerId, providerId),
834
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
835
+ ),
836
+ )
837
+ // Stable list position, not `created_at`: two accounts created in the
838
+ // same millisecond could swap between loads. `id` breaks a tie so the
839
+ // order is total even before a reorder assigns distinct indices.
840
+ .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
841
+ return this.accountsWithUsage(tenantId, rows);
842
+ }
843
+
844
+ async listAllAccounts(tenantId: string): Promise<readonly ProviderAccountResponse[]> {
845
+ const rows = await this.db
846
+ .select()
847
+ .from(providerAccounts)
848
+ .where(globalOrOwnedBy(providerAccounts.tenantId, tenantId))
849
+ .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
850
+ return this.accountsWithUsage(tenantId, rows);
851
+ }
852
+
853
+ async createAccount(
854
+ tenantId: string,
855
+ providerId: string,
856
+ request: CreateProviderAccountRequest,
857
+ existingTx?: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
858
+ includeUsage = true,
859
+ sortIndexOverride?: number,
860
+ ): Promise<ProviderAccountResponse> {
861
+ // Callers inside an existing transaction pass it in so the account lands in
862
+ // that unit of work (the batch path); otherwise this opens its own.
863
+ const run = async (
864
+ tx: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
865
+ ): Promise<ProviderAccountResponse> => {
866
+ let effectiveSecret = request.secret;
867
+ let effectiveCredentialKind = request.credentialKind;
868
+ const requestedCredentialMode: CredentialMode = request.credentialMode ?? "auto";
869
+ let effectiveCredentialMode: CredentialMode = requestedCredentialMode;
870
+ let tokenExpiresAt: Date | undefined;
871
+ let jwtIssuer: string | undefined;
872
+ let oauthRefreshCiphertext: Buffer | undefined;
873
+ let oauthExpiresAt: Date | undefined;
874
+ let oauthHasRefreshToken = false;
875
+ let pastedAuthState: Readonly<Record<string, unknown>> = {};
876
+
877
+ if (
878
+ (request.credentialKind === "oauth" || request.credentialKind === "api_key") &&
879
+ request.secret.trim().length > 0
880
+ ) {
881
+ const trimmed = request.secret.trim();
882
+ const parts = parsePastedOAuthCredential(trimmed);
883
+ pastedAuthState = parts.authState;
884
+ const hasRefreshToken = parts.refreshToken !== parts.accessToken;
885
+ const parsedJwt =
886
+ requestedCredentialMode === "api_key"
887
+ ? undefined
888
+ : parseJwtCredential(parts.accessToken);
889
+ if (requestedCredentialMode === "jwt" && parsedJwt === undefined) {
890
+ throw new ConsoleDomainError(
891
+ "invalid_request",
892
+ 400,
893
+ "credentialMode jwt requires a valid three-part JWT",
894
+ );
895
+ }
896
+ if (requestedCredentialMode === "api_key") {
897
+ effectiveSecret = parts.accessToken;
898
+ effectiveCredentialKind = "api_key";
899
+ effectiveCredentialMode = "api_key";
900
+ } else if (
901
+ parsedJwt !== undefined &&
902
+ (requestedCredentialMode === "jwt" || !hasRefreshToken)
903
+ ) {
904
+ effectiveSecret = parts.accessToken;
905
+ effectiveCredentialKind = "api_key";
906
+ effectiveCredentialMode = "jwt";
907
+ tokenExpiresAt = parsedJwt.expiresAt;
908
+ // Kept alongside the expiry: the console shows who issued a static
909
+ // token, and the secret itself is never readable after this point.
910
+ jwtIssuer = parsedJwt.issuer;
911
+ } else if (request.credentialKind === "oauth" || hasRefreshToken) {
912
+ effectiveSecret = parts.accessToken;
913
+ effectiveCredentialKind = hasRefreshToken ? "oauth" : "api_key";
914
+ effectiveCredentialMode = hasRefreshToken ? "auto" : "api_key";
915
+ if (hasRefreshToken) {
916
+ oauthRefreshCiphertext = encryptCredential(parts.refreshToken);
917
+ oauthHasRefreshToken = true;
918
+ }
919
+ oauthExpiresAt = parts.expiresAt;
920
+ } else {
921
+ effectiveCredentialMode = "api_key";
922
+ }
923
+ }
924
+
925
+ // Append to the end of this provider's list rather than relying on
926
+ // creation time, so a new account never displaces existing positions.
927
+ const credentialFingerprint =
928
+ effectiveCredentialKind === "none" || effectiveSecret.length === 0
929
+ ? undefined
930
+ : hashSecret(effectiveSecret);
931
+ const accountAuthState = {
932
+ ...pastedAuthState,
933
+ ...(request.authState ?? {}),
934
+ credentialMode: effectiveCredentialMode,
935
+ ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt: tokenExpiresAt.toISOString() }),
936
+ ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
937
+ };
938
+ const nextSortIndex =
939
+ sortIndexOverride ?? (await this.nextAccountSortIndex(tx, providerId, tenantId));
940
+ // Read existing labels only when one has to be generated: a named
941
+ // account costs no extra query, and this is the path a large batch
942
+ // paste walks once per row.
943
+ const label =
944
+ request.label ??
945
+ (await this.generateAccountLabel(tx, providerId, tenantId, effectiveCredentialMode));
946
+ const rows = await tx
947
+ .insert(providerAccounts)
948
+ .values({
949
+ providerId,
950
+ tenantId,
951
+ sortIndex: nextSortIndex,
952
+ label,
953
+ credentialCiphertext: encryptCredential(effectiveSecret),
954
+ ...(credentialFingerprint ? { credentialFingerprint } : {}),
955
+ credentialKind: effectiveCredentialKind,
956
+ status: "active",
957
+ authState: accountAuthState,
958
+ // An OAuth account pasted without a refresh token is a *static*
959
+ // token: the pasted value is a bearer token used exactly as issued
960
+ // and there is no refresh grant to run. Flag it as static so the
961
+ // console reads it as an informational "static token" rather than
962
+ // "re-login required" — the token is still valid and dispatchable —
963
+ // and so the refresh sweep skips it instead of retrying a refresh
964
+ // that can never succeed.
965
+ ...(effectiveCredentialKind === "oauth" && !oauthHasRefreshToken || effectiveCredentialMode === "jwt"
966
+ ? { staticToken: true }
967
+ : {}),
968
+ })
969
+ .returning();
970
+ const row = rows[0];
971
+ if (!row) throw new Error("failed to create provider account");
972
+
973
+ if (effectiveCredentialKind === "oauth") {
974
+ await tx.insert(providerOauthStates).values({
975
+ providerAccountId: row.id,
976
+ ...(oauthRefreshCiphertext ? { refreshCiphertext: oauthRefreshCiphertext } : {}),
977
+ expiresAt: oauthExpiresAt ?? null,
978
+ });
979
+ }
980
+ if (request.credentialKind === "oauth" && !oauthHasRefreshToken) {
981
+ pushStructuredConsoleLog(
982
+ "info",
983
+ "OAuth access token stored as a static API credential; it will not be refreshed",
984
+ {
985
+ event: "token_refresh",
986
+ providerId,
987
+ accountId: row.id,
988
+ errorCode: "static_token",
989
+ },
990
+ );
991
+ }
992
+
993
+ if (!includeUsage) {
994
+ const emptyUsage = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };
995
+ return this.mapAccount(row, { today: emptyUsage, allTime: emptyUsage });
996
+ }
997
+ const [account] = await this.accountsWithUsage(tenantId, [row]);
998
+ if (!account) throw new Error("created provider account could not be mapped");
999
+ return account;
1000
+ };
1001
+
1002
+ try {
1003
+ if (existingTx !== undefined) {
1004
+ return await run(existingTx);
1005
+ }
1006
+ return await this.db.transaction(run);
1007
+ } catch (error) {
1008
+ if (isUniqueViolation(error)) {
1009
+ throw new ConsoleDomainError(
1010
+ "provider_account_duplicate",
1011
+ 409,
1012
+ "A provider account with this credential already exists",
1013
+ );
1014
+ }
1015
+ throw error;
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * Creates many accounts in one round-trip.
1021
+ *
1022
+ * The whole batch shares one transaction, so a paste of 40 credentials costs
1023
+ * one connection checkout rather than 40. Each item is created through the
1024
+ * same `createAccount` path the single route uses — there is no second
1025
+ * implementation of credential detection to drift.
1026
+ *
1027
+ * Items are created sequentially inside that transaction: the unique
1028
+ * credential fingerprint makes two identical pastes collide, and a nested
1029
+ * transaction per item keeps that collision from aborting the whole batch.
1030
+ * Outcomes are reported per index, so a partial paste still lands the
1031
+ * accounts that were fine — an operator fixing one bad line should not have
1032
+ * to re-import 39.
1033
+ */
1034
+ async createAccountBatch(
1035
+ tenantId: string,
1036
+ providerId: string,
1037
+ requests: readonly CreateProviderAccountRequest[],
1038
+ ): Promise<CreateProviderAccountBatchResult> {
1039
+ if (requests.length === 0) {
1040
+ return { created: 0, failed: 0, results: [] };
1041
+ }
1042
+ const results: CreateProviderAccountBatchItemResult[] = [];
1043
+ let created = 0;
1044
+ let failed = 0;
1045
+
1046
+ await this.db.transaction(async (tx) => {
1047
+ let nextSortIndex = await this.nextAccountSortIndex(tx, providerId, tenantId);
1048
+ for (const [index, request] of requests.entries()) {
1049
+ try {
1050
+ // A nested transaction acts as a savepoint: a duplicate-fingerprint
1051
+ // violation rolls back only this item, not the accounts before it.
1052
+ const account = await tx.transaction(async (inner) =>
1053
+ this.createAccount(tenantId, providerId, request, inner, false, nextSortIndex),
1054
+ );
1055
+ created += 1;
1056
+ nextSortIndex += 1;
1057
+ results.push({ index, ok: true, ...(account ? { account } : {}) });
1058
+ } catch (error) {
1059
+ failed += 1;
1060
+ results.push({
1061
+ index,
1062
+ ok: false,
1063
+ error: error instanceof Error ? error.message : String(error),
1064
+ code: error instanceof ConsoleDomainError ? error.code : "create_failed",
1065
+ });
1066
+ }
1067
+ }
1068
+ });
1069
+
1070
+ return { created, failed, results };
1071
+ }
1072
+
1073
+ async updateAccount(
1074
+ tenantId: string,
1075
+ providerId: string,
1076
+ accountId: string,
1077
+ patch: UpdateProviderAccountRequest,
1078
+ ): Promise<ProviderAccountResponse | undefined> {
1079
+ const set: Partial<typeof providerAccounts.$inferInsert> = {};
1080
+ if (patch.label !== undefined) set.label = patch.label;
1081
+ if (patch.secret !== undefined) {
1082
+ set.credentialCiphertext = encryptCredential(patch.secret);
1083
+ set.credentialFingerprint =
1084
+ patch.secret.length === 0 ? null : hashSecret(patch.secret);
1085
+ }
1086
+ if (patch.status !== undefined) set.status = patch.status;
1087
+ // Toggling the static-token flag: turning it on declares the credential is
1088
+ // used as issued and never refreshed, so any stale re-auth flag is cleared —
1089
+ // the operator has said the account is fine, and the pill must stop reading
1090
+ // "Re-login required". Turning it off returns the account to normal OAuth
1091
+ // refresh handling; the sweep picks it up again on its next pass.
1092
+ if (patch.staticToken !== undefined) {
1093
+ set.staticToken = patch.staticToken;
1094
+ if (patch.staticToken) {
1095
+ set.lastError = null;
1096
+ set.lastErrorCategory = null;
1097
+ set.lastErrorAt = null;
1098
+ }
1099
+ }
1100
+ // Status toggles are not recovery: preserve the health machine's evidence
1101
+ // until the operator uses Recover or replaces the rejected credential.
1102
+ const clearsFailureState = patch.secret !== undefined && patch.secret.length > 0;
1103
+ if (clearsFailureState) {
1104
+ set.consecutiveFailures = 0;
1105
+ set.cooldownUntil = null;
1106
+ set.modelCooldowns = {};
1107
+ set.lastError = null;
1108
+ set.lastErrorCategory = null;
1109
+ set.lastErrorAt = null;
1110
+ }
1111
+ const where = and(
1112
+ eq(providerAccounts.id, accountId),
1113
+ eq(providerAccounts.providerId, providerId),
1114
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1115
+ );
1116
+ try {
1117
+ const rows =
1118
+ Object.keys(set).length > 0
1119
+ ? await this.db.update(providerAccounts).set(set).where(where).returning()
1120
+ : await this.db.select().from(providerAccounts).where(where);
1121
+ const row = rows[0];
1122
+ if (!row) return undefined;
1123
+ // Secret/status mutation: drop any cached credential so the next
1124
+ // attempt decrypts the new ciphertext (or refuses a disabled account).
1125
+ if (patch.secret !== undefined || patch.status !== undefined) {
1126
+ invalidateCredentialCache(accountId);
1127
+ }
1128
+ const [account] = await this.accountsWithUsage(tenantId, [row]);
1129
+ return account;
1130
+ } catch (error) {
1131
+ if (isUniqueViolation(error)) {
1132
+ throw new ConsoleDomainError(
1133
+ "provider_account_duplicate",
1134
+ 409,
1135
+ "A provider account with this credential already exists",
1136
+ );
1137
+ }
1138
+ throw error;
1139
+ }
1140
+ }
1141
+
1142
+ private mapAccount(
1143
+ row: typeof providerAccounts.$inferSelect,
1144
+ usage: {
1145
+ readonly today: ProviderAccountTokenUsage;
1146
+ readonly allTime: ProviderAccountTokenUsage;
1147
+ readonly inflight?: number | undefined;
1148
+ },
1149
+ ): ProviderAccountResponse {
1150
+ const authState =
1151
+ row.authState !== null && typeof row.authState === "object" && !Array.isArray(row.authState)
1152
+ ? (row.authState as Record<string, unknown>)
1153
+ : undefined;
1154
+ const rawCredentialMode = authState?.["credentialMode"];
1155
+ const credentialMode: CredentialMode | undefined =
1156
+ rawCredentialMode === "auto" || rawCredentialMode === "jwt" || rawCredentialMode === "api_key"
1157
+ ? rawCredentialMode
1158
+ : undefined;
1159
+ const tokenExpiresAt =
1160
+ typeof authState?.["tokenExpiresAt"] === "string" ? authState["tokenExpiresAt"] : undefined;
1161
+ const jwtIssuer =
1162
+ typeof authState?.["jwtIssuer"] === "string" ? authState["jwtIssuer"] : undefined;
1163
+ return {
1164
+ id: row.id,
1165
+ providerId: row.providerId,
1166
+ tenantId: row.tenantId,
1167
+ label: row.label,
1168
+ credentialKind: row.credentialKind,
1169
+ ...(credentialMode === undefined ? {} : { credentialMode }),
1170
+ ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt }),
1171
+ ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
1172
+ status: row.status,
1173
+ ...(usage.inflight === undefined ? {} : { inflight: usage.inflight }),
1174
+ usageToday: usage.today,
1175
+ usageAllTime: usage.allTime,
1176
+ consecutiveFailures: row.consecutiveFailures,
1177
+ ...(row.lastSuccessAt ? { lastSuccessAt: row.lastSuccessAt.toISOString() } : {}),
1178
+ ...(row.lastError ? { lastError: row.lastError } : {}),
1179
+ ...(row.lastErrorCategory ? { lastErrorCategory: row.lastErrorCategory } : {}),
1180
+ ...(row.lastErrorAt ? { lastErrorAt: row.lastErrorAt.toISOString() } : {}),
1181
+ ...(row.cooldownUntil ? { cooldownUntil: row.cooldownUntil.toISOString() } : {}),
1182
+ ...(liveModelCooldowns(row.modelCooldowns) ?? {}),
1183
+ ...(row.lastRecoveredAt ? { lastRecoveredAt: row.lastRecoveredAt.toISOString() } : {}),
1184
+ createdAt: row.createdAt.toISOString(),
1185
+ sortIndex: row.sortIndex,
1186
+ ...(row.staticToken ? { staticToken: true } : {}),
1187
+ };
1188
+ }
1189
+
1190
+ async listAccountHealthEvents(
1191
+ tenantId: string,
1192
+ providerId: string,
1193
+ accountId: string,
1194
+ ): Promise<readonly AccountHealthEventRecord[]> {
1195
+ const owned = await this.db
1196
+ .select({ id: providerAccounts.id })
1197
+ .from(providerAccounts)
1198
+ .where(
1199
+ and(
1200
+ eq(providerAccounts.id, accountId),
1201
+ eq(providerAccounts.providerId, providerId),
1202
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1203
+ ),
1204
+ )
1205
+ .limit(1);
1206
+ if (owned.length === 0) return [];
1207
+ return listAccountHealthEvents(this.db, accountId);
1208
+ }
1209
+
1210
+ /** Deletes one account's stored health & error rows, for the modal's purge. */
1211
+ async purgeAccountHealthEvents(
1212
+ tenantId: string,
1213
+ providerId: string,
1214
+ accountId: string,
1215
+ ): Promise<number> {
1216
+ const owned = await this.db
1217
+ .select({ id: providerAccounts.id })
1218
+ .from(providerAccounts)
1219
+ .where(
1220
+ and(
1221
+ eq(providerAccounts.id, accountId),
1222
+ eq(providerAccounts.providerId, providerId),
1223
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1224
+ ),
1225
+ )
1226
+ .limit(1);
1227
+ if (owned.length === 0) return 0;
1228
+ return deleteAccountHealthEvents(this.db, accountId);
1229
+ }
1230
+ async listBuddyGrowthTasks(
1231
+ tenantId: string,
1232
+ providerId: string,
1233
+ accountId: string,
1234
+ dayKey: string,
1235
+ ): Promise<readonly BuddyGrowthTaskLedgerEntry[]> {
1236
+ const owned = await this.db
1237
+ .select({ id: providerAccounts.id })
1238
+ .from(providerAccounts)
1239
+ .where(
1240
+ and(
1241
+ eq(providerAccounts.id, accountId),
1242
+ eq(providerAccounts.providerId, providerId),
1243
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1244
+ ),
1245
+ )
1246
+ .limit(1);
1247
+ if (owned.length === 0) return [];
1248
+ const rows = await this.db
1249
+ .select({
1250
+ accountId: buddyTaskLedger.accountId,
1251
+ task: buddyTaskLedger.task,
1252
+ claimedAt: buddyTaskLedger.claimedAt,
1253
+ })
1254
+ .from(buddyTaskLedger)
1255
+ .where(
1256
+ and(
1257
+ eq(buddyTaskLedger.accountId, accountId),
1258
+ eq(buddyTaskLedger.dayKey, dayKey),
1259
+ ),
1260
+ );
1261
+ return rows.map((row) => ({
1262
+ accountId: row.accountId,
1263
+ task: row.task,
1264
+ claimedAt: row.claimedAt.toISOString(),
1265
+ }));
1266
+ }
1267
+
1268
+ async recoverAccount(
1269
+ tenantId: string,
1270
+ providerId: string,
1271
+ accountId: string,
1272
+ ): Promise<boolean> {
1273
+ const owned = await this.db
1274
+ .select({ id: providerAccounts.id })
1275
+ .from(providerAccounts)
1276
+ .where(
1277
+ and(
1278
+ eq(providerAccounts.id, accountId),
1279
+ eq(providerAccounts.providerId, providerId),
1280
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1281
+ ),
1282
+ )
1283
+ .limit(1);
1284
+ if (owned.length === 0) return false;
1285
+ return recoverAccount(this.db, accountId, "manual_operator_recovery");
1286
+ }
1287
+
1288
+
1289
+ async syncModels(tenantId: string, providerId: string): Promise<{ synced: number }> {
1290
+ return this.probing.syncModels(tenantId, providerId);
1291
+ }
1292
+ }