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