Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

6.4 KB
Raw Blame
/**
 * Provider Registry for Local LLM Providers
 *
 * Supports Ollama and other OpenAI-compatible local providers.
 * Extensible via configuration - no code changes needed to add new providers.
 *
 * New syntax: provider@model[:concurrency]
 * Legacy syntax: prefix/model or prefix:model (with deprecation warnings)
 */

import { getApiKey, getEndpoint as getConfigEndpoint } from "../profile-config.js";
import { isLocalProviderName, parseModelSpec } from "./model-parser.js";

/**
 * Config-first URL resolution. ~/.claudish/config.json's `endpoints` map
 * wins over the env var, which wins over the static default. Same precedence
 * the TUI's URL editor expects, and matches the apiKeys behavior.
 */
function resolveBaseUrl(envVar: string, fallbackEnvVars: string[], staticDefault: string): string {
  for (const v of [envVar, ...fallbackEnvVars]) {
    const fromConfig = getConfigEndpoint(v);
    if (fromConfig) return fromConfig;
  }
  for (const v of [envVar, ...fallbackEnvVars]) {
    const fromEnv = process.env[v];
    if (fromEnv) return fromEnv;
  }
  return staticDefault;
}

function resolveApiKey(envVar: string): string | undefined {
  // Config wins (set via `s` key in TUI). Env is fallback.
  return getApiKey(envVar) || process.env[envVar] || undefined;
}

export interface LocalProvider {
  name: string;
  baseUrl: string;
  apiPath: string;
  envVar: string;
  prefixes: string[]; // Legacy prefixes for backwards compatibility
  /** Optional API key — sent as Bearer if set. Empty/undefined skips auth.
   *  Useful for LM Studio with "Reachable on local network" + auth enabled,
   *  vLLM started with --api-key, or remote Ollama via reverse proxy. */
  apiKey?: string;
}

export interface ResolvedProvider {
  provider: LocalProvider;
  modelName: string;
  concurrency?: number; // Concurrency limit from model spec
  isLegacySyntax?: boolean; // For deprecation warnings
}

export interface UrlParsedModel {
  baseUrl: string;
  modelName: string;
}

// Built-in provider configurations
const getProviders = (): LocalProvider[] => [
  {
    name: "ollama",
    baseUrl: resolveBaseUrl("OLLAMA_BASE_URL", ["OLLAMA_HOST"], "http://localhost:11434"),
    apiPath: "/v1/chat/completions",
    envVar: "OLLAMA_BASE_URL",
    prefixes: ["ollama/", "ollama:"],
    apiKey: resolveApiKey("OLLAMA_API_KEY"),
  },
  {
    name: "lmstudio",
    baseUrl: resolveBaseUrl("LMSTUDIO_BASE_URL", [], "http://localhost:1234"),
    apiPath: "/v1/chat/completions",
    envVar: "LMSTUDIO_BASE_URL",
    prefixes: ["lmstudio/", "lmstudio:", "mlstudio/", "mlstudio:"], // mlstudio alias for common typo
    apiKey: resolveApiKey("LMSTUDIO_API_KEY"),
  },
  {
    name: "vllm",
    baseUrl: resolveBaseUrl("VLLM_BASE_URL", [], "http://localhost:8000"),
    apiPath: "/v1/chat/completions",
    envVar: "VLLM_BASE_URL",
    prefixes: ["vllm/", "vllm:"],
    apiKey: resolveApiKey("VLLM_API_KEY"),
  },
  {
    name: "mlx",
    baseUrl: resolveBaseUrl("MLX_BASE_URL", [], "http://127.0.0.1:8080"),
    apiPath: "/v1/chat/completions",
    envVar: "MLX_BASE_URL",
    prefixes: ["mlx/", "mlx:"],
    apiKey: resolveApiKey("MLX_API_KEY"),
  },
];

/**
 * Get all registered providers (refreshes env vars on each call)
 */
export function getRegisteredProviders(): LocalProvider[] {
  return getProviders();
}

/**
 * Resolve a model ID to a local provider
 *
 * Supports both new syntax (provider@model) and legacy syntax (prefix/model)
 */
export function resolveProvider(modelId: string): ResolvedProvider | null {
  const providers = getProviders();

  // Try new model parser first
  const parsed = parseModelSpec(modelId);

  // Check if parsed provider is a local provider
  if (isLocalProviderName(parsed.provider)) {
    const provider = providers.find((p) => p.name.toLowerCase() === parsed.provider.toLowerCase());

    if (provider) {
      return {
        provider,
        modelName: parsed.model,
        concurrency: parsed.concurrency,
        isLegacySyntax: parsed.isLegacySyntax,
      };
    }
  }

  // Legacy: check prefix patterns for backwards compatibility
  for (const provider of providers) {
    for (const prefix of provider.prefixes) {
      if (modelId.startsWith(prefix)) {
        // Check for concurrency suffix
        let modelName = modelId.slice(prefix.length);
        let concurrency: number | undefined;

        const concurrencyMatch = modelName.match(/^(.+):(\d+)$/);
        if (concurrencyMatch) {
          modelName = concurrencyMatch[1];
          concurrency = Number.parseInt(concurrencyMatch[2], 10);
        }

        return {
          provider,
          modelName,
          concurrency,
          isLegacySyntax: true,
        };
      }
    }
  }

  return null;
}

/**
 * Check if a model ID matches any local provider pattern
 */
export function isLocalProvider(modelId: string): boolean {
  // Try model parser first
  const parsed = parseModelSpec(modelId);
  if (isLocalProviderName(parsed.provider)) {
    return true;
  }

  // Check legacy prefix patterns
  if (resolveProvider(modelId) !== null) {
    return true;
  }

  // Check URL patterns
  if (parseUrlModel(modelId) !== null) {
    return true;
  }

  return false;
}

/**
 * Parse a URL-style model specification
 * Supports: http://localhost:11434/modelname or http://host:port/v1/modelname
 */
export function parseUrlModel(modelId: string): UrlParsedModel | null {
  // Check for http:// or https:// prefix
  if (!modelId.startsWith("http://") && !modelId.startsWith("https://")) {
    return null;
  }

  try {
    const url = new URL(modelId);
    const pathParts = url.pathname.split("/").filter(Boolean);

    if (pathParts.length === 0) {
      return null;
    }

    // Model name is the last path segment
    const modelName = pathParts[pathParts.length - 1];

    // Base URL is everything except the model name
    // Handle cases like /v1/modelname or just /modelname
    let basePath = "";
    if (pathParts.length > 1) {
      // Check if second-to-last is "v1" or similar API version
      const prefix = pathParts.slice(0, -1).join("/");
      if (prefix) basePath = `/${prefix}`;
    }

    const baseUrl = `${url.protocol}//${url.host}${basePath}`;

    return {
      baseUrl,
      modelName,
    };
  } catch {
    return null;
  }
}

/**
 * Create an ad-hoc provider config for URL-based models
 */
export function createUrlProvider(parsed: UrlParsedModel): LocalProvider {
  return {
    name: "custom-url",
    baseUrl: parsed.baseUrl,
    apiPath: "/v1/chat/completions",
    envVar: "",
    prefixes: [],
  };
}