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