Skip to content

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

11.1 KB
Raw Blame
/**
 * OpenAI ProviderTransport
 *
 * Handles communication with OpenAI's API (and OpenAI-compatible providers
 * like GLM, Zen). Supports both Chat Completions and Codex Responses API.
 * Includes 30-second timeout with detailed error reporting.
 */

import { callAbortError, sleepUnlessAborted } from "../../handlers/shared/call-context.js";
import { isQuotaExhaustionError } from "../../handlers/shared/quota-exhaustion.js";
import type { RemoteProvider } from "../../handlers/shared/remote-provider-types.js";
import { log } from "../../logger.js";
import type { DiscoveryOutcome } from "./probe-discovery.js";
import { discoverProviderProbeModel } from "./provider-model-discovery.js";
import type { ProviderTransport, StreamFormat } from "./types.js";

export class OpenAIProviderTransport implements ProviderTransport {
  readonly name: string;
  readonly displayName: string;
  readonly streamFormat: StreamFormat;

  protected provider: RemoteProvider;
  private apiKey: string;
  protected modelName: string;

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

    // Declarative only: the parser is the adapter's (`wire.api` chooses it).
    this.streamFormat = "openai-sse";
  }

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

  /**
   * Honor the optional streamFormatOverride declared on the RemoteProvider.
   * Lets a custom endpoint (e.g. an aggregator whose openai transport actually
   * speaks anthropic-sse) win over the dialect's default choice of openai-sse.
   */
  overrideStreamFormat(): StreamFormat | undefined {
    return this.provider.streamFormatOverride;
  }

  /**
   * Honours the provider's declared `authScheme` and merges its static
   * `headers`, mirroring AnthropicProviderTransport.
   *
   * Both were silently dropped until 2026-08-14: this method emitted a Bearer
   * header and nothing else, so a `RemoteProvider` carrying `authScheme:
   * "x-api-key"` or `headers` had those fields validated, registered, and then
   * evaporate at the only point they matter. That is the whole reason
   * CLAUDE.md's own documented `corp-proxy` custom endpoint (`transport:
   * "openai"` + `authScheme: "X-Api-Key"` + `headers: {"X-Team": …}`) could not
   * work — a user following the docs got a credential error from a config the
   * schema had accepted.
   *
   * No builtin using this transport declares either field, so the default path
   * is unchanged: absent/`"bearer"` scheme with no provider headers produces
   * the identical single-Authorization object it always did. The `if (apiKey)`
   * guard is kept for the same reason — a keyless provider must send no auth
   * header rather than an empty one.
   */
  async getHeaders(): Promise<Record<string, string>> {
    const headers: Record<string, string> = {};
    // `authScheme: "none"` is stated explicitly rather than relying on the
    // `this.apiKey` guard below. The guard already produces the right result
    // (a keyless endpoint resolves to ""), but only by coincidence — a future
    // edit that gave keyless endpoints a placeholder value would start signing
    // them again with nothing here to say that is wrong.
    if (this.provider.authScheme !== "none" && this.apiKey) {
      if (this.provider.authScheme === "x-api-key") {
        headers["x-api-key"] = this.apiKey;
      } else {
        headers.Authorization = `Bearer ${this.apiKey}`;
      }
    }
    // Provider headers are merged whether or not a key resolved: for a gateway
    // whose auth lives in a custom header, they ARE the credential.
    if (this.provider.headers) {
      Object.assign(headers, this.provider.headers);
    }
    return headers;
  }

  /**
   * Discover from the provider definition's authenticated model-list endpoint.
   *
   * OpenAI-compatible subscriptions such as Sakana Subscription and Grok
   * Build have account-scoped dynamic models catalogs that are not interchangeable with their
   * metered siblings. The shared helper uses the same credential authority and
   * model-discovery cache as the picker, so probe fallback never guesses a
   * cross-silo model id.
   */
  async discoverProbeModel(exclude?: ReadonlySet<string>): Promise<DiscoveryOutcome> {
    return discoverProviderProbeModel(this.provider.name, this.displayName, exclude);
  }

  /**
   * Override fetch with 30-second timeout and bounded 429 retry. The retry
   * budget is intentionally tight (~3s worst case) so probe deadlines and
   * user-perceived latency stay reasonable — long retry chains on rate
   * limits are worse UX than honest failures.
   *
   * Terminal 429s (billing/balance errors) are detected by body sniff and
   * skip the retry chain entirely: retrying a balance error wastes wall
   * clock and lies about endpoint health.
   */
  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++) {
      try {
        const response = await fetchFn();

        if (response.status === 429 && attempt < maxRetries) {
          // Sniff body for terminal billing/quota errors. Clone first so the
          // caller still gets a readable body if we return this response.
          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 (see the catch below).
          if (await sleepUnlessAborted(delayMs, opts?.signal)) throw callAbortError();
          continue;
        }

        return response;
      } catch (fetchError: any) {
        // The caller's own deadline, not this transport's 30 s timeout: the
        // abort is rethrown unchanged, so it is never reported as a timeout.
        if (opts?.signal?.aborted) throw fetchError;
        if (fetchError.name === "AbortError") {
          log(`[${this.displayName}] Request timed out after 30s`);
          throw new OpenAITimeoutError(this.provider.baseUrl, fetchError);
        }
        if (fetchError.cause?.code === "UND_ERR_CONNECT_TIMEOUT") {
          log(`[${this.displayName}] Connection timeout: ${fetchError.message}`);
          throw new OpenAIConnectionError(
            this.provider.baseUrl,
            fetchError.cause?.code,
            fetchError
          );
        }
        throw fetchError;
      }
    }

    // All retries exhausted — return the last 429 response
    return lastResponse!;
  }

  static formatDisplayName(name: string): string {
    if (name === "opencode-zen") return "Zen";
    if (name === "opencode-zen-go") return "Zen Go";
    if (name === "glm") return "GLM";
    if (name === "glm-coding") return "GLM Coding";
    if (name === "openai") return "OpenAI";
    if (name === "meta-muse-code") return "Muse Code";
    return name.charAt(0).toUpperCase() + name.slice(1);
  }
}

/**
 * Detect 429 response bodies that indicate a non-retryable condition —
 * billing/balance errors that won't resolve no matter how long we wait.
 * Conservative: only matches well-known patterns, falls through to retry
 * for anything ambiguous.
 *
 * Examples caught:
 *   - GLM/Zhipu: code 1113, "Insufficient balance or no resource package"
 *   - OpenAI:    "You exceeded your current quota"
 *   - Many:     "insufficient_quota", "billing_not_active", "out of credits"
 */
export function isTerminal429(body: string): boolean {
  if (!body) return false;

  // A spent SUBSCRIPTION allowance is terminal for this request even though it is
  // not a billing failure. Zen Go answers `429 "5-hour usage limit reached.
  // Resets in 3hr 17min"` — a window that refills on a clock, so no amount of
  // backoff inside one request can recover it. Without this, the transport's
  // 429 loop retried it until the caller's timeout: a `create_session` against a
  // bare `minimax-m2.5` burned its full 60s budget retrying an exhausted plan
  // instead of failing fast so the fallback chain could reach the metered
  // provider that was ready to serve.
  if (isQuotaExhaustionError(429, body)) return true;

  const lower = body.toLowerCase();
  return (
    lower.includes("insufficient balance") ||
    lower.includes("insufficient_balance") ||
    lower.includes("insufficient_quota") ||
    lower.includes("insufficient quota") ||
    lower.includes("billing_not_active") ||
    lower.includes("billing not active") ||
    lower.includes("quota_exceeded") ||
    lower.includes("exceeded your current quota") ||
    lower.includes("out of credits") ||
    lower.includes('"code":"1113"') ||
    lower.includes('"code":1113')
  );
}

/**
 * Both classes carry `code` AND `cause` on purpose.
 *
 * `classifyConnectionError` (handlers/shared/connection-error.ts) recognises a
 * failure-to-reach-the-host by walking `.code` and then the `.cause` chain to
 * depth 8. These two classes used to set neither, so wrapping a real connect
 * failure in one of them ERASED the evidence: the classifier returned `null`,
 * ComposedHandler rethrew, and the throw escaped into `fallback-handler.ts`'s
 * catch — which records `status: 0` and advances the chain unconditionally,
 * moving a subscription user onto metered billing during a network outage.
 *
 * `cause` alone would be enough for the classifier, but `code` is set too so an
 * inspector that only reads the top-level error still sees what happened.
 */
export class OpenAITimeoutError extends Error {
  /** ETIMEDOUT: `connection-error.ts` maps this to kind "unreachable". */
  readonly code = "ETIMEDOUT";
  constructor(baseUrl: string, cause?: unknown) {
    super(`Request to OpenAI API timed out. Check your network connection to ${baseUrl}`, {
      cause,
    });
    this.name = "OpenAITimeoutError";
  }
}

export class OpenAIConnectionError extends Error {
  /** The originating syscall/undici code, e.g. UND_ERR_CONNECT_TIMEOUT. */
  readonly code: string;
  constructor(baseUrl: string, code: string, cause?: unknown) {
    super(
      `Cannot connect to OpenAI API (${baseUrl}). This may be due to: network/firewall blocking, VPN interference, or regional restrictions. Error: ${code}`,
      { cause }
    );
    this.name = "OpenAIConnectionError";
    this.code = code;
  }
}

// Backward-compatible alias
/** @deprecated Use OpenAIProviderTransport */
export { OpenAIProviderTransport as OpenAIProvider };