import { and, eq, inArray, isNull } from "drizzle-orm"; import { withRlsContext, type Database } from "./database"; import { listConnectionsMetadataInScope, type ConnectionMetadataWithVerification, } from "./connection-metadata"; import { listWorkspaceProviderCustomModelsByKindInScope, type WorkspaceCustomModelProviderKind, type WorkspaceProviderCustomModel, } from "./model-catalog"; import { mapOrganizationModelProviderCustomModel, type OrganizationModelProviderAuthMethod, type OrganizationModelProviderCustomModel, type OrganizationModelCatalogProviderKind, } from "./organization-model-providers"; import { listOrganizationCompatibleEndpointsInScope, type OrganizationCompatibleEndpointForWorkspace, } from "./organization-compatible-model-endpoints"; import { isWorkspaceEuOnlyInScope } from "./organization-inference-residency"; import { organizationAnthropicApiKeyPool } from "./organization-anthropic-api-keys"; import * as schema from "./schema"; /** Attempt-local read results, never a cross-turn credential or authority cache. */ export type ModelProviderExecutionInputs = { claudeSubscriptionEnabled: boolean; loadOrganizationCredentials: boolean; workspaceModels: Record; organizationModels: Record< OrganizationModelCatalogProviderKind, OrganizationModelProviderCustomModel[] >; workspaceConnections: ConnectionMetadataWithVerification[]; encryptedCredentials: Partial>; /** Azure OpenAI's non-secret resource endpoint, beside its encrypted key. */ organizationEndpoints: Partial>; /** Azure OpenAI's sign-in method, when it is Microsoft Entra ID instead of a key. */ organizationAuthMethods: Partial>; /** * The organization's OpenAI-compatible endpoints this workspace can use, * with their models; each carries its encrypted key when credentials load. */ organizationCompatibleEndpoints: OrganizationCompatibleEndpointForWorkspace[]; /** * The organization's Anthropic API keys when its connection holds several * (encrypted, its own key first, without keys refused for lack of * credits); null for a single key, or when credentials don't load. */ organizationAnthropicApiKeys: { id: string; credentialEncrypted: string }[] | null; /** Whether the workspace is EU-only (`isWorkspaceEuOnly`), read in the same transaction. */ euOnly: boolean; }; /** * Read the full execution catalog in one scoped transaction. Selected workspace * credentials still use the normal live broker and model-access check afterwards. * Keep organization model queries unchanged: their row order feeds the catalog. */ export async function loadModelProviderExecutionInputs( db: Database, input: { accountId: string; workspaceId: string; claudeSubscriptionEnabled: boolean; loadOrganizationCredentials: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const euOnly = await isWorkspaceEuOnlyInScope(scopedDb, input); const kinds: WorkspaceCustomModelProviderKind[] = [ "vercel_gateway", "openrouter", "opper", "anthropic", ...(input.claudeSubscriptionEnabled ? ["claude_subscription" as const] : []), ]; const workspaceModels = await listWorkspaceProviderCustomModelsByKindInScope(scopedDb, { ...input, providerKinds: kinds, }); const workspaceConnections = await listConnectionsMetadataInScope( scopedDb, input.workspaceId, null, ); const organizationModels: ModelProviderExecutionInputs["organizationModels"] = { vercel_gateway: [], openrouter: [], opper: [], anthropic: [], claude_subscription: [], openai: [], azure_openai: [], }; // Organization-only kinds: a workspace's own OpenAI or Azure key is a // direct connection, not a custom-model provider. for (const providerKind of [...kinds, "openai" as const, "azure_openai" as const]) { const rows = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.accountId), eq(schema.organizationModelProviderCustomModels.providerKind, providerKind), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ); organizationModels[providerKind] = rows.map(mapOrganizationModelProviderCustomModel); } const encryptedCredentials: ModelProviderExecutionInputs["encryptedCredentials"] = {}; const organizationEndpoints: ModelProviderExecutionInputs["organizationEndpoints"] = {}; const organizationAuthMethods: ModelProviderExecutionInputs["organizationAuthMethods"] = {}; let organizationAnthropicApiKeys: ModelProviderExecutionInputs["organizationAnthropicApiKeys"] = null; if (input.loadOrganizationCredentials) { const rows = await scopedDb .select({ providerKind: schema.organizationModelProviderConnections.providerKind, credentialEncrypted: schema.organizationModelProviderConnections.credentialEncrypted, endpoint: schema.organizationModelProviderConnections.endpoint, authMethod: schema.organizationModelProviderConnections.authMethod, version: schema.organizationModelProviderConnections.version, apiKeyMembers: schema.organizationModelProviderConnections.apiKeyMembers, apiKeyCreditRefusals: schema.organizationModelProviderConnections.apiKeyCreditRefusals, }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq(schema.organizationModelProviderConnections.status, "active"), inArray(schema.organizationModelProviderConnections.providerKind, [ "vercel_gateway", "openrouter", "opper", "anthropic", "openai", "azure_openai", ]), ), ); for (const row of rows) { if (row.providerKind !== "elevenlabs" && row.providerKind !== "openai_compatible") { encryptedCredentials[row.providerKind] = row.credentialEncrypted; } if (row.providerKind === "azure_openai" && row.endpoint) { organizationEndpoints.azure_openai = row.endpoint; } if (row.providerKind === "azure_openai" && row.authMethod !== "api_key") { organizationAuthMethods.azure_openai = row.authMethod; } if (row.providerKind === "anthropic") { organizationAnthropicApiKeys = organizationAnthropicApiKeyPool(row); } } } const organizationCompatibleEndpoints = await listOrganizationCompatibleEndpointsInScope( scopedDb, { accountId: input.accountId, includeCredentials: input.loadOrganizationCredentials }, ); return { claudeSubscriptionEnabled: input.claudeSubscriptionEnabled, loadOrganizationCredentials: input.loadOrganizationCredentials, workspaceModels, workspaceConnections, organizationModels, encryptedCredentials, organizationEndpoints, organizationAuthMethods, organizationCompatibleEndpoints, organizationAnthropicApiKeys, euOnly, }; }); }