UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

426 lines (425 loc) • 17.3 kB
/** * Provider Configuration Utility * Consolidated configuration helpers for all AI providers * Eliminates duplicate error messages and configuration logic * Enhanced with format validation and advanced error classification * Extended with Claude subscription OAuth support */ import type { APIValidationResult, ProviderConfigOptions, AnthropicAuthMethod, ClaudeSubscriptionTier, AnthropicAuthConfig, AnthropicAuthConfigResult, OpenAICompatConfigInput, OpenAICompatCredentials } from "../types/index.js"; /** * API key format validation patterns (extracted from advanced validation system) * Exported for use across the codebase to replace scattered regex patterns */ export declare const API_KEY_FORMATS: Record<string, RegExp>; /** * OAuth token format validation patterns * These patterns are more flexible as OAuth tokens can vary by provider */ export declare const OAUTH_TOKEN_FORMATS: Record<string, RegExp>; /** * API key length constants to replace scattered magic numbers */ export declare const API_KEY_LENGTHS: { readonly OPENAI_MIN: 48; readonly ANTHROPIC_MIN: 95; readonly HUGGINGFACE_EXACT: 37; readonly AZURE_MIN: 32; readonly MISTRAL_EXACT: 32; readonly AWS_ACCESS_KEY: 20; readonly GOOGLE_AI_EXACT: 39; }; /** * Project ID format validation (for Google Cloud) */ export declare const PROJECT_ID_FORMAT: { readonly MIN_LENGTH: 6; readonly MAX_LENGTH: 30; readonly PATTERN: RegExp; }; /** * Validates API key format for a specific provider * @param providerKey Provider identifier (e.g., 'openai', 'anthropic') * @param apiKey The API key to validate * @returns True if format is valid */ export declare function validateApiKeyFormat(providerKey: string, apiKey: string): boolean; /** * Enhanced validation with format checking * @param config Provider configuration options * @param enableFormatValidation Whether to validate API key format * @returns Validation result with detailed information */ export declare function validateApiKeyEnhanced(config: ProviderConfigOptions, enableFormatValidation?: boolean): APIValidationResult; /** * Validates an API key for a provider and returns it (BACKWARD COMPATIBLE) * Throws detailed error message if validation fails * @param config Provider configuration options * @returns The validated API key */ export declare function validateApiKey(config: ProviderConfigOptions): string; /** * Gets a provider model with fallback to default * @param envVar Environment variable name for the model * @param defaultModel Default model to use if env var not set * @returns The model name to use */ export declare function getProviderModel(envVar: string, defaultModel: string): string; /** * Checks if provider credentials are available * @param envVars Array of environment variable names to check * @returns True if one of the credentials is available */ export declare function hasProviderCredentials(envVars: string[]): boolean; /** * Evaluates a `ProviderDescriptor.envVars.extraRequiredFallbacks`-shaped * list against an env-var source. Each entry is either a single env var * name (satisfied on its own) or a nested array of names that must ALL be * present together (e.g. Vertex's GOOGLE_AUTH_CLIENT_EMAIL + * GOOGLE_AUTH_PRIVATE_KEY pair, which is only valid auth as a pair). * Returns true when at least one entry is satisfied. The single evaluation * site for this shape — every consumer (providerUtils.ts, providerHealth.ts, * setup.ts, environmentManager.ts) must call this instead of re-deriving the * same `.some()`/`.every()` logic, so they can't drift out of sync with each * other or with the real auth gate (hasGoogleCredentials()). * @param env Explicit env-var source (`process.env`, or a parsed .env file) — * never hardcoded, so callers checking a file's contents (not the live * process env) can reuse this too. */ export declare function satisfiesFallbacks(fallbacks: readonly (string | readonly string[])[] | undefined, env: Record<string, string | undefined>): boolean; /** * Creates Anthropic provider configuration * Supports both API key and OAuth authentication methods */ export declare function createAnthropicConfig(): ProviderConfigOptions; /** * Creates OpenAI provider configuration */ export declare function createOpenAIConfig(): ProviderConfigOptions; /** * Creates HuggingFace provider configuration */ export declare function createHuggingFaceConfig(): ProviderConfigOptions; /** * Creates Mistral provider configuration */ export declare function createMistralConfig(): ProviderConfigOptions; /** * Creates AWS Access Key configuration for Bedrock */ export declare function createAWSAccessKeyConfig(): ProviderConfigOptions; /** * Creates AWS Secret Key configuration for Bedrock */ export declare function createAWSSecretConfig(): ProviderConfigOptions; /** * Creates Azure OpenAI API Key configuration */ export declare function createAzureAPIKeyConfig(): ProviderConfigOptions; /** * Creates Azure OpenAI Endpoint configuration */ export declare function createAzureEndpointConfig(): ProviderConfigOptions; /** * Creates OpenAI Compatible provider configuration */ export declare function createOpenAICompatibleConfig(): ProviderConfigOptions; /** * Creates DeepSeek provider configuration */ export declare function createDeepSeekConfig(): ProviderConfigOptions; /** * Creates NVIDIA NIM provider configuration */ export declare function createNvidiaNimConfig(): ProviderConfigOptions; /** * Creates xAI Grok provider configuration. */ export declare function createXaiConfig(): ProviderConfigOptions; /** * Creates SambaNova provider configuration. */ export declare function createSambanovaConfig(): ProviderConfigOptions; export declare function createCerebrasConfig(): ProviderConfigOptions; /** * Creates Groq provider configuration. */ export declare function createGroqConfig(): ProviderConfigOptions; /** * Creates Cohere provider configuration. */ export declare function createCohereConfig(): ProviderConfigOptions; /** * Creates Replicate provider configuration. */ export declare function createReplicateConfig(): ProviderConfigOptions; /** * Creates Together AI provider configuration. */ export declare function createTogetherAIConfig(): ProviderConfigOptions; /** * Creates Fireworks AI provider configuration. */ export declare function createFireworksConfig(): ProviderConfigOptions; /** * Creates Perplexity provider configuration. */ export declare function createPerplexityConfig(): ProviderConfigOptions; /** * Creates Voyage AI provider configuration (embedding-only). */ export declare function createVoyageConfig(): ProviderConfigOptions; /** * Creates Jina AI provider configuration (embeddings + reranking). */ export declare function createJinaConfig(): ProviderConfigOptions; /** * Creates Stability AI provider configuration (image generation). */ export declare function createStabilityConfig(): ProviderConfigOptions; /** * Creates Ideogram provider configuration (image generation). */ export declare function createIdeogramConfig(): ProviderConfigOptions; /** * Creates Recraft provider configuration (image generation, vector focus). */ export declare function createRecraftConfig(): ProviderConfigOptions; /** * Creates Cloudflare Workers AI provider configuration. * * Cloudflare requires both `CLOUDFLARE_API_KEY` (workers-AI-scoped token) * AND `CLOUDFLARE_ACCOUNT_ID` since the endpoint is per-account. */ export declare function createCloudflareConfig(): ProviderConfigOptions; /** * Creates Google Vertex Project ID configuration */ export declare function createVertexProjectConfig(): ProviderConfigOptions; /** * Creates Google Cloud Authentication configuration */ export declare function createGoogleAuthConfig(): ProviderConfigOptions; /** * Creates Anthropic Base Provider configuration */ export declare function createAnthropicBaseConfig(): ProviderConfigOptions; /** * Gets AWS Region with default fallback * Supports both AWS_REGION and AWS_DEFAULT_REGION for broader compatibility */ export declare function getAWSRegion(): string; /** * Gets AWS Session Token if available */ export declare function getAWSSessionToken(): string | undefined; /** * Checks if HuggingFace credentials are available */ export declare function hasHuggingFaceCredentials(): boolean; /** * Gets the configured Anthropic authentication method * Defaults to "api_key" for backward compatibility * @returns The configured authentication method */ export declare function getAnthropicAuthMethod(): AnthropicAuthMethod; /** * Gets the configured Claude subscription tier * Defaults to "api" for backward compatibility (API key users) * @returns The configured subscription tier */ export declare function getAnthropicSubscriptionTier(): ClaudeSubscriptionTier; /** * Validates OAuth access token format * @param token The token to validate * @returns True if the token format is valid */ export declare function validateOAuthAccessToken(token: string): boolean; /** * Validates OAuth refresh token format * @param token The token to validate * @returns True if the token format is valid */ export declare function validateOAuthRefreshToken(token: string): boolean; /** * Detects the best available authentication method for Anthropic * Checks environment variables and returns the most appropriate auth configuration * @returns Complete authentication configuration */ export declare function detectAnthropicAuth(): AnthropicAuthConfigResult; /** * Checks if Anthropic credentials are available (either API key or OAuth) * @returns True if any valid authentication is configured */ export declare function hasAnthropicCredentials(): boolean; /** * Gets the authentication token or key for Anthropic API calls * Returns the appropriate credential based on configured auth method * @returns The API key or OAuth access token, or undefined if not configured */ export declare function getAnthropicCredential(): string | undefined; /** * Checks if OAuth refresh is needed based on token state * This is a placeholder for actual token expiration checking * @returns True if refresh is needed */ export declare function needsOAuthRefresh(): boolean; /** * Gets subscription tier limits for informational purposes * These are approximate limits and may change * @param tier The subscription tier * @returns Object with tier limit information */ export declare function getSubscriptionTierLimits(tier: ClaudeSubscriptionTier): { messagesPerDay: number | "unlimited"; contextWindow: number; priorityAccess: boolean; description: string; }; /** * Environment variables for Anthropic/Claude subscription configuration * These control authentication method, subscription tier, and feature flags */ export declare const ANTHROPIC_ENV_VARS: { /** Authentication method: "api_key" or "oauth" */ readonly AUTH_METHOD: "ANTHROPIC_AUTH_METHOD"; /** Subscription tier: "free", "pro", "max", "max_5", "max_20", or "api" */ readonly SUBSCRIPTION_TIER: "ANTHROPIC_SUBSCRIPTION_TIER"; /** Enable beta features: "true" or "false" */ readonly ENABLE_BETA_FEATURES: "ANTHROPIC_ENABLE_BETA_FEATURES"; /** API key for api_key authentication */ readonly API_KEY: "ANTHROPIC_API_KEY"; /** OAuth access token for oauth authentication (canonical, with BC fallbacks) */ readonly OAUTH_ACCESS_TOKEN: "ANTHROPIC_OAUTH_TOKEN"; /** OAuth refresh token for oauth authentication */ readonly OAUTH_REFRESH_TOKEN: "ANTHROPIC_OAUTH_REFRESH_TOKEN"; /** OAuth token expiry timestamp (Unix epoch in seconds) */ readonly OAUTH_TOKEN_EXPIRY: "ANTHROPIC_OAUTH_TOKEN_EXPIRY"; }; /** * Valid subscription tier values for validation */ export declare const VALID_SUBSCRIPTION_TIERS: readonly ClaudeSubscriptionTier[]; /** * Valid authentication method values for validation */ export declare const VALID_AUTH_METHODS: readonly AnthropicAuthMethod[]; /** * Validates a subscription tier value * @param tier The tier value to validate * @returns True if the tier is valid, false otherwise */ export declare function isValidSubscriptionTier(tier: string | undefined): tier is ClaudeSubscriptionTier; /** * Validates an authentication method value * @param method The method value to validate * @returns True if the method is valid, false otherwise */ export declare function isValidAuthMethod(method: string | undefined): method is AnthropicAuthMethod; /** * Validates subscription tier and returns a detailed result * @param tier The tier value to validate * @returns Validation result with error details if invalid */ export declare function validateSubscriptionTier(tier: string | undefined): { isValid: boolean; tier?: ClaudeSubscriptionTier; error?: string; }; /** * Gets the complete Anthropic authentication configuration * Detects auth method from environment or config and loads appropriate credentials * * @returns Complete AnthropicAuthConfig with method, credentials, and tier */ export declare function getAnthropicAuthConfig(): AnthropicAuthConfig; /** * Detects the subscription tier from environment variables or config * Checks environment variable first, then config, defaults to "api" if using API key * * @returns The detected subscription tier */ export declare function detectSubscriptionTier(): ClaudeSubscriptionTier; /** * Determines whether beta features should be enabled * Checks environment/config and defaults based on authentication method * * @returns True if beta features should be enabled */ export declare function shouldEnableBetaFeatures(): boolean; /** * Gets complete subscription configuration including auth, tier, and features * Combines all configuration sources into a unified config object * * @returns Complete subscription configuration */ export declare function getAnthropicSubscriptionConfig(): { auth: AnthropicAuthConfig; tier: ClaudeSubscriptionTier; betaFeaturesEnabled: boolean; limits: ReturnType<typeof getSubscriptionTierLimits>; isConfigured: boolean; error?: string; }; /** * Checks if the current subscription tier has access to a specific feature * @param feature The feature to check * @param currentTier The current subscription tier (optional, auto-detects if not provided) * @returns True if the tier has access to the feature */ export declare function hasSubscriptionFeature(feature: "extended_thinking" | "priority_access" | "vision" | "file_analysis" | "mcp_tools" | "computer_use" | "web_search", currentTier?: ClaudeSubscriptionTier): boolean; /** * Gets a human-readable description of the current authentication configuration * Useful for debugging and user feedback * * @returns Human-readable configuration description */ export declare function describeAnthropicConfig(): string; /** * Resolves the {apiKey, baseURL} pair for a config-driven OpenAI-compatible * catalog entry (see OpenAICompatCatalogEntry in types/providers.ts). * * Extracted from the identical 6-line precedence block that was copy-pasted * across groq.ts, xai.ts, togetherAi.ts, fireworks.ts, perplexity.ts, and * mistral.ts, plus Cloudflare's accountId-computed-baseURL variant. * * Precedence (matches every ported subclass's original behavior exactly): * apiKey: credentials.apiKey (trimmed, non-blank) > env var > throw * baseURL: credentials.baseURL (trimmed, non-blank) * > env var (if entry.baseURLEnvVar is set, trimmed, non-blank) * > entry.defaultBaseURL * baseURL (computedBaseURL entries, e.g. Cloudflare): * credentials.baseURL > computedBaseURL.build(accountId), where * accountId = credentials.accountId (trimmed) > env var (trimmed) * > throw computedBaseURL.missingValueMessage */ export declare function resolveOpenAICompatConfig(entry: OpenAICompatConfigInput, credentials?: OpenAICompatCredentials): { apiKey: string; baseURL: string; }; /** * TypeSafe (Jev) — the `decide` inference type. Not a text provider. */ export declare function createTypeSafeConfig(): ProviderConfigOptions; /** * Laya — the `decide` inference type. Not a text provider, and it has no * built-in endpoint: LAYA_BASE_URL is required alongside the key. */ export declare function createLayaConfig(): ProviderConfigOptions; /** * XOR — the `decide` inference type. Not a text provider, and it has no * built-in endpoint: XOR_BASE_URL is required alongside the key. */ export declare function createXorConfig(): ProviderConfigOptions; /** * Perplexity Decisions API — the `decide` inference type, not the Sonar text * models. It reads the same PERPLEXITY_API_KEY as the `perplexity` text * provider and has a public endpoint, so the key alone configures it. */ export declare function createPerplexityDeciderConfig(): ProviderConfigOptions; /** * Cloudflare Clef — the `decide` inference type, reached through Workers AI, * not the Workers AI text models. It reads the same CLOUDFLARE_API_KEY and * CLOUDFLARE_ACCOUNT_ID as the `cloudflare` text provider; the endpoint is * Cloudflare's own, so the two together configure it. */ export declare function createCloudflareClefConfig(): ProviderConfigOptions;