Skip to content

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

11.4 KB
Raw Blame
/**
 * Anthropic-Compatible ProviderTransport
 *
 * Handles communication with providers that speak native Anthropic API format
 * (MiniMax, Kimi, Kimi Coding, Z.AI). Auth uses x-api-key header with
 * anthropic-version, plus Kimi OAuth fallback for kimi-coding.
 */

import { credentials } from "../../auth/credentials/authority.js";
import { terminalCredentialError } from "../../auth/credentials/credential-error.js";
import { callAbortError, sleepUnlessAborted } from "../../handlers/shared/call-context.js";
import type { RemoteProvider } from "../../handlers/shared/remote-provider-types.js";
import { log } from "../../logger.js";
import { getProviderByName } from "../provider-definitions.js";
import { isTerminal429 } from "./openai.js";
import type { DiscoveryOutcome } from "./probe-discovery.js";
import { discoverProviderProbeModel } from "./provider-model-discovery.js";
import type { ProviderTransport, StreamFormat } from "./types.js";

export class AnthropicProviderTransport implements ProviderTransport {
  readonly name: string;
  readonly displayName: string;
  readonly streamFormat: StreamFormat = "anthropic-sse";

  private provider: RemoteProvider;
  private apiKey: string;

  constructor(provider: RemoteProvider, apiKey: string) {
    this.provider = provider;
    this.apiKey = apiKey;
    this.name = provider.name;
    this.displayName = AnthropicProviderTransport.formatDisplayName(provider.name);
  }

  getEndpoint(): string {
    return `${this.provider.baseUrl}${this.provider.apiPath}`;
  }

  /**
   * Honor the optional streamFormatOverride declared on the RemoteProvider.
   * Lets custom endpoints (e.g. qwen-token-plan serving an Anthropic-compatible
   * wire format for a Qwen-named model) win over the dialect's default choice.
   * No-op when unset — by default Anthropic-compat speaks anthropic-sse anyway.
   */
  overrideStreamFormat(): StreamFormat | undefined {
    return this.provider.streamFormatOverride;
  }

  async getHeaders(): Promise<Record<string, string>> {
    const headers: Record<string, string> = {
      "anthropic-version": "2023-06-01",
    };

    // `"none"` must be checked BEFORE the else, which emits `x-api-key`
    // UNCONDITIONALLY — including for an empty key. That is why a keyless
    // endpoint could not simply leave `apiKey` blank: it would put a literal
    // `x-api-key: ` on the wire, and a gateway that ignores unknown auth may
    // still reject a malformed one. An absent header is the only correct
    // representation of "no credential".
    if (this.provider.authScheme === "none") {
      // Nothing to sign with. `provider.headers` is still merged below — for a
      // gateway whose auth lives in a custom header, those ARE the credential.
    } else if (this.provider.authScheme === "bearer") {
      headers.Authorization = `Bearer ${this.apiKey}`;
    } else {
      headers["x-api-key"] = this.apiKey;
    }

    // Add provider-specific headers
    if (this.provider.headers) {
      Object.assign(headers, this.provider.headers);
    }

    // Kimi Coding: OAuth wins over API key when both are present.
    // Per kimi.com/code docs, the canonical auth path for the coding
    // subscription is OAuth (claudish login kimi). A stale or wrong
    // KIMI_CODING_API_KEY env var would otherwise produce 401 even
    // though the user has a valid OAuth token on disk.
    //
    // The transport no longer manages OAuth itself — it delegates to the
    // credential authority, which mints the OAuth artifact (anthropic-version +
    // Bearer token + the X-Msh-* platform headers) and applies the
    // OAuth_FALLBACK_TO_API_KEY → api-key fallback internally. Every failure is
    // rethrown; nothing falls back to the x-api-key populated above.
    if (this.provider.name === "kimi-coding") {
      try {
        const auth = await credentials.getRequestAuth("kimi-coding", { model: "" });
        // An artifact that signs nothing: the login is gone (a rejected login
        // deletes kimi-oauth.json, so on every LATER request the composite
        // skips the OAuth half) and KIMI_CODING_API_KEY is unset, so the
        // api-key half returned `{headers:{}}`. The `x-api-key` above is then
        // `this.apiKey`, the construction-time OAuth token, which upstream
        // answers with a bare 401. Stop with the login instruction instead.
        if (!auth.headers.Authorization && !auth.headers["x-api-key"]) {
          throw terminalCredentialError(
            "No Kimi Code credential: the Kimi login is missing or was rejected, and KIMI_CODING_API_KEY is not set. Run `claudish login kimi` to sign in."
          );
        }
        // If the authority returned an OAuth Bearer, it replaces the api-key auth.
        if (auth.headers.Authorization) {
          delete headers["x-api-key"];
        }
        Object.assign(headers, auth.headers);
      } catch (e: any) {
        // Every failure is rethrown, for ComposedHandler's getHeaders site to
        // classify: a network fault (recovered), a token host's 429/5xx
        // (retried), a dead login ("run `claudish login kimi`", terminal).
        // Swallowing here was the transport-catch bug (CLAUDE.md): the request
        // went out with `x-api-key: ""` or a stale token.
        //
        // The fallback to the Coding Plan's own KIMI_CODING_API_KEY (the same
        // flat-rate plan) is decided where the key lives: the kimi-coding
        // composite falls through only when that key is present, and then
        // returns its artifact without throwing (composite-credential.ts). A
        // Moonshot key (MOONSHOT_API_KEY / KIMI_API_KEY, a metered product)
        // belongs to the `kimi` composite and never signs kc@. `this.apiKey`
        // never signs kc@ alone: for an OAuth user it is the construction-time
        // token, so an artifact with no header is refused above.
        log(`[${this.displayName}] OAuth path failed: ${e.message}`);
        throw e;
      }
    }

    return headers;
  }

  /**
   * Discover a probe-friendly model from the provider's OWN authenticated
   * model list.
   *
   * Why this transport needs it at all: several Anthropic-compat providers are
   * SUBSCRIPTIONS (Alibaba Token Plan, Kimi Coding). The cloud /probeModels
   * catalog fundamentally cannot know which models a given key is entitled to
   * — that is a property of the caller's plan, not of the provider — so the
   * TUI falls back to GET /v1/probe-discover, which requires this method.
   * Without it the Test column reads "no probe model: transport does not
   * support discovery" for every subscription provider.
   *
   * Source of truth is the provider's own `modelDiscovery` descriptor (already
   * declared by qwen-token-plan and kimi-coding), reached through the shared
   * `discoverProviderModels()` — the same authenticated call the picker and
   * the context-window resolver use, so it shares their cache and their
   * credential-authority auth path. No new HTTP path is introduced here.
   *
   * Ordering: `rankDiscoveredModels()` (largest live context window first,
   * alphabetical tiebreak) — the same order the picker defaults to, so the
   * probe exercises the model the user would actually get.
   *
   * Non-chat rows are dropped by `discoverProviderProbeModel`, with the shared
   * `isReportedChatCapable()` filter the picker uses too, rather
   * than a per-provider skip list: qwen-token-plan's dynamic models catalog mixes
   * image/TTS models (`wan2.7-image`, `qwen-audio-3.0-tts-plus`) in with the text models, and
   * hardcoding model ids here would rot the moment Alibaba ships the next one.
   */
  async discoverProbeModel(exclude?: ReadonlySet<string>): Promise<DiscoveryOutcome> {
    return discoverProviderProbeModel(this.provider.name, this.displayName, exclude);
  }

  /**
   * Retry 429 responses with bounded backoff. Anthropic-compat providers
   * (Kimi, MiniMax, Z.AI) throttle aggressively; one quick retry helps
   * recover transient bursts. The retry budget is intentionally tight
   * (~3s worst case) so probe deadlines (typically 15s) don't get blown
   * by an extended retry chain — the probe surfaces 429 as a healthy
   * "throttled" signal instead.
   *
   * Terminal 429s (billing/quota) skip the retry chain — see isTerminal429
   * in transport/openai.ts for the patterns matched.
   */
  async enqueueRequest(
    fetchFn: () => Promise<Response>,
    opts?: { signal?: AbortSignal }
  ): Promise<Response> {
    const maxRetries = 2;
    let lastResponse: Response | null = null;

    for (let attempt = 0; attempt <= maxRetries; attempt++) {
      const response = await fetchFn();

      if (response.status === 429 && attempt < maxRetries) {
        const bodyText = await response
          .clone()
          .text()
          .catch(() => "");
        if (isTerminal429(bodyText)) {
          log(`[${this.displayName}] 429 is terminal (billing/quota), not retrying`);
          return response;
        }
        lastResponse = response;
        const retryAfter = response.headers.get("Retry-After");
        let delayMs: number;
        if (retryAfter && !Number.isNaN(Number(retryAfter))) {
          delayMs = Math.min(Number(retryAfter) * 1000, 2000);
        } else {
          // 500ms, 1000ms — quick recovery without blowing probe budget
          delayMs = 500 * (attempt + 1);
        }
        log(
          `[${this.displayName}] 429 rate limited, retry ${attempt + 1}/${maxRetries} in ${(delayMs / 1000).toFixed(1)}s`
        );
        // An internal call's deadline ends the wait; the re-try would be
        // refused by the caller's pre-start check anyway, so stop here.
        if (await sleepUnlessAborted(delayMs, opts?.signal)) throw callAbortError();
        continue;
      }

      return response;
    }

    return lastResponse!;
  }

  /**
   * DERIVED from the provider catalog — deliberately not a second table.
   *
   * This used to be a private map of eight names that SHADOWED
   * `ProviderDefinition.displayName`, so renaming a provider in one place
   * silently left this transport's log lines on the old label. That is the
   * two-table coupling `provider-definitions.ts` exists to prevent: a provider
   * whose label is stored twice keeps the stale one wherever nobody looked.
   * `qwen-coding` was missing from the map and logged "Qwen-coding";
   * `qwen-payg` logged "Qwen API" while its definition says "Alibaba PAYG".
   *
   * The other former entries are byte-identical to their definition's
   * `displayName` (minimax, minimax-coding, kimi, kimi-coding, z-ai,
   * qwen-token-plan). `moonshot → "Kimi"` is dropped on purpose: `moonshot` is
   * one of `kimi`'s SHORTCUTS, never a provider `name`, so the entry was
   * unreachable from `provider.name` — and `moonshot-cn` is a genuinely
   * different service (CLAUDE.md), which the old entry would have collapsed
   * into "Kimi" had it ever been reached.
   *
   * The title-case fallback is unchanged, so a runtime custom endpoint with no
   * definition renders exactly as it did before.
   *
   * NOTE: `transport/openai.ts` keeps its own map on purpose — it carries no
   * Alibaba entry, and deriving it would rename `Zen`/`Zen Go` in every log
   * line for two providers this change has no business touching.
   */
  static formatDisplayName(name: string): string {
    return (
      getProviderByName(name.toLowerCase())?.displayName ||
      name.charAt(0).toUpperCase() + name.slice(1)
    );
  }
}

// Backward-compatible alias
/** @deprecated Use AnthropicProviderTransport */
export { AnthropicProviderTransport as AnthropicCompatProvider };