import { createHash } from "node:crypto"; import { CLAUDE_DEFAULT_CONNECTION_MODEL_IDS, environmentsEncryptionKeyBytes, type AzureEntraProviderCredential, type Settings, } from "@opengeni/config"; import { ClaudeProviderAccountAuthoritySnapshotV1 } from "@opengeni/contracts"; import { and, count, eq, exists, inArray, isNull, sql } from "drizzle-orm"; import { z } from "zod"; import { type Database, setSubjectRlsContext, withRlsContext } from "./database"; import { subscriptionCoreClaudeCustomModelAdmitted, type SubscriptionCoreClaudeAdmissionCarrier, } from "./subscription-core-claude-reads"; import { decryptEnvironmentValue } from "./environment-crypto"; import { defaultModelRequestHash } from "./model-catalog"; import * as schema from "./schema"; import type { ConnectedModelListPricing, OrganizationModelProviderAuthMethod } from "./schema"; export type { ConnectedModelListPricing, OrganizationModelProviderAuthMethod } from "./schema"; /** Providers whose organization key runs models, with custom models to choose. */ export type OrganizationModelCatalogProviderKind = | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "openai" | "azure_openai"; /** Every organization provider key, including ElevenLabs for realtime voice. */ export type OrganizationModelProviderKind = OrganizationModelCatalogProviderKind | "elevenlabs"; export type OrganizationModelProviderConnection = { providerKind: OrganizationModelProviderKind; status: "active" | "revoked"; version: number; /** Azure OpenAI only: the non-secret resource endpoint; null for every other kind. */ endpoint: string | null; /** How the connection signs in; Microsoft Entra ID methods are Azure OpenAI only. */ authMethod: OrganizationModelProviderAuthMethod; createdAt: Date; updatedAt: Date; }; /** * What an organization connection signs in with. An API key is stored as the * key itself, so every existing row reads unchanged; a Microsoft Entra ID * method is stored as a small versioned JSON document under the same * encryption (the app's client secret is the only secret in it). */ export type OrganizationModelProviderCredential = | { method: "api_key"; apiKey: string } | { method: "entra_client_secret"; tenantId: string; clientId: string; clientSecret: string } | { method: "entra_deployment_identity" }; /** The decrypted credential of an active Azure OpenAI or OpenAI connection, with its endpoint. */ export type OrganizationDirectProviderCredential = | { apiKey: string; endpoint: string | null } | { azureEntra: AzureEntraProviderCredential; endpoint: string | null }; /** The plaintext stored (encrypted) for a credential, and its non-secret method. */ export function organizationModelProviderCredentialPlaintext( credential: OrganizationModelProviderCredential, ): { authMethod: OrganizationModelProviderAuthMethod; plaintext: string } { switch (credential.method) { case "api_key": return { authMethod: "api_key", plaintext: credential.apiKey }; case "entra_client_secret": return { authMethod: "entra_client_secret", plaintext: JSON.stringify({ version: 1, tenantId: credential.tenantId, clientId: credential.clientId, clientSecret: credential.clientSecret, }), }; case "entra_deployment_identity": return { authMethod: "entra_deployment_identity", plaintext: JSON.stringify({ version: 1 }) }; } } const StoredEntraClientSecret = z.object({ version: z.literal(1), tenantId: z.string().min(1), clientId: z.string().min(1), clientSecret: z.string().min(1), }); /** * Read a stored credential back. An unreadable Entra document yields null, so * the connection fails closed instead of sending it anywhere as a key. */ function storedDirectCredential( authMethod: OrganizationModelProviderAuthMethod, plaintext: string, endpoint: string | null, ): OrganizationDirectProviderCredential | null { if (authMethod === "api_key") return { apiKey: plaintext, endpoint }; if (authMethod === "entra_deployment_identity") return { azureEntra: { source: "deployment_identity" }, endpoint }; let document: unknown; try { document = JSON.parse(plaintext); } catch { return null; } const parsed = StoredEntraClientSecret.safeParse(document); if (!parsed.success) return null; return { azureEntra: { source: "client_secret", tenantId: parsed.data.tenantId, clientId: parsed.data.clientId, clientSecret: parsed.data.clientSecret, }, endpoint, }; } export type OrganizationModelProviderCustomModel = { id: string; accountId: string; providerKind: OrganizationModelCatalogProviderKind; upstreamModelId: string; label: string | null; /** OpenAI and Azure OpenAI only: the catalogue model whose list rate prices it. */ listPricingModelId: string | null; /** OpenAI and Azure OpenAI only: the administrator's own list rate. */ listPricing: ConnectedModelListPricing | null; version: number; retiredAt: Date | null; createdAt: Date; updatedAt: Date; }; /** * What a connected model's usage costs: the catalogue model it is priced * from (an Azure deployment's base model), its own rate, or unknown (null). */ export type ConnectedModelListPrice = | { basis: "model"; modelId: string } | { basis: "custom"; pricing: ConnectedModelListPricing } | null; /** The stored columns of a {@link ConnectedModelListPrice}. */ export function connectedModelListPriceColumns(price: ConnectedModelListPrice): { priceBasisModelId: string | null; listPricing: ConnectedModelListPricing | null; } { return { priceBasisModelId: price?.basis === "model" ? price.modelId : null, listPricing: price?.basis === "custom" ? price.pricing : null, }; } /** Exact accepted source; never resolve the caller's current pool at this fence. */ export type OrganizationClaudeModelAdmissionAuthority = | { sessionId: string } | { authoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1; /** * The scheduled task an update re-admits. On Claude's core route its * accepted authority (the task's compatibility record) decides instead * of the v1 snapshot; ignored on the legacy route. */ scheduledTaskId?: string; /** * The accepted source a fresh prompt copies: an edit's source turn, or * the receiving session of agent-submitted work. On Claude's core * route its accepted authority decides; ignored on the legacy route * (the snapshot already carries it). Absent for a human's own new work * and for service actors, which resolve the current source. */ acceptedSource?: | { kind: "session_turn"; turnId: string } | { kind: "receiving_session"; sessionId: string }; }; /** The carrier whose accepted authority Claude's core route reads for an admission. */ function claudeAdmissionCarrier( authority: OrganizationClaudeModelAdmissionAuthority, ): SubscriptionCoreClaudeAdmissionCarrier | null { if ("sessionId" in authority) return { kind: "session_initial", sessionId: authority.sessionId }; if (authority.scheduledTaskId !== undefined) return { kind: "scheduled_task", scheduledTaskId: authority.scheduledTaskId }; return authority.acceptedSource ?? null; } export class OrganizationModelProviderConflictError extends Error {} export class OrganizationModelProviderLimitError extends Error {} function digest(value: unknown): string { return createHash("sha256").update(JSON.stringify(value)).digest("hex"); } export function organizationModelProviderCredentialDigest(credential: string): string { return createHash("sha256").update(credential).digest("hex"); } /** Runs `use` as an organization administrator (refused otherwise), in the organization's scope. */ export async function withOrganizationProviderAdministrator( db: Database, input: { organizationId: string; actorSubjectId: string }, use: (scopedDb: Database) => Promise, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); await scopedDb.execute(sql` select get_organization_administration_overview( ${input.organizationId}::uuid, ${input.actorSubjectId} ) `); return await use(scopedDb); }, ); } function mapConnection( row: typeof schema.organizationModelProviderConnections.$inferSelect, ): OrganizationModelProviderConnection { return { // Every caller reads one of its own kinds; OpenAI-compatible endpoints have their own reads. providerKind: row.providerKind as OrganizationModelProviderKind, status: row.status, version: row.version, endpoint: row.endpoint ?? null, authMethod: row.authMethod, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } function mapConnectionOperation( row: typeof schema.organizationModelProviderConnectionOperations.$inferSelect, ): OrganizationModelProviderConnection { return { providerKind: row.providerKind as OrganizationModelProviderKind, status: row.resultStatus, version: row.resultVersion, endpoint: row.resultEndpoint ?? null, authMethod: row.resultAuthMethod, createdAt: row.resultCreatedAt, updatedAt: row.resultUpdatedAt, }; } async function recordConnectionOperation( db: Database, input: { accountId: string; operationId: string; requestHash: string; connection: OrganizationModelProviderConnection; }, ): Promise { await db.insert(schema.organizationModelProviderConnectionOperations).values({ accountId: input.accountId, providerKind: input.connection.providerKind, operationId: input.operationId, requestHash: input.requestHash, resultStatus: input.connection.status, resultVersion: input.connection.version, resultEndpoint: input.connection.endpoint, resultAuthMethod: input.connection.authMethod, resultCreatedAt: input.connection.createdAt, resultUpdatedAt: input.connection.updatedAt, }); } export function mapOrganizationModelProviderCustomModel( row: typeof schema.organizationModelProviderCustomModels.$inferSelect, ): OrganizationModelProviderCustomModel { return { id: row.id, accountId: row.accountId, // Callers filter by their own kinds; OpenAI-compatible models have their own reads. providerKind: row.providerKind as OrganizationModelCatalogProviderKind, upstreamModelId: row.upstreamModelId, label: row.label, listPricingModelId: row.priceBasisModelId, listPricing: row.listPricing, version: row.version, retiredAt: row.retiredAt, createdAt: row.createdAt, updatedAt: row.updatedAt, }; } const mapModel = mapOrganizationModelProviderCustomModel; export async function getOrganizationModelProviderConnection( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelProviderKind; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.organizationId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), ), ) .limit(1); return row ? mapConnection(row) : null; }); } export async function upsertOrganizationModelProviderConnection( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelProviderKind; credentialEncrypted: string; credentialDigest: string; /** * Required for `azure_openai` and refused for every other kind: the * normalized non-secret resource endpoint. The request hash binds it with * the key digest, so a replay naming another endpoint conflicts and an * endpoint change is a new connection version. */ endpoint?: string | null; /** * How the stored credential signs in; defaults to an API key. Microsoft * Entra ID methods are refused for every kind but `azure_openai`. A * non-default method is bound into the request hash. */ authMethod?: OrganizationModelProviderAuthMethod; /** * OpenAI and Azure OpenAI only: models (Azure deployment names) the caller * already checked with this credential, saved with the connection in the * same transaction. One the organization already offers is kept as it is. * Bound into the request hash when present. */ models?: readonly string[]; /** * The price the server detected for a new model in `models` while * checking it (Azure's reported base model). Not part of the request * identity; a model the organization already offers keeps its own. */ modelListPrices?: Readonly>; operationId: string; expectedVersion?: number; }, ): Promise { const endpoint = input.endpoint ?? null; const authMethod = input.authMethod ?? "api_key"; const models = input.models?.length ? [...new Set(input.models)].sort() : null; if ((input.providerKind === "azure_openai") !== (endpoint !== null)) throw new Error("an organization Azure OpenAI connection needs exactly its resource endpoint"); if (authMethod !== "api_key" && input.providerKind !== "azure_openai") throw new Error( "only an organization Azure OpenAI connection signs in with Microsoft Entra ID", ); if (models && input.providerKind !== "openai" && input.providerKind !== "azure_openai") throw new Error("only an organization OpenAI or Azure OpenAI connection saves its models"); return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider:${input.organizationId}:${input.providerKind}`}, 0))`, ); const requestHash = digest({ operation: "upsert", expectedVersion: input.expectedVersion, credentialDigest: input.credentialDigest, // Present only for Azure, so every pre-existing kind keeps its hash. ...(endpoint === null ? {} : { endpoint }), // Present only for Entra, so every API-key connection keeps its hash. ...(authMethod === "api_key" ? {} : { authMethod }), // Present only when models are saved with it, so other requests keep their hash. ...(models === null ? {} : { models }), }); const [replay] = await scopedDb .select() .from(schema.organizationModelProviderConnectionOperations) .where( and( eq(schema.organizationModelProviderConnectionOperations.accountId, input.organizationId), eq(schema.organizationModelProviderConnectionOperations.providerKind, input.providerKind), eq(schema.organizationModelProviderConnectionOperations.operationId, input.operationId), ), ) .limit(1); if (replay) { if (replay.requestHash !== requestHash) throw new OrganizationModelProviderConflictError(); return mapConnectionOperation(replay); } const [existing] = await scopedDb .select() .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.organizationId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), ), ) .for("update") .limit(1); const expected = input.expectedVersion ?? 0; if ((existing?.version ?? 0) !== expected) throw new OrganizationModelProviderConflictError(); const [row] = existing ? await scopedDb .update(schema.organizationModelProviderConnections) .set({ status: "active", credentialEncrypted: input.credentialEncrypted, endpoint, authMethod, version: existing.version + 1, operationId: input.operationId, requestHash, updatedBySubjectId: input.actorSubjectId, updatedAt: new Date(), }) .where(eq(schema.organizationModelProviderConnections.id, existing.id)) .returning() : await scopedDb .insert(schema.organizationModelProviderConnections) .values({ accountId: input.organizationId, providerKind: input.providerKind, credentialEncrypted: input.credentialEncrypted, endpoint, authMethod, operationId: input.operationId, requestHash, updatedBySubjectId: input.actorSubjectId, }) .returning(); if (!row) throw new Error("organization provider connection write returned no row"); const connection = mapConnection(row); await recordConnectionOperation(scopedDb, { accountId: input.organizationId, operationId: input.operationId, requestHash, connection, }); for (const upstreamModelId of models ?? []) { await ensureOrganizationModelProviderCustomModel(scopedDb, { organizationId: input.organizationId, actorSubjectId: input.actorSubjectId, // Checked above: only OpenAI and Azure OpenAI save models here. providerKind: input.providerKind as "openai" | "azure_openai", upstreamModelId, // One operation per model of this request, so the save stays replayable. operationId: derivedOperationId(`${input.operationId}:model:${upstreamModelId}`), ...(input.modelListPrices && Object.hasOwn(input.modelListPrices, upstreamModelId) ? { listPrice: input.modelListPrices[upstreamModelId]! } : {}), }); } return connection; }); } /** A stable UUID for an operation derived from another one. */ function derivedOperationId(seed: string): string { const bytes = createHash("sha256").update(seed, "utf8").digest().subarray(0, 16); bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50; bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } /** Offer a model unless the organization already offers it. */ async function ensureOrganizationModelProviderCustomModel( scopedDb: Database, input: Parameters[1], ): Promise { const [offered] = await scopedDb .select({ id: schema.organizationModelProviderCustomModels.id }) .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.upstreamModelId, input.upstreamModelId), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ) .limit(1); if (offered) return; await createOrganizationModelProviderCustomModel(scopedDb, input); } export async function revokeOrganizationModelProviderConnection( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelProviderKind; operationId: string; expectedVersion: number; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider:${input.organizationId}:${input.providerKind}`}, 0))`, ); await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider-models:${input.organizationId}:${input.providerKind}`}, 0))`, ); const requestHash = digest({ operation: "revoke", expectedVersion: input.expectedVersion }); const [replay] = await scopedDb .select() .from(schema.organizationModelProviderConnectionOperations) .where( and( eq(schema.organizationModelProviderConnectionOperations.accountId, input.organizationId), eq(schema.organizationModelProviderConnectionOperations.providerKind, input.providerKind), eq(schema.organizationModelProviderConnectionOperations.operationId, input.operationId), ), ) .limit(1); if (replay) { if (replay.requestHash !== requestHash) throw new OrganizationModelProviderConflictError(); return mapConnectionOperation(replay); } const [existing] = await scopedDb .select() .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.organizationId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), ), ) .for("update") .limit(1); if (!existing) throw new OrganizationModelProviderConflictError(); if (existing.version !== input.expectedVersion) throw new OrganizationModelProviderConflictError(); const [row] = await scopedDb .update(schema.organizationModelProviderConnections) .set({ status: "revoked", credentialEncrypted: "", version: existing.version + 1, operationId: input.operationId, requestHash, updatedBySubjectId: input.actorSubjectId, updatedAt: new Date(), }) .where(eq(schema.organizationModelProviderConnections.id, existing.id)) .returning(); if (!row) throw new Error("organization provider revoke returned no row"); const connection = mapConnection(row); await recordConnectionOperation(scopedDb, { accountId: input.organizationId, operationId: input.operationId, requestHash, connection, }); return connection; }); } export async function organizationModelProviderConnectionActiveForWorkspace( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelProviderKind }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.organizationModelProviderConnections.id }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), eq(schema.organizationModelProviderConnections.status, "active"), ), ) .limit(1); return Boolean(row); }); } export async function loadOrganizationModelProviderApiKey( db: Database, settings: Settings, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelProviderKind }, prepared?: { loadOrganizationCredentials: boolean; encryptedCredentials: Partial>; organizationAuthMethods: Partial>; }, ): Promise { const key = environmentsEncryptionKeyBytes(settings); if (prepared && prepared.loadOrganizationCredentials !== (key !== null)) { throw new Error("Prepared provider credentials do not match encryption settings"); } if (!key) return null; if (prepared) { const encrypted = prepared.encryptedCredentials[input.providerKind]; // A Microsoft Entra ID connection has no key to hand out. if ( input.providerKind === "azure_openai" && (prepared.organizationAuthMethods.azure_openai ?? "api_key") !== "api_key" ) return null; return encrypted === undefined ? null : decryptEnvironmentValue(key, encrypted); } return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select({ credentialEncrypted: schema.organizationModelProviderConnections.credentialEncrypted, authMethod: schema.organizationModelProviderConnections.authMethod, }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), eq(schema.organizationModelProviderConnections.status, "active"), ), ) .limit(1); return row && row.authMethod === "api_key" ? decryptEnvironmentValue(key, row.credentialEncrypted) : null; }); } /** Execution metadata only, under the same tenant scope as the credential loader. */ export async function getOrganizationModelProviderExecutionConnectionId( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelProviderKind }, ): Promise { return withRlsContext(db, input, async (tx) => { const [row] = await tx .select({ id: schema.organizationModelProviderConnections.id }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), eq(schema.organizationModelProviderConnections.status, "active"), ), ) .limit(1); return row?.id ?? null; }); } /** * The decrypted key (or Azure OpenAI's Microsoft Entra ID sign-in) and * non-secret endpoint of an active organization connection, read under the * workspace's RLS scope (the connection's access policy decides which of the * organization's shared and Personal workspaces see it). * Null when there is no active connection or no encryption key; callers then * fail closed and never fall back to deployment credentials. */ export async function loadOrganizationModelProviderCredential( db: Database, settings: Settings, input: { accountId: string; workspaceId: string; providerKind: "openai" | "azure_openai" }, prepared?: { loadOrganizationCredentials: boolean; encryptedCredentials: Partial>; organizationEndpoints: Partial>; /** Present for an Azure OpenAI connection that signs in with Microsoft Entra ID. */ organizationAuthMethods: Partial>; }, ): Promise { const key = environmentsEncryptionKeyBytes(settings); if (prepared && prepared.loadOrganizationCredentials !== (key !== null)) { throw new Error("Prepared provider credentials do not match encryption settings"); } if (!key) return null; if (prepared) { const encrypted = prepared.encryptedCredentials[input.providerKind]; if (encrypted === undefined) return null; const azure = input.providerKind === "azure_openai"; return storedDirectCredential( (azure ? prepared.organizationAuthMethods.azure_openai : undefined) ?? "api_key", decryptEnvironmentValue(key, encrypted), azure ? (prepared.organizationEndpoints.azure_openai ?? null) : null, ); } return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select({ credentialEncrypted: schema.organizationModelProviderConnections.credentialEncrypted, endpoint: schema.organizationModelProviderConnections.endpoint, authMethod: schema.organizationModelProviderConnections.authMethod, }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), eq(schema.organizationModelProviderConnections.status, "active"), ), ) .limit(1); return row ? storedDirectCredential( row.authMethod, decryptEnvironmentValue(key, row.credentialEncrypted), row.endpoint ?? null, ) : null; }); } /** * The administrator's view of an active organization connection credential, * for a setup check (Azure deployment verification) before a custom model is * saved. Never returned to a client. */ export async function loadOrganizationModelProviderCredentialForAdministrator( db: Database, settings: Settings, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelProviderKind; }, ): Promise { const key = environmentsEncryptionKeyBytes(settings); if (!key) return null; return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { const [row] = await scopedDb .select({ credentialEncrypted: schema.organizationModelProviderConnections.credentialEncrypted, endpoint: schema.organizationModelProviderConnections.endpoint, authMethod: schema.organizationModelProviderConnections.authMethod, }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.organizationId), eq(schema.organizationModelProviderConnections.providerKind, input.providerKind), eq(schema.organizationModelProviderConnections.status, "active"), ), ) .limit(1); return row ? storedDirectCredential( row.authMethod, decryptEnvironmentValue(key, row.credentialEncrypted), row.endpoint ?? null, ) : null; }); } export async function listOrganizationModelProviderCustomModelsForWorkspace( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelCatalogProviderKind; includeRetired?: boolean; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.accountId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), ...(input.includeRetired ? [] : [isNull(schema.organizationModelProviderCustomModels.retiredAt)]), ), ); return rows.map(mapModel); }); } export type OrganizationModelProviderCatalogEntry = { active: boolean; models: OrganizationModelProviderCustomModel[]; /** Azure OpenAI only: the connection's non-secret endpoint (null when never connected). */ endpoint?: string | null; }; /** Read provider readiness and active model definitions without credential material. */ export async function getOrganizationModelProviderCatalogForWorkspace( db: Database, input: { accountId: string; workspaceId: string; providerKinds: readonly OrganizationModelCatalogProviderKind[]; }, ): Promise> { if (input.providerKinds.length === 0) return await getOrganizationModelProviderCatalogInScope(db, input); return await withRlsContext(db, input, (scopedDb) => getOrganizationModelProviderCatalogInScope(scopedDb, input), ); } /** Internal reader; the caller owns the workspace's tenant scope and shared fence. */ export async function getOrganizationModelProviderCatalogInScope( scopedDb: Database, input: { accountId: string; workspaceId: string; providerKinds: readonly OrganizationModelCatalogProviderKind[]; }, ): Promise> { const catalog: Record< OrganizationModelCatalogProviderKind, OrganizationModelProviderCatalogEntry > = { vercel_gateway: { active: false, models: [] }, openrouter: { active: false, models: [] }, anthropic: { active: false, models: [] }, claude_subscription: { active: false, models: [] }, opper: { active: false, models: [] }, openai: { active: false, models: [] }, azure_openai: { active: false, models: [], endpoint: null }, }; if (input.providerKinds.length === 0) return catalog; // Every row of a requested kind: readiness comes from active rows only, // while Azure's non-secret endpoint is kept from a revoked row too, so its // curated deployments stay listed (not ready) instead of vanishing. const connections = await scopedDb .select({ providerKind: schema.organizationModelProviderConnections.providerKind, status: schema.organizationModelProviderConnections.status, endpoint: schema.organizationModelProviderConnections.endpoint, }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), inArray(schema.organizationModelProviderConnections.providerKind, [...input.providerKinds]), ), ); const models = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.accountId), inArray(schema.organizationModelProviderCustomModels.providerKind, [ ...input.providerKinds, ]), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ); for (const connection of connections) { if (connection.providerKind === "elevenlabs" || connection.providerKind === "openai_compatible") continue; const entry = catalog[connection.providerKind]; if (connection.status === "active") entry.active = true; if (connection.providerKind === "azure_openai") entry.endpoint = connection.endpoint ?? null; } for (const model of models) if (model.providerKind !== "openai_compatible") catalog[model.providerKind].models.push(mapModel(model)); return catalog; } export async function getOrganizationModelProviderCustomModelForExecution( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelCatalogProviderKind; upstreamModelId: string; }, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { const [row] = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.accountId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.upstreamModelId, input.upstreamModelId), ), ) .orderBy( sql`(${schema.organizationModelProviderCustomModels.retiredAt} is null) desc`, sql`${schema.organizationModelProviderCustomModels.updatedAt} desc`, ) .limit(1); return row ? mapModel(row) : null; }); } export async function withOrganizationModelProviderCustomModelReadLock( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelCatalogProviderKind; }, use: (scopedDb: Database) => Promise, ): Promise { return await withRlsContext(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock_shared(hashtextextended(${`organization-model-provider-models:${input.accountId}:${input.providerKind}`}, 0))`, ); return await use(scopedDb); }); } export async function lockActiveOrganizationModelProviderCustomModelForAdmission( db: Database, input: { accountId: string; workspaceId: string; providerKind: OrganizationModelCatalogProviderKind; upstreamModelId: string; claudeAuthority?: OrganizationClaudeModelAdmissionAuthority; }, ): Promise { return await withOrganizationModelProviderCustomModelReadLock(db, input, async (scopedDb) => { if (input.providerKind === "claude_subscription") { if (!input.claudeAuthority) return null; // The core admits from the organization pool and never reads a v1 snapshot. if ( !(await subscriptionCoreClaudeCustomModelAdmitted(scopedDb, { accountId: input.accountId, workspaceId: input.workspaceId, upstreamModelId: input.upstreamModelId, carrier: claudeAdmissionCarrier(input.claudeAuthority), })) ) return null; } const [row] = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.accountId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.upstreamModelId, input.upstreamModelId), isNull(schema.organizationModelProviderCustomModels.retiredAt), input.providerKind === "claude_subscription" ? undefined : exists( scopedDb .select({ id: schema.organizationModelProviderConnections.id }) .from(schema.organizationModelProviderConnections) .where( and( eq(schema.organizationModelProviderConnections.accountId, input.accountId), eq( schema.organizationModelProviderConnections.providerKind, input.providerKind, ), eq(schema.organizationModelProviderConnections.status, "active"), ), ), ), ), ) .limit(1); return row ? mapModel(row) : null; }); } export async function listOrganizationModelProviderCustomModels( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelCatalogProviderKind; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { const rows = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ); return rows.map(mapModel); }); } /** * First connection of a Claude account for the organization: offer the * default models. Does nothing once the organization has any Claude model * record of this kind, active or removed, so a configured or trimmed list is * never changed. Returns how many models were added. */ export async function seedOrganizationClaudeDefaultModels( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: "anthropic" | "claude_subscription"; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider-models:${input.organizationId}:${input.providerKind}`}, 0))`, ); const [existing] = await scopedDb .select({ value: count() }) .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), ), ); if (Number(existing?.value ?? 0) > 0) return 0; await scopedDb.insert(schema.organizationModelProviderCustomModels).values( CLAUDE_DEFAULT_CONNECTION_MODEL_IDS.map((upstreamModelId) => ({ accountId: input.organizationId, providerKind: input.providerKind, upstreamModelId, label: null, createOperationId: crypto.randomUUID(), createRequestHash: defaultModelRequestHash(upstreamModelId), createdBySubjectId: input.actorSubjectId, })), ); return CLAUDE_DEFAULT_CONNECTION_MODEL_IDS.length; }); } export async function createOrganizationModelProviderCustomModel( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelCatalogProviderKind; upstreamModelId: string; label?: string; operationId: string; /** * OpenAI and Azure OpenAI only: the price the server detected while * checking the model (Azure's reported base model). Not part of the * request identity, so a replay returns the first result. */ listPrice?: ConnectedModelListPrice; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider-models:${input.organizationId}:${input.providerKind}`}, 0))`, ); const requestHash = digest({ upstreamModelId: input.upstreamModelId, label: input.label ?? null, }); const [replay] = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.createOperationId, input.operationId), ), ) .limit(1); if (replay) { if (replay.createRequestHash !== requestHash) throw new OrganizationModelProviderConflictError(); return mapModel(replay); } const [{ active = 0, total = 0 } = {}] = await scopedDb .select({ active: count( sql`case when ${schema.organizationModelProviderCustomModels.retiredAt} is null then 1 end`, ), total: count(), }) .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), ), ); if (Number(active) >= 100 || Number(total) >= 1000) throw new OrganizationModelProviderLimitError(); const [duplicate] = await scopedDb .select({ id: schema.organizationModelProviderCustomModels.id }) .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.upstreamModelId, input.upstreamModelId), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ) .limit(1); if (duplicate) throw new OrganizationModelProviderConflictError(); const [row] = await scopedDb .insert(schema.organizationModelProviderCustomModels) .values({ accountId: input.organizationId, providerKind: input.providerKind, upstreamModelId: input.upstreamModelId, label: input.label ?? null, ...(input.listPrice !== undefined && (input.providerKind === "openai" || input.providerKind === "azure_openai") ? connectedModelListPriceColumns(input.listPrice) : {}), createOperationId: input.operationId, createRequestHash: requestHash, createdBySubjectId: input.actorSubjectId, }) .returning(); if (!row) throw new Error("organization custom model create returned no row"); return mapModel(row); }); } export async function retireOrganizationModelProviderCustomModel( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: OrganizationModelCatalogProviderKind; customModelId: string; expectedVersion: number; operationId: string; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => { await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider-models:${input.organizationId}:${input.providerKind}`}, 0))`, ); const requestHash = digest({ customModelId: input.customModelId, expectedVersion: input.expectedVersion, }); const [replay] = await scopedDb .select() .from(schema.organizationModelProviderCustomModels) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.deleteOperationId, input.operationId), ), ) .limit(1); if (replay) { if (replay.deleteRequestHash !== requestHash) throw new OrganizationModelProviderConflictError(); return mapModel(replay); } const [row] = await scopedDb .update(schema.organizationModelProviderCustomModels) .set({ retiredAt: new Date(), deleteOperationId: input.operationId, deleteRequestHash: requestHash, version: input.expectedVersion + 1, updatedAt: new Date(), }) .where( and( eq(schema.organizationModelProviderCustomModels.accountId, input.organizationId), eq(schema.organizationModelProviderCustomModels.providerKind, input.providerKind), eq(schema.organizationModelProviderCustomModels.id, input.customModelId), eq(schema.organizationModelProviderCustomModels.version, input.expectedVersion), isNull(schema.organizationModelProviderCustomModels.retiredAt), ), ) .returning(); if (!row) throw new OrganizationModelProviderConflictError(); return mapModel(row); }); } type CustomModelRow = typeof schema.organizationModelProviderCustomModels.$inferSelect; /** * Set what an organization OpenAI, Azure OpenAI or OpenAI-compatible model's * usage costs, inside the administrator's scope. The version guards * concurrent edits; repeating the change that produced the current version * returns the model unchanged. A missing or retired model is a conflict. */ export async function setOrganizationCustomModelListPriceInScope( scopedDb: Database, input: { organizationId: string; providerKind: "openai" | "azure_openai" | "openai_compatible"; /** OpenAI-compatible models only: the endpoint the model belongs to. */ connectionId?: string; customModelId: string; expectedVersion: number; price: ConnectedModelListPrice; }, ): Promise { const models = schema.organizationModelProviderCustomModels; await scopedDb.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`organization-model-provider-models:${input.organizationId}:${input.providerKind}`}, 0))`, ); const [current] = await scopedDb .select() .from(models) .where( and( eq(models.accountId, input.organizationId), eq(models.providerKind, input.providerKind), input.connectionId === undefined ? isNull(models.connectionId) : eq(models.connectionId, input.connectionId), eq(models.id, input.customModelId), isNull(models.retiredAt), ), ) .limit(1); if (!current) throw new OrganizationModelProviderConflictError(); const columns = connectedModelListPriceColumns(input.price); const unchanged = current.priceBasisModelId === columns.priceBasisModelId && sameListPricing(current.listPricing, columns.listPricing); if (current.version === input.expectedVersion + 1 && unchanged) return current; if (current.version !== input.expectedVersion) throw new OrganizationModelProviderConflictError(); const [row] = await scopedDb .update(models) .set({ ...columns, version: current.version + 1, updatedAt: new Date() }) .where(and(eq(models.id, current.id), eq(models.version, current.version))) .returning(); if (!row) throw new OrganizationModelProviderConflictError(); return row; } /** * Whether two stored rates are the same rate, field by field: jsonb keeps * its own key order, so a serialized comparison would miss a repeat. */ export function sameListPricing( left: ConnectedModelListPricing | null, right: ConnectedModelListPricing | null, ): boolean { if (left === null || right === null) return left === right; return ( left.inputMicrosPerMillionTokens === right.inputMicrosPerMillionTokens && left.cachedInputMicrosPerMillionTokens === right.cachedInputMicrosPerMillionTokens && left.cacheWriteMicrosPerMillionTokens === right.cacheWriteMicrosPerMillionTokens && left.outputMicrosPerMillionTokens === right.outputMicrosPerMillionTokens ); } /** {@link setOrganizationCustomModelListPriceInScope} for an OpenAI model or Azure deployment. */ export async function setOrganizationModelProviderCustomModelListPrice( db: Database, input: { organizationId: string; actorSubjectId: string; providerKind: "openai" | "azure_openai"; customModelId: string; expectedVersion: number; price: ConnectedModelListPrice; }, ): Promise { return await withOrganizationProviderAdministrator(db, input, async (scopedDb) => mapModel(await setOrganizationCustomModelListPriceInScope(scopedDb, input)), ); }