import { decryptEpayKey, encryptEpayKey } from "./epay/encryption-core.ts"; export type ModelProviderType = "openai" | "openai-compatible" | "anthropic"; export type ModelProviderCredential = Readonly<{ encryptedApiKey: string | null; }>; function encryptionMasterKey(environment: Readonly> = process.env) { return environment.MODEL_PROVIDER_CONFIG_ENCRYPTION_KEY?.trim() ?? ""; } export function encryptModelProviderApiKey( apiKey: string, environment: Readonly> = process.env, ) { return encryptEpayKey(apiKey.trim(), encryptionMasterKey(environment)); } export function decryptModelProviderApiKey( provider: ModelProviderCredential, environment: Readonly> = process.env, ) { if (!provider.encryptedApiKey) return ""; return decryptEpayKey(provider.encryptedApiKey, encryptionMasterKey(environment)); } export function modelProviderModelsUrl(provider: Readonly<{ providerType: ModelProviderType; baseUrl: string | null; }>) { if (provider.providerType === "openai") return "https://api.openai.com/v1/models"; if (provider.providerType === "anthropic") return "https://api.anthropic.com/v1/models"; const url = new URL(provider.baseUrl ?? ""); url.username = ""; url.password = ""; url.search = ""; url.hash = ""; const basePath = url.pathname.replace(/\/+$/, ""); url.pathname = basePath.endsWith("/models") ? basePath : `${basePath}/models`; return url.toString(); } export function modelProviderRequestHeaders(providerType: ModelProviderType, apiKey: string): Readonly> { return providerType === "anthropic" ? { "x-api-key": apiKey, "anthropic-version": "2023-06-01" } : { authorization: `Bearer ${apiKey}` }; } export function modelConnectionTestSucceeded(status: number) { return status >= 200 && status <= 299; }