github-router 0.3.297 → 0.3.302

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 (100) hide show
  1. package/dist/{attribution-settings-B70GmZ68.js → attribution-settings-B1xutIts.js} +146 -10
  2. package/dist/attribution-settings-B1xutIts.js.map +1 -0
  3. package/dist/{auth-CluG5e-l.js → auth-CpjOjoUG.js} +4 -3
  4. package/dist/{auth-CluG5e-l.js.map → auth-CpjOjoUG.js.map} +1 -1
  5. package/dist/browser-ext/manifest.json +1 -1
  6. package/dist/{check-usage-iOzfnKJe.js → check-usage-BsN3S4Fu.js} +4 -4
  7. package/dist/{check-usage-iOzfnKJe.js.map → check-usage-BsN3S4Fu.js.map} +1 -1
  8. package/dist/{claude-DMMfvfns.js → claude-uRuzEH0W.js} +130 -78
  9. package/dist/claude-uRuzEH0W.js.map +1 -0
  10. package/dist/{codex-DVOyVv2B.js → codex-D5ag-liR.js} +6 -5
  11. package/dist/{codex-DVOyVv2B.js.map → codex-D5ag-liR.js.map} +1 -1
  12. package/dist/{debug-DsEwleGg.js → debug-BXRPyeqO.js} +2 -2
  13. package/dist/{debug-DsEwleGg.js.map → debug-BXRPyeqO.js.map} +1 -1
  14. package/dist/engine-2uMJ4Isk.js +2 -0
  15. package/dist/{gate-discovery-G6PAG61j.js → gate-discovery-BTRVyKWu.js} +5 -5
  16. package/dist/{gate-discovery-G6PAG61j.js.map → gate-discovery-BTRVyKWu.js.map} +1 -1
  17. package/dist/{get-copilot-usage-B7Z4XVWj.js → get-copilot-usage-ByjQqhdi.js} +3 -2
  18. package/dist/{get-copilot-usage-B7Z4XVWj.js.map → get-copilot-usage-ByjQqhdi.js.map} +1 -1
  19. package/dist/hooks.mjs +287 -5
  20. package/dist/hooks.sha256 +1 -1
  21. package/dist/{internal-artifact-open-D6tKMg8v.js → internal-artifact-open-DRSxShAW.js} +2 -2
  22. package/dist/{internal-artifact-open-D6tKMg8v.js.map → internal-artifact-open-DRSxShAW.js.map} +1 -1
  23. package/dist/{internal-fast-dispatch-guard-N-RaLrOn.js → internal-fast-dispatch-guard-CYOWbxjX.js} +1 -1
  24. package/dist/{internal-fast-dispatch-guard-Bkr_iGOu.js → internal-fast-dispatch-guard-D2HcfXZv.js} +2 -2
  25. package/dist/{internal-fast-dispatch-guard-Bkr_iGOu.js.map → internal-fast-dispatch-guard-D2HcfXZv.js.map} +1 -1
  26. package/dist/{internal-first-mate-guard-C9BV7J4U.js → internal-first-mate-guard-Bcb5JwiO.js} +3 -3
  27. package/dist/{internal-first-mate-guard-C9BV7J4U.js.map → internal-first-mate-guard-Bcb5JwiO.js.map} +1 -1
  28. package/dist/{internal-first-mate-guard-WJApyc8j.js → internal-first-mate-guard-Brh_uois.js} +1 -1
  29. package/dist/internal-max-dispatch-guard-Bcjavapx.js +2 -0
  30. package/dist/internal-max-dispatch-guard-BjSVXMvC.js +198 -0
  31. package/dist/internal-max-dispatch-guard-BjSVXMvC.js.map +1 -0
  32. package/dist/{internal-plan-review-t3PuNfuL.js → internal-plan-review-DVY-iV2x.js} +3 -3
  33. package/dist/{internal-plan-review-t3PuNfuL.js.map → internal-plan-review-DVY-iV2x.js.map} +1 -1
  34. package/dist/{internal-prompt-submit-C3KovHQG.js → internal-prompt-submit-BTqRn4FW.js} +4 -4
  35. package/dist/{internal-prompt-submit-C3KovHQG.js.map → internal-prompt-submit-BTqRn4FW.js.map} +1 -1
  36. package/dist/{internal-session-bind-d2uoja8I.js → internal-session-bind-YfH656lt.js} +2 -2
  37. package/dist/{internal-session-bind-d2uoja8I.js.map → internal-session-bind-YfH656lt.js.map} +1 -1
  38. package/dist/{internal-stop-hook-BjzrF1zd.js → internal-stop-hook-BZg__ab6.js} +5 -5
  39. package/dist/{internal-stop-hook-BjzrF1zd.js.map → internal-stop-hook-BZg__ab6.js.map} +1 -1
  40. package/dist/{internal-stop-review-YtDUGXpX.js → internal-stop-review-B8MmEyQ1.js} +2 -2
  41. package/dist/{internal-stop-review-YtDUGXpX.js.map → internal-stop-review-B8MmEyQ1.js.map} +1 -1
  42. package/dist/{internal-worker-guard-CdkeS9PN.js → internal-worker-guard-Dr6W83TC.js} +2 -2
  43. package/dist/{internal-worker-guard-CdkeS9PN.js.map → internal-worker-guard-Dr6W83TC.js.map} +1 -1
  44. package/dist/{internal-workspace-header-tuBXJV22.js → internal-workspace-header-Cep0WSIb.js} +2 -2
  45. package/dist/{internal-workspace-header-tuBXJV22.js.map → internal-workspace-header-Cep0WSIb.js.map} +1 -1
  46. package/dist/lifecycle-4TZrJuAa.js +2 -0
  47. package/dist/{lifecycle-CM9eTzvk.js → lifecycle-CmPJ6e_6.js} +2 -2
  48. package/dist/{lifecycle-CM9eTzvk.js.map → lifecycle-CmPJ6e_6.js.map} +1 -1
  49. package/dist/{lifecycle-Bg6doY3-.js → lifecycle-DgsJ_8Am.js} +2 -2
  50. package/dist/{lifecycle-Bg6doY3-.js.map → lifecycle-DgsJ_8Am.js.map} +1 -1
  51. package/dist/lifecycle-O91Vzzb-.js +2 -0
  52. package/dist/main.js +19 -18
  53. package/dist/main.js.map +1 -1
  54. package/dist/max-profile-contract-BTXowh6k.js +264 -0
  55. package/dist/max-profile-contract-BTXowh6k.js.map +1 -0
  56. package/dist/{mcp-workspace-header-dERl2YTT.js → mcp-workspace-header-NzFD0Wgd.js} +2 -2
  57. package/dist/{mcp-workspace-header-dERl2YTT.js.map → mcp-workspace-header-NzFD0Wgd.js.map} +1 -1
  58. package/dist/{models-DZ4hYsR7.js → models-1KwEUgzd.js} +3 -3
  59. package/dist/{models-DZ4hYsR7.js.map → models-1KwEUgzd.js.map} +1 -1
  60. package/dist/{orchestration-BiGCEwbH.js → orchestration-CYyp9w-t.js} +2 -2
  61. package/dist/{orchestration-BiGCEwbH.js.map → orchestration-CYyp9w-t.js.map} +1 -1
  62. package/dist/paths-DDAiPVto.js +2 -0
  63. package/dist/{paths-Ci485qSJ.js → paths-IcZW8gZx.js} +4 -4
  64. package/dist/{paths-Ci485qSJ.js.map → paths-IcZW8gZx.js.map} +1 -1
  65. package/dist/{peer-mcp-personas-ce6_YMnX.js → peer-mcp-personas-DwEiYeJS.js} +423 -186
  66. package/dist/peer-mcp-personas-DwEiYeJS.js.map +1 -0
  67. package/dist/{plan-review-hook-DuW0pSoM.js → plan-review-hook-szSNt6uU.js} +3 -3
  68. package/dist/{plan-review-hook-DuW0pSoM.js.map → plan-review-hook-szSNt6uU.js.map} +1 -1
  69. package/dist/{prompt-submit-hook-IMl7ssfr.js → prompt-submit-hook-ZUxo_jEl.js} +3 -3
  70. package/dist/{prompt-submit-hook-IMl7ssfr.js.map → prompt-submit-hook-ZUxo_jEl.js.map} +1 -1
  71. package/dist/{provision-BhCtm3md.js → provision-BLT1pCFy.js} +4 -4
  72. package/dist/{provision-BhCtm3md.js.map → provision-BLT1pCFy.js.map} +1 -1
  73. package/dist/{self-invocation-DAB_od0C.js → self-invocation-BJWbA8ka.js} +2 -2
  74. package/dist/{self-invocation-DAB_od0C.js.map → self-invocation-BJWbA8ka.js.map} +1 -1
  75. package/dist/{serve-Blj_dRSr.js → serve-wEZoOijw.js} +13 -12
  76. package/dist/{serve-Blj_dRSr.js.map → serve-wEZoOijw.js.map} +1 -1
  77. package/dist/{server-setup-DhG3YZPj.js → server-setup-Zn5wkosb.js} +213 -37
  78. package/dist/server-setup-Zn5wkosb.js.map +1 -0
  79. package/dist/{start-8QaqICtd.js → start-DSqU8d8h.js} +3 -3
  80. package/dist/{start-8QaqICtd.js.map → start-DSqU8d8h.js.map} +1 -1
  81. package/dist/state-B8adscCv.js +51 -0
  82. package/dist/state-B8adscCv.js.map +1 -0
  83. package/dist/{stop-gate-hook-DQnh_KfI.js → stop-gate-hook-CJOk28zd.js} +3 -3
  84. package/dist/{stop-gate-hook-DQnh_KfI.js.map → stop-gate-hook-CJOk28zd.js.map} +1 -1
  85. package/dist/{stop-gate-policy-DMr3KVmw.js → stop-gate-policy-zhzRIj6G.js} +2 -2
  86. package/dist/{stop-gate-policy-DMr3KVmw.js.map → stop-gate-policy-zhzRIj6G.js.map} +1 -1
  87. package/dist/{token-BtJhjXXu.js → token-CbuFyx-B.js} +4 -50
  88. package/dist/token-CbuFyx-B.js.map +1 -0
  89. package/dist/{worker-dispatch-BEHkTbnH.js → worker-dispatch-DgP5yT26.js} +2 -2
  90. package/dist/{worker-dispatch-BEHkTbnH.js.map → worker-dispatch-DgP5yT26.js.map} +1 -1
  91. package/package.json +1 -1
  92. package/dist/attribution-settings-B70GmZ68.js.map +0 -1
  93. package/dist/claude-DMMfvfns.js.map +0 -1
  94. package/dist/engine-BkGRuUNs.js +0 -2
  95. package/dist/lifecycle-CGLt1cJQ.js +0 -2
  96. package/dist/lifecycle-DoUwpVDB.js +0 -2
  97. package/dist/paths-GD7bgGGy.js +0 -2
  98. package/dist/peer-mcp-personas-ce6_YMnX.js.map +0 -1
  99. package/dist/server-setup-DhG3YZPj.js.map +0 -1
  100. package/dist/token-BtJhjXXu.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"token-BtJhjXXu.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\"\nimport type { LaunchProfileId } from \"./launch-profile\"\n\n/**\n * One authenticated `github-router claude` (or `serve`) launch's identity\n * and capability scope, keyed by `launchId` in `state.launchRegistry`.\n *\n * Replaces the earlier scalar `state.peerMcpNonce` assumption — a single\n * process-global nonce cannot express \"which profile is this caller\", so\n * a concurrent fast + standard launch (or a reconnect) had no way to keep\n * their identities from being interchangeable. Each entry carries BOTH\n * credentials a launch presents on the wire:\n *\n * - `nonce` — the `/mcp` bearer (Streamable HTTP `Authorization` header).\n * - `secret` — the `/v1/messages` identity-preflight bearer, deliberately\n * a SEPARATE credential from `nonce` so leaking one surface's token\n * (say, via a client log) does not also authenticate the other.\n *\n * `allowedGroups` / `allowedPersonas` are the narrowing declaration for\n * scoped MCP surfaces: `undefined` means UNRESTRICTED (the standard/BYO\n * launch shape today), and a concrete `ReadonlySet` is the fast profile's\n * hard allow-list. This module only stores and looks up the declaration;\n * enforcing it against `tools/list` / `tools/call` is the MCP route\n * handler's job.\n */\nexport interface LaunchRegistryEntry {\n /** Opaque per-launch id. Primary key into `state.launchRegistry`. */\n launchId: string\n /** `/mcp` Streamable HTTP bearer for this launch. */\n nonce: string\n /** `/v1/messages` identity-preflight bearer for this launch. */\n secret: string\n /** Which launch profile authenticated this entry. */\n profileId: LaunchProfileId\n /** Scoped MCP group allow-list. `undefined` = unrestricted. */\n allowedGroups?: ReadonlySet<string>\n /** Persona (peers-group) tool-name allow-list. `undefined` = unrestricted. */\n allowedPersonas?: ReadonlySet<string>\n createdAt: number\n}\n\n/**\n * Registry key backing the `state.peerMcpNonce` back-compat accessor\n * below. Not a real launch id (no `registerLaunch` caller ever produces\n * this string), so it can never collide with a genuine per-launch UUID.\n */\nconst DEFAULT_LAUNCH_ID = \"__default__\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n\n /**\n * Where `githubToken` came from, which decides whether the proxy may\n * re-read it from disk.\n *\n * `\"file\"` — read from `PATHS.GITHUB_TOKEN_PATH`. A re-read is allowed, so\n * an out-of-band `github-router auth` heals a running proxy without a\n * restart.\n *\n * `\"explicit\"` — supplied by the operator via `--github-token` / `GH_TOKEN`.\n * The file is NEVER read on this path: silently replacing a\n * caller-supplied credential with whatever happens to be on disk would\n * override an explicit instruction. It also means \"run `github-router\n * auth`\" is false advice for this source — the remediation is to replace\n * the supplied value.\n */\n githubTokenSource?: \"file\" | \"explicit\"\n\n /**\n * Monotonic counter bumped on every SUCCESSFUL Copilot token exchange.\n *\n * This is the retry criterion for `tryRefreshAndRetry`, and it is\n * deliberately not \"did the token string change\": two consecutive\n * successful exchanges were observed returning an identical token, so a\n * string comparison would silently suppress legitimate retries. Nor is it\n * the refresh's own verdict — with requests A and B both holding a stale\n * token, A can refresh while B's later 401 is cooled down to a no-op, and\n * a verdict of \"nothing happened\" would fail B even though a good token is\n * already in `copilotToken`. Comparing generations answers the question\n * each request actually has: \"is what is in state now different from what\n * I already tried?\"\n */\n copilotTokenGeneration: number\n\n /**\n * Wall-clock ms after which `copilotToken` should be refreshed — already\n * skew-adjusted, so the per-request check is a plain `Date.now() >=` compare.\n *\n * Derived from the exchange's `refresh_in` (a DURATION) and never from its\n * absolute `expires_at`. A local clock running ahead of GitHub's would make\n * an absolute timestamp look already-past on a brand-new token and drive a\n * refresh storm; a duration is immune, because it is anchored to the same\n * clock that later reads it.\n */\n copilotTokenRefreshAt?: number\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 * Keyed per-launch registry for the loopback `/mcp` endpoint AND the\n * `/v1/messages` identity preflight. Set by the `claude` subcommand\n * (via `registerLaunch` in `./launch-registry`) after `setupAndServe`\n * and before spawning Claude Code; removed by the launch's own\n * cleanup. When empty, `/mcp` rejects all requests — closes the\n * loopback-no-auth gap (DNS rebinding, malicious browser-ext native\n * messaging, sibling-process probe) exactly as the old scalar nonce\n * did when unset.\n *\n * Multiple entries coexist for concurrent fast/standard launches (or a\n * launch plus a reconnect); each is looked up by its OWN nonce/secret,\n * so two launches' authenticated identities never cross.\n */\n launchRegistry: Map<string, LaunchRegistryEntry>\n\n /**\n * @deprecated Back-compat accessor over the registry's DEFAULT_LAUNCH_ID\n * entry (profileId \"standard\", unrestricted `allowedGroups`/\n * `allowedPersonas`) — defined below via `Object.defineProperty`, not a\n * real stored field. Reading returns that entry's nonce; writing creates\n * or updates it (or deletes it on `undefined`). Exists so single-launch\n * call sites and tests that already do `state.peerMcpNonce = NONCE`\n * keep working unmodified while `checkAuth` and the identity preflight\n * consult the real keyed registry underneath. New code should call\n * `registerLaunch` / `findLaunchByNonce` / `findLaunchBySecret` from\n * `./launch-registry` directly instead of reading/writing this field.\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 copilotTokenGeneration: 0,\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 launchRegistry: new Map(),\n}\n\n// `peerMcpNonce` is not a plain data field — it's a live view onto\n// `state.launchRegistry.get(DEFAULT_LAUNCH_ID)`. Defined via\n// `Object.defineProperty` (rather than a class) so `state` stays the\n// plain object literal every existing importer already destructures /\n// mutates directly.\nObject.defineProperty(state, \"peerMcpNonce\", {\n enumerable: true,\n configurable: true,\n get(): string | undefined {\n return state.launchRegistry.get(DEFAULT_LAUNCH_ID)?.nonce\n },\n set(value: string | undefined) {\n if (value === undefined) {\n state.launchRegistry.delete(DEFAULT_LAUNCH_ID)\n return\n }\n const existing = state.launchRegistry.get(DEFAULT_LAUNCH_ID)\n state.launchRegistry.set(DEFAULT_LAUNCH_ID, {\n launchId: DEFAULT_LAUNCH_ID,\n nonce: value,\n // A caller that only ever touches `peerMcpNonce` exposes MCP only and has\n // no Messages identity secret.\n // Never reuse the MCP bearer across surfaces: an empty secret cannot match\n // any non-empty custom header, while registered Claude launches always use\n // `registerLaunch` with independently generated credentials.\n secret: existing?.secret ?? \"\",\n profileId: existing?.profileId ?? \"standard\",\n allowedGroups: existing?.allowedGroups,\n allowedPersonas: existing?.allowedPersonas,\n createdAt: existing?.createdAt ?? Date.now(),\n })\n },\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 // A dispatch that raced a pool teardown. Previously in NEITHER set, so it\n // fell through to \"non_transport\" and was rethrown raw at the retry loop —\n // an unclassified error escaping a classifier is a gap, not a policy.\n \"UND_ERR_CLOSED\",\n // HTTP/2 session death. These reached \"transient\" only incidentally, via the\n // outer TypeError(\"fetch failed\") message match, which means a future change\n // to that string would silently reclassify them. Name them.\n \"ERR_HTTP2_INVALID_SESSION\",\n \"ERR_HTTP2_GOAWAY_SESSION\",\n \"ERR_HTTP2_STREAM_CANCEL\",\n])\n\n/**\n * TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,\n * or a certificate this client cannot validate. Retrying any of these buys\n * three times the latency before the identical failure.\n *\n * Deliberately NOT the blanket `\"ssl routines\"` match this replaces. Every\n * OpenSSL error carries that string, so the catch-all also swallowed alert 20\n * (`bad record mac`) — an integrity fault a fresh connection routinely clears.\n * See TRANSIENT_TLS_MESSAGES.\n *\n * Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order\n * in `classifyTransportError` checks the narrower transient alert first, so an\n * overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that\n * no error matches two buckets.\n */\nconst DETERMINISTIC_TLS_MESSAGES = [\n \"self signed certificate\",\n \"certificate has expired\",\n \"unable to verify the first certificate\",\n \"unable to get local issuer certificate\",\n \"hostname/ip does not match certificate\",\n \"certificate verify failed\",\n \"unknown ca\",\n \"wrong version number\",\n \"unsupported protocol\",\n \"no protocols available\",\n \"alert handshake failure\",\n \"alert protocol version\",\n \"alert insufficient security\",\n \"tls handshake\",\n]\n\n/**\n * TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication\n * somewhere on the path. The connection is unusable, but the next one is\n * typically fine, which is exactly what a bounded retry is for.\n *\n * This also matches OpenSSL's local-detection wording (\"decryption failed or\n * bad record mac\", reason 281) as well as the received-alert wording (\"ssl/tls\n * alert bad record mac\", reason 1020). Both are integrity faults and both\n * warrant the same one-bounded-replay policy.\n *\n * An earlier revision promoted four alert phrases; three were wrong and stay\n * deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,\n * alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22\n * (`record overflow`) is a malformed or desynchronised stream. Promoting those\n * converts fail-fast configuration errors into 3x latency.\n */\nconst TRANSIENT_TLS_MESSAGES = [\"bad record mac\"]\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 *\n * Buckets are evaluated in a stated total order, narrowest first, and the first\n * match wins — so no error can land in two of them:\n *\n * 1. caller cancel\n * 2. TLS alert 20 (`bad record mac`) — integrity, retryable\n * 3. deterministic cert/config codes and messages, plus refused/DNS-miss\n * 4. transient codes (incl. HTTP/2 session death) and generic transport text\n * 5. everything else — `non_transport`, rethrown raw\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 // Narrowest match first: TLS alert 20 is an integrity fault, not a\n // configuration fault, and it must not be swallowed by the broader cert /\n // protocol patterns below (which is exactly what the old blanket\n // `\"ssl routines\"` match did — it failed the alert after ONE attempt).\n if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase))\n // Catch-all for every OTHER OpenSSL failure. Safe here, and only here,\n // because the one retryable alert already returned above — so this keeps\n // fail-fast for the long tail (`tlsv13 alert certificate required`,\n // `sslv3 alert bad certificate`, `tlsv1 alert internal error`, …) without\n // re-swallowing alert 20.\n //\n // Without it those errors fall through to the generic transient branch via\n // the outer `TypeError: fetch failed`, turning a permanent configuration\n // failure into three attempts. Narrowing the deterministic list alone was\n // not sufficient; the residue has to land somewhere deliberate.\n || messages.includes(\"ssl routines\")\n // A refused connection or a DNS miss is a configuration signal, so it\n // fails fast rather than being hammered. Kept deliberately, not inherited:\n // transient DNS is already covered by EAI_AGAIN, and a genuinely\n // restarting upstream surfaces as ECONNRESET or a 5xx, both of which do\n // retry.\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 // 502 / api_error, NOT 503 / overloaded_error.\n //\n // We already exhausted our own retries against a transport that failed,\n // so \"I am busy, retry later\" is both inaccurate and expensive:\n // `overloaded_error` is the type Claude Code retries hardest against,\n // and each client retry costs another full round of upstream attempts.\n // On a session near the 1M-token context limit that re-uploads a\n // multi-megabyte body every time, which is what turned a fast failure\n // into multi-minute stalls when this mapping shipped.\n //\n // Trade-off, deliberate: the client now surfaces the error instead of\n // papering over a genuinely recoverable blip. That is the behaviour\n // operators had before the mapping was introduced.\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"api_error\",\n message: `Upstream transport was interrupted at ${target} after ${error.attempts} attempts. ${diagnostic}`,\n },\n },\n 502,\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 an upstream context-overflow rejection onto Claude Code's gateway\n // capability-rejection contract, so the client runs its own recovery\n // (reactive compaction + retry) instead of stranding the session.\n //\n // This is the whole reason a long session used to brick: Copilot rejects\n // with \"Your input exceeds the context window of this model\" on a 400, and\n // the client's classifier only consults its \"context window\" test on a\n // 413 — so that 400 matched no class, produced no canonical error, and no\n // compaction was ever triggered. `/compact` then re-sent the same\n // oversized request and failed identically.\n const overflowClass = classifyOverflow(\n error.response.status,\n errorJson,\n errorText,\n )\n if (overflowClass) {\n const upstream = resolveErrorMessage(errorJson, errorText)\n consola.error(\n `HTTP error (mapped to ${overflowClass}):`,\n errorJson ?? errorText,\n )\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"invalid_request_error\",\n message: buildCapabilityRejectedMessage(overflowClass, 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 // Copilot's exact wording. Load-bearing: Claude Code's own classifier only\n // consults its \"context window\" test on a 413, so this phrasing on a 400\n // classifies as NOTHING there and the session strands instead of compacting.\n \"exceeds the context window\",\n]\n\n/** Upstream wording for the `max_tokens_context_overflow` class: the prompt\n * itself fits, but prompt + requested `max_tokens` does not. A different\n * client recovery (lower `max_tokens`) than dropping history, so it must not\n * be collapsed into `prompt_too_long`. */\nconst MAX_TOKENS_OVERFLOW_SUBSTRING =\n \"input length and `max_tokens` exceed context limit\"\n\n/**\n * Prefix of Claude Code's gateway capability-rejection contract.\n *\n * A gateway that replaces an upstream 400/413 body hides the wording the\n * client recovers from, so the client accepts a stable token in its place:\n * `capability_rejected: <class>`. Verified in the installed 2.1.247 bundle —\n * `IZ(e) = JBn(e.message) || wd(e.message, \"prompt_too_long\")`, i.e. the\n * ORIGINAL WORDING or the TOKEN, either one. We emit both: the token is the\n * documented contract, the wording is the older independently-matched path,\n * and neither costs anything. `wd` boundary-checks the character after the\n * class, so whatever follows the token must not match `[A-Za-z0-9_:.-]`.\n */\nconst CAPABILITY_REJECTED_PREFIX = \"capability_rejected: \"\n\n/**\n * Build the `error.message` for a classified overflow.\n *\n * A space after the class satisfies the client's right-boundary check; the\n * human-readable tail preserves the upstream detail for a user reading the\n * transcript, and independently satisfies the wording matcher.\n */\nexport function buildCapabilityRejectedMessage(\n overflowClass: \"prompt_too_long\" | \"max_tokens_context_overflow\",\n upstream: string,\n): string {\n const wording =\n overflowClass === \"prompt_too_long\"\n ? \"prompt is too long\"\n : MAX_TOKENS_OVERFLOW_SUBSTRING\n return `${CAPABILITY_REJECTED_PREFIX}${overflowClass} (${wording}: ${upstream})`\n}\n\n/**\n * Which overflow class an upstream rejection belongs to, or undefined when it\n * is not an overflow at all.\n *\n * The `max_tokens` variant is tested FIRST and independently of\n * `isContextOverflow`: it names a different client recovery (lower\n * `max_tokens`, keep the history) than dropping history, so collapsing it into\n * `prompt_too_long` would trigger the wrong one.\n */\nexport function classifyOverflow(\n status: number,\n errorJson: unknown,\n errorText: string,\n): \"prompt_too_long\" | \"max_tokens_context_overflow\" | undefined {\n if (status !== 400 && status !== 413) return undefined\n if (overflowHaystack(errorJson, errorText).includes(MAX_TOKENS_OVERFLOW_SUBSTRING)) {\n return \"max_tokens_context_overflow\"\n }\n return isContextOverflow(status, errorJson, errorText)\n ? \"prompt_too_long\"\n : undefined\n}\n\nfunction overflowHaystack(errorJson: unknown, errorText: string): string {\n return (\n errorText +\n \" \" +\n (typeof errorJson === \"object\" && errorJson !== null\n ? JSON.stringify(errorJson)\n : \"\")\n ).toLowerCase()\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 = overflowHaystack(errorJson, errorText)\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\"\nimport { createHash } from \"node:crypto\"\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\n/**\n * Short, non-reversible identifier for a credential, safe to log.\n *\n * During the 2026-08-08 incident the logs could not answer the one question\n * that mattered: was the process holding a stale credential, or was the\n * credential on disk itself dead? The operator re-authenticated at 13:53 and\n * the proxy kept failing, and nothing recorded whether those were the same\n * secret. A truncated SHA-256 makes two credentials comparable across log\n * lines without ever printing one. 8 hex chars is ample to distinguish the\n * handful of credentials a machine sees, and far too short to attack.\n */\nexport function credentialFingerprint(token: string | undefined): string {\n if (!token) return \"none\"\n return createHash(\"sha256\").update(token).digest(\"hex\").slice(0, 8)\n}\n\n/** How a failed token exchange should be treated. */\nexport type TokenExchangeFailureKind =\n /** The credential itself was rejected. Only a human can fix this. */\n | \"credential_rejected\"\n /** The entitlement lapsed; the credential is fine. Different remedy. */\n | \"entitlement_lapsed\"\n /** Anything else — rate limits, 5xx, transport. Retrying may work. */\n | \"transient\"\n\n/**\n * A failed `/copilot_internal/v2/token` exchange, carrying enough to diagnose\n * it after the fact.\n *\n * The predecessor threw `HTTPError(\"Failed to get Copilot token\", response)`\n * and every catch logged only `.message`, so status and body were dropped —\n * which is why the incident is unattributable.\n */\nexport class CopilotTokenExchangeError extends HTTPError {\n readonly kind: TokenExchangeFailureKind\n readonly status: number\n /** Fingerprint of the credential that was rejected, never the credential. */\n readonly credential: string\n\n constructor(opts: {\n kind: TokenExchangeFailureKind\n status: number\n credential: string\n detail: string\n response: Response\n }) {\n super(\n `Failed to get Copilot token: HTTP ${opts.status} (${opts.kind}, credential ${opts.credential})${\n opts.detail ? ` — ${opts.detail}` : \"\"\n }`,\n opts.response,\n )\n this.kind = opts.kind\n this.status = opts.status\n this.credential = opts.credential\n }\n}\n\n/** Upper bound on how much of an error body we quote into a log line. */\nconst ERROR_BODY_SNIPPET_CHARS = 300\n\n/**\n * `notification_id` values that mean \"the credential is valid but the\n * entitlement is not\". These need a different remedy than a bad credential:\n * telling someone whose subscription lapsed to re-authenticate sends them\n * around a loop that cannot help.\n */\nconst ENTITLEMENT_NOTIFICATIONS = new Set([\n \"access_revoked\",\n \"subscription_ended\",\n \"no_copilot_access\",\n])\n\n/**\n * Classify a non-OK exchange response.\n *\n * Deliberately asymmetric: only a 401, or a 403 that NAMES an entitlement\n * problem, is treated as terminal. A bare 403 stays transient because GitHub\n * returns 403 for primary rate limits (`x-ratelimit-remaining: 0`) and\n * secondary abuse limits — telling a user with a perfectly good credential to\n * re-authenticate because they were briefly rate-limited would be a worse\n * failure than the one being fixed. The costs are not symmetric: calling a\n * terminal failure transient wastes some retries, while calling a transient\n * failure terminal kills a working session.\n */\nfunction classifyExchangeFailure(\n status: number,\n body: string,\n): TokenExchangeFailureKind {\n if (status === 401) return \"credential_rejected\"\n if (status === 403) {\n let notificationId: unknown\n try {\n const parsed = JSON.parse(body) as Record<string, unknown>\n notificationId =\n parsed.notification_id\n ?? (parsed.error as Record<string, unknown> | undefined)?.notification_id\n } catch {\n // Not JSON: a rate-limit body, an HTML error page. Transient.\n }\n if (\n typeof notificationId === \"string\"\n && ENTITLEMENT_NOTIFICATIONS.has(notificationId)\n ) {\n return \"entitlement_lapsed\"\n }\n }\n return \"transient\"\n}\n\n/**\n * Exchange the GitHub credential for a short-lived Copilot token.\n *\n * `credentialOverride` lets a caller try a candidate credential WITHOUT\n * publishing it to the process-global `state` first. That matters because\n * `state` is shared by every concurrent request: installing an unvalidated\n * credential globally, even briefly, would make unrelated in-flight requests\n * send it and 401 while a perfectly good credential was still in hand.\n */\nexport const getCopilotToken = async (credentialOverride?: string) => {\n const credentialInUse = credentialOverride ?? state.githubToken\n const credential = credentialFingerprint(credentialInUse)\n // A shallow view over the real state: everything else (editor version,\n // plugin version) still comes from the live object, only the credential is\n // substituted, and nothing is mutated.\n const authState =\n credentialOverride === undefined\n ? state\n : { ...state, githubToken: credentialOverride }\n\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(authState),\n }),\n { label: \"/copilot_internal/v2/token\" },\n )\n\n if (!response.ok) {\n // Read the body BEFORE throwing. The predecessor discarded it, so every\n // occurrence of this failure was unattributable after the fact.\n //\n // Read the ORIGINAL rather than a clone: a clone leaves the original body\n // unconsumed, and since the only consumer downstream is a `.message` log,\n // that stream — and its socket — would stay pinned open. The body we need\n // is captured into `detail` here, so nothing downstream has to re-read it.\n let body: string\n try {\n body = await response.text()\n } catch {\n body = \"(could not read error body)\"\n }\n const kind = classifyExchangeFailure(response.status, body)\n throw new CopilotTokenExchangeError({\n kind,\n status: response.status,\n credential,\n detail: body.slice(0, ERROR_BODY_SNIPPET_CHARS).replaceAll(/\\s+/g, \" \").trim(),\n // The original body is now consumed, so hand the error a fresh Response\n // carrying the same bytes. `HTTPError.response` stays readable for any\n // future consumer, without leaving an unconsumed stream behind.\n response: new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n })\n }\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 * Prices for `batch_size` tokens, scaled by 1e9. Present on the live\n * catalog even where `is_premium` / `multiplier` are absent\n * (usage-based-billing accounts populate this instead), which is why both\n * shapes are modelled: reading only the premium pair silently yields\n * nothing on those accounts.\n */\n token_prices?: {\n input_price?: number\n output_price?: number\n cache_price?: number\n cache_read_price?: number\n cache_write_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) or on a base slug that natively advertises a\n // >=1M window (how opus-4.8, opus-5 and sonnet-5 all ship), perfect —\n // the upstream call routes to the 1M backend and Claude Code's local\n // accounting was right. Otherwise — a non-enterprise tier carrying\n // only the 200K opus variant, or a genuinely 200K model such as\n // claude-haiku-4.5 — warn and return the 200K resolution so the\n // request still succeeds, at the cost of Claude Code over-accounting\n // context against the proxy (it will compact early because it thinks\n // the window is 1M). The decorators upstream of this are all\n // catalog-gated, so reaching that branch means the catalog changed\n // under a running process or the slug was pinned by hand.\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 {\n CopilotTokenExchangeError,\n credentialFingerprint,\n getCopilotToken,\n} 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 * Transient filesystem errors from a read that raced the temp+rename write.\n *\n * On Windows a read landing in that window fails with one of these even\n * though a perfectly good file exists microseconds later. Treating one as\n * fatal at startup would cost a launch for no reason.\n */\nconst TRANSIENT_READ_CODES = new Set([\"EPERM\", \"EBUSY\", \"EACCES\", \"ENOENT\"])\n\nfunction isTransientReadError(err: unknown): boolean {\n const code = (err as NodeJS.ErrnoException | undefined)?.code\n return typeof code === \"string\" && TRANSIENT_READ_CODES.has(code)\n}\n\n/**\n * Read the credential file, retrying briefly through a racing rename.\n *\n * Same delays and the same reasoning as {@link RENAME_RETRY_DELAYS_MS} on the\n * write side: the contending handle closes almost immediately, so a short\n * bounded retry converts a spurious launch failure into a non-event. A\n * persistent failure still propagates — the caller must not believe a\n * credential was read when it was not.\n */\nasync function readGithubTokenWithRetry(): Promise<string> {\n let lastErr: unknown\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) {\n try {\n return await readGithubToken()\n } catch (err) {\n lastErr = err\n if (!isTransientReadError(err)) throw err\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 throw lastErr\n}\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 * Safety margin subtracted from the derived refresh deadline, so a request\n * arriving just before expiry refreshes rather than racing it.\n */\nconst REFRESH_SKEW_MS = 120_000\n\n/**\n * Bounds on a `refresh_in` we are willing to turn into a timer delay. An\n * absurd or missing upstream value must not produce a zero-length timer (a\n * hot loop hammering GitHub) or an effectively infinite one (a token that is\n * never refreshed). 60s floor, 6h ceiling, 1500s default — the value GitHub\n * actually returns today.\n */\nconst MIN_REFRESH_IN_S = 60\nconst MAX_REFRESH_IN_S = 6 * 60 * 60\nconst DEFAULT_REFRESH_IN_S = 1500\n\n/** Backoff schedule after a failed refresh, then hold at the last value. */\nconst REFRESH_BACKOFF_MS = [5_000, 15_000, 60_000, 300_000] as const\n\nfunction clampRefreshIn(refreshIn: unknown): number {\n if (typeof refreshIn !== \"number\" || !Number.isFinite(refreshIn)) {\n return DEFAULT_REFRESH_IN_S\n }\n return Math.min(Math.max(refreshIn, MIN_REFRESH_IN_S), MAX_REFRESH_IN_S)\n}\n\n/**\n * Adopt an exchange result into `state`.\n *\n * The generation bump is what lets an in-flight request know a newer token\n * exists (see `State.copilotTokenGeneration`), so it happens on EVERY success\n * — including one that returns a byte-identical token, which upstream\n * demonstrably does.\n */\n/**\n * Floor on how far ahead the derived refresh deadline may be placed.\n *\n * The deadline is `now + refresh_in - skew`, and the skew (120s) is larger\n * than the `refresh_in` floor (60s) — so a short upstream `refresh_in` would\n * put the deadline in the PAST, the scheduler would floor its delay to 1s,\n * and the proxy would hammer the token endpoint at 1 Hz forever. The deadline\n * must always be in the future, whatever upstream says.\n */\nconst MIN_REFRESH_LEAD_MS = 30_000\n\nfunction commitCopilotToken(token: string, refreshIn: unknown): void {\n state.copilotToken = token\n state.copilotTokenGeneration += 1\n // Derived from the DURATION, never the absolute `expires_at`: a clock\n // running ahead of GitHub's would make an absolute deadline look\n // already-past on a brand-new token and drive a refresh storm.\n const lead = Math.max(\n clampRefreshIn(refreshIn) * 1000 - REFRESH_SKEW_MS,\n MIN_REFRESH_LEAD_MS,\n )\n state.copilotTokenRefreshAt = Date.now() + lead\n}\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 timer\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 timer 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 *\n * The schedule is a SELF-RE-ARMING `setTimeout`, not a fixed `setInterval`.\n * Three reasons: the delay tracks each response's own `refresh_in` instead of\n * the one captured at startup; a failure can back off (5s → 15s → 60s → 300s)\n * instead of waiting a full period during which the token is already dead;\n * and one timer cannot disagree with itself the way a period timer plus a\n * separate retry timer can.\n */\nexport const setupCopilotToken = async (): Promise<StopCopilotTokenRefresh> => {\n const { token, refresh_in } = await getCopilotToken()\n commitCopilotToken(token, refresh_in)\n\n consola.debug(\n `GitHub Copilot Token fetched successfully! (credential ${credentialFingerprint(state.githubToken)})`,\n )\n if (state.showToken) {\n consola.info(\"Copilot token:\", token)\n }\n\n let handle: ReturnType<typeof setTimeout> | undefined\n let disposed = false\n let failures = 0\n\n const arm = (delayMs: number) => {\n // Checked here rather than only at the call sites because every caller\n // reaches this after an `await`, and disposal can land in that window.\n if (disposed) return\n handle = setTimeout(() => {\n void tick()\n }, delayMs)\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\n const tick = async () => {\n const outcome = await refreshCopilotToken(\"interval\")\n // The disposer may have run while the exchange was in flight. Re-arming\n // now would resurrect the loop after it was explicitly stopped — the\n // classic leaked-timer-after-dispose bug.\n if (disposed) return\n if (outcome === \"refreshed\") {\n failures = 0\n arm(nextDelayFromState())\n return\n }\n // Any non-success (including a skipped no-op) backs off rather than\n // spinning: the token is dead or dying and hammering will not help.\n const delay =\n REFRESH_BACKOFF_MS[Math.min(failures, REFRESH_BACKOFF_MS.length - 1)]\n failures += 1\n arm(delay)\n }\n\n arm(nextDelayFromState())\n\n return () => {\n if (disposed) return\n disposed = true\n if (handle) clearTimeout(handle)\n }\n}\n\n/**\n * Delay until the next scheduled refresh, from the deadline already stored on\n * `state`. Floored at 1s so a pathological deadline can never busy-loop.\n */\nfunction nextDelayFromState(): number {\n const deadline = state.copilotTokenRefreshAt\n if (deadline === undefined) return DEFAULT_REFRESH_IN_S * 1000\n return Math.max(deadline - Date.now(), 1000)\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<RefreshOutcome> | 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\n/**\n * Clear the refresh cooldowns. TEST-ONLY.\n *\n * The cooldowns are module state that outlives any one test, so without a\n * reset a test's refresh silently suppresses the next test's. The alternative\n * — stubbing `Date.now` far into the future — leaks into every other test\n * sharing the process (it broke the cooldown assertions in `token.test.ts`),\n * so an explicit reset is both narrower and honest about what it touches.\n */\nexport function __resetRefreshCooldownsForTests(): void {\n lastRefreshSuccess = 0\n lastRefreshFailure = 0\n}\n\n/**\n * What a refresh attempt did. Used for LOGGING and classification only —\n * never to decide whether a request should retry. That decision belongs to\n * the generation counter (see {@link tryRefreshAndRetry}), because a \"skipped\"\n * outcome for one request can coincide with another request having just\n * installed a perfectly good token.\n */\nexport type RefreshOutcome =\n | \"refreshed\"\n | \"skipped\"\n | \"credential_rejected\"\n | \"entitlement_lapsed\"\n | \"transient_failure\"\n\n/**\n * Read the credential from disk, returning it only if it is usable.\n *\n * Every failure mode here resolves to `undefined` (meaning \"keep using what\n * is in memory\") rather than throwing or returning a partial value. The file\n * is replaced by temp+rename (`writeTokenFileAtomic`), and on Windows a read\n * racing that rename fails with EPERM/EBUSY/EACCES/ENOENT. None of those mean\n * the in-memory credential went bad, so none of them may clear it — and a\n * filesystem error must never escape into the refresh loop and kill the timer.\n */\nasync function readGithubTokenIfUsable(): Promise<string | undefined> {\n if (state.githubTokenSource === \"explicit\") return undefined\n try {\n const raw = await readGithubToken()\n const trimmed = raw.trim()\n // A zero-length read is what a torn/partial write looks like. Adopting it\n // would replace a working credential with nothing.\n return trimmed.length > 0 ? trimmed : undefined\n } catch (err) {\n consola.debug(\"Could not re-read GitHub credential from disk:\", err)\n return undefined\n }\n}\n\n/**\n * Perform one exchange, preferring a newer credential from disk if there is one.\n *\n * The disk token is a CANDIDATE: it is passed to the exchange directly and\n * published to `state.githubToken` only after that exchange succeeds. It is\n * never installed globally on spec — `state` is shared by every concurrent\n * request, so an unvalidated credential visible there would be sent by\n * unrelated in-flight requests and 401 them while a working credential was\n * still in hand.\n */\nasync function exchangeWithFreshestCredential(): Promise<{\n token: string\n refresh_in: number\n}> {\n const onDisk = await readGithubTokenIfUsable()\n const inMemory = state.githubToken\n\n if (onDisk && onDisk !== inMemory) {\n consola.info(\n `GitHub credential on disk differs from the one in memory `\n + `(${credentialFingerprint(inMemory)} → ${credentialFingerprint(onDisk)}); trying it.`,\n )\n // Try the candidate WITHOUT publishing it. On success it becomes the\n // credential of record; on failure nothing was ever exposed to roll back.\n const result = await getCopilotToken(onDisk)\n state.githubToken = onDisk\n state.githubTokenSource = \"file\"\n return result\n }\n\n return getCopilotToken()\n}\n\nexport async function refreshCopilotToken(\n reason: \"interval\" | \"401-retry\" | \"expiry\",\n): Promise<RefreshOutcome> {\n // Single-flight: this check and the assignment below MUST NOT be separated\n // by an await. Anything awaited in between yields the event loop, letting a\n // second caller pass this guard before the first has published its promise\n // — which would launch overlapping exchanges against GitHub, exactly the\n // storm the mutex exists to prevent. The cooldown check needs to read the\n // credential from disk, so it lives INSIDE the body below rather than here.\n if (inflightRefresh) return inflightRefresh\n\n const run = async (): Promise<RefreshOutcome> => {\n // The `finally` that clears `inflightRefresh` must cover EVERY exit from\n // this body, including the early cooldown returns below. If a `return`\n // escaped it, the stale promise would stay published and every later\n // refresh would short-circuit to it forever — a permanently wedged\n // refresh loop, which is worse than the bug being fixed.\n try {\n // Refresh-storm protection: if a recent refresh already completed,\n // decline new reactive attempts. Interval refreshes always proceed\n // (they're spaced by the derived deadline, well outside the window).\n // Reactive 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 //\n // A cooldown skip is NOT the same as \"your request should give up\": the\n // caller re-checks the generation counter and will still retry if some\n // other caller refreshed. See `tryRefreshAndRetry`.\n if (reason === \"401-retry\" || reason === \"expiry\") {\n const now = Date.now()\n // A credential newer than the one we last tried is new information,\n // not a repeat attempt, so it bypasses both cooldowns. Without this,\n // the window right after `github-router auth` — exactly the recovery\n // path — would be swallowed by the 30s success cooldown.\n const onDisk = await readGithubTokenIfUsable()\n const hasNewerCredential = Boolean(\n onDisk && onDisk !== state.githubToken,\n )\n\n if (!hasNewerCredential) {\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 \"skipped\"\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 \"skipped\"\n }\n }\n }\n\n consola.debug(`Refreshing Copilot token (reason=${reason})`)\n try {\n const { token, refresh_in } = await exchangeWithFreshestCredential()\n commitCopilotToken(token, refresh_in)\n lastRefreshSuccess = Date.now()\n consola.debug(\n `Copilot token refreshed (credential ${credentialFingerprint(state.githubToken)}, generation ${state.copilotTokenGeneration})`,\n )\n if (state.showToken) {\n consola.info(\"Refreshed Copilot token:\", token)\n }\n return \"refreshed\"\n } catch (error) {\n lastRefreshFailure = Date.now()\n // Log the STATUS and body, not just the message. Their absence is why\n // the 2026-08-08 incident could not be attributed after the fact.\n consola.error(\n `Failed to refresh Copilot token (reason=${reason}):`,\n error instanceof Error ? error.message : error,\n )\n if (error instanceof CopilotTokenExchangeError) {\n if (error.kind === \"credential_rejected\") return \"credential_rejected\"\n if (error.kind === \"entitlement_lapsed\") return \"entitlement_lapsed\"\n }\n return \"transient_failure\"\n }\n } finally {\n // Only release the lock if it is still OURS. An unconditional clear\n // would let a finished attempt release a lock a newer attempt holds,\n // re-opening the overlapping-exchange window this mutex exists to\n // close. Identity-checking makes that safe no matter how the code\n // around it is later rearranged. `attempt` is assigned before any\n // await inside `run()` can settle, so it is always bound here.\n if (inflightRefresh === attempt) inflightRefresh = undefined\n }\n }\n\n const attempt = run()\n inflightRefresh = attempt\n return attempt\n}\n\n/**\n * Refresh the Copilot token if its derived deadline has passed.\n *\n * Called on EVERY request. The common path is one `Date.now()` and one\n * integer compare — no I/O — against an upstream call that costs hundreds of\n * milliseconds, so the overhead is not measurable. Sampling (every Nth\n * request) was considered and rejected: a session that idles and then resumes\n * may issue only a handful of requests, so a sampled guard would fail to fire\n * in precisely the scenario it exists for. Actual refreshes do not get more\n * frequent, because `refreshCopilotToken` is single-flighted and the deadline\n * moves forward on success.\n */\nexport async function ensureFreshCopilotToken(): Promise<void> {\n const deadline = state.copilotTokenRefreshAt\n if (deadline === undefined || Date.now() < deadline) return\n await refreshCopilotToken(\"expiry\")\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 — but ONLY if the token actually moved on.\n *\n * The retry criterion is the generation counter, not the refresh's verdict\n * and not a token-string comparison. Both alternatives are wrong:\n *\n * - By verdict: requests A and B both hold token T0 and both 401. A\n * refreshes to T1. B's refresh call lands inside the 30s success cooldown\n * and reports \"skipped\", so a verdict-based rule would give up and fail B\n * with a 503 — even though T1 is sitting in state and would have worked.\n * - By string: upstream demonstrably returns a byte-identical token from\n * two consecutive successful exchanges, so an unchanged string does not\n * mean an unchanged credential state.\n *\n * Comparing generations answers the question the request actually has: is\n * what is in state now different from what I already tried? When it is not,\n * we skip a re-send that is guaranteed to 401 again.\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 await ensureFreshCopilotToken()\n\n const generationBefore = state.copilotTokenGeneration\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\n if (state.copilotTokenGeneration === generationBefore) {\n // Nothing new to try. Re-sending the same credential would buy a second\n // guaranteed 401 — which is what every request during the 2026-08-08\n // outage paid, for an hour.\n consola.debug(\n `${routePath}: no newer Copilot token available (generation ${generationBefore}); not retrying`,\n )\n return first\n }\n\n // Re-invoke the request with the 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 // Retrying: a startup read can race an `auth` rewrite in another\n // terminal, and on Windows that surfaces as a transient EPERM/EBUSY/\n // ENOENT. Failing launch over a window that closes in milliseconds\n // would be a self-inflicted outage.\n const githubToken = await readGithubTokenWithRetry()\n\n if (githubToken && !options?.force) {\n state.githubToken = githubToken\n state.githubTokenSource = \"file\"\n if (state.showToken) {\n consola.info(\"GitHub token:\", githubToken)\n }\n await logUser()\n\n return\n }\n\n consola.info(\n options?.force\n ? \"Re-authenticating, getting new access token\"\n : \"Not logged in, getting new access token\",\n )\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 state.githubTokenSource = \"file\"\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":";;;;;;;;;;;;AAgDA,MAAM,oBAAoB;AAoL1B,MAAa,QAAe;CAC1B,aAAa;CACb,wBAAwB;CACxB,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;CACzC,gCAAgB,IAAI,IAAI;AAC1B;AAOA,OAAO,eAAe,OAAO,gBAAgB;CAC3C,YAAY;CACZ,cAAc;CACd,MAA0B;EACxB,OAAO,MAAM,eAAe,IAAI,iBAAiB,CAAC,EAAE;CACtD;CACA,IAAI,OAA2B;EAC7B,IAAI,UAAU,KAAA,GAAW;GACvB,MAAM,eAAe,OAAO,iBAAiB;GAC7C;EACF;EACA,MAAM,WAAW,MAAM,eAAe,IAAI,iBAAiB;EAC3D,MAAM,eAAe,IAAI,mBAAmB;GAC1C,UAAU;GACV,OAAO;GAMP,QAAQ,UAAU,UAAU;GAC5B,WAAW,UAAU,aAAa;GAClC,eAAe,UAAU;GACzB,iBAAiB,UAAU;GAC3B,WAAW,UAAU,aAAa,KAAK,IAAI;EAC7C,CAAC;CACH;AACF,CAAC;;;ACjRD,MAAa,yBAAyB;CACpC,gBAAgB;CAChB,QAAQ;AACV;AAEA,MAAM,0BAA0B;AAEhC,S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