github-router 0.3.269 → 0.3.270

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{attribution-settings-B1txv_Lk.js → attribution-settings-of5gJM5a.js} +3 -3
  2. package/dist/{attribution-settings-B1txv_Lk.js.map → attribution-settings-of5gJM5a.js.map} +1 -1
  3. package/dist/{auth-r-my7efo.js → auth-DIFbHOu0.js} +2 -2
  4. package/dist/{auth-r-my7efo.js.map → auth-DIFbHOu0.js.map} +1 -1
  5. package/dist/browser-ext/manifest.json +1 -1
  6. package/dist/{check-usage-CZr2ZkG0.js → check-usage-DfnrR-d_.js} +3 -3
  7. package/dist/{check-usage-CZr2ZkG0.js.map → check-usage-DfnrR-d_.js.map} +1 -1
  8. package/dist/{claude-BjNY0J6e.js → claude-BlzCUbVq.js} +7 -7
  9. package/dist/{claude-BjNY0J6e.js.map → claude-BlzCUbVq.js.map} +1 -1
  10. package/dist/{codex-CoRWpkHL.js → codex-BaFcXOyg.js} +5 -5
  11. package/dist/{codex-CoRWpkHL.js.map → codex-BaFcXOyg.js.map} +1 -1
  12. package/dist/engine-mwIgHJoi.js +2 -0
  13. package/dist/{gate-discovery-D-7oua8b.js → gate-discovery-AUAjqSpV.js} +2 -2
  14. package/dist/{gate-discovery-D-7oua8b.js.map → gate-discovery-AUAjqSpV.js.map} +1 -1
  15. package/dist/{get-copilot-usage-CFEpeA7E.js → get-copilot-usage-Ds09xSmH.js} +2 -2
  16. package/dist/{get-copilot-usage-CFEpeA7E.js.map → get-copilot-usage-Ds09xSmH.js.map} +1 -1
  17. package/dist/{internal-stop-hook-Db5o9RcZ.js → internal-stop-hook-B1MIwmTR.js} +2 -2
  18. package/dist/{internal-stop-hook-Db5o9RcZ.js.map → internal-stop-hook-B1MIwmTR.js.map} +1 -1
  19. package/dist/main.js +8 -8
  20. package/dist/{models-CJLt4XjP.js → models-BFQUp0ov.js} +2 -2
  21. package/dist/{models-CJLt4XjP.js.map → models-BFQUp0ov.js.map} +1 -1
  22. package/dist/{peer-mcp-personas-DSbBlgFt.js → peer-mcp-personas-pWP3Eyt7.js} +152 -84
  23. package/dist/{peer-mcp-personas-DSbBlgFt.js.map → peer-mcp-personas-pWP3Eyt7.js.map} +1 -1
  24. package/dist/{provision-CA-xwnFu.js → provision-CsYUVdMT.js} +2 -2
  25. package/dist/{provision-CA-xwnFu.js.map → provision-CsYUVdMT.js.map} +1 -1
  26. package/dist/{serve-DHny4ewF.js → serve--c9n9hk4.js} +6 -6
  27. package/dist/{serve-DHny4ewF.js.map → serve--c9n9hk4.js.map} +1 -1
  28. package/dist/{server-setup-Dd293T1O.js → server-setup-BmyWS4WU.js} +393 -99
  29. package/dist/server-setup-BmyWS4WU.js.map +1 -0
  30. package/dist/{start-P2rmHBkL.js → start-CXnLBouJ.js} +3 -3
  31. package/dist/{start-P2rmHBkL.js.map → start-CXnLBouJ.js.map} +1 -1
  32. package/dist/{token-C_q95GF7.js → token-iaSGp76k.js} +303 -143
  33. package/dist/token-iaSGp76k.js.map +1 -0
  34. package/package.json +1 -1
  35. package/dist/engine-DpVC7HRL.js +0 -2
  36. package/dist/server-setup-Dd293T1O.js.map +0 -1
  37. package/dist/token-C_q95GF7.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-iaSGp76k.js","names":["process"],"sources":["../src/lib/state.ts","../src/lib/api-config.ts","../src/lib/upstream-retry.ts","../src/lib/error.ts","../src/services/github/get-copilot-token.ts","../src/services/github/get-device-code.ts","../src/services/github/get-user.ts","../src/services/copilot/get-models.ts","../src/services/get-copilot-version.ts","../src/services/get-vscode-version.ts","../src/lib/editor-version-cache.ts","../src/lib/utils.ts","../src/services/github/poll-access-token.ts","../src/lib/token.ts"],"sourcesContent":["import { randomBytes, randomUUID } from \"node:crypto\"\n\nimport type { ModelsResponse } from \"~/services/copilot/get-models\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n\n /**\n * Second, WRITE-capable GitHub token for the first-mate\n * agent-orchestration surface (`--agents`). Minted by a separate\n * device-flow login against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`, scopes `repo workflow read:org`) and\n * stored at `PATHS.GITHUB_AGENT_TOKEN_PATH`, apart from `githubToken`\n * (the Copilot App token, read:user). The first-mate GitHub service\n * layer uses this for ALL its calls (reads included, so it also works\n * on private repos). Undefined until the agent login has run.\n */\n githubAgentToken?: string\n\n accountType: string\n copilotApiUrl?: string\n models?: ModelsResponse\n vsCodeVersion?: string\n copilotVersion?: string\n\n manualApprove: boolean\n rateLimitWait: boolean\n showToken: boolean\n extendedBetas: boolean\n\n /**\n * Opt-in flag for the browser-control MCP tools (`browser_*`). Set by\n * `setupAndServe` from the `--browse` CLI flag or\n * `GH_ROUTER_ENABLE_BROWSE=1` env var. When false, all `browser_*`\n * tools are dropped from `tools/list` AND `tools/call` returns\n * -32601 — same defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `browserToolsEnabled()` in\n * `src/routes/mcp/handler.ts`.\n */\n browseEnabled: boolean\n\n /**\n * Opt-in flag for the fleet session-control MCP tools (`mcp__fleet__*`).\n * Set by `setupAndServe` from the `--fleet` CLI flag or\n * `GH_ROUTER_ENABLE_FLEET=1` env var. When false, all fleet tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `fleetToolsEnabled()` in\n * `src/lib/mcp-capabilities.ts`.\n */\n fleetEnabled: boolean\n\n /**\n * Opt-in flag for the first-mate agent-orchestration MCP tools\n * (`mcp__first-mate__*`) and the in-process GitHub cloud-agent driving\n * layer. Set by `setupAndServe` from the `--agents` CLI flag or\n * `GH_ROUTER_ENABLE_AGENTS=1`. When false, the first-mate tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `fleetToolsEnabled()`. Additionally\n * requires `state.githubAgentToken` present (the write login), so the\n * surface is invisible rather than 401-ing when unauthenticated. See\n * `agentToolsEnabled()` in `src/lib/mcp-capabilities.ts`.\n */\n agentsEnabled: boolean\n\n /**\n * When true, --power-browse was passed (or GH_ROUTER_ENABLE_POWER_BROWSE=1\n * is set). Exposes the FULL browser MCP surface (~18 tools) on /mcp,\n * including the L0/L1 primitives that hand DOM details (refs,\n * bboxes, role/name dumps) to the lead model. Default --browse mode\n * exposes only the 6 lead-model tools (act, observe, extract,\n * navigate, screenshot, open_tab). Always implies browseEnabled.\n */\n powerBrowseEnabled: boolean\n\n /**\n * Humanlike pacing override:\n * \"on\" - --humanlike CLI flag or GH_ROUTER_HUMANLIKE=1 env;\n * inject Beta-distributed inter-action delays, Bezier\n * mouse paths, per-keystroke jitter, scroll chunking\n * into every browser_* action dispatch.\n * \"off\" - GH_ROUTER_BROWSER_NO_HUMANLIKE=1; HARD disable, wins\n * over \"on\" so tests are reproducible.\n * \"auto\" - default; pacing engages only when bot-challenge\n * detection fires (Phase 4-future).\n *\n * Lead model never sees this state — it's an internal concern.\n */\n humanlikeForce: \"on\" | \"off\" | \"auto\"\n\n // Rate limiting configuration\n rateLimitSeconds?: number\n lastRequestTimestamp?: number\n\n // Persistent session identifiers to match VS Code fingerprint\n sessionId: string\n machineId: string\n\n /**\n * Per-launch nonce for the loopback `/mcp` endpoint. Set by the\n * `claude` subcommand after `setupAndServe` and before spawning\n * Claude Code; the spawned MCP client reads it from the\n * `--mcp-config` tempfile and presents it as `Authorization: Bearer`.\n * When unset, `/mcp` rejects all requests — closes the\n * loopback-no-auth gap (DNS rebinding, malicious browser-ext\n * native messaging, sibling-process probe).\n */\n peerMcpNonce?: string\n\n /**\n * Set by `github-router serve` (a single machine-wide control plane serving\n * many repos). When true, repo-scoped worker tools require an explicit/So-derived\n * `workspace` and must NOT silently default to the proxy launch cwd.\n */\n serveMode?: boolean\n}\n\nexport const state: State = {\n accountType: \"enterprise\",\n manualApprove: false,\n rateLimitWait: false,\n showToken: false,\n extendedBetas: false,\n browseEnabled: false,\n fleetEnabled: false,\n agentsEnabled: false,\n powerBrowseEnabled: false,\n humanlikeForce: \"auto\",\n sessionId: randomUUID(),\n machineId: randomBytes(32).toString(\"hex\"),\n}\n","import { randomUUID } from \"node:crypto\"\n\nimport type { State } from \"./state\"\n\nexport const standardHeaders = () => ({\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n})\n\nconst DEFAULT_COPILOT_VERSION = \"0.43.2026033101\"\n\nexport function copilotVersion(state: State): string {\n return state.copilotVersion ?? DEFAULT_COPILOT_VERSION\n}\n\nconst API_VERSION = \"2026-01-09\"\n\nexport const copilotBaseUrl = (state: State) =>\n state.copilotApiUrl ?? \"https://api.githubcopilot.com\"\nexport const copilotHeaders = (\n state: State,\n vision: boolean = false,\n integrationId: string = \"vscode-chat\",\n) => {\n const version = copilotVersion(state)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${state.copilotToken}`,\n \"content-type\": standardHeaders()[\"content-type\"],\n \"copilot-integration-id\": integrationId,\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": `copilot-chat/${version}`,\n \"user-agent\": `GitHubCopilotChat/${version}`,\n \"openai-intent\": \"conversation-panel\",\n \"x-interaction-type\": \"conversation-panel\",\n \"x-github-api-version\": API_VERSION,\n \"x-request-id\": randomUUID(),\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n \"VScode-SessionId\": state.sessionId,\n \"VScode-MachineId\": state.machineId,\n }\n\n if (vision) headers[\"copilot-vision-request\"] = \"true\"\n\n return headers\n}\n\nexport const GITHUB_API_BASE_URL =\n process.env.GITHUB_API_URL ?? \"https://api.github.com\"\nexport const githubHeaders = (state: State) => ({\n ...standardHeaders(),\n authorization: `token ${state.githubToken}`,\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": `copilot-chat/${copilotVersion(state)}`,\n \"user-agent\": `GitHubCopilotChat/${copilotVersion(state)}`,\n \"x-github-api-version\": API_VERSION,\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n})\n\nexport const GITHUB_BASE_URL = \"https://github.com\"\nexport const GITHUB_CLIENT_ID = \"Iv1.b507a08c87ecfe98\"\nexport const GITHUB_APP_SCOPES = [\"read:user\"].join(\" \")\n\n// --- First-mate agent-orchestration write identity (`--agents`) ---------\n// The Copilot device-login token above (a GitHub *App* token, read:user)\n// can READ the agent surface but 403s on any write/push. The first-mate\n// controller needs a WRITE-capable token to create issues, assign cloud\n// coding agents, comment, dispatch workflows, and merge. We mint a second,\n// isolated token via a separate device-flow login against the GitHub CLI's\n// public OAuth client (a classic OAuth App that honors the requested\n// scopes — verified to accept `repo workflow read:org` at\n// `/login/device/code`). Stored apart at PATHS.GITHUB_AGENT_TOKEN_PATH;\n// never mixed with `state.githubToken`.\nexport const GITHUB_AGENT_CLIENT_ID = \"178c6fc778ccc68e1d6a\"\nexport const GITHUB_AGENT_SCOPES = [\"repo\", \"workflow\", \"read:org\"].join(\" \")\nexport const GITHUB_GRAPHQL_URL =\n process.env.GITHUB_GRAPHQL_URL ?? \"https://api.github.com/graphql\"\n// GitHub's documented REST/GraphQL API version for the general-purpose\n// (non-Copilot) surface the first-mate layer drives. The Agent-Tasks\n// preview client overrides this per-call with its own dated version.\nexport const GITHUB_REST_API_VERSION = \"2022-11-28\"\nexport const githubAgentHeaders = (state: State) => ({\n ...standardHeaders(),\n authorization: `token ${state.githubAgentToken}`,\n \"x-github-api-version\": GITHUB_REST_API_VERSION,\n \"user-agent\": \"github-router-first-mate\",\n})\nexport const githubAgentGraphQLHeaders = (state: State, features?: string) => ({\n ...githubAgentHeaders(state),\n ...(features ? { \"GraphQL-Features\": features } : {}),\n})\n","/**\n * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).\n *\n * Retries ONLY on transient conditions — never on success, never on a\n * deterministic 4xx (400/401/403/404…), so a malformed request or auth\n * failure fails fast instead of being hammered. 401 is intentionally NOT\n * retried here: it stays with the existing token-refresh path so the\n * 401→503 forwardError invariant is preserved.\n *\n * Retryable:\n * - HTTP 429 + 5xx (500/502/503/504) — the \"upstream is sick\" class.\n * - network errors (ECONNRESET / \"fetch failed\" / \"terminated\" / EPIPE …).\n * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S\n * `signal` is NOT aborted (a user cancel aborts the caller's signal\n * and is rethrown immediately, never retried).\n *\n * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The\n * inter-attempt sleep is abortable so a user cancel during backoff\n * returns promptly. Bounded `attempts` keep a single call from holding an\n * inflight slot indefinitely (robust AND fast).\n *\n * Streaming note: the user-facing passthrough and the worker loop must\n * only retry in the PRE-FIRST-BYTE window — a retry after bytes have\n * streamed would duplicate output. Callers there pass a `doFetch` that\n * has not yet handed its body to the consumer.\n */\n\nimport consola from \"consola\"\n\nexport interface TransientRetryOpts {\n /** Total attempts including the first (default 3 → up to 2 retries). */\n attempts?: number\n /** Retryable HTTP statuses (default 429, 500, 502, 503, 504). */\n retryStatuses?: ReadonlyArray<number>\n /** Backoff base (default 250ms) and cap (default 4000ms). */\n baseDelayMs?: number\n maxDelayMs?: number\n /** Caller's abort signal — a user cancel fails fast (never retried). */\n signal?: AbortSignal\n /** Short label for debug logging (e.g. \"codex_critic\", \"advisor\"). */\n label?: string\n /** Upstream endpoint when it differs from the human-readable label. */\n endpoint?: string\n}\n\nconst DEFAULT_RETRY_STATUSES: ReadonlyArray<number> = [429, 500, 502, 503, 504]\nconst TRANSPORT_MESSAGE_MAX = 512\nconst TRANSIENT_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n])\nconst DETERMINISTIC_CODES = new Set([\n \"ENOTFOUND\",\n \"ECONNREFUSED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n \"CERT_HAS_EXPIRED\",\n \"CERT_NOT_YET_VALID\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED\",\n \"ERR_SSL_WRONG_VERSION_NUMBER\",\n])\nconst CREDENTIAL_RE =\n /\\b(eyJ[A-Za-z0-9_-]{20,}(?:\\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\\s+\\S{20,})\\b/gi\nconst SECRET_ASSIGNMENT_RE =\n /\\b(authorization|api[_-]?key|access[_-]?token|token|password)\\s*[:=]\\s*([^\\s,;]+)/gi\nconst REQUEST_BODY_RE =\n /\\b(request\\s+body|body)\\s*[:=]\\s*.*$/gi\n\nexport type TransportErrorClassification =\n | \"transient\"\n | \"deterministic\"\n | \"non_transport\"\n | \"cancelled\"\n\nexport interface TransportErrorDetails {\n classification: TransportErrorClassification\n name: string\n message: string\n code?: string\n causeCode?: string\n}\n\nexport interface TransportExhaustionMetadata {\n endpoint?: string\n label?: string\n attempts: number\n classification: \"transient\" | \"deterministic\"\n lastError: Omit<TransportErrorDetails, \"classification\">\n}\n\nexport class TransportExhaustionError extends Error {\n readonly endpoint?: string\n readonly label?: string\n readonly attempts: number\n readonly classification: \"transient\" | \"deterministic\"\n readonly lastError: Omit<TransportErrorDetails, \"classification\">\n\n constructor(metadata: TransportExhaustionMetadata, cause: unknown) {\n const target = metadata.endpoint ?? metadata.label ?? \"upstream\"\n const lastError = {\n name: sanitizeTransportText(metadata.lastError.name),\n message: sanitizeTransportText(metadata.lastError.message),\n code: metadata.lastError.code\n ? sanitizeTransportText(metadata.lastError.code)\n : undefined,\n causeCode: metadata.lastError.causeCode\n ? sanitizeTransportText(metadata.lastError.causeCode)\n : undefined,\n }\n const code = lastError.causeCode ?? lastError.code\n const suffix = code ? ` (${code})` : \"\"\n super(\n `Upstream transport ${metadata.classification === \"transient\" ? \"failed\" : \"is unreachable\"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? \"\" : \"s\"}: ${lastError.name}: ${lastError.message}${suffix}`,\n { cause },\n )\n this.name = \"TransportExhaustionError\"\n this.endpoint = metadata.endpoint\n ? sanitizeTransportText(metadata.endpoint)\n : undefined\n this.label = metadata.label ? sanitizeTransportText(metadata.label) : undefined\n this.attempts = metadata.attempts\n this.classification = metadata.classification\n this.lastError = lastError\n }\n}\n\nfunction readStringProperty(value: unknown, key: string): string | undefined {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n const property = (value as Record<string, unknown>)[key]\n return typeof property === \"string\" ? property : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readCause(value: unknown): unknown {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n return (value as { cause?: unknown }).cause\n } catch {\n return undefined\n }\n}\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return \"[unserializable error]\"\n }\n}\n\nexport function sanitizeTransportText(value: string): string {\n const sanitized = value\n .replace(/\\r\\n|\\r|\\n/g, \" \")\n .replace(CREDENTIAL_RE, \"[REDACTED]\")\n .replace(SECRET_ASSIGNMENT_RE, \"$1=[REDACTED]\")\n .replace(REQUEST_BODY_RE, \"$1=[REDACTED]\")\n return sanitized.length > TRANSPORT_MESSAGE_MAX\n ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…`\n : sanitized\n}\n\n/**\n * Classify errors thrown before the first response byte. Deterministic\n * connectivity/configuration signals win over generic runtime wording such as\n * TypeError(\"fetch failed\"), because the nested cause is more specific.\n */\nexport function classifyTransportError(\n error: unknown,\n opts: { callerCancelled?: boolean } = {},\n): TransportErrorDetails {\n const name = readStringProperty(error, \"name\") ?? \"Error\"\n const rawMessage =\n readStringProperty(error, \"message\")\n ?? (typeof error === \"string\" ? error : safeString(error))\n const message = sanitizeTransportText(rawMessage)\n const code = readStringProperty(error, \"code\")\n\n const causes: unknown[] = []\n const seen = new Set<unknown>()\n let current = readCause(error)\n for (let depth = 0; current !== undefined && depth < 4; depth++) {\n if (\n (typeof current === \"object\" || typeof current === \"function\")\n && current !== null\n ) {\n if (seen.has(current)) break\n seen.add(current)\n }\n causes.push(current)\n current = readCause(current)\n }\n const causeCode = causes\n .map((cause) => readStringProperty(cause, \"code\"))\n .find((value): value is string => value !== undefined)\n const codes = [code, ...causes.map((cause) => readStringProperty(cause, \"code\"))]\n .filter((value): value is string => value !== undefined)\n .map((value) => value.toUpperCase())\n const messages = [\n rawMessage,\n ...causes.map((cause) => readStringProperty(cause, \"message\") ?? \"\"),\n ]\n .join(\" \")\n .toLowerCase()\n\n if (opts.callerCancelled) {\n return { classification: \"cancelled\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || messages.includes(\"self signed certificate\")\n || messages.includes(\"certificate has expired\")\n || messages.includes(\"unable to verify the first certificate\")\n || messages.includes(\"unable to get local issuer certificate\")\n || messages.includes(\"hostname/ip does not match certificate\")\n || messages.includes(\"tls handshake\")\n || messages.includes(\"ssl routines\")\n || messages.includes(\"econnrefused\")\n || messages.includes(\"enotfound\")\n ) {\n return { classification: \"deterministic\", name, message, code, causeCode }\n }\n if (\n name === \"AbortError\"\n || name === \"TimeoutError\"\n || name === \"InactivityTimeout\"\n || codes.some((value) => TRANSIENT_CODES.has(value))\n || messages.includes(\"terminated\")\n || messages.includes(\"fetch failed\")\n || messages.includes(\"network error\")\n || messages.includes(\"socket hang up\")\n || messages.includes(\"socket closed\")\n || messages.includes(\"econnreset\")\n || messages.includes(\"etimedout\")\n || messages.includes(\"epipe\")\n || messages.includes(\"eai_again\")\n ) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n return { classification: \"non_transport\", name, message, code, causeCode }\n}\n\nfunction transportExhaustion(\n error: unknown,\n attempts: number,\n opts: TransientRetryOpts,\n details: TransportErrorDetails,\n): TransportExhaustionError {\n if (\n details.classification !== \"transient\"\n && details.classification !== \"deterministic\"\n ) {\n throw new TypeError(\"transportExhaustion requires a transport error\")\n }\n return new TransportExhaustionError(\n {\n endpoint: opts.endpoint ?? opts.label,\n label: opts.label,\n attempts,\n classification: details.classification,\n lastError: {\n name: details.name,\n message: details.message,\n code: details.code,\n causeCode: details.causeCode,\n },\n },\n error,\n )\n}\n\nfunction parseRetryAfter(headerValue: string | null): number | undefined {\n if (!headerValue) return undefined\n const secs = Number(headerValue)\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000)\n const dateMs = Date.parse(headerValue)\n if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now())\n return undefined\n}\n\n/** Sleep that resolves early (does not reject) when `signal` aborts — the\n * retry loop re-checks `signal.aborted` at the top and throws there. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n if (signal) {\n if (signal.aborted) {\n done()\n return\n }\n signal.addEventListener(\"abort\", done, { once: true })\n }\n })\n}\n\n/**\n * Run `doFetch` with bounded transient-failure retries. `doFetch` is a\n * thunk so each attempt issues a FRESH request (bodies can't be replayed\n * from a consumed stream). Returns the final `Response` — which may still\n * carry a retryable status if all attempts are exhausted (the caller\n * handles that as it would a single-shot failure).\n */\nexport async function fetchWithTransientRetry(\n doFetch: (attempt: number) => Promise<Response>,\n opts: TransientRetryOpts = {},\n): Promise<Response> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n\n let res: Response | undefined\n let caught: unknown\n try {\n res = await doFetch(attempt)\n } catch (err) {\n caught = err\n }\n\n // Success or a non-retryable status → done.\n if (res && !retryStatuses.includes(res.status)) return res\n\n // A thrown error: a user cancel fails fast; otherwise only retry the\n // transient network/timeout class.\n if (caught !== undefined) {\n if (signal?.aborted) throw caught\n const details = classifyTransportError(caught)\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(caught, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw caught\n }\n\n // Out of attempts → return the last error response (or rethrow).\n if (attempt >= attempts) {\n if (res) return res\n const details = classifyTransportError(caught)\n throw transportExhaustion(caught, attempt, opts, details)\n }\n\n // Free the connection before retrying a retryable-status response.\n const retryAfterMs = res\n ? parseRetryAfter(res.headers.get(\"retry-after\"))\n : undefined\n if (res?.body) {\n try {\n await res.body.cancel()\n } catch {\n /* already torn down */\n }\n }\n\n // Full jitter (random within the exponential cap), Retry-After wins.\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n const why = res\n ? `HTTP ${res.status}`\n : (caught as { name?: string } | undefined)?.name ?? \"error\"\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n}\n\n/** Extract an HTTP status from a thrown error (HTTPError carries\n * `.response.status`; others may carry `.status`/`.statusCode`; last\n * resort parses `\"HTTP <code>\"` from the message). */\nfunction errorStatus(err: unknown): number | undefined {\n const e = err as\n | {\n status?: unknown\n statusCode?: unknown\n response?: { status?: unknown }\n message?: string\n }\n | undefined\n for (const v of [e?.status, e?.statusCode, e?.response?.status]) {\n if (typeof v === \"number\") return v\n }\n const m = /\\bHTTP (\\d{3})\\b/.exec(e?.message ?? \"\")\n return m ? Number(m[1]) : undefined\n}\n\n/**\n * Generic transient-retry for a non-`Response`-returning call (e.g. the\n * Copilot service clients, which throw `HTTPError` on non-OK and throw on\n * network errors). Retries `fn()` when it throws a transient error — an\n * `HTTPError`-like with a retryable status (429/5xx) OR a transient\n * network/timeout error — using the same backoff + abort semantics as\n * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.\n * 401), a non-transient throw, or a user cancel.\n */\nexport async function withTransientRetry<T>(\n fn: (attempt: number) => Promise<T>,\n opts: TransientRetryOpts = {},\n): Promise<T> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n try {\n return await fn(attempt)\n } catch (err) {\n if (signal?.aborted) throw err\n const status = errorStatus(err)\n const details = classifyTransportError(err)\n if (status !== undefined) {\n if (!retryStatuses.includes(status) || attempt >= attempts) throw err\n } else {\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(err, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw err\n if (attempt >= attempts) {\n throw transportExhaustion(err, attempt, opts, details)\n }\n }\n\n const retryAfterMs = parseRetryAfter(\n (err as { response?: { headers?: { get?: (k: string) => string | null } } })\n ?.response?.headers?.get?.(\"retry-after\") ?? null,\n )\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${\n status !== undefined ? `HTTP ${status}` : (err as { name?: string })?.name ?? \"error\"\n }); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n }\n}\n","import type { Context } from \"hono\"\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\"\n\nimport consola from \"consola\"\n\nimport {\n sanitizeTransportText,\n TransportExhaustionError,\n} from \"~/lib/upstream-retry\"\n\nexport class HTTPError extends Error {\n response: Response\n\n constructor(message: string, response: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport async function forwardError(c: Context, error: unknown) {\n consola.error(`Error occurred at ${c.req.path}:`, error)\n\n if (error instanceof TransportExhaustionError) {\n const target = sanitizeTransportText(\n error.endpoint ?? error.label ?? c.req.path,\n )\n const diagnostic = formatTransportDiagnostic(error)\n if (error.classification === \"transient\") {\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"overloaded_error\",\n message: `Upstream transport was interrupted at ${target} after ${error.attempts} attempts; retry later. ${diagnostic}`,\n },\n },\n 503,\n )\n }\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"api_error\",\n message: `Could not connect to upstream at ${target}. Check DNS, proxy, firewall, and TLS configuration. ${diagnostic}`,\n },\n },\n 502,\n )\n }\n\n if (error instanceof HTTPError) {\n const errorText = await error.response.text().catch(() => \"\")\n let errorJson: unknown\n try {\n errorJson = JSON.parse(errorText)\n } catch {\n errorJson = undefined\n }\n\n // Map upstream context-overflow errors (413, or 400 with a known\n // overflow substring) to Anthropic's \"prompt is too long\" 400 shape so\n // Claude Code triggers self-compaction instead of bubbling the error.\n // Note: a live probe of an oversized prompt against Copilot returned\n // 200 with stop_reason:\"refusal\" rather than 413/400 — this guard is\n // defensive for the documented Anthropic contract, not load-bearing.\n if (isContextOverflow(error.response.status, errorJson, errorText)) {\n const upstream = resolveErrorMessage(errorJson, errorText)\n consola.error(\"HTTP error (mapped to overflow):\", errorJson ?? errorText)\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"invalid_request_error\",\n message: `prompt is too long: ${upstream}`,\n },\n },\n 400,\n )\n }\n\n // Remap upstream 401 to 503 — maintain the no-401 invariant on the\n // Anthropic-shape boundary. Claude Code's reactive refresh path\n // (function `SZ1` → `D3(0,true,...)` in v2.1.140 binary) fires on\n // any 401 from upstream and attempts to refresh the OAuth token.\n // Spawned-via-proxy sessions use a synthetic credential\n // (`ensureClaudeConfigMirror`'s SYNTHETIC_CREDENTIAL); refreshing\n // it would fail and degrade the session. Mapping 401 → 503 lets\n // the upstream message still reach the user while side-stepping\n // the refresh path. 503 maps to Anthropic's \"overloaded_error\"\n // type — semantically reasonable for \"proxy got an upstream\n // failure, retry later\".\n const responseStatus =\n error.response.status === 401 ? 503 : error.response.status\n\n // Forward upstream Anthropic-format errors as-is (with remapped status)\n if (isAnthropicError(errorJson)) {\n consola.error(\"HTTP error:\", errorJson)\n return c.json(errorJson, responseStatus as ContentfulStatusCode)\n }\n\n const message = resolveErrorMessage(errorJson, errorText)\n consola.error(\"HTTP error:\", errorJson ?? errorText)\n return c.json(\n {\n type: \"error\",\n error: {\n type: resolveErrorType(responseStatus),\n message,\n },\n },\n responseStatus as ContentfulStatusCode,\n )\n }\n\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"api_error\",\n message: error instanceof Error ? error.message : String(error),\n },\n },\n 500,\n )\n}\n\nfunction formatTransportDiagnostic(error: TransportExhaustionError): string {\n const code = error.lastError.causeCode ?? error.lastError.code\n const codeText = code ? ` (${sanitizeTransportText(code)})` : \"\"\n return `${sanitizeTransportText(error.lastError.name)}: ${sanitizeTransportText(error.lastError.message)}${codeText}`\n}\n\n// Extracts error message from { message } or { error: { message } } payloads.\nfunction resolveErrorMessage(errorJson: unknown, fallback: string): string {\n if (typeof errorJson !== \"object\" || errorJson === null) return fallback\n\n const errorRecord = errorJson as Record<string, unknown>\n if (errorRecord.message !== undefined) return String(errorRecord.message)\n\n if (typeof errorRecord.error === \"object\" && errorRecord.error !== null) {\n const nestedRecord = errorRecord.error as Record<string, unknown>\n if (nestedRecord.message !== undefined) return String(nestedRecord.message)\n }\n\n return fallback\n}\n\n/**\n * Check if a parsed JSON body is already in Anthropic error format:\n * { type: \"error\", error: { type: \"...\", message: \"...\" } }\n */\nfunction isAnthropicError(json: unknown): boolean {\n if (typeof json !== \"object\" || json === null) return false\n const record = json as Record<string, unknown>\n if (record.type !== \"error\") return false\n if (typeof record.error !== \"object\" || record.error === null) return false\n const inner = record.error as Record<string, unknown>\n return typeof inner.type === \"string\" && typeof inner.message === \"string\"\n}\n\nconst CONTEXT_OVERFLOW_SUBSTRINGS = [\n \"prompt is too long\",\n \"context_length_exceeded\",\n \"context length exceeded\",\n \"input is too long\",\n \"maximum context length\",\n \"too many tokens\",\n]\n\n/**\n * Detect upstream context-overflow errors so we can remap them to a 400\n * \"prompt is too long\" shape that triggers Claude Code self-compaction.\n *\n * Always remaps 413 (treated as a hard payload-size signal regardless of\n * body wording). Remaps 400 only when the error text contains one of the\n * known overflow substrings — a regular 400 (e.g. \"model not found\") must\n * NOT remap.\n */\nexport function isContextOverflow(\n status: number,\n errorJson: unknown,\n errorText: string,\n): boolean {\n if (status === 413) return true\n if (status !== 400) return false\n\n const haystack = (\n errorText +\n \" \" +\n (typeof errorJson === \"object\" && errorJson !== null\n ? JSON.stringify(errorJson)\n : \"\")\n ).toLowerCase()\n\n return CONTEXT_OVERFLOW_SUBSTRINGS.some((s) => haystack.includes(s))\n}\n\n/**\n * Map HTTP status to Anthropic error type.\n *\n * Note: a 401 from upstream is remapped to 503 in `forwardError` BEFORE\n * this function is called (no-401 invariant — see comment there). The\n * 401 → \"authentication_error\" mapping below is preserved for\n * defensive coverage in case any code path calls `resolveErrorType`\n * directly with an unsanitized status.\n */\nfunction resolveErrorType(status: number): string {\n if (status === 400) return \"invalid_request_error\"\n if (status === 401) return \"authentication_error\"\n if (status === 403) return \"permission_error\"\n if (status === 404) return \"not_found_error\"\n if (status === 429) return \"rate_limit_error\"\n if (status === 503) return \"overloaded_error\"\n if (status === 529) return \"overloaded_error\"\n return \"api_error\"\n}\n","import consola from \"consola\"\n\nimport { GITHUB_API_BASE_URL, githubHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\n/**\n * Allowlist of hosts the router will trust as the Copilot API base URL.\n * Anything else returned in `endpoints.api` (e.g. via a tampered or\n * misconfigured token-exchange response) is rejected — otherwise a\n * malicious value would receive the long-lived GitHub PAT we send to\n * `/mcp` for web search (see `src/services/copilot/web-search.ts`).\n */\nconst COPILOT_HOST_ALLOWLIST = [\n \"api.githubcopilot.com\",\n \"api.individual.githubcopilot.com\",\n \"api.business.githubcopilot.com\",\n \"api.enterprise.githubcopilot.com\",\n]\n\n/**\n * True iff `rawUrl` is an HTTPS URL whose host is a trusted Copilot API host.\n * Exported so every path that sends a long-lived token to a discovered\n * Copilot host (web search, first-mate CAPI session logs) shares one allowlist.\n */\nexport function isAllowedCopilotHost(rawUrl: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(rawUrl)\n } catch {\n return false\n }\n if (parsed.protocol !== \"https:\") return false\n return COPILOT_HOST_ALLOWLIST.includes(parsed.hostname)\n}\n\nexport const getCopilotToken = async () => {\n // GitHub PAT → Copilot token exchange. A transient 429/5xx/network blip\n // here aborts launch (and the interval-driven refresh that keeps the\n // session alive), so retry the transient class with bounded backoff. NO\n // 401-refresh compose: this call IS the token source, and a 401 means a\n // bad/expired GitHub PAT — deterministic, fail fast (retrying would burn\n // budget against a credential that can't recover without re-auth).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/copilot_internal/v2/token`, {\n headers: githubHeaders(state),\n }),\n { label: \"/copilot_internal/v2/token\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get Copilot token\", response)\n\n const data = (await response.json()) as GetCopilotTokenResponse\n\n // Use the API base URL from the token response if available, matching\n // how VS Code determines the CAPI endpoint dynamically — but only when\n // it points at a github-controlled host (see allowlist above).\n // We deliberately do NOT clobber an existing `state.copilotApiUrl` in\n // the disallowed branch: when the user sets `COPILOT_API_URL` themselves\n // (e.g. for local testing or a CI mock), that's an explicit opt-in and\n // a different threat model than a tampered token-exchange response.\n // Allowlist-failing token-response values are simply ignored.\n if (data.endpoints?.api) {\n if (isAllowedCopilotHost(data.endpoints.api)) {\n state.copilotApiUrl = data.endpoints.api\n } else {\n consola.warn(\n `Refusing to honor Copilot API endpoint \"${data.endpoints.api}\" from ` +\n `the token-exchange response — not in allowlist ` +\n `(${COPILOT_HOST_ALLOWLIST.join(\", \")}). ` +\n (state.copilotApiUrl\n ? `Keeping existing override \"${state.copilotApiUrl}\".`\n : `Falling back to the default api.githubcopilot.com.`),\n )\n }\n }\n\n return data\n}\n\ninterface GetCopilotTokenResponse {\n expires_at: number\n refresh_in: number\n token: string\n endpoints?: {\n api?: string\n proxy?: string\n telemetry?: string\n \"origin-tracker\"?: string\n }\n}\n","import {\n GITHUB_APP_SCOPES,\n GITHUB_BASE_URL,\n GITHUB_CLIENT_ID,\n standardHeaders,\n} from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport interface DeviceApp {\n clientId: string\n scope: string\n}\n\nconst DEFAULT_DEVICE_APP: DeviceApp = {\n clientId: GITHUB_CLIENT_ID,\n scope: GITHUB_APP_SCOPES,\n}\n\nexport async function getDeviceCode(\n app: DeviceApp = DEFAULT_DEVICE_APP,\n): Promise<DeviceCodeResponse> {\n // Idempotent device-code bootstrap POST (just requests a fresh code) — a\n // transient 429/5xx/network blip here aborts the whole login flow, so\n // retry the transient class. No auth on this call, so no 401 concern.\n //\n // `app` is parameterized so a SECOND identity (the first-mate write\n // token via the GitHub CLI OAuth client) can reuse this exact flow\n // without a copy-paste fork; defaults preserve the original Copilot\n // App device login.\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_BASE_URL}/login/device/code`, {\n method: \"POST\",\n headers: standardHeaders(),\n body: JSON.stringify({\n client_id: app.clientId,\n scope: app.scope,\n }),\n }),\n { label: \"/login/device/code\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get device code\", response)\n\n return (await response.json()) as DeviceCodeResponse\n}\n\nexport interface DeviceCodeResponse {\n device_code: string\n user_code: string\n verification_uri: string\n expires_in: number\n interval: number\n}\n","import { GITHUB_API_BASE_URL, standardHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport async function getGitHubUser() {\n // GitHub PAT GET — retry transient 429/5xx/network; a 401 (bad PAT) fails\n // fast (not retried by the helper).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/user`, {\n headers: {\n authorization: `token ${state.githubToken}`,\n ...standardHeaders(),\n },\n }),\n { label: \"/user\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get GitHub user\", response)\n\n return (await response.json()) as GithubUserResponse\n}\n\n// Trimmed for the sake of simplicity\ninterface GithubUserResponse {\n login: string\n}\n","import { copilotBaseUrl, copilotHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { tryRefreshAndRetry } from \"~/lib/token\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport const getModels = async () => {\n // Startup catalog fetch — a transient 429/5xx/network blip here leaves\n // the model catalog empty for the whole session, so retry it. This is a\n // Copilot-token GET, so it keeps the 401-refresh path\n // (`tryRefreshAndRetry`) nested INSIDE the transient retry: 401 →\n // refresh once (never retried by the transient layer); 429/5xx/network\n // → bounded retry with backoff. A consumed (non-streamed) GET body is\n // safe to replay.\n const response = await fetchWithTransientRetry(\n () =>\n tryRefreshAndRetry(\n () =>\n fetch(`${copilotBaseUrl(state)}/models`, {\n headers: copilotHeaders(state),\n }),\n \"/models\",\n ),\n { label: \"/models\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get models\", response)\n\n return (await response.json()) as ModelsResponse\n}\n\nexport interface ModelsResponse {\n data: Array<Model>\n object: string\n}\n\ninterface ModelLimits {\n max_context_window_tokens?: number\n max_output_tokens?: number\n max_prompt_tokens?: number\n max_inputs?: number\n max_non_streaming_output_tokens?: number\n vision?: {\n max_prompt_image_size?: number\n max_prompt_images?: number\n supported_media_types?: string[]\n }\n}\n\ninterface ModelSupports {\n tool_calls?: boolean\n parallel_tool_calls?: boolean\n dimensions?: boolean\n streaming?: boolean\n vision?: boolean\n structured_outputs?: boolean\n adaptive_thinking?: boolean\n max_thinking_budget?: number\n min_thinking_budget?: number\n reasoning_effort?: Array<string>\n}\n\ninterface ModelCapabilities {\n family: string\n limits?: ModelLimits\n object: string\n supports?: ModelSupports\n tokenizer: string\n type: string\n}\n\nexport interface Model {\n capabilities: ModelCapabilities\n id: string\n model_picker_enabled: boolean\n name: string\n object: string\n preview: boolean\n vendor: string\n version: string\n supported_endpoints?: Array<string>\n requestHeaders?: Record<string, string>\n policy?: {\n state: string\n terms: string\n }\n billing?: {\n is_premium: boolean\n multiplier: number\n restricted_to?: string[]\n /**\n * Per-token prices, scaled by 1e9. Present on the live catalog even\n * where `is_premium` / `multiplier` are absent (usage-based-billing\n * accounts populate this instead), which is why both shapes are\n * modelled: reading only the premium pair silently yields nothing\n * on those accounts.\n */\n token_prices?: {\n input_price?: number\n output_price?: number\n cache_price?: number\n batch_size?: number\n }\n }\n is_chat_default?: boolean\n is_chat_fallback?: boolean\n model_picker_category?: string\n /** Vendor-authored cost tier (`low` | `medium` | `high` | `very_high`). */\n model_picker_price_category?: string\n info_messages?: Array<{ code: string; message: string }>\n warning_messages?: Array<{ code: string; message: string }>\n}\n","/**\n * Last-resort floor when the lookup fails. A fallback must never become the\n * cached steady state — see the note on `VSCODE_VERSION_FALLBACK` in\n * `./get-vscode-version`.\n */\nexport const COPILOT_CHAT_VERSION_FALLBACK = \"0.43.2026033101\"\nconst FALLBACK = COPILOT_CHAT_VERSION_FALLBACK\n\ninterface MarketplaceResult {\n results: Array<{\n extensions: Array<{\n versions: Array<{ version: string }>\n }>\n }>\n}\n\n/**\n * The lookup, reporting failure as `undefined` rather than as the fallback.\n * See `getVSCodeVersionOrUndefined` for why the distinction matters to the\n * version cache.\n */\nexport async function getCopilotChatVersionOrUndefined(): Promise<\n string | undefined\n> {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, 5000)\n\n try {\n const response = await fetch(\n \"https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json;api-version=7.1-preview.1\",\n },\n body: JSON.stringify({\n filters: [\n {\n criteria: [{ filterType: 7, value: \"GitHub.copilot-chat\" }],\n },\n ],\n flags: 914,\n }),\n signal: controller.signal,\n },\n )\n\n if (!response.ok) return undefined\n\n const data = (await response.json()) as MarketplaceResult\n const version =\n data?.results?.[0]?.extensions?.[0]?.versions?.[0]?.version\n\n return version\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\n/** Fallback-substituting wrapper, for callers that just want a version. */\nexport async function getCopilotChatVersion(): Promise<string> {\n return (await getCopilotChatVersionOrUndefined()) ?? FALLBACK\n}\n","/**\n * Last-resort floor when the lookup fails. A fallback must never become the\n * cached steady state, or a transient outage would freeze the version we\n * impersonate. See `src/lib/editor-version-cache.ts`.\n */\nexport const VSCODE_VERSION_FALLBACK = \"1.104.3\"\nconst FALLBACK = VSCODE_VERSION_FALLBACK\n\n/**\n * The lookup, reporting failure as `undefined` rather than as the fallback.\n *\n * The distinction is load-bearing for the cache: it must not infer \"the fetch\n * failed\" from `value === FALLBACK`, because the live version legitimately\n * equals the constant right after someone bumps `VSCODE_VERSION_FALLBACK` to\n * the then-current release — and that reading would refuse to cache a perfectly\n * good result, making every launch re-pay the ~1.5s network call forever.\n */\nexport async function getVSCodeVersionOrUndefined(): Promise<string | undefined> {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, 5000)\n\n try {\n const response = await fetch(\n \"https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=visual-studio-code-bin\",\n {\n signal: controller.signal,\n },\n )\n\n const pkgbuild = await response.text()\n const pkgverRegex = /pkgver=([0-9.]+)/\n const match = pkgbuild.match(pkgverRegex)\n\n return match ? match[1] : undefined\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\n/** Fallback-substituting wrapper, for callers that just want a version. */\nexport async function getVSCodeVersion(): Promise<string> {\n return (await getVSCodeVersionOrUndefined()) ?? FALLBACK\n}\n\n","/**\n * Disk-backed TTL cache for the EDITOR IDENTITY versions the proxy sends\n * upstream: the VS Code version (`editor-version`) and the Copilot Chat\n * extension version (`editor-plugin-version`), see `src/lib/api-config.ts`.\n *\n * Why this exists: impersonating VS Code is non-negotiable — Copilot is\n * addressed as if by the real editor, so those headers must carry real,\n * current versions. But the two lookups are NETWORK calls to third parties\n * (the Arch AUR PKGBUILD and the VS Marketplace), and they sat on the\n * blocking launch path of EVERY invocation. The AUR fetch alone measured\n * ~1.5-1.8s, which every `github-router` process paid — including the\n * per-turn Claude Code hooks (`internal-prompt-submit`, `internal-stop-hook`,\n * …), each of which is a fresh `node dist/main.js` spawn.\n *\n * The fix is a cache, NOT a removal. Both fetches are still made; they are\n * just made at most once per `TTL_HOURS` instead of once (twice, before the\n * duplicate top-level await in `get-vscode-version.ts` was dropped) per\n * launch. A 12h TTL keeps the impersonated versions well inside the real\n * editor's release cadence.\n *\n * Two invariants that keep impersonation honest:\n *\n * 1. A FALLBACK is NEVER cached. `getVSCodeVersion()` /\n * `getCopilotChatVersion()` return a hardcoded constant when the network\n * fails, and that constant must stay a last-resort floor for the current\n * process — never the persisted steady state. Persisting it would let a\n * transient outage silently freeze the advertised version for 12h, and\n * (worse) survive restarts. `writeEntry` is therefore only reached on a\n * value that differs from the fallback.\n * 2. The timestamp is written only on SUCCESS. An offline machine retries\n * on the next launch rather than pinning a stale entry, which is the\n * opposite of `claude-version-check.ts`'s throttle (that one stamps\n * after the probes regardless, so an offline box pays both timeouts\n * hourly). Do not copy that detail here.\n *\n * The file lives beside `last-update-check` / `last-self-update-check` and is\n * deliberately named distinctly so the three throttles never cross-suppress.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"./paths\"\n\nconst TTL_HOURS = 12\n\n/** One cached lookup: the resolved value plus when it was resolved. */\ninterface CacheEntry {\n value: string\n checkedAt: string\n}\n\ninterface EditorVersionCache {\n vscode?: CacheEntry\n copilotChat?: CacheEntry\n}\n\n/** Which upstream identity a cached entry belongs to. */\nexport type EditorVersionKey = \"vscode\" | \"copilotChat\"\n\nfunction cacheFilePath(): string {\n return path.join(PATHS.APP_DIR, \"last-editor-versions\")\n}\n\n/**\n * True when running under a test runner.\n *\n * Detected from the entry file, not an env var: `bun test` sets no marker of\n * its own and this repo builds with `NODE_ENV=production`, so `argv[1]` (the\n * spec file being executed) is the reliable signal. `BUN_TEST` / `NODE_ENV`\n * are still honored for other runners.\n *\n * The cache's own tests sandbox `homedir()` and opt back in via\n * `__allowEditorVersionWritesForTests`, so they still cover the write path.\n */\nfunction isTestRunner(): boolean {\n if (_allowWriteInTests) return false\n if (process.env.BUN_TEST === \"1\" || process.env.NODE_ENV === \"test\") {\n return true\n }\n const entry = process.argv[1] ?? \"\"\n return /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(entry)\n}\n\n/** Set by the cache's own (sandboxed) tests so they can cover the write path. */\nlet _allowWriteInTests = false\n\n/**\n * Test-only: re-enable persistence. ONLY safe from a test that has redirected\n * `homedir()` to a temp dir — otherwise it writes the caller's fixture into the\n * developer's real cache and the proxy advertises it upstream.\n */\nexport function __allowEditorVersionWritesForTests(on: boolean): void {\n _allowWriteInTests = on\n}\n\nasync function readCache(): Promise<EditorVersionCache> {\n try {\n const parsed = JSON.parse(\n await fs.readFile(cacheFilePath(), \"utf8\"),\n ) as EditorVersionCache\n // A hand-edited or truncated file must degrade to \"no cache\", not throw.\n if (!parsed || typeof parsed !== \"object\") return {}\n return parsed\n } catch {\n return {}\n }\n}\n\nfunction isFresh(entry: CacheEntry | undefined): entry is CacheEntry {\n if (!entry || typeof entry.value !== \"string\" || entry.value.length === 0) {\n return false\n }\n const last = new Date(entry.checkedAt).getTime()\n if (Number.isNaN(last)) return false\n // A clock moved backwards would make `age` negative; treating that as stale\n // costs one refetch, whereas treating it as fresh could pin a bad value.\n const ageHours = (Date.now() - last) / 1000 / 3600\n return ageHours >= 0 && ageHours < TTL_HOURS\n}\n\n/**\n * Serializes the read-modify-write below.\n *\n * `setupAndServe` resolves both keys concurrently (`Promise.all`). Without\n * this, both callers would `readCache()` into their OWN object, spend ~1.5s in\n * their network fetch, and then write that stale object back — so whichever\n * finished last would clobber the other's entry, and one of the two versions\n * would re-fetch on every launch forever.\n *\n * The chain also re-reads immediately before mutating, so the write is against\n * current disk state rather than the snapshot taken before the fetch.\n */\nlet writeChain: Promise<void> = Promise.resolve()\n\nfunction serializeWrite(fn: () => Promise<void>): Promise<void> {\n const next = writeChain.then(fn, fn)\n // Never let a rejection poison the chain for later writers.\n writeChain = next.catch(() => {})\n return next\n}\n\n/**\n * Resolve `key` through the cache, calling `fetchFresh` only on a miss.\n *\n * `fetchFresh` signals failure by returning `undefined` — NOT by returning the\n * fallback constant. Inferring failure from `value === fallback` would break\n * exactly when the live version happens to equal the hardcoded constant, which\n * is the normal state right after someone bumps that constant to the\n * then-current version: the entry would never be written and every launch\n * would pay the ~1.5s fetch forever, silently defeating the cache.\n *\n * `fallback` is returned when the lookup fails and no usable cached value\n * exists. It is never persisted (invariant 1 above), so a transient outage\n * cannot freeze the version we impersonate.\n */\nexport async function resolveEditorVersion(\n key: EditorVersionKey,\n fetchFresh: () => Promise<string | undefined>,\n fallback: string,\n): Promise<string> {\n const entry = (await readCache())[key]\n const cachedValue = isFresh(entry) ? entry.value : undefined\n if (cachedValue !== undefined) return cachedValue\n\n const fetched = await fetchFresh()\n\n if (fetched !== undefined && fetched.length > 0) {\n // Never persist from a test process. The cached value is sent upstream as\n // the `editor-version` header, so a test that stubs the fetcher would\n // otherwise write its fixture into the DEVELOPER'S real cache and the\n // proxy would advertise it to Copilot for the full 12h TTL. That is not\n // hypothetical — a smoke test caught `editor-version: vscode/1.2.3` live\n // on this machine, sourced from a unit-test stub.\n //\n // Belt-and-braces with sandboxing the cache's own tests: any FUTURE test\n // that reaches this function through some other caller is covered too,\n // without every such test having to remember to mock homedir(). Reads stay\n // enabled, so warm-cache behavior is still exercisable.\n if (isTestRunner()) return fetched\n await serializeWrite(async () => {\n // Re-read INSIDE the chain: another key's write may have landed while\n // this one was in its fetch, and that entry must survive.\n const cache = await readCache()\n cache[key] = { value: fetched, checkedAt: new Date().toISOString() }\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n // A write failure only costs a refetch next launch.\n consola.debug(\"Failed to write editor-version cache:\", err)\n }\n })\n return fetched\n }\n\n // The lookup failed. A stale-but-real cached value beats the hardcoded\n // constant: a version that was genuinely current when it was cached is a\n // closer impersonation than one frozen at release time. Left un-restamped,\n // so the next launch still retries.\n if (typeof entry?.value === \"string\" && entry.value.length > 0) {\n return entry.value\n }\n return fallback\n}\n\n/** Test seam: the on-disk path, so tests can point HOME at a temp dir. */\nexport function editorVersionCachePath(): string {\n return cacheFilePath()\n}\n","import consola from \"consola\"\n\nimport { getModels } from \"~/services/copilot/get-models\"\nimport {\n COPILOT_CHAT_VERSION_FALLBACK,\n getCopilotChatVersionOrUndefined,\n} from \"~/services/get-copilot-version\"\nimport {\n getVSCodeVersionOrUndefined,\n VSCODE_VERSION_FALLBACK,\n} from \"~/services/get-vscode-version\"\n\nimport { resolveEditorVersion } from \"./editor-version-cache\"\nimport { state } from \"./state\"\n\nexport const sleep = (ms: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n\nexport const isNullish = (value: unknown): value is null | undefined =>\n value === null || value === undefined\n\n/**\n * Beta prefixes VS Code Copilot Chat v0.43 actually sends.\n * Default mode — makes proxy traffic indistinguishable from VS Code.\n */\nconst VSCODE_BETA_PREFIXES = [\n \"interleaved-thinking-\",\n \"context-management-\",\n \"advanced-tool-use-\",\n]\n\n/**\n * Extended beta prefixes for Claude CLI compatibility.\n * Enabled via --extended-betas flag. Includes all betas confirmed\n * to work with the Copilot API.\n *\n * Notably absent (Copilot 400s on these — verified live):\n * context-1m-, skills-, files-api-, code-execution-, output-128k-,\n * advisor-tool- (see EXPLICITLY_STRIPPED_BETA_PREFIXES below).\n * 1M context is unlocked by selecting `claude-opus-4.7-1m-internal`\n * as the model id, not via a beta header.\n *\n * Empirical verification (2026-05-11 against api.enterprise.githubcopilot.com):\n * task-budgets-2026-03-13 → 200 ACCEPTED (cost-ceiling leverage)\n * token-efficient-tools-2026-03-28 → 200 ACCEPTED (per-tool token saving)\n * summarize-connector-text-2026-03-13 → 200 (Anthropic-internal feature flag,\n * won't fire for non-ant users; allowlisted defensively for ant edge case)\n * afk-mode-2026-01-31 → 200 (Anthropic-internal feature flag)\n * cli-internal-2026-02-09 → 200 (USER_TYPE=ant only)\n * oauth-2025-04-20 → 200 (Files-API path; Files-API itself\n * is not supportable via Copilot, but the header alone is harmless)\n * prompt-caching-scope-2026-01-05 → 200 even with body cache_control.scope\n * stripped (already covered by `prompt-caching-` prefix above)\n */\nconst EXTENDED_BETA_PREFIXES = [\n ...VSCODE_BETA_PREFIXES,\n \"claude-code-\",\n \"effort-\",\n \"prompt-caching-\",\n \"computer-use-\",\n \"pdfs-\",\n \"max-tokens-\",\n \"token-counting-\",\n \"compact-\",\n \"structured-outputs-\",\n \"fast-mode-\",\n \"mcp-client-\",\n \"mcp-servers-\",\n \"redact-thinking-\",\n \"web-search-\",\n // Empirically accepted by Copilot, sent by Claude Code v2.1.138+\n \"task-budgets-\",\n \"token-efficient-tools-\",\n // Anthropic-internal feature flags (won't reach proxy from non-ant users\n // due to Bun build-time dead-code elimination, but allowlisted so the rare\n // ant-user / managed-deployment case flows cleanly).\n \"summarize-connector-text-\",\n \"afk-mode-\",\n \"cli-internal-\",\n \"oauth-\",\n]\n\n/**\n * Beta prefixes the proxy explicitly STRIPS even from the extended\n * allowlist (and even if a future leverage mode broadens the allowlist\n * further). Defensive layer: today's allowlist-only filter would already\n * drop these because they're not in any allowlist, but keeping an\n * explicit deny-list catches future changes that broaden allow rules\n * (e.g. a hypothetical pattern-based mode that lets `claude-*` through).\n *\n * Empirical (2026-05-11): Copilot returns HTTP 400\n * `unsupported beta header(s): advisor-tool-2026-03-01`\n * on every request that includes `advisor-tool-`. Stripping it is the\n * difference between a working request (no ADVISOR semantics) and a\n * fully-failed request. Document upstream limitation in CLAUDE.md.\n */\nconst EXPLICITLY_STRIPPED_BETA_PREFIXES = [\n \"advisor-tool-\",\n] as const\n\n/**\n * Filter an `anthropic-beta` header value, keeping only beta flags\n * in the active whitelist AND not in the explicit-strip list.\n * Uses extended prefixes when --extended-betas is enabled, VS Code-only\n * prefixes otherwise. Returns the filtered comma-separated string,\n * or undefined if nothing remains.\n */\nexport function filterBetaHeader(value: string): string | undefined {\n const prefixes = state.extendedBetas\n ? EXTENDED_BETA_PREFIXES\n : VSCODE_BETA_PREFIXES\n const filtered = value\n .split(\",\")\n .map((v) => v.trim())\n .filter(\n (v) =>\n v\n && prefixes.some((prefix) => v.startsWith(prefix))\n && !EXPLICITLY_STRIPPED_BETA_PREFIXES.some((p) => v.startsWith(p)),\n )\n .join(\",\")\n return filtered || undefined\n}\n\n/**\n * Normalize a model ID for fuzzy comparison: lowercase, replace dots with\n * dashes, insert dash at letter→digit boundaries, and collapse repeated\n * dashes. E.g. \"gpt5.3-codex\" → \"gpt-5-3-codex\", \"GPT-5.3-Codex\" → \"gpt-5-3-codex\".\n */\nexport function normalizeModelId(id: string): string {\n return id\n .toLowerCase()\n .replace(/\\./g, \"-\")\n .replace(/([a-z])(\\d)/g, \"$1-$2\")\n .replace(/-{2,}/g, \"-\")\n}\n\n/**\n * Resolve a model name to the best available variant in the Copilot model list.\n *\n * Resolution cascade:\n * 0. `[1m]` literal-bracket suffix: strip, delegate, warn if downgraded.\n * Bracketed slug must never reach Copilot (400s on it). See cc-backup\n * `src/utils/context.ts:35-40` for Claude Code's 1M unlock mechanism.\n * 1. Exact match\n * 2. Case-insensitive match\n * 3. Family preference (opus→1m, codex→highest version)\n * 4. Normalized match (dots→dashes, letter-digit boundaries)\n * 5. Anthropic dated-slug retry: if the input matches `claude-...-YYYYMMDD`,\n * strip the date and re-run the cascade once. Family-guarded so non-claude\n * 8-digit suffixes can't be mis-stripped; runs after Steps 1-4 so explicit\n * version pinning (a dated catalog id matched at Step 1) always wins.\n * 6. Return as-is with a warning\n */\n/**\n * `[1m]`-downgrade warnings we've already emitted this process. `resolveModel`\n * is called many times per launch (env setup, model validation, the banner,\n * and — under `serve` — on every model-picker `/models` poll), so the downgrade\n * notice is deduped to once per model id to avoid log spam.\n */\nconst warnedOneMDowngrade = new Set<string>()\n\n/** Test-only: clear the once-per-process `[1m]`-downgrade warning cache. */\nexport function __resetOneMDowngradeWarnings(): void {\n warnedOneMDowngrade.clear()\n}\n\nexport function resolveModel(modelId: string): string {\n const models = state.models?.data\n if (!models) return modelId\n\n // [1m] literal-bracket suffix: Claude Code's request for 1M context\n // accounting. cc-backup `src/utils/context.ts:35-40` has1mContext\n // matches `/\\[1m\\]/i`; getContextWindowForModel returns 1_000_000\n // when true. parseUserSpecifiedModel (model.ts:445-506) reattaches\n // the bracket after alias resolution, so Claude Code SENDS the\n // bracketed slug verbatim on the wire (`model: \"claude-opus-4-7[1m]\"`).\n // Copilot doesn't recognize the bracket → 400.\n //\n // Strip for the catalog lookup and delegate. If the stripped\n // resolution lands on a `-1m` variant (enterprise opus path via\n // family preference), perfect — the upstream call routes to the 1M\n // backend and Claude Code's local accounting was right. Otherwise\n // (non-enterprise for opus, or any [1m] on sonnet/haiku where\n // Copilot has no -1m backend), warn and return the 200K resolution\n // so the request still succeeds — at the cost of Claude Code\n // over-accounting context against the proxy (it will compact early\n // because it thinks the window is 1M).\n //\n // Bounded recursion: the stripped form no longer matches the regex,\n // so the inner resolveModel call cannot re-enter this branch.\n const oneMMatch = modelId.match(/^(.*)\\[1m\\]$/i)\n if (oneMMatch) {\n const stripped = oneMMatch[1]\n const resolved = resolveModel(stripped)\n // The resolved slug delivers 1M context either as a `-1m` variant OR\n // as a base slug that natively advertises a >=1M window (how opus-4.8\n // and opus-5 ship — a single slug, no `-1m` sibling). Only warn about a\n // real downgrade: a resolved model whose catalog window is under 1M.\n const resolvedIs1M =\n /-1m(?:$|-)/.test(resolved)\n || (models.find((m) => m.id === resolved)?.capabilities?.limits\n ?.max_context_window_tokens ?? 0) >= 1_000_000\n if (!resolvedIs1M && !warnedOneMDowngrade.has(modelId)) {\n warnedOneMDowngrade.add(modelId)\n consola.warn(\n `Model \"${modelId}\" requested 1M context but no 1M backend is in Copilot's catalog for this tier/family; downgrading upstream to \"${resolved}\" (200K). Claude Code's local context accounting will still assume 1M — expect premature auto-compact. Drop the [1m] suffix (or unset CLAUDE_CODE_DISABLE_1M_CONTEXT if you set it) to silence.`,\n )\n }\n return resolved\n }\n\n // 1. Exact match\n if (models.some((m) => m.id === modelId)) return modelId\n\n // 2. Case-insensitive match\n const lower = modelId.toLowerCase()\n const ciMatch = models.find((m) => m.id.toLowerCase() === lower)\n if (ciMatch) return ciMatch.id\n\n // 3. Family preference — before normalization so product aliases\n // (opus→1m, codex→latest) take priority over fuzzy matches\n if (lower.includes(\"opus\")) {\n // Match ...-1m or ...-1m-<anything> (e.g. claude-opus-4.7-1m-internal).\n // Prefer the 1M variant whose major.minor matches the requested version,\n // otherwise find() would silently downgrade claude-opus-4.7 to a\n // claude-opus-4.6-1m if the latter happens to come first in the list.\n // Accept both dotted (\"opus-4.7\") and dashed (\"opus-4-7\") inputs —\n // Claude Code historically sends the dashed form.\n const oneMs = models.filter(\n (m) => m.id.includes(\"opus\") && /-1m(?:$|-)/.test(m.id),\n )\n // Capture the requested version. The minor segment is OPTIONAL so a\n // single-segment slug like `claude-opus-5` registers as a specific\n // version (\"5\") rather than falling through to the `oneMs[0]` wildcard\n // below — which would silently downgrade a catalog-absent `claude-opus-5`\n // to the first unrelated opus `-1m` sibling (e.g. claude-opus-4.6-1m).\n const versionMatch = lower.match(/opus-(\\d+)(?:[.-](\\d+))?/)\n const requestedVersion = versionMatch\n ? versionMatch[2]\n ? `${versionMatch[1]}.${versionMatch[2]}`\n : versionMatch[1]\n : undefined\n const preferred = requestedVersion\n ? oneMs.find((m) => m.id.includes(`opus-${requestedVersion}-`))\n : undefined\n // When a specific version was requested (e.g. \"claude-opus-4-8\") but\n // no matching 1M variant exists in the catalog, do NOT fall back to a\n // different version's 1M variant — that silently downgrades (e.g.\n // 4.8 → 4.6-1m). Instead, fall through to step 4 (normalization)\n // which will resolve the bare dotted entry (claude-opus-4.8).\n const oneM = preferred ?? (requestedVersion ? undefined : oneMs[0])\n if (oneM) return oneM.id\n }\n\n if (lower.includes(\"codex\")) {\n const codexModels = models.filter(\n (m) => m.id.includes(\"codex\") && !m.id.includes(\"mini\"),\n )\n if (codexModels.length > 0) {\n codexModels.sort((a, b) => b.id.localeCompare(a.id))\n return codexModels[0].id\n }\n }\n\n // 4. Normalized match (dots → dashes, letter-digit boundaries)\n const normalized = normalizeModelId(modelId)\n const normMatch = models.find(\n (m) => normalizeModelId(m.id) === normalized,\n )\n if (normMatch) return normMatch.id\n\n // 5. Anthropic dated-slug retry. Claude Code's /model UI ships Anthropic's\n // published slugs (e.g. \"claude-haiku-4-5-20251001\") that carry a\n // -YYYYMMDD suffix Copilot's catalog doesn't use. Strip the date and\n // re-run the cascade once so the request maps to the floating tag\n // (claude-haiku-4.5). Family-guarded to `claude-` so a hypothetical\n // \"gpt-...-20260101\" can't be silently stripped. Bounded recursion:\n // the stripped id no longer matches the regex, so the retry's own\n // Step 5 is a no-op.\n const dateStripped = modelId.replace(/^(claude-[\\w.-]+)-20\\d{6}$/i, \"$1\")\n if (dateStripped !== modelId) {\n const retried = resolveModel(dateStripped)\n // resolveModel returns the input unchanged on miss; treat unchanged-and-\n // not-in-catalog as miss to avoid logging a misleading \"resolved\" hop.\n const retryHit =\n retried !== dateStripped || models.some((m) => m.id === dateStripped)\n if (retryHit) {\n consola.info(\n `Resolved Anthropic dated slug \"${modelId}\" → \"${retried}\" (stripped -YYYYMMDD; pass an explicit catalog id to pin a snapshot)`,\n )\n return retried\n }\n }\n\n // 6. Legacy family fallback. Claude Code's settings.json may pin slugs\n // whose Copilot equivalent does not exist (e.g. claude-3-7-sonnet-20250219\n // or claude-sonnet-4-0 — neither is in Copilot's enterprise catalog as\n // of 2026-05-11; a request for either returns HTTP 400 \"model not\n // supported\"). Step 5's dated-retry strips the date but the resulting\n // \"claude-3-7-sonnet\" still has no Copilot equivalent. Rather than\n // dead-end the request, fall back to the highest available family\n // member (sonnet → highest sonnet, haiku → highest haiku). Surfaces\n // via consola.info so the user sees the substitution. Opus is already\n // handled by the family preference in Step 3.\n //\n // Guards (codex-reviewer findings):\n // (a) Family fires only for `claude-` prefixed inputs — protects\n // against custom-sonnet-future or any non-Anthropic provider\n // coincidentally containing \"sonnet\"/\"haiku\" in its slug.\n // (b) Family token must be word-bounded (`-sonnet-` / `-sonnet$`)\n // so a hypothetical claude-supersonnet-* doesn't match.\n // (c) Sort uses numeric collation (`{numeric: true}`) so a future\n // claude-sonnet-4.10 sorts higher than claude-sonnet-4.6\n // (lexicographic alone would invert).\n if (lower.startsWith(\"claude-\")) {\n const matchSonnet = /(?:^|-)sonnet(?:-|$)/.test(lower)\n const matchHaiku = /(?:^|-)haiku(?:-|$)/.test(lower)\n if (matchSonnet || matchHaiku) {\n const family = matchSonnet ? \"sonnet\" : \"haiku\"\n const familyMembers = models.filter((m) =>\n new RegExp(`(?:^|-)${family}(?:-|$|\\\\.)`).test(m.id),\n )\n if (familyMembers.length > 0) {\n familyMembers.sort((a, b) =>\n b.id.localeCompare(a.id, undefined, { numeric: true }),\n )\n const best = familyMembers[0].id\n consola.info(\n `Model \"${modelId}\" not in Copilot catalog; falling back to highest available \"${best}\" (legacy ${family} slug). Pin a current catalog id to silence.`,\n )\n return best\n }\n }\n }\n\n // 7. No match — warn and return as-is\n consola.warn(\n `Model \"${modelId}\" not found in Copilot model list. Available: ${models.map((m) => m.id).join(\", \")}`,\n )\n return modelId\n}\n\n/**\n * Resolve a codex model ID, falling back to the best available codex model.\n * Used by the codex subcommand for model selection.\n */\nexport function resolveCodexModel(modelId: string): string {\n const resolved = resolveModel(modelId)\n const models = state.models?.data\n if (!models) return resolved\n\n // Check if the resolved model exists in the model list\n if (models.some((m) => m.id === resolved)) return resolved\n\n // Fall back to the best available codex-class model. The /responses\n // endpoint is the discriminator — gpt-5.5 dropped the -codex suffix but\n // still routes through /responses. Prefer explicit -codex ids when both\n // exist, otherwise pick the highest version-like id.\n const candidates = models.filter((m) => {\n const endpoints = m.supported_endpoints ?? []\n if (m.id.includes(\"mini\") || m.id.includes(\"nano\")) return false\n return endpoints.length === 0 || endpoints.includes(\"/responses\")\n })\n\n if (candidates.length > 0) {\n candidates.sort((a, b) => {\n const aCodex = a.id.includes(\"codex\") ? 1 : 0\n const bCodex = b.id.includes(\"codex\") ? 1 : 0\n if (aCodex !== bCodex) return bCodex - aCodex\n return b.id.localeCompare(a.id)\n })\n const best = candidates[0].id\n consola.warn(`Model \"${modelId}\" not available, using \"${best}\" instead`)\n return best\n }\n\n return resolved\n}\n\nexport async function cacheModels(): Promise<void> {\n const models = await getModels()\n state.models = models\n}\n\nexport const cacheVSCodeVersion = async () => {\n const response = await resolveEditorVersion(\n \"vscode\",\n getVSCodeVersionOrUndefined,\n VSCODE_VERSION_FALLBACK,\n )\n state.vsCodeVersion = response\n\n consola.info(`Using VSCode version: ${response}`)\n}\n\nexport const cacheCopilotVersion = async () => {\n const version = await resolveEditorVersion(\n \"copilotChat\",\n getCopilotChatVersionOrUndefined,\n COPILOT_CHAT_VERSION_FALLBACK,\n )\n state.copilotVersion = version\n\n consola.info(`Using Copilot Chat version: ${version}`)\n}\n","import consola from \"consola\"\n\nimport {\n GITHUB_BASE_URL,\n GITHUB_CLIENT_ID,\n standardHeaders,\n} from \"~/lib/api-config\"\nimport { sleep } from \"~/lib/utils\"\n\nimport type { DeviceCodeResponse } from \"./get-device-code\"\n\n/**\n * Per-attempt cap for a single device-code poll.\n *\n * Deliberately NOT the shared transient-retry layer: a non-OK response here is\n * the EXPECTED steady state (`authorization_pending` until the user finishes in\n * their browser), so retrying it as a transient fault would just hammer GitHub\n * inside a loop that is already a retry loop with its own interval.\n *\n * What was genuinely missing is a bound on a single attempt. Without a signal a\n * hung socket blocks the loop forever: the `expiresAt` check only runs between\n * attempts, so it can never fire while one attempt is stuck. This caps each\n * attempt so the loop keeps ticking and the expiry bound stays real.\n */\nconst POLL_ATTEMPT_TIMEOUT_MS = 30_000\n\nexport async function pollAccessToken(\n deviceCode: DeviceCodeResponse,\n clientId: string = GITHUB_CLIENT_ID,\n): Promise<string> {\n // Interval is in seconds, we need to multiply by 1000 to get milliseconds\n // I'm also adding another second, just to be safe\n const sleepDuration = (deviceCode.interval + 1) * 1000\n consola.debug(`Polling access token with interval of ${sleepDuration}ms`)\n const expiresAt = Date.now() + deviceCode.expires_in * 1000\n // Remembered so a permanent misconfiguration (bad DNS, TLS interception, a\n // blocking proxy) is reported as itself rather than surfacing as a bare\n // \"device code expired\" after the full window has silently burned.\n let lastFetchError: unknown\n\n while (Date.now() < expiresAt) {\n let response: Response\n try {\n response = await fetch(`${GITHUB_BASE_URL}/login/oauth/access_token`, {\n method: \"POST\",\n headers: standardHeaders(),\n body: JSON.stringify({\n client_id: clientId,\n device_code: deviceCode.device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n signal: AbortSignal.timeout(POLL_ATTEMPT_TIMEOUT_MS),\n })\n } catch (err) {\n // A timed-out or failed attempt is not fatal — the device code may still\n // be authorized before it expires, so keep polling until it does.\n lastFetchError = err\n consola.debug(\"Access-token poll attempt failed; retrying:\", err)\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n continue\n }\n\n // Reaching here means the transport worked, whatever the HTTP status. Clear\n // any earlier transport failure so a transient blip mid-flow cannot make\n // the final message blame the network for a genuine expiry.\n lastFetchError = undefined\n\n if (!response.ok) {\n consola.error(\"Failed to poll access token:\", await response.text())\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n continue\n }\n\n const json = await response.json()\n consola.debug(\"Polling access token response:\", json)\n\n const { access_token } = json as AccessTokenResponse\n\n if (access_token) {\n return access_token\n }\n\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n }\n\n // If every attempt failed at the transport layer, the device code almost\n // certainly did NOT expire — the network did. Report that, with the real\n // error as `cause`, so a misconfigured proxy or TLS setup is diagnosable\n // instead of masquerading as a timing problem.\n if (lastFetchError !== undefined) {\n throw new Error(\n \"Could not reach GitHub to complete device-code authorization. Check network/proxy/TLS settings and run auth again.\",\n { cause: lastFetchError },\n )\n }\n throw new Error(\"Device code expired. Please run auth again.\")\n}\n\ninterface AccessTokenResponse {\n access_token: string\n token_type: string\n scope: string\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\n\nimport { PATHS } from \"~/lib/paths\"\nimport { getCopilotToken } from \"~/services/github/get-copilot-token\"\nimport { getDeviceCode } from \"~/services/github/get-device-code\"\nimport { getGitHubUser } from \"~/services/github/get-user\"\nimport { pollAccessToken } from \"~/services/github/poll-access-token\"\n\nimport {\n GITHUB_AGENT_CLIENT_ID,\n GITHUB_AGENT_SCOPES,\n GITHUB_API_BASE_URL,\n githubAgentHeaders,\n} from \"./api-config\"\nimport { HTTPError } from \"./error\"\nimport { state } from \"./state\"\n\nconst readGithubToken = () => fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n\n/**\n * Backoff for a transient Windows rename failure. On Windows `fs.rename` over\n * an existing destination transiently fails with EPERM / EBUSY / EACCES when\n * anything else holds the target open for a moment (antivirus, the search\n * indexer, a backup agent). Nothing is wrong and the handle closes microseconds\n * later — but without a retry, a scan landing on the wrong millisecond throws\n * out of a credential write and costs the user a re-auth. Same delays as\n * `renameWithRetry` in `~/lib/claude-md-injection`, which documents the\n * underlying behavior at length.\n */\nconst RENAME_RETRY_DELAYS_MS = [50, 200, 500] as const\n\n/**\n * Replace a credential file atomically: temp + rename, with bounded retry.\n *\n * A plain `fs.writeFile` truncates the destination before it writes, so a\n * crash, a full disk, or a kill mid-write leaves a truncated token on disk and\n * forces the user through a re-auth. `rename` within the same directory is\n * atomic on both NTFS and POSIX, so a reader sees either the old token or the\n * new one, never a partial.\n *\n * The temp name uses `randomBytes`, not `Math.random()`: this names a file that\n * briefly holds a credential, and a predictable name in a shared directory\n * invites a pre-creation race. Combined with `flag: \"wx\"` (fail if it exists)\n * the write refuses to follow anything an attacker pre-placed, rather than\n * silently writing the token through a planted symlink.\n *\n * Permissions: the temp file is created 0o600, and `rename` carries that mode\n * with it on POSIX — so the destination's mode is preserved, not weakened.\n * (On Windows `chmod` is a no-op anyway; see `chmodIfPossible` in `~/lib/paths`.\n * Both token files live under `CLAUDE_RUNTIME_DIR`, which is chmod'd 0o700, so\n * directory ACLs are what actually protect them there.)\n */\nasync function writeTokenFileAtomic(\n filePath: string,\n token: string,\n): Promise<void> {\n const tmp = `${filePath}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`\n try {\n await fs.writeFile(tmp, token, { mode: 0o600, flag: \"wx\" })\n\n let lastErr: unknown\n let renamed = false\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) {\n try {\n await fs.rename(tmp, filePath)\n renamed = true\n break\n } catch (err) {\n lastErr = err\n // Don't sleep after the final attempt.\n if (attempt < RENAME_RETRY_DELAYS_MS.length) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n }\n // A persistent failure (permissions, full disk) still throws: the caller\n // must not believe a credential was stored when it was not.\n if (!renamed) throw lastErr\n } catch (err) {\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n}\n\nconst writeGithubToken = (token: string) =>\n writeTokenFileAtomic(PATHS.GITHUB_TOKEN_PATH, token)\n\nconst readGithubAgentToken = () =>\n fs.readFile(PATHS.GITHUB_AGENT_TOKEN_PATH, \"utf8\")\n\nconst writeGithubAgentToken = (token: string) =>\n writeTokenFileAtomic(PATHS.GITHUB_AGENT_TOKEN_PATH, token)\n\n/**\n * Stops the background Copilot-token refresh started by\n * {@link setupCopilotToken}. Idempotent.\n */\nexport type StopCopilotTokenRefresh = () => void\n\n/**\n * Fetch the Copilot token and keep it fresh in the background.\n *\n * Returns a disposer that stops the refresh loop. **Long-lived callers**\n * (`start`/`claude`/`codex`, via `setupAndServe`) can ignore it — the interval\n * is `unref()`d, so it never holds the event loop open on its own. The one-shot\n * `models` command calls it, so ownership of the timer is explicit rather than\n * implied by a runtime flag. (`check-usage` does not call this function at all;\n * it only needs `setupGitHubToken`.)\n *\n * Both halves are load-bearing, for different failure modes. Without the\n * `unref()`, `github-router models` printed its full correct output and then\n * hung forever: its success path just returns (only the failure branches call\n * `process.exit`), and the un-unref'd interval pinned the event loop. Without\n * the disposer, that fix would depend on a property no caller can see, so the\n * next one-shot command would inherit the same trap.\n */\nexport const setupCopilotToken = async (): Promise<StopCopilotTokenRefresh> => {\n const { token, refresh_in } = await getCopilotToken()\n state.copilotToken = token\n\n // Display the Copilot token to the screen\n consola.debug(\"GitHub Copilot Token fetched successfully!\")\n if (state.showToken) {\n consola.info(\"Copilot token:\", token)\n }\n\n const refreshInterval = Math.max((refresh_in - 60) * 1000, 1000)\n const handle = setInterval(() => {\n void refreshCopilotToken(\"interval\")\n }, refreshInterval)\n // A refresh timer is not a reason for the process to stay alive; it exists\n // to serve work that is already keeping it alive.\n handle.unref?.()\n\n let stopped = false\n return () => {\n if (stopped) return\n stopped = true\n clearInterval(handle)\n }\n}\n\n// Single-flight mutex around the refresh fetch. Concurrent triggers (interval\n// + a 401-retry path) share one in-flight refresh promise so we never\n// overlap network calls or race writes to state.copilotToken.\nlet inflightRefresh: Promise<void> | undefined\n// Cooldowns are keyed off the OUTCOME of the last refresh, not the attempt:\n// - lastRefreshSuccess: throttles 401-retries when the token is fresh\n// (don't pointlessly re-fetch a token we just got).\n// - lastRefreshFailure: shorter backoff so a transient upstream blip\n// doesn't suppress legitimate refresh attempts for a full 30s, but\n// still prevents a thundering-herd refresh-storm against an upstream\n// that's persistently failing.\nlet lastRefreshSuccess = 0\nlet lastRefreshFailure = 0\nconst REFRESH_SUCCESS_COOLDOWN_MS = 30_000\nconst REFRESH_FAILURE_COOLDOWN_MS = 5_000\n\nexport async function refreshCopilotToken(\n reason: \"interval\" | \"401-retry\",\n): Promise<void> {\n if (inflightRefresh) return inflightRefresh\n // Refresh-storm protection: if a recent refresh already completed,\n // decline new 401-retry attempts. Interval refreshes always proceed\n // (they're spaced by `refresh_in - 60s` which is well outside the\n // window). 401-retry attempts respect both cooldowns:\n // - skip if a refresh succeeded within the last 30s (token is fresh)\n // - skip if a refresh failed within the last 5s (back off briefly)\n if (reason === \"401-retry\") {\n const now = Date.now()\n if (now - lastRefreshSuccess < REFRESH_SUCCESS_COOLDOWN_MS) {\n consola.debug(\n `refreshCopilotToken(${reason}) skipped: prior success within ${REFRESH_SUCCESS_COOLDOWN_MS}ms`,\n )\n return\n }\n if (now - lastRefreshFailure < REFRESH_FAILURE_COOLDOWN_MS) {\n consola.debug(\n `refreshCopilotToken(${reason}) skipped: prior failure within ${REFRESH_FAILURE_COOLDOWN_MS}ms`,\n )\n return\n }\n }\n\n inflightRefresh = (async () => {\n consola.debug(`Refreshing Copilot token (reason=${reason})`)\n try {\n const { token } = await getCopilotToken()\n state.copilotToken = token\n lastRefreshSuccess = Date.now()\n consola.debug(\"Copilot token refreshed\")\n if (state.showToken) {\n consola.info(\"Refreshed Copilot token:\", token)\n }\n } catch (error) {\n lastRefreshFailure = Date.now()\n consola.error(\n `Failed to refresh Copilot token (reason=${reason}):`,\n error,\n )\n } finally {\n inflightRefresh = undefined\n }\n })()\n return inflightRefresh\n}\n\n/**\n * Try `request()`. If it returns a 401, refresh the Copilot token (subject\n * to the single-flight + refresh-storm-protection of `refreshCopilotToken`)\n * and retry once. After one retry, propagate whatever the second attempt\n * returned — the caller's existing 401-handling path is preserved.\n *\n * The `request` callback is responsible for capturing `state.copilotToken`\n * locally before any await; this helper does NOT re-build the request\n * itself, just re-invokes the callback after a refresh.\n */\nexport async function tryRefreshAndRetry(\n request: () => Promise<Response>,\n routePath: string,\n): Promise<Response> {\n const first = await request()\n if (first.status !== 401) return first\n\n consola.warn(\n `${routePath}: upstream returned 401, attempting one token refresh + retry`,\n )\n await refreshCopilotToken(\"401-retry\")\n // Re-invoke the request with the (possibly) new token in state.\n return request()\n}\n\ninterface SetupGitHubTokenOptions {\n force?: boolean\n}\n\nexport async function setupGitHubToken(\n options?: SetupGitHubTokenOptions,\n): Promise<void> {\n try {\n const githubToken = await readGithubToken()\n\n if (githubToken && !options?.force) {\n state.githubToken = githubToken\n if (state.showToken) {\n consola.info(\"GitHub token:\", githubToken)\n }\n await logUser()\n\n return\n }\n\n consola.info(\"Not logged in, getting new access token\")\n const response = await getDeviceCode()\n consola.debug(\"Device code response:\", response)\n\n consola.info(\n `Please enter the code \"${response.user_code}\" in ${response.verification_uri}`,\n )\n\n const token = await pollAccessToken(response)\n await writeGithubToken(token)\n state.githubToken = token\n\n if (state.showToken) {\n consola.info(\"GitHub token:\", token)\n }\n await logUser()\n } catch (error) {\n if (error instanceof HTTPError) {\n consola.error(\"Failed to get GitHub token:\", await error.response.json())\n throw error\n }\n\n consola.error(\"Failed to get GitHub token:\", error)\n throw error\n }\n}\n\nasync function logUser() {\n const user = await getGitHubUser()\n consola.info(`Logged in as ${user.login}`)\n}\n\n/**\n * Set up the SECOND, write-capable GitHub token used by the first-mate\n * agent-orchestration surface (`--agents`). Mirrors `setupGitHubToken`\n * but authenticates against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`) requesting `repo workflow read:org`, and\n * stores the result apart at `PATHS.GITHUB_AGENT_TOKEN_PATH`. The Copilot\n * App token (`state.githubToken`) is left completely untouched — this is\n * a distinct identity for a distinct capability.\n *\n * Long-lived (device-flow user token) → no refresh loop; a later 401 is\n * surfaced to the caller as a revoked grant to re-run the login. Called\n * once from `setupAndServe` when `state.agentsEnabled` is true.\n */\nexport async function setupGitHubAgentToken(\n options?: SetupGitHubTokenOptions,\n): Promise<void> {\n try {\n const existing = (await readGithubAgentToken().catch(() => \"\")).trim()\n\n if (existing && !options?.force) {\n state.githubAgentToken = existing\n if (state.showToken) {\n consola.info(\"GitHub agent token:\", existing)\n }\n await warnIfAgentScopesInsufficient()\n return\n }\n\n consola.info(\n \"Agent mode (--agents): a second GitHub login is required for a write-capable token (repo, workflow, read:org).\",\n )\n const response = await getDeviceCode({\n clientId: GITHUB_AGENT_CLIENT_ID,\n scope: GITHUB_AGENT_SCOPES,\n })\n consola.debug(\"Agent device code response:\", response)\n\n consola.info(\n `Please enter the code \"${response.user_code}\" in ${response.verification_uri} to authorize github-router's cloud-agent orchestration to act on your repositories.`,\n )\n\n const token = await pollAccessToken(response, GITHUB_AGENT_CLIENT_ID)\n await writeGithubAgentToken(token)\n state.githubAgentToken = token\n\n if (state.showToken) {\n consola.info(\"GitHub agent token:\", token)\n }\n await warnIfAgentScopesInsufficient()\n } catch (error) {\n if (error instanceof HTTPError) {\n consola.error(\n \"Failed to get GitHub agent token:\",\n await error.response.json(),\n )\n throw error\n }\n\n consola.error(\"Failed to get GitHub agent token:\", error)\n throw error\n }\n}\n\n/**\n * Best-effort check that the agent token actually carries the scopes we\n * asked for. The GitHub CLI OAuth client is a classic OAuth App, so the\n * granted scopes are echoed in the `x-oauth-scopes` response header on\n * any authenticated call. Warn loudly (not fatal) if `repo`/`workflow`\n * are missing so the failure is diagnosable at login rather than at the\n * first write 403.\n */\nasync function warnIfAgentScopesInsufficient(): Promise<void> {\n try {\n const res = await fetch(`${GITHUB_API_BASE_URL}/user`, {\n headers: githubAgentHeaders(state),\n })\n if (res.status === 401) {\n consola.warn(\n \"GitHub agent token was rejected (401) — the grant may have been revoked. Re-run with --agents to log in again.\",\n )\n return\n }\n const scopes = (res.headers.get(\"x-oauth-scopes\") ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n const missing = [\"repo\", \"workflow\"].filter((s) => !scopes.includes(s))\n if (missing.length > 0) {\n consola.warn(\n `GitHub agent token is missing scope(s): ${missing.join(\", \")}. `\n + \"The first-mate surface needs 'repo' + 'workflow' to create issues, \"\n + \"assign cloud agents, and dispatch workflows. Re-run the agent login \"\n + \"and grant the requested scopes.\",\n )\n }\n } catch (err) {\n consola.debug(\"Agent token scope check skipped:\", err)\n }\n}\n"],"mappings":";;;;;;;AAsHA,MAAa,QAAe;CAC1B,aAAa;CACb,eAAe;CACf,eAAe;CACf,WAAW;CACX,eAAe;CACf,eAAe;CACf,cAAc;CACd,eAAe;CACf,oBAAoB;CACpB,gBAAgB;CAChB,WAAW,WAAW;CACtB,WAAW,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;AAC3C;;;AC/HA,MAAa,yBAAyB;CACpC,gBAAgB;CAChB,QAAQ;AACV;AAEA,MAAM,0BAA0B;AAEhC,SAAgB,eAAe,OAAsB;CACnD,OAAO,MAAM,kBAAkB;AACjC;AAEA,MAAM,cAAc;AAEpB,MAAa,kBAAkB,UAC7B,MAAM,iBAAiB;AACzB,MAAa,kBACX,OACA,SAAkB,OAClB,gBAAwB,kBACrB;CACH,MAAM,UAAU,eAAe,KAAK;CACpC,MAAM,UAAkC;EACtC,eAAe,UAAU,MAAM;EAC/B,gBAAgB,gBAAgB,CAAC,CAAC;EAClC,0BAA0B;EAC1B,kBAAkB,UAAU,MAAM;EAClC,yBAAyB,gBAAgB;EACzC,cAAc,qBAAqB;E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,UAAU,CAAC,QAAQ,UAAU,CAAC,CAAC,QAAQ,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;EACtE,IAAI,QAAQ,SAAS,GACnB,QAAQ,KACN,2CAA2C,QAAQ,KAAK,IAAI,EAAE,yKAIhE;CAEJ,SAAS,KAAK;EACZ,QAAQ,MAAM,oCAAoC,GAAG;CACvD;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "github-router",
3
- "version": "0.3.269",
3
+ "version": "0.3.270",
4
4
  "license": "MIT",
5
5
  "description": "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.",
6
6
  "keywords": [
@@ -1,2 +0,0 @@
1
- import { b as runWorkerAgent } from "./peer-mcp-personas-DSbBlgFt.js";
2
- export { runWorkerAgent };