import { sql, type SQL, type SQLWrapper } from "drizzle-orm"; import { modelIdListIncludes } from "@opengeni/contracts/claude-subscription-model-ids"; import { rawRows, type Database } from "./database"; import { SUBSCRIPTION_CORE_CODEX_PROVIDER } from "./subscription-core-codex-provider"; import { SUBSCRIPTION_CORE_XAI_PROVIDER } from "./subscription-core-xai-adapter"; import { subscriptionCoreProvider } from "./subscription-core-providers"; import { subscriptionCoreWakeReason, type SubscriptionCoreWake, } from "./subscription-core/administration"; import { SUBSCRIPTION_CORE_CLAUDE_PROVIDER } from "./subscription-core-claude-adapter"; import { getSubscriptionCoreModelConnectionAccess, ModelConnectionWorkspaceNotInOrganizationError, readSubscriptionCoreModelConnectionAccess, removeSubscriptionCoreModelConnectionFromWorkspace, updateSubscriptionCoreModelConnectionAccess, withModelConnectionAccessScope, type ModelConnectionAccess, } from "./subscription-core/access-editor"; import { listSubscriptionCoreAdministeredWorkspaceIds, type SubscriptionCoreAccess, } from "./subscription-core/access"; // The policy shape, its errors and the route scope are shared with the // provider-neutral core editor; the public names stay exported from here. export { ModelConnectionAccessForbiddenError, ModelConnectionWorkspaceNotInOrganizationError, type ModelConnectionAccess, } from "./subscription-core/access-editor"; export type ModelConnectionKind = | "codex" | "supergrok" | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "openai" | "azure_openai" /** An organization's own OpenAI-compatible endpoint; always named by its connection id. */ | "openai_compatible"; export type ModelConnectionTarget = { accountId: string; workspaceId: string | null; subjectId: string; kind: ModelConnectionKind; connectionId: string; }; export function connectionModelAllowed( allowedModels: readonly string[] | null | undefined, modelId: string, ): boolean { // A model listed under any of its id forms is the same model. return allowedModels == null || modelIdListIncludes(allowedModels, modelId); } /** * Replace a default only when it is outside the assigned pool. An assigned * paused/unhealthy default remains explicit intent: rotation-off must wait, * not silently change the billed subscription. Allocation checks health later. */ export function assignedConnectionDefault( preferred: string | null, accounts: readonly { id: string; status: string; allocatorEnabled: boolean }[], ): string | null { return accounts.some((account) => account.id === preferred) ? preferred : (accounts.find((account) => account.status === "active" && account.allocatorEnabled)?.id ?? null); } function relation(target: ModelConnectionTarget): { table: SQLWrapper; condition: SQL } { if (subscriptionCoreProviderOfKind(target.kind)) throw new Error("Subscription access policies use the shared core"); if ( target.kind === "openai_compatible" && (target.workspaceId !== null || target.connectionId === "current") ) throw new Error("An OpenAI-compatible endpoint's access is set on its organization connection"); if (target.workspaceId === null) return { table: sql.identifier("organization_model_provider_connections"), condition: sql`account_id = ${target.accountId}::uuid AND provider_kind = ${target.kind} AND status = 'active' AND ${target.connectionId === "current" ? sql`true` : sql`id::text = ${target.connectionId}`}`, }; // Workspace OpenAI and Azure OpenAI keep their exact direct-connection rail; // only the organization connection has an access policy of this kind. if ( target.kind === "openai" || target.kind === "azure_openai" || target.kind === "openai_compatible" ) throw new Error("OpenAI access policies exist only for organization connections"); return { table: sql.identifier("connections"), condition: sql`account_id = ${target.accountId}::uuid AND workspace_id = ${target.workspaceId}::uuid AND id = ${target.connectionId}::uuid AND subject_id IS NULL AND kind = 'api_key' AND status = 'active' AND metadata->>'credentialRole' = ${target.kind === "vercel_gateway" ? "vercel_ai_gateway" : target.kind} ${target.kind === "anthropic" ? sql`AND lower(provider_domain) = 'api.anthropic.com'` : sql``} ${target.kind === "opper" ? sql`AND lower(provider_domain) = 'api.opper.ai'` : sql``}`, }; } export async function getModelConnectionAccess( db: Database, target: ModelConnectionTarget, ): Promise { if (subscriptionCoreProviderOfKind(target.kind)) return await getSubscriptionCoreProviderModelConnectionAccess(db, target); return await withModelConnectionAccessScope(db, target, async (tx) => { const { table, condition } = relation(target); const [row] = await rawRows( tx, sql`SELECT allowed_model_ids AS "allowedModels", allowed_workspace_ids AS "allowedWorkspaces", allow_personal_workspaces AS "allowPersonalWorkspaces", access_policy_version AS version FROM ${table} WHERE ${condition} LIMIT 1`, ); return row ?? null; }); } /** * The core provider of a connection kind whose access policy lives on the * shared subscription core once that provider cut over; null for the kinds * that never move (API-key connections) or have not moved yet. */ function subscriptionCoreProviderOfKind(kind: ModelConnectionKind): string | null { if (kind === "codex") return SUBSCRIPTION_CORE_CODEX_PROVIDER; if (kind === "supergrok") return SUBSCRIPTION_CORE_XAI_PROVIDER; if (kind === "claude_subscription") return SUBSCRIPTION_CORE_CLAUDE_PROVIDER; return null; } /** * The core wake of an access change to a connection of this kind (a wider * scope or model list can make waiting work placeable), with the provider * and the display name the wake reports, all from the provider's binding; * null for a kind whose provider is not on the core. */ export function subscriptionCoreAccessChangeWake( kind: ModelConnectionKind, accountId: string, ): { provider: string; displayName: string; wake: SubscriptionCoreWake } | null { const providerId = subscriptionCoreProviderOfKind(kind); if (!providerId) return null; const binding = subscriptionCoreProvider(providerId); return { provider: binding.adapter.provider, displayName: binding.adapter.displayName, wake: { accountId, reason: subscriptionCoreWakeReason(binding, "access_changed") }, }; } /** * A shared subscription connection's access on the shared subscription core, * with the workspaces that use it as their own and its delegated manager, for * a kind whose provider is on the core (the caller checked its route is * `core`). */ export async function readSubscriptionCoreProviderModelConnectionAccess( db: Database, target: ModelConnectionTarget, ): Promise { const provider = subscriptionCoreProviderOfKind(target.kind); if (!provider) throw new Error("This connection kind is not read from the core"); return await readSubscriptionCoreModelConnectionAccess(db, provider, target); } /** A shared subscription connection's access policy on the core (see the reader). */ export async function getSubscriptionCoreProviderModelConnectionAccess( db: Database, target: ModelConnectionTarget, ): Promise { const provider = subscriptionCoreProviderOfKind(target.kind); if (!provider) throw new Error("This connection kind is not read from the core"); return await getSubscriptionCoreModelConnectionAccess(db, provider, target); } /** Save what a shared subscription connection serves on the core (see the reader). */ export async function updateSubscriptionCoreProviderModelConnectionAccess( db: Database, target: ModelConnectionTarget, policy: ModelConnectionAccess, ): Promise { const provider = subscriptionCoreProviderOfKind(target.kind); if (!provider) throw new Error("This connection kind is not written to the core"); return await updateSubscriptionCoreModelConnectionAccess(db, provider, target, policy); } /** * Removes another workspace's own subscription connection from the workspace * in `target` (D-52), for a kind whose provider is on the core. True when * removed; null when no such connection serves the workspace. */ export async function removeSubscriptionCoreProviderModelConnectionFromWorkspace( db: Database, target: ModelConnectionTarget & { workspaceId: string }, ): Promise { const provider = subscriptionCoreProviderOfKind(target.kind); if (!provider) throw new Error("This connection kind is not written to the core"); return await removeSubscriptionCoreModelConnectionFromWorkspace(db, provider, target); } /** * The workspaces the person in `target` administers, which a workspace's own * subscription connection can be given to from that workspace's route (D-52). */ export async function listModelConnectionAdministeredWorkspaceIds( db: Database, target: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { return await listSubscriptionCoreAdministeredWorkspaceIds(db, target); } /** * A shared Codex connection's access on the shared subscription core, with * the workspaces that use it as their own and its delegated manager. */ export async function readSubscriptionCoreCodexModelConnectionAccess( db: Database, target: ModelConnectionTarget, ): Promise { if (target.kind !== "codex") throw new Error("Only Codex connections are read from the core"); return await readSubscriptionCoreProviderModelConnectionAccess(db, target); } /** A shared Codex connection's access policy on the shared subscription core. */ export async function getSubscriptionCoreCodexModelConnectionAccess( db: Database, target: ModelConnectionTarget, ): Promise { if (target.kind !== "codex") throw new Error("Only Codex connections are read from the core"); return await getSubscriptionCoreProviderModelConnectionAccess(db, target); } /** Save what a shared Codex connection serves on the core. */ export async function updateSubscriptionCoreCodexModelConnectionAccess( db: Database, target: ModelConnectionTarget, policy: ModelConnectionAccess, ): Promise { if (target.kind !== "codex") throw new Error("Only Codex connections are written to the core"); return await updateSubscriptionCoreProviderModelConnectionAccess(db, target, policy); } export async function updateModelConnectionAccess( db: Database, target: ModelConnectionTarget, policy: ModelConnectionAccess, ): Promise { if (subscriptionCoreProviderOfKind(target.kind)) return null; if (policy.allowedPeople != null) throw new Error("Only accounts on the shared subscription core can be limited to people"); return await withModelConnectionAccessScope(db, target, async (tx) => { const { table, condition } = relation(target); if (target.workspaceId !== null && policy.allowedWorkspaces !== null) throw new Error("Workspace connections cannot assign other workspaces"); if (target.workspaceId === null && policy.allowedWorkspaces !== null) { const allowed = await rawRows<{ workspace_id: string }>( tx, sql`select workspace_id from list_organization_workspace_ids(${target.accountId}::uuid)`, ); const ids = new Set(allowed.map((row) => row.workspace_id)); if (policy.allowedWorkspaces.some((id) => !ids.has(id))) throw new ModelConnectionWorkspaceNotInOrganizationError(); } const [row] = await rawRows( tx, sql`UPDATE ${table} SET allowed_model_ids = ${policy.allowedModels === null ? sql`NULL` : sql`ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(policy.allowedModels)}::jsonb))`}, allowed_workspace_ids = ${policy.allowedWorkspaces === null ? sql`NULL` : sql`ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(policy.allowedWorkspaces)}::jsonb)::uuid)`}, allow_personal_workspaces = ${policy.allowPersonalWorkspaces}, access_policy_version = access_policy_version + 1, access_policy_updated_by = ${target.subjectId}, access_policy_updated_at = now() WHERE ${condition} AND access_policy_version = ${policy.version} RETURNING allowed_model_ids AS "allowedModels", allowed_workspace_ids AS "allowedWorkspaces", allow_personal_workspaces AS "allowPersonalWorkspaces", access_policy_version AS version`, ); return row ?? null; }); }