cartethyia 2.7.3 → 2.7.5

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 (625) hide show
  1. package/.env.example +2 -0
  2. package/README.md +17 -5
  3. package/dist/dashboard/assets/{BannedPage-2TJD37Hb.js → BannedPage-Cj15GsMp.js} +1 -1
  4. package/dist/dashboard/assets/BannedPage-Cj15GsMp.js.gz +0 -0
  5. package/dist/dashboard/assets/ClaimGiftsButton-D83pBJ6J.js +1 -0
  6. package/dist/dashboard/assets/ClaimGiftsButton-D83pBJ6J.js.gz +0 -0
  7. package/dist/dashboard/assets/{CliToolDetailPage-xefJNRmJ.js → CliToolDetailPage-DZKmVuJN.js} +1 -1
  8. package/dist/dashboard/assets/CliToolDetailPage-DZKmVuJN.js.gz +0 -0
  9. package/dist/dashboard/assets/{CliToolsPage-Rj9iHQ3F.js → CliToolsPage-BIccZmeL.js} +1 -1
  10. package/dist/dashboard/assets/CliToolsPage-BIccZmeL.js.gz +0 -0
  11. package/dist/dashboard/assets/CombosPage-DEEKkYD-.js +1 -0
  12. package/dist/dashboard/assets/CombosPage-DEEKkYD-.js.gz +0 -0
  13. package/dist/dashboard/assets/ConsoleLogPage-D5rol2j2.js +1 -0
  14. package/dist/dashboard/assets/ConsoleLogPage-D5rol2j2.js.gz +0 -0
  15. package/dist/dashboard/assets/CustomizationPage-BKj_r0rp.js +1 -0
  16. package/dist/dashboard/assets/CustomizationPage-BKj_r0rp.js.gz +0 -0
  17. package/dist/dashboard/assets/InjectSystemPromptPanel-B5nZvmf0.js +656 -0
  18. package/dist/dashboard/assets/InjectSystemPromptPanel-B5nZvmf0.js.gz +0 -0
  19. package/dist/dashboard/assets/{LoginPage-C4w7vea-.js → LoginPage-DkXb6dx-.js} +1 -1
  20. package/dist/dashboard/assets/LoginPage-DkXb6dx-.js.gz +0 -0
  21. package/dist/dashboard/assets/{ModelPicker-BtPcAfot.js → ModelPicker-DnQPSIA8.js} +1 -1
  22. package/dist/dashboard/assets/ModelPicker-DnQPSIA8.js.gz +0 -0
  23. package/dist/dashboard/assets/OverviewPage-Ci2wQKUz.js +1 -0
  24. package/dist/dashboard/assets/OverviewPage-Ci2wQKUz.js.gz +0 -0
  25. package/dist/dashboard/assets/ProviderDetailPage-odlgYrOg.js +5 -0
  26. package/dist/dashboard/assets/ProviderDetailPage-odlgYrOg.js.gz +0 -0
  27. package/dist/dashboard/assets/ProviderIcon-EfeloBn4.js +1 -0
  28. package/dist/dashboard/assets/ProviderIcon-EfeloBn4.js.gz +0 -0
  29. package/dist/dashboard/assets/ProvidersPage-CqFBQEB8.js +1 -0
  30. package/dist/dashboard/assets/ProvidersPage-CqFBQEB8.js.gz +0 -0
  31. package/dist/dashboard/assets/ProxyPage-5SnUSy3j.js +9 -0
  32. package/dist/dashboard/assets/ProxyPage-5SnUSy3j.js.gz +0 -0
  33. package/dist/dashboard/assets/QuotaPage-CmnMDzhP.js +1 -0
  34. package/dist/dashboard/assets/QuotaPage-CmnMDzhP.js.gz +0 -0
  35. package/dist/dashboard/assets/SettingsPage-BJtRZ4qD.js +1 -0
  36. package/dist/dashboard/assets/SettingsPage-BJtRZ4qD.js.gz +0 -0
  37. package/dist/dashboard/assets/{SetupPage-BQS0Rx_u.js → SetupPage-WTa0sktC.js} +1 -1
  38. package/dist/dashboard/assets/SetupPage-WTa0sktC.js.gz +0 -0
  39. package/dist/dashboard/assets/{StudioPage-TP7voAQ0.js → StudioPage-BfAb5-o_.js} +3 -3
  40. package/dist/dashboard/assets/StudioPage-BfAb5-o_.js.gz +0 -0
  41. package/dist/dashboard/assets/UsagePage-BNzeZ2Vk.js +56 -0
  42. package/dist/dashboard/assets/UsagePage-BNzeZ2Vk.js.gz +0 -0
  43. package/dist/dashboard/assets/api-keys-l29JROPv.js +1 -0
  44. package/dist/dashboard/assets/api-keys-l29JROPv.js.gz +0 -0
  45. package/dist/dashboard/assets/app--PJWq8_C.css +2 -0
  46. package/dist/dashboard/assets/app--PJWq8_C.css.gz +0 -0
  47. package/dist/dashboard/assets/{assert-C0YYuZJ4.js → assert-C0K-c4eo.js} +1 -1
  48. package/dist/dashboard/assets/assert-C0K-c4eo.js.gz +0 -0
  49. package/dist/dashboard/assets/{badge-B_DMpMJN.js → badge-DfbhQU4k.js} +1 -1
  50. package/dist/dashboard/assets/badge-DfbhQU4k.js.gz +0 -0
  51. package/dist/dashboard/assets/{banner-DMrMPmth.js → banner-BllT4LcF.js} +1 -1
  52. package/dist/dashboard/assets/banner-BllT4LcF.js.gz +0 -0
  53. package/dist/dashboard/assets/brand/login_register.jpg +0 -0
  54. package/dist/dashboard/assets/brand/login_register_initial.jpg +0 -0
  55. package/dist/dashboard/assets/brand/og_bansos.jpg +0 -0
  56. package/dist/dashboard/assets/brand/og_image.jpg +0 -0
  57. package/dist/dashboard/assets/{card-Be5Uzamx.js → card-CtkX66Wd.js} +1 -1
  58. package/dist/dashboard/assets/card-CtkX66Wd.js.gz +0 -0
  59. package/dist/dashboard/assets/chevron-left-Bf6CaTSJ.js +1 -0
  60. package/dist/dashboard/assets/chevron-left-Bf6CaTSJ.js.gz +0 -0
  61. package/dist/dashboard/assets/{cli-tools-muFRphDu.js → cli-tools-CQXVMn4P.js} +1 -1
  62. package/dist/dashboard/assets/cli-tools-CQXVMn4P.js.gz +0 -0
  63. package/dist/dashboard/assets/{clipboard-button-DOfrVmsi.js → clipboard-button-BQqBQd2n.js} +1 -1
  64. package/dist/dashboard/assets/clipboard-button-BQqBQd2n.js.gz +0 -0
  65. package/dist/dashboard/assets/{dialog-C9omdjQt.js → dialog-BEK7KP0H.js} +1 -1
  66. package/dist/dashboard/assets/dialog-BEK7KP0H.js.gz +0 -0
  67. package/dist/dashboard/assets/{drawer-Bm8WKaGY.js → drawer-BrTEZ8zu.js} +1 -1
  68. package/dist/dashboard/assets/drawer-BrTEZ8zu.js.gz +0 -0
  69. package/dist/dashboard/assets/entry-CHWxbS56.js +1 -0
  70. package/dist/dashboard/assets/entry-CHWxbS56.js.gz +0 -0
  71. package/dist/dashboard/assets/{entry-q5HwZ8nN.js → entry-EBHJ3DrE.js} +1 -1
  72. package/dist/dashboard/assets/entry-EBHJ3DrE.js.gz +0 -0
  73. package/dist/dashboard/assets/entry-LCS85hiq.js +4 -0
  74. package/dist/dashboard/assets/entry-LCS85hiq.js.gz +0 -0
  75. package/dist/dashboard/assets/{formatters-BTScrQpe.js → formatters-BAACA727.js} +1 -1
  76. package/dist/dashboard/assets/formatters-BAACA727.js.gz +0 -0
  77. package/dist/dashboard/assets/{github-badge-Orjuzemr.js → github-badge-YSCE4UC2.js} +1 -1
  78. package/dist/dashboard/assets/github-badge-YSCE4UC2.js.gz +0 -0
  79. package/dist/dashboard/assets/{index-cPrX5vn6.js → index-FQlj0HUT.js} +2 -2
  80. package/dist/dashboard/assets/index-FQlj0HUT.js.gz +0 -0
  81. package/dist/dashboard/assets/{inline-Dvux8w-0.js → inline-C4gU5iOL.js} +1 -1
  82. package/dist/dashboard/assets/inline-C4gU5iOL.js.gz +0 -0
  83. package/dist/dashboard/assets/{input-CU1Rgf3p.js → input-BHHX_Tmm.js} +1 -1
  84. package/dist/dashboard/assets/input-BHHX_Tmm.js.gz +0 -0
  85. package/dist/dashboard/assets/{layout-C_7A6H55.js → layout-CajrYUnD.js} +1 -1
  86. package/dist/dashboard/assets/{layout-C_7A6H55.js.gz → layout-CajrYUnD.js.gz} +0 -0
  87. package/dist/dashboard/assets/{list-row-CzFvogbj.js → list-row-Bx2I7XUe.js} +1 -1
  88. package/dist/dashboard/assets/list-row-Bx2I7XUe.js.gz +0 -0
  89. package/dist/dashboard/assets/live-DNNqRbj2.js +1 -0
  90. package/dist/dashboard/assets/live-DNNqRbj2.js.gz +0 -0
  91. package/dist/dashboard/assets/minimize-2-BTmMTK4o.js +1 -0
  92. package/dist/dashboard/assets/minimize-2-BTmMTK4o.js.gz +0 -0
  93. package/dist/dashboard/assets/{mutation-JJGQm8TD.js → mutation-Rr0TIvcj.js} +1 -1
  94. package/dist/dashboard/assets/mutation-Rr0TIvcj.js.gz +0 -0
  95. package/dist/dashboard/assets/network-C5UBACrJ.js +1 -0
  96. package/dist/dashboard/assets/network-C5UBACrJ.js.gz +0 -0
  97. package/dist/dashboard/assets/numbers-CUWAZK4J.js +2 -0
  98. package/dist/dashboard/assets/numbers-CUWAZK4J.js.gz +0 -0
  99. package/dist/dashboard/assets/pagination-Xsi9Qx04.js +1 -0
  100. package/dist/dashboard/assets/pagination-Xsi9Qx04.js.gz +0 -0
  101. package/dist/dashboard/assets/{query-keys-CLaNz8Xz.js → query-keys-BloKtaXJ.js} +1 -1
  102. package/dist/dashboard/assets/query-keys-BloKtaXJ.js.gz +0 -0
  103. package/dist/dashboard/assets/quota-DvQbD_sr.js +1 -0
  104. package/dist/dashboard/assets/quota-DvQbD_sr.js.gz +0 -0
  105. package/dist/dashboard/assets/{routing-BEH32QOC.js → routing-in0f_IfK.js} +1 -1
  106. package/dist/dashboard/assets/routing-in0f_IfK.js.gz +0 -0
  107. package/dist/dashboard/assets/{select-B3iTetHN.js → select-BLULNqTp.js} +2 -2
  108. package/dist/dashboard/assets/select-BLULNqTp.js.gz +0 -0
  109. package/dist/dashboard/assets/settings-CcGczj6I.js +1 -0
  110. package/dist/dashboard/assets/settings-CcGczj6I.js.gz +0 -0
  111. package/dist/dashboard/assets/shield-BMQNxORh.js +1 -0
  112. package/dist/dashboard/assets/shield-BMQNxORh.js.gz +0 -0
  113. package/dist/dashboard/assets/{stack-KrOrm7JZ.js → stack-D2lIR0tg.js} +1 -1
  114. package/dist/dashboard/assets/stack-D2lIR0tg.js.gz +0 -0
  115. package/dist/dashboard/assets/{state-DLS7IDMy.js → state-DTARjfiW.js} +1 -1
  116. package/dist/dashboard/assets/state-DTARjfiW.js.gz +0 -0
  117. package/dist/dashboard/assets/{switch-42ItvbAs.js → switch-c0oPSnqW.js} +1 -1
  118. package/dist/dashboard/assets/switch-c0oPSnqW.js.gz +0 -0
  119. package/dist/dashboard/assets/{useMutation-Dmnfh1Ue.js → useMutation-m8WGNPrz.js} +1 -1
  120. package/dist/dashboard/assets/useMutation-m8WGNPrz.js.gz +0 -0
  121. package/dist/dashboard/console-backgrounds.jpg +0 -0
  122. package/dist/dashboard/console-backgrounds_initial.jpg +0 -0
  123. package/dist/dashboard/index.html +2 -2
  124. package/dist/dashboard/index.html.gz +0 -0
  125. package/dist/dashboard/precompressed-assets.json +59 -57
  126. package/migrations/full-postgres/0027_qoder_identity_genuine_seed.sql +9 -10
  127. package/migrations/full-postgres/0032_add_provider_pool_accounts.sql +53 -0
  128. package/migrations/full-postgres/0033_add_api_key_ban.sql +9 -0
  129. package/migrations/full-postgres/0034_add_api_key_ban_until.sql +7 -0
  130. package/migrations/full-postgres/0035_align_pool_account_status_enum.sql +21 -0
  131. package/migrations/full-postgres/0036_system_prompt_presets_refs.sql +10 -0
  132. package/migrations/full-postgres/0037_share_concurrency_scope.sql +3 -0
  133. package/migrations/full-postgres/0038_add_accounts_quota_snapshot.sql +7 -0
  134. package/migrations/full-postgres/0039_add_telemetry_provider_model_indexes.sql +13 -0
  135. package/migrations/full-postgres/0040_add_models_dialect.sql +3 -0
  136. package/migrations/full-postgres/0041_add_daily_checkin_ledger_account_fk.sql +7 -0
  137. package/migrations/lite-sqlite3/0027_qoder_identity_genuine_seed.sql +9 -10
  138. package/migrations/lite-sqlite3/0032_add_provider_pool_accounts.sql +44 -0
  139. package/migrations/lite-sqlite3/0033_add_api_key_ban.sql +8 -0
  140. package/migrations/lite-sqlite3/0034_add_api_key_ban_until.sql +5 -0
  141. package/migrations/lite-sqlite3/0035_align_pool_account_status_enum.sql +6 -0
  142. package/migrations/lite-sqlite3/0036_system_prompt_presets_refs.sql +14 -0
  143. package/migrations/lite-sqlite3/0037_share_concurrency_scope.sql +3 -0
  144. package/migrations/lite-sqlite3/0038_add_accounts_quota_snapshot.sql +4 -0
  145. package/migrations/lite-sqlite3/0039_add_telemetry_provider_model_indexes.sql +6 -0
  146. package/migrations/lite-sqlite3/0040_add_models_dialect.sql +3 -0
  147. package/migrations/lite-sqlite3/0041_add_daily_checkin_ledger_account_fk.sql +26 -0
  148. package/package.json +4 -5
  149. package/scripts/cli/update.ts +15 -41
  150. package/src/boot/app.ts +67 -10
  151. package/src/boot/dependencies.ts +786 -732
  152. package/src/boot/lifecycle.ts +11 -12
  153. package/src/config/cooldowns.ts +34 -55
  154. package/src/config/network.ts +8 -4
  155. package/src/config/package-paths.ts +1 -1
  156. package/src/config/providers.ts +13 -14
  157. package/src/config/resources.ts +0 -5
  158. package/src/config/runtime.ts +2 -5
  159. package/src/config/spec.ts +26 -6
  160. package/src/console/api-keys/ban-constants.ts +38 -0
  161. package/src/console/api-keys/contracts.ts +92 -31
  162. package/src/console/api-keys/routes.ts +131 -6
  163. package/src/console/audit/routes.ts +3 -3
  164. package/src/console/auth/access.ts +4 -4
  165. package/src/console/auth/account-reset.ts +5 -5
  166. package/src/console/auth/audit-recorder.ts +1 -1
  167. package/src/console/auth/lockout.ts +7 -3
  168. package/src/console/auth/row-coercion.ts +57 -12
  169. package/src/console/auth/session-resolver.ts +1 -1
  170. package/src/console/auth/session-service.ts +8 -2
  171. package/src/console/auth/session.ts +40 -34
  172. package/src/console/auth/setup-service.ts +4 -3
  173. package/src/console/auth/user-store.ts +1 -1
  174. package/src/console/backup/9router-map.ts +0 -3
  175. package/src/console/backup/contracts.ts +11 -9
  176. package/src/console/backup/export-endpoint.ts +11 -12
  177. package/src/console/backup/nine-router.ts +1 -7
  178. package/src/console/backup/routes.ts +32 -36
  179. package/src/console/backup/service.ts +468 -468
  180. package/src/console/backup/store.ts +47 -29
  181. package/src/console/backup/validate.ts +11 -1
  182. package/src/console/cli-tools/contracts.ts +7 -7
  183. package/src/console/cli-tools/injectors/cline.ts +110 -110
  184. package/src/console/cli-tools/injectors/codex.ts +181 -181
  185. package/src/console/cli-tools/injectors/copilot.ts +108 -108
  186. package/src/console/cli-tools/injectors/driver.ts +247 -247
  187. package/src/console/cli-tools/injectors/jcode.ts +115 -115
  188. package/src/console/cli-tools/injectors/openclaw.ts +161 -161
  189. package/src/console/cli-tools/injectors/opencode.ts +153 -153
  190. package/src/console/cli-tools/routes.ts +4 -4
  191. package/src/console/cli-tools/service.ts +1 -1
  192. package/src/console/cli-tools/store.ts +2 -2
  193. package/src/console/console-router-guards.ts +2 -2
  194. package/src/console/console-router.ts +36 -4
  195. package/src/console/dashboard-assets.ts +9 -9
  196. package/src/console/data-management/routes.ts +3 -3
  197. package/src/console/domain-registration.ts +18 -4
  198. package/src/console/inferhub/client.ts +0 -7
  199. package/src/console/inferhub/key-store.ts +1 -1
  200. package/src/console/inferhub/normalize.ts +2 -2
  201. package/src/console/inferhub/routes.ts +1 -1
  202. package/src/console/inferhub/types.ts +1 -1
  203. package/src/console/observability/contracts.ts +5 -1
  204. package/src/console/observability/live.ts +34 -21
  205. package/src/console/observability/logs.ts +4 -4
  206. package/src/console/observability/performance.ts +3 -3
  207. package/src/console/observability/routes.ts +3 -3
  208. package/src/console/observability/sse.ts +62 -8
  209. package/src/console/observability/store.ts +36 -20
  210. package/src/console/providers/catalog/catalog-projections.ts +1 -1
  211. package/src/console/providers/catalog/contracts.ts +82 -22
  212. package/src/console/providers/catalog/model-operations.ts +1 -1
  213. package/src/console/providers/catalog/provider-operations.ts +110 -17
  214. package/src/console/providers/catalog/public-model-store.ts +0 -0
  215. package/src/console/providers/catalog/routes.ts +30 -6
  216. package/src/console/providers/catalog/store-helpers.ts +349 -326
  217. package/src/console/providers/catalog/store.ts +1662 -1292
  218. package/src/console/providers/detail/routes.ts +4 -4
  219. package/src/console/providers/oauth/callback-listener.ts +100 -18
  220. package/src/console/providers/oauth/routes.ts +95 -16
  221. package/src/console/quota/account-quota-global.ts +41 -3
  222. package/src/console/quota/account-quota-shared.ts +10 -3
  223. package/src/console/quota/account-quota-tenant.ts +285 -67
  224. package/src/console/quota/account-test-egress.ts +4 -4
  225. package/src/console/quota/daily-growth-job.ts +308 -0
  226. package/src/console/quota/native-identity.ts +2 -2
  227. package/src/console/quota/quota-view.ts +1 -1
  228. package/src/console/remote-support/routes.ts +1 -1
  229. package/src/console/remote-support/service.ts +2 -2
  230. package/src/console/routing/model/contracts.ts +1 -1
  231. package/src/console/routing/model/routes.ts +3 -3
  232. package/src/console/routing/pools/contracts.ts +13 -10
  233. package/src/console/routing/pools/import-parse.ts +3 -3
  234. package/src/console/routing/pools/operations.ts +14 -7
  235. package/src/console/routing/pools/probe-verdict.ts +8 -3
  236. package/src/console/routing/pools/relay-deploy.ts +12 -12
  237. package/src/console/routing/pools/routes.ts +3 -3
  238. package/src/console/routing/pools/store.ts +21 -1
  239. package/src/console/settings/contracts.ts +29 -2
  240. package/src/console/settings/routes.ts +3 -3
  241. package/src/console/settings/store.ts +20 -0
  242. package/src/console/share/share-router.ts +112 -44
  243. package/src/console/share/share-stats.ts +109 -39
  244. package/src/console/share/share-usage.ts +1 -1
  245. package/src/console/shared/errors.ts +2 -2
  246. package/src/console/shared/object.ts +18 -0
  247. package/src/console/shared/read-through-cache.ts +42 -6
  248. package/src/console/shared/transaction.ts +14 -0
  249. package/src/console/system-prompt/contracts.ts +89 -12
  250. package/src/console/system-prompt/routes.ts +98 -45
  251. package/src/console/updates/apply-update.ts +244 -0
  252. package/src/console/updates/routes.ts +256 -98
  253. package/src/main.ts +11 -5
  254. package/src/network/http2-bidi.ts +1 -1
  255. package/src/network/ip-utils.ts +298 -0
  256. package/src/network/outbound-fetch.ts +76 -5
  257. package/src/network/pool/agent.ts +7 -6
  258. package/src/network/pool/byte-accounting.ts +1 -1
  259. package/src/network/pool/resolver.ts +55 -51
  260. package/src/network/pool/selector.ts +150 -136
  261. package/src/network/pool-cooldown-store.ts +71 -16
  262. package/src/network/pool-health-machine.ts +22 -2
  263. package/src/network/rate-limit-verdict.ts +68 -0
  264. package/src/network/retry.ts +1 -1
  265. package/src/network/ssrf.ts +24 -75
  266. package/src/observability/event-log.ts +2 -2
  267. package/src/observability/event-query.ts +286 -214
  268. package/src/observability/log-sanitize.ts +1 -1
  269. package/src/observability/metrics.ts +4 -4
  270. package/src/observability/payload-capture.ts +6 -5
  271. package/src/observability/payload-store.ts +1 -1
  272. package/src/observability/runtime-metrics.ts +1 -1
  273. package/src/observability/telemetry-buffer.ts +12 -3
  274. package/src/observability/telemetry-reconciliation.ts +3 -3
  275. package/src/observability/telemetry-status.ts +1 -1
  276. package/src/observability/token-speed.ts +1 -1
  277. package/src/persistence/connection-url.ts +1 -1
  278. package/src/persistence/db-handle.ts +1 -1
  279. package/src/persistence/db-pg.ts +2 -2
  280. package/src/persistence/db-sqlite.ts +10 -5
  281. package/src/persistence/dialect.ts +5 -1
  282. package/src/persistence/readiness.ts +19 -7
  283. package/src/persistence/redis.ts +1 -1
  284. package/src/persistence/schema.ts +177 -45
  285. package/src/persistence/shared-cache.ts +2 -2
  286. package/src/persistence/sort-order.ts +1 -1
  287. package/src/persistence/stores/api-key-store.ts +109 -4
  288. package/src/persistence/stores/share-store.ts +20 -8
  289. package/src/persistence/stores/telemetry-store.ts +1 -1
  290. package/src/persistence/system-prompt-store.ts +63 -18
  291. package/src/persistence/tenant-preferences.ts +1 -1
  292. package/src/persistence/ttl-cache.ts +3 -3
  293. package/src/persistence/usage-flush.ts +7 -2
  294. package/src/protocol/canonical-model.ts +1 -1
  295. package/src/protocol/codecs.ts +12 -16
  296. package/src/protocol/dsml.ts +3 -49
  297. package/src/protocol/gateway-error.ts +6 -3
  298. package/src/protocol/image-clamp.ts +2 -2
  299. package/src/protocol/image-generation.ts +2 -2
  300. package/src/protocol/reasoning-text.ts +1 -1
  301. package/src/protocol/reasoning.ts +7 -52
  302. package/src/protocol/registry.ts +50 -15
  303. package/src/protocol/request/chat.ts +46 -19
  304. package/src/protocol/request/codex.ts +1 -1
  305. package/src/protocol/request/messages.ts +46 -14
  306. package/src/protocol/request/responses.ts +19 -10
  307. package/src/protocol/response/chat.ts +27 -12
  308. package/src/protocol/response/codex.ts +2 -2
  309. package/src/protocol/response/gemini.ts +1 -1
  310. package/src/protocol/response/messages.ts +6 -6
  311. package/src/protocol/response/omp-tool-call-markup.ts +1 -1
  312. package/src/protocol/response/responses.ts +3 -3
  313. package/src/protocol/sse-decoder.ts +64 -4
  314. package/src/protocol/stop-reason.ts +2 -2
  315. package/src/protocol/think-split.ts +347 -0
  316. package/src/protocol/translation/attachment-integrity.ts +3 -3
  317. package/src/protocol/translation/cache-controls.ts +8 -20
  318. package/src/protocol/translation/capabilities.ts +8 -8
  319. package/src/protocol/translation/dialect/deepseek.ts +10 -0
  320. package/src/protocol/translation/dialect/inband.ts +39 -0
  321. package/src/protocol/translation/dialect/model-thinking.ts +89 -0
  322. package/src/protocol/translation/dialect/qwen.ts +114 -0
  323. package/src/protocol/translation/dialect/resolver.ts +83 -0
  324. package/src/protocol/translation/dialect/rules.ts +93 -0
  325. package/src/protocol/translation/dialect/thinking-ladder.ts +245 -0
  326. package/src/protocol/translation/dialect/types.ts +58 -0
  327. package/src/protocol/translation/quirks.ts +18 -4
  328. package/src/protocol/translation/thinking.ts +12 -252
  329. package/src/protocol/translation/tool-id.ts +3 -3
  330. package/src/protocol/translation/tool-repair.ts +1 -1
  331. package/src/protocol/upstream/post-json.ts +6 -1
  332. package/src/protocol/upstream/send-claude-messages.ts +3 -3
  333. package/src/providers/adapters/base-adapter.ts +1 -1
  334. package/src/providers/adapters/compatible-adapter.ts +44 -5
  335. package/src/providers/authentication/jwt-validator.ts +0 -5
  336. package/src/providers/authentication/oauth-client.ts +254 -253
  337. package/src/providers/authentication/oauth-flow-store.ts +42 -7
  338. package/src/providers/authentication/oauth-refresh-service.ts +2 -2
  339. package/src/providers/bundled-discovery-providers.ts +6 -30
  340. package/src/providers/configured-openai-providers.ts +82 -97
  341. package/src/providers/configured-provider.ts +1 -1
  342. package/src/providers/default-registry.ts +23 -35
  343. package/src/providers/discovery/catalog/catalog-format.ts +13 -2
  344. package/src/providers/discovery/discovery-types.ts +0 -1
  345. package/src/providers/discovery/openai-model-discovery.ts +2 -2
  346. package/src/providers/discovery/probe-phases.ts +50 -15
  347. package/src/providers/discovery/probing-service.ts +18 -20
  348. package/src/providers/integrations/agentrouter/agentrouter.ts +14 -5
  349. package/src/providers/integrations/alibabacp/alibabacp.ts +2 -2
  350. package/src/providers/integrations/anthropic.ts +4 -11
  351. package/src/providers/integrations/antigravity/antigravity-oauth.ts +0 -1
  352. package/src/providers/integrations/antigravity/antigravity-protocol.ts +0 -14
  353. package/src/providers/integrations/antigravity/antigravity.ts +15 -26
  354. package/src/providers/integrations/buddy/buddy-catalog-shared.ts +2 -2
  355. package/src/providers/integrations/buddy/buddy-chat-shared.ts +20 -4
  356. package/src/providers/integrations/buddy/buddy-cli-headers.ts +19 -52
  357. package/src/providers/integrations/buddy/buddy-discovery-shared.ts +37 -6
  358. package/src/providers/integrations/buddy/buddy-identity.ts +108 -1
  359. package/src/providers/integrations/buddy/buddy-media.ts +16 -16
  360. package/src/providers/integrations/buddy/buddy-oauth-shared.ts +1 -1
  361. package/src/providers/integrations/buddy/codebuddy/cn-provider.ts +1 -2
  362. package/src/providers/integrations/buddy/codebuddy/provider.ts +5 -16
  363. package/src/providers/integrations/buddy/codebuddy/shared.ts +30 -9
  364. package/src/providers/integrations/buddy/workbuddy/provider.ts +6 -10
  365. package/src/providers/integrations/buddy/workbuddy/shared.ts +21 -3
  366. package/src/providers/integrations/claude/claude-betas.ts +1 -1
  367. package/src/providers/integrations/claude/claude-cch.ts +148 -148
  368. package/src/providers/integrations/claude/claude-credentials.ts +1 -1
  369. package/src/providers/integrations/claude/claude-slow-lane-retry.ts +1 -1
  370. package/src/providers/integrations/claude/claude.ts +3 -10
  371. package/src/providers/integrations/claude/fallback-credit.ts +3 -7
  372. package/src/providers/integrations/cline/cline.ts +2 -2
  373. package/src/providers/integrations/cloudflareai/cloudflareai.ts +4 -7
  374. package/src/providers/integrations/codex/codex-device-code.ts +101 -101
  375. package/src/providers/integrations/codex/codex-errors.ts +1 -1
  376. package/src/providers/integrations/codex/codex-oauth.ts +0 -1
  377. package/src/providers/integrations/codex/codex.ts +14 -15
  378. package/src/providers/integrations/commandcode/commandcode.ts +76 -116
  379. package/src/providers/integrations/commandcode/quota.ts +132 -48
  380. package/src/providers/integrations/cursor/cursor-http2.ts +11 -14
  381. package/src/providers/integrations/cursor/cursor-quota.ts +2 -6
  382. package/src/providers/integrations/cursor/cursor-request.ts +0 -87
  383. package/src/providers/integrations/cursor/cursor-shared.ts +0 -4
  384. package/src/providers/integrations/cursor/cursor.ts +53 -20
  385. package/src/providers/integrations/cursor/protocol/framing.ts +0 -56
  386. package/src/providers/integrations/cursor/protocol/messages.ts +0 -96
  387. package/src/providers/integrations/factory/factory.ts +13 -13
  388. package/src/providers/integrations/gemini.ts +11 -11
  389. package/src/providers/integrations/github/github-discovery.ts +55 -10
  390. package/src/providers/integrations/github/github-oauth.ts +6 -5
  391. package/src/providers/integrations/github/github.ts +47 -20
  392. package/src/providers/integrations/grok/grok-oauth.ts +261 -261
  393. package/src/providers/integrations/grok/grok-quota-frame.ts +1 -1
  394. package/src/providers/integrations/grok/grok-quota.ts +16 -7
  395. package/src/providers/integrations/grok/grok-ratelimit-store.ts +0 -5
  396. package/src/providers/integrations/grok/grok-ratelimit.ts +3 -0
  397. package/src/providers/integrations/grok/grok.ts +88 -42
  398. package/src/providers/integrations/inferhub.ts +4 -11
  399. package/src/providers/integrations/kilo/kilo-oauth.ts +1 -1
  400. package/src/providers/integrations/kimi/kimi.ts +4 -11
  401. package/src/providers/integrations/kiro/kiro-cache.ts +31 -0
  402. package/src/providers/integrations/kiro/kiro-catalog.ts +31 -5
  403. package/src/providers/integrations/kiro/kiro-discovery.ts +47 -43
  404. package/src/providers/integrations/kiro/kiro-machine-id.ts +6 -3
  405. package/src/providers/integrations/kiro/kiro-oauth.ts +523 -255
  406. package/src/providers/integrations/kiro/kiro-quota.ts +35 -47
  407. package/src/providers/integrations/kiro/kiro-request.ts +8 -11
  408. package/src/providers/integrations/kiro/kiro-stream.ts +13 -0
  409. package/src/providers/integrations/kiro/kiro.ts +91 -78
  410. package/src/providers/integrations/muse/muse-oauth.ts +0 -1
  411. package/src/providers/integrations/muse/muse-quota.ts +0 -4
  412. package/src/providers/integrations/muse/muse.ts +6 -9
  413. package/src/providers/integrations/opencode/fingerprint.ts +7 -5
  414. package/src/providers/integrations/opencode/provider.ts +17 -24
  415. package/src/providers/integrations/perplexity.ts +2 -2
  416. package/src/providers/integrations/qoder/qoder-catalog.ts +132 -17
  417. package/src/providers/integrations/qoder/qoder-checkin.ts +26 -8
  418. package/src/providers/integrations/qoder/qoder-native-identity-store.ts +9 -8
  419. package/src/providers/integrations/qoder/qoder-oauth.ts +165 -25
  420. package/src/providers/integrations/qoder/qoder-quota.ts +48 -6
  421. package/src/providers/integrations/qoder/qoder-realm.ts +22 -28
  422. package/src/providers/integrations/qoder/qoder-sse.ts +159 -0
  423. package/src/providers/integrations/qoder/qoder-umid.ts +33 -38
  424. package/src/providers/integrations/qoder/qoder-virtual.ts +14 -2
  425. package/src/providers/integrations/qoder/qoder.ts +521 -63
  426. package/src/providers/integrations/shared/connect.ts +0 -54
  427. package/src/providers/integrations/shared/hash.ts +15 -0
  428. package/src/providers/integrations/shared/session-cache.ts +136 -0
  429. package/src/providers/integrations/tokenharbor.ts +2 -2
  430. package/src/providers/integrations/trae/trae-cache.ts +7 -87
  431. package/src/providers/integrations/trae/trae-catalog.ts +1 -6
  432. package/src/providers/integrations/trae/trae-protocol.ts +17 -8
  433. package/src/providers/integrations/trae/trae-realm.ts +0 -7
  434. package/src/providers/integrations/trae/trae.ts +59 -19
  435. package/src/providers/integrations/xai/xai-oauth.ts +5 -5
  436. package/src/providers/integrations/zcode/oauth.ts +1 -1
  437. package/src/providers/integrations/zcode-start-plan/gifts.ts +265 -0
  438. package/src/providers/integrations/zcode-start-plan/oauth.ts +154 -0
  439. package/src/providers/integrations/zcode-start-plan/provider.ts +131 -0
  440. package/src/providers/integrations/zcode-start-plan/quota.ts +152 -0
  441. package/src/providers/integrations/zcode-start-plan/zcode_prompt.json +10 -0
  442. package/src/providers/operations/account-error-classification.ts +131 -116
  443. package/src/providers/operations/account-health-service.ts +31 -39
  444. package/src/providers/operations/account-reset-service.ts +58 -1
  445. package/src/providers/operations/cli-platform.ts +31 -5
  446. package/src/providers/operations/client-version-resolver.ts +4 -6
  447. package/src/providers/operations/client-versions.ts +10 -7
  448. package/src/providers/operations/provider-catalog-seeder.ts +2 -0
  449. package/src/providers/operations/provider-catalog-service.ts +22 -6
  450. package/src/providers/operations/provider-credential-service.ts +35 -6
  451. package/src/providers/operations/upstream-deadline.ts +3 -3
  452. package/src/providers/provider-contracts.ts +65 -10
  453. package/src/providers/provider-credential-resolver.ts +1 -1
  454. package/src/providers/provider-metadata.ts +17 -2
  455. package/src/providers/provider-model-definition.ts +22 -1
  456. package/src/providers/provider-probe.ts +4 -2
  457. package/src/providers/provider-registry.ts +4 -4
  458. package/src/providers/provider-usage.ts +81 -16
  459. package/src/providers/quota/cache.ts +29 -0
  460. package/src/providers/quota/quota-contracts.ts +28 -10
  461. package/src/providers/quota/refresh.ts +29 -6
  462. package/src/providers/quota/snapshot.ts +94 -0
  463. package/src/providers/search/search-provider.ts +6 -8
  464. package/src/providers/search/search-providers.ts +2 -1
  465. package/src/security/abuse.ts +8 -8
  466. package/src/security/admission/reasons.ts +17 -17
  467. package/src/security/admission/service.ts +2 -2
  468. package/src/security/admission/ttl.ts +61 -61
  469. package/src/security/api-key-auth.ts +20 -8
  470. package/src/security/client-router-fingerprint.ts +4 -4
  471. package/src/security/credential-codec.ts +3 -3
  472. package/src/security/csrf.ts +2 -2
  473. package/src/security/ip-boundary.ts +16 -189
  474. package/src/security/model-access-rule.ts +1 -1
  475. package/src/security/outbound-headers.ts +18 -0
  476. package/src/shared/coerce.ts +19 -0
  477. package/src/shared/invoke-guard.ts +47 -0
  478. package/src/transport/contracts.ts +13 -4
  479. package/src/transport/dispatch/attempt-finalize.ts +5 -4
  480. package/src/transport/dispatch/attempt-loop.ts +10 -7
  481. package/src/transport/dispatch/capture-policy.ts +34 -37
  482. package/src/transport/dispatch/empty-stream.ts +28 -25
  483. package/src/transport/dispatch/generation.ts +33 -53
  484. package/src/transport/dispatch/leases.ts +8 -8
  485. package/src/transport/dispatch/native-shared.ts +127 -0
  486. package/src/transport/dispatch/proxy-request.ts +10 -8
  487. package/src/transport/dispatch/responses-compact.ts +35 -56
  488. package/src/transport/dispatch/retry-policy.ts +4 -67
  489. package/src/transport/dispatch/stream-bridge.ts +1 -1
  490. package/src/transport/dispatch/streaming/encoder.ts +18 -72
  491. package/src/transport/dispatch/streaming/finalize.ts +11 -10
  492. package/src/transport/dispatch/streaming/stream.ts +7 -3
  493. package/src/transport/dispatch/streaming/thinking-loop.ts +1 -1
  494. package/src/transport/dispatch/systemone.ts +27 -55
  495. package/src/transport/dispatch/token-count.ts +49 -46
  496. package/src/transport/dispatch/websearch.ts +24 -50
  497. package/src/transport/drain-endpoint.ts +3 -3
  498. package/src/transport/failure-policy.ts +19 -6
  499. package/src/transport/guards/auth-guard.ts +6 -11
  500. package/src/transport/guards/body-policy.ts +7 -7
  501. package/src/transport/guards/error-lifecycle.ts +18 -3
  502. package/src/transport/guards/guard-errors.ts +7 -3
  503. package/src/transport/guards/headroom-guard.ts +2 -2
  504. package/src/transport/guards/pipeline.ts +7 -7
  505. package/src/transport/guards/readiness-guard.ts +16 -2
  506. package/src/transport/guards/request-context.ts +15 -20
  507. package/src/transport/request/preparer.ts +306 -27
  508. package/src/transport/request/rtk/compress-request.ts +3 -3
  509. package/src/transport/request/rtk/rtk-constants.ts +2 -2
  510. package/src/transport/request/rtk/rtk-filters.ts +8 -8
  511. package/src/transport/request/state.ts +5 -20
  512. package/src/transport/request/system-prompt-injection.ts +74 -11
  513. package/src/transport/request/tenant-preferences.ts +22 -0
  514. package/src/transport/routing/candidate-index.ts +2 -2
  515. package/src/transport/routing/round-robin.ts +1 -1
  516. package/src/transport/routing/route-catalog.ts +113 -19
  517. package/src/transport/routing/route-model.ts +131 -38
  518. package/src/transport/routing/router.ts +154 -39
  519. package/src/transport/shutdown-notice.ts +21 -9
  520. package/src/transport/surface/adapters.ts +3 -3
  521. package/src/transport/surface/chat/encode.ts +7 -7
  522. package/src/transport/surface/chat/parse.ts +7 -7
  523. package/src/transport/surface/completion.ts +3 -3
  524. package/src/transport/surface/content-parts.ts +1 -1
  525. package/src/transport/surface/dialects.ts +2 -2
  526. package/src/transport/surface/messages/encode.ts +1 -1
  527. package/src/transport/surface/messages/parse.ts +3 -3
  528. package/src/transport/surface/responses/adapter.ts +1 -1
  529. package/src/transport/surface/responses/errors.ts +0 -9
  530. package/src/transport/vision-handoff-cache.ts +58 -0
  531. package/src/transport/vision-handoff.ts +376 -0
  532. package/src/workers/account-identity-sweep.ts +2 -2
  533. package/src/workers/buddy-growth-tasks.ts +392 -346
  534. package/src/workers/daily-checkin.ts +102 -49
  535. package/src/workers/maintenance-lease.ts +2 -35
  536. package/src/workers/oauth-refresh-sweep.ts +8 -1
  537. package/src/workers/quota-refresh-sweep.ts +120 -82
  538. package/src/workers/scheduler.ts +67 -4
  539. package/src/workers/sweep-runner.ts +24 -5
  540. package/src/workers/zcode-gift-claim.ts +108 -0
  541. package/dist/dashboard/assets/AccountCooldown-Bjo92Qat.js +0 -1
  542. package/dist/dashboard/assets/AccountCooldown-Bjo92Qat.js.gz +0 -0
  543. package/dist/dashboard/assets/BannedPage-2TJD37Hb.js.gz +0 -0
  544. package/dist/dashboard/assets/CliToolDetailPage-xefJNRmJ.js.gz +0 -0
  545. package/dist/dashboard/assets/CliToolsPage-Rj9iHQ3F.js.gz +0 -0
  546. package/dist/dashboard/assets/CombosPage-JEbYJFxw.js +0 -1
  547. package/dist/dashboard/assets/CombosPage-JEbYJFxw.js.gz +0 -0
  548. package/dist/dashboard/assets/ConsoleLogPage-C3xx_inM.js +0 -1
  549. package/dist/dashboard/assets/ConsoleLogPage-C3xx_inM.js.gz +0 -0
  550. package/dist/dashboard/assets/CustomizationPage-Dw306gJU.js +0 -1
  551. package/dist/dashboard/assets/CustomizationPage-Dw306gJU.js.gz +0 -0
  552. package/dist/dashboard/assets/HealthEventsModal-jaBo1TWV.js +0 -1
  553. package/dist/dashboard/assets/HealthEventsModal-jaBo1TWV.js.gz +0 -0
  554. package/dist/dashboard/assets/LoginPage-C4w7vea-.js.gz +0 -0
  555. package/dist/dashboard/assets/ModelPicker-BtPcAfot.js.gz +0 -0
  556. package/dist/dashboard/assets/OverviewPage-CGC5gNs1.js +0 -1
  557. package/dist/dashboard/assets/OverviewPage-CGC5gNs1.js.gz +0 -0
  558. package/dist/dashboard/assets/ProviderDetailPage-DQcthNGt.js +0 -4
  559. package/dist/dashboard/assets/ProviderDetailPage-DQcthNGt.js.gz +0 -0
  560. package/dist/dashboard/assets/ProviderIcon-FB6yS4v1.js +0 -1
  561. package/dist/dashboard/assets/ProviderIcon-FB6yS4v1.js.gz +0 -0
  562. package/dist/dashboard/assets/ProvidersPage-0OsXRGXe.js +0 -1
  563. package/dist/dashboard/assets/ProvidersPage-0OsXRGXe.js.gz +0 -0
  564. package/dist/dashboard/assets/ProxyPage-DdPc8slb.js +0 -9
  565. package/dist/dashboard/assets/ProxyPage-DdPc8slb.js.gz +0 -0
  566. package/dist/dashboard/assets/QuotaPage-Ci5O4BnH.js +0 -1
  567. package/dist/dashboard/assets/QuotaPage-Ci5O4BnH.js.gz +0 -0
  568. package/dist/dashboard/assets/SettingsPage-CDZjTt87.js +0 -1
  569. package/dist/dashboard/assets/SettingsPage-CDZjTt87.js.gz +0 -0
  570. package/dist/dashboard/assets/SetupPage-BQS0Rx_u.js.gz +0 -0
  571. package/dist/dashboard/assets/SortableList-BAL5npBC.js +0 -1
  572. package/dist/dashboard/assets/SortableList-BAL5npBC.js.gz +0 -0
  573. package/dist/dashboard/assets/StudioPage-TP7voAQ0.js.gz +0 -0
  574. package/dist/dashboard/assets/UsagePage-Cj_fEzhg.js +0 -56
  575. package/dist/dashboard/assets/UsagePage-Cj_fEzhg.js.gz +0 -0
  576. package/dist/dashboard/assets/api-keys-MbI7e7rt.js +0 -1
  577. package/dist/dashboard/assets/api-keys-MbI7e7rt.js.gz +0 -0
  578. package/dist/dashboard/assets/app-B2vyPoII.css +0 -2
  579. package/dist/dashboard/assets/app-B2vyPoII.css.gz +0 -0
  580. package/dist/dashboard/assets/assert-C0YYuZJ4.js.gz +0 -0
  581. package/dist/dashboard/assets/badge-B_DMpMJN.js.gz +0 -0
  582. package/dist/dashboard/assets/banner-DMrMPmth.js.gz +0 -0
  583. package/dist/dashboard/assets/card-Be5Uzamx.js.gz +0 -0
  584. package/dist/dashboard/assets/cli-tools-muFRphDu.js.gz +0 -0
  585. package/dist/dashboard/assets/clipboard-button-DOfrVmsi.js.gz +0 -0
  586. package/dist/dashboard/assets/dialog-C9omdjQt.js.gz +0 -0
  587. package/dist/dashboard/assets/drawer-Bm8WKaGY.js.gz +0 -0
  588. package/dist/dashboard/assets/entry-DS90gUks.js +0 -1
  589. package/dist/dashboard/assets/entry-DS90gUks.js.gz +0 -0
  590. package/dist/dashboard/assets/entry-j40LJotO.js +0 -4
  591. package/dist/dashboard/assets/entry-j40LJotO.js.gz +0 -0
  592. package/dist/dashboard/assets/entry-q5HwZ8nN.js.gz +0 -0
  593. package/dist/dashboard/assets/formatters-BTScrQpe.js.gz +0 -0
  594. package/dist/dashboard/assets/github-badge-Orjuzemr.js.gz +0 -0
  595. package/dist/dashboard/assets/index-cPrX5vn6.js.gz +0 -0
  596. package/dist/dashboard/assets/inline-Dvux8w-0.js.gz +0 -0
  597. package/dist/dashboard/assets/input-CU1Rgf3p.js.gz +0 -0
  598. package/dist/dashboard/assets/list-row-CzFvogbj.js.gz +0 -0
  599. package/dist/dashboard/assets/live-KaG15HLQ.js +0 -1
  600. package/dist/dashboard/assets/live-KaG15HLQ.js.gz +0 -0
  601. package/dist/dashboard/assets/minimize-2-D-MN8W8a.js +0 -1
  602. package/dist/dashboard/assets/minimize-2-D-MN8W8a.js.gz +0 -0
  603. package/dist/dashboard/assets/mutation-JJGQm8TD.js.gz +0 -0
  604. package/dist/dashboard/assets/numbers-BNDZnsUE.js +0 -2
  605. package/dist/dashboard/assets/numbers-BNDZnsUE.js.gz +0 -0
  606. package/dist/dashboard/assets/query-keys-CLaNz8Xz.js.gz +0 -0
  607. package/dist/dashboard/assets/quota-DZGyp0N5.js +0 -1
  608. package/dist/dashboard/assets/quota-DZGyp0N5.js.gz +0 -0
  609. package/dist/dashboard/assets/routing-BEH32QOC.js.gz +0 -0
  610. package/dist/dashboard/assets/select-B3iTetHN.js.gz +0 -0
  611. package/dist/dashboard/assets/settings-Dt3Eqbnq.js +0 -1
  612. package/dist/dashboard/assets/settings-Dt3Eqbnq.js.gz +0 -0
  613. package/dist/dashboard/assets/stack-KrOrm7JZ.js.gz +0 -0
  614. package/dist/dashboard/assets/state-DLS7IDMy.js.gz +0 -0
  615. package/dist/dashboard/assets/stream-retry-5QnVuSSo.js +0 -1
  616. package/dist/dashboard/assets/stream-retry-5QnVuSSo.js.gz +0 -0
  617. package/dist/dashboard/assets/switch-42ItvbAs.js.gz +0 -0
  618. package/dist/dashboard/assets/useMutation-Dmnfh1Ue.js.gz +0 -0
  619. package/src/network/response-headers.ts +0 -39
  620. package/src/protocol/response/dsml.ts +0 -38
  621. package/src/providers/integrations/xiaomi-mimo/think-stream.ts +0 -229
  622. /package/dist/dashboard/assets/{app-wvwCi4Eh.js → app-Bgd3zANQ.js} +0 -0
  623. /package/dist/dashboard/assets/{app-wvwCi4Eh.js.gz → app-Bgd3zANQ.js.gz} +0 -0
  624. /package/dist/dashboard/assets/brand/{og_bansos.webp → og_bansos_initial.webp} +0 -0
  625. /package/dist/dashboard/assets/brand/{og_image.webp → og_image_initial.webp} +0 -0
@@ -1,1292 +1,1662 @@
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
- }
1
+ // Drizzle-backed provider, account, model, routing, and API-key repositories.
2
+ import { and, asc, eq, gte, 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 { providerRateLimitIsIpScoped } from "../../../providers/provider-metadata";
6
+ import type { ModelDefinition } from "../../../providers/provider-model-definition";
7
+ import type { ProviderRegistry } from "../../../providers/provider-registry";
8
+ import { BUNDLED_PROVIDER_MODULES } from "../../../providers/default-registry";
9
+ import { globalOrOwnedBy, ownedByOnly } from "../../../persistence/tenant-scope";
10
+ import { nextSortIndex, reorderSortIndex } from "../../../persistence/sort-order";
11
+ import type { CartethyiaDatabase } from "../../../persistence/db-handle";
12
+ import { buddyTaskLedger, models, networkPools, providerAccounts, providerOauthStates, providerPoolAccounts, providers, telemetryEvents, telemetryUsageTotals, tenantDisabledModels } from "../../../persistence/schema";
13
+ import { IS_GATEWAY_ERROR_SQL } from "../../../observability/event-query";
14
+ import type { WireFamily } from "../../../protocol/canonical-model";
15
+ import { listAccountHealthEvents, recoverAccount, deleteAccountHealthEvents, type AccountHealthEventRecord } from "../../../providers/operations/account-health-service";
16
+ import { invalidateCredentialCache } from "../../../providers/operations/provider-credential-service";
17
+ import { encryptCredential, hashSecret } from "../../../security/crypto";
18
+ import type { TelemetryBatchBuffer } from "../../../observability/telemetry-buffer";
19
+ import { bumpCatalogRevision, type BundledProviderCatalog } from "../../../providers/operations/provider-catalog-service";
20
+ 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";
21
+ import { isServiceKind, validateCompatibilityProfile } from "./contracts";
22
+ import { ProviderProbingService, type ProbeOutboundResolver } from "../../../providers/discovery/probing-service";
23
+ import {
24
+ applyModelMetadataOverride,
25
+ resolveManualModelMetadata,
26
+ } from "../../../providers/provider-model-definition";
27
+ import { isUniqueViolation } from "../../../persistence/boot";
28
+ import { DEFAULT_ENDPOINT_BY_WIRE_FAMILY, endpointPathForProviderModel, mapProviderRow } from "./catalog-projections";
29
+ import { pushStructuredConsoleLog } from "../../../observability/log-ring";
30
+
31
+ const emptyUsage: ProviderAccountTokenUsage = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };
32
+
33
+ /**
34
+ * The owning pool's provider cooldown markers, filtered to the ones still in
35
+ * force and shaped like `NetworkPoolResponse.providerCooldowns`. Expired
36
+ * markers are skipped — a spent window is not a reason to flag the row.
37
+ */
38
+ function activePoolProviderCooldowns(
39
+ markers: Record<string, { until: number; reason: string; blocked?: boolean }>,
40
+ ): { providerId: string; until: string; reason: string; blocked: boolean }[] {
41
+ const now = Date.now();
42
+ const active: { providerId: string; until: string; reason: string; blocked: boolean }[] = [];
43
+ for (const [providerId, marker] of Object.entries(markers)) {
44
+ if (marker.until <= now) continue;
45
+ active.push({
46
+ providerId,
47
+ until: new Date(marker.until).toISOString(),
48
+ reason: marker.reason,
49
+ blocked: marker.blocked === true,
50
+ });
51
+ }
52
+ return active;
53
+ }
54
+
55
+ /** Real Drizzle-backed provider and model catalog repository. */
56
+
57
+ import {
58
+ asStoredText,
59
+ liveModelCooldowns,
60
+ mapModelRow,
61
+ nextGeneratedAccountLabel,
62
+ parseJwtCredential,
63
+ parsePastedOAuthCredential,
64
+ withImageModality,
65
+ } from "./store-helpers";
66
+
67
+ export {
68
+ accountLabelKindSegment,
69
+ mapModelRow,
70
+ nextGeneratedAccountLabel,
71
+ withImageModality,
72
+ } from "./store-helpers";
73
+
74
+ export class DrizzleProviderCatalogStore implements ProviderCatalogStore {
75
+ private readonly probing: ProviderProbingService;
76
+ private readonly bundledModelCatalog: ReadonlyMap<string, readonly ModelDefinition[]>;
77
+ private readonly providerRegistry: ProviderRegistry;
78
+
79
+ private readonly readAccountInflight:
80
+ | ((
81
+ providerId: string,
82
+ tenantId: string,
83
+ ) => Promise<readonly AccountInflightReading[]>)
84
+ | undefined;
85
+
86
+ constructor(
87
+ private readonly db: CartethyiaDatabase,
88
+ options: {
89
+ readonly telemetryBuffer: TelemetryBatchBuffer;
90
+ readonly bundledModelCatalog: BundledProviderCatalog;
91
+ readonly providerRegistry: ProviderRegistry;
92
+ readonly outboundFetchFor: ProbeOutboundResolver;
93
+ readonly snapshotInvalidator: { invalidate(): unknown };
94
+ readonly readAccountInflight?:
95
+ | ((
96
+ providerId: string,
97
+ tenantId: string,
98
+ ) => Promise<readonly AccountInflightReading[]>)
99
+ | undefined;
100
+ },
101
+ ) {
102
+ this.bundledModelCatalog = options.bundledModelCatalog.modelsByProvider;
103
+ this.providerRegistry = options.providerRegistry;
104
+ this.readAccountInflight = options.readAccountInflight;
105
+ this.probing = new ProviderProbingService({
106
+ db,
107
+ telemetryBuffer: options.telemetryBuffer,
108
+ defaultEndpoints: DEFAULT_ENDPOINT_BY_WIRE_FAMILY,
109
+ bundledModelCatalog: this.bundledModelCatalog,
110
+ outboundFetchFor: options.outboundFetchFor,
111
+ snapshotInvalidator: options.snapshotInvalidator,
112
+ providerRegistry: options.providerRegistry,
113
+ });
114
+ }
115
+ async list(tenantId: string): Promise<readonly ProviderRecord[]> {
116
+ const bundledIds = BUNDLED_PROVIDER_MODULES.map((provider) => provider.id);
117
+ const rows = await this.db
118
+ .select()
119
+ .from(providers)
120
+ .where(
121
+ and(
122
+ globalOrOwnedBy(providers.tenantId, tenantId),
123
+ or(inArray(providers.id, bundledIds), eq(providers.tenantId, tenantId)),
124
+ ),
125
+ )
126
+ .orderBy(asc(providers.id));
127
+ return rows.map((row) => mapProviderRow(row, this.providerRegistry));
128
+ }
129
+ async get(tenantId: string, providerId: string): Promise<ProviderRecord | undefined> {
130
+ const rows = await this.db
131
+ .select()
132
+ .from(providers)
133
+ .where(
134
+ and(
135
+ eq(providers.id, providerId),
136
+ globalOrOwnedBy(providers.tenantId, tenantId),
137
+ ),
138
+ )
139
+ .limit(1);
140
+ const row = rows[0];
141
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
142
+ }
143
+ async create(record: ProviderRecord): Promise<void> {
144
+ if (isBundledProviderId(record.providerId))
145
+ throw new ConsoleDomainError(
146
+ "provider_is_builtin",
147
+ 403,
148
+ "Built-in provider cannot be created",
149
+ );
150
+ parseCustomProviderId(record.providerId);
151
+ if (record.compatibilityProfile) validateCompatibilityProfile(record.compatibilityProfile);
152
+ await this.db.insert(providers).values({
153
+ id: record.providerId,
154
+ tenantId: record.tenantId ?? null,
155
+ enabled: record.enabled,
156
+ ...(record.wireFamilyDefault ? { wireFamilyDefault: record.wireFamilyDefault } : {}),
157
+ capabilityProfile: record.capabilityProfile ?? null,
158
+ baseUrl: record.baseUrl ?? null,
159
+ compatibilityProfile: record.compatibilityProfile ?? null,
160
+ });
161
+ }
162
+ async update(
163
+ tenantId: string,
164
+ providerId: string,
165
+ patch: Partial<ProviderRecord>,
166
+ ): Promise<ProviderRecord | undefined> {
167
+ if (isBundledProviderId(providerId))
168
+ throw new ConsoleDomainError(
169
+ "provider_is_builtin",
170
+ 403,
171
+ "Built-in provider cannot be updated",
172
+ );
173
+ if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
174
+ const set: Partial<typeof providers.$inferInsert> = {};
175
+ if (patch.enabled !== undefined) set.enabled = patch.enabled;
176
+ if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
177
+ if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
178
+ if (patch.compatibilityProfile !== undefined)
179
+ set.compatibilityProfile = patch.compatibilityProfile;
180
+ const rows =
181
+ Object.keys(set).length > 0
182
+ ? await this.db
183
+ .update(providers)
184
+ .set(set)
185
+ .where(
186
+ and(
187
+ eq(providers.id, providerId),
188
+ ownedByOnly(providers.tenantId, tenantId),
189
+ ),
190
+ )
191
+ .returning()
192
+ : await this.db
193
+ .select()
194
+ .from(providers)
195
+ .where(
196
+ and(
197
+ eq(providers.id, providerId),
198
+ ownedByOnly(providers.tenantId, tenantId),
199
+ ),
200
+ );
201
+ const row = rows[0];
202
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
203
+ }
204
+ async delete(tenantId: string, providerId: string): Promise<boolean> {
205
+ if (isBundledProviderId(providerId))
206
+ throw new ConsoleDomainError(
207
+ "provider_is_builtin",
208
+ 403,
209
+ "Built-in provider cannot be deleted",
210
+ );
211
+ // Custom-provider rows own their models, accounts, disabled-model flags,
212
+ // and routing preferences: deleting the parent cascades all of them
213
+ // (models/provider_accounts/provider_oauth_states via provider FK,
214
+ // health_events via account FK, tenant_disabled_models and
215
+ // provider_routing_settings via provider FK) in one atomic DELETE.
216
+ const deleted = await this.db
217
+ .delete(providers)
218
+ .where(and(eq(providers.id, providerId), ownedByOnly(providers.tenantId, tenantId)))
219
+ .returning({ id: providers.id });
220
+ if (deleted.length === 0) return false;
221
+ this.providerRegistry.unregister(providerId);
222
+ // The provider left the registry, so the compiled catalog is now missing it
223
+ // — the snapshot's re-seed is gated on that revision, and a delete that did
224
+ // not bump it would leave the provider's model rows behind.
225
+ bumpCatalogRevision();
226
+ return true;
227
+ }
228
+ async updateGlobal(
229
+ providerId: string,
230
+ patch: Partial<ProviderRecord>,
231
+ ): Promise<ProviderRecord | undefined> {
232
+ const isBuiltin = isBundledProviderId(providerId);
233
+ if (isBuiltin && Object.keys(patch).some((field) => field !== "enabled")) {
234
+ throw new ConsoleDomainError(
235
+ "provider_is_builtin",
236
+ 403,
237
+ "Built-in providers only support enable/disable",
238
+ );
239
+ }
240
+ if (patch.compatibilityProfile) validateCompatibilityProfile(patch.compatibilityProfile);
241
+ const set: Partial<typeof providers.$inferInsert> = {};
242
+ if (patch.enabled !== undefined) set.enabled = patch.enabled;
243
+ if (patch.capabilityProfile !== undefined) set.capabilityProfile = patch.capabilityProfile;
244
+ if (patch.baseUrl !== undefined) set.baseUrl = patch.baseUrl;
245
+ if (patch.compatibilityProfile !== undefined) {
246
+ set.compatibilityProfile = patch.compatibilityProfile;
247
+ }
248
+ const rows =
249
+ Object.keys(set).length > 0
250
+ ? await this.db
251
+ .update(providers)
252
+ .set(set)
253
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
254
+ .returning()
255
+ : await this.db
256
+ .select()
257
+ .from(providers)
258
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)));
259
+ const row = rows[0];
260
+ return row ? mapProviderRow(row, this.providerRegistry) : undefined;
261
+ }
262
+
263
+ async deleteGlobal(providerId: string): Promise<boolean> {
264
+ if (isBundledProviderId(providerId)) {
265
+ throw new ConsoleDomainError(
266
+ "provider_is_builtin",
267
+ 403,
268
+ "Built-in provider cannot be deleted",
269
+ );
270
+ }
271
+ const rows = await this.db
272
+ .delete(providers)
273
+ .where(and(eq(providers.id, providerId), isNull(providers.tenantId)))
274
+ .returning({ id: providers.id });
275
+ return rows.length > 0;
276
+ }
277
+ async listModels(tenantId: string, providerId: string): Promise<readonly ModelCatalogEntry[]> {
278
+ const byProvider = await this.listModelsForTenant(tenantId, providerId);
279
+ return byProvider.get(providerId) ?? [];
280
+ }
281
+
282
+ /**
283
+ * Every enabled-and-disabled model row the tenant can see, grouped by
284
+ * provider. One pair of statements for the whole tenant instead of a pair per
285
+ * provider.
286
+ *
287
+ * The per-provider `listModels` shape costs two queries per call, so a caller
288
+ * that needs every provider's models — the flat catalog the picker renders —
289
+ * issued `2 * providers + 2` statements, growing with the bundled catalog.
290
+ * Grouping here makes it constant: one disabled-model read and one models
291
+ * join, regardless of provider count. `providerId` narrows it to a single
292
+ * provider for callers that already know which one they want.
293
+ */
294
+ async listModelsForTenant(
295
+ tenantId: string,
296
+ providerId?: string,
297
+ ): Promise<Map<string, readonly ModelCatalogEntry[]>> {
298
+ const disabled = await this.db
299
+ .select({
300
+ providerId: tenantDisabledModels.providerId,
301
+ modelId: tenantDisabledModels.modelId,
302
+ endpointPath: tenantDisabledModels.endpointPath,
303
+ })
304
+ .from(tenantDisabledModels)
305
+ .where(
306
+ providerId === undefined
307
+ ? eq(tenantDisabledModels.tenantId, tenantId)
308
+ : and(
309
+ eq(tenantDisabledModels.tenantId, tenantId),
310
+ eq(tenantDisabledModels.providerId, providerId),
311
+ ),
312
+ );
313
+ const disabledKeys = new Set(
314
+ disabled.map((d) => `${d.providerId}::${d.modelId}::${d.endpointPath}`),
315
+ );
316
+ const dbRows = await this.db
317
+ .select({ model: models })
318
+ .from(models)
319
+ .innerJoin(providers, eq(models.providerId, providers.id))
320
+ .where(
321
+ and(
322
+ ...(providerId === undefined ? [] : [eq(models.providerId, providerId)]),
323
+ globalOrOwnedBy(providers.tenantId, tenantId),
324
+ ),
325
+ );
326
+ const grouped = new Map<string, ModelCatalogEntry[]>();
327
+ for (const { model: row } of dbRows) {
328
+ const isDisabled = disabledKeys.has(
329
+ `${row.providerId}::${row.modelId}::${row.endpointPath}`,
330
+ );
331
+ const list = grouped.get(row.providerId) ?? [];
332
+ list.push(mapModelRow(row, isDisabled));
333
+ grouped.set(row.providerId, list);
334
+ }
335
+ return grouped;
336
+ }
337
+ async registerModels(
338
+ tenantId: string,
339
+ providerId: string,
340
+ modelIds: readonly string[],
341
+ wireFamily?: string,
342
+ metadata?: ModelMetadataOverride,
343
+ ): Promise<void> {
344
+ const owner = await this.db
345
+ .select({
346
+ id: providers.id,
347
+ baseUrl: providers.baseUrl,
348
+ compatibilityProfile: providers.compatibilityProfile,
349
+ })
350
+ .from(providers)
351
+ .where(and(eq(providers.id, providerId), globalOrOwnedBy(providers.tenantId, tenantId)))
352
+ .limit(1);
353
+ if (!owner[0]) {
354
+ throw new ConsoleDomainError("provider_not_found", 404, `Provider ${providerId} not found`);
355
+ }
356
+ const family = (wireFamily ?? "chat") as WireFamily;
357
+ // Static endpoint from the provider's own bundled catalog via the probing
358
+ // service (the same startup-built map this store is constructed with).
359
+ // Without this, bundled providers on versioned bases (cline) get the
360
+ // generic `/v1/…` default, which joins into an unreachable path and every
361
+ // probe/dispatch 404s.
362
+ const staticEndpoint = await this.probing.resolveStaticEndpoint(providerId, family);
363
+ const endpointPath = endpointPathForProviderModel(
364
+ family,
365
+ owner[0].compatibilityProfile,
366
+ staticEndpoint === undefined ? undefined : { [family]: staticEndpoint },
367
+ );
368
+ if (modelIds.length === 0) return;
369
+ // Single multi-row insert and upsert of the capability flags so a
370
+ // re-registration repairs a row whose `tool_call` (and `reasoning`) was
371
+ // seeded false — a manual add persists schema defaults, which capability
372
+ // preflight reads as "route cannot use tools" and silently strips `tools`
373
+ // from every request. `enabled` stays operator-owned; `source` is refreshed
374
+ // to `manual`.
375
+ await this.db
376
+ .insert(models)
377
+ .values(
378
+ modelIds.map((modelId) => ({
379
+ providerId,
380
+ modelId,
381
+ wireFamily: family,
382
+ endpointPath,
383
+ ...applyModelMetadataOverride(
384
+ resolveManualModelMetadata(providerId, modelId),
385
+ metadata,
386
+ ),
387
+ source: "manual",
388
+ sourceUpdatedAt: new Date(),
389
+ enabled: true,
390
+ })),
391
+ )
392
+ .onConflictDoUpdate({
393
+ target: [models.providerId, models.modelId, models.endpointPath],
394
+ set: {
395
+ wireFamily: sql`excluded.wire_family`,
396
+ contextLimit: sql`excluded.context_limit`,
397
+ outputLimit: sql`excluded.output_limit`,
398
+ modalities: sql`excluded.modalities`,
399
+ reasoning: sql`excluded.reasoning`,
400
+ toolCall: sql`excluded.tool_call`,
401
+ source: sql`'manual'`,
402
+ sourceUpdatedAt: sql`excluded.source_updated_at`,
403
+ },
404
+ });
405
+ }
406
+
407
+ /**
408
+ * One-shot connectivity probe and model discovery live in
409
+ * `services/provider-probing.ts` — the store only forwards so the domain
410
+ * `ProviderCatalogStore` interface is unchanged.
411
+ */
412
+ async probeModel(
413
+ tenantId: string,
414
+ providerId: string,
415
+ request: ProbeModelRequest,
416
+ ): Promise<ProbeModelResult> {
417
+ return this.probing.probeModel(tenantId, providerId, request);
418
+ }
419
+
420
+ /** Ad-hoc BYOK connectivity test; delegates to the shared probing service. */
421
+ async testByokConnection(
422
+ tenantId: string,
423
+ request: ByokConnectionTestRequest,
424
+ ): Promise<ByokConnectionTestResult> {
425
+ return this.probing.testByokConnection(tenantId, request);
426
+ }
427
+
428
+ /**
429
+ * Batched provider-wide probe: the first registered model runs sequentially
430
+ * (warms OAuth token / connection pools), the rest run concurrently bounded
431
+ * to 5. Registered model ids come from this store's own catalog read.
432
+ */
433
+ async probeAllModels(tenantId: string, providerId: string): Promise<ProbeAllModelsResult> {
434
+ const entries = await this.listModels(tenantId, providerId);
435
+ const requests = entries.map((entry) => ({
436
+ modelId: entry.modelId,
437
+ route: entry.route,
438
+ serviceKind: isServiceKind(entry.serviceKind) ? entry.serviceKind : ("llm" as const),
439
+ }));
440
+ const uniqueRequests = requests.filter(
441
+ (request, index, all) =>
442
+ all.findIndex(
443
+ (candidate) =>
444
+ candidate.modelId === request.modelId &&
445
+ candidate.route === request.route &&
446
+ candidate.serviceKind === request.serviceKind,
447
+ ) === index,
448
+ );
449
+ return this.probing.probeAllModels(tenantId, providerId, uniqueRequests);
450
+ }
451
+ async probeAllAccounts(
452
+ tenantId: string,
453
+ providerId: string,
454
+ request: ProbeModelRequest,
455
+ ): Promise<ProbeAllAccountsResult> {
456
+ return this.probing.probeAllAccounts(tenantId, providerId, request);
457
+ }
458
+ /** Toggles a persisted model's routing eligibility. */
459
+ async setModelEnabled(
460
+ tenantId: string,
461
+ providerId: string,
462
+ request: SetModelEnabledRequest,
463
+ ): Promise<boolean> {
464
+ // Tenant-owned (BYOK) model: toggle the shared row directly.
465
+ const owned = await this.db
466
+ .select({ id: models.id })
467
+ .from(models)
468
+ .innerJoin(providers, eq(models.providerId, providers.id))
469
+ .where(
470
+ and(
471
+ eq(models.providerId, providerId),
472
+ eq(models.modelId, request.modelId),
473
+ eq(models.endpointPath, request.route),
474
+ ownedByOnly(providers.tenantId, tenantId),
475
+ ),
476
+ )
477
+ .limit(1);
478
+ const ownedTarget = owned[0];
479
+ if (ownedTarget) {
480
+ await this.db
481
+ .update(models)
482
+ .set({ enabled: request.enabled })
483
+ .where(eq(models.id, ownedTarget.id));
484
+ return true;
485
+ }
486
+
487
+ // Global/built-in model: tenants cannot mutate the shared row, so record
488
+ // (or clear) a tenant-scoped disable in `tenantDisabledModels`.
489
+ const global = await this.db
490
+ .select({ id: models.id })
491
+ .from(models)
492
+ .innerJoin(providers, eq(models.providerId, providers.id))
493
+ .where(
494
+ and(
495
+ eq(models.providerId, providerId),
496
+ eq(models.modelId, request.modelId),
497
+ eq(models.endpointPath, request.route),
498
+ isNull(providers.tenantId),
499
+ ),
500
+ )
501
+ .limit(1);
502
+ if (global[0] === undefined) return false;
503
+ if (request.enabled) {
504
+ await this.db
505
+ .delete(tenantDisabledModels)
506
+ .where(
507
+ and(
508
+ eq(tenantDisabledModels.tenantId, tenantId),
509
+ eq(tenantDisabledModels.providerId, providerId),
510
+ eq(tenantDisabledModels.modelId, request.modelId),
511
+ eq(tenantDisabledModels.endpointPath, request.route),
512
+ ),
513
+ );
514
+ return true;
515
+ }
516
+ await this.db
517
+ .insert(tenantDisabledModels)
518
+ .values({
519
+ tenantId,
520
+ providerId,
521
+ modelId: request.modelId,
522
+ endpointPath: request.route,
523
+ })
524
+ .onConflictDoNothing({
525
+ target: [
526
+ tenantDisabledModels.tenantId,
527
+ tenantDisabledModels.providerId,
528
+ tenantDisabledModels.modelId,
529
+ tenantDisabledModels.endpointPath,
530
+ ],
531
+ });
532
+ return true;
533
+ }
534
+
535
+ /**
536
+ * Updates one model's limits and capability flags.
537
+ *
538
+ * Two row kinds are writable. A tenant-owned (BYOK) row is updated directly.
539
+ * A model belonging to a *global* provider row is also updated directly:
540
+ * bundled providers are seeded once with `tenant_id IS NULL` and `providers.id`
541
+ * is the primary key, so a bundled provider can only ever have that one row —
542
+ * there is no tenant-scoped row to edit instead. Auto-fetched rows
543
+ * (`discovered` / `auto_free`) live on exactly those providers, which is why
544
+ * the previous `ownedByOnly` filter answered `not_found` for every model the
545
+ * operator had just fetched and could not be edited at all.
546
+ *
547
+ * A global `builtin` row is rejected: it is re-seeded from the bundle on every
548
+ * boot, so an edit there would be silently reverted, and `deleteModel` refuses
549
+ * it for the same reason.
550
+ *
551
+ * Absent override fields leave the stored value untouched — an edit that only
552
+ * sets the context ceiling must not reset the capability flags.
553
+ */
554
+ async updateModelMetadata(
555
+ tenantId: string,
556
+ providerId: string,
557
+ request: UpdateModelMetadataRequest,
558
+ ): Promise<boolean> {
559
+ const findRow = (ownership: SQL) =>
560
+ this.db
561
+ .select({ id: models.id, modalities: models.modalities, source: models.source })
562
+ .from(models)
563
+ .innerJoin(providers, eq(models.providerId, providers.id))
564
+ .where(
565
+ and(
566
+ eq(models.providerId, providerId),
567
+ eq(models.modelId, request.modelId),
568
+ eq(models.endpointPath, request.route),
569
+ ownership,
570
+ ),
571
+ )
572
+ .limit(1);
573
+ const owned = await findRow(ownedByOnly(providers.tenantId, tenantId));
574
+ let row = owned[0];
575
+ if (row === undefined) {
576
+ const global = await findRow(isNull(providers.tenantId));
577
+ const candidate = global[0];
578
+ if (candidate === undefined) return false;
579
+ if (candidate.source === "builtin") {
580
+ throw new ConsoleDomainError(
581
+ "builtin_model_immutable",
582
+ 403,
583
+ `Built-in model ${providerId}/${request.modelId} cannot be edited — the bundle re-seeds it on every boot`,
584
+ );
585
+ }
586
+ row = candidate;
587
+ }
588
+
589
+ const override = request.metadata;
590
+ const set: Record<string, unknown> = { sourceUpdatedAt: new Date() };
591
+ if (override?.contextLimit !== undefined) set.contextLimit = override.contextLimit;
592
+ if (override?.outputLimit !== undefined) set.outputLimit = override.outputLimit;
593
+ // Passthrough grants every capability and cannot be partly revoked by a
594
+ // per-flag field: the point of the flag is that the operator does not know
595
+ // which capabilities the model has, so an explicit `false` alongside it is
596
+ // either stale or a mistake.
597
+ if (override?.passthrough === true) {
598
+ set.reasoning = true;
599
+ set.toolCall = true;
600
+ set.modalities = withImageModality(asStoredText(row.modalities), true);
601
+ } else {
602
+ if (override?.reasoning !== undefined) set.reasoning = override.reasoning;
603
+ if (override?.toolCall !== undefined) set.toolCall = override.toolCall;
604
+ if (override?.image !== undefined)
605
+ set.modalities = withImageModality(asStoredText(row.modalities), override.image);
606
+ }
607
+ await this.db.update(models).set(set).where(eq(models.id, row.id));
608
+ return true;
609
+ }
610
+
611
+ async deleteModel(
612
+ tenantId: string,
613
+ providerId: string,
614
+ request: SetModelEnabledRequest,
615
+ ): Promise<boolean> {
616
+ const owned = await this.db
617
+ .select({ id: models.id })
618
+ .from(models)
619
+ .innerJoin(providers, eq(models.providerId, providers.id))
620
+ .where(
621
+ and(
622
+ eq(models.providerId, providerId),
623
+ eq(models.modelId, request.modelId),
624
+ eq(models.endpointPath, request.route),
625
+ ownedByOnly(providers.tenantId, tenantId),
626
+ ),
627
+ )
628
+ .limit(1);
629
+ const target = owned[0];
630
+ if (target) {
631
+ const rows = await this.db
632
+ .delete(models)
633
+ .where(eq(models.id, target.id))
634
+ .returning({ id: models.id });
635
+ return rows.length > 0;
636
+ }
637
+ const global = await this.db
638
+ .select({ id: models.id, source: models.source })
639
+ .from(models)
640
+ .innerJoin(providers, eq(models.providerId, providers.id))
641
+ .where(
642
+ and(
643
+ eq(models.providerId, providerId),
644
+ eq(models.modelId, request.modelId),
645
+ eq(models.endpointPath, request.route),
646
+ isNull(providers.tenantId),
647
+ ),
648
+ )
649
+ .limit(1);
650
+ if (!global[0]) return false;
651
+ // Built-in models are immutable catalog: tenants can only disable them
652
+ // (via tenantDisabledModels), never delete the shared row.
653
+ if (global[0].source === "builtin") {
654
+ throw new ConsoleDomainError(
655
+ "builtin_model_immutable",
656
+ 403,
657
+ `Built-in model ${providerId}/${request.modelId} cannot be deleted — disable it instead`,
658
+ );
659
+ }
660
+ const rows = await this.db
661
+ .delete(models)
662
+ .where(eq(models.id, global[0].id))
663
+ .returning({ id: models.id });
664
+ await this.db
665
+ .delete(tenantDisabledModels)
666
+ .where(
667
+ and(
668
+ eq(tenantDisabledModels.tenantId, tenantId),
669
+ eq(tenantDisabledModels.providerId, providerId),
670
+ eq(tenantDisabledModels.modelId, request.modelId),
671
+ eq(tenantDisabledModels.endpointPath, request.route),
672
+ ),
673
+ );
674
+ return rows.length > 0;
675
+ }
676
+
677
+ private async accountsWithUsage(
678
+ tenantId: string,
679
+ rows: readonly (typeof providerAccounts.$inferSelect)[],
680
+ ): Promise<readonly ProviderAccountResponse[]> {
681
+ if (rows.length === 0) return [];
682
+ const accountIds = rows.map((row) => row.id);
683
+ // Today's per-account usage is one GROUP BY, not a read of every event
684
+ // since midnight. The read is scoped to the accounts on this page via the
685
+ // `(tenant, account, created_at)` index — a full-tenant breakdown scanned
686
+ // every of today's events and capped at 100 groups, so an account past
687
+ // the cap silently read as "no usage today".
688
+ const todayGroups = await this.accountTodayUsage(tenantId, accountIds);
689
+ const todayByAccount = new Map(
690
+ todayGroups.map((group) => [
691
+ group.key,
692
+ {
693
+ requests: group.requests,
694
+ errors: group.errors,
695
+ inputTokens: group.inputTokens,
696
+ outputTokens: group.outputTokens,
697
+ },
698
+ ]),
699
+ );
700
+ const [lifetimeRows] = await Promise.all([
701
+ this.db
702
+ .select()
703
+ .from(telemetryUsageTotals)
704
+ .where(
705
+ and(
706
+ eq(telemetryUsageTotals.tenantId, tenantId),
707
+ eq(telemetryUsageTotals.identityType, "account"),
708
+ inArray(telemetryUsageTotals.entityId, accountIds),
709
+ ),
710
+ ),
711
+ ]);
712
+ const lifetimeByAccount = new Map(lifetimeRows.map((row) => [row.entityId, row]));
713
+ const mapUsage = (row: {
714
+ readonly requests: number | string | null;
715
+ readonly errors: number | string | null;
716
+ readonly inputTokens: number | string | null;
717
+ readonly outputTokens: number | string | null;
718
+ } | undefined): ProviderAccountTokenUsage => {
719
+ const inputTokens = Number(row?.inputTokens ?? 0);
720
+ const outputTokens = Number(row?.outputTokens ?? 0);
721
+ return {
722
+ requests: Number(row?.requests ?? 0),
723
+ errors: Number(row?.errors ?? 0),
724
+ inputTokens,
725
+ outputTokens,
726
+ totalTokens: inputTokens + outputTokens,
727
+ };
728
+ };
729
+ const first = rows[0];
730
+ const inflightByAccount = await this.accountInflightFor(tenantId, first?.providerId);
731
+ return rows.map((row) => {
732
+ const inflight = inflightByAccount.get(row.id);
733
+ return this.mapAccount(row, {
734
+ today: mapUsage(todayByAccount.get(row.id)),
735
+ allTime: mapUsage(lifetimeByAccount.get(row.id)),
736
+ ...(inflight === undefined ? {} : { inflight }),
737
+ });
738
+ });
739
+ }
740
+
741
+ /**
742
+ * Today's per-account usage for a concrete id set. Scoped to those ids so
743
+ * the `(tenant, account, created_at)` index serves the range instead of a
744
+ * full-tenant window scan; returns exactly one group per account with
745
+ * traffic, so an account is never lost to a top-N cap.
746
+ */
747
+ private async accountTodayUsage(
748
+ tenantId: string,
749
+ accountIds: readonly string[],
750
+ ): Promise<
751
+ Array<{ key: string; requests: number; errors: number; inputTokens: number; outputTokens: number }>
752
+ > {
753
+ if (accountIds.length === 0) return [];
754
+ const todayStart = new Date();
755
+ todayStart.setUTCHours(0, 0, 0, 0);
756
+ const rows = await this.db
757
+ .select({
758
+ accountId: telemetryEvents.accountId,
759
+ requests: sql<number>`count(*)`,
760
+ errors: sql<number>`sum(case when ${IS_GATEWAY_ERROR_SQL} then 1 else 0 end)`,
761
+ inputTokens: sql<number>`coalesce(sum(${telemetryEvents.inputTokens}), 0)`,
762
+ outputTokens: sql<number>`coalesce(sum(${telemetryEvents.outputTokens}), 0)`,
763
+ })
764
+ .from(telemetryEvents)
765
+ .where(
766
+ and(
767
+ eq(telemetryEvents.tenantId, tenantId),
768
+ gte(telemetryEvents.createdAt, todayStart),
769
+ inArray(telemetryEvents.accountId, accountIds),
770
+ ),
771
+ )
772
+ .groupBy(telemetryEvents.accountId);
773
+ return rows.flatMap((row) => {
774
+ if (row.accountId === null) return [];
775
+ return [
776
+ {
777
+ key: row.accountId,
778
+ requests: Number(row.requests),
779
+ errors: Number(row.errors),
780
+ inputTokens: Number(row.inputTokens),
781
+ outputTokens: Number(row.outputTokens),
782
+ },
783
+ ];
784
+ });
785
+ }
786
+
787
+ private async accountInflightFor(
788
+ tenantId: string,
789
+ providerId: string | undefined,
790
+ ): Promise<Map<string, number>> {
791
+ const readings = new Map<string, number>();
792
+ if (!this.readAccountInflight || !providerId) return readings;
793
+ const rows = await this.readAccountInflight(providerId, tenantId);
794
+ for (const row of rows) {
795
+ if (typeof row.accountId !== "string" || !Number.isFinite(row.inflight)) continue;
796
+ readings.set(row.accountId, Math.max(0, Math.floor(row.inflight)));
797
+ }
798
+ return readings;
799
+ }
800
+
801
+ /**
802
+ * Next free list position for a new account in this provider's list.
803
+ *
804
+ * Scoped to (provider, tenant) because the list is per provider: a tenant
805
+ * with accounts under two providers must not have the second provider's
806
+ * first account land at a high index.
807
+ */
808
+ /**
809
+ * Labels already in use for one provider, for numbering a generated name.
810
+ *
811
+ * Scoped to this provider and tenant: `dcint-key-1` and `other-key-1` belong
812
+ * to different providers and must not collide with each other.
813
+ */
814
+ private async generateAccountLabel(
815
+ db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
816
+ providerId: string,
817
+ tenantId: string,
818
+ credentialMode: CredentialMode,
819
+ ): Promise<string> {
820
+ const rows = await db
821
+ .select({ label: providerAccounts.label })
822
+ .from(providerAccounts)
823
+ .where(
824
+ and(
825
+ eq(providerAccounts.providerId, providerId),
826
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
827
+ ),
828
+ );
829
+ return nextGeneratedAccountLabel(
830
+ providerId,
831
+ credentialMode,
832
+ rows.map((row) => row.label).filter((label): label is string => typeof label === "string"),
833
+ );
834
+ }
835
+
836
+ private async nextAccountSortIndex(
837
+ db: CartethyiaDatabase | Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
838
+ providerId: string,
839
+ tenantId: string,
840
+ ): Promise<number> {
841
+ return nextSortIndex(
842
+ db,
843
+ { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
844
+ and(
845
+ eq(providerAccounts.providerId, providerId),
846
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
847
+ ),
848
+ );
849
+ }
850
+
851
+ /** Rewrites one provider's account order; `accountIds` is the full order. */
852
+ async reorderAccounts(
853
+ tenantId: string,
854
+ providerId: string,
855
+ accountIds: readonly string[],
856
+ ): Promise<void> {
857
+ await reorderSortIndex(
858
+ this.db,
859
+ { table: providerAccounts, idColumn: providerAccounts.id, sortIndexColumn: providerAccounts.sortIndex },
860
+ and(
861
+ eq(providerAccounts.providerId, providerId),
862
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
863
+ ),
864
+ accountIds,
865
+ );
866
+ }
867
+
868
+ async listAccountAuthStates(
869
+ tenantId: string,
870
+ providerId: string,
871
+ accountIds: readonly string[],
872
+ ): Promise<Readonly<Record<string, Readonly<Record<string, unknown>>>>> {
873
+ if (accountIds.length === 0) return {};
874
+ const rows = await this.db
875
+ .select({ id: providerAccounts.id, authState: providerAccounts.authState })
876
+ .from(providerAccounts)
877
+ .where(
878
+ and(
879
+ eq(providerAccounts.providerId, providerId),
880
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
881
+ inArray(providerAccounts.id, accountIds),
882
+ ),
883
+ );
884
+ const out: Record<string, Readonly<Record<string, unknown>>> = {};
885
+ for (const row of rows) {
886
+ if (row.authState !== null && typeof row.authState === "object" && !Array.isArray(row.authState)) {
887
+ out[row.id] = row.authState as Record<string, unknown>;
888
+ }
889
+ }
890
+ return out;
891
+ }
892
+
893
+ async listAccounts(
894
+ tenantId: string,
895
+ providerId: string,
896
+ ): Promise<readonly ProviderAccountResponse[]> {
897
+ const rows = await this.db
898
+ .select()
899
+ .from(providerAccounts)
900
+ .where(
901
+ and(
902
+ eq(providerAccounts.providerId, providerId),
903
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
904
+ ),
905
+ )
906
+ // Stable list position, not `created_at`: two accounts created in the
907
+ // same millisecond could swap between loads. `id` breaks a tie so the
908
+ // order is total even before a reorder assigns distinct indices.
909
+ .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
910
+ const accounts = await this.accountsWithUsage(tenantId, rows);
911
+ const poolAccounts = await this.listPoolAccounts(tenantId, providerId);
912
+ if (poolAccounts.length === 0) return accounts;
913
+ // Pool-as-account rows are appended after real accounts. They are
914
+ // account *equivalents* for ip-scoped, credential-less providers, so the
915
+ // operator sees the egresses that carry those providers' rate limits in
916
+ // the same list that already explains health.
917
+ return [...accounts, ...poolAccounts];
918
+ }
919
+
920
+ /**
921
+ * One cheap id-only read of an account set, for callers that need the set
922
+ * (e.g. the routing-inflight reader) without the usage aggregates
923
+ * `listAccounts` computes (P-02). No ORDER BY: the set is order-insensitive.
924
+ */
925
+ async listAccountIds(
926
+ tenantId: string,
927
+ providerId: string,
928
+ ): Promise<readonly string[]> {
929
+ const rows = await this.db
930
+ .select({ id: providerAccounts.id })
931
+ .from(providerAccounts)
932
+ .where(
933
+ and(
934
+ eq(providerAccounts.providerId, providerId),
935
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
936
+ ),
937
+ );
938
+ return rows.map((row) => row.id);
939
+ }
940
+
941
+ async listAllAccounts(tenantId: string): Promise<readonly ProviderAccountResponse[]> {
942
+ const rows = await this.db
943
+ .select()
944
+ .from(providerAccounts)
945
+ .where(globalOrOwnedBy(providerAccounts.tenantId, tenantId))
946
+ .orderBy(asc(providerAccounts.sortIndex), asc(providerAccounts.createdAt), asc(providerAccounts.id));
947
+ const accounts = await this.accountsWithUsage(tenantId, rows);
948
+ const poolAccounts = await this.listAllPoolAccounts(tenantId);
949
+ if (poolAccounts.length === 0) return accounts;
950
+ return [...accounts, ...poolAccounts];
951
+ }
952
+
953
+ async listAllAccountSummaries(
954
+ tenantId: string,
955
+ ): Promise<readonly { providerId: string; status: string }[]> {
956
+ const rows = await this.db
957
+ .select({ providerId: providerAccounts.providerId, status: providerAccounts.status })
958
+ .from(providerAccounts)
959
+ .where(globalOrOwnedBy(providerAccounts.tenantId, tenantId));
960
+ return rows.map((row) => ({ providerId: row.providerId, status: row.status }));
961
+ }
962
+
963
+ /**
964
+ * Per-provider account totals for one tenant, from a single grouped read (one
965
+ * statement, served by the `(provider_id, tenant_id)` index). `active` counts
966
+ * every status except `disabled` — an account parked by the health machine
967
+ * (`cooldown`) is still a connection, matching how the account-overview badge
968
+ * reads status. Used by the provider list overview (`accountCount` /
969
+ * `activeAccountCount`); totals are never counted in a per-provider loop.
970
+ */
971
+ async providerAccountCounts(
972
+ tenantId: string,
973
+ ): Promise<readonly { providerId: string; total: number; active: number }[]> {
974
+ const rows = await this.db
975
+ .select({
976
+ providerId: providerAccounts.providerId,
977
+ total: sql<number>`count(*)`,
978
+ active: sql<number>`sum(case when ${providerAccounts.status} <> 'disabled' then 1 else 0 end)`,
979
+ })
980
+ .from(providerAccounts)
981
+ .where(globalOrOwnedBy(providerAccounts.tenantId, tenantId))
982
+ .groupBy(providerAccounts.providerId);
983
+ return rows.map((row) => ({
984
+ providerId: row.providerId,
985
+ total: Number(row.total),
986
+ active: Number(row.active),
987
+ }));
988
+ }
989
+
990
+ /**
991
+ * Per-provider enabled model-row counts for one tenant, from a single grouped
992
+ * read over `models ⋈ providers`. A model counts only when the row is enabled
993
+ * and the tenant has not suppressed it via `tenant_disabled_models` — the
994
+ * same visibility rule the per-provider model listing applies, so the
995
+ * overview badge never disagrees with what the detail page would list.
996
+ */
997
+ async providerModelCounts(
998
+ tenantId: string,
999
+ ): Promise<readonly { providerId: string; count: number }[]> {
1000
+ const rows = await this.db
1001
+ .select({ providerId: models.providerId, count: sql<number>`count(*)` })
1002
+ .from(models)
1003
+ .innerJoin(providers, eq(models.providerId, providers.id))
1004
+ .leftJoin(
1005
+ tenantDisabledModels,
1006
+ and(
1007
+ eq(tenantDisabledModels.tenantId, tenantId),
1008
+ eq(tenantDisabledModels.providerId, models.providerId),
1009
+ eq(tenantDisabledModels.modelId, models.modelId),
1010
+ eq(tenantDisabledModels.endpointPath, models.endpointPath),
1011
+ ),
1012
+ )
1013
+ .where(
1014
+ and(
1015
+ eq(models.enabled, true),
1016
+ globalOrOwnedBy(providers.tenantId, tenantId),
1017
+ isNull(tenantDisabledModels.id),
1018
+ ),
1019
+ )
1020
+ .groupBy(models.providerId);
1021
+ return rows.map((row) => ({ providerId: row.providerId, count: Number(row.count) }));
1022
+ }
1023
+
1024
+ /**
1025
+ * Pool-as-account rows for one provider. Only providers whose rate limit
1026
+ * follows the egress address materialize these; every other provider's pool
1027
+ * list stays empty, so real accounts are returned unchanged.
1028
+ *
1029
+ * The pool row is the source of health truth: `provider_pool_accounts`
1030
+ * rows are created at backfill and never mutated, so the surface reads the
1031
+ * owning pool's live status/last-* fields and lives on top of them.
1032
+ */
1033
+ private async listPoolAccounts(
1034
+ tenantId: string,
1035
+ providerId: string,
1036
+ ): Promise<readonly ProviderAccountResponse[]> {
1037
+ if (!providerRateLimitIsIpScoped(providerId)) return [];
1038
+ const rows = await this.db
1039
+ .select()
1040
+ .from(providerPoolAccounts)
1041
+ .where(
1042
+ and(
1043
+ eq(providerPoolAccounts.providerId, providerId),
1044
+ eq(providerPoolAccounts.tenantId, tenantId),
1045
+ ),
1046
+ )
1047
+ .orderBy(asc(providerPoolAccounts.createdAt), asc(providerPoolAccounts.id));
1048
+ if (rows.length === 0) return [];
1049
+ const pools = await this.poolsById(tenantId, rows.map((row) => row.networkPoolId));
1050
+ const usage = await this.poolUsage(tenantId, rows.map((row) => row.networkPoolId));
1051
+ return rows.map((row) => this.mapPoolAccount(row, pools.get(row.networkPoolId), usage.get(row.networkPoolId)));
1052
+ }
1053
+
1054
+ /** Pool-as-account rows across every provider, for tenant-wide listings. */
1055
+ private async listAllPoolAccounts(
1056
+ tenantId: string,
1057
+ ): Promise<readonly ProviderAccountResponse[]> {
1058
+ const rows = await this.db
1059
+ .select()
1060
+ .from(providerPoolAccounts)
1061
+ .where(eq(providerPoolAccounts.tenantId, tenantId))
1062
+ .orderBy(asc(providerPoolAccounts.createdAt), asc(providerPoolAccounts.id));
1063
+ if (rows.length === 0) return [];
1064
+ const pools = await this.poolsById(tenantId, rows.map((row) => row.networkPoolId));
1065
+ const usage = await this.poolUsage(tenantId, rows.map((row) => row.networkPoolId));
1066
+ return rows.map((row) => this.mapPoolAccount(row, pools.get(row.networkPoolId), usage.get(row.networkPoolId)));
1067
+ }
1068
+
1069
+ /** Selects the owning network pools for a set of pool-account rows. */
1070
+ private async poolsById(
1071
+ tenantId: string,
1072
+ poolIds: readonly string[],
1073
+ ): Promise<Map<string, typeof networkPools.$inferSelect>> {
1074
+ const map = new Map<string, typeof networkPools.$inferSelect>();
1075
+ if (poolIds.length === 0) return map;
1076
+ const rows = await this.db
1077
+ .select()
1078
+ .from(networkPools)
1079
+ .where(
1080
+ and(
1081
+ eq(networkPools.tenantId, tenantId),
1082
+ inArray(networkPools.id, poolIds),
1083
+ ),
1084
+ );
1085
+ for (const row of rows) map.set(row.id, row);
1086
+ return map;
1087
+ }
1088
+
1089
+ /**
1090
+ * Today + lifetime token usage per pool, from telemetry. Pools carry no
1091
+ * rows in `telemetry_usage_totals` (that table only admits account/api_key
1092
+ * identity types), so lifetime here is aggregated from the retained event
1093
+ * window (the same bounded window the usage page reads) rather than from
1094
+ * durable rollups.
1095
+ */
1096
+ private async poolUsage(
1097
+ tenantId: string,
1098
+ poolIds: readonly string[],
1099
+ ): Promise<Map<string, { today: ProviderAccountTokenUsage; allTime: ProviderAccountTokenUsage }>> {
1100
+ const map = new Map<string, { today: ProviderAccountTokenUsage; allTime: ProviderAccountTokenUsage }>();
1101
+ if (poolIds.length === 0) return map;
1102
+ const todayStart = new Date();
1103
+ todayStart.setUTCHours(0, 0, 0, 0);
1104
+ const [todayRows, lifetimeRows] = await Promise.all([
1105
+ this.db
1106
+ .select({
1107
+ poolId: telemetryEvents.networkPoolId,
1108
+ requests: sql<number>`count(*)`,
1109
+ errors: sql<number>`sum(case when ${IS_GATEWAY_ERROR_SQL} then 1 else 0 end)`,
1110
+ inputTokens: sql<number>`coalesce(sum(${telemetryEvents.inputTokens}), 0)`,
1111
+ outputTokens: sql<number>`coalesce(sum(${telemetryEvents.outputTokens}), 0)`,
1112
+ })
1113
+ .from(telemetryEvents)
1114
+ .where(
1115
+ and(
1116
+ eq(telemetryEvents.tenantId, tenantId),
1117
+ gte(telemetryEvents.createdAt, todayStart),
1118
+ inArray(telemetryEvents.networkPoolId, poolIds),
1119
+ ),
1120
+ )
1121
+ .groupBy(telemetryEvents.networkPoolId),
1122
+ this.db
1123
+ .select({
1124
+ poolId: telemetryEvents.networkPoolId,
1125
+ requests: sql<number>`count(*)`,
1126
+ errors: sql<number>`sum(case when ${IS_GATEWAY_ERROR_SQL} then 1 else 0 end)`,
1127
+ inputTokens: sql<number>`coalesce(sum(${telemetryEvents.inputTokens}), 0)`,
1128
+ outputTokens: sql<number>`coalesce(sum(${telemetryEvents.outputTokens}), 0)`,
1129
+ })
1130
+ .from(telemetryEvents)
1131
+ .where(
1132
+ and(
1133
+ eq(telemetryEvents.tenantId, tenantId),
1134
+ inArray(telemetryEvents.networkPoolId, poolIds),
1135
+ ),
1136
+ )
1137
+ .groupBy(telemetryEvents.networkPoolId),
1138
+ ]);
1139
+ const toUsage = (row: {
1140
+ readonly requests: number | string | null;
1141
+ readonly errors: number | string | null;
1142
+ readonly inputTokens: number | string | null;
1143
+ readonly outputTokens: number | string | null;
1144
+ }): ProviderAccountTokenUsage => {
1145
+ const inputTokens = Number(row.inputTokens ?? 0);
1146
+ const outputTokens = Number(row.outputTokens ?? 0);
1147
+ return {
1148
+ requests: Number(row.requests ?? 0),
1149
+ errors: Number(row.errors ?? 0),
1150
+ inputTokens,
1151
+ outputTokens,
1152
+ totalTokens: inputTokens + outputTokens,
1153
+ };
1154
+ };
1155
+ for (const id of poolIds) {
1156
+ const today = todayRows.find((row) => row.poolId === id);
1157
+ const lifetime = lifetimeRows.find((row) => row.poolId === id);
1158
+ map.set(id, {
1159
+ today: today ? toUsage(today) : emptyUsage,
1160
+ allTime: lifetime ? toUsage(lifetime) : emptyUsage,
1161
+ });
1162
+ }
1163
+ return map;
1164
+ }
1165
+
1166
+ private mapPoolAccount(
1167
+ row: typeof providerPoolAccounts.$inferSelect,
1168
+ pool: typeof networkPools.$inferSelect | undefined,
1169
+ usage: { today: ProviderAccountTokenUsage; allTime: ProviderAccountTokenUsage } | undefined,
1170
+ ): ProviderAccountResponse {
1171
+ return {
1172
+ id: row.id,
1173
+ providerId: row.providerId,
1174
+ tenantId: row.tenantId,
1175
+ label: row.label,
1176
+ credentialKind: "none",
1177
+ // Health truth lives on the owning pool; fall back to the row only when
1178
+ // the pool row is unreachable (deleted cascade would have removed the
1179
+ // account row, so this is defensive).
1180
+ status: pool?.status ?? row.status,
1181
+ usageToday: usage?.today ?? emptyUsage,
1182
+ usageAllTime: usage?.allTime ?? emptyUsage,
1183
+ consecutiveFailures: pool?.consecutiveFailures ?? row.consecutiveFailures,
1184
+ ...(pool?.lastSuccessAt
1185
+ ? { lastSuccessAt: pool.lastSuccessAt.toISOString() }
1186
+ : row.lastSuccessAt
1187
+ ? { lastSuccessAt: row.lastSuccessAt.toISOString() }
1188
+ : {}),
1189
+ ...(pool?.lastError ? { lastError: pool.lastError } : row.lastError ? { lastError: row.lastError } : {}),
1190
+ ...(pool?.lastErrorCategory
1191
+ ? { lastErrorCategory: pool.lastErrorCategory }
1192
+ : row.lastErrorCategory
1193
+ ? { lastErrorCategory: row.lastErrorCategory }
1194
+ : {}),
1195
+ ...(pool?.lastErrorAt
1196
+ ? { lastErrorAt: pool.lastErrorAt.toISOString() }
1197
+ : row.lastErrorAt
1198
+ ? { lastErrorAt: row.lastErrorAt.toISOString() }
1199
+ : {}),
1200
+ ...(pool?.cooldownUntil
1201
+ ? { cooldownUntil: pool.cooldownUntil.toISOString() }
1202
+ : row.cooldownUntil
1203
+ ? { cooldownUntil: row.cooldownUntil.toISOString() }
1204
+ : {}),
1205
+ ...(pool?.lastRecoveredAt
1206
+ ? { lastRecoveredAt: pool.lastRecoveredAt.toISOString() }
1207
+ : row.lastRecoveredAt
1208
+ ? { lastRecoveredAt: row.lastRecoveredAt.toISOString() }
1209
+ : {}),
1210
+ createdAt: row.createdAt.toISOString(),
1211
+ sortIndex: 0,
1212
+ kind: "pool",
1213
+ networkPoolId: row.networkPoolId,
1214
+ ...(pool?.providerCooldowns
1215
+ ? { providerCooldowns: activePoolProviderCooldowns(pool.providerCooldowns) }
1216
+ : {}),
1217
+ };
1218
+ }
1219
+
1220
+ async createAccount(
1221
+ tenantId: string,
1222
+ providerId: string,
1223
+ request: CreateProviderAccountRequest,
1224
+ existingTx?: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1225
+ includeUsage = true,
1226
+ sortIndexOverride?: number,
1227
+ ): Promise<ProviderAccountResponse> {
1228
+ // Callers inside an existing transaction pass it in so the account lands in
1229
+ // that unit of work (the batch path); otherwise this opens its own.
1230
+ const run = async (
1231
+ tx: Parameters<Parameters<CartethyiaDatabase["transaction"]>[0]>[0],
1232
+ ): Promise<ProviderAccountResponse> => {
1233
+ let effectiveSecret = request.secret;
1234
+ let effectiveCredentialKind = request.credentialKind;
1235
+ const requestedCredentialMode: CredentialMode = request.credentialMode ?? "auto";
1236
+ let effectiveCredentialMode: CredentialMode = requestedCredentialMode;
1237
+ let tokenExpiresAt: Date | undefined;
1238
+ let jwtIssuer: string | undefined;
1239
+ let oauthRefreshCiphertext: Buffer | undefined;
1240
+ let oauthExpiresAt: Date | undefined;
1241
+ let oauthHasRefreshToken = false;
1242
+ let pastedAuthState: Readonly<Record<string, unknown>> = {};
1243
+
1244
+ if (
1245
+ (request.credentialKind === "oauth" || request.credentialKind === "api_key") &&
1246
+ request.secret.trim().length > 0
1247
+ ) {
1248
+ const trimmed = request.secret.trim();
1249
+ const parts = parsePastedOAuthCredential(trimmed);
1250
+ pastedAuthState = parts.authState;
1251
+ const hasRefreshToken = parts.refreshToken !== parts.accessToken;
1252
+ const parsedJwt =
1253
+ requestedCredentialMode === "api_key"
1254
+ ? undefined
1255
+ : parseJwtCredential(parts.accessToken);
1256
+ if (requestedCredentialMode === "jwt" && parsedJwt === undefined) {
1257
+ throw new ConsoleDomainError(
1258
+ "invalid_request",
1259
+ 400,
1260
+ "credentialMode jwt requires a valid three-part JWT",
1261
+ );
1262
+ }
1263
+ if (requestedCredentialMode === "api_key") {
1264
+ effectiveSecret = parts.accessToken;
1265
+ effectiveCredentialKind = "api_key";
1266
+ effectiveCredentialMode = "api_key";
1267
+ } else if (
1268
+ parsedJwt !== undefined &&
1269
+ (requestedCredentialMode === "jwt" || !hasRefreshToken)
1270
+ ) {
1271
+ effectiveSecret = parts.accessToken;
1272
+ effectiveCredentialKind = "api_key";
1273
+ effectiveCredentialMode = "jwt";
1274
+ tokenExpiresAt = parsedJwt.expiresAt;
1275
+ // Kept alongside the expiry: the console shows who issued a static
1276
+ // token, and the secret itself is never readable after this point.
1277
+ jwtIssuer = parsedJwt.issuer;
1278
+ } else if (request.credentialKind === "oauth" || hasRefreshToken) {
1279
+ effectiveSecret = parts.accessToken;
1280
+ effectiveCredentialKind = hasRefreshToken ? "oauth" : "api_key";
1281
+ effectiveCredentialMode = hasRefreshToken ? "auto" : "api_key";
1282
+ if (hasRefreshToken) {
1283
+ oauthRefreshCiphertext = encryptCredential(parts.refreshToken);
1284
+ oauthHasRefreshToken = true;
1285
+ }
1286
+ oauthExpiresAt = parts.expiresAt;
1287
+ } else {
1288
+ effectiveCredentialMode = "api_key";
1289
+ }
1290
+ }
1291
+
1292
+ // Append to the end of this provider's list rather than relying on
1293
+ // creation time, so a new account never displaces existing positions.
1294
+ const credentialFingerprint =
1295
+ effectiveCredentialKind === "none" || effectiveSecret.length === 0
1296
+ ? undefined
1297
+ : hashSecret(effectiveSecret);
1298
+ const accountAuthState = {
1299
+ ...pastedAuthState,
1300
+ ...(request.authState ?? {}),
1301
+ credentialMode: effectiveCredentialMode,
1302
+ ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt: tokenExpiresAt.toISOString() }),
1303
+ ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
1304
+ };
1305
+ const nextSortIndex =
1306
+ sortIndexOverride ?? (await this.nextAccountSortIndex(tx, providerId, tenantId));
1307
+ // Read existing labels only when one has to be generated: a named
1308
+ // account costs no extra query, and this is the path a large batch
1309
+ // paste walks once per row.
1310
+ const label =
1311
+ request.label ??
1312
+ (await this.generateAccountLabel(tx, providerId, tenantId, effectiveCredentialMode));
1313
+ const rows = await tx
1314
+ .insert(providerAccounts)
1315
+ .values({
1316
+ providerId,
1317
+ tenantId,
1318
+ sortIndex: nextSortIndex,
1319
+ label,
1320
+ credentialCiphertext: encryptCredential(effectiveSecret),
1321
+ ...(credentialFingerprint ? { credentialFingerprint } : {}),
1322
+ credentialKind: effectiveCredentialKind,
1323
+ status: "active",
1324
+ authState: accountAuthState,
1325
+ // An OAuth account pasted without a refresh token is a *static*
1326
+ // token: the pasted value is a bearer token used exactly as issued
1327
+ // and there is no refresh grant to run. Flag it as static so the
1328
+ // console reads it as an informational "static token" rather than
1329
+ // "re-login required" — the token is still valid and dispatchable —
1330
+ // and so the refresh sweep skips it instead of retrying a refresh
1331
+ // that can never succeed.
1332
+ ...(effectiveCredentialKind === "oauth" && !oauthHasRefreshToken || effectiveCredentialMode === "jwt"
1333
+ ? { staticToken: true }
1334
+ : {}),
1335
+ })
1336
+ .returning();
1337
+ const row = rows[0];
1338
+ if (!row) throw new Error("failed to create provider account");
1339
+
1340
+ if (effectiveCredentialKind === "oauth") {
1341
+ await tx.insert(providerOauthStates).values({
1342
+ providerAccountId: row.id,
1343
+ ...(oauthRefreshCiphertext ? { refreshCiphertext: oauthRefreshCiphertext } : {}),
1344
+ expiresAt: oauthExpiresAt ?? null,
1345
+ });
1346
+ }
1347
+ if (request.credentialKind === "oauth" && !oauthHasRefreshToken) {
1348
+ pushStructuredConsoleLog(
1349
+ "info",
1350
+ "OAuth access token stored as a static API credential; it will not be refreshed",
1351
+ {
1352
+ event: "token_refresh",
1353
+ providerId,
1354
+ accountId: row.id,
1355
+ errorCode: "static_token",
1356
+ },
1357
+ );
1358
+ }
1359
+
1360
+ if (!includeUsage) {
1361
+ const emptyUsage = { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };
1362
+ return this.mapAccount(row, { today: emptyUsage, allTime: emptyUsage });
1363
+ }
1364
+ const [account] = await this.accountsWithUsage(tenantId, [row]);
1365
+ if (!account) throw new Error("created provider account could not be mapped");
1366
+ return account;
1367
+ };
1368
+
1369
+ try {
1370
+ if (existingTx !== undefined) {
1371
+ return await run(existingTx);
1372
+ }
1373
+ return await this.db.transaction(run);
1374
+ } catch (error) {
1375
+ if (isUniqueViolation(error)) {
1376
+ throw new ConsoleDomainError(
1377
+ "provider_account_duplicate",
1378
+ 409,
1379
+ "A provider account with this credential already exists",
1380
+ );
1381
+ }
1382
+ throw error;
1383
+ }
1384
+ }
1385
+
1386
+ /**
1387
+ * Creates many accounts in one round-trip.
1388
+ *
1389
+ * The whole batch shares one transaction, so a paste of 40 credentials costs
1390
+ * one connection checkout rather than 40. Each item is created through the
1391
+ * same `createAccount` path the single route uses — there is no second
1392
+ * implementation of credential detection to drift.
1393
+ *
1394
+ * Items are created sequentially inside that transaction: the unique
1395
+ * credential fingerprint makes two identical pastes collide, and a nested
1396
+ * transaction per item keeps that collision from aborting the whole batch.
1397
+ * Outcomes are reported per index, so a partial paste still lands the
1398
+ * accounts that were fine — an operator fixing one bad line should not have
1399
+ * to re-import 39.
1400
+ */
1401
+ async createAccountBatch(
1402
+ tenantId: string,
1403
+ providerId: string,
1404
+ requests: readonly CreateProviderAccountRequest[],
1405
+ ): Promise<CreateProviderAccountBatchResult> {
1406
+ if (requests.length === 0) {
1407
+ return { created: 0, failed: 0, results: [] };
1408
+ }
1409
+ const results: CreateProviderAccountBatchItemResult[] = [];
1410
+ let created = 0;
1411
+ let failed = 0;
1412
+
1413
+ await this.db.transaction(async (tx) => {
1414
+ let nextSortIndex = await this.nextAccountSortIndex(tx, providerId, tenantId);
1415
+ for (const [index, request] of requests.entries()) {
1416
+ try {
1417
+ // A nested transaction acts as a savepoint: a duplicate-fingerprint
1418
+ // violation rolls back only this item, not the accounts before it.
1419
+ const account = await tx.transaction(async (inner) =>
1420
+ this.createAccount(tenantId, providerId, request, inner, false, nextSortIndex),
1421
+ );
1422
+ created += 1;
1423
+ nextSortIndex += 1;
1424
+ results.push({ index, ok: true, ...(account ? { account } : {}) });
1425
+ } catch (error) {
1426
+ failed += 1;
1427
+ results.push({
1428
+ index,
1429
+ ok: false,
1430
+ error: error instanceof Error ? error.message : String(error),
1431
+ code: error instanceof ConsoleDomainError ? error.code : "create_failed",
1432
+ });
1433
+ }
1434
+ }
1435
+ });
1436
+
1437
+ return { created, failed, results };
1438
+ }
1439
+
1440
+ async updateAccount(
1441
+ tenantId: string,
1442
+ providerId: string,
1443
+ accountId: string,
1444
+ patch: UpdateProviderAccountRequest,
1445
+ ): Promise<ProviderAccountResponse | undefined> {
1446
+ const set: Partial<typeof providerAccounts.$inferInsert> = {};
1447
+ if (patch.label !== undefined) set.label = patch.label;
1448
+ if (patch.secret !== undefined) {
1449
+ set.credentialCiphertext = encryptCredential(patch.secret);
1450
+ set.credentialFingerprint =
1451
+ patch.secret.length === 0 ? null : hashSecret(patch.secret);
1452
+ }
1453
+ if (patch.status !== undefined) set.status = patch.status;
1454
+ // Toggling the static-token flag: turning it on declares the credential is
1455
+ // used as issued and never refreshed, so any stale re-auth flag is cleared —
1456
+ // the operator has said the account is fine, and the pill must stop reading
1457
+ // "Re-login required". Turning it off returns the account to normal OAuth
1458
+ // refresh handling; the sweep picks it up again on its next pass.
1459
+ if (patch.staticToken !== undefined) {
1460
+ set.staticToken = patch.staticToken;
1461
+ if (patch.staticToken) {
1462
+ set.lastError = null;
1463
+ set.lastErrorCategory = null;
1464
+ set.lastErrorAt = null;
1465
+ }
1466
+ }
1467
+ // Status toggles are not recovery: preserve the health machine's evidence
1468
+ // until the operator uses Recover or replaces the rejected credential.
1469
+ const clearsFailureState = patch.secret !== undefined && patch.secret.length > 0;
1470
+ if (clearsFailureState) {
1471
+ set.consecutiveFailures = 0;
1472
+ set.cooldownUntil = null;
1473
+ set.modelCooldowns = {};
1474
+ set.lastError = null;
1475
+ set.lastErrorCategory = null;
1476
+ set.lastErrorAt = null;
1477
+ }
1478
+ const where = and(
1479
+ eq(providerAccounts.id, accountId),
1480
+ eq(providerAccounts.providerId, providerId),
1481
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1482
+ );
1483
+ try {
1484
+ const rows =
1485
+ Object.keys(set).length > 0
1486
+ ? await this.db.update(providerAccounts).set(set).where(where).returning()
1487
+ : await this.db.select().from(providerAccounts).where(where);
1488
+ const row = rows[0];
1489
+ if (!row) return undefined;
1490
+ // Secret/status mutation: drop any cached credential so the next
1491
+ // attempt decrypts the new ciphertext (or refuses a disabled account).
1492
+ if (patch.secret !== undefined || patch.status !== undefined) {
1493
+ invalidateCredentialCache(accountId);
1494
+ }
1495
+ const [account] = await this.accountsWithUsage(tenantId, [row]);
1496
+ return account;
1497
+ } catch (error) {
1498
+ if (isUniqueViolation(error)) {
1499
+ throw new ConsoleDomainError(
1500
+ "provider_account_duplicate",
1501
+ 409,
1502
+ "A provider account with this credential already exists",
1503
+ );
1504
+ }
1505
+ throw error;
1506
+ }
1507
+ }
1508
+
1509
+ private mapAccount(
1510
+ row: typeof providerAccounts.$inferSelect,
1511
+ usage: {
1512
+ readonly today: ProviderAccountTokenUsage;
1513
+ readonly allTime: ProviderAccountTokenUsage;
1514
+ readonly inflight?: number | undefined;
1515
+ },
1516
+ ): ProviderAccountResponse {
1517
+ const authState =
1518
+ row.authState !== null && typeof row.authState === "object" && !Array.isArray(row.authState)
1519
+ ? (row.authState as Record<string, unknown>)
1520
+ : undefined;
1521
+ const rawCredentialMode = authState?.["credentialMode"];
1522
+ const credentialMode: CredentialMode | undefined =
1523
+ rawCredentialMode === "auto" || rawCredentialMode === "jwt" || rawCredentialMode === "api_key"
1524
+ ? rawCredentialMode
1525
+ : undefined;
1526
+ const tokenExpiresAt =
1527
+ typeof authState?.["tokenExpiresAt"] === "string" ? authState["tokenExpiresAt"] : undefined;
1528
+ const jwtIssuer =
1529
+ typeof authState?.["jwtIssuer"] === "string" ? authState["jwtIssuer"] : undefined;
1530
+ const authMethod =
1531
+ typeof authState?.["authMethod"] === "string" ? authState["authMethod"] : undefined;
1532
+ return {
1533
+ id: row.id,
1534
+ providerId: row.providerId,
1535
+ tenantId: row.tenantId,
1536
+ label: row.label,
1537
+ credentialKind: row.credentialKind,
1538
+ ...(credentialMode === undefined ? {} : { credentialMode }),
1539
+ ...(tokenExpiresAt === undefined ? {} : { tokenExpiresAt }),
1540
+ ...(jwtIssuer === undefined ? {} : { jwtIssuer }),
1541
+ ...(authMethod === undefined ? {} : { authMethod }),
1542
+ status: row.status,
1543
+ ...(usage.inflight === undefined ? {} : { inflight: usage.inflight }),
1544
+ usageToday: usage.today,
1545
+ usageAllTime: usage.allTime,
1546
+ consecutiveFailures: row.consecutiveFailures,
1547
+ ...(row.lastSuccessAt ? { lastSuccessAt: row.lastSuccessAt.toISOString() } : {}),
1548
+ ...(row.lastError ? { lastError: row.lastError } : {}),
1549
+ ...(row.lastErrorCategory ? { lastErrorCategory: row.lastErrorCategory } : {}),
1550
+ ...(row.lastErrorAt ? { lastErrorAt: row.lastErrorAt.toISOString() } : {}),
1551
+ ...(row.cooldownUntil ? { cooldownUntil: row.cooldownUntil.toISOString() } : {}),
1552
+ ...(liveModelCooldowns(row.modelCooldowns) ?? {}),
1553
+ ...(row.lastRecoveredAt ? { lastRecoveredAt: row.lastRecoveredAt.toISOString() } : {}),
1554
+ createdAt: row.createdAt.toISOString(),
1555
+ sortIndex: row.sortIndex,
1556
+ ...(row.staticToken ? { staticToken: true } : {}),
1557
+ };
1558
+ }
1559
+
1560
+ async listAccountHealthEvents(
1561
+ tenantId: string,
1562
+ providerId: string,
1563
+ accountId: string,
1564
+ ): Promise<readonly AccountHealthEventRecord[]> {
1565
+ const owned = await this.db
1566
+ .select({ id: providerAccounts.id })
1567
+ .from(providerAccounts)
1568
+ .where(
1569
+ and(
1570
+ eq(providerAccounts.id, accountId),
1571
+ eq(providerAccounts.providerId, providerId),
1572
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1573
+ ),
1574
+ )
1575
+ .limit(1);
1576
+ if (owned.length === 0) return [];
1577
+ return listAccountHealthEvents(this.db, accountId);
1578
+ }
1579
+
1580
+ /** Deletes one account's stored health & error rows, for the modal's purge. */
1581
+ async purgeAccountHealthEvents(
1582
+ tenantId: string,
1583
+ providerId: string,
1584
+ accountId: string,
1585
+ ): Promise<number> {
1586
+ const owned = await this.db
1587
+ .select({ id: providerAccounts.id })
1588
+ .from(providerAccounts)
1589
+ .where(
1590
+ and(
1591
+ eq(providerAccounts.id, accountId),
1592
+ eq(providerAccounts.providerId, providerId),
1593
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1594
+ ),
1595
+ )
1596
+ .limit(1);
1597
+ if (owned.length === 0) return 0;
1598
+ return deleteAccountHealthEvents(this.db, accountId);
1599
+ }
1600
+ async listBuddyGrowthTasks(
1601
+ tenantId: string,
1602
+ providerId: string,
1603
+ accountId: string,
1604
+ dayKey: string,
1605
+ ): Promise<readonly BuddyGrowthTaskLedgerEntry[]> {
1606
+ const owned = await this.db
1607
+ .select({ id: providerAccounts.id })
1608
+ .from(providerAccounts)
1609
+ .where(
1610
+ and(
1611
+ eq(providerAccounts.id, accountId),
1612
+ eq(providerAccounts.providerId, providerId),
1613
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1614
+ ),
1615
+ )
1616
+ .limit(1);
1617
+ if (owned.length === 0) return [];
1618
+ const rows = await this.db
1619
+ .select({
1620
+ accountId: buddyTaskLedger.accountId,
1621
+ task: buddyTaskLedger.task,
1622
+ claimedAt: buddyTaskLedger.claimedAt,
1623
+ })
1624
+ .from(buddyTaskLedger)
1625
+ .where(
1626
+ and(
1627
+ eq(buddyTaskLedger.accountId, accountId),
1628
+ eq(buddyTaskLedger.dayKey, dayKey),
1629
+ ),
1630
+ );
1631
+ return rows.map((row) => ({
1632
+ accountId: row.accountId,
1633
+ task: row.task,
1634
+ claimedAt: row.claimedAt.toISOString(),
1635
+ }));
1636
+ }
1637
+
1638
+ async recoverAccount(
1639
+ tenantId: string,
1640
+ providerId: string,
1641
+ accountId: string,
1642
+ ): Promise<boolean> {
1643
+ const owned = await this.db
1644
+ .select({ id: providerAccounts.id })
1645
+ .from(providerAccounts)
1646
+ .where(
1647
+ and(
1648
+ eq(providerAccounts.id, accountId),
1649
+ eq(providerAccounts.providerId, providerId),
1650
+ globalOrOwnedBy(providerAccounts.tenantId, tenantId),
1651
+ ),
1652
+ )
1653
+ .limit(1);
1654
+ if (owned.length === 0) return false;
1655
+ return recoverAccount(this.db, accountId, "manual_operator_recovery");
1656
+ }
1657
+
1658
+
1659
+ async syncModels(tenantId: string, providerId: string): Promise<{ synced: number }> {
1660
+ return this.probing.syncModels(tenantId, providerId);
1661
+ }
1662
+ }