Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

28.4 KB
Raw Blame
import { randomBytes } from "node:crypto";

import {
  BaseExecutor,
  ExecuteInput,
  type ProviderConfig,
  type ProviderCredentials,
} from "./base.ts";
import { PROVIDERS, OAUTH_ENDPOINTS } from "../config/constants.ts";
import { getModelTargetFormat } from "../config/providerModels.ts";
import { containsMediaKind } from "../utils/mediaParts.ts";
import {
  getGitHubCopilotChatHeaders,
  getGitHubCopilotRefreshHeaders,
} from "../config/providerHeaderProfiles.ts";
import { sanitizeResponsesInputItems } from "../services/responsesInputSanitizer.ts";
import {
  isGithubTemperatureUnsupportedModel,
  stripUnsupportedParams,
} from "../translator/paramSupport.ts";
import {
  COPILOT_AUTO_API_VERSION,
  COPILOT_AUTO_TIMEOUT_MS,
  buildAutoSessionKey,
  copilotAutoSessions,
  extractAutoPrompt,
  hasAutoImageInput,
  parseAutoDecision,
  type CopilotAutoDecision,
} from "./github/autoModel.ts";

/** Correlation-id fallback for runtimes without crypto.randomUUID — still CSPRNG-backed. */
function randomIdFallback(): string {
  return `${Date.now()}-${randomBytes(9).toString("hex")}`;
}

/**
 * What a Copilot credential refresh resolves to.
 *
 * `refreshCredentials()` returns one of three shapes — the raw GitHub token pair, that pair
 * plus the minted Copilot token, or the Copilot token folded onto the existing credentials —
 * and `null` when nothing could be refreshed. Left to inference, the union of those literals
 * is narrower than the contract subclasses actually honor: `GheCopilotExecutor` carries a
 * wider `providerSpecificData` (it also records the enterprise proxy URL) and omits
 * `expiresIn`, which made a valid override fail with TS2416. Every field is therefore
 * optional here — callers already treat them as such.
 */
export interface RefreshedCopilotCredentials {
  accessToken?: string;
  refreshToken?: string;
  expiresIn?: number;
  copilotToken?: string;
  copilotTokenExpiresAt?: string | number;
  providerSpecificData?: Record<string, unknown>;
}

type GithubExecutorConfig = ProviderConfig & Record<string, unknown>;

/** Outcome of a Copilot `/auto` model selection (see ./github/autoModel.ts). */
export type CopilotAutoResolution =
  | { ok: true; decision: CopilotAutoDecision; cached: boolean }
  | { ok: false; status: number; message: string };

export class GithubExecutor extends BaseExecutor {
  constructor(provider = "github", config?: GithubExecutorConfig) {
    super(provider, config ?? PROVIDERS.github);
  }

  getCopilotToken(credentials: Record<string, any> | null | undefined) {
    return credentials?.copilotToken || credentials?.providerSpecificData?.copilotToken || null;
  }

  getCopilotTokenExpiresAt(credentials: Record<string, any> | null | undefined) {
    return (
      credentials?.copilotTokenExpiresAt ||
      credentials?.providerSpecificData?.copilotTokenExpiresAt ||
      null
    );
  }

  // GitHub Copilot's /responses endpoint only serves OpenAI (gpt/codex) models.
  // Gemini and Claude variants on Copilot reject with HTTP 400
  //   "model <id> does not support Responses API." (unsupported_api_for_model)
  // Pin a defensive invariant: even if a future registry edit (or an upstream
  // model-discovery refresh) tagged a Claude/Gemini entry as openai-responses,
  // the executor must still route it to /chat/completions. Port of 9router#1536
  // (follow-up to #663); also reinforces the existing comments on the gh
  // registry entries (claude-opus-4-5-20251101, claude-opus-4.7, gemini-*).
  supportsResponsesEndpoint(model: string | null | undefined): boolean {
    const m = (model || "").toLowerCase();
    if (!m) return true;
    return !(m.includes("gemini") || m.includes("claude"));
  }

  buildUrl(
    model: string,
    _stream: boolean,
    _urlIndex = 0,
    credentials?: ProviderCredentials | null
  ) {
    // #2905/#7364-pattern: a custom Copilot model's per-model targetFormat
    // override isn't in the static PROVIDER_MODELS registry, so
    // getModelTargetFormat() can't see it. chatCore/executionCredentials.ts
    // threads the resolved override onto providerSpecificData.targetFormat
    // for exactly this case — prefer it when present.
    const overrideTargetFormat = (
      credentials as { providerSpecificData?: { targetFormat?: unknown } }
    )?.providerSpecificData?.targetFormat;
    const targetFormat =
      typeof overrideTargetFormat === "string"
        ? overrideTargetFormat
        : getModelTargetFormat("gh", model);
    // Claude models: ALWAYS route to Copilot's Anthropic-native /v1/messages
    // shim — the only Copilot endpoint that surfaces prompt-cache token counts
    // for Claude and avoids a lossy round-trip of tool_use/tool_result/thinking
    // content blocks through the OpenAI shape. Matched on the model NAME (not
    // only the registry's per-model targetFormat) so a Claude model that is
    // missing its targetFormat tag, or a custom Claude id, still gets the native
    // shim rather than silently falling through to /chat/completions. Mirrors
    // the Hermes copilot routing (`if "claude" in model: return CAPI_MESSAGES_URL`).
    // Port of decolua/9router#2608 (author: yidecode).
    const isClaudeModel = /claude/i.test(model || "");
    if ((targetFormat === "claude" || isClaudeModel) && this.config.messagesUrl) {
      return this.config.messagesUrl;
    }
    // 9router#102: Copilot Codex models advertise supported_endpoints: ["/responses"]
    // and 400 on /chat/completions. Route any *-codex id to /responses even when it
    // isn't in the curated registry, so newly-shipped Codex models work out of the box.
    // 9router#1536: but never route Gemini/Claude variants to /responses (they 400) —
    // gate the whole decision on supportsResponsesEndpoint().
    if (
      (targetFormat === "openai-responses" || /codex/i.test(model)) &&
      this.supportsResponsesEndpoint(model)
    ) {
      return (
        this.config.responsesBaseUrl ||
        this.config.baseUrl?.replace(/\/chat\/completions\/?$/, "/responses") ||
        "https://api.githubcopilot.com/responses"
      );
    }
    return this.config.baseUrl;
  }

  injectResponseFormat(messages: Array<Record<string, any>>, responseFormat: any) {
    if (!responseFormat) return messages;

    let formatInstruction = "";
    if (responseFormat.type === "json_object") {
      formatInstruction =
        "Respond only with valid JSON. Do not include any text before or after the JSON object.";
    } else if (responseFormat.type === "json_schema" && responseFormat.json_schema) {
      formatInstruction = `Respond only with valid JSON matching this schema:\n${JSON.stringify(
        responseFormat.json_schema.schema,
        null,
        2
      )}\nDo not include any text before or after the JSON.`;
    }

    if (!formatInstruction) return messages;

    const systemIdx = messages.findIndex((m) => m.role === "system");
    if (systemIdx >= 0) {
      return messages.map((m, i: number) =>
        i === systemIdx ? { ...m, content: `${m.content}\n\n${formatInstruction}` } : m
      );
    }

    return [{ role: "system", content: formatInstruction }, ...messages];
  }

  transformRequest(model: string, body: any, stream: boolean, credentials: any): any {
    void stream;
    void credentials;

    const sourceBody = body && typeof body === "object" ? body : {};
    const modifiedBody = { ...sourceBody };

    // Claude models arrive here already translated to Anthropic-native shape by
    // chatCore.ts (registry targetFormat: "claude" — see registry/github/index.ts)
    // and are dispatched at /v1/messages (buildUrl above), which behaves like the
    // real Anthropic API. None of the /chat/completions-only quirks below apply —
    // content-part flattening would destroy native tool_use/tool_result/thinking
    // blocks, and the native endpoint (unlike Copilot's /chat/completions) honors
    // assistant-message prefill. Port of decolua/9router#2608 (author: yidecode).
    const isClaudeNative = getModelTargetFormat("gh", model) === "claude";

    if (Array.isArray(sourceBody.input)) {
      modifiedBody.input = sanitizeResponsesInputItems(sourceBody.input, false);
    }

    if (Array.isArray(sourceBody.messages)) {
      modifiedBody.messages = sourceBody.messages.map((msg) => {
        if (!msg || typeof msg !== "object") return msg;
        const role = typeof msg.role === "string" ? msg.role.toLowerCase() : "";
        if (role !== "assistant") return msg;
        if (msg.reasoning_text === undefined && msg.reasoning_content === undefined) return msg;
        const next = { ...msg };
        delete next.reasoning_text;
        delete next.reasoning_content;
        return next;
      });
    }

    if (Array.isArray(modifiedBody.tools) && modifiedBody.tools.length > 128) {
      modifiedBody.tools = modifiedBody.tools.slice(0, 128);
    }

    // GitHub Copilot's GPT-5.4+ and GPT-6.x models reject requests carrying `temperature`
    // with HTTP 400: "Unsupported parameter: 'temperature' is not supported with this model."
    // OmniRoute's existing `stripGpt5SamplingWhenReasoning` guard only fires for
    // provider==="openai" (raw api.openai.com Chat Completions), so GitHub Copilot routes
    // never hit it. Strip temperature here unconditionally (chat and Responses bodies) so the
    // 400 cannot reach the user. Same predicate as the "github" rule in paramSupport.ts so
    // the two can't drift. Port from 9router#612 (closes upstream #536) and 9router#4706.
    if (isGithubTemperatureUnsupportedModel(model) && modifiedBody.temperature !== undefined) {
      delete modifiedBody.temperature;
    }

    // The quirks below (response_format-as-system-prompt, content-part flattening,
    // trailing-assistant-prefill drop) are all workarounds for /chat/completions-only
    // limitations. They either don't apply to Claude-shape bodies or actively corrupt
    // them, so they are skipped entirely for the native /v1/messages path. Port of
    // decolua/9router#2608 (author: yidecode) — see class doc comment above.
    if (!isClaudeNative) {
      this.applyChatCompletionsOnlyQuirks(model, modifiedBody);
    }

    // Config-driven strip of params unsupported by the target provider/model.
    // For GitHub Copilot this removes Claude-style `thinking` and
    // `reasoning_effort` for Claude models that reject them upstream
    // (Haiku 4.5 / Opus 4.7 — Opus 4.6 / Sonnet 4.6 keep them).
    // Port from 9router#7ae9fff6 (fixes upstream #1748, #713).
    stripUnsupportedParams("github", model, modifiedBody);

    return modifiedBody;
  }

  // GitHub Copilot's /chat/completions endpoint has several quirks that the native
  // /v1/messages shim doesn't share — extracted from transformRequest so the native
  // path (the common case for Claude models going forward) doesn't pay their branch
  // cost. Mutates modifiedBody in place.
  private applyChatCompletionsOnlyQuirks(model: string, modifiedBody): void {
    // Claude models on /chat/completions don't support response_format — inject the
    // instruction as a system message instead. Port from 9router (see
    // injectResponseFormat above).
    if (modifiedBody.response_format && model.toLowerCase().includes("claude")) {
      modifiedBody.messages = this.injectResponseFormat(
        Array.isArray(modifiedBody.messages) ? modifiedBody.messages : [],
        modifiedBody.response_format
      );
      delete modifiedBody.response_format;
    }

    if (!Array.isArray(modifiedBody.messages)) return;

    // GitHub Copilot /chat/completions only accepts {type:'text'} or {type:'image_url'}
    // content parts. Clients like Cursor IDE pass through Anthropic-shape parts
    // (tool_use, tool_result, thinking) untouched when using Claude models, which makes
    // the endpoint return: "type has to be either 'image_url' or 'text'" (HTTP 400).
    // Serialize unknown part types as text, drop empty parts, and collapse to null when
    // every part is stripped (assistant messages whose only content was tool_calls).
    // Port from 9router#220 (fixes 9router#219).
    modifiedBody.messages = modifiedBody.messages.map((msg: any) =>
      this.sanitizeChatCompletionsMessage(msg)
    );

    // GitHub Copilot's /chat/completions endpoint rejects a conversation that ends
    // with an assistant message: "This model does not support assistant message
    // prefill. The conversation must end with a user message." (HTTP 400). Anthropic
    // clients such as newest Claude Desktop send a trailing assistant turn as a
    // prefill seed — the Anthropic API honors it, but Copilot does not. Drop it here,
    // scoped to the GitHub executor only (the shared translator/contextManager and
    // other providers that DO honor prefill are untouched).
    // Port of 9router#2143 (author: Manuel <[email protected]>).
    modifiedBody.messages = this.dropTrailingAssistantPrefill(modifiedBody.messages);
  }

  private sanitizeChatCompletionsMessage(msg: any): any {
    if (!msg || typeof msg !== "object") return msg;
    // String content and missing content (e.g. assistant w/ only tool_calls) pass through.
    if (typeof msg.content === "string" || msg.content == null) return msg;
    if (!Array.isArray(msg.content)) return msg;

    const cleanContent = msg.content
      .map((part: any) => {
        if (!part || typeof part !== "object") return part;
        if (part.type === "text") return part;
        if (part.type === "image_url") return part;
        // Serialize any unsupported part (tool_use, tool_result, thinking, etc.) as text.
        // Try common text-carrying fields first; fall back to a JSON dump so nothing is
        // silently dropped from the model's context.
        const raw =
          (typeof part.text === "string" && part.text) ||
          (typeof part.thinking === "string" && part.thinking) ||
          (typeof part.content === "string" && part.content) ||
          (part.content != null && JSON.stringify(part.content)) ||
          JSON.stringify(part);
        return { type: "text", text: typeof raw === "string" ? raw : JSON.stringify(raw) };
      })
      .filter((part: any) => !(part && part.type === "text" && part.text === ""));

    // If every part stripped to empty (e.g. tool_use with no text), collapse to null so
    // GitHub does not reject an empty-array body. tool_calls ride alongside content.
    return { ...msg, content: cleanContent.length > 0 ? cleanContent : null };
  }

  // Remove trailing assistant message(s). GitHub Copilot's /chat/completions endpoint
  // can't honor an assistant prefill and 400s unless the conversation ends with a
  // non-assistant (user/tool) message. Never empties the array — an assistant-only
  // conversation keeps its last message. No-op (same array reference) when the
  // conversation already ends with a non-assistant message.
  // Port of 9router#2143 (author: Manuel <[email protected]>).
  dropTrailingAssistantPrefill(messages: any): any {
    if (!Array.isArray(messages) || messages.length === 0) return messages;
    let end = messages.length;
    while (end > 1 && messages[end - 1]?.role === "assistant") end--;
    return end === messages.length ? messages : messages.slice(0, end);
  }

  async execute(input: ExecuteInput) {
    const result = await super.execute(input);
    // BaseExecutor.execute() is typed as the union it contracts for; the bare-Response
    // arm has nothing to materialize, which is what the existing `!result.response`
    // guard already meant.
    if (result instanceof Response || !result?.response) return result;

    if (!input.stream) {
      // wreq-js clone/text semantics consume the original response body. Materialize
      // non-streaming responses immediately so downstream code always sees a native
      // fetch Response with a readable body.
      const status = result.response.status;
      const statusText = result.response.statusText;
      const headers = new Headers(result.response.headers);
      const payload = await result.response.text();
      result.response = new Response(payload, { status, statusText, headers });
      return result;
    }

    return result;
  }

  buildHeaders(
    credentials: ProviderCredentials,
    stream = true,
    clientHeaders?: Record<string, string> | null,
    model?: string,
    _health?: unknown,
    body?: unknown
  ): Record<string, string> {
    const token = this.getCopilotToken(credentials) || credentials.accessToken;
    const initiator = this.resolveInitiatorHeader(clientHeaders);
    const clientIntegrationId =
      this.readClientHeader(clientHeaders, "copilot-integration-id") || undefined;

    const headers: Record<string, string> = {
      ...getGitHubCopilotChatHeaders(
        stream ? "text/event-stream" : "application/json",
        initiator,
        clientIntegrationId ? { integrationId: clientIntegrationId } : undefined
      ),
      Authorization: `Bearer ${token}`,
      "x-request-id": crypto.randomUUID?.() || randomIdFallback(),
    };

    // Per-call / per-conversation / per-turn correlation ids the @github/copilot
    // CLI 1.0.88 puts on every inference request (MITM-captured). The machine
    // id (getGitHubCopilotMachineId) is stable per-install; these three are
    // fresh uuids. A Copilot-aware client may pin the session/task ids across a
    // conversation via its own headers — honor those when present, else mint.
    const genId = () => crypto.randomUUID?.() || randomIdFallback();
    headers["x-interaction-id"] =
      this.readClientHeader(clientHeaders, "x-interaction-id") || genId();
    headers["x-client-session-id"] =
      this.readClientHeader(clientHeaders, "x-client-session-id") || genId();
    headers["x-agent-task-id"] = this.readClientHeader(clientHeaders, "x-agent-task-id") || genId();
    // Repository correlation sentinels. The CLI sends the working repo's nwo/host
    // or these literals when there is no repository context. OmniRoute is not
    // repo-scoped, so forward a client-supplied value when present, else sentinel.
    headers["x-github-repository-nwo"] =
      this.readClientHeader(clientHeaders, "x-github-repository-nwo") || "__no_repository__";
    headers["x-github-repository-host"] =
      this.readClientHeader(clientHeaders, "x-github-repository-host") || "__no_repository__";
    // OpenAI-SDK (stainless) signature the CLI carries on streamed turns only.
    if (stream) {
      headers["x-stainless-helper-method"] = "stream";
    }

    // Claude models routed to the Anthropic-native /v1/messages shim require the
    // anthropic-version header (harmless no-op on /chat/completions and /responses,
    // but /v1/messages rejects the request without it). Match on the model NAME so
    // it fires for every claude-* id (tagged or not), consistent with buildUrl.
    // Port of decolua/9router#2608.
    if (model && /claude/i.test(model)) {
      headers["anthropic-version"] = "2023-06-01";
    }

    // Forward a vision signal when the client already set it. Copilot's
    // /v1/messages proxy returns an empty content block for image turns unless
    // copilot-vision-request:true is present; a Copilot-aware harness that sends
    // it should have it honored rather than stripped.
    // Also set it ourselves when the turn carries an image (chat
    // `messages` or Responses `input`), so plain OpenAI-SDK clients get vision too.
    const turns = (body as { messages?: unknown; input?: unknown } | null | undefined) || {};
    const bodyHasImage =
      containsMediaKind(turns.messages as Parameters<typeof containsMediaKind>[0], "image") ||
      containsMediaKind(turns.input as Parameters<typeof containsMediaKind>[0], "image");
    if (
      bodyHasImage ||
      (this.readClientHeader(clientHeaders, "copilot-vision-request") || "").toLowerCase() ===
        "true"
    ) {
      headers["copilot-vision-request"] = "true";
    }

    // Copilot "auto": a request whose model was picked by /auto must carry the
    // session token that decision returned, on the API version that issued it.
    const sessionToken = (credentials as { copilotSessionToken?: unknown }).copilotSessionToken;
    if (typeof sessionToken === "string" && sessionToken) {
      headers["Copilot-Session-Token"] = sessionToken;
      headers["x-github-api-version"] = COPILOT_AUTO_API_VERSION;
    }

    return headers;
  }

  /** Copilot's `/auto` endpoint lives next to /chat/completions on the same host. */
  getAutoUrl(): string {
    const base = this.config.baseUrl || "https://api.githubcopilot.com/chat/completions";
    return base.replace(/\/chat\/completions\/?$/, "/auto");
  }

  /**
   * Ask Copilot which concrete model should serve an `auto` request. Decisions are
   * cached per (account, conversation) until shortly before their session token
   * expires, and re-resolved when an image turn arrives on a non-vision pick.
   */
  async resolveAutoModel({
    body,
    credentials,
    sessionKey,
    signal,
    log,
  }: {
    body: unknown;
    credentials: ProviderCredentials;
    sessionKey?: string | null;
    signal?: AbortSignal | null;
    log?: { info?: (tag: string, message: string) => void } | null;
  }): Promise<CopilotAutoResolution> {
    const cacheKey = buildAutoSessionKey(credentials as Record<string, unknown>, sessionKey);
    const hasImage = hasAutoImageInput(body);
    const cached = copilotAutoSessions.getUsable(cacheKey, hasImage);
    if (cached) return { ok: true, decision: cached, cached: true };

    const prompt = extractAutoPrompt(body);
    if (!prompt) {
      return { ok: false, status: 400, message: "GitHub Copilot auto requires a user text prompt" };
    }
    const url = this.getAutoUrl();
    this.assertOutboundUrlAllowed(url);
    const headers = this.buildHeaders(credentials, false);
    headers["x-github-api-version"] = COPILOT_AUTO_API_VERSION;
    const timeout = AbortSignal.timeout(COPILOT_AUTO_TIMEOUT_MS);
    const requestSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;

    let response: Response;
    try {
      response = await fetch(url, {
        method: "POST",
        headers,
        body: JSON.stringify(hasImage ? { prompt, has_image: true } : { prompt }),
        signal: requestSignal,
      });
    } catch (error) {
      const timedOut = timeout.aborted && !signal?.aborted;
      return {
        ok: false,
        status: timedOut ? 504 : 502,
        message: `GitHub Copilot auto model selection failed: ${
          error instanceof Error ? error.message : String(error)
        }`,
      };
    }

    if (!response.ok) {
      const detail = await response.text().catch(() => "");
      return {
        ok: false,
        status: response.status,
        message: `GitHub Copilot auto model selection failed (${response.status})${
          detail ? `: ${detail}` : ""
        }`,
      };
    }

    const decision = parseAutoDecision(await response.json().catch(() => null));
    if (!decision) {
      return {
        ok: false,
        status: 502,
        message: "GitHub Copilot auto returned no selected model or session token",
      };
    }
    copilotAutoSessions.set(cacheKey, decision);
    log?.info?.("GITHUB", `Copilot auto selected ${decision.model}`);
    return { ok: true, decision, cached: false };
  }

  // Case-insensitive read of a single client header value. Client header maps
  // arrive with inconsistent casing depending on the transport, so match on the
  // lowercased key rather than assuming a canonical form.
  private readClientHeader(
    clientHeaders: Record<string, string> | null | undefined,
    name: string
  ): string | null {
    if (!clientHeaders) return null;
    const target = name.toLowerCase();
    const direct = clientHeaders[name] ?? clientHeaders[target];
    if (typeof direct === "string") return direct;
    for (const key in clientHeaders) {
      if (key.toLowerCase() === target) {
        const val = clientHeaders[key];
        return typeof val === "string" ? val : null;
      }
    }
    return null;
  }

  // Forward the client's x-initiator header when present. OpenCode and other
  // Copilot-aware clients use this to distinguish user-initiated turns
  // (x-initiator: user) from autonomous tool-call continuations
  // (x-initiator: agent). GitHub Copilot's billing treats "agent" turns as
  // free, so forwarding the value avoids burning a premium request on every
  // tool-call round-trip. Falls back to "user" when the header is absent to
  // preserve the existing default behaviour. Extracted from buildHeaders so
  // header assembly stays the one place that reads it.
  private resolveInitiatorHeader(clientHeaders?: Record<string, string> | null): string {
    let clientInitiator = clientHeaders?.["x-initiator"] || clientHeaders?.["X-Initiator"];
    if (!clientInitiator && clientHeaders) {
      for (const key in clientHeaders) {
        if (key.toLowerCase() === "x-initiator") {
          clientInitiator = clientHeaders[key];
          break;
        }
      }
    }
    return clientInitiator === "agent" || clientInitiator === "user" ? clientInitiator : "user";
  }

  async refreshCopilotToken(githubAccessToken, log) {
    try {
      const response = await fetch("https://api.github.com/copilot_internal/v2/token", {
        headers: getGitHubCopilotRefreshHeaders(`token ${githubAccessToken}`),
      });
      if (!response.ok) return null;
      const data = await response.json();
      log?.info?.("TOKEN", "Copilot token refreshed");
      return { token: data.token, expiresAt: data.expires_at };
    } catch (error) {
      log?.error?.("TOKEN", `Copilot refresh error: ${error.message}`);
      return null;
    }
  }

  async refreshGitHubToken(refreshToken, log) {
    try {
      // GitHub Copilot is a public device-flow client: send the public client_id, and
      // only attach client_secret when one is actually configured — never the literal
      // "undefined" that new URLSearchParams produces for a missing value (9router#442).
      const params = new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        client_id: this.config.clientId,
      });
      if (this.config.clientSecret) {
        params.set("client_secret", this.config.clientSecret);
      }
      const response = await fetch(OAUTH_ENDPOINTS.github.token, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
        },
        body: params,
      });
      if (!response.ok) return null;
      const tokens = await response.json();
      log?.info?.("TOKEN", "GitHub token refreshed");
      return {
        accessToken: tokens.access_token,
        refreshToken: tokens.refresh_token || refreshToken,
        expiresIn: tokens.expires_in,
      };
    } catch (error) {
      log?.error?.("TOKEN", `GitHub refresh error: ${error.message}`);
      return null;
    }
  }

  async refreshCredentials(credentials, log): Promise<RefreshedCopilotCredentials | null> {
    let copilotResult = await this.refreshCopilotToken(credentials.accessToken, log);

    if (!copilotResult && credentials.refreshToken) {
      const githubTokens = await this.refreshGitHubToken(credentials.refreshToken, log);
      if (githubTokens?.accessToken) {
        copilotResult = await this.refreshCopilotToken(githubTokens.accessToken, log);
        if (copilotResult) {
          return {
            ...githubTokens,
            copilotToken: copilotResult.token,
            copilotTokenExpiresAt: copilotResult.expiresAt,
            providerSpecificData: {
              copilotToken: copilotResult.token,
              copilotTokenExpiresAt: copilotResult.expiresAt,
            },
          };
        }
        return githubTokens;
      }
    }

    if (copilotResult) {
      return {
        accessToken: credentials.accessToken,
        refreshToken: credentials.refreshToken,
        copilotToken: copilotResult.token,
        copilotTokenExpiresAt: copilotResult.expiresAt,
        providerSpecificData: {
          copilotToken: copilotResult.token,
          copilotTokenExpiresAt: copilotResult.expiresAt,
        },
      };
    }

    return null;
  }

  needsRefresh(credentials) {
    // Always refresh if no copilotToken
    if (!this.getCopilotToken(credentials)) return true;

    const copilotTokenExpiresAt = this.getCopilotTokenExpiresAt(credentials);
    if (copilotTokenExpiresAt) {
      // Handle both Unix timestamp (seconds) and ISO string
      let expiresAtMs = copilotTokenExpiresAt;
      if (typeof expiresAtMs === "number" && expiresAtMs < 1e12) {
        expiresAtMs = expiresAtMs * 1000; // Convert seconds to ms
      } else if (typeof expiresAtMs === "string") {
        expiresAtMs = new Date(expiresAtMs).getTime();
      }
      if (expiresAtMs - Date.now() < 5 * 60 * 1000) return true;
    }
    return super.needsRefresh(credentials);
  }
}

export default GithubExecutor;