@bastani/atomic 0.9.4-alpha.6 → 0.9.4-alpha.7
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/CHANGELOG.md +20 -0
- package/dist/builtin/cursor/package.json +3 -3
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +2 -2
- package/dist/builtin/subagents/CHANGELOG.md +14 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/runs/background/async-execution-chain.ts +11 -1
- package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +11 -1
- package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +2 -0
- package/dist/builtin/subagents/src/runs/background/subagent-runner-step.ts +27 -4
- package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +25 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-types.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution.ts +3 -1
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +22 -0
- package/dist/builtin/subagents/src/runs/foreground/execution-run-sync.ts +15 -5
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +5 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +4 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +4 -1
- package/dist/builtin/subagents/src/runs/shared/attempt-watchdog.ts +126 -0
- package/dist/builtin/subagents/src/runs/shared/model-candidate-filter.ts +53 -0
- package/dist/builtin/subagents/src/runs/shared/model-fallback.ts +52 -53
- package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +2 -0
- package/dist/builtin/subagents/src/shared/model-info.ts +16 -0
- package/dist/builtin/subagents/src/shared/types-config.ts +2 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +6 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/runs/shared/model-fallback-failures.ts +34 -4
- package/dist/core/agent-session-extension-bindings.d.ts +2 -0
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +10 -2
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +2 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/copilot-model-catalog.d.ts +25 -74
- package/dist/core/copilot-model-catalog.d.ts.map +1 -1
- package/dist/core/copilot-model-catalog.js +118 -68
- package/dist/core/copilot-model-catalog.js.map +1 -1
- package/dist/core/copilot-model-synthesis.d.ts +10 -0
- package/dist/core/copilot-model-synthesis.d.ts.map +1 -0
- package/dist/core/copilot-model-synthesis.js +89 -0
- package/dist/core/copilot-model-synthesis.js.map +1 -0
- package/dist/core/model-registry-builtins.d.ts.map +1 -1
- package/dist/core/model-registry-builtins.js +21 -3
- package/dist/core/model-registry-builtins.js.map +1 -1
- package/dist/core/tools/read-selectors.d.ts.map +1 -1
- package/dist/core/tools/read-selectors.js +19 -1
- package/dist/core/tools/read-selectors.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +1 -0
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/docs/models.md +3 -3
- package/docs/providers.md +1 -1
- package/docs/rpc.md +2 -2
- package/docs/sdk.md +1 -1
- package/docs/settings.md +2 -1
- package/docs/subagents.md +6 -0
- package/docs/workflows.md +2 -0
- package/npm-shrinkwrap.json +27 -27
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-model-catalog.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAKH,yEAAyE;AACzE,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,gEAAgE;AAChE,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AAE3E,wGAAwG;AACxG,eAAO,MAAM,+BAA+B,SAAU,CAAC;AAEvD,eAAO,MAAM,2BAA2B,eAAe,CAAC;AAExD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAMpE,CAAC;AAEF,oFAAoF;AACpF,eAAO,MAAM,4BAA4B,6CAA6C,CAAC;AAEvF,mFAAmF;AACnF,eAAO,MAAM,2BAA2B,kCAAkC,CAAC;AAE3E,wEAAwE;AACxE,eAAO,MAAM,+BAA+B,6CAA6C,CAAC;AAE1F,eAAO,MAAM,wBAAwB,yBAAyB,CAAC;AAC/D,eAAO,MAAM,sBAAsB,uBAAuB,CAAC;AAC3D,eAAO,MAAM,2BAA2B,4BAA4B,CAAC;AACrE,eAAO,MAAM,qBAAqB,sBAAsB,CAAC;AAEzD,KAAK,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAqC7D,wBAAgB,2BAA2B,CAAC,GAAG,GAAE,kBAAgC,GAAG,MAAM,GAAG,SAAS,CAGrG;AAED,qFAAqF;AACrF,eAAO,MAAM,4BAA4B,QAAiB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AAO,EAAE,mBAAmB,GAAG,IAAI,CAE/E;AAED,iFAAiF;AACjF,wBAAgB,4BAA4B,IAAI,mBAAmB,CAElE;AAED,sDAAsD;AACtD,wBAAgB,8BAA8B,IAAI,IAAI,CAErD;AAuBD,MAAM,WAAW,8BAA8B;IAC9C,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,+CAA+C;IAC/C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAmBD,wGAAwG;AACxG,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,8BAA8B,GACrC,mBAAmB,GAAG,SAAS,CAsBjC;AAED,6FAA6F;AAC7F,wBAAgB,wBAAwB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,mBAAmB,EAC5B,GAAG,CAAC,EAAE,MAAM,GACV,IAAI,CAaN;AAED,yFAAyF;AACzF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED,0FAA0F;AAC1F,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;;;;;;;;;GASG;AACH,wBAAgB,sCAAsC,CACrD,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,EAAE,MAAM,GACV,OAAO,CAOT","sourcesContent":["/**\n * GitHub Copilot model catalog (CAPI) — dynamic prompt-token budgets.\n *\n * GitHub's Copilot API (CAPI) exposes distinct model limits via `GET {baseUrl}/models`:\n *\n * - `capabilities.limits.max_context_window_tokens` is the model's total context capacity\n * (prompt + completion reserve).\n * - `capabilities.limits.max_prompt_tokens` is the maximum prompt/input budget Atomic can safely\n * fill before the provider must reserve output tokens.\n * - `billing.token_prices.<tier>.context_max` is a prompt-token billing/selection threshold. The\n * `default` tier is the short prompt budget (e.g. gpt-5.5 272k, Claude 200k); a\n * `long_context` tier adds a selectable larger prompt budget (e.g. gpt-5.5 922k, Claude 936k).\n *\n * Atomic shows the model's full context window for the selectable long tier (the\n * `max_context_window_tokens` total, e.g. 1_000_000/1_050_000), matching how the native `openai/*`\n * and `anthropic/*` providers advertise these models. Because GitHub enforces a lower server-side\n * prompt cap (`max_prompt_tokens`, e.g. 936k/922k) below that total, the prompt cap is retained as\n * an internal effective input budget (`CopilotModelContext.maxInputTokens`) that drives compaction\n * thresholds and the overflow-recovery guard, so the branded total can be displayed without\n * overrunning the server limit. The default (short) tier stays at the `default` billing tier's\n * prompt budget.\n *\n * This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers\n * windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes\n * stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot\n * provider) and cached on disk for a short TTL, exactly like the Copilot CLI.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) for a single Copilot model. */\nexport interface CopilotModelContext {\n\t/**\n\t * Base/displayed context window — shown in the footer. The default tier's `context_max`, or the\n\t * model-level `max_prompt_tokens` fallback otherwise.\n\t */\n\tcontextWindow: number;\n\t/**\n\t * Selectable windows (`[default, long]`) when the model exposes a `long_context` tier larger than\n\t * its default; absent for single-window models. The long entry is the model's full\n\t * `max_context_window_tokens` (total capacity) when advertised, matching `openai/*` and\n\t * `anthropic/*`.\n\t */\n\tcontextWindowOptions?: readonly number[];\n\t/**\n\t * Hard prompt/input cap (`max_prompt_tokens`) when it sits below the displayed long window. Used\n\t * as the effective input budget for compaction thresholds and overflow recovery so the branded\n\t * total can be shown without overrunning GitHub's server-side prompt limit. Absent when the\n\t * displayed window already equals the input cap.\n\t */\n\tmaxInputTokens?: number;\n}\n\n/** Map of model id → resolved input-token context window(s). */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 3 as const;\n\n/**\n * Resolve the Copilot CAPI base URL.\n *\n * Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with\n * `proxy.` swapped for `api.`. Env-token routing resolves explicit `COPILOT_API_TARGET` /\n * `GITHUB_COPILOT_BASE_URL` overrides, then `GITHUB_SERVER_URL` (`*.ghe.com` ->\n * `copilot-api.<tenant>.ghe.com`, other non-github.com -> `api.enterprise.githubcopilot.com`),\n * then the public Copilot routing hub `api.githubcopilot.com` for `COPILOT_GITHUB_TOKEN`. Stored\n * OAuth credentials still fall back to the generated individual host when no token route is known.\n */\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\n/** Raw token limits parsed from a CAPI model entry. */\nexport interface CopilotModelLimits {\n\t/** `capabilities.limits.max_prompt_tokens` — maximum prompt/input budget (the hard input cap). */\n\tmaxPromptTokens?: number;\n\t/** `capabilities.limits.max_context_window_tokens` — total context capacity (the displayed long tier). */\n\tmaxContextWindowTokens?: number;\n\t/** `capabilities.limits.max_output_tokens` — output reserve; derives the input cap when `max_prompt_tokens` is absent. */\n\tmaxOutputTokens?: number;\n\t/** `billing.token_prices.default.context_max` — default-tier prompt threshold. */\n\tdefaultContextMax?: number;\n\t/** `billing.token_prices.long_context.context_max` — long-context prompt threshold. */\n\tlongContextMax?: number;\n}\n\n/**\n * Resolve a model's input-token context window(s) from its CAPI limits.\n *\n * `contextWindow` is the model's base input budget — the default tier's `context_max` when tiered,\n * otherwise `max_prompt_tokens ?? max_context_window_tokens ?? 128_000`. A `long_context` tier that\n * is larger than the base adds a second selectable window. Returns `undefined` when the entry\n * carries no usable limit signal at all.\n */\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\treturn longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t}\n\treturn { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst limits = asRecord(asRecord(record.capabilities)?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst context = resolveCopilotModelContext({\n\t\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t\t});\n\t\tif (context) catalog.set(id, context);\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) {\n\t\t\treturn maxInputTokens !== undefined\n\t\t\t\t? { contextWindow, contextWindowOptions: options, maxInputTokens }\n\t\t\t\t: { contextWindow, contextWindowOptions: options };\n\t\t}\n\t}\n\treturn maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n}\n\n/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\n/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\n/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\n/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"copilot-model-catalog.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAK/E,yGAAyG;AACzG,MAAM,WAAW,mBAAmB;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IAC5B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,oBAAoB;IACpC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,qFAAqF;AACrF,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AAE3E,wGAAwG;AACxG,eAAO,MAAM,+BAA+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AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;;;;;;;;;GASG;AACH,wBAAgB,sCAAsC,CACrD,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,EAAE,MAAM,GACV,OAAO,CAOT","sourcesContent":["/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
@@ -1,30 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* GitHub Copilot model catalog (CAPI) — dynamic prompt-token budgets.
|
|
3
|
-
*
|
|
4
|
-
* GitHub's Copilot API (CAPI) exposes distinct model limits via `GET {baseUrl}/models`:
|
|
5
|
-
*
|
|
6
|
-
* - `capabilities.limits.max_context_window_tokens` is the model's total context capacity
|
|
7
|
-
* (prompt + completion reserve).
|
|
8
|
-
* - `capabilities.limits.max_prompt_tokens` is the maximum prompt/input budget Atomic can safely
|
|
9
|
-
* fill before the provider must reserve output tokens.
|
|
10
|
-
* - `billing.token_prices.<tier>.context_max` is a prompt-token billing/selection threshold. The
|
|
11
|
-
* `default` tier is the short prompt budget (e.g. gpt-5.5 272k, Claude 200k); a
|
|
12
|
-
* `long_context` tier adds a selectable larger prompt budget (e.g. gpt-5.5 922k, Claude 936k).
|
|
13
|
-
*
|
|
14
|
-
* Atomic shows the model's full context window for the selectable long tier (the
|
|
15
|
-
* `max_context_window_tokens` total, e.g. 1_000_000/1_050_000), matching how the native `openai/*`
|
|
16
|
-
* and `anthropic/*` providers advertise these models. Because GitHub enforces a lower server-side
|
|
17
|
-
* prompt cap (`max_prompt_tokens`, e.g. 936k/922k) below that total, the prompt cap is retained as
|
|
18
|
-
* an internal effective input budget (`CopilotModelContext.maxInputTokens`) that drives compaction
|
|
19
|
-
* thresholds and the overflow-recovery guard, so the branded total can be displayed without
|
|
20
|
-
* overrunning the server limit. The default (short) tier stays at the `default` billing tier's
|
|
21
|
-
* prompt budget.
|
|
22
|
-
*
|
|
23
|
-
* This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers
|
|
24
|
-
* windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes
|
|
25
|
-
* stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot
|
|
26
|
-
* provider) and cached on disk for a short TTL, exactly like the Copilot CLI.
|
|
27
|
-
*/
|
|
1
|
+
/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */
|
|
28
2
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
29
3
|
import { dirname, join } from "node:path";
|
|
30
4
|
/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */
|
|
@@ -95,17 +69,7 @@ export function copilotTokenFromEnvironment(env = process.env) {
|
|
|
95
69
|
/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */
|
|
96
70
|
export const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;
|
|
97
71
|
/** Current on-disk cache schema version. */
|
|
98
|
-
export const COPILOT_CATALOG_CACHE_VERSION =
|
|
99
|
-
/**
|
|
100
|
-
* Resolve the Copilot CAPI base URL.
|
|
101
|
-
*
|
|
102
|
-
* Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with
|
|
103
|
-
* `proxy.` swapped for `api.`. Env-token routing resolves explicit `COPILOT_API_TARGET` /
|
|
104
|
-
* `GITHUB_COPILOT_BASE_URL` overrides, then `GITHUB_SERVER_URL` (`*.ghe.com` ->
|
|
105
|
-
* `copilot-api.<tenant>.ghe.com`, other non-github.com -> `api.enterprise.githubcopilot.com`),
|
|
106
|
-
* then the public Copilot routing hub `api.githubcopilot.com` for `COPILOT_GITHUB_TOKEN`. Stored
|
|
107
|
-
* OAuth credentials still fall back to the generated individual host when no token route is known.
|
|
108
|
-
*/
|
|
72
|
+
export const COPILOT_CATALOG_CACHE_VERSION = 5;
|
|
109
73
|
export function copilotApiBaseUrlFromToken(token, enterpriseDomain, env = process.env) {
|
|
110
74
|
const explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);
|
|
111
75
|
if (explicitOverride)
|
|
@@ -134,14 +98,49 @@ function asRecord(value) {
|
|
|
134
98
|
function toPositiveInt(value) {
|
|
135
99
|
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
|
|
136
100
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
101
|
+
function stringArray(value) {
|
|
102
|
+
if (!Array.isArray(value))
|
|
103
|
+
return undefined;
|
|
104
|
+
const strings = value.filter((item) => typeof item === "string" && item.length > 0);
|
|
105
|
+
return strings.length > 0 ? strings : undefined;
|
|
106
|
+
}
|
|
107
|
+
function supportedFlag(record, key) {
|
|
108
|
+
const value = record?.[key];
|
|
109
|
+
if (typeof value === "boolean")
|
|
110
|
+
return value;
|
|
111
|
+
if (typeof value === "number")
|
|
112
|
+
return Number.isFinite(value) && value > 0;
|
|
113
|
+
if (Array.isArray(value))
|
|
114
|
+
return value.length > 0;
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
function parseCopilotSupports(value) {
|
|
118
|
+
const record = asRecord(value);
|
|
119
|
+
if (!record)
|
|
120
|
+
return undefined;
|
|
121
|
+
const supports = {
|
|
122
|
+
adaptiveThinking: supportedFlag(record, "adaptive_thinking"),
|
|
123
|
+
maxThinkingBudget: supportedFlag(record, "max_thinking_budget"),
|
|
124
|
+
minThinkingBudget: supportedFlag(record, "min_thinking_budget"),
|
|
125
|
+
parallelToolCalls: supportedFlag(record, "parallel_tool_calls"),
|
|
126
|
+
reasoningEffort: supportedFlag(record, "reasoning_effort"),
|
|
127
|
+
reasoningEffortLevels: stringArray(record.reasoning_effort),
|
|
128
|
+
streaming: supportedFlag(record, "streaming"),
|
|
129
|
+
structuredOutputs: supportedFlag(record, "structured_outputs"),
|
|
130
|
+
toolCalls: supportedFlag(record, "tool_calls"),
|
|
131
|
+
vision: supportedFlag(record, "vision"),
|
|
132
|
+
};
|
|
133
|
+
return Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;
|
|
134
|
+
}
|
|
135
|
+
function parseCopilotLimits(limits, prices) {
|
|
136
|
+
return {
|
|
137
|
+
maxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),
|
|
138
|
+
maxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),
|
|
139
|
+
maxOutputTokens: toPositiveInt(limits?.max_output_tokens),
|
|
140
|
+
defaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),
|
|
141
|
+
longContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
145
144
|
export function resolveCopilotModelContext(limits) {
|
|
146
145
|
const hasSignal = limits.maxPromptTokens !== undefined ||
|
|
147
146
|
limits.maxContextWindowTokens !== undefined ||
|
|
@@ -166,11 +165,12 @@ export function resolveCopilotModelContext(limits) {
|
|
|
166
165
|
limits.longContextMax;
|
|
167
166
|
// Only carry the cap when the displayed long window actually exceeds it (the branded-total
|
|
168
167
|
// case); when they coincide there is no gap and the input budget is just the window.
|
|
169
|
-
|
|
168
|
+
const resolved = longWindow > inputCap
|
|
170
169
|
? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }
|
|
171
170
|
: { contextWindow: base, contextWindowOptions: [base, longWindow] };
|
|
171
|
+
return limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;
|
|
172
172
|
}
|
|
173
|
-
return { contextWindow: base };
|
|
173
|
+
return limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };
|
|
174
174
|
}
|
|
175
175
|
/**
|
|
176
176
|
* Parse a raw CAPI `/models` response body into an input-token context-window catalog.
|
|
@@ -187,17 +187,25 @@ export function parseCopilotModelCatalog(body) {
|
|
|
187
187
|
const id = record.id;
|
|
188
188
|
if (typeof id !== "string" || id.length === 0)
|
|
189
189
|
continue;
|
|
190
|
-
const
|
|
190
|
+
const capabilities = asRecord(record.capabilities);
|
|
191
|
+
const limitsRecord = asRecord(capabilities?.limits);
|
|
191
192
|
const prices = asRecord(asRecord(record.billing)?.token_prices);
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
193
|
+
const limits = parseCopilotLimits(limitsRecord, prices);
|
|
194
|
+
const context = resolveCopilotModelContext(limits);
|
|
195
|
+
if (context) {
|
|
196
|
+
const policy = asRecord(record.policy);
|
|
197
|
+
catalog.set(id, {
|
|
198
|
+
...context,
|
|
199
|
+
displayName: typeof record.name === "string" && record.name.length > 0 ? record.name : undefined,
|
|
200
|
+
vendor: typeof record.vendor === "string" && record.vendor.length > 0 ? record.vendor : undefined,
|
|
201
|
+
supportedEndpoints: stringArray(record.supported_endpoints),
|
|
202
|
+
supports: parseCopilotSupports(capabilities?.supports),
|
|
203
|
+
limits,
|
|
204
|
+
modelPickerEnabled: typeof record.model_picker_enabled === "boolean" ? record.model_picker_enabled : undefined,
|
|
205
|
+
policyState: typeof policy?.state === "string" ? policy.state : undefined,
|
|
206
|
+
type: typeof capabilities?.type === "string" ? capabilities.type : undefined,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
201
209
|
}
|
|
202
210
|
return catalog;
|
|
203
211
|
}
|
|
@@ -247,24 +255,69 @@ function hostFromBaseUrl(baseUrl) {
|
|
|
247
255
|
return baseUrl;
|
|
248
256
|
}
|
|
249
257
|
}
|
|
258
|
+
function sanitizeCachedSupports(value) {
|
|
259
|
+
const record = asRecord(value);
|
|
260
|
+
if (!record)
|
|
261
|
+
return undefined;
|
|
262
|
+
const supports = {
|
|
263
|
+
adaptiveThinking: supportedFlag(record, "adaptiveThinking"),
|
|
264
|
+
maxThinkingBudget: supportedFlag(record, "maxThinkingBudget"),
|
|
265
|
+
minThinkingBudget: supportedFlag(record, "minThinkingBudget"),
|
|
266
|
+
parallelToolCalls: supportedFlag(record, "parallelToolCalls"),
|
|
267
|
+
reasoningEffort: supportedFlag(record, "reasoningEffort"),
|
|
268
|
+
reasoningEffortLevels: stringArray(record.reasoningEffortLevels),
|
|
269
|
+
streaming: supportedFlag(record, "streaming"),
|
|
270
|
+
structuredOutputs: supportedFlag(record, "structuredOutputs"),
|
|
271
|
+
toolCalls: supportedFlag(record, "toolCalls"),
|
|
272
|
+
vision: supportedFlag(record, "vision"),
|
|
273
|
+
};
|
|
274
|
+
return Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;
|
|
275
|
+
}
|
|
276
|
+
function sanitizeCachedLimits(value) {
|
|
277
|
+
const record = asRecord(value);
|
|
278
|
+
if (!record)
|
|
279
|
+
return undefined;
|
|
280
|
+
const limits = {
|
|
281
|
+
maxPromptTokens: toPositiveInt(record.maxPromptTokens),
|
|
282
|
+
maxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),
|
|
283
|
+
maxOutputTokens: toPositiveInt(record.maxOutputTokens),
|
|
284
|
+
defaultContextMax: toPositiveInt(record.defaultContextMax),
|
|
285
|
+
longContextMax: toPositiveInt(record.longContextMax),
|
|
286
|
+
};
|
|
287
|
+
return Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;
|
|
288
|
+
}
|
|
250
289
|
function sanitizeCachedContext(value) {
|
|
251
290
|
const record = asRecord(value);
|
|
252
291
|
const contextWindow = toPositiveInt(record?.contextWindow);
|
|
253
292
|
if (contextWindow === undefined)
|
|
254
293
|
return undefined;
|
|
255
294
|
const maxInputTokens = toPositiveInt(record?.maxInputTokens);
|
|
295
|
+
const maxTokens = toPositiveInt(record?.maxTokens);
|
|
256
296
|
const rawOptions = record?.contextWindowOptions;
|
|
297
|
+
const base = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };
|
|
298
|
+
if (maxTokens !== undefined)
|
|
299
|
+
base.maxTokens = maxTokens;
|
|
257
300
|
if (Array.isArray(rawOptions)) {
|
|
258
301
|
const options = rawOptions.map(toPositiveInt).filter((n) => n !== undefined);
|
|
259
|
-
if (options.length > 1)
|
|
260
|
-
|
|
261
|
-
? { contextWindow, contextWindowOptions: options, maxInputTokens }
|
|
262
|
-
: { contextWindow, contextWindowOptions: options };
|
|
263
|
-
}
|
|
302
|
+
if (options.length > 1)
|
|
303
|
+
base.contextWindowOptions = options;
|
|
264
304
|
}
|
|
265
|
-
|
|
305
|
+
const displayName = record && typeof record.displayName === "string" && record.displayName.length > 0 ? record.displayName : undefined;
|
|
306
|
+
const vendor = record && typeof record.vendor === "string" && record.vendor.length > 0 ? record.vendor : undefined;
|
|
307
|
+
const policyState = record && typeof record.policyState === "string" ? record.policyState : undefined;
|
|
308
|
+
const type = record && typeof record.type === "string" ? record.type : undefined;
|
|
309
|
+
return {
|
|
310
|
+
...base,
|
|
311
|
+
displayName,
|
|
312
|
+
vendor,
|
|
313
|
+
supportedEndpoints: stringArray(record?.supportedEndpoints),
|
|
314
|
+
supports: sanitizeCachedSupports(record?.supports),
|
|
315
|
+
limits: sanitizeCachedLimits(record?.limits),
|
|
316
|
+
modelPickerEnabled: typeof record?.modelPickerEnabled === "boolean" ? record.modelPickerEnabled : undefined,
|
|
317
|
+
policyState,
|
|
318
|
+
type,
|
|
319
|
+
};
|
|
266
320
|
}
|
|
267
|
-
/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */
|
|
268
321
|
export function readCopilotCatalogCache(path, options) {
|
|
269
322
|
let parsed;
|
|
270
323
|
try {
|
|
@@ -294,7 +347,6 @@ export function readCopilotCatalogCache(path, options) {
|
|
|
294
347
|
}
|
|
295
348
|
return catalog;
|
|
296
349
|
}
|
|
297
|
-
/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */
|
|
298
350
|
export function writeCopilotCatalogCache(path, baseUrl, catalog, now) {
|
|
299
351
|
const payload = {
|
|
300
352
|
version: COPILOT_CATALOG_CACHE_VERSION,
|
|
@@ -310,11 +362,9 @@ export function writeCopilotCatalogCache(path, baseUrl, catalog, now) {
|
|
|
310
362
|
// best-effort cache; ignore write failures
|
|
311
363
|
}
|
|
312
364
|
}
|
|
313
|
-
/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */
|
|
314
365
|
export function copilotCatalogCacheHost(baseUrl) {
|
|
315
366
|
return hostFromBaseUrl(baseUrl);
|
|
316
367
|
}
|
|
317
|
-
/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */
|
|
318
368
|
export function copilotCatalogCachePath(agentDir) {
|
|
319
369
|
return join(agentDir, "cache", "copilot-models.json");
|
|
320
370
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-model-catalog.js","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA4B1C,wGAAwG;AACxG,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,YAAY,CAAC;AAExD;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAqC;IACxE,YAAY,EAAE,0BAA0B;IACxC,gBAAgB,EAAE,gBAAgB;IAClC,uBAAuB,EAAE,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A4B,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * GitHub Copilot model catalog (CAPI) — dynamic prompt-token budgets.\n *\n * GitHub's Copilot API (CAPI) exposes distinct model limits via `GET {baseUrl}/models`:\n *\n * - `capabilities.limits.max_context_window_tokens` is the model's total context capacity\n * (prompt + completion reserve).\n * - `capabilities.limits.max_prompt_tokens` is the maximum prompt/input budget Atomic can safely\n * fill before the provider must reserve output tokens.\n * - `billing.token_prices.<tier>.context_max` is a prompt-token billing/selection threshold. The\n * `default` tier is the short prompt budget (e.g. gpt-5.5 272k, Claude 200k); a\n * `long_context` tier adds a selectable larger prompt budget (e.g. gpt-5.5 922k, Claude 936k).\n *\n * Atomic shows the model's full context window for the selectable long tier (the\n * `max_context_window_tokens` total, e.g. 1_000_000/1_050_000), matching how the native `openai/*`\n * and `anthropic/*` providers advertise these models. Because GitHub enforces a lower server-side\n * prompt cap (`max_prompt_tokens`, e.g. 936k/922k) below that total, the prompt cap is retained as\n * an internal effective input budget (`CopilotModelContext.maxInputTokens`) that drives compaction\n * thresholds and the overflow-recovery guard, so the branded total can be displayed without\n * overrunning the server limit. The default (short) tier stays at the `default` billing tier's\n * prompt budget.\n *\n * This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers\n * windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes\n * stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot\n * provider) and cached on disk for a short TTL, exactly like the Copilot CLI.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) for a single Copilot model. */\nexport interface CopilotModelContext {\n\t/**\n\t * Base/displayed context window — shown in the footer. The default tier's `context_max`, or the\n\t * model-level `max_prompt_tokens` fallback otherwise.\n\t */\n\tcontextWindow: number;\n\t/**\n\t * Selectable windows (`[default, long]`) when the model exposes a `long_context` tier larger than\n\t * its default; absent for single-window models. The long entry is the model's full\n\t * `max_context_window_tokens` (total capacity) when advertised, matching `openai/*` and\n\t * `anthropic/*`.\n\t */\n\tcontextWindowOptions?: readonly number[];\n\t/**\n\t * Hard prompt/input cap (`max_prompt_tokens`) when it sits below the displayed long window. Used\n\t * as the effective input budget for compaction thresholds and overflow recovery so the branded\n\t * total can be shown without overrunning GitHub's server-side prompt limit. Absent when the\n\t * displayed window already equals the input cap.\n\t */\n\tmaxInputTokens?: number;\n}\n\n/** Map of model id → resolved input-token context window(s). */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 3 as const;\n\n/**\n * Resolve the Copilot CAPI base URL.\n *\n * Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with\n * `proxy.` swapped for `api.`. Env-token routing resolves explicit `COPILOT_API_TARGET` /\n * `GITHUB_COPILOT_BASE_URL` overrides, then `GITHUB_SERVER_URL` (`*.ghe.com` ->\n * `copilot-api.<tenant>.ghe.com`, other non-github.com -> `api.enterprise.githubcopilot.com`),\n * then the public Copilot routing hub `api.githubcopilot.com` for `COPILOT_GITHUB_TOKEN`. Stored\n * OAuth credentials still fall back to the generated individual host when no token route is known.\n */\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\n/** Raw token limits parsed from a CAPI model entry. */\nexport interface CopilotModelLimits {\n\t/** `capabilities.limits.max_prompt_tokens` — maximum prompt/input budget (the hard input cap). */\n\tmaxPromptTokens?: number;\n\t/** `capabilities.limits.max_context_window_tokens` — total context capacity (the displayed long tier). */\n\tmaxContextWindowTokens?: number;\n\t/** `capabilities.limits.max_output_tokens` — output reserve; derives the input cap when `max_prompt_tokens` is absent. */\n\tmaxOutputTokens?: number;\n\t/** `billing.token_prices.default.context_max` — default-tier prompt threshold. */\n\tdefaultContextMax?: number;\n\t/** `billing.token_prices.long_context.context_max` — long-context prompt threshold. */\n\tlongContextMax?: number;\n}\n\n/**\n * Resolve a model's input-token context window(s) from its CAPI limits.\n *\n * `contextWindow` is the model's base input budget — the default tier's `context_max` when tiered,\n * otherwise `max_prompt_tokens ?? max_context_window_tokens ?? 128_000`. A `long_context` tier that\n * is larger than the base adds a second selectable window. Returns `undefined` when the entry\n * carries no usable limit signal at all.\n */\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\treturn longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t}\n\treturn { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst limits = asRecord(asRecord(record.capabilities)?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst context = resolveCopilotModelContext({\n\t\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t\t});\n\t\tif (context) catalog.set(id, context);\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) {\n\t\t\treturn maxInputTokens !== undefined\n\t\t\t\t? { contextWindow, contextWindowOptions: options, maxInputTokens }\n\t\t\t\t: { contextWindow, contextWindowOptions: options };\n\t\t}\n\t}\n\treturn maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n}\n\n/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\n/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\n/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\n/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"copilot-model-catalog.js","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAkC1C,wGAAwG;AACxG,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,YAAY,CAAC;AAExD;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAqC;IACxE,YAAY,EAAE,0BAA0B;IACxC,gBAAgB,EAAE,gBAAgB;IAClC,uBAAuB,EAAE,qBAAqB;IAC9C,wBAAwB,EAAE,aAAa;IACvC,sBAAsB,EAAE,2BAA2B;CACnD,CAAC;AAEF,oFAAoF;AACpF,MAAM,CAAC,MAAM,4BAA4B,GAAG,0CAA0C,CAAC;AAEvF,mFAAmF;AACnF,MAAM,CAAC,MAAM,2BAA2B,GAAG,+BAA+B,CAAC;AAE3E,wEAAwE;AACxE,MAAM,CAAC,MAAM,+BAA+B,GAAG,0CAA0C,CAAC;AAE1F,MAAM,CAAC,MAAM,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;GASG;AACH,MAAM,UAAU,sCAAsC,CACrD,WAA+B,EAC/B,SAAiB,EACjB,GAAY;IAEZ,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,IAAI,GAAG,uBAAuB,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,CAAC;IAC9E,MAAM,MAAM,GAAG,uBAAuB,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,iBAAiB,EAAE,CAAC,CAAC;IAClG,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,4BAA4B,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
import { type CopilotModelContext } from "./copilot-model-catalog.ts";
|
|
3
|
+
export interface CopilotModelTemplate {
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export declare function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>["thinkingLevelMap"] | undefined;
|
|
8
|
+
export declare function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate;
|
|
9
|
+
export declare function synthesizeCopilotCatalogModels(catalog: ReadonlyMap<string, CopilotModelContext>, existingIds: ReadonlySet<string>, template: CopilotModelTemplate): Model<Api>[];
|
|
10
|
+
//# sourceMappingURL=copilot-model-synthesis.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-model-synthesis.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-synthesis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAyD,KAAK,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAa7H,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,kBAAkB,CAAC,GAAG,SAAS,CAkB3H;AAqBD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,oBAAoB,CAM7F;AAED,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,EACjD,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,EAChC,QAAQ,EAAE,oBAAoB,GAC5B,KAAK,CAAC,GAAG,CAAC,EAAE,CA4Bd","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { COPILOT_CATALOG_HEADERS, DEFAULT_COPILOT_API_BASE_URL, type CopilotModelContext } from \"./copilot-model-catalog.ts\";\nimport { withContextWindowOptions } from \"./context-window.ts\";\n\nconst GITHUB_COPILOT_PROVIDER = \"github-copilot\";\nconst ENDPOINT_API_PREFERENCE = [\n\t[\"/v1/messages\", \"anthropic-messages\"],\n\t[\"/responses\", \"openai-responses\"],\n\t[\"/chat/completions\", \"openai-completions\"],\n] as const satisfies readonly (readonly [string, Api])[];\n\nconst ZERO_COST: Model<Api>[\"cost\"] = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\nconst ADAPTIVE_THINKING_LEVEL_MAP: Model<Api>[\"thinkingLevelMap\"] = { minimal: \"low\", xhigh: \"max\" };\n\nexport interface CopilotModelTemplate {\n\tbaseUrl: string;\n\theaders?: Record<string, string>;\n}\n\nexport function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>[\"thinkingLevelMap\"] | undefined {\n\tconst advertised = entry.supports?.reasoningEffortLevels;\n\tif (!advertised || advertised.length === 0) {\n\t\treturn entry.supports?.adaptiveThinking ? ADAPTIVE_THINKING_LEVEL_MAP : undefined;\n\t}\n\n\tconst levels = new Set(advertised);\n\tconst map: Model<Api>[\"thinkingLevelMap\"] = {\n\t\tminimal: levels.has(\"minimal\") ? \"minimal\" : null,\n\t\tlow: levels.has(\"low\") ? \"low\" : null,\n\t\tmedium: levels.has(\"medium\") ? \"medium\" : null,\n\t\thigh: levels.has(\"high\") ? \"high\" : null,\n\t};\n\tif (levels.has(\"none\")) map.off = \"none\";\n\telse if (api !== \"anthropic-messages\" || !entry.supports?.adaptiveThinking) map.off = null;\n\tif (levels.has(\"xhigh\")) map.xhigh = \"xhigh\";\n\telse if (levels.has(\"max\") && entry.supports?.adaptiveThinking) map.xhigh = \"max\";\n\treturn map;\n}\n\nfunction mapCopilotApi(entry: CopilotModelContext): Api | undefined {\n\tconst endpoints = new Set(entry.supportedEndpoints ?? []);\n\treturn ENDPOINT_API_PREFERENCE.find(([endpoint]) => endpoints.has(endpoint))?.[1];\n}\n\nfunction hasReasoning(entry: CopilotModelContext): boolean {\n\treturn Boolean(\n\t\tentry.supports?.reasoningEffort || entry.supports?.adaptiveThinking || entry.supports?.minThinkingBudget || entry.supports?.maxThinkingBudget,\n\t);\n}\n\nfunction canSynthesizeCopilotModel(id: string, entry: CopilotModelContext): boolean {\n\tif (id.includes(\"/\")) return false;\n\tif (entry.modelPickerEnabled !== true) return false;\n\tif (entry.type !== \"chat\") return false;\n\tif (entry.policyState?.toLowerCase() === \"disabled\") return false;\n\treturn mapCopilotApi(entry) !== undefined;\n}\n\nexport function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate {\n\tconst sibling = models.find((model) => model.provider === GITHUB_COPILOT_PROVIDER);\n\treturn {\n\t\tbaseUrl: sibling?.baseUrl ?? DEFAULT_COPILOT_API_BASE_URL,\n\t\theaders: sibling?.headers ?? COPILOT_CATALOG_HEADERS,\n\t};\n}\n\nexport function synthesizeCopilotCatalogModels(\n\tcatalog: ReadonlyMap<string, CopilotModelContext>,\n\texistingIds: ReadonlySet<string>,\n\ttemplate: CopilotModelTemplate,\n): Model<Api>[] {\n\tconst synthesized: Model<Api>[] = [];\n\tfor (const [id, entry] of catalog) {\n\t\tif (existingIds.has(id) || !canSynthesizeCopilotModel(id, entry)) continue;\n\t\tconst api = mapCopilotApi(entry);\n\t\tif (!api) continue;\n\t\tlet model: Model<Api> = {\n\t\t\tid,\n\t\t\tname: entry.displayName ?? id,\n\t\t\tapi,\n\t\t\tprovider: GITHUB_COPILOT_PROVIDER,\n\t\t\tbaseUrl: template.baseUrl,\n\t\t\theaders: template.headers,\n\t\t\treasoning: hasReasoning(entry),\n\t\t\tthinkingLevelMap: copilotThinkingLevelMapFor(entry, api),\n\t\t\tcompat: entry.supports?.adaptiveThinking ? ({ forceAdaptiveThinking: true } as Model<Api>[\"compat\"]) : undefined,\n\t\t\tinput: entry.supports?.vision ? [\"text\", \"image\"] : [\"text\"],\n\t\t\tcost: ZERO_COST,\n\t\t\tmaxInputTokens: entry.maxInputTokens,\n\t\t\tcontextWindow: entry.contextWindow,\n\t\t\tmaxTokens: entry.maxTokens ?? entry.limits?.maxOutputTokens ?? entry.maxInputTokens ?? entry.contextWindow,\n\t\t};\n\t\tif (entry.contextWindowOptions && entry.contextWindowOptions.length > 1) {\n\t\t\tmodel = withContextWindowOptions(model, entry.contextWindowOptions);\n\t\t}\n\t\tsynthesized.push(model);\n\t}\n\treturn synthesized;\n}\n"]}
|