github-router 0.3.263 → 0.3.270
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attribution-settings-DFIVIRG8.js → attribution-settings-of5gJM5a.js} +4 -4
- package/dist/{attribution-settings-DFIVIRG8.js.map → attribution-settings-of5gJM5a.js.map} +1 -1
- package/dist/{auth-WA88cE9q.js → auth-DIFbHOu0.js} +3 -3
- package/dist/{auth-WA88cE9q.js.map → auth-DIFbHOu0.js.map} +1 -1
- package/dist/browser-bridge/index.js +67 -27
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-v2apGKz7.js → check-usage-DfnrR-d_.js} +4 -4
- package/dist/{check-usage-v2apGKz7.js.map → check-usage-DfnrR-d_.js.map} +1 -1
- package/dist/{claude-BCI3Sx6_.js → claude-BlzCUbVq.js} +15 -14
- package/dist/{claude-BCI3Sx6_.js.map → claude-BlzCUbVq.js.map} +1 -1
- package/dist/{codex-DyJIrbJt.js → codex-BaFcXOyg.js} +5 -5
- package/dist/{codex-DyJIrbJt.js.map → codex-BaFcXOyg.js.map} +1 -1
- package/dist/{debug-vshv4nIv.js → debug-CuuxCk_J.js} +2 -2
- package/dist/{debug-vshv4nIv.js.map → debug-CuuxCk_J.js.map} +1 -1
- package/dist/engine-mwIgHJoi.js +2 -0
- package/dist/{exec-DTO2oin0.js → exec-y8C_MU8A.js} +89 -18
- package/dist/exec-y8C_MU8A.js.map +1 -0
- package/dist/{gate-discovery-cMbt8Ct2.js → gate-discovery-AUAjqSpV.js} +6 -6
- package/dist/{gate-discovery-cMbt8Ct2.js.map → gate-discovery-AUAjqSpV.js.map} +1 -1
- package/dist/{get-copilot-usage-DOFJWJaQ.js → get-copilot-usage-Ds09xSmH.js} +2 -2
- package/dist/{get-copilot-usage-DOFJWJaQ.js.map → get-copilot-usage-Ds09xSmH.js.map} +1 -1
- package/dist/{internal-artifact-open-CZGO831M.js → internal-artifact-open-CDqPfegE.js} +2 -2
- package/dist/{internal-artifact-open-CZGO831M.js.map → internal-artifact-open-CDqPfegE.js.map} +1 -1
- package/dist/{internal-plan-review-6gkcOAjT.js → internal-plan-review-CH9qTHoZ.js} +3 -3
- package/dist/{internal-plan-review-6gkcOAjT.js.map → internal-plan-review-CH9qTHoZ.js.map} +1 -1
- package/dist/{internal-prompt-submit-C0XOPgcP.js → internal-prompt-submit-Bve1s4z_.js} +5 -5
- package/dist/{internal-prompt-submit-C0XOPgcP.js.map → internal-prompt-submit-Bve1s4z_.js.map} +1 -1
- package/dist/{internal-session-bind-DtSBTkQe.js → internal-session-bind-Cc8bMXHK.js} +2 -2
- package/dist/{internal-session-bind-DtSBTkQe.js.map → internal-session-bind-Cc8bMXHK.js.map} +1 -1
- package/dist/{internal-stop-hook-CBcE2Js8.js → internal-stop-hook-B1MIwmTR.js} +6 -6
- package/dist/{internal-stop-hook-CBcE2Js8.js.map → internal-stop-hook-B1MIwmTR.js.map} +1 -1
- package/dist/{internal-stop-review-_1Mqz7eT.js → internal-stop-review-CWE7_QVv.js} +2 -2
- package/dist/{internal-stop-review-_1Mqz7eT.js.map → internal-stop-review-CWE7_QVv.js.map} +1 -1
- package/dist/{lifecycle-DjC9tC1A.js → lifecycle-0XrazT05.js} +2 -2
- package/dist/{lifecycle-DjC9tC1A.js.map → lifecycle-0XrazT05.js.map} +1 -1
- package/dist/lifecycle-2M0IThRr.js +2 -0
- package/dist/{lifecycle-Bd1Fyf4B.js → lifecycle-AgNOtFRv.js} +3 -3
- package/dist/{lifecycle-Bd1Fyf4B.js.map → lifecycle-AgNOtFRv.js.map} +1 -1
- package/dist/lifecycle-C8kFsAj-.js +2 -0
- package/dist/main.js +14 -14
- package/dist/{models-Cv6gprpy.js → models-BFQUp0ov.js} +35 -30
- package/dist/models-BFQUp0ov.js.map +1 -0
- package/dist/{orchestration-B6qidQAd.js → orchestration-B_Q3ncXI.js} +3 -3
- package/dist/{orchestration-B6qidQAd.js.map → orchestration-B_Q3ncXI.js.map} +1 -1
- package/dist/paths-BbHtQAOs.js +2 -0
- package/dist/{paths-BXrbboAS.js → paths-Bg1_DWhi.js} +3 -3
- package/dist/{paths-BXrbboAS.js.map → paths-Bg1_DWhi.js.map} +1 -1
- package/dist/{peer-mcp-personas-B22ncnbQ.js → peer-mcp-personas-pWP3Eyt7.js} +235 -108
- package/dist/peer-mcp-personas-pWP3Eyt7.js.map +1 -0
- package/dist/{plan-review-hook-Bo4y1r3j.js → plan-review-hook-BKOcW5s4.js} +3 -3
- package/dist/{plan-review-hook-Bo4y1r3j.js.map → plan-review-hook-BKOcW5s4.js.map} +1 -1
- package/dist/{prompt-submit-hook-BFRFLSk5.js → prompt-submit-hook-F7Zih_au.js} +2 -2
- package/dist/{prompt-submit-hook-BFRFLSk5.js.map → prompt-submit-hook-F7Zih_au.js.map} +1 -1
- package/dist/{provision-DSpLQHC3.js → provision-CsYUVdMT.js} +5 -5
- package/dist/{provision-DSpLQHC3.js.map → provision-CsYUVdMT.js.map} +1 -1
- package/dist/{serve-D9tBVVoK.js → serve--c9n9hk4.js} +11 -11
- package/dist/{serve-D9tBVVoK.js.map → serve--c9n9hk4.js.map} +1 -1
- package/dist/{server-setup-BM9Smfek.js → server-setup-BmyWS4WU.js} +559 -158
- package/dist/server-setup-BmyWS4WU.js.map +1 -0
- package/dist/{start-D7Hx2T_T.js → start-CXnLBouJ.js} +3 -3
- package/dist/{start-D7Hx2T_T.js.map → start-CXnLBouJ.js.map} +1 -1
- package/dist/{stop-gate-hook-Bmwla_2u.js → stop-gate-hook-BqpumJtl.js} +3 -3
- package/dist/{stop-gate-hook-Bmwla_2u.js.map → stop-gate-hook-BqpumJtl.js.map} +1 -1
- package/dist/{stop-gate-policy-CoMKWSsS.js → stop-gate-policy-C0XOBZhB.js} +3 -3
- package/dist/{stop-gate-policy-CoMKWSsS.js.map → stop-gate-policy-C0XOBZhB.js.map} +1 -1
- package/dist/{token-C8Uh7aUe.js → token-iaSGp76k.js} +356 -147
- package/dist/token-iaSGp76k.js.map +1 -0
- package/package.json +2 -2
- package/dist/engine-D8dlcSW6.js +0 -2
- package/dist/exec-DTO2oin0.js.map +0 -1
- package/dist/lifecycle-CRTWEbiP.js +0 -2
- package/dist/lifecycle-DUPXAOQS.js +0 -2
- package/dist/models-Cv6gprpy.js.map +0 -1
- package/dist/paths-Dz1WyRJG.js +0 -2
- package/dist/peer-mcp-personas-B22ncnbQ.js.map +0 -1
- package/dist/server-setup-BM9Smfek.js.map +0 -1
- package/dist/token-C8Uh7aUe.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token-iaSGp76k.js","names":["process"],"sources":["../src/lib/state.ts","../src/lib/api-config.ts","../src/lib/upstream-retry.ts","../src/lib/error.ts","../src/services/github/get-copilot-token.ts","../src/services/github/get-device-code.ts","../src/services/github/get-user.ts","../src/services/copilot/get-models.ts","../src/services/get-copilot-version.ts","../src/services/get-vscode-version.ts","../src/lib/editor-version-cache.ts","../src/lib/utils.ts","../src/services/github/poll-access-token.ts","../src/lib/token.ts"],"sourcesContent":["import { randomBytes, randomUUID } from \"node:crypto\"\n\nimport type { ModelsResponse } from \"~/services/copilot/get-models\"\n\nexport interface State {\n githubToken?: string\n copilotToken?: string\n\n /**\n * Second, WRITE-capable GitHub token for the first-mate\n * agent-orchestration surface (`--agents`). Minted by a separate\n * device-flow login against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`, scopes `repo workflow read:org`) and\n * stored at `PATHS.GITHUB_AGENT_TOKEN_PATH`, apart from `githubToken`\n * (the Copilot App token, read:user). The first-mate GitHub service\n * layer uses this for ALL its calls (reads included, so it also works\n * on private repos). Undefined until the agent login has run.\n */\n githubAgentToken?: string\n\n accountType: string\n copilotApiUrl?: string\n models?: ModelsResponse\n vsCodeVersion?: string\n copilotVersion?: string\n\n manualApprove: boolean\n rateLimitWait: boolean\n showToken: boolean\n extendedBetas: boolean\n\n /**\n * Opt-in flag for the browser-control MCP tools (`browser_*`). Set by\n * `setupAndServe` from the `--browse` CLI flag or\n * `GH_ROUTER_ENABLE_BROWSE=1` env var. When false, all `browser_*`\n * tools are dropped from `tools/list` AND `tools/call` returns\n * -32601 — same defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `browserToolsEnabled()` in\n * `src/routes/mcp/handler.ts`.\n */\n browseEnabled: boolean\n\n /**\n * Opt-in flag for the fleet session-control MCP tools (`mcp__fleet__*`).\n * Set by `setupAndServe` from the `--fleet` CLI flag or\n * `GH_ROUTER_ENABLE_FLEET=1` env var. When false, all fleet tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `workerToolsEnabled()` /\n * `standInToolEnabled()`. See `fleetToolsEnabled()` in\n * `src/lib/mcp-capabilities.ts`.\n */\n fleetEnabled: boolean\n\n /**\n * Opt-in flag for the first-mate agent-orchestration MCP tools\n * (`mcp__first-mate__*`) and the in-process GitHub cloud-agent driving\n * layer. Set by `setupAndServe` from the `--agents` CLI flag or\n * `GH_ROUTER_ENABLE_AGENTS=1`. When false, the first-mate tools are\n * dropped from `tools/list` AND `tools/call` returns -32601 — same\n * defense-in-depth pattern as `fleetToolsEnabled()`. Additionally\n * requires `state.githubAgentToken` present (the write login), so the\n * surface is invisible rather than 401-ing when unauthenticated. See\n * `agentToolsEnabled()` in `src/lib/mcp-capabilities.ts`.\n */\n agentsEnabled: boolean\n\n /**\n * When true, --power-browse was passed (or GH_ROUTER_ENABLE_POWER_BROWSE=1\n * is set). Exposes the FULL browser MCP surface (~18 tools) on /mcp,\n * including the L0/L1 primitives that hand DOM details (refs,\n * bboxes, role/name dumps) to the lead model. Default --browse mode\n * exposes only the 6 lead-model tools (act, observe, extract,\n * navigate, screenshot, open_tab). Always implies browseEnabled.\n */\n powerBrowseEnabled: boolean\n\n /**\n * Humanlike pacing override:\n * \"on\" - --humanlike CLI flag or GH_ROUTER_HUMANLIKE=1 env;\n * inject Beta-distributed inter-action delays, Bezier\n * mouse paths, per-keystroke jitter, scroll chunking\n * into every browser_* action dispatch.\n * \"off\" - GH_ROUTER_BROWSER_NO_HUMANLIKE=1; HARD disable, wins\n * over \"on\" so tests are reproducible.\n * \"auto\" - default; pacing engages only when bot-challenge\n * detection fires (Phase 4-future).\n *\n * Lead model never sees this state — it's an internal concern.\n */\n humanlikeForce: \"on\" | \"off\" | \"auto\"\n\n // Rate limiting configuration\n rateLimitSeconds?: number\n lastRequestTimestamp?: number\n\n // Persistent session identifiers to match VS Code fingerprint\n sessionId: string\n machineId: string\n\n /**\n * Per-launch nonce for the loopback `/mcp` endpoint. Set by the\n * `claude` subcommand after `setupAndServe` and before spawning\n * Claude Code; the spawned MCP client reads it from the\n * `--mcp-config` tempfile and presents it as `Authorization: Bearer`.\n * When unset, `/mcp` rejects all requests — closes the\n * loopback-no-auth gap (DNS rebinding, malicious browser-ext\n * native messaging, sibling-process probe).\n */\n peerMcpNonce?: string\n\n /**\n * Set by `github-router serve` (a single machine-wide control plane serving\n * many repos). When true, repo-scoped worker tools require an explicit/So-derived\n * `workspace` and must NOT silently default to the proxy launch cwd.\n */\n serveMode?: boolean\n}\n\nexport const state: State = {\n accountType: \"enterprise\",\n manualApprove: false,\n rateLimitWait: false,\n showToken: false,\n extendedBetas: false,\n browseEnabled: false,\n fleetEnabled: false,\n agentsEnabled: false,\n powerBrowseEnabled: false,\n humanlikeForce: \"auto\",\n sessionId: randomUUID(),\n machineId: randomBytes(32).toString(\"hex\"),\n}\n","import { randomUUID } from \"node:crypto\"\n\nimport type { State } from \"./state\"\n\nexport const standardHeaders = () => ({\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n})\n\nconst DEFAULT_COPILOT_VERSION = \"0.43.2026033101\"\n\nexport function copilotVersion(state: State): string {\n return state.copilotVersion ?? DEFAULT_COPILOT_VERSION\n}\n\nconst API_VERSION = \"2026-01-09\"\n\nexport const copilotBaseUrl = (state: State) =>\n state.copilotApiUrl ?? \"https://api.githubcopilot.com\"\nexport const copilotHeaders = (\n state: State,\n vision: boolean = false,\n integrationId: string = \"vscode-chat\",\n) => {\n const version = copilotVersion(state)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${state.copilotToken}`,\n \"content-type\": standardHeaders()[\"content-type\"],\n \"copilot-integration-id\": integrationId,\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": `copilot-chat/${version}`,\n \"user-agent\": `GitHubCopilotChat/${version}`,\n \"openai-intent\": \"conversation-panel\",\n \"x-interaction-type\": \"conversation-panel\",\n \"x-github-api-version\": API_VERSION,\n \"x-request-id\": randomUUID(),\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n \"VScode-SessionId\": state.sessionId,\n \"VScode-MachineId\": state.machineId,\n }\n\n if (vision) headers[\"copilot-vision-request\"] = \"true\"\n\n return headers\n}\n\nexport const GITHUB_API_BASE_URL =\n process.env.GITHUB_API_URL ?? \"https://api.github.com\"\nexport const githubHeaders = (state: State) => ({\n ...standardHeaders(),\n authorization: `token ${state.githubToken}`,\n \"editor-version\": `vscode/${state.vsCodeVersion}`,\n \"editor-plugin-version\": `copilot-chat/${copilotVersion(state)}`,\n \"user-agent\": `GitHubCopilotChat/${copilotVersion(state)}`,\n \"x-github-api-version\": API_VERSION,\n \"x-vscode-user-agent-library-version\": \"electron-fetch\",\n})\n\nexport const GITHUB_BASE_URL = \"https://github.com\"\nexport const GITHUB_CLIENT_ID = \"Iv1.b507a08c87ecfe98\"\nexport const GITHUB_APP_SCOPES = [\"read:user\"].join(\" \")\n\n// --- First-mate agent-orchestration write identity (`--agents`) ---------\n// The Copilot device-login token above (a GitHub *App* token, read:user)\n// can READ the agent surface but 403s on any write/push. The first-mate\n// controller needs a WRITE-capable token to create issues, assign cloud\n// coding agents, comment, dispatch workflows, and merge. We mint a second,\n// isolated token via a separate device-flow login against the GitHub CLI's\n// public OAuth client (a classic OAuth App that honors the requested\n// scopes — verified to accept `repo workflow read:org` at\n// `/login/device/code`). Stored apart at PATHS.GITHUB_AGENT_TOKEN_PATH;\n// never mixed with `state.githubToken`.\nexport const GITHUB_AGENT_CLIENT_ID = \"178c6fc778ccc68e1d6a\"\nexport const GITHUB_AGENT_SCOPES = [\"repo\", \"workflow\", \"read:org\"].join(\" \")\nexport const GITHUB_GRAPHQL_URL =\n process.env.GITHUB_GRAPHQL_URL ?? \"https://api.github.com/graphql\"\n// GitHub's documented REST/GraphQL API version for the general-purpose\n// (non-Copilot) surface the first-mate layer drives. The Agent-Tasks\n// preview client overrides this per-call with its own dated version.\nexport const GITHUB_REST_API_VERSION = \"2022-11-28\"\nexport const githubAgentHeaders = (state: State) => ({\n ...standardHeaders(),\n authorization: `token ${state.githubAgentToken}`,\n \"x-github-api-version\": GITHUB_REST_API_VERSION,\n \"user-agent\": \"github-router-first-mate\",\n})\nexport const githubAgentGraphQLHeaders = (state: State, features?: string) => ({\n ...githubAgentHeaders(state),\n ...(features ? { \"GraphQL-Features\": features } : {}),\n})\n","/**\n * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).\n *\n * Retries ONLY on transient conditions — never on success, never on a\n * deterministic 4xx (400/401/403/404…), so a malformed request or auth\n * failure fails fast instead of being hammered. 401 is intentionally NOT\n * retried here: it stays with the existing token-refresh path so the\n * 401→503 forwardError invariant is preserved.\n *\n * Retryable:\n * - HTTP 429 + 5xx (500/502/503/504) — the \"upstream is sick\" class.\n * - network errors (ECONNRESET / \"fetch failed\" / \"terminated\" / EPIPE …).\n * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S\n * `signal` is NOT aborted (a user cancel aborts the caller's signal\n * and is rethrown immediately, never retried).\n *\n * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The\n * inter-attempt sleep is abortable so a user cancel during backoff\n * returns promptly. Bounded `attempts` keep a single call from holding an\n * inflight slot indefinitely (robust AND fast).\n *\n * Streaming note: the user-facing passthrough and the worker loop must\n * only retry in the PRE-FIRST-BYTE window — a retry after bytes have\n * streamed would duplicate output. Callers there pass a `doFetch` that\n * has not yet handed its body to the consumer.\n */\n\nimport consola from \"consola\"\n\nexport interface TransientRetryOpts {\n /** Total attempts including the first (default 3 → up to 2 retries). */\n attempts?: number\n /** Retryable HTTP statuses (default 429, 500, 502, 503, 504). */\n retryStatuses?: ReadonlyArray<number>\n /** Backoff base (default 250ms) and cap (default 4000ms). */\n baseDelayMs?: number\n maxDelayMs?: number\n /** Caller's abort signal — a user cancel fails fast (never retried). */\n signal?: AbortSignal\n /** Short label for debug logging (e.g. \"codex_critic\", \"advisor\"). */\n label?: string\n /** Upstream endpoint when it differs from the human-readable label. */\n endpoint?: string\n}\n\nconst DEFAULT_RETRY_STATUSES: ReadonlyArray<number> = [429, 500, 502, 503, 504]\nconst TRANSPORT_MESSAGE_MAX = 512\nconst TRANSIENT_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n])\nconst DETERMINISTIC_CODES = new Set([\n \"ENOTFOUND\",\n \"ECONNREFUSED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n \"CERT_HAS_EXPIRED\",\n \"CERT_NOT_YET_VALID\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED\",\n \"ERR_SSL_WRONG_VERSION_NUMBER\",\n])\nconst CREDENTIAL_RE =\n /\\b(eyJ[A-Za-z0-9_-]{20,}(?:\\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\\s+\\S{20,})\\b/gi\nconst SECRET_ASSIGNMENT_RE =\n /\\b(authorization|api[_-]?key|access[_-]?token|token|password)\\s*[:=]\\s*([^\\s,;]+)/gi\nconst REQUEST_BODY_RE =\n /\\b(request\\s+body|body)\\s*[:=]\\s*.*$/gi\n\nexport type TransportErrorClassification =\n | \"transient\"\n | \"deterministic\"\n | \"non_transport\"\n | \"cancelled\"\n\nexport interface TransportErrorDetails {\n classification: TransportErrorClassification\n name: string\n message: string\n code?: string\n causeCode?: string\n}\n\nexport interface TransportExhaustionMetadata {\n endpoint?: string\n label?: string\n attempts: number\n classification: \"transient\" | \"deterministic\"\n lastError: Omit<TransportErrorDetails, \"classification\">\n}\n\nexport class TransportExhaustionError extends Error {\n readonly endpoint?: string\n readonly label?: string\n readonly attempts: number\n readonly classification: \"transient\" | \"deterministic\"\n readonly lastError: Omit<TransportErrorDetails, \"classification\">\n\n constructor(metadata: TransportExhaustionMetadata, cause: unknown) {\n const target = metadata.endpoint ?? metadata.label ?? \"upstream\"\n const lastError = {\n name: sanitizeTransportText(metadata.lastError.name),\n message: sanitizeTransportText(metadata.lastError.message),\n code: metadata.lastError.code\n ? sanitizeTransportText(metadata.lastError.code)\n : undefined,\n causeCode: metadata.lastError.causeCode\n ? sanitizeTransportText(metadata.lastError.causeCode)\n : undefined,\n }\n const code = lastError.causeCode ?? lastError.code\n const suffix = code ? ` (${code})` : \"\"\n super(\n `Upstream transport ${metadata.classification === \"transient\" ? \"failed\" : \"is unreachable\"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? \"\" : \"s\"}: ${lastError.name}: ${lastError.message}${suffix}`,\n { cause },\n )\n this.name = \"TransportExhaustionError\"\n this.endpoint = metadata.endpoint\n ? sanitizeTransportText(metadata.endpoint)\n : undefined\n this.label = metadata.label ? sanitizeTransportText(metadata.label) : undefined\n this.attempts = metadata.attempts\n this.classification = metadata.classification\n this.lastError = lastError\n }\n}\n\nfunction readStringProperty(value: unknown, key: string): string | undefined {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n const property = (value as Record<string, unknown>)[key]\n return typeof property === \"string\" ? property : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readCause(value: unknown): unknown {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n return (value as { cause?: unknown }).cause\n } catch {\n return undefined\n }\n}\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return \"[unserializable error]\"\n }\n}\n\nexport function sanitizeTransportText(value: string): string {\n const sanitized = value\n .replace(/\\r\\n|\\r|\\n/g, \" \")\n .replace(CREDENTIAL_RE, \"[REDACTED]\")\n .replace(SECRET_ASSIGNMENT_RE, \"$1=[REDACTED]\")\n .replace(REQUEST_BODY_RE, \"$1=[REDACTED]\")\n return sanitized.length > TRANSPORT_MESSAGE_MAX\n ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…`\n : sanitized\n}\n\n/**\n * Classify errors thrown before the first response byte. Deterministic\n * connectivity/configuration signals win over generic runtime wording such as\n * TypeError(\"fetch failed\"), because the nested cause is more specific.\n */\nexport function classifyTransportError(\n error: unknown,\n opts: { callerCancelled?: boolean } = {},\n): TransportErrorDetails {\n const name = readStringProperty(error, \"name\") ?? \"Error\"\n const rawMessage =\n readStringProperty(error, \"message\")\n ?? (typeof error === \"string\" ? error : safeString(error))\n const message = sanitizeTransportText(rawMessage)\n const code = readStringProperty(error, \"code\")\n\n const causes: unknown[] = []\n const seen = new Set<unknown>()\n let current = readCause(error)\n for (let depth = 0; current !== undefined && depth < 4; depth++) {\n if (\n (typeof current === \"object\" || typeof current === \"function\")\n && current !== null\n ) {\n if (seen.has(current)) break\n seen.add(current)\n }\n causes.push(current)\n current = readCause(current)\n }\n const causeCode = causes\n .map((cause) => readStringProperty(cause, \"code\"))\n .find((value): value is string => value !== undefined)\n const codes = [code, ...causes.map((cause) => readStringProperty(cause, \"code\"))]\n .filter((value): value is string => value !== undefined)\n .map((value) => value.toUpperCase())\n const messages = [\n rawMessage,\n ...causes.map((cause) => readStringProperty(cause, \"message\") ?? \"\"),\n ]\n .join(\" \")\n .toLowerCase()\n\n if (opts.callerCancelled) {\n return { classification: \"cancelled\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || messages.includes(\"self signed certificate\")\n || messages.includes(\"certificate has expired\")\n || messages.includes(\"unable to verify the first certificate\")\n || messages.includes(\"unable to get local issuer certificate\")\n || messages.includes(\"hostname/ip does not match certificate\")\n || messages.includes(\"tls handshake\")\n || messages.includes(\"ssl routines\")\n || messages.includes(\"econnrefused\")\n || messages.includes(\"enotfound\")\n ) {\n return { classification: \"deterministic\", name, message, code, causeCode }\n }\n if (\n name === \"AbortError\"\n || name === \"TimeoutError\"\n || name === \"InactivityTimeout\"\n || codes.some((value) => TRANSIENT_CODES.has(value))\n || messages.includes(\"terminated\")\n || messages.includes(\"fetch failed\")\n || messages.includes(\"network error\")\n || messages.includes(\"socket hang up\")\n || messages.includes(\"socket closed\")\n || messages.includes(\"econnreset\")\n || messages.includes(\"etimedout\")\n || messages.includes(\"epipe\")\n || messages.includes(\"eai_again\")\n ) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n return { classification: \"non_transport\", name, message, code, causeCode }\n}\n\nfunction transportExhaustion(\n error: unknown,\n attempts: number,\n opts: TransientRetryOpts,\n details: TransportErrorDetails,\n): TransportExhaustionError {\n if (\n details.classification !== \"transient\"\n && details.classification !== \"deterministic\"\n ) {\n throw new TypeError(\"transportExhaustion requires a transport error\")\n }\n return new TransportExhaustionError(\n {\n endpoint: opts.endpoint ?? opts.label,\n label: opts.label,\n attempts,\n classification: details.classification,\n lastError: {\n name: details.name,\n message: details.message,\n code: details.code,\n causeCode: details.causeCode,\n },\n },\n error,\n )\n}\n\nfunction parseRetryAfter(headerValue: string | null): number | undefined {\n if (!headerValue) return undefined\n const secs = Number(headerValue)\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000)\n const dateMs = Date.parse(headerValue)\n if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now())\n return undefined\n}\n\n/** Sleep that resolves early (does not reject) when `signal` aborts — the\n * retry loop re-checks `signal.aborted` at the top and throws there. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n if (signal) {\n if (signal.aborted) {\n done()\n return\n }\n signal.addEventListener(\"abort\", done, { once: true })\n }\n })\n}\n\n/**\n * Run `doFetch` with bounded transient-failure retries. `doFetch` is a\n * thunk so each attempt issues a FRESH request (bodies can't be replayed\n * from a consumed stream). Returns the final `Response` — which may still\n * carry a retryable status if all attempts are exhausted (the caller\n * handles that as it would a single-shot failure).\n */\nexport async function fetchWithTransientRetry(\n doFetch: (attempt: number) => Promise<Response>,\n opts: TransientRetryOpts = {},\n): Promise<Response> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n\n let res: Response | undefined\n let caught: unknown\n try {\n res = await doFetch(attempt)\n } catch (err) {\n caught = err\n }\n\n // Success or a non-retryable status → done.\n if (res && !retryStatuses.includes(res.status)) return res\n\n // A thrown error: a user cancel fails fast; otherwise only retry the\n // transient network/timeout class.\n if (caught !== undefined) {\n if (signal?.aborted) throw caught\n const details = classifyTransportError(caught)\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(caught, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw caught\n }\n\n // Out of attempts → return the last error response (or rethrow).\n if (attempt >= attempts) {\n if (res) return res\n const details = classifyTransportError(caught)\n throw transportExhaustion(caught, attempt, opts, details)\n }\n\n // Free the connection before retrying a retryable-status response.\n const retryAfterMs = res\n ? parseRetryAfter(res.headers.get(\"retry-after\"))\n : undefined\n if (res?.body) {\n try {\n await res.body.cancel()\n } catch {\n /* already torn down */\n }\n }\n\n // Full jitter (random within the exponential cap), Retry-After wins.\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n const why = res\n ? `HTTP ${res.status}`\n : (caught as { name?: string } | undefined)?.name ?? \"error\"\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n}\n\n/** Extract an HTTP status from a thrown error (HTTPError carries\n * `.response.status`; others may carry `.status`/`.statusCode`; last\n * resort parses `\"HTTP <code>\"` from the message). */\nfunction errorStatus(err: unknown): number | undefined {\n const e = err as\n | {\n status?: unknown\n statusCode?: unknown\n response?: { status?: unknown }\n message?: string\n }\n | undefined\n for (const v of [e?.status, e?.statusCode, e?.response?.status]) {\n if (typeof v === \"number\") return v\n }\n const m = /\\bHTTP (\\d{3})\\b/.exec(e?.message ?? \"\")\n return m ? Number(m[1]) : undefined\n}\n\n/**\n * Generic transient-retry for a non-`Response`-returning call (e.g. the\n * Copilot service clients, which throw `HTTPError` on non-OK and throw on\n * network errors). Retries `fn()` when it throws a transient error — an\n * `HTTPError`-like with a retryable status (429/5xx) OR a transient\n * network/timeout error — using the same backoff + abort semantics as\n * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.\n * 401), a non-transient throw, or a user cancel.\n */\nexport async function withTransientRetry<T>(\n fn: (attempt: number) => Promise<T>,\n opts: TransientRetryOpts = {},\n): Promise<T> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n try {\n return await fn(attempt)\n } catch (err) {\n if (signal?.aborted) throw err\n const status = errorStatus(err)\n const details = classifyTransportError(err)\n if (status !== undefined) {\n if (!retryStatuses.includes(status) || attempt >= attempts) throw err\n } else {\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(err, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw err\n if (attempt >= attempts) {\n throw transportExhaustion(err, attempt, opts, details)\n }\n }\n\n const retryAfterMs = parseRetryAfter(\n (err as { response?: { headers?: { get?: (k: string) => string | null } } })\n ?.response?.headers?.get?.(\"retry-after\") ?? null,\n )\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${\n status !== undefined ? `HTTP ${status}` : (err as { name?: string })?.name ?? \"error\"\n }); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n }\n}\n","import type { Context } from \"hono\"\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\"\n\nimport consola from \"consola\"\n\nimport {\n sanitizeTransportText,\n TransportExhaustionError,\n} from \"~/lib/upstream-retry\"\n\nexport class HTTPError extends Error {\n response: Response\n\n constructor(message: string, response: Response) {\n super(message)\n this.response = response\n }\n}\n\nexport async function forwardError(c: Context, error: unknown) {\n consola.error(`Error occurred at ${c.req.path}:`, error)\n\n if (error instanceof TransportExhaustionError) {\n const target = sanitizeTransportText(\n error.endpoint ?? error.label ?? c.req.path,\n )\n const diagnostic = formatTransportDiagnostic(error)\n if (error.classification === \"transient\") {\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"overloaded_error\",\n message: `Upstream transport was interrupted at ${target} after ${error.attempts} attempts; retry later. ${diagnostic}`,\n },\n },\n 503,\n )\n }\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"api_error\",\n message: `Could not connect to upstream at ${target}. Check DNS, proxy, firewall, and TLS configuration. ${diagnostic}`,\n },\n },\n 502,\n )\n }\n\n if (error instanceof HTTPError) {\n const errorText = await error.response.text().catch(() => \"\")\n let errorJson: unknown\n try {\n errorJson = JSON.parse(errorText)\n } catch {\n errorJson = undefined\n }\n\n // Map upstream context-overflow errors (413, or 400 with a known\n // overflow substring) to Anthropic's \"prompt is too long\" 400 shape so\n // Claude Code triggers self-compaction instead of bubbling the error.\n // Note: a live probe of an oversized prompt against Copilot returned\n // 200 with stop_reason:\"refusal\" rather than 413/400 — this guard is\n // defensive for the documented Anthropic contract, not load-bearing.\n if (isContextOverflow(error.response.status, errorJson, errorText)) {\n const upstream = resolveErrorMessage(errorJson, errorText)\n consola.error(\"HTTP error (mapped to overflow):\", errorJson ?? errorText)\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"invalid_request_error\",\n message: `prompt is too long: ${upstream}`,\n },\n },\n 400,\n )\n }\n\n // Remap upstream 401 to 503 — maintain the no-401 invariant on the\n // Anthropic-shape boundary. Claude Code's reactive refresh path\n // (function `SZ1` → `D3(0,true,...)` in v2.1.140 binary) fires on\n // any 401 from upstream and attempts to refresh the OAuth token.\n // Spawned-via-proxy sessions use a synthetic credential\n // (`ensureClaudeConfigMirror`'s SYNTHETIC_CREDENTIAL); refreshing\n // it would fail and degrade the session. Mapping 401 → 503 lets\n // the upstream message still reach the user while side-stepping\n // the refresh path. 503 maps to Anthropic's \"overloaded_error\"\n // type — semantically reasonable for \"proxy got an upstream\n // failure, retry later\".\n const responseStatus =\n error.response.status === 401 ? 503 : error.response.status\n\n // Forward upstream Anthropic-format errors as-is (with remapped status)\n if (isAnthropicError(errorJson)) {\n consola.error(\"HTTP error:\", errorJson)\n return c.json(errorJson, responseStatus as ContentfulStatusCode)\n }\n\n const message = resolveErrorMessage(errorJson, errorText)\n consola.error(\"HTTP error:\", errorJson ?? errorText)\n return c.json(\n {\n type: \"error\",\n error: {\n type: resolveErrorType(responseStatus),\n message,\n },\n },\n responseStatus as ContentfulStatusCode,\n )\n }\n\n return c.json(\n {\n type: \"error\",\n error: {\n type: \"api_error\",\n message: error instanceof Error ? error.message : String(error),\n },\n },\n 500,\n )\n}\n\nfunction formatTransportDiagnostic(error: TransportExhaustionError): string {\n const code = error.lastError.causeCode ?? error.lastError.code\n const codeText = code ? ` (${sanitizeTransportText(code)})` : \"\"\n return `${sanitizeTransportText(error.lastError.name)}: ${sanitizeTransportText(error.lastError.message)}${codeText}`\n}\n\n// Extracts error message from { message } or { error: { message } } payloads.\nfunction resolveErrorMessage(errorJson: unknown, fallback: string): string {\n if (typeof errorJson !== \"object\" || errorJson === null) return fallback\n\n const errorRecord = errorJson as Record<string, unknown>\n if (errorRecord.message !== undefined) return String(errorRecord.message)\n\n if (typeof errorRecord.error === \"object\" && errorRecord.error !== null) {\n const nestedRecord = errorRecord.error as Record<string, unknown>\n if (nestedRecord.message !== undefined) return String(nestedRecord.message)\n }\n\n return fallback\n}\n\n/**\n * Check if a parsed JSON body is already in Anthropic error format:\n * { type: \"error\", error: { type: \"...\", message: \"...\" } }\n */\nfunction isAnthropicError(json: unknown): boolean {\n if (typeof json !== \"object\" || json === null) return false\n const record = json as Record<string, unknown>\n if (record.type !== \"error\") return false\n if (typeof record.error !== \"object\" || record.error === null) return false\n const inner = record.error as Record<string, unknown>\n return typeof inner.type === \"string\" && typeof inner.message === \"string\"\n}\n\nconst CONTEXT_OVERFLOW_SUBSTRINGS = [\n \"prompt is too long\",\n \"context_length_exceeded\",\n \"context length exceeded\",\n \"input is too long\",\n \"maximum context length\",\n \"too many tokens\",\n]\n\n/**\n * Detect upstream context-overflow errors so we can remap them to a 400\n * \"prompt is too long\" shape that triggers Claude Code self-compaction.\n *\n * Always remaps 413 (treated as a hard payload-size signal regardless of\n * body wording). Remaps 400 only when the error text contains one of the\n * known overflow substrings — a regular 400 (e.g. \"model not found\") must\n * NOT remap.\n */\nexport function isContextOverflow(\n status: number,\n errorJson: unknown,\n errorText: string,\n): boolean {\n if (status === 413) return true\n if (status !== 400) return false\n\n const haystack = (\n errorText +\n \" \" +\n (typeof errorJson === \"object\" && errorJson !== null\n ? JSON.stringify(errorJson)\n : \"\")\n ).toLowerCase()\n\n return CONTEXT_OVERFLOW_SUBSTRINGS.some((s) => haystack.includes(s))\n}\n\n/**\n * Map HTTP status to Anthropic error type.\n *\n * Note: a 401 from upstream is remapped to 503 in `forwardError` BEFORE\n * this function is called (no-401 invariant — see comment there). The\n * 401 → \"authentication_error\" mapping below is preserved for\n * defensive coverage in case any code path calls `resolveErrorType`\n * directly with an unsanitized status.\n */\nfunction resolveErrorType(status: number): string {\n if (status === 400) return \"invalid_request_error\"\n if (status === 401) return \"authentication_error\"\n if (status === 403) return \"permission_error\"\n if (status === 404) return \"not_found_error\"\n if (status === 429) return \"rate_limit_error\"\n if (status === 503) return \"overloaded_error\"\n if (status === 529) return \"overloaded_error\"\n return \"api_error\"\n}\n","import consola from \"consola\"\n\nimport { GITHUB_API_BASE_URL, githubHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\n/**\n * Allowlist of hosts the router will trust as the Copilot API base URL.\n * Anything else returned in `endpoints.api` (e.g. via a tampered or\n * misconfigured token-exchange response) is rejected — otherwise a\n * malicious value would receive the long-lived GitHub PAT we send to\n * `/mcp` for web search (see `src/services/copilot/web-search.ts`).\n */\nconst COPILOT_HOST_ALLOWLIST = [\n \"api.githubcopilot.com\",\n \"api.individual.githubcopilot.com\",\n \"api.business.githubcopilot.com\",\n \"api.enterprise.githubcopilot.com\",\n]\n\n/**\n * True iff `rawUrl` is an HTTPS URL whose host is a trusted Copilot API host.\n * Exported so every path that sends a long-lived token to a discovered\n * Copilot host (web search, first-mate CAPI session logs) shares one allowlist.\n */\nexport function isAllowedCopilotHost(rawUrl: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(rawUrl)\n } catch {\n return false\n }\n if (parsed.protocol !== \"https:\") return false\n return COPILOT_HOST_ALLOWLIST.includes(parsed.hostname)\n}\n\nexport const getCopilotToken = async () => {\n // GitHub PAT → Copilot token exchange. A transient 429/5xx/network blip\n // here aborts launch (and the interval-driven refresh that keeps the\n // session alive), so retry the transient class with bounded backoff. NO\n // 401-refresh compose: this call IS the token source, and a 401 means a\n // bad/expired GitHub PAT — deterministic, fail fast (retrying would burn\n // budget against a credential that can't recover without re-auth).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/copilot_internal/v2/token`, {\n headers: githubHeaders(state),\n }),\n { label: \"/copilot_internal/v2/token\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get Copilot token\", response)\n\n const data = (await response.json()) as GetCopilotTokenResponse\n\n // Use the API base URL from the token response if available, matching\n // how VS Code determines the CAPI endpoint dynamically — but only when\n // it points at a github-controlled host (see allowlist above).\n // We deliberately do NOT clobber an existing `state.copilotApiUrl` in\n // the disallowed branch: when the user sets `COPILOT_API_URL` themselves\n // (e.g. for local testing or a CI mock), that's an explicit opt-in and\n // a different threat model than a tampered token-exchange response.\n // Allowlist-failing token-response values are simply ignored.\n if (data.endpoints?.api) {\n if (isAllowedCopilotHost(data.endpoints.api)) {\n state.copilotApiUrl = data.endpoints.api\n } else {\n consola.warn(\n `Refusing to honor Copilot API endpoint \"${data.endpoints.api}\" from ` +\n `the token-exchange response — not in allowlist ` +\n `(${COPILOT_HOST_ALLOWLIST.join(\", \")}). ` +\n (state.copilotApiUrl\n ? `Keeping existing override \"${state.copilotApiUrl}\".`\n : `Falling back to the default api.githubcopilot.com.`),\n )\n }\n }\n\n return data\n}\n\ninterface GetCopilotTokenResponse {\n expires_at: number\n refresh_in: number\n token: string\n endpoints?: {\n api?: string\n proxy?: string\n telemetry?: string\n \"origin-tracker\"?: string\n }\n}\n","import {\n GITHUB_APP_SCOPES,\n GITHUB_BASE_URL,\n GITHUB_CLIENT_ID,\n standardHeaders,\n} from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport interface DeviceApp {\n clientId: string\n scope: string\n}\n\nconst DEFAULT_DEVICE_APP: DeviceApp = {\n clientId: GITHUB_CLIENT_ID,\n scope: GITHUB_APP_SCOPES,\n}\n\nexport async function getDeviceCode(\n app: DeviceApp = DEFAULT_DEVICE_APP,\n): Promise<DeviceCodeResponse> {\n // Idempotent device-code bootstrap POST (just requests a fresh code) — a\n // transient 429/5xx/network blip here aborts the whole login flow, so\n // retry the transient class. No auth on this call, so no 401 concern.\n //\n // `app` is parameterized so a SECOND identity (the first-mate write\n // token via the GitHub CLI OAuth client) can reuse this exact flow\n // without a copy-paste fork; defaults preserve the original Copilot\n // App device login.\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_BASE_URL}/login/device/code`, {\n method: \"POST\",\n headers: standardHeaders(),\n body: JSON.stringify({\n client_id: app.clientId,\n scope: app.scope,\n }),\n }),\n { label: \"/login/device/code\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get device code\", response)\n\n return (await response.json()) as DeviceCodeResponse\n}\n\nexport interface DeviceCodeResponse {\n device_code: string\n user_code: string\n verification_uri: string\n expires_in: number\n interval: number\n}\n","import { GITHUB_API_BASE_URL, standardHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport async function getGitHubUser() {\n // GitHub PAT GET — retry transient 429/5xx/network; a 401 (bad PAT) fails\n // fast (not retried by the helper).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/user`, {\n headers: {\n authorization: `token ${state.githubToken}`,\n ...standardHeaders(),\n },\n }),\n { label: \"/user\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get GitHub user\", response)\n\n return (await response.json()) as GithubUserResponse\n}\n\n// Trimmed for the sake of simplicity\ninterface GithubUserResponse {\n login: string\n}\n","import { copilotBaseUrl, copilotHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { tryRefreshAndRetry } from \"~/lib/token\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport const getModels = async () => {\n // Startup catalog fetch — a transient 429/5xx/network blip here leaves\n // the model catalog empty for the whole session, so retry it. This is a\n // Copilot-token GET, so it keeps the 401-refresh path\n // (`tryRefreshAndRetry`) nested INSIDE the transient retry: 401 →\n // refresh once (never retried by the transient layer); 429/5xx/network\n // → bounded retry with backoff. A consumed (non-streamed) GET body is\n // safe to replay.\n const response = await fetchWithTransientRetry(\n () =>\n tryRefreshAndRetry(\n () =>\n fetch(`${copilotBaseUrl(state)}/models`, {\n headers: copilotHeaders(state),\n }),\n \"/models\",\n ),\n { label: \"/models\" },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get models\", response)\n\n return (await response.json()) as ModelsResponse\n}\n\nexport interface ModelsResponse {\n data: Array<Model>\n object: string\n}\n\ninterface ModelLimits {\n max_context_window_tokens?: number\n max_output_tokens?: number\n max_prompt_tokens?: number\n max_inputs?: number\n max_non_streaming_output_tokens?: number\n vision?: {\n max_prompt_image_size?: number\n max_prompt_images?: number\n supported_media_types?: string[]\n }\n}\n\ninterface ModelSupports {\n tool_calls?: boolean\n parallel_tool_calls?: boolean\n dimensions?: boolean\n streaming?: boolean\n vision?: boolean\n structured_outputs?: boolean\n adaptive_thinking?: boolean\n max_thinking_budget?: number\n min_thinking_budget?: number\n reasoning_effort?: Array<string>\n}\n\ninterface ModelCapabilities {\n family: string\n limits?: ModelLimits\n object: string\n supports?: ModelSupports\n tokenizer: string\n type: string\n}\n\nexport interface Model {\n capabilities: ModelCapabilities\n id: string\n model_picker_enabled: boolean\n name: string\n object: string\n preview: boolean\n vendor: string\n version: string\n supported_endpoints?: Array<string>\n requestHeaders?: Record<string, string>\n policy?: {\n state: string\n terms: string\n }\n billing?: {\n is_premium: boolean\n multiplier: number\n restricted_to?: string[]\n /**\n * Per-token prices, scaled by 1e9. Present on the live catalog even\n * where `is_premium` / `multiplier` are absent (usage-based-billing\n * accounts populate this instead), which is why both shapes are\n * modelled: reading only the premium pair silently yields nothing\n * on those accounts.\n */\n token_prices?: {\n input_price?: number\n output_price?: number\n cache_price?: number\n batch_size?: number\n }\n }\n is_chat_default?: boolean\n is_chat_fallback?: boolean\n model_picker_category?: string\n /** Vendor-authored cost tier (`low` | `medium` | `high` | `very_high`). */\n model_picker_price_category?: string\n info_messages?: Array<{ code: string; message: string }>\n warning_messages?: Array<{ code: string; message: string }>\n}\n","/**\n * Last-resort floor when the lookup fails. A fallback must never become the\n * cached steady state — see the note on `VSCODE_VERSION_FALLBACK` in\n * `./get-vscode-version`.\n */\nexport const COPILOT_CHAT_VERSION_FALLBACK = \"0.43.2026033101\"\nconst FALLBACK = COPILOT_CHAT_VERSION_FALLBACK\n\ninterface MarketplaceResult {\n results: Array<{\n extensions: Array<{\n versions: Array<{ version: string }>\n }>\n }>\n}\n\n/**\n * The lookup, reporting failure as `undefined` rather than as the fallback.\n * See `getVSCodeVersionOrUndefined` for why the distinction matters to the\n * version cache.\n */\nexport async function getCopilotChatVersionOrUndefined(): Promise<\n string | undefined\n> {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, 5000)\n\n try {\n const response = await fetch(\n \"https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json;api-version=7.1-preview.1\",\n },\n body: JSON.stringify({\n filters: [\n {\n criteria: [{ filterType: 7, value: \"GitHub.copilot-chat\" }],\n },\n ],\n flags: 914,\n }),\n signal: controller.signal,\n },\n )\n\n if (!response.ok) return undefined\n\n const data = (await response.json()) as MarketplaceResult\n const version =\n data?.results?.[0]?.extensions?.[0]?.versions?.[0]?.version\n\n return version\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\n/** Fallback-substituting wrapper, for callers that just want a version. */\nexport async function getCopilotChatVersion(): Promise<string> {\n return (await getCopilotChatVersionOrUndefined()) ?? FALLBACK\n}\n","/**\n * Last-resort floor when the lookup fails. A fallback must never become the\n * cached steady state, or a transient outage would freeze the version we\n * impersonate. See `src/lib/editor-version-cache.ts`.\n */\nexport const VSCODE_VERSION_FALLBACK = \"1.104.3\"\nconst FALLBACK = VSCODE_VERSION_FALLBACK\n\n/**\n * The lookup, reporting failure as `undefined` rather than as the fallback.\n *\n * The distinction is load-bearing for the cache: it must not infer \"the fetch\n * failed\" from `value === FALLBACK`, because the live version legitimately\n * equals the constant right after someone bumps `VSCODE_VERSION_FALLBACK` to\n * the then-current release — and that reading would refuse to cache a perfectly\n * good result, making every launch re-pay the ~1.5s network call forever.\n */\nexport async function getVSCodeVersionOrUndefined(): Promise<string | undefined> {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, 5000)\n\n try {\n const response = await fetch(\n \"https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=visual-studio-code-bin\",\n {\n signal: controller.signal,\n },\n )\n\n const pkgbuild = await response.text()\n const pkgverRegex = /pkgver=([0-9.]+)/\n const match = pkgbuild.match(pkgverRegex)\n\n return match ? match[1] : undefined\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\n/** Fallback-substituting wrapper, for callers that just want a version. */\nexport async function getVSCodeVersion(): Promise<string> {\n return (await getVSCodeVersionOrUndefined()) ?? FALLBACK\n}\n\n","/**\n * Disk-backed TTL cache for the EDITOR IDENTITY versions the proxy sends\n * upstream: the VS Code version (`editor-version`) and the Copilot Chat\n * extension version (`editor-plugin-version`), see `src/lib/api-config.ts`.\n *\n * Why this exists: impersonating VS Code is non-negotiable — Copilot is\n * addressed as if by the real editor, so those headers must carry real,\n * current versions. But the two lookups are NETWORK calls to third parties\n * (the Arch AUR PKGBUILD and the VS Marketplace), and they sat on the\n * blocking launch path of EVERY invocation. The AUR fetch alone measured\n * ~1.5-1.8s, which every `github-router` process paid — including the\n * per-turn Claude Code hooks (`internal-prompt-submit`, `internal-stop-hook`,\n * …), each of which is a fresh `node dist/main.js` spawn.\n *\n * The fix is a cache, NOT a removal. Both fetches are still made; they are\n * just made at most once per `TTL_HOURS` instead of once (twice, before the\n * duplicate top-level await in `get-vscode-version.ts` was dropped) per\n * launch. A 12h TTL keeps the impersonated versions well inside the real\n * editor's release cadence.\n *\n * Two invariants that keep impersonation honest:\n *\n * 1. A FALLBACK is NEVER cached. `getVSCodeVersion()` /\n * `getCopilotChatVersion()` return a hardcoded constant when the network\n * fails, and that constant must stay a last-resort floor for the current\n * process — never the persisted steady state. Persisting it would let a\n * transient outage silently freeze the advertised version for 12h, and\n * (worse) survive restarts. `writeEntry` is therefore only reached on a\n * value that differs from the fallback.\n * 2. The timestamp is written only on SUCCESS. An offline machine retries\n * on the next launch rather than pinning a stale entry, which is the\n * opposite of `claude-version-check.ts`'s throttle (that one stamps\n * after the probes regardless, so an offline box pays both timeouts\n * hourly). Do not copy that detail here.\n *\n * The file lives beside `last-update-check` / `last-self-update-check` and is\n * deliberately named distinctly so the three throttles never cross-suppress.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"./paths\"\n\nconst TTL_HOURS = 12\n\n/** One cached lookup: the resolved value plus when it was resolved. */\ninterface CacheEntry {\n value: string\n checkedAt: string\n}\n\ninterface EditorVersionCache {\n vscode?: CacheEntry\n copilotChat?: CacheEntry\n}\n\n/** Which upstream identity a cached entry belongs to. */\nexport type EditorVersionKey = \"vscode\" | \"copilotChat\"\n\nfunction cacheFilePath(): string {\n return path.join(PATHS.APP_DIR, \"last-editor-versions\")\n}\n\n/**\n * True when running under a test runner.\n *\n * Detected from the entry file, not an env var: `bun test` sets no marker of\n * its own and this repo builds with `NODE_ENV=production`, so `argv[1]` (the\n * spec file being executed) is the reliable signal. `BUN_TEST` / `NODE_ENV`\n * are still honored for other runners.\n *\n * The cache's own tests sandbox `homedir()` and opt back in via\n * `__allowEditorVersionWritesForTests`, so they still cover the write path.\n */\nfunction isTestRunner(): boolean {\n if (_allowWriteInTests) return false\n if (process.env.BUN_TEST === \"1\" || process.env.NODE_ENV === \"test\") {\n return true\n }\n const entry = process.argv[1] ?? \"\"\n return /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(entry)\n}\n\n/** Set by the cache's own (sandboxed) tests so they can cover the write path. */\nlet _allowWriteInTests = false\n\n/**\n * Test-only: re-enable persistence. ONLY safe from a test that has redirected\n * `homedir()` to a temp dir — otherwise it writes the caller's fixture into the\n * developer's real cache and the proxy advertises it upstream.\n */\nexport function __allowEditorVersionWritesForTests(on: boolean): void {\n _allowWriteInTests = on\n}\n\nasync function readCache(): Promise<EditorVersionCache> {\n try {\n const parsed = JSON.parse(\n await fs.readFile(cacheFilePath(), \"utf8\"),\n ) as EditorVersionCache\n // A hand-edited or truncated file must degrade to \"no cache\", not throw.\n if (!parsed || typeof parsed !== \"object\") return {}\n return parsed\n } catch {\n return {}\n }\n}\n\nfunction isFresh(entry: CacheEntry | undefined): entry is CacheEntry {\n if (!entry || typeof entry.value !== \"string\" || entry.value.length === 0) {\n return false\n }\n const last = new Date(entry.checkedAt).getTime()\n if (Number.isNaN(last)) return false\n // A clock moved backwards would make `age` negative; treating that as stale\n // costs one refetch, whereas treating it as fresh could pin a bad value.\n const ageHours = (Date.now() - last) / 1000 / 3600\n return ageHours >= 0 && ageHours < TTL_HOURS\n}\n\n/**\n * Serializes the read-modify-write below.\n *\n * `setupAndServe` resolves both keys concurrently (`Promise.all`). Without\n * this, both callers would `readCache()` into their OWN object, spend ~1.5s in\n * their network fetch, and then write that stale object back — so whichever\n * finished last would clobber the other's entry, and one of the two versions\n * would re-fetch on every launch forever.\n *\n * The chain also re-reads immediately before mutating, so the write is against\n * current disk state rather than the snapshot taken before the fetch.\n */\nlet writeChain: Promise<void> = Promise.resolve()\n\nfunction serializeWrite(fn: () => Promise<void>): Promise<void> {\n const next = writeChain.then(fn, fn)\n // Never let a rejection poison the chain for later writers.\n writeChain = next.catch(() => {})\n return next\n}\n\n/**\n * Resolve `key` through the cache, calling `fetchFresh` only on a miss.\n *\n * `fetchFresh` signals failure by returning `undefined` — NOT by returning the\n * fallback constant. Inferring failure from `value === fallback` would break\n * exactly when the live version happens to equal the hardcoded constant, which\n * is the normal state right after someone bumps that constant to the\n * then-current version: the entry would never be written and every launch\n * would pay the ~1.5s fetch forever, silently defeating the cache.\n *\n * `fallback` is returned when the lookup fails and no usable cached value\n * exists. It is never persisted (invariant 1 above), so a transient outage\n * cannot freeze the version we impersonate.\n */\nexport async function resolveEditorVersion(\n key: EditorVersionKey,\n fetchFresh: () => Promise<string | undefined>,\n fallback: string,\n): Promise<string> {\n const entry = (await readCache())[key]\n const cachedValue = isFresh(entry) ? entry.value : undefined\n if (cachedValue !== undefined) return cachedValue\n\n const fetched = await fetchFresh()\n\n if (fetched !== undefined && fetched.length > 0) {\n // Never persist from a test process. The cached value is sent upstream as\n // the `editor-version` header, so a test that stubs the fetcher would\n // otherwise write its fixture into the DEVELOPER'S real cache and the\n // proxy would advertise it to Copilot for the full 12h TTL. That is not\n // hypothetical — a smoke test caught `editor-version: vscode/1.2.3` live\n // on this machine, sourced from a unit-test stub.\n //\n // Belt-and-braces with sandboxing the cache's own tests: any FUTURE test\n // that reaches this function through some other caller is covered too,\n // without every such test having to remember to mock homedir(). Reads stay\n // enabled, so warm-cache behavior is still exercisable.\n if (isTestRunner()) return fetched\n await serializeWrite(async () => {\n // Re-read INSIDE the chain: another key's write may have landed while\n // this one was in its fetch, and that entry must survive.\n const cache = await readCache()\n cache[key] = { value: fetched, checkedAt: new Date().toISOString() }\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n // A write failure only costs a refetch next launch.\n consola.debug(\"Failed to write editor-version cache:\", err)\n }\n })\n return fetched\n }\n\n // The lookup failed. A stale-but-real cached value beats the hardcoded\n // constant: a version that was genuinely current when it was cached is a\n // closer impersonation than one frozen at release time. Left un-restamped,\n // so the next launch still retries.\n if (typeof entry?.value === \"string\" && entry.value.length > 0) {\n return entry.value\n }\n return fallback\n}\n\n/** Test seam: the on-disk path, so tests can point HOME at a temp dir. */\nexport function editorVersionCachePath(): string {\n return cacheFilePath()\n}\n","import consola from \"consola\"\n\nimport { getModels } from \"~/services/copilot/get-models\"\nimport {\n COPILOT_CHAT_VERSION_FALLBACK,\n getCopilotChatVersionOrUndefined,\n} from \"~/services/get-copilot-version\"\nimport {\n getVSCodeVersionOrUndefined,\n VSCODE_VERSION_FALLBACK,\n} from \"~/services/get-vscode-version\"\n\nimport { resolveEditorVersion } from \"./editor-version-cache\"\nimport { state } from \"./state\"\n\nexport const sleep = (ms: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n\nexport const isNullish = (value: unknown): value is null | undefined =>\n value === null || value === undefined\n\n/**\n * Beta prefixes VS Code Copilot Chat v0.43 actually sends.\n * Default mode — makes proxy traffic indistinguishable from VS Code.\n */\nconst VSCODE_BETA_PREFIXES = [\n \"interleaved-thinking-\",\n \"context-management-\",\n \"advanced-tool-use-\",\n]\n\n/**\n * Extended beta prefixes for Claude CLI compatibility.\n * Enabled via --extended-betas flag. Includes all betas confirmed\n * to work with the Copilot API.\n *\n * Notably absent (Copilot 400s on these — verified live):\n * context-1m-, skills-, files-api-, code-execution-, output-128k-,\n * advisor-tool- (see EXPLICITLY_STRIPPED_BETA_PREFIXES below).\n * 1M context is unlocked by selecting `claude-opus-4.7-1m-internal`\n * as the model id, not via a beta header.\n *\n * Empirical verification (2026-05-11 against api.enterprise.githubcopilot.com):\n * task-budgets-2026-03-13 → 200 ACCEPTED (cost-ceiling leverage)\n * token-efficient-tools-2026-03-28 → 200 ACCEPTED (per-tool token saving)\n * summarize-connector-text-2026-03-13 → 200 (Anthropic-internal feature flag,\n * won't fire for non-ant users; allowlisted defensively for ant edge case)\n * afk-mode-2026-01-31 → 200 (Anthropic-internal feature flag)\n * cli-internal-2026-02-09 → 200 (USER_TYPE=ant only)\n * oauth-2025-04-20 → 200 (Files-API path; Files-API itself\n * is not supportable via Copilot, but the header alone is harmless)\n * prompt-caching-scope-2026-01-05 → 200 even with body cache_control.scope\n * stripped (already covered by `prompt-caching-` prefix above)\n */\nconst EXTENDED_BETA_PREFIXES = [\n ...VSCODE_BETA_PREFIXES,\n \"claude-code-\",\n \"effort-\",\n \"prompt-caching-\",\n \"computer-use-\",\n \"pdfs-\",\n \"max-tokens-\",\n \"token-counting-\",\n \"compact-\",\n \"structured-outputs-\",\n \"fast-mode-\",\n \"mcp-client-\",\n \"mcp-servers-\",\n \"redact-thinking-\",\n \"web-search-\",\n // Empirically accepted by Copilot, sent by Claude Code v2.1.138+\n \"task-budgets-\",\n \"token-efficient-tools-\",\n // Anthropic-internal feature flags (won't reach proxy from non-ant users\n // due to Bun build-time dead-code elimination, but allowlisted so the rare\n // ant-user / managed-deployment case flows cleanly).\n \"summarize-connector-text-\",\n \"afk-mode-\",\n \"cli-internal-\",\n \"oauth-\",\n]\n\n/**\n * Beta prefixes the proxy explicitly STRIPS even from the extended\n * allowlist (and even if a future leverage mode broadens the allowlist\n * further). Defensive layer: today's allowlist-only filter would already\n * drop these because they're not in any allowlist, but keeping an\n * explicit deny-list catches future changes that broaden allow rules\n * (e.g. a hypothetical pattern-based mode that lets `claude-*` through).\n *\n * Empirical (2026-05-11): Copilot returns HTTP 400\n * `unsupported beta header(s): advisor-tool-2026-03-01`\n * on every request that includes `advisor-tool-`. Stripping it is the\n * difference between a working request (no ADVISOR semantics) and a\n * fully-failed request. Document upstream limitation in CLAUDE.md.\n */\nconst EXPLICITLY_STRIPPED_BETA_PREFIXES = [\n \"advisor-tool-\",\n] as const\n\n/**\n * Filter an `anthropic-beta` header value, keeping only beta flags\n * in the active whitelist AND not in the explicit-strip list.\n * Uses extended prefixes when --extended-betas is enabled, VS Code-only\n * prefixes otherwise. Returns the filtered comma-separated string,\n * or undefined if nothing remains.\n */\nexport function filterBetaHeader(value: string): string | undefined {\n const prefixes = state.extendedBetas\n ? EXTENDED_BETA_PREFIXES\n : VSCODE_BETA_PREFIXES\n const filtered = value\n .split(\",\")\n .map((v) => v.trim())\n .filter(\n (v) =>\n v\n && prefixes.some((prefix) => v.startsWith(prefix))\n && !EXPLICITLY_STRIPPED_BETA_PREFIXES.some((p) => v.startsWith(p)),\n )\n .join(\",\")\n return filtered || undefined\n}\n\n/**\n * Normalize a model ID for fuzzy comparison: lowercase, replace dots with\n * dashes, insert dash at letter→digit boundaries, and collapse repeated\n * dashes. E.g. \"gpt5.3-codex\" → \"gpt-5-3-codex\", \"GPT-5.3-Codex\" → \"gpt-5-3-codex\".\n */\nexport function normalizeModelId(id: string): string {\n return id\n .toLowerCase()\n .replace(/\\./g, \"-\")\n .replace(/([a-z])(\\d)/g, \"$1-$2\")\n .replace(/-{2,}/g, \"-\")\n}\n\n/**\n * Resolve a model name to the best available variant in the Copilot model list.\n *\n * Resolution cascade:\n * 0. `[1m]` literal-bracket suffix: strip, delegate, warn if downgraded.\n * Bracketed slug must never reach Copilot (400s on it). See cc-backup\n * `src/utils/context.ts:35-40` for Claude Code's 1M unlock mechanism.\n * 1. Exact match\n * 2. Case-insensitive match\n * 3. Family preference (opus→1m, codex→highest version)\n * 4. Normalized match (dots→dashes, letter-digit boundaries)\n * 5. Anthropic dated-slug retry: if the input matches `claude-...-YYYYMMDD`,\n * strip the date and re-run the cascade once. Family-guarded so non-claude\n * 8-digit suffixes can't be mis-stripped; runs after Steps 1-4 so explicit\n * version pinning (a dated catalog id matched at Step 1) always wins.\n * 6. Return as-is with a warning\n */\n/**\n * `[1m]`-downgrade warnings we've already emitted this process. `resolveModel`\n * is called many times per launch (env setup, model validation, the banner,\n * and — under `serve` — on every model-picker `/models` poll), so the downgrade\n * notice is deduped to once per model id to avoid log spam.\n */\nconst warnedOneMDowngrade = new Set<string>()\n\n/** Test-only: clear the once-per-process `[1m]`-downgrade warning cache. */\nexport function __resetOneMDowngradeWarnings(): void {\n warnedOneMDowngrade.clear()\n}\n\nexport function resolveModel(modelId: string): string {\n const models = state.models?.data\n if (!models) return modelId\n\n // [1m] literal-bracket suffix: Claude Code's request for 1M context\n // accounting. cc-backup `src/utils/context.ts:35-40` has1mContext\n // matches `/\\[1m\\]/i`; getContextWindowForModel returns 1_000_000\n // when true. parseUserSpecifiedModel (model.ts:445-506) reattaches\n // the bracket after alias resolution, so Claude Code SENDS the\n // bracketed slug verbatim on the wire (`model: \"claude-opus-4-7[1m]\"`).\n // Copilot doesn't recognize the bracket → 400.\n //\n // Strip for the catalog lookup and delegate. If the stripped\n // resolution lands on a `-1m` variant (enterprise opus path via\n // family preference), perfect — the upstream call routes to the 1M\n // backend and Claude Code's local accounting was right. Otherwise\n // (non-enterprise for opus, or any [1m] on sonnet/haiku where\n // Copilot has no -1m backend), warn and return the 200K resolution\n // so the request still succeeds — at the cost of Claude Code\n // over-accounting context against the proxy (it will compact early\n // because it thinks the window is 1M).\n //\n // Bounded recursion: the stripped form no longer matches the regex,\n // so the inner resolveModel call cannot re-enter this branch.\n const oneMMatch = modelId.match(/^(.*)\\[1m\\]$/i)\n if (oneMMatch) {\n const stripped = oneMMatch[1]\n const resolved = resolveModel(stripped)\n // The resolved slug delivers 1M context either as a `-1m` variant OR\n // as a base slug that natively advertises a >=1M window (how opus-4.8\n // and opus-5 ship — a single slug, no `-1m` sibling). Only warn about a\n // real downgrade: a resolved model whose catalog window is under 1M.\n const resolvedIs1M =\n /-1m(?:$|-)/.test(resolved)\n || (models.find((m) => m.id === resolved)?.capabilities?.limits\n ?.max_context_window_tokens ?? 0) >= 1_000_000\n if (!resolvedIs1M && !warnedOneMDowngrade.has(modelId)) {\n warnedOneMDowngrade.add(modelId)\n consola.warn(\n `Model \"${modelId}\" requested 1M context but no 1M backend is in Copilot's catalog for this tier/family; downgrading upstream to \"${resolved}\" (200K). Claude Code's local context accounting will still assume 1M — expect premature auto-compact. Drop the [1m] suffix (or unset CLAUDE_CODE_DISABLE_1M_CONTEXT if you set it) to silence.`,\n )\n }\n return resolved\n }\n\n // 1. Exact match\n if (models.some((m) => m.id === modelId)) return modelId\n\n // 2. Case-insensitive match\n const lower = modelId.toLowerCase()\n const ciMatch = models.find((m) => m.id.toLowerCase() === lower)\n if (ciMatch) return ciMatch.id\n\n // 3. Family preference — before normalization so product aliases\n // (opus→1m, codex→latest) take priority over fuzzy matches\n if (lower.includes(\"opus\")) {\n // Match ...-1m or ...-1m-<anything> (e.g. claude-opus-4.7-1m-internal).\n // Prefer the 1M variant whose major.minor matches the requested version,\n // otherwise find() would silently downgrade claude-opus-4.7 to a\n // claude-opus-4.6-1m if the latter happens to come first in the list.\n // Accept both dotted (\"opus-4.7\") and dashed (\"opus-4-7\") inputs —\n // Claude Code historically sends the dashed form.\n const oneMs = models.filter(\n (m) => m.id.includes(\"opus\") && /-1m(?:$|-)/.test(m.id),\n )\n // Capture the requested version. The minor segment is OPTIONAL so a\n // single-segment slug like `claude-opus-5` registers as a specific\n // version (\"5\") rather than falling through to the `oneMs[0]` wildcard\n // below — which would silently downgrade a catalog-absent `claude-opus-5`\n // to the first unrelated opus `-1m` sibling (e.g. claude-opus-4.6-1m).\n const versionMatch = lower.match(/opus-(\\d+)(?:[.-](\\d+))?/)\n const requestedVersion = versionMatch\n ? versionMatch[2]\n ? `${versionMatch[1]}.${versionMatch[2]}`\n : versionMatch[1]\n : undefined\n const preferred = requestedVersion\n ? oneMs.find((m) => m.id.includes(`opus-${requestedVersion}-`))\n : undefined\n // When a specific version was requested (e.g. \"claude-opus-4-8\") but\n // no matching 1M variant exists in the catalog, do NOT fall back to a\n // different version's 1M variant — that silently downgrades (e.g.\n // 4.8 → 4.6-1m). Instead, fall through to step 4 (normalization)\n // which will resolve the bare dotted entry (claude-opus-4.8).\n const oneM = preferred ?? (requestedVersion ? undefined : oneMs[0])\n if (oneM) return oneM.id\n }\n\n if (lower.includes(\"codex\")) {\n const codexModels = models.filter(\n (m) => m.id.includes(\"codex\") && !m.id.includes(\"mini\"),\n )\n if (codexModels.length > 0) {\n codexModels.sort((a, b) => b.id.localeCompare(a.id))\n return codexModels[0].id\n }\n }\n\n // 4. Normalized match (dots → dashes, letter-digit boundaries)\n const normalized = normalizeModelId(modelId)\n const normMatch = models.find(\n (m) => normalizeModelId(m.id) === normalized,\n )\n if (normMatch) return normMatch.id\n\n // 5. Anthropic dated-slug retry. Claude Code's /model UI ships Anthropic's\n // published slugs (e.g. \"claude-haiku-4-5-20251001\") that carry a\n // -YYYYMMDD suffix Copilot's catalog doesn't use. Strip the date and\n // re-run the cascade once so the request maps to the floating tag\n // (claude-haiku-4.5). Family-guarded to `claude-` so a hypothetical\n // \"gpt-...-20260101\" can't be silently stripped. Bounded recursion:\n // the stripped id no longer matches the regex, so the retry's own\n // Step 5 is a no-op.\n const dateStripped = modelId.replace(/^(claude-[\\w.-]+)-20\\d{6}$/i, \"$1\")\n if (dateStripped !== modelId) {\n const retried = resolveModel(dateStripped)\n // resolveModel returns the input unchanged on miss; treat unchanged-and-\n // not-in-catalog as miss to avoid logging a misleading \"resolved\" hop.\n const retryHit =\n retried !== dateStripped || models.some((m) => m.id === dateStripped)\n if (retryHit) {\n consola.info(\n `Resolved Anthropic dated slug \"${modelId}\" → \"${retried}\" (stripped -YYYYMMDD; pass an explicit catalog id to pin a snapshot)`,\n )\n return retried\n }\n }\n\n // 6. Legacy family fallback. Claude Code's settings.json may pin slugs\n // whose Copilot equivalent does not exist (e.g. claude-3-7-sonnet-20250219\n // or claude-sonnet-4-0 — neither is in Copilot's enterprise catalog as\n // of 2026-05-11; a request for either returns HTTP 400 \"model not\n // supported\"). Step 5's dated-retry strips the date but the resulting\n // \"claude-3-7-sonnet\" still has no Copilot equivalent. Rather than\n // dead-end the request, fall back to the highest available family\n // member (sonnet → highest sonnet, haiku → highest haiku). Surfaces\n // via consola.info so the user sees the substitution. Opus is already\n // handled by the family preference in Step 3.\n //\n // Guards (codex-reviewer findings):\n // (a) Family fires only for `claude-` prefixed inputs — protects\n // against custom-sonnet-future or any non-Anthropic provider\n // coincidentally containing \"sonnet\"/\"haiku\" in its slug.\n // (b) Family token must be word-bounded (`-sonnet-` / `-sonnet$`)\n // so a hypothetical claude-supersonnet-* doesn't match.\n // (c) Sort uses numeric collation (`{numeric: true}`) so a future\n // claude-sonnet-4.10 sorts higher than claude-sonnet-4.6\n // (lexicographic alone would invert).\n if (lower.startsWith(\"claude-\")) {\n const matchSonnet = /(?:^|-)sonnet(?:-|$)/.test(lower)\n const matchHaiku = /(?:^|-)haiku(?:-|$)/.test(lower)\n if (matchSonnet || matchHaiku) {\n const family = matchSonnet ? \"sonnet\" : \"haiku\"\n const familyMembers = models.filter((m) =>\n new RegExp(`(?:^|-)${family}(?:-|$|\\\\.)`).test(m.id),\n )\n if (familyMembers.length > 0) {\n familyMembers.sort((a, b) =>\n b.id.localeCompare(a.id, undefined, { numeric: true }),\n )\n const best = familyMembers[0].id\n consola.info(\n `Model \"${modelId}\" not in Copilot catalog; falling back to highest available \"${best}\" (legacy ${family} slug). Pin a current catalog id to silence.`,\n )\n return best\n }\n }\n }\n\n // 7. No match — warn and return as-is\n consola.warn(\n `Model \"${modelId}\" not found in Copilot model list. Available: ${models.map((m) => m.id).join(\", \")}`,\n )\n return modelId\n}\n\n/**\n * Resolve a codex model ID, falling back to the best available codex model.\n * Used by the codex subcommand for model selection.\n */\nexport function resolveCodexModel(modelId: string): string {\n const resolved = resolveModel(modelId)\n const models = state.models?.data\n if (!models) return resolved\n\n // Check if the resolved model exists in the model list\n if (models.some((m) => m.id === resolved)) return resolved\n\n // Fall back to the best available codex-class model. The /responses\n // endpoint is the discriminator — gpt-5.5 dropped the -codex suffix but\n // still routes through /responses. Prefer explicit -codex ids when both\n // exist, otherwise pick the highest version-like id.\n const candidates = models.filter((m) => {\n const endpoints = m.supported_endpoints ?? []\n if (m.id.includes(\"mini\") || m.id.includes(\"nano\")) return false\n return endpoints.length === 0 || endpoints.includes(\"/responses\")\n })\n\n if (candidates.length > 0) {\n candidates.sort((a, b) => {\n const aCodex = a.id.includes(\"codex\") ? 1 : 0\n const bCodex = b.id.includes(\"codex\") ? 1 : 0\n if (aCodex !== bCodex) return bCodex - aCodex\n return b.id.localeCompare(a.id)\n })\n const best = candidates[0].id\n consola.warn(`Model \"${modelId}\" not available, using \"${best}\" instead`)\n return best\n }\n\n return resolved\n}\n\nexport async function cacheModels(): Promise<void> {\n const models = await getModels()\n state.models = models\n}\n\nexport const cacheVSCodeVersion = async () => {\n const response = await resolveEditorVersion(\n \"vscode\",\n getVSCodeVersionOrUndefined,\n VSCODE_VERSION_FALLBACK,\n )\n state.vsCodeVersion = response\n\n consola.info(`Using VSCode version: ${response}`)\n}\n\nexport const cacheCopilotVersion = async () => {\n const version = await resolveEditorVersion(\n \"copilotChat\",\n getCopilotChatVersionOrUndefined,\n COPILOT_CHAT_VERSION_FALLBACK,\n )\n state.copilotVersion = version\n\n consola.info(`Using Copilot Chat version: ${version}`)\n}\n","import consola from \"consola\"\n\nimport {\n GITHUB_BASE_URL,\n GITHUB_CLIENT_ID,\n standardHeaders,\n} from \"~/lib/api-config\"\nimport { sleep } from \"~/lib/utils\"\n\nimport type { DeviceCodeResponse } from \"./get-device-code\"\n\n/**\n * Per-attempt cap for a single device-code poll.\n *\n * Deliberately NOT the shared transient-retry layer: a non-OK response here is\n * the EXPECTED steady state (`authorization_pending` until the user finishes in\n * their browser), so retrying it as a transient fault would just hammer GitHub\n * inside a loop that is already a retry loop with its own interval.\n *\n * What was genuinely missing is a bound on a single attempt. Without a signal a\n * hung socket blocks the loop forever: the `expiresAt` check only runs between\n * attempts, so it can never fire while one attempt is stuck. This caps each\n * attempt so the loop keeps ticking and the expiry bound stays real.\n */\nconst POLL_ATTEMPT_TIMEOUT_MS = 30_000\n\nexport async function pollAccessToken(\n deviceCode: DeviceCodeResponse,\n clientId: string = GITHUB_CLIENT_ID,\n): Promise<string> {\n // Interval is in seconds, we need to multiply by 1000 to get milliseconds\n // I'm also adding another second, just to be safe\n const sleepDuration = (deviceCode.interval + 1) * 1000\n consola.debug(`Polling access token with interval of ${sleepDuration}ms`)\n const expiresAt = Date.now() + deviceCode.expires_in * 1000\n // Remembered so a permanent misconfiguration (bad DNS, TLS interception, a\n // blocking proxy) is reported as itself rather than surfacing as a bare\n // \"device code expired\" after the full window has silently burned.\n let lastFetchError: unknown\n\n while (Date.now() < expiresAt) {\n let response: Response\n try {\n response = await fetch(`${GITHUB_BASE_URL}/login/oauth/access_token`, {\n method: \"POST\",\n headers: standardHeaders(),\n body: JSON.stringify({\n client_id: clientId,\n device_code: deviceCode.device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n signal: AbortSignal.timeout(POLL_ATTEMPT_TIMEOUT_MS),\n })\n } catch (err) {\n // A timed-out or failed attempt is not fatal — the device code may still\n // be authorized before it expires, so keep polling until it does.\n lastFetchError = err\n consola.debug(\"Access-token poll attempt failed; retrying:\", err)\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n continue\n }\n\n // Reaching here means the transport worked, whatever the HTTP status. Clear\n // any earlier transport failure so a transient blip mid-flow cannot make\n // the final message blame the network for a genuine expiry.\n lastFetchError = undefined\n\n if (!response.ok) {\n consola.error(\"Failed to poll access token:\", await response.text())\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n continue\n }\n\n const json = await response.json()\n consola.debug(\"Polling access token response:\", json)\n\n const { access_token } = json as AccessTokenResponse\n\n if (access_token) {\n return access_token\n }\n\n if (Date.now() >= expiresAt) break\n await sleep(sleepDuration)\n }\n\n // If every attempt failed at the transport layer, the device code almost\n // certainly did NOT expire — the network did. Report that, with the real\n // error as `cause`, so a misconfigured proxy or TLS setup is diagnosable\n // instead of masquerading as a timing problem.\n if (lastFetchError !== undefined) {\n throw new Error(\n \"Could not reach GitHub to complete device-code authorization. Check network/proxy/TLS settings and run auth again.\",\n { cause: lastFetchError },\n )\n }\n throw new Error(\"Device code expired. Please run auth again.\")\n}\n\ninterface AccessTokenResponse {\n access_token: string\n token_type: string\n scope: string\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\n\nimport { PATHS } from \"~/lib/paths\"\nimport { getCopilotToken } from \"~/services/github/get-copilot-token\"\nimport { getDeviceCode } from \"~/services/github/get-device-code\"\nimport { getGitHubUser } from \"~/services/github/get-user\"\nimport { pollAccessToken } from \"~/services/github/poll-access-token\"\n\nimport {\n GITHUB_AGENT_CLIENT_ID,\n GITHUB_AGENT_SCOPES,\n GITHUB_API_BASE_URL,\n githubAgentHeaders,\n} from \"./api-config\"\nimport { HTTPError } from \"./error\"\nimport { state } from \"./state\"\n\nconst readGithubToken = () => fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n\n/**\n * Backoff for a transient Windows rename failure. On Windows `fs.rename` over\n * an existing destination transiently fails with EPERM / EBUSY / EACCES when\n * anything else holds the target open for a moment (antivirus, the search\n * indexer, a backup agent). Nothing is wrong and the handle closes microseconds\n * later — but without a retry, a scan landing on the wrong millisecond throws\n * out of a credential write and costs the user a re-auth. Same delays as\n * `renameWithRetry` in `~/lib/claude-md-injection`, which documents the\n * underlying behavior at length.\n */\nconst RENAME_RETRY_DELAYS_MS = [50, 200, 500] as const\n\n/**\n * Replace a credential file atomically: temp + rename, with bounded retry.\n *\n * A plain `fs.writeFile` truncates the destination before it writes, so a\n * crash, a full disk, or a kill mid-write leaves a truncated token on disk and\n * forces the user through a re-auth. `rename` within the same directory is\n * atomic on both NTFS and POSIX, so a reader sees either the old token or the\n * new one, never a partial.\n *\n * The temp name uses `randomBytes`, not `Math.random()`: this names a file that\n * briefly holds a credential, and a predictable name in a shared directory\n * invites a pre-creation race. Combined with `flag: \"wx\"` (fail if it exists)\n * the write refuses to follow anything an attacker pre-placed, rather than\n * silently writing the token through a planted symlink.\n *\n * Permissions: the temp file is created 0o600, and `rename` carries that mode\n * with it on POSIX — so the destination's mode is preserved, not weakened.\n * (On Windows `chmod` is a no-op anyway; see `chmodIfPossible` in `~/lib/paths`.\n * Both token files live under `CLAUDE_RUNTIME_DIR`, which is chmod'd 0o700, so\n * directory ACLs are what actually protect them there.)\n */\nasync function writeTokenFileAtomic(\n filePath: string,\n token: string,\n): Promise<void> {\n const tmp = `${filePath}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`\n try {\n await fs.writeFile(tmp, token, { mode: 0o600, flag: \"wx\" })\n\n let lastErr: unknown\n let renamed = false\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) {\n try {\n await fs.rename(tmp, filePath)\n renamed = true\n break\n } catch (err) {\n lastErr = err\n // Don't sleep after the final attempt.\n if (attempt < RENAME_RETRY_DELAYS_MS.length) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n }\n // A persistent failure (permissions, full disk) still throws: the caller\n // must not believe a credential was stored when it was not.\n if (!renamed) throw lastErr\n } catch (err) {\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n}\n\nconst writeGithubToken = (token: string) =>\n writeTokenFileAtomic(PATHS.GITHUB_TOKEN_PATH, token)\n\nconst readGithubAgentToken = () =>\n fs.readFile(PATHS.GITHUB_AGENT_TOKEN_PATH, \"utf8\")\n\nconst writeGithubAgentToken = (token: string) =>\n writeTokenFileAtomic(PATHS.GITHUB_AGENT_TOKEN_PATH, token)\n\n/**\n * Stops the background Copilot-token refresh started by\n * {@link setupCopilotToken}. Idempotent.\n */\nexport type StopCopilotTokenRefresh = () => void\n\n/**\n * Fetch the Copilot token and keep it fresh in the background.\n *\n * Returns a disposer that stops the refresh loop. **Long-lived callers**\n * (`start`/`claude`/`codex`, via `setupAndServe`) can ignore it — the interval\n * is `unref()`d, so it never holds the event loop open on its own. The one-shot\n * `models` command calls it, so ownership of the timer is explicit rather than\n * implied by a runtime flag. (`check-usage` does not call this function at all;\n * it only needs `setupGitHubToken`.)\n *\n * Both halves are load-bearing, for different failure modes. Without the\n * `unref()`, `github-router models` printed its full correct output and then\n * hung forever: its success path just returns (only the failure branches call\n * `process.exit`), and the un-unref'd interval pinned the event loop. Without\n * the disposer, that fix would depend on a property no caller can see, so the\n * next one-shot command would inherit the same trap.\n */\nexport const setupCopilotToken = async (): Promise<StopCopilotTokenRefresh> => {\n const { token, refresh_in } = await getCopilotToken()\n state.copilotToken = token\n\n // Display the Copilot token to the screen\n consola.debug(\"GitHub Copilot Token fetched successfully!\")\n if (state.showToken) {\n consola.info(\"Copilot token:\", token)\n }\n\n const refreshInterval = Math.max((refresh_in - 60) * 1000, 1000)\n const handle = setInterval(() => {\n void refreshCopilotToken(\"interval\")\n }, refreshInterval)\n // A refresh timer is not a reason for the process to stay alive; it exists\n // to serve work that is already keeping it alive.\n handle.unref?.()\n\n let stopped = false\n return () => {\n if (stopped) return\n stopped = true\n clearInterval(handle)\n }\n}\n\n// Single-flight mutex around the refresh fetch. Concurrent triggers (interval\n// + a 401-retry path) share one in-flight refresh promise so we never\n// overlap network calls or race writes to state.copilotToken.\nlet inflightRefresh: Promise<void> | undefined\n// Cooldowns are keyed off the OUTCOME of the last refresh, not the attempt:\n// - lastRefreshSuccess: throttles 401-retries when the token is fresh\n// (don't pointlessly re-fetch a token we just got).\n// - lastRefreshFailure: shorter backoff so a transient upstream blip\n// doesn't suppress legitimate refresh attempts for a full 30s, but\n// still prevents a thundering-herd refresh-storm against an upstream\n// that's persistently failing.\nlet lastRefreshSuccess = 0\nlet lastRefreshFailure = 0\nconst REFRESH_SUCCESS_COOLDOWN_MS = 30_000\nconst REFRESH_FAILURE_COOLDOWN_MS = 5_000\n\nexport async function refreshCopilotToken(\n reason: \"interval\" | \"401-retry\",\n): Promise<void> {\n if (inflightRefresh) return inflightRefresh\n // Refresh-storm protection: if a recent refresh already completed,\n // decline new 401-retry attempts. Interval refreshes always proceed\n // (they're spaced by `refresh_in - 60s` which is well outside the\n // window). 401-retry attempts respect both cooldowns:\n // - skip if a refresh succeeded within the last 30s (token is fresh)\n // - skip if a refresh failed within the last 5s (back off briefly)\n if (reason === \"401-retry\") {\n const now = Date.now()\n if (now - lastRefreshSuccess < REFRESH_SUCCESS_COOLDOWN_MS) {\n consola.debug(\n `refreshCopilotToken(${reason}) skipped: prior success within ${REFRESH_SUCCESS_COOLDOWN_MS}ms`,\n )\n return\n }\n if (now - lastRefreshFailure < REFRESH_FAILURE_COOLDOWN_MS) {\n consola.debug(\n `refreshCopilotToken(${reason}) skipped: prior failure within ${REFRESH_FAILURE_COOLDOWN_MS}ms`,\n )\n return\n }\n }\n\n inflightRefresh = (async () => {\n consola.debug(`Refreshing Copilot token (reason=${reason})`)\n try {\n const { token } = await getCopilotToken()\n state.copilotToken = token\n lastRefreshSuccess = Date.now()\n consola.debug(\"Copilot token refreshed\")\n if (state.showToken) {\n consola.info(\"Refreshed Copilot token:\", token)\n }\n } catch (error) {\n lastRefreshFailure = Date.now()\n consola.error(\n `Failed to refresh Copilot token (reason=${reason}):`,\n error,\n )\n } finally {\n inflightRefresh = undefined\n }\n })()\n return inflightRefresh\n}\n\n/**\n * Try `request()`. If it returns a 401, refresh the Copilot token (subject\n * to the single-flight + refresh-storm-protection of `refreshCopilotToken`)\n * and retry once. After one retry, propagate whatever the second attempt\n * returned — the caller's existing 401-handling path is preserved.\n *\n * The `request` callback is responsible for capturing `state.copilotToken`\n * locally before any await; this helper does NOT re-build the request\n * itself, just re-invokes the callback after a refresh.\n */\nexport async function tryRefreshAndRetry(\n request: () => Promise<Response>,\n routePath: string,\n): Promise<Response> {\n const first = await request()\n if (first.status !== 401) return first\n\n consola.warn(\n `${routePath}: upstream returned 401, attempting one token refresh + retry`,\n )\n await refreshCopilotToken(\"401-retry\")\n // Re-invoke the request with the (possibly) new token in state.\n return request()\n}\n\ninterface SetupGitHubTokenOptions {\n force?: boolean\n}\n\nexport async function setupGitHubToken(\n options?: SetupGitHubTokenOptions,\n): Promise<void> {\n try {\n const githubToken = await readGithubToken()\n\n if (githubToken && !options?.force) {\n state.githubToken = githubToken\n if (state.showToken) {\n consola.info(\"GitHub token:\", githubToken)\n }\n await logUser()\n\n return\n }\n\n consola.info(\"Not logged in, getting new access token\")\n const response = await getDeviceCode()\n consola.debug(\"Device code response:\", response)\n\n consola.info(\n `Please enter the code \"${response.user_code}\" in ${response.verification_uri}`,\n )\n\n const token = await pollAccessToken(response)\n await writeGithubToken(token)\n state.githubToken = token\n\n if (state.showToken) {\n consola.info(\"GitHub token:\", token)\n }\n await logUser()\n } catch (error) {\n if (error instanceof HTTPError) {\n consola.error(\"Failed to get GitHub token:\", await error.response.json())\n throw error\n }\n\n consola.error(\"Failed to get GitHub token:\", error)\n throw error\n }\n}\n\nasync function logUser() {\n const user = await getGitHubUser()\n consola.info(`Logged in as ${user.login}`)\n}\n\n/**\n * Set up the SECOND, write-capable GitHub token used by the first-mate\n * agent-orchestration surface (`--agents`). Mirrors `setupGitHubToken`\n * but authenticates against the GitHub CLI's OAuth client\n * (`GITHUB_AGENT_CLIENT_ID`) requesting `repo workflow read:org`, and\n * stores the result apart at `PATHS.GITHUB_AGENT_TOKEN_PATH`. The Copilot\n * App token (`state.githubToken`) is left completely untouched — this is\n * a distinct identity for a distinct capability.\n *\n * Long-lived (device-flow user token) → no refresh loop; a later 401 is\n * surfaced to the caller as a revoked grant to re-run the login. Called\n * once from `setupAndServe` when `state.agentsEnabled` is true.\n */\nexport async function setupGitHubAgentToken(\n options?: SetupGitHubTokenOptions,\n): Promise<void> {\n try {\n const existing = (await readGithubAgentToken().catch(() => \"\")).trim()\n\n if (existing && !options?.force) {\n state.githubAgentToken = existing\n if (state.showToken) {\n consola.info(\"GitHub agent token:\", existing)\n }\n await warnIfAgentScopesInsufficient()\n return\n }\n\n consola.info(\n \"Agent mode (--agents): a second GitHub login is required for a write-capable token (repo, workflow, read:org).\",\n )\n const response = await getDeviceCode({\n clientId: GITHUB_AGENT_CLIENT_ID,\n scope: GITHUB_AGENT_SCOPES,\n })\n consola.debug(\"Agent device code response:\", response)\n\n consola.info(\n `Please enter the code \"${response.user_code}\" in ${response.verification_uri} to authorize github-router's cloud-agent orchestration to act on your repositories.`,\n )\n\n const token = await pollAccessToken(response, GITHUB_AGENT_CLIENT_ID)\n await writeGithubAgentToken(token)\n state.githubAgentToken = token\n\n if (state.showToken) {\n consola.info(\"GitHub agent token:\", token)\n }\n await warnIfAgentScopesInsufficient()\n } catch (error) {\n if (error instanceof HTTPError) {\n consola.error(\n \"Failed to get GitHub agent token:\",\n await error.response.json(),\n )\n throw error\n }\n\n consola.error(\"Failed to get GitHub agent token:\", error)\n throw error\n }\n}\n\n/**\n * Best-effort check that the agent token actually carries the scopes we\n * asked for. The GitHub CLI OAuth client is a classic OAuth App, so the\n * granted scopes are echoed in the `x-oauth-scopes` response header on\n * any authenticated call. Warn loudly (not fatal) if `repo`/`workflow`\n * are missing so the failure is diagnosable at login rather than at the\n * first write 403.\n */\nasync function warnIfAgentScopesInsufficient(): Promise<void> {\n try {\n const res = await fetch(`${GITHUB_API_BASE_URL}/user`, {\n headers: githubAgentHeaders(state),\n })\n if (res.status === 401) {\n consola.warn(\n \"GitHub agent token was rejected (401) — the grant may have been revoked. Re-run with --agents to log in again.\",\n )\n return\n }\n const scopes = (res.headers.get(\"x-oauth-scopes\") ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n const missing = [\"repo\", \"workflow\"].filter((s) => !scopes.includes(s))\n if (missing.length > 0) {\n consola.warn(\n `GitHub agent token is missing scope(s): ${missing.join(\", \")}. `\n + \"The first-mate surface needs 'repo' + 'workflow' to create issues, \"\n + \"assign cloud agents, and dispatch workflows. Re-run the agent login \"\n + \"and grant the requested scopes.\",\n )\n }\n } catch (err) {\n consola.debug(\"Agent token scope check skipped:\", err)\n }\n}\n"],"mappings":";;;;;;;AAsHA,MAAa,QAAe;CAC1B,aAAa;CACb,eAAe;CACf,eAAe;CACf,WAAW;CACX,eAAe;CACf,eAAe;CACf,cAAc;CACd,eAAe;CACf,oBAAoB;CACpB,gBAAgB;CAChB,WAAW,WAAW;CACtB,WAAW,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;AAC3C;;;AC/HA,MAAa,yBAAyB;CACpC,gBAAgB;CAChB,QAAQ;AACV;AAEA,MAAM,0BAA0B;AAEhC,SAAgB,eAAe,OAAsB;CACnD,OAAO,MAAM,kBAAkB;AACjC;AAEA,MAAM,cAAc;AAEpB,MAAa,kBAAkB,UAC7B,MAAM,iBAAiB;AACzB,MAAa,kBACX,OACA,SAAkB,OAClB,gBAAwB,kBACrB;CACH,MAAM,UAAU,eAAe,KAAK;CACpC,MAAM,UAAkC;EACtC,eAAe,UAAU,MAAM;EAC/B,gBAAgB,gBAAgB,CAAC,CAAC;EAClC,0BAA0B;EAC1B,kBAAkB,UAAU,MAAM;EAClC,yBAAyB,gBAAgB;EACzC,cAAc,qBAAqB;EACnC,iBAAiB;EACjB,sBAAsB;EACtB,wBAAwB;EACxB,gBAAgB,WAAW;EAC3B,uCAAuC;EACvC,oBAAoB,MAAM;EAC1B,oBAAoB,MAAM;CAC5B;CAEA,IAAI,QAAQ,QAAQ,4BAA4B;CAEhD,OAAO;AACT;AAEA,MAAa,sBACX,QAAQ,IAAI,kBAAkB;AAChC,MAAa,iBAAiB,WAAkB;CAC9C,GAAG,gBAAgB;CACnB,eAAe,SAAS,MAAM;CAC9B,kBAAkB,UAAU,MAAM;CAClC,yBAAyB,gBAAgB,eAAe,KAAK;CAC7D,cAAc,qBAAqB,eAAe,KAAK;CACvD,wBAAwB;CACxB,uCAAuC;AACzC;AAEA,MAAa,kBAAkB;AAC/B,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QAAQ,MAAM,+BAA+B,QAAQ;EAErD,QAAQ,KACN,0BAA0B,SAAS,UAAU,OAAO,SAAS,iBAAiB,qFAChF;EAEA,MAAM,QAAQ,MAAM,gBAAgB,UAAU,sBAAsB;EACpE,MAAM,sBAAsB,KAAK;EACjC,MAAM,mBAAmB;EAEzB,IAAI,MAAM,WACR,QAAQ,KAAK,uBAAuB,KAAK;EAE3C,MAAM,8BAA8B;CACtC,SAAS,OAAO;EACd,IAAI,iBAAiB,WAAW;GAC9B,QAAQ,MACN,qCACA,MAAM,MAAM,SAAS,KAAK,CAC5B;GACA,MAAM;EACR;EAEA,QAAQ,MAAM,qCAAqC,KAAK;EACxD,MAAM;CACR;AACF;;;;;;;;;AAUA,eAAe,gCAA+C;CAC5D,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,GAAG,oBAAoB,QAAQ,EACrD,SAAS,mBAAmB,KAAK,EACnC,CAAC;EACD,IAAI,IAAI,WAAW,KAAK;GACtB,QAAQ,KACN,gHACF;GACA;EACF;EACA,MAAM,UAAU,IAAI,QAAQ,IAAI,gBAAgB,KAAK,GAAA,CAClD,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO;EACjB,MAAM,UAAU,CAAC,QAAQ,UAAU,CAAC,CAAC,QAAQ,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;EACtE,IAAI,QAAQ,SAAS,GACnB,QAAQ,KACN,2CAA2C,QAAQ,KAAK,IAAI,EAAE,yKAIhE;CAEJ,SAAS,KAAK;EACZ,QAAQ,MAAM,oCAAoC,GAAG;CACvD;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "github-router",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.270",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.",
|
|
6
6
|
"keywords": [
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"release": "./publish/release.sh",
|
|
43
43
|
"start": "NODE_ENV=production bun run ./src/main.ts",
|
|
44
44
|
"test": "bun run build && bun scripts/run-tests.ts",
|
|
45
|
-
"typecheck": "tsc",
|
|
45
|
+
"typecheck": "tsc && tsc -p tsconfig.browser.json",
|
|
46
46
|
"verify:serve": "node scripts/verify-serve-session.mjs",
|
|
47
47
|
"verify:plan-mode": "node scripts/verify-plan-mode-cloudcli.mjs"
|
|
48
48
|
},
|
package/dist/engine-D8dlcSW6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"exec-DTO2oin0.js","names":[],"sources":["../src/lib/exec.ts"],"sourcesContent":["/**\n * Windows-safe, injection-safe command execution helpers.\n *\n * Why this module exists: on Windows, npm-installed CLIs (`claude`,\n * `npm`, `codex`) are `.cmd`/`.bat` shims. Node's `execFile`/`spawn`\n * with `shell:false` cannot launch them (CreateProcess only resolves\n * `.exe`), so callers must go through `cmd.exe` (`shell:true`). That in\n * turn opens two hazards this module closes:\n *\n * 1. **Metacharacter injection** (`& | < > ^ ( ) ! %`). A naive\n * \"quote only tokens with spaces\" scheme lets `pkg@latest&calc`\n * run `calc` as a second command. `buildExecInvocation` applies\n * real cmd.exe quoting (argv-quote + caret-escape) and fails\n * closed on `%` (which cannot be reliably escaped on the cmd\n * command line).\n *\n * 2. **CWD shadowing.** `cmd.exe` resolves a bare `npm` from the\n * current directory before PATH, so an untrusted repo can plant\n * `npm.cmd`. `resolveExecutable` resolves to an absolute path\n * against PATH only (honoring PATHEXT), never the cwd, so callers\n * spawn the real binary by absolute path.\n *\n * All runners are best-effort and timeout-bounded; callers wrap in\n * try/catch and never let an update/probe failure block launch.\n */\n\nimport { spawn, spawnSync, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\n/**\n * Parse a boolean-ish env value. Returns `undefined` when unset or\n * unrecognized so callers can apply their own default. Accepts\n * `1|true|yes|on` (true) and `0|false|no|off|<empty>` (false),\n * case-insensitive. The single shared parser for all new `GH_ROUTER_*`\n * flags so on/off semantics don't drift per call site.\n */\nexport function parseBoolEnv(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined\n const v = value.trim().toLowerCase()\n if (v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\") return true\n if (v === \"0\" || v === \"false\" || v === \"no\" || v === \"off\" || v === \"\") {\n return false\n }\n return undefined\n}\n\n/**\n * Parse a positive-integer env value. Returns `undefined` when unset, empty, or\n * not a clean positive integer, so callers apply their own default.\n *\n * The single shared parser for numeric `GH_ROUTER_*` knobs, and it deliberately\n * uses `Number()` rather than `parseInt()`. `parseInt` stops at the first\n * character it cannot consume, so it silently truncates instead of rejecting:\n * `\"3e5\"` becomes 3, `\"300_000\"` becomes 300, `\"60000ms\"` becomes 60000. For a\n * timeout or a concurrency cap that is the worst possible failure — a user who\n * writes `GH_ROUTER_STOP_GATE_TIMEOUT_MS=3e5` intending five minutes gets three\n * MILLISECONDS, and the resulting instant failure looks like a product bug\n * rather than a typo. Falling back to the documented default is strictly safer\n * than honouring a number the user never meant.\n *\n * Found by a cross-lab reviewer during a capability audit, at three shipped call\n * sites, while three separate local helpers in this repo already parsed the same\n * shape correctly and one of them documented this exact hazard. That is the\n * argument for one shared parser rather than a fourth copy.\n */\nexport function parseIntEnv(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const raw = value.trim()\n if (raw === \"\") return undefined\n const n = Number(raw)\n if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return undefined\n return n\n}\n\n/** Read the PATH value from an env object, case-insensitively. */\nfunction pathValueOf(env: NodeJS.ProcessEnv): string {\n for (const key of Object.keys(env)) {\n if (key.toLowerCase() === \"path\") return env[key] ?? \"\"\n }\n return \"\"\n}\n\nexport interface ResolveExecutableOpts {\n env?: NodeJS.ProcessEnv\n platform?: NodeJS.Platform\n /** Directory to treat as \"current dir\" and exclude from resolution. */\n cwd?: string\n}\n\n/**\n * Resolve an executable name to an absolute path against PATH, honoring\n * `PATHEXT` on Windows and **excluding the current working directory**.\n *\n * Returns `null` when unresolved — callers treat that as \"tool absent\"\n * and skip (best-effort). Spawning the returned absolute path means\n * `cmd.exe`'s implicit cwd-first lookup never applies, closing the\n * planted-`npm.cmd` vector.\n */\nexport function resolveExecutable(\n name: string,\n opts: ResolveExecutableOpts = {},\n): string | null {\n const platform = opts.platform ?? process.platform\n const env = opts.env ?? process.env\n // Defensive: some test harnesses mock `node:process` without `cwd`.\n // Absent a usable cwd we simply skip the cwd-exclusion guard (the\n // returned absolute path already bypasses cmd.exe's cwd-first lookup).\n const cwdRaw =\n opts.cwd ?? (typeof process.cwd === \"function\" ? process.cwd() : undefined)\n const resolvedCwd = cwdRaw ? path.resolve(cwdRaw) : null\n\n const dirs = pathValueOf(env)\n .split(path.delimiter)\n // Drop empty entries and a literal \".\" — both denote the cwd on\n // Windows, which we explicitly refuse to resolve against.\n .filter((d) => d.length > 0 && d !== \".\")\n\n const isWin = platform === \"win32\"\n\n // POSIX: an explicit path component → resolve directly.\n if (!isWin && name.includes(\"/\")) {\n return existsSync(name) ? path.resolve(name) : null\n }\n // Windows: an explicit path component (with a separator) → direct.\n if (isWin && (name.includes(\"\\\\\") || name.includes(\"/\"))) {\n return existsSync(name) ? path.resolve(name) : null\n }\n\n const exts =\n isWin && path.extname(name) === \"\"\n ? (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim())\n .filter(Boolean)\n : [\"\"]\n\n for (const dir of dirs) {\n // Belt-and-suspenders: never resolve against the cwd even if it is\n // listed explicitly in PATH.\n if (resolvedCwd && path.resolve(dir) === resolvedCwd) continue\n for (const ext of exts) {\n const candidate = path.join(dir, name + ext)\n if (existsSync(candidate)) return candidate\n }\n }\n return null\n}\n\n/**\n * Quote one argument for a `cmd.exe /c \"<line>\"` command line so the\n * target program receives it verbatim and no `cmd.exe` metacharacter\n * retains shell meaning.\n *\n * Two phases (the canonical Windows approach — Colascione / Rust std):\n * 1. **argv quoting** so `CommandLineToArgvW` in the target parses\n * the token as one argument (double-quote, backslash-escape).\n * 2. **caret-escaping** every `cmd.exe` metacharacter — including the\n * quotes from phase 1 — so `cmd.exe` is never in quote-mode, strips\n * the carets, and hands the argv-quoted string to the program.\n *\n * `%` is special: it cannot be reliably escaped on the `cmd.exe`\n * *command line* (caret does not stop `%VAR%` expansion there). Rather\n * than mis-escape, we **throw** — our callers never pass `%`, so this\n * fails closed on the one unescapable injection vector.\n */\nexport function quoteWinArg(arg: string): string {\n if (arg.includes(\"%\")) {\n throw new Error(\n \"buildExecInvocation: argument contains '%', which cannot be safely \" +\n \"escaped on the Windows command line; refusing to build the command.\",\n )\n }\n\n // Phase 1 — argv quoting.\n let quoted: string\n if (arg.length > 0 && !/[ \\t\\n\\v\"&|<>()^!]/.test(arg)) {\n quoted = arg\n } else {\n let s = '\"'\n let backslashes = 0\n for (const ch of arg) {\n if (ch === \"\\\\\") {\n backslashes++\n } else if (ch === '\"') {\n s += \"\\\\\".repeat(backslashes * 2 + 1) + '\"'\n backslashes = 0\n } else {\n s += \"\\\\\".repeat(backslashes) + ch\n backslashes = 0\n }\n }\n s += \"\\\\\".repeat(backslashes * 2) + '\"'\n quoted = s\n }\n\n // Phase 2 — caret-escape all cmd.exe metacharacters (and the carets\n // themselves). cmd strips these; the program sees the phase-1 string.\n return quoted.replace(/[()!^\"<>&|]/g, \"^$&\")\n}\n\nexport interface ExecInvocation {\n command: string\n args: string[]\n shell: boolean\n}\n\n/**\n * Build the platform-correct `spawn` invocation for a command given as\n * an argv array. Pure / unit-testable (no spawn).\n *\n * - win32 → a single caret/argv-quoted command string + `shell:true`\n * + empty args array (the empty array avoids the DEP0190 warning\n * that fires when args and `shell:true` are combined). `cmd[0]`\n * should already be an absolute path from `resolveExecutable`.\n * - posix → `(cmd[0], cmd.slice(1))` with `shell:false` — no shell,\n * no injection surface.\n */\nexport function buildExecInvocation(\n cmd: string[],\n platform: NodeJS.Platform = process.platform,\n): ExecInvocation {\n if (cmd.length === 0) throw new Error(\"buildExecInvocation: empty command\")\n if (platform === \"win32\") {\n return { command: cmd.map(quoteWinArg).join(\" \"), args: [], shell: true }\n }\n return { command: cmd[0], args: cmd.slice(1), shell: false }\n}\n\nexport interface RunOpts {\n cwd?: string\n /** Hard timeout in ms; the process tree is killed on expiry. */\n timeoutMs?: number\n /** Extra env to merge over the parent env for the child. */\n env?: NodeJS.ProcessEnv\n}\n\nexport interface RunResult {\n stdout: string\n stderr: string\n /** Exit code; `null` when killed by signal/timeout. */\n code: number | null\n timedOut: boolean\n}\n\nfunction runInternal(\n cmd: string[],\n stdoutMode: \"pipe\" | \"inherit\" | \"ignore\",\n opts: RunOpts,\n): Promise<RunResult> {\n const { command, args, shell } = buildExecInvocation(cmd)\n return new Promise<RunResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell,\n windowsHide: true,\n stdio: [\n \"ignore\",\n stdoutMode,\n stdoutMode === \"inherit\" ? \"inherit\" : \"pipe\",\n ],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n let stdout = \"\"\n let stderr = \"\"\n let timedOut = false\n let settled = false\n\n const timer = opts.timeoutMs\n ? setTimeout(() => {\n timedOut = true\n killTree(child.pid)\n }, opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n stdout += c.toString(\"utf8\")\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n stderr += c.toString(\"utf8\")\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n resolve({ stdout, stderr, code, timedOut })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/** Kill a process tree best-effort (taskkill /T on Windows). */\nfunction killTree(pid: number | undefined): void {\n if (!pid) return\n try {\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n } else {\n process.kill(pid, \"SIGTERM\")\n }\n } catch {\n // already gone\n }\n}\n\n/** Run a command and capture stdout/stderr. Rejects on spawn error. */\nexport function runCommandCapture(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command discarding output (still captures stderr for errors). */\nexport function runCommandVoid(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command with the child's stdout/stderr inherited to the user. */\nexport function runCommandInherit(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"inherit\", opts)\n}\n\nexport interface ManagedExeOpts extends RunOpts {\n /**\n * Hard cap on captured stdout bytes. On overflow the child is\n * tree-killed and the result carries `stdoutTruncated: true`. Defends\n * against a full-`CodeUnit` colgrep `--json` payload (source + 5\n * analysis layers per hit) bloating memory.\n */\n maxStdoutBytes?: number\n /**\n * When true, exceeding `maxStdoutBytes` does NOT tree-kill the child — it\n * sets `stdoutTruncated` and stops BUFFERING further stdout while still\n * draining the pipe (no backpressure). Use for a child whose kill is unsafe\n * (e.g. colgrep, which writes a non-atomic index — a byte-cap kill during\n * its result output could interrupt a write). The child runs to completion\n * (bounded by `timeoutMs` / `inactivityTimeoutMs`). Default false (kill).\n */\n truncateInsteadOfKill?: boolean\n /**\n * Called synchronously with the spawned child right after spawn\n * succeeds, BEFORE any output arrives. The colbert lifecycle ledger\n * uses this to register the child so a session-exit sweep can\n * tree-kill an orphan. Never throws into the runner.\n */\n onSpawn?: (child: ReturnType<typeof spawn>) => void\n /**\n * Inactivity (stall) watchdog. When set, a timer is armed for\n * `inactivityTimeoutMs` and RESET on every stdout/stderr data chunk. On\n * expiry (no output for the window) it consults `onInactivityCheck`: a\n * `true` return means \"still making progress via an out-of-band signal\"\n * (e.g. the colgrep index dir is still growing on disk even though the\n * process is silent on a non-TTY pipe) and the watchdog re-arms; a\n * `false`/absent return tree-kills the child and sets `stalled: true`.\n * This is the progress-based \"stuck\" detector that lets a long-but-\n * progressing build run to completion while still killing a hung one —\n * independent of the coarse total `timeoutMs` backstop.\n */\n inactivityTimeoutMs?: number\n /** External progress probe consulted when the inactivity timer fires.\n * Return `true` to re-arm (still progressing), `false`/throw to kill.\n * MUST be cheap + synchronous (called on a timer, not awaited). */\n onInactivityCheck?: () => boolean\n}\n\nexport interface ManagedExeResult extends RunResult {\n /** True iff stdout was truncated at `maxStdoutBytes` (child was killed). */\n stdoutTruncated: boolean\n /** True iff the inactivity watchdog killed the child (no progress). */\n stalled: boolean\n}\n\n/**\n * Run a **native executable** (a real `.exe`/Mach-O/ELF, NOT a `.cmd`\n * shim) capturing stdout/stderr, with `shell:false` on EVERY platform.\n *\n * Why a separate runner from `runCommandCapture`: that path routes\n * through `buildExecInvocation`, which on Windows builds a\n * `cmd.exe`-quoted command string and **throws on `%`** (`quoteWinArg`).\n * A workspace path can legally contain `%` (and `&`, `(`, `)`, `!`, …),\n * so the managed colgrep binary — which IS a native `.exe`, not a shim —\n * must bypass cmd.exe entirely. `spawn(absExe, args, {shell:false})`\n * resolves the `.exe` via CreateProcess directly: no cmd.exe, no\n * metacharacter hazard, no `%` refusal. POSIX was already `shell:false`.\n * This is what makes \"ANY absolute workspace\" hold on Windows.\n *\n * Lifecycle:\n * - `timeoutMs` → tree-kill on expiry (`taskkill /T /F` on Windows,\n * POSIX process-group `kill(-pgid)` so colgrep's rayon worker\n * children die too). `timedOut: true` in the result.\n * - `maxStdoutBytes` → tree-kill + `stdoutTruncated: true` once the\n * captured stdout exceeds the cap.\n * - `onSpawn(child)` → register the child with the caller's ledger.\n *\n * `command` MUST be an absolute path to the executable (the caller\n * resolves it; we never search PATH here — there is nothing to inject).\n */\nexport function runManagedExeCapture(\n command: string,\n args: ReadonlyArray<string>,\n opts: ManagedExeOpts = {},\n): Promise<ManagedExeResult> {\n const isWin = process.platform === \"win32\"\n return new Promise<ManagedExeResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, [...args], {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: false,\n windowsHide: true,\n // POSIX: new process group so we can kill the whole tree\n // (colgrep + rayon workers) with kill(-pgid). Windows uses\n // taskkill /T instead; `detached` there has no group semantics.\n detached: !isWin,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n try {\n opts.onSpawn?.(child)\n } catch {\n // ledger registration must never break the spawn\n }\n\n const chunks: Array<Buffer> = []\n let stdoutBytes = 0\n const stderrChunks: Array<Buffer> = []\n let stderrBytes = 0\n const STDERR_CAP = 64 * 1024\n let timedOut = false\n let stdoutTruncated = false\n let stalled = false\n let settled = false\n\n // Exactly one terminator wins: the first to fire records its reason and\n // tree-kills; later ones no-op. Keeps timedOut / stalled / stdoutTruncated\n // mutually exclusive and avoids a double tree-kill.\n let terminated = false\n const terminate = (reason: \"timeout\" | \"stall\" | \"truncate\"): void => {\n if (terminated) return\n terminated = true\n if (reason === \"timeout\") timedOut = true\n else if (reason === \"stall\") stalled = true\n else stdoutTruncated = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n killManagedTree(child, isWin)\n }\n\n const timer = opts.timeoutMs\n ? setTimeout(() => terminate(\"timeout\"), opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n // Inactivity (stall) watchdog. Re-arms itself: when the window elapses\n // with no output, consult the external progress probe — re-arm if it\n // says \"still progressing\" (e.g. the index dir grew), else kill + mark\n // stalled. Reset on every data chunk (a chatty process never stalls).\n let inactivityTimer: ReturnType<typeof setTimeout> | undefined\n const armInactivity = (): void => {\n if (opts.inactivityTimeoutMs === undefined || settled || terminated) return\n inactivityTimer = setTimeout(() => {\n if (settled) return\n // No probe → pure output-inactivity kill. A probe that THROWS is\n // inconclusive → don't kill (re-arm); the absolute timeoutMs backstop\n // still catches a genuinely wedged process.\n let progressing = false\n if (opts.onInactivityCheck) {\n try {\n progressing = opts.onInactivityCheck() === true\n } catch {\n progressing = true\n }\n }\n if (progressing) {\n armInactivity()\n return\n }\n terminate(\"stall\")\n }, opts.inactivityTimeoutMs)\n inactivityTimer?.unref?.()\n }\n const resetInactivity = (): void => {\n if (inactivityTimer) clearTimeout(inactivityTimer)\n armInactivity()\n }\n armInactivity()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n if (stdoutTruncated) return\n stdoutBytes += c.length\n if (\n opts.maxStdoutBytes !== undefined &&\n stdoutBytes > opts.maxStdoutBytes\n ) {\n stdoutTruncated = true\n // Default: tree-kill on overflow. Opt-in: keep the child alive and\n // just stop buffering (the data handler keeps firing + discarding via\n // the `if (stdoutTruncated) return` guard above, so the pipe drains\n // and the child never blocks on a full buffer).\n if (!opts.truncateInsteadOfKill) terminate(\"truncate\")\n return\n }\n chunks.push(c)\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n // Hard byte cap on stderr — append only the slice that fits so a\n // single huge chunk can't overshoot. Never logged raw (it can\n // embed source code from colgrep).\n if (stderrBytes >= STDERR_CAP) return\n const remaining = STDERR_CAP - stderrBytes\n const slice = c.length > remaining ? c.subarray(0, remaining) : c\n stderrChunks.push(slice)\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n resolve({\n stdout: Buffer.concat(chunks).toString(\"utf8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf8\"),\n code,\n timedOut,\n stdoutTruncated,\n stalled,\n })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Tree-kill a managed child. Windows: `taskkill /T /F /PID` (whole\n * tree). POSIX: kill the process GROUP (`-pgid`) so colgrep's rayon\n * worker children die with the parent.\n *\n * `runManagedExeCapture` always spawns POSIX children `detached:true`\n * (their own process group), so the group kill is the correct and\n * sufficient primitive. We deliberately do NOT fall back to a positive-\n * pid `process.kill(pid)` when the group kill fails: by the time a kill\n * fires (timeout / byte-cap race), the child may have already exited and\n * its PID been recycled by an unrelated process — a positive-pid kill\n * would then target the wrong process. `ESRCH` (group already gone) is\n * the success case for our purposes; any other error is swallowed.\n */\nexport function killManagedTree(\n child: ReturnType<typeof spawn>,\n isWin: boolean = process.platform === \"win32\",\n): void {\n const pid = child.pid\n if (!pid) return\n try {\n if (isWin) {\n spawn(\"taskkill\", [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n } else {\n // Negative pid → the process group (we spawned detached). No\n // positive-pid fallback (PID-reuse hazard — see doc comment).\n process.kill(-pid, \"SIGKILL\")\n }\n } catch {\n // ESRCH (already gone) / EPERM — best-effort, nothing more to do.\n }\n}\n\n/**\n * Absolute path to Windows `taskkill.exe`. Bare `\"taskkill\"` would let\n * `CreateProcess`'s search order (which can include the cwd) run a planted\n * `taskkill.exe`; pinning the System32 path closes that hijack.\n */\nfunction taskkillExe(): string {\n const root =\n process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\"\n return path.join(root, \"System32\", \"taskkill.exe\")\n}\n\n/**\n * Tree-kill a child process on a SHUTDOWN/exit path, deterministically.\n *\n * Distinct from `killManagedTree` in two ways that matter when the proxy\n * is about to call `process.exit`:\n *\n * 1. **Windows uses `spawnSync`, not async `spawn`.** An async taskkill\n * may never issue before `process.exit` tears the event loop down;\n * the synchronous form guarantees the kill command has run. It is\n * time-bounded so a wedged taskkill can't hang shutdown.\n * 2. **POSIX honors `detachedGroup`.** The launched CLI is spawned\n * `detached:true` (its own process group) so `kill(-pid)` reaps the\n * whole group; other callers (e.g. ripgrep) are NOT detached, so\n * `child.kill()` on the positive pid is correct. A negative-pid kill\n * on a non-detached child would throw or hit the wrong target.\n *\n * Both branches escalate SIGTERM → SIGKILL after `graceMs` so a CLI that\n * traps SIGTERM still dies. The escalation timer is `.unref()`'d so it\n * never holds the event loop open. Errors are swallowed (already-gone /\n * EBUSY / ESRCH are the success case for our purposes).\n */\nexport function killChildProcessTree(\n child: ChildProcess,\n opts: { detachedGroup: boolean; graceMs?: number } = { detachedGroup: false },\n): void {\n const pid = child.pid\n if (!pid) return\n const graceMs = opts.graceMs ?? 500\n\n if (process.platform === \"win32\") {\n // /T = whole tree, /F = force. taskkill walks the live parent-PID\n // chain, so it reaps grandchildren regardless of the cmd.exe-vs-direct\n // spawn shape. Sync (completes before an imminent process.exit) and\n // time-bounded (a wedged taskkill must not hang shutdown).\n try {\n spawnSync(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n timeout: 5000,\n })\n } catch {\n // Already gone / EBUSY race — best-effort.\n }\n return\n }\n\n // POSIX: signal the group (detached) or the lone child (non-detached).\n const target = opts.detachedGroup ? -pid : pid\n try {\n process.kill(target, \"SIGTERM\")\n } catch {\n // ESRCH — already gone.\n }\n const t = setTimeout(() => {\n // For a lone (non-detached) child, skip escalation once it has exited\n // — its positive PID could have been recycled. For a process GROUP the\n // leader's exit does NOT mean the group is empty (a SIGTERM-ignoring\n // grandchild may survive), and the group id is only reused once the\n // group is fully gone, so always attempt the group SIGKILL (ESRCH when\n // already empty is the success case).\n if (\n !opts.detachedGroup &&\n (child.exitCode !== null || child.signalCode !== null)\n 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AM,UAAU,KAAK,WAAW;CAEhC,IAAI,QAAQ,aAAa,SAAS;EAKhC,IAAI;GACF,UAAU,YAAY,GAAG;IAAC;IAAM;IAAM;IAAQ,OAAO,GAAG;GAAC,GAAG;IAC1D,OAAO;IACP,aAAa;IACb,SAAS;GACX,CAAC;EACH,QAAQ,CAER;EACA;CACF;CAGA,MAAM,SAAS,KAAK,gBAAgB,CAAC,MAAM;CAC3C,IAAI;EACF,QAAQ,KAAK,QAAQ,SAAS;CAChC,QAAQ,CAER;CAoBA,iBAnB2B;EAOzB,IACE,CAAC,KAAK,kBACL,MAAM,aAAa,QAAQ,MAAM,eAAe,OAEjD;EAEF,IAAI;GACF,QAAQ,KAAK,QAAQ,SAAS;EAChC,QAAQ,CAER;CACF,GAAG,OACH,CAAC,CAAC,QAAQ;AACZ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"models-Cv6gprpy.js","names":[],"sources":["../src/models.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupCopilotToken, setupGitHubToken } from \"./lib/token\"\nimport { getModels, type Model } from \"./services/copilot/get-models\"\n\nexport const models = defineCommand({\n meta: {\n name: \"models\",\n description:\n \"List available GitHub Copilot models and their capabilities. Pass an optional pattern to filter (case-insensitive substring match on id, name, vendor, family).\",\n },\n args: {\n pattern: {\n type: \"positional\",\n required: false,\n description:\n \"Substring to filter models by (matches id, name, vendor, or family).\",\n },\n json: {\n type: \"boolean\",\n default: false,\n description: \"Emit raw JSON instead of the pretty layout.\",\n },\n },\n async run({ args }) {\n await ensurePaths()\n await setupGitHubToken()\n try {\n await setupCopilotToken()\n } catch (err) {\n consola.error(\"Failed to obtain Copilot token:\", err)\n process.exit(1)\n }\n\n let catalog: Awaited<ReturnType<typeof getModels>>\n try {\n catalog = await getModels()\n } catch (err) {\n consola.error(\"Failed to fetch Copilot model catalog:\", err)\n process.exit(1)\n }\n\n const all = catalog.data\n const pattern = args.pattern?.toString().trim()\n const filtered = pattern ? filterModels(all, pattern) : all\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(filtered, null, 2)}\\n`)\n return\n }\n\n if (filtered.length === 0) {\n consola.warn(\n `No models matched \"${pattern}\". ${all.length} models available — try a different substring or run without an argument to list everything.`,\n )\n process.exit(1)\n }\n\n const grouped = groupByVendor(filtered)\n const lines: Array<string> = []\n const header = pattern\n ? `${filtered.length}/${all.length} models match \"${pattern}\"`\n : `${all.length} models available`\n lines.push(header)\n lines.push(\"\")\n for (const [vendor, list] of grouped) {\n lines.push(`▾ ${vendor} (${list.length})`)\n for (const model of list) {\n lines.push(...formatModel(model))\n }\n lines.push(\"\")\n }\n process.stdout.write(lines.join(\"\\n\"))\n },\n})\n\nfunction filterModels(models: Array<Model>, pattern: string): Array<Model> {\n const needle = pattern.toLowerCase()\n return models.filter((m) => {\n const haystack = [\n m.id,\n m.name,\n m.vendor,\n m.capabilities.family,\n m.capabilities.type,\n m.model_picker_category ?? \"\",\n ]\n .join(\" \")\n .toLowerCase()\n return haystack.includes(needle)\n })\n}\n\nfunction groupByVendor(models: Array<Model>): Array<[string, Array<Model>]> {\n const map = new Map<string, Array<Model>>()\n for (const m of models) {\n const key = m.vendor || \"(unknown vendor)\"\n const bucket = map.get(key)\n if (bucket) bucket.push(m)\n else map.set(key, [m])\n }\n // Stable vendor order: alphabetical for predictability.\n return [...map.entries()].sort(([a], [b]) => a.localeCompare(b))\n}\n\n/**\n * Test-only exports. Not part of the public CLI surface — kept out of\n * the default export so they don't show up in IDE autocomplete on\n * `import { ... } from \"github-router/models\"` consumers.\n */\nexport const __testing = { filterModels, groupByVendor, formatModel, formatTokens }\n\nfunction formatModel(model: Model): Array<string> {\n const lines: Array<string> = []\n const tags: Array<string> = []\n if (model.preview) tags.push(\"preview\")\n if (model.is_chat_default) tags.push(\"chat-default\")\n if (model.is_chat_fallback) tags.push(\"chat-fallback\")\n if (model.billing?.is_premium) tags.push(\"premium\")\n if (model.billing?.restricted_to?.length) {\n tags.push(`restricted:${model.billing.restricted_to.join(\"/\")}`)\n }\n if (model.policy && model.policy.state !== \"enabled\") {\n tags.push(`policy:${model.policy.state}`)\n }\n const tagStr = tags.length > 0 ? ` [${tags.join(\", \")}]` : \"\"\n lines.push(` • ${model.id}${tagStr}`)\n if (model.name && model.name !== model.id) {\n lines.push(` name: ${model.name}`)\n }\n const meta: Array<string> = [\n `family: ${model.capabilities.family}`,\n `type: ${model.capabilities.type}`,\n ]\n if (model.capabilities.tokenizer) {\n meta.push(`tokenizer: ${model.capabilities.tokenizer}`)\n }\n if (model.version) {\n meta.push(`version: ${model.version}`)\n }\n lines.push(` ${meta.join(\" · \")}`)\n\n const limits = model.capabilities.limits\n const limitParts: Array<string> = []\n if (limits) {\n if (limits.max_context_window_tokens) {\n limitParts.push(`ctx ${formatTokens(limits.max_context_window_tokens)}`)\n } else if (limits.max_prompt_tokens) {\n limitParts.push(`prompt ${formatTokens(limits.max_prompt_tokens)}`)\n }\n if (limits.max_output_tokens) {\n limitParts.push(`out ${formatTokens(limits.max_output_tokens)}`)\n }\n if (\n limits.max_non_streaming_output_tokens\n && limits.max_non_streaming_output_tokens !== limits.max_output_tokens\n ) {\n limitParts.push(\n `out-non-stream ${formatTokens(limits.max_non_streaming_output_tokens)}`,\n )\n }\n if (limits.max_inputs) limitParts.push(`inputs ${limits.max_inputs}`)\n if (limits.vision?.max_prompt_images) {\n limitParts.push(`images ${limits.vision.max_prompt_images}`)\n }\n }\n if (limitParts.length > 0) {\n lines.push(` limits: ${limitParts.join(\" · \")}`)\n }\n\n const supports = model.capabilities.supports\n const supportFlags: Array<string> = []\n if (supports) {\n if (supports.tool_calls) supportFlags.push(\"tools\")\n if (supports.parallel_tool_calls) supportFlags.push(\"parallel-tools\")\n if (supports.streaming) supportFlags.push(\"streaming\")\n if (supports.vision) supportFlags.push(\"vision\")\n if (supports.structured_outputs) supportFlags.push(\"structured-outputs\")\n if (supports.dimensions) supportFlags.push(\"dimensions\")\n if (supports.adaptive_thinking) {\n const min = supports.min_thinking_budget\n const max = supports.max_thinking_budget\n const range\n = min !== undefined && max !== undefined\n ? `(${formatTokens(min)}-${formatTokens(max)})`\n : \"\"\n supportFlags.push(`adaptive-thinking${range}`)\n }\n if (supports.reasoning_effort && supports.reasoning_effort.length > 0) {\n supportFlags.push(`reasoning:${supports.reasoning_effort.join(\"/\")}`)\n }\n }\n if (supportFlags.length > 0) {\n lines.push(` supports: ${supportFlags.join(\", \")}`)\n }\n\n if (model.supported_endpoints && model.supported_endpoints.length > 0) {\n lines.push(` endpoints: ${model.supported_endpoints.join(\", \")}`)\n }\n if (model.billing) {\n const billParts: Array<string> = []\n if (model.billing.is_premium) billParts.push(\"premium\")\n if (typeof model.billing.multiplier === \"number\") {\n billParts.push(`×${model.billing.multiplier}`)\n }\n if (billParts.length > 0) {\n lines.push(` billing: ${billParts.join(\" \")}`)\n }\n }\n return lines\n}\n\n/**\n * Format a token count in a compact human-readable form: `1024` →\n * `1k`, `4096` → `4k`, `131072` → `128k`, `1048576` → `1M`. Prefer\n * binary multiples (mebi, kibi) since Claude Code / Copilot context\n * windows are reported in binary units (`1M context` = 1024 × 1024\n * tokens). Fall back to decimal (`64k` for `64000`) when the value\n * is a clean decimal multiple but not binary.\n */\nfunction formatTokens(n: number): string {\n if (n >= 1_048_576 && n % 1_048_576 === 0) return `${n / 1_048_576}M`\n if (n >= 1024 && n % 1024 === 0) return `${n / 1024}k`\n if (n >= 1_000_000 && n % 1_000_000 === 0) return `${n / 1_000_000}M`\n if (n >= 1000 && n % 1000 === 0) return `${n / 1000}k`\n return `${n}`\n}\n"],"mappings":";;;;;AAOA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aACE;CACJ;CACA,MAAM;EACJ,SAAS;GACP,MAAM;GACN,UAAU;GACV,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE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