@codeworksh/aikit 0.9.1 → 0.9.2
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/cli.mjs +3 -3
- package/{copilot-CcD3g6H8.mjs → copilot-bFammM5T.mjs} +2 -2
- package/{copilot-CcD3g6H8.mjs.map → copilot-bFammM5T.mjs.map} +1 -1
- package/{copilot-headers-DceqXlpj.mjs → copilot-headers-01-kLz8g.mjs} +2 -2
- package/{copilot-headers-DceqXlpj.mjs.map → copilot-headers-01-kLz8g.mjs.map} +1 -1
- package/{github-copilot-SIUCJz1G.mjs → github-copilot-eDhLBMfL.mjs} +2 -2
- package/{github-copilot-SIUCJz1G.mjs.map → github-copilot-eDhLBMfL.mjs.map} +1 -1
- package/github-copilot-gMaBI_-X.mjs +3 -0
- package/index.d.mts +1 -1
- package/index.mjs +4 -4
- package/{model-CrVLp622.d.mts → model-BetbWJV7.d.mts} +14 -3
- package/{model-gCDbmGqT.mjs → model-Czo0SKj0.mjs} +42 -4
- package/model-Czo0SKj0.mjs.map +1 -0
- package/{modelgen-DvorXOjJ.mjs → modelgen-DR-uhl3l.mjs} +11 -14
- package/modelgen-DR-uhl3l.mjs.map +1 -0
- package/modelgen.d.mts +1 -1
- package/modelgen.mjs +1 -1
- package/oauth/github/copilot.mjs +1 -1
- package/{openai-codex-Bqzti6Mc.mjs → openai-codex-CpaJcE8Q.mjs} +2 -2
- package/{openai-codex-Bqzti6Mc.mjs.map → openai-codex-CpaJcE8Q.mjs.map} +1 -1
- package/openai-codex-Dm1GGNs0.mjs +2 -0
- package/package.json +1 -1
- package/{registry-ZxwIW0gX.mjs → registry-vtzL8QxA.mjs} +4 -4
- package/{registry-ZxwIW0gX.mjs.map → registry-vtzL8QxA.mjs.map} +1 -1
- package/github-copilot-BJIrxOzT.mjs +0 -3
- package/model-gCDbmGqT.mjs.map +0 -1
- package/modelgen-DvorXOjJ.mjs.map +0 -1
- package/openai-codex-DA1Q7mLN.mjs +0 -2
package/cli.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { r as OpenAICodexOAuthClient, t as JsonOpenAICodexAuthStorage } from "./codex-CLDBTrFm.mjs";
|
|
3
|
-
import { t as ModelgenCommand } from "./modelgen-
|
|
4
|
-
import { i as JsonGitHubCopilotAuthStorage, r as GitHubCopilotOAuthClient } from "./copilot-
|
|
3
|
+
import { t as ModelgenCommand } from "./modelgen-DR-uhl3l.mjs";
|
|
4
|
+
import { i as JsonGitHubCopilotAuthStorage, r as GitHubCopilotOAuthClient } from "./copilot-bFammM5T.mjs";
|
|
5
5
|
import { n as promptLine, t as openBrowser } from "./interactive-eoNnscGB.mjs";
|
|
6
6
|
import { a as oauthNotice, c as summarizeGitHubCopilot, i as oauthLoginIssue, l as summarizeOpenAICodex, n as checkOAuthProvider, r as formatOAuthSummary, s as oauthRefreshIssue } from "./summary-C_QyCVWa.mjs";
|
|
7
7
|
import yargs from "yargs";
|
|
8
8
|
import { hideBin } from "yargs/helpers";
|
|
9
9
|
//#region package.json
|
|
10
|
-
var version = "0.9.
|
|
10
|
+
var version = "0.9.2";
|
|
11
11
|
//#endregion
|
|
12
12
|
//#region src/cli/oauth.ts
|
|
13
13
|
async function runOpenAICodexAuth(args) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as pollDeviceCode, n as isObject, r as readEnv, t as JsonAuthStorage } from "./storage-v6qjTQ0v.mjs";
|
|
2
|
-
import { n as GITHUB_COPILOT_STATIC_HEADERS, t as GITHUB_COPILOT_API_VERSION } from "./copilot-headers-
|
|
2
|
+
import { n as GITHUB_COPILOT_STATIC_HEADERS, t as GITHUB_COPILOT_API_VERSION } from "./copilot-headers-01-kLz8g.mjs";
|
|
3
3
|
//#region src/oauth/github/copilot.ts
|
|
4
4
|
/**
|
|
5
5
|
* GitHub Copilot OAuth.
|
|
@@ -422,4 +422,4 @@ async function getGitHubCopilotApiKey(options = {}) {
|
|
|
422
422
|
//#endregion
|
|
423
423
|
export { createGitHubCopilotDeviceFlow as a, fetchGitHubCopilotUser as c, gitHubCopilotBaseUrl as d, gitHubCopilotEntitlementError as f, pollGitHubCopilotDeviceToken as h, JsonGitHubCopilotAuthStorage as i, getGitHubCopilotApiKey as l, normalizeGitHubDomain as m, GITHUB_COPILOT_PROVIDER_ID as n, enableGitHubCopilotModels as o, gitHubCopilotHeaders as p, GitHubCopilotOAuthClient as r, fetchGitHubCopilotModels as s, GITHUB_COPILOT_API_KEY_ENV as t, gitHubApiDomain as u };
|
|
424
424
|
|
|
425
|
-
//# sourceMappingURL=copilot-
|
|
425
|
+
//# sourceMappingURL=copilot-bFammM5T.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-CcD3g6H8.mjs","names":[],"sources":["../../src/oauth/github/copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth.\n *\n * The device flow yields a plain GitHub OAuth token (`ghu_`/`gho_`), which the\n * Copilot API accepts directly as a Bearer credential — no session-token\n * exchange and no refresh path. `getGitHubCopilotApiKey` resolves a token from\n * `COPILOT_GITHUB_TOKEN` or the codework auth.json store, and nothing else;\n * `GitHubCopilotOAuthClient#login` performs the device flow.\n */\n\nimport {\n\tGITHUB_COPILOT_API_VERSION,\n\tGITHUB_COPILOT_STATIC_HEADERS,\n} from \"../../providers/github-copilot/copilot-headers.ts\";\nimport { pollDeviceCode } from \"../devcode.ts\";\nimport { JsonAuthStorage, isObject, readEnv } from \"../storage.ts\";\n\nexport const GITHUB_COPILOT_API_KEY_ENV = \"COPILOT_GITHUB_TOKEN\";\n\n// The official GitHub Copilot OAuth client id — the same one copilot.vim,\n// copilot.lua, and pi use, so the consent screen shows \"GitHub Copilot\".\nconst CLIENT_ID = \"Iv1.b507a08c87ecfe98\";\nconst SCOPE = \"read:user\";\nconst DEFAULT_DOMAIN = \"github.com\";\nconst DEFAULT_BASE_URL = \"https://api.githubcopilot.com\";\nconst USER_API_VERSION = \"2025-04-01\";\nconst DEFAULT_PROVIDER_ID = \"github-copilot\";\nexport const GITHUB_COPILOT_PROVIDER_ID = DEFAULT_PROVIDER_ID;\nconst DEFAULT_MODELS_RETRY = { maxRetries: 2, maxElapsedMs: 5000 };\n\nexport type GitHubCopilotOAuthCredentials = {\n\t/** GitHub OAuth token (`ghu_`/`gho_`), used directly as the Copilot Bearer credential. */\n\taccess: string;\n\t/** Same token; kept for shape parity with other OAuth credentials. */\n\trefresh: string;\n\t/** Always 0 — GitHub OAuth tokens do not expire; re-login only on persistent 401. */\n\texpires: number;\n\tenterpriseUrl?: string;\n\t/** `endpoints.api` from `/copilot_internal/user` — the plan-specific Copilot API host. */\n\tapiEndpoint?: string;\n\t/** Model ids visible to the account at login time, from `GET {base}/models`. */\n\tavailableModelIds?: string[];\n};\n\nexport type GitHubCopilotDeviceFlow = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds: number;\n\texpiresInSeconds?: number;\n};\n\nexport type GitHubCopilotUser = {\n\tchatEnabled?: boolean;\n\tcanSignupForLimited?: boolean;\n\tapiEndpoint?: string;\n};\n\nexport type GitHubCopilotRemoteModel = {\n\tid: string;\n\tsupportedEndpoints: string[];\n\tpolicyState?: string;\n\tpickerEnabled: boolean;\n\ttoolCalls: boolean;\n};\n\nexport type GitHubCopilotLoginOptions = {\n\tenterpriseUrl?: string | undefined;\n\t/** Enable `policy.state === \"unconfigured\"` catalog models after login. Off by default — it writes account policy. */\n\tenableModels?: boolean | undefined;\n\tsignal?: AbortSignal | undefined;\n\tfetch?: typeof globalThis.fetch | undefined;\n\tonAuth: (info: { url: string; userCode: string; instructions?: string | undefined }) => void;\n\tonProgress?: ((message: string) => void) | undefined;\n};\n\nexport interface GitHubCopilotAuthStorage {\n\tget(): Promise<GitHubCopilotOAuthCredentials | undefined>;\n\tset(credentials: GitHubCopilotOAuthCredentials): Promise<void>;\n\tclear(): Promise<void>;\n}\n\nexport type JsonGitHubCopilotAuthStorageOptions = {\n\tpath?: string;\n\tproviderId?: string;\n};\n\ntype FetchLike = typeof globalThis.fetch;\n\nfunction fetchWith(options: { fetch?: FetchLike | undefined }): FetchLike {\n\treturn options.fetch ?? globalThis.fetch;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"GitHub Copilot login cancelled\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"GitHub Copilot login cancelled\"));\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport function normalizeGitHubDomain(input: string | undefined): string | undefined {\n\tconst trimmed = input?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst url = trimmed.includes(\"://\") ? new URL(trimmed) : new URL(`https://${trimmed}`);\n\t\treturn url.hostname;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The `api.` host serving `copilot_internal/*` for a given GitHub domain. */\nexport function gitHubApiDomain(domain: string): string {\n\treturn domain === DEFAULT_DOMAIN ? \"api.github.com\" : `api.${domain}`;\n}\n\n/** The Copilot inference host for a credential or enterprise domain. */\nexport function gitHubCopilotBaseUrl(options?: {\n\tenterpriseUrl?: string | undefined;\n\tapiEndpoint?: string | undefined;\n}): string {\n\tconst apiEndpoint = options?.apiEndpoint;\n\tif (typeof apiEndpoint === \"string\" && apiEndpoint) return apiEndpoint.replace(/\\/+$/, \"\");\n\tconst domain = normalizeGitHubDomain(options?.enterpriseUrl);\n\treturn domain ? `https://copilot-api.${domain}` : DEFAULT_BASE_URL;\n}\n\n/**\n * GitHub reports Copilot access on `/copilot_internal/user`; OAuth itself\n * succeeds for any GitHub account, so this is the only signal that the account\n * can chat.\n */\nexport function gitHubCopilotEntitlementError(user: {\n\tchat_enabled?: boolean | undefined;\n\tcan_signup_for_limited?: boolean | undefined;\n}): string | undefined {\n\tif (user.chat_enabled !== false) return undefined;\n\tif (user.can_signup_for_limited) {\n\t\treturn \"This GitHub account is not signed up for GitHub Copilot. Sign up for Copilot Free at https://github.com/features/copilot/plans and connect again.\";\n\t}\n\treturn \"This GitHub account does not have GitHub Copilot access. It needs an active Copilot subscription or a seat assigned by an organization.\";\n}\n\nexport async function createGitHubCopilotDeviceFlow(\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<GitHubCopilotDeviceFlow> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\tconst response = await fetchWith(options)(`https://${domain}/login/device/code`, {\n\t\tmethod: \"POST\",\n\t\theaders: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({ client_id: CLIENT_ID, scope: SCOPE }),\n\t\tsignal: options.signal ?? null,\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub device code request failed (${response.status})`);\n\t}\n\n\tconst data: unknown = await response.json();\n\tif (!isObject(data)) throw new Error(\"Invalid GitHub device code response\");\n\tconst { device_code, user_code, verification_uri, interval, expires_in } = data;\n\tif (\n\t\ttypeof device_code !== \"string\" ||\n\t\ttypeof user_code !== \"string\" ||\n\t\ttypeof verification_uri !== \"string\" ||\n\t\t(interval !== undefined && typeof interval !== \"number\") ||\n\t\t(expires_in !== undefined && typeof expires_in !== \"number\")\n\t) {\n\t\tthrow new Error(\"Invalid GitHub device code response fields\");\n\t}\n\n\t// The verification URI is opened in the user's browser; force it to be a URL\n\t// so `open` cannot be tricked into launching something else.\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(verification_uri);\n\t} catch {\n\t\tthrow new Error(\"Untrusted verification_uri in GitHub device code response\");\n\t}\n\tif (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n\t\tthrow new Error(\"Untrusted verification_uri in GitHub device code response\");\n\t}\n\n\treturn {\n\t\tdeviceCode: device_code,\n\t\tuserCode: user_code,\n\t\tverificationUri: parsed.href,\n\t\tintervalSeconds: typeof interval === \"number\" && interval > 0 ? interval : 5,\n\t\t...(typeof expires_in === \"number\" && { expiresInSeconds: expires_in }),\n\t};\n}\n\nexport async function pollGitHubCopilotDeviceToken(\n\tflow: GitHubCopilotDeviceFlow,\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<string> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\tconst send = fetchWith(options);\n\n\treturn pollDeviceCode<string>({\n\t\tintervalSeconds: flow.intervalSeconds,\n\t\t...(flow.expiresInSeconds !== undefined && { expiresInSeconds: flow.expiresInSeconds }),\n\t\twaitBeforeFirstPoll: true,\n\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\tpoll: async () => {\n\t\t\tconst response = await send(`https://${domain}/login/oauth/access_token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tdevice_code: flow.deviceCode,\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal ?? null,\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\treturn { status: \"failed\", message: `GitHub device token poll failed (${response.status})` };\n\t\t\t}\n\n\t\t\tconst data: unknown = await response.json();\n\t\t\tif (!isObject(data)) return { status: \"failed\", message: \"Invalid GitHub device token response\" };\n\n\t\t\tif (typeof data.access_token === \"string\" && data.access_token) {\n\t\t\t\treturn { status: \"complete\", value: data.access_token };\n\t\t\t}\n\n\t\t\tconst error = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tif (error === \"authorization_pending\") return { status: \"pending\" };\n\t\t\tif (error === \"slow_down\") {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"slow_down\",\n\t\t\t\t\t...(typeof data.interval === \"number\" && data.interval > 0 && { intervalSeconds: data.interval }),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst description = typeof data.error_description === \"string\" ? `: ${data.error_description}` : \"\";\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `GitHub device authorization failed: ${error ?? \"unknown error\"}${description}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\n/**\n * Look up the account's Copilot entitlement and per-plan API endpoint.\n *\n * A failed or malformed lookup returns `undefined` rather than denying login —\n * only an explicit `chat_enabled: false` answer blocks.\n */\nexport async function fetchGitHubCopilotUser(\n\ttoken: string,\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<GitHubCopilotUser | undefined> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\ttry {\n\t\tconst response = await fetchWith(options)(`https://${gitHubApiDomain(domain)}/copilot_internal/user`, {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\"User-Agent\": GITHUB_COPILOT_STATIC_HEADERS[\"User-Agent\"],\n\t\t\t\t\"X-GitHub-Api-Version\": USER_API_VERSION,\n\t\t\t},\n\t\t\tsignal: options.signal ?? null,\n\t\t});\n\t\tif (!response.ok) return undefined;\n\t\tconst data: unknown = await response.json();\n\t\tif (!isObject(data)) return undefined;\n\t\tconst endpoints = isObject(data.endpoints) ? data.endpoints : undefined;\n\t\treturn {\n\t\t\t...(typeof data.chat_enabled === \"boolean\" && { chatEnabled: data.chat_enabled }),\n\t\t\t...(typeof data.can_signup_for_limited === \"boolean\" && { canSignupForLimited: data.can_signup_for_limited }),\n\t\t\t...(typeof endpoints?.api === \"string\" && endpoints.api && { apiEndpoint: endpoints.api.replace(/\\/+$/, \"\") }),\n\t\t};\n\t} catch (error) {\n\t\tif (options.signal?.aborted) throw error;\n\t\treturn undefined;\n\t}\n}\n\nasync function fetchWithRateLimitRetry(\n\tsend: FetchLike,\n\turl: string,\n\tinit: RequestInit,\n\toptions: { signal?: AbortSignal; maxRetries: number; maxElapsedMs: number },\n): Promise<Response> {\n\tconst deadline = Date.now() + options.maxElapsedMs;\n\tfor (let retry = 0; ; retry++) {\n\t\tconst response = await send(url, { ...init, signal: options.signal ?? null });\n\t\tif (response.status !== 429 || retry >= options.maxRetries) return response;\n\n\t\tconst retryAfter = response.headers.get(\"retry-after\");\n\t\tlet delayMs = 500 * 2 ** retry;\n\t\tif (retryAfter) {\n\t\t\tconst seconds = Number.parseFloat(retryAfter);\n\t\t\tdelayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1000;\n\t\t\tif (!Number.isFinite(delayMs)) return response;\n\t\t}\n\t\tdelayMs = Math.max(0, delayMs);\n\t\tif (delayMs >= deadline - Date.now()) return response;\n\t\tawait response.body?.cancel();\n\t\tawait sleep(delayMs, options.signal);\n\t}\n}\n\n/**\n * The account-visible Copilot model catalog. `GET {base}/models` is the ground\n * truth for endpoint routing (`supported_endpoints`) and enablement (`policy`,\n * `model_picker_enabled`) — models.dev has no equivalent data.\n */\nexport async function fetchGitHubCopilotModels(\n\ttoken: string,\n\toptions: {\n\t\tbaseURL?: string | undefined;\n\t\tdomain?: string | undefined;\n\t\tfetch?: FetchLike | undefined;\n\t\tsignal?: AbortSignal | undefined;\n\t\tmaxRetries?: number | undefined;\n\t\tmaxElapsedMs?: number | undefined;\n\t} = {},\n): Promise<GitHubCopilotRemoteModel[]> {\n\tconst baseURL = options.baseURL ?? gitHubCopilotBaseUrl({ enterpriseUrl: options.domain });\n\tconst response = await fetchWithRateLimitRetry(\n\t\tfetchWith(options),\n\t\t`${baseURL}/models`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\t\t\"X-GitHub-Api-Version\": GITHUB_COPILOT_API_VERSION,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\tmaxRetries: options.maxRetries ?? DEFAULT_MODELS_RETRY.maxRetries,\n\t\t\tmaxElapsedMs: options.maxElapsedMs ?? DEFAULT_MODELS_RETRY.maxElapsedMs,\n\t\t},\n\t);\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot models request failed (${response.status})`);\n\t}\n\n\tconst data: unknown = await response.json();\n\tconst list = isObject(data) ? data.data : undefined;\n\tif (!Array.isArray(list)) throw new Error(\"Invalid GitHub Copilot models response\");\n\n\treturn list.flatMap((raw) => {\n\t\tif (!isObject(raw) || typeof raw.id !== \"string\") return [];\n\t\tconst capabilities = isObject(raw.capabilities) ? raw.capabilities : undefined;\n\t\tconst supports = isObject(capabilities?.supports) ? capabilities.supports : undefined;\n\t\tconst policy = isObject(raw.policy) ? raw.policy : undefined;\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: raw.id,\n\t\t\t\tsupportedEndpoints: Array.isArray(raw.supported_endpoints)\n\t\t\t\t\t? raw.supported_endpoints.filter((entry): entry is string => typeof entry === \"string\")\n\t\t\t\t\t: [],\n\t\t\t\t...(typeof policy?.state === \"string\" && { policyState: policy.state }),\n\t\t\t\tpickerEnabled: raw.model_picker_enabled === true,\n\t\t\t\ttoolCalls: supports?.tool_calls !== false,\n\t\t\t},\n\t\t];\n\t});\n}\n\n/**\n * Enable models the account has not configured yet (`policy.state ===\n * \"unconfigured\"`). Best effort per model; a rate limit that outlives the\n * retry budget stops the batch.\n */\nexport async function enableGitHubCopilotModels(\n\ttoken: string,\n\tmodelIds: readonly string[],\n\toptions: {\n\t\tbaseURL?: string | undefined;\n\t\tdomain?: string | undefined;\n\t\tfetch?: FetchLike | undefined;\n\t\tsignal?: AbortSignal | undefined;\n\t} = {},\n): Promise<string[]> {\n\tconst baseURL = options.baseURL ?? gitHubCopilotBaseUrl({ enterpriseUrl: options.domain });\n\tconst send = fetchWith(options);\n\tconst enabled: string[] = [];\n\tfor (const modelId of modelIds) {\n\t\ttry {\n\t\t\tconst response = await fetchWithRateLimitRetry(\n\t\t\t\tsend,\n\t\t\t\t`${baseURL}/models/${modelId}/policy`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\t\t\t\t\"openai-intent\": \"chat-policy\",\n\t\t\t\t\t\t\"x-interaction-type\": \"chat-policy\",\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ state: \"enabled\" }),\n\t\t\t\t},\n\t\t\t\t{ ...(options.signal !== undefined && { signal: options.signal }), maxRetries: 2, maxElapsedMs: 5000 },\n\t\t\t);\n\t\t\tif (response.status === 429) break;\n\t\t\tif (response.ok) enabled.push(modelId);\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw error;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn enabled;\n}\n\nfunction isGitHubCopilotCredentials(value: unknown): value is GitHubCopilotOAuthCredentials {\n\tif (!isObject(value)) return false;\n\treturn typeof value.access === \"string\" && typeof value.refresh === \"string\" && typeof value.expires === \"number\";\n}\n\nexport class JsonGitHubCopilotAuthStorage implements GitHubCopilotAuthStorage {\n\tprivate readonly storage: JsonAuthStorage<GitHubCopilotOAuthCredentials>;\n\n\tconstructor(options: JsonGitHubCopilotAuthStorageOptions = {}) {\n\t\tthis.storage = new JsonAuthStorage({\n\t\t\tproviderId: options.providerId ?? DEFAULT_PROVIDER_ID,\n\t\t\tisCredentials: isGitHubCopilotCredentials,\n\t\t\t...(options.path !== undefined && { path: options.path }),\n\t\t});\n\t}\n\n\tget path(): string {\n\t\treturn this.storage.path;\n\t}\n\n\tget providerId(): string {\n\t\treturn this.storage.providerId;\n\t}\n\n\tget(): Promise<GitHubCopilotOAuthCredentials | undefined> {\n\t\treturn this.storage.get();\n\t}\n\n\tset(credentials: GitHubCopilotOAuthCredentials): Promise<void> {\n\t\treturn this.storage.set(credentials);\n\t}\n\n\tclear(): Promise<void> {\n\t\treturn this.storage.clear();\n\t}\n}\n\nexport type GitHubCopilotOAuthClientOptions = {\n\tstorage?: GitHubCopilotAuthStorage;\n};\n\nexport class GitHubCopilotOAuthClient {\n\treadonly storage: GitHubCopilotAuthStorage;\n\n\tconstructor(options: GitHubCopilotOAuthClientOptions = {}) {\n\t\tthis.storage = options.storage ?? new JsonGitHubCopilotAuthStorage();\n\t}\n\n\tasync login(options: GitHubCopilotLoginOptions): Promise<GitHubCopilotOAuthCredentials> {\n\t\tconst enterpriseUrl = options.enterpriseUrl?.trim() || undefined;\n\t\tconst domain = normalizeGitHubDomain(enterpriseUrl) ?? DEFAULT_DOMAIN;\n\t\tif (enterpriseUrl && !normalizeGitHubDomain(enterpriseUrl)) {\n\t\t\tthrow new Error(\"Invalid GitHub Enterprise URL/domain\");\n\t\t}\n\n\t\tconst flow = await createGitHubCopilotDeviceFlow({ domain, fetch: options.fetch, signal: options.signal });\n\t\toptions.onAuth({\n\t\t\turl: flow.verificationUri,\n\t\t\tuserCode: flow.userCode,\n\t\t\tinstructions: \"Complete the GitHub device authorization to finish GitHub Copilot authentication.\",\n\t\t});\n\n\t\tconst access = await pollGitHubCopilotDeviceToken(flow, {\n\t\t\tdomain,\n\t\t\tfetch: options.fetch,\n\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t});\n\n\t\tconst user = await fetchGitHubCopilotUser(access, { domain, fetch: options.fetch, signal: options.signal });\n\t\tconst denied = user\n\t\t\t? gitHubCopilotEntitlementError({\n\t\t\t\t\tchat_enabled: user.chatEnabled,\n\t\t\t\t\tcan_signup_for_limited: user.canSignupForLimited,\n\t\t\t\t})\n\t\t\t: undefined;\n\t\tif (denied) throw new Error(denied);\n\n\t\tconst apiEndpoint =\n\t\t\tuser?.apiEndpoint ?? gitHubCopilotBaseUrl({ enterpriseUrl: domain === DEFAULT_DOMAIN ? undefined : domain });\n\n\t\toptions.onProgress?.(\"Fetching available Copilot models...\");\n\t\tlet availableModelIds: string[] | undefined;\n\t\tlet unconfigured: string[] = [];\n\t\ttry {\n\t\t\tconst models = await fetchGitHubCopilotModels(access, {\n\t\t\t\tbaseURL: apiEndpoint,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\t});\n\t\t\tconst usable = models.filter((model) => model.toolCalls && model.policyState !== \"disabled\");\n\t\t\tconst pickerIds = usable.filter((model) => model.pickerEnabled).map((model) => model.id);\n\t\t\t// Some Individual accounts report picker=false for every model despite\n\t\t\t// enabled policies; only that endpoint gets the policy fallback.\n\t\t\tconst host = new URL(apiEndpoint).hostname;\n\t\t\tconst policyFallback = pickerIds.length === 0 && host === \"api.individual.githubcopilot.com\";\n\t\t\tavailableModelIds = pickerIds.length\n\t\t\t\t? pickerIds\n\t\t\t\t: policyFallback\n\t\t\t\t\t? usable.filter((model) => model.policyState === \"enabled\").map((model) => model.id)\n\t\t\t\t\t: [];\n\t\t\tunconfigured = usable.filter((model) => model.policyState === \"unconfigured\").map((model) => model.id);\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw error;\n\t\t\toptions.onProgress?.(\"Could not fetch the Copilot model catalog; continuing without it.\");\n\t\t}\n\n\t\tif (options.enableModels && unconfigured.length > 0) {\n\t\t\toptions.onProgress?.(\"Enabling Copilot models...\");\n\t\t\tconst enabled = await enableGitHubCopilotModels(access, unconfigured, {\n\t\t\t\tbaseURL: apiEndpoint,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\t});\n\t\t\tavailableModelIds = [...new Set([...(availableModelIds ?? []), ...enabled])];\n\t\t}\n\n\t\tconst credentials: GitHubCopilotOAuthCredentials = {\n\t\t\taccess,\n\t\t\trefresh: access,\n\t\t\texpires: 0,\n\t\t\t...(domain !== DEFAULT_DOMAIN && { enterpriseUrl: domain }),\n\t\t\tapiEndpoint,\n\t\t\t...(availableModelIds !== undefined && availableModelIds.length > 0 && { availableModelIds }),\n\t\t};\n\t\tawait this.storage.set(credentials);\n\t\treturn credentials;\n\t}\n\n\t/** The stored `ghu_` token, returned as-is — it never expires. */\n\tasync getCredentials(): Promise<GitHubCopilotOAuthCredentials | undefined> {\n\t\treturn this.storage.get();\n\t}\n\n\tasync getApiKey(): Promise<string | undefined> {\n\t\treturn (await this.getCredentials())?.access;\n\t}\n\n\tasync getHeaders(): Promise<Record<string, string> | undefined> {\n\t\tconst credentials = await this.getCredentials();\n\t\treturn credentials ? gitHubCopilotHeaders(credentials) : undefined;\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tawait this.storage.clear();\n\t}\n}\n\nexport function gitHubCopilotHeaders(credentials: GitHubCopilotOAuthCredentials): Record<string, string> {\n\treturn {\n\t\tAuthorization: `Bearer ${credentials.access}`,\n\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\"X-GitHub-Api-Version\": GITHUB_COPILOT_API_VERSION,\n\t};\n}\n\n/**\n * Resolve the GitHub Copilot API credential: `COPILOT_GITHUB_TOKEN` first, then\n * an explicit `auth --github-copilot` login from codework auth.json.\n *\n * Nothing else is consulted, by design. `GITHUB_TOKEN` and `GH_TOKEN` are\n * usually set for git or `gh` and carry no Copilot access — in GitHub Actions\n * `GITHUB_TOKEN` is a workflow token — so reading them turns a working login\n * into an unexplained 401. Credentials another application stored for itself\n * (an editor's Copilot sign-in) are not consulted either: a token codework was\n * never given should not silently become the identity its runs bill and act as.\n *\n * Returns undefined when nothing is available; the device flow only runs via\n * `GitHubCopilotOAuthClient#login`.\n */\nexport async function getGitHubCopilotApiKey(\n\toptions: GitHubCopilotOAuthClientOptions = {},\n): Promise<string | und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SAAS;GACT,SAAS;GACT,GAAI,WAAW,kBAAkB,EAAE,eAAe,OAAO;GACzD;GACA,GAAI,sBAAsB,KAAA,KAAa,kBAAkB,SAAS,KAAK,EAAE,kBAAkB;EAC5F;EACA,MAAM,KAAK,QAAQ,IAAI,WAAW;EAClC,OAAO;CACR;;CAGA,MAAM,iBAAqE;EAC1E,OAAO,KAAK,QAAQ,IAAI;CACzB;CAEA,MAAM,YAAyC;EAC9C,QAAQ,MAAM,KAAK,eAAe,EAAA,EAAI;CACvC;CAEA,MAAM,aAA0D;EAC/D,MAAM,cAAc,MAAM,KAAK,eAAe;EAC9C,OAAO,cAAc,qBAAqB,WAAW,IAAI,KAAA;CAC1D;CAEA,MAAM,SAAwB;EAC7B,MAAM,KAAK,QAAQ,MAAM;CAC1B;AACD;AAEA,SAAgB,qBAAqB,aAAoE;CACxG,OAAO;EACN,eAAe,UAAU,YAAY;EACrC,GAAG;EACH,wBAAwB;CACzB;AACD;;;;;;;;;;;;;;;AAgBA,eAAsB,uBACrB,UAA2C,CAAC,GACd;CAC9B,MAAM,YAAY,QAAQ,0BAA0B;CACpD,IAAI,WAAW,OAAO;CAEtB,OAAO,IAAI,yBAAyB,OAAO,CAAC,CAAC,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"copilot-bFammM5T.mjs","names":[],"sources":["../../src/oauth/github/copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth.\n *\n * The device flow yields a plain GitHub OAuth token (`ghu_`/`gho_`), which the\n * Copilot API accepts directly as a Bearer credential — no session-token\n * exchange and no refresh path. `getGitHubCopilotApiKey` resolves a token from\n * `COPILOT_GITHUB_TOKEN` or the codework auth.json store, and nothing else;\n * `GitHubCopilotOAuthClient#login` performs the device flow.\n */\n\nimport {\n\tGITHUB_COPILOT_API_VERSION,\n\tGITHUB_COPILOT_STATIC_HEADERS,\n} from \"../../providers/github-copilot/copilot-headers.ts\";\nimport { pollDeviceCode } from \"../devcode.ts\";\nimport { JsonAuthStorage, isObject, readEnv } from \"../storage.ts\";\n\nexport const GITHUB_COPILOT_API_KEY_ENV = \"COPILOT_GITHUB_TOKEN\";\n\n// The official GitHub Copilot OAuth client id — the same one copilot.vim,\n// copilot.lua, and pi use, so the consent screen shows \"GitHub Copilot\".\nconst CLIENT_ID = \"Iv1.b507a08c87ecfe98\";\nconst SCOPE = \"read:user\";\nconst DEFAULT_DOMAIN = \"github.com\";\nconst DEFAULT_BASE_URL = \"https://api.githubcopilot.com\";\nconst USER_API_VERSION = \"2025-04-01\";\nconst DEFAULT_PROVIDER_ID = \"github-copilot\";\nexport const GITHUB_COPILOT_PROVIDER_ID = DEFAULT_PROVIDER_ID;\nconst DEFAULT_MODELS_RETRY = { maxRetries: 2, maxElapsedMs: 5000 };\n\nexport type GitHubCopilotOAuthCredentials = {\n\t/** GitHub OAuth token (`ghu_`/`gho_`), used directly as the Copilot Bearer credential. */\n\taccess: string;\n\t/** Same token; kept for shape parity with other OAuth credentials. */\n\trefresh: string;\n\t/** Always 0 — GitHub OAuth tokens do not expire; re-login only on persistent 401. */\n\texpires: number;\n\tenterpriseUrl?: string;\n\t/** `endpoints.api` from `/copilot_internal/user` — the plan-specific Copilot API host. */\n\tapiEndpoint?: string;\n\t/** Model ids visible to the account at login time, from `GET {base}/models`. */\n\tavailableModelIds?: string[];\n};\n\nexport type GitHubCopilotDeviceFlow = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds: number;\n\texpiresInSeconds?: number;\n};\n\nexport type GitHubCopilotUser = {\n\tchatEnabled?: boolean;\n\tcanSignupForLimited?: boolean;\n\tapiEndpoint?: string;\n};\n\nexport type GitHubCopilotRemoteModel = {\n\tid: string;\n\tsupportedEndpoints: string[];\n\tpolicyState?: string;\n\tpickerEnabled: boolean;\n\ttoolCalls: boolean;\n};\n\nexport type GitHubCopilotLoginOptions = {\n\tenterpriseUrl?: string | undefined;\n\t/** Enable `policy.state === \"unconfigured\"` catalog models after login. Off by default — it writes account policy. */\n\tenableModels?: boolean | undefined;\n\tsignal?: AbortSignal | undefined;\n\tfetch?: typeof globalThis.fetch | undefined;\n\tonAuth: (info: { url: string; userCode: string; instructions?: string | undefined }) => void;\n\tonProgress?: ((message: string) => void) | undefined;\n};\n\nexport interface GitHubCopilotAuthStorage {\n\tget(): Promise<GitHubCopilotOAuthCredentials | undefined>;\n\tset(credentials: GitHubCopilotOAuthCredentials): Promise<void>;\n\tclear(): Promise<void>;\n}\n\nexport type JsonGitHubCopilotAuthStorageOptions = {\n\tpath?: string;\n\tproviderId?: string;\n};\n\ntype FetchLike = typeof globalThis.fetch;\n\nfunction fetchWith(options: { fetch?: FetchLike | undefined }): FetchLike {\n\treturn options.fetch ?? globalThis.fetch;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"GitHub Copilot login cancelled\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"GitHub Copilot login cancelled\"));\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport function normalizeGitHubDomain(input: string | undefined): string | undefined {\n\tconst trimmed = input?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst url = trimmed.includes(\"://\") ? new URL(trimmed) : new URL(`https://${trimmed}`);\n\t\treturn url.hostname;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The `api.` host serving `copilot_internal/*` for a given GitHub domain. */\nexport function gitHubApiDomain(domain: string): string {\n\treturn domain === DEFAULT_DOMAIN ? \"api.github.com\" : `api.${domain}`;\n}\n\n/** The Copilot inference host for a credential or enterprise domain. */\nexport function gitHubCopilotBaseUrl(options?: {\n\tenterpriseUrl?: string | undefined;\n\tapiEndpoint?: string | undefined;\n}): string {\n\tconst apiEndpoint = options?.apiEndpoint;\n\tif (typeof apiEndpoint === \"string\" && apiEndpoint) return apiEndpoint.replace(/\\/+$/, \"\");\n\tconst domain = normalizeGitHubDomain(options?.enterpriseUrl);\n\treturn domain ? `https://copilot-api.${domain}` : DEFAULT_BASE_URL;\n}\n\n/**\n * GitHub reports Copilot access on `/copilot_internal/user`; OAuth itself\n * succeeds for any GitHub account, so this is the only signal that the account\n * can chat.\n */\nexport function gitHubCopilotEntitlementError(user: {\n\tchat_enabled?: boolean | undefined;\n\tcan_signup_for_limited?: boolean | undefined;\n}): string | undefined {\n\tif (user.chat_enabled !== false) return undefined;\n\tif (user.can_signup_for_limited) {\n\t\treturn \"This GitHub account is not signed up for GitHub Copilot. Sign up for Copilot Free at https://github.com/features/copilot/plans and connect again.\";\n\t}\n\treturn \"This GitHub account does not have GitHub Copilot access. It needs an active Copilot subscription or a seat assigned by an organization.\";\n}\n\nexport async function createGitHubCopilotDeviceFlow(\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<GitHubCopilotDeviceFlow> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\tconst response = await fetchWith(options)(`https://${domain}/login/device/code`, {\n\t\tmethod: \"POST\",\n\t\theaders: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({ client_id: CLIENT_ID, scope: SCOPE }),\n\t\tsignal: options.signal ?? null,\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub device code request failed (${response.status})`);\n\t}\n\n\tconst data: unknown = await response.json();\n\tif (!isObject(data)) throw new Error(\"Invalid GitHub device code response\");\n\tconst { device_code, user_code, verification_uri, interval, expires_in } = data;\n\tif (\n\t\ttypeof device_code !== \"string\" ||\n\t\ttypeof user_code !== \"string\" ||\n\t\ttypeof verification_uri !== \"string\" ||\n\t\t(interval !== undefined && typeof interval !== \"number\") ||\n\t\t(expires_in !== undefined && typeof expires_in !== \"number\")\n\t) {\n\t\tthrow new Error(\"Invalid GitHub device code response fields\");\n\t}\n\n\t// The verification URI is opened in the user's browser; force it to be a URL\n\t// so `open` cannot be tricked into launching something else.\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(verification_uri);\n\t} catch {\n\t\tthrow new Error(\"Untrusted verification_uri in GitHub device code response\");\n\t}\n\tif (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n\t\tthrow new Error(\"Untrusted verification_uri in GitHub device code response\");\n\t}\n\n\treturn {\n\t\tdeviceCode: device_code,\n\t\tuserCode: user_code,\n\t\tverificationUri: parsed.href,\n\t\tintervalSeconds: typeof interval === \"number\" && interval > 0 ? interval : 5,\n\t\t...(typeof expires_in === \"number\" && { expiresInSeconds: expires_in }),\n\t};\n}\n\nexport async function pollGitHubCopilotDeviceToken(\n\tflow: GitHubCopilotDeviceFlow,\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<string> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\tconst send = fetchWith(options);\n\n\treturn pollDeviceCode<string>({\n\t\tintervalSeconds: flow.intervalSeconds,\n\t\t...(flow.expiresInSeconds !== undefined && { expiresInSeconds: flow.expiresInSeconds }),\n\t\twaitBeforeFirstPoll: true,\n\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\tpoll: async () => {\n\t\t\tconst response = await send(`https://${domain}/login/oauth/access_token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tdevice_code: flow.deviceCode,\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal ?? null,\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\treturn { status: \"failed\", message: `GitHub device token poll failed (${response.status})` };\n\t\t\t}\n\n\t\t\tconst data: unknown = await response.json();\n\t\t\tif (!isObject(data)) return { status: \"failed\", message: \"Invalid GitHub device token response\" };\n\n\t\t\tif (typeof data.access_token === \"string\" && data.access_token) {\n\t\t\t\treturn { status: \"complete\", value: data.access_token };\n\t\t\t}\n\n\t\t\tconst error = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tif (error === \"authorization_pending\") return { status: \"pending\" };\n\t\t\tif (error === \"slow_down\") {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"slow_down\",\n\t\t\t\t\t...(typeof data.interval === \"number\" && data.interval > 0 && { intervalSeconds: data.interval }),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst description = typeof data.error_description === \"string\" ? `: ${data.error_description}` : \"\";\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `GitHub device authorization failed: ${error ?? \"unknown error\"}${description}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\n/**\n * Look up the account's Copilot entitlement and per-plan API endpoint.\n *\n * A failed or malformed lookup returns `undefined` rather than denying login —\n * only an explicit `chat_enabled: false` answer blocks.\n */\nexport async function fetchGitHubCopilotUser(\n\ttoken: string,\n\toptions: { domain?: string | undefined; fetch?: FetchLike | undefined; signal?: AbortSignal | undefined } = {},\n): Promise<GitHubCopilotUser | undefined> {\n\tconst domain = options.domain ?? DEFAULT_DOMAIN;\n\ttry {\n\t\tconst response = await fetchWith(options)(`https://${gitHubApiDomain(domain)}/copilot_internal/user`, {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\"User-Agent\": GITHUB_COPILOT_STATIC_HEADERS[\"User-Agent\"],\n\t\t\t\t\"X-GitHub-Api-Version\": USER_API_VERSION,\n\t\t\t},\n\t\t\tsignal: options.signal ?? null,\n\t\t});\n\t\tif (!response.ok) return undefined;\n\t\tconst data: unknown = await response.json();\n\t\tif (!isObject(data)) return undefined;\n\t\tconst endpoints = isObject(data.endpoints) ? data.endpoints : undefined;\n\t\treturn {\n\t\t\t...(typeof data.chat_enabled === \"boolean\" && { chatEnabled: data.chat_enabled }),\n\t\t\t...(typeof data.can_signup_for_limited === \"boolean\" && { canSignupForLimited: data.can_signup_for_limited }),\n\t\t\t...(typeof endpoints?.api === \"string\" && endpoints.api && { apiEndpoint: endpoints.api.replace(/\\/+$/, \"\") }),\n\t\t};\n\t} catch (error) {\n\t\tif (options.signal?.aborted) throw error;\n\t\treturn undefined;\n\t}\n}\n\nasync function fetchWithRateLimitRetry(\n\tsend: FetchLike,\n\turl: string,\n\tinit: RequestInit,\n\toptions: { signal?: AbortSignal; maxRetries: number; maxElapsedMs: number },\n): Promise<Response> {\n\tconst deadline = Date.now() + options.maxElapsedMs;\n\tfor (let retry = 0; ; retry++) {\n\t\tconst response = await send(url, { ...init, signal: options.signal ?? null });\n\t\tif (response.status !== 429 || retry >= options.maxRetries) return response;\n\n\t\tconst retryAfter = response.headers.get(\"retry-after\");\n\t\tlet delayMs = 500 * 2 ** retry;\n\t\tif (retryAfter) {\n\t\t\tconst seconds = Number.parseFloat(retryAfter);\n\t\t\tdelayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1000;\n\t\t\tif (!Number.isFinite(delayMs)) return response;\n\t\t}\n\t\tdelayMs = Math.max(0, delayMs);\n\t\tif (delayMs >= deadline - Date.now()) return response;\n\t\tawait response.body?.cancel();\n\t\tawait sleep(delayMs, options.signal);\n\t}\n}\n\n/**\n * The account-visible Copilot model catalog. `GET {base}/models` is the ground\n * truth for endpoint routing (`supported_endpoints`) and enablement (`policy`,\n * `model_picker_enabled`) — models.dev has no equivalent data.\n */\nexport async function fetchGitHubCopilotModels(\n\ttoken: string,\n\toptions: {\n\t\tbaseURL?: string | undefined;\n\t\tdomain?: string | undefined;\n\t\tfetch?: FetchLike | undefined;\n\t\tsignal?: AbortSignal | undefined;\n\t\tmaxRetries?: number | undefined;\n\t\tmaxElapsedMs?: number | undefined;\n\t} = {},\n): Promise<GitHubCopilotRemoteModel[]> {\n\tconst baseURL = options.baseURL ?? gitHubCopilotBaseUrl({ enterpriseUrl: options.domain });\n\tconst response = await fetchWithRateLimitRetry(\n\t\tfetchWith(options),\n\t\t`${baseURL}/models`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\t\t\"X-GitHub-Api-Version\": GITHUB_COPILOT_API_VERSION,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\tmaxRetries: options.maxRetries ?? DEFAULT_MODELS_RETRY.maxRetries,\n\t\t\tmaxElapsedMs: options.maxElapsedMs ?? DEFAULT_MODELS_RETRY.maxElapsedMs,\n\t\t},\n\t);\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot models request failed (${response.status})`);\n\t}\n\n\tconst data: unknown = await response.json();\n\tconst list = isObject(data) ? data.data : undefined;\n\tif (!Array.isArray(list)) throw new Error(\"Invalid GitHub Copilot models response\");\n\n\treturn list.flatMap((raw) => {\n\t\tif (!isObject(raw) || typeof raw.id !== \"string\") return [];\n\t\tconst capabilities = isObject(raw.capabilities) ? raw.capabilities : undefined;\n\t\tconst supports = isObject(capabilities?.supports) ? capabilities.supports : undefined;\n\t\tconst policy = isObject(raw.policy) ? raw.policy : undefined;\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: raw.id,\n\t\t\t\tsupportedEndpoints: Array.isArray(raw.supported_endpoints)\n\t\t\t\t\t? raw.supported_endpoints.filter((entry): entry is string => typeof entry === \"string\")\n\t\t\t\t\t: [],\n\t\t\t\t...(typeof policy?.state === \"string\" && { policyState: policy.state }),\n\t\t\t\tpickerEnabled: raw.model_picker_enabled === true,\n\t\t\t\ttoolCalls: supports?.tool_calls !== false,\n\t\t\t},\n\t\t];\n\t});\n}\n\n/**\n * Enable models the account has not configured yet (`policy.state ===\n * \"unconfigured\"`). Best effort per model; a rate limit that outlives the\n * retry budget stops the batch.\n */\nexport async function enableGitHubCopilotModels(\n\ttoken: string,\n\tmodelIds: readonly string[],\n\toptions: {\n\t\tbaseURL?: string | undefined;\n\t\tdomain?: string | undefined;\n\t\tfetch?: FetchLike | undefined;\n\t\tsignal?: AbortSignal | undefined;\n\t} = {},\n): Promise<string[]> {\n\tconst baseURL = options.baseURL ?? gitHubCopilotBaseUrl({ enterpriseUrl: options.domain });\n\tconst send = fetchWith(options);\n\tconst enabled: string[] = [];\n\tfor (const modelId of modelIds) {\n\t\ttry {\n\t\t\tconst response = await fetchWithRateLimitRetry(\n\t\t\t\tsend,\n\t\t\t\t`${baseURL}/models/${modelId}/policy`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\t\t\t\t\"openai-intent\": \"chat-policy\",\n\t\t\t\t\t\t\"x-interaction-type\": \"chat-policy\",\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ state: \"enabled\" }),\n\t\t\t\t},\n\t\t\t\t{ ...(options.signal !== undefined && { signal: options.signal }), maxRetries: 2, maxElapsedMs: 5000 },\n\t\t\t);\n\t\t\tif (response.status === 429) break;\n\t\t\tif (response.ok) enabled.push(modelId);\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw error;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn enabled;\n}\n\nfunction isGitHubCopilotCredentials(value: unknown): value is GitHubCopilotOAuthCredentials {\n\tif (!isObject(value)) return false;\n\treturn typeof value.access === \"string\" && typeof value.refresh === \"string\" && typeof value.expires === \"number\";\n}\n\nexport class JsonGitHubCopilotAuthStorage implements GitHubCopilotAuthStorage {\n\tprivate readonly storage: JsonAuthStorage<GitHubCopilotOAuthCredentials>;\n\n\tconstructor(options: JsonGitHubCopilotAuthStorageOptions = {}) {\n\t\tthis.storage = new JsonAuthStorage({\n\t\t\tproviderId: options.providerId ?? DEFAULT_PROVIDER_ID,\n\t\t\tisCredentials: isGitHubCopilotCredentials,\n\t\t\t...(options.path !== undefined && { path: options.path }),\n\t\t});\n\t}\n\n\tget path(): string {\n\t\treturn this.storage.path;\n\t}\n\n\tget providerId(): string {\n\t\treturn this.storage.providerId;\n\t}\n\n\tget(): Promise<GitHubCopilotOAuthCredentials | undefined> {\n\t\treturn this.storage.get();\n\t}\n\n\tset(credentials: GitHubCopilotOAuthCredentials): Promise<void> {\n\t\treturn this.storage.set(credentials);\n\t}\n\n\tclear(): Promise<void> {\n\t\treturn this.storage.clear();\n\t}\n}\n\nexport type GitHubCopilotOAuthClientOptions = {\n\tstorage?: GitHubCopilotAuthStorage;\n};\n\nexport class GitHubCopilotOAuthClient {\n\treadonly storage: GitHubCopilotAuthStorage;\n\n\tconstructor(options: GitHubCopilotOAuthClientOptions = {}) {\n\t\tthis.storage = options.storage ?? new JsonGitHubCopilotAuthStorage();\n\t}\n\n\tasync login(options: GitHubCopilotLoginOptions): Promise<GitHubCopilotOAuthCredentials> {\n\t\tconst enterpriseUrl = options.enterpriseUrl?.trim() || undefined;\n\t\tconst domain = normalizeGitHubDomain(enterpriseUrl) ?? DEFAULT_DOMAIN;\n\t\tif (enterpriseUrl && !normalizeGitHubDomain(enterpriseUrl)) {\n\t\t\tthrow new Error(\"Invalid GitHub Enterprise URL/domain\");\n\t\t}\n\n\t\tconst flow = await createGitHubCopilotDeviceFlow({ domain, fetch: options.fetch, signal: options.signal });\n\t\toptions.onAuth({\n\t\t\turl: flow.verificationUri,\n\t\t\tuserCode: flow.userCode,\n\t\t\tinstructions: \"Complete the GitHub device authorization to finish GitHub Copilot authentication.\",\n\t\t});\n\n\t\tconst access = await pollGitHubCopilotDeviceToken(flow, {\n\t\t\tdomain,\n\t\t\tfetch: options.fetch,\n\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t});\n\n\t\tconst user = await fetchGitHubCopilotUser(access, { domain, fetch: options.fetch, signal: options.signal });\n\t\tconst denied = user\n\t\t\t? gitHubCopilotEntitlementError({\n\t\t\t\t\tchat_enabled: user.chatEnabled,\n\t\t\t\t\tcan_signup_for_limited: user.canSignupForLimited,\n\t\t\t\t})\n\t\t\t: undefined;\n\t\tif (denied) throw new Error(denied);\n\n\t\tconst apiEndpoint =\n\t\t\tuser?.apiEndpoint ?? gitHubCopilotBaseUrl({ enterpriseUrl: domain === DEFAULT_DOMAIN ? undefined : domain });\n\n\t\toptions.onProgress?.(\"Fetching available Copilot models...\");\n\t\tlet availableModelIds: string[] | undefined;\n\t\tlet unconfigured: string[] = [];\n\t\ttry {\n\t\t\tconst models = await fetchGitHubCopilotModels(access, {\n\t\t\t\tbaseURL: apiEndpoint,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\t});\n\t\t\tconst usable = models.filter((model) => model.toolCalls && model.policyState !== \"disabled\");\n\t\t\tconst pickerIds = usable.filter((model) => model.pickerEnabled).map((model) => model.id);\n\t\t\t// Some Individual accounts report picker=false for every model despite\n\t\t\t// enabled policies; only that endpoint gets the policy fallback.\n\t\t\tconst host = new URL(apiEndpoint).hostname;\n\t\t\tconst policyFallback = pickerIds.length === 0 && host === \"api.individual.githubcopilot.com\";\n\t\t\tavailableModelIds = pickerIds.length\n\t\t\t\t? pickerIds\n\t\t\t\t: policyFallback\n\t\t\t\t\t? usable.filter((model) => model.policyState === \"enabled\").map((model) => model.id)\n\t\t\t\t\t: [];\n\t\t\tunconfigured = usable.filter((model) => model.policyState === \"unconfigured\").map((model) => model.id);\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted) throw error;\n\t\t\toptions.onProgress?.(\"Could not fetch the Copilot model catalog; continuing without it.\");\n\t\t}\n\n\t\tif (options.enableModels && unconfigured.length > 0) {\n\t\t\toptions.onProgress?.(\"Enabling Copilot models...\");\n\t\t\tconst enabled = await enableGitHubCopilotModels(access, unconfigured, {\n\t\t\t\tbaseURL: apiEndpoint,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\t\t});\n\t\t\tavailableModelIds = [...new Set([...(availableModelIds ?? []), ...enabled])];\n\t\t}\n\n\t\tconst credentials: GitHubCopilotOAuthCredentials = {\n\t\t\taccess,\n\t\t\trefresh: access,\n\t\t\texpires: 0,\n\t\t\t...(domain !== DEFAULT_DOMAIN && { enterpriseUrl: domain }),\n\t\t\tapiEndpoint,\n\t\t\t...(availableModelIds !== undefined && availableModelIds.length > 0 && { availableModelIds }),\n\t\t};\n\t\tawait this.storage.set(credentials);\n\t\treturn credentials;\n\t}\n\n\t/** The stored `ghu_` token, returned as-is — it never expires. */\n\tasync getCredentials(): Promise<GitHubCopilotOAuthCredentials | undefined> {\n\t\treturn this.storage.get();\n\t}\n\n\tasync getApiKey(): Promise<string | undefined> {\n\t\treturn (await this.getCredentials())?.access;\n\t}\n\n\tasync getHeaders(): Promise<Record<string, string> | undefined> {\n\t\tconst credentials = await this.getCredentials();\n\t\treturn credentials ? gitHubCopilotHeaders(credentials) : undefined;\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tawait this.storage.clear();\n\t}\n}\n\nexport function gitHubCopilotHeaders(credentials: GitHubCopilotOAuthCredentials): Record<string, string> {\n\treturn {\n\t\tAuthorization: `Bearer ${credentials.access}`,\n\t\t...GITHUB_COPILOT_STATIC_HEADERS,\n\t\t\"X-GitHub-Api-Version\": GITHUB_COPILOT_API_VERSION,\n\t};\n}\n\n/**\n * Resolve the GitHub Copilot API credential: `COPILOT_GITHUB_TOKEN` first, then\n * an explicit `auth --github-copilot` login from codework auth.json.\n *\n * Nothing else is consulted, by design. `GITHUB_TOKEN` and `GH_TOKEN` are\n * usually set for git or `gh` and carry no Copilot access — in GitHub Actions\n * `GITHUB_TOKEN` is a workflow token — so reading them turns a working login\n * into an unexplained 401. Credentials another application stored for itself\n * (an editor's Copilot sign-in) are not consulted either: a token codework was\n * never given should not silently become the identity its runs bill and act as.\n *\n * Returns undefined when nothing is available; the device flow only runs via\n * `GitHubCopilotOAuthClient#login`.\n */\nexport async function getGitHubCopilotApiKey(\n\toptions: GitHubCopilotOAuthClientOptions = {},\n): Promise<string | undefined> {\n\tconst dedicated = readEnv(GITHUB_COPILOT_API_KEY_ENV);\n\tif (dedicated) return dedicated;\n\n\treturn new GitHubCopilotOAuthClient(options).getApiKey();\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,6BAA6B;AAI1C,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAa,6BAA6B;AAC1C,MAAM,uBAAuB;CAAE,YAAY;CAAG,cAAc;AAAK;AA6DjE,SAAS,UAAU,SAAuD;CACzE,OAAO,QAAQ,SAAS,WAAW;AACpC;AAEA,SAAS,MAAM,IAAY,QAAqC;CAC/D,OAAO,IAAI,SAAS,SAAS,WAAW;EACvC,IAAI,QAAQ,SAAS;GACpB,uBAAO,IAAI,MAAM,gCAAgC,CAAC;GAClD;EACD;EACA,MAAM,UAAU,iBAAiB;GAChC,QAAQ,oBAAoB,SAAS,OAAO;GAC5C,QAAQ;EACT,GAAG,EAAE;EACL,MAAM,gBAAgB;GACrB,aAAa,OAAO;GACpB,uBAAO,IAAI,MAAM,gCAAgC,CAAC;EACnD;EACA,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC1D,CAAC;AACF;AAEA,SAAgB,sBAAsB,OAA+C;CACpF,MAAM,UAAU,OAAO,KAAK;CAC5B,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI;EAEH,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/providers/github-copilot/copilot-headers.ts
|
|
3
3
|
/**
|
|
4
4
|
* Copilot request identity.
|
|
@@ -101,4 +101,4 @@ function applyCopilotHeaders(headers, options) {
|
|
|
101
101
|
//#endregion
|
|
102
102
|
export { copilotRequestMetadata as i, GITHUB_COPILOT_STATIC_HEADERS as n, applyCopilotHeaders as r, GITHUB_COPILOT_API_VERSION as t };
|
|
103
103
|
|
|
104
|
-
//# sourceMappingURL=copilot-headers-
|
|
104
|
+
//# sourceMappingURL=copilot-headers-01-kLz8g.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-headers-
|
|
1
|
+
{"version":3,"file":"copilot-headers-01-kLz8g.mjs","names":[],"sources":["../../src/providers/github-copilot/copilot-headers.ts"],"sourcesContent":["/**\n * Copilot request identity.\n *\n * Every inference request must look like it came from the Copilot Chat client:\n * the static headers identify that client, while `x-initiator` and\n * `Copilot-Vision-Request` describe the serialized body.\n */\n\nimport { isAnthropicAdaptiveThinkingModel } from \"../../model/model.ts\";\n\nexport const GITHUB_COPILOT_API_VERSION = \"2026-08-01\";\n\nexport const GITHUB_COPILOT_STATIC_HEADERS = {\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} as const;\n\n/** `X-Interaction-Type` is `conversation-{type}`; only `agent` is wired today. */\nexport type GitHubCopilotInteractionType = \"agent\" | \"subagent\" | \"background\" | \"compaction\";\n\n// Copilot rejects these betas on adaptive-thinking Claude models.\nconst ADAPTIVE_UNSUPPORTED_BETAS = new Set([\n\t\"interleaved-thinking-2025-05-14\",\n\t\"fine-grained-tool-streaming-2025-05-14\",\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ntype RequestMetadata = { agent: boolean; vision: boolean };\n\nfunction responsesMetadata(input: unknown): RequestMetadata {\n\tconst list = Array.isArray(input) ? input : [];\n\tconst last = list[list.length - 1];\n\tlet vision = false;\n\tfor (const item of list) {\n\t\tif (!isRecord(item) || !Array.isArray(item.content)) continue;\n\t\tif (item.content.some((part) => isRecord(part) && part.type === \"input_image\")) vision = true;\n\t}\n\treturn { agent: isRecord(last) && last.role !== \"user\", vision };\n}\n\nfunction completionsMetadata(messages: unknown): RequestMetadata {\n\tconst list = Array.isArray(messages) ? messages : [];\n\tconst last = list[list.length - 1];\n\tlet vision = false;\n\tfor (const message of list) {\n\t\tif (!isRecord(message) || !Array.isArray(message.content)) continue;\n\t\tif (message.content.some((part) => isRecord(part) && part.type === \"image_url\")) vision = true;\n\t}\n\treturn { agent: isRecord(last) && last.role !== \"user\", vision };\n}\n\nfunction messagesMetadata(messages: unknown): RequestMetadata {\n\tconst list = Array.isArray(messages) ? messages : [];\n\tconst last = list[list.length - 1];\n\tlet vision = false;\n\tfor (const message of list) {\n\t\tif (!isRecord(message) || !Array.isArray(message.content)) continue;\n\t\tfor (const part of message.content) {\n\t\t\tif (!isRecord(part)) continue;\n\t\t\tif (part.type === \"image\") vision = true;\n\t\t\tif (\n\t\t\t\tpart.type === \"tool_result\" &&\n\t\t\t\tArray.isArray(part.content) &&\n\t\t\t\tpart.content.some((inner) => isRecord(inner) && inner.type === \"image\")\n\t\t\t) {\n\t\t\t\tvision = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst content = isRecord(last) && Array.isArray(last.content) ? last.content : [];\n\t// A trailing user turn that only carries tool_result parts is still an agent\n\t// step — it answers a tool call, not a human prompt.\n\tconst agent =\n\t\t!isRecord(last) || last.role !== \"user\" || !content.some((part) => isRecord(part) && part.type !== \"tool_result\");\n\treturn { agent, vision };\n}\n\n/** Derive `x-initiator` and `Copilot-Vision-Request` inputs from the serialized body. */\nexport function copilotRequestMetadata(url: string, body: unknown): RequestMetadata {\n\tif (!isRecord(body)) return { agent: false, vision: false };\n\tif (url.includes(\"/responses\")) return responsesMetadata(body.input);\n\tif (Array.isArray(body.messages)) {\n\t\treturn url.includes(\"/completions\") ? completionsMetadata(body.messages) : messagesMetadata(body.messages);\n\t}\n\treturn { agent: false, vision: false };\n}\n\nexport function applyCopilotHeaders(\n\theaders: Headers,\n\toptions: {\n\t\ttoken: string;\n\t\turl: string;\n\t\tbody: unknown;\n\t\tsessionId?: string;\n\t\tinteractionType?: GitHubCopilotInteractionType;\n\t},\n): void {\n\t// Whatever the adapters configured (API key, x-api-key) is replaced by the\n\t// resolved Copilot token; OAuth `ghu_`/`gho_` tokens are Bearer credentials.\n\theaders.delete(\"authorization\");\n\theaders.delete(\"x-api-key\");\n\theaders.set(\"Authorization\", `Bearer ${options.token}`);\n\n\tfor (const [key, value] of Object.entries(GITHUB_COPILOT_STATIC_HEADERS)) {\n\t\theaders.set(key, value);\n\t}\n\theaders.set(\"Openai-Intent\", \"conversation-edits\");\n\theaders.set(\"X-GitHub-Api-Version\", GITHUB_COPILOT_API_VERSION);\n\n\tconst interactionType = `conversation-${options.interactionType ?? \"agent\"}`;\n\theaders.set(\"X-Interaction-Type\", interactionType);\n\tif (options.sessionId) headers.set(\"X-Interaction-Id\", options.sessionId);\n\n\t// `x-initiator` can only escalate to `agent`, never back to `user` — a\n\t// non-agent interaction or an agent-shaped body overrides a declared `user`.\n\tif (interactionType !== \"conversation-agent\") {\n\t\theaders.set(\"x-initiator\", \"agent\");\n\t}\n\tconst metadata = copilotRequestMetadata(options.url, options.body);\n\tif (metadata.agent) {\n\t\theaders.set(\"x-initiator\", \"agent\");\n\t} else if (!headers.has(\"x-initiator\")) {\n\t\theaders.set(\"x-initiator\", \"user\");\n\t}\n\tif (metadata.vision) {\n\t\theaders.set(\"Copilot-Vision-Request\", \"true\");\n\t}\n\n\tconst model = isRecord(options.body) && typeof options.body.model === \"string\" ? options.body.model : undefined;\n\tconst beta = headers.get(\"anthropic-beta\");\n\tif (model && beta && isAnthropicAdaptiveThinkingModel(model)) {\n\t\tconst kept = beta\n\t\t\t.split(\",\")\n\t\t\t.map((entry) => entry.trim())\n\t\t\t.filter((entry) => entry && !ADAPTIVE_UNSUPPORTED_BETAS.has(entry));\n\t\tif (kept.length > 0) {\n\t\t\theaders.set(\"anthropic-beta\", kept.join(\",\"));\n\t\t} else {\n\t\t\theaders.delete(\"anthropic-beta\");\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,6BAA6B;AAE1C,MAAa,gCAAgC;CAC5C,cAAc;CACd,kBAAkB;CAClB,yBAAyB;CACzB,0BAA0B;AAC3B;AAMA,MAAM,6CAA6B,IAAI,IAAI,CAC1C,mCACA,wCACD,CAAC;AAED,SAAS,SAAS,OAAkD;CACnE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC3E;AAIA,SAAS,kBAAkB,OAAiC;CAC3D,MAAM,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;CAC7C,MAAM,OAAO,KAAK,KAAK,SAAS;CAChC,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,MAAM;EACxB,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,KAAK,OAAO,GAAG;EACrD,IAAI,KAAK,QAAQ,MAAM,SAAS,SAAS,IAAI,KAAK,KAAK,SAAS,aAAa,GAAG,SAAS;CAC1F;CACA,OAAO;EAAE,OAAO,SAAS,IAAI,KAAK,KAAK,SAAS;EAAQ;CAAO;AAChE;AAEA,SAAS,oBAAoB,UAAoC;CAChE,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC;CACnD,MAAM,OAAO,KAAK,KAAK,SAAS;CAChC,IAAI,SAAS;CACb,KAAK,MAAM,WAAW,MAAM;EAC3B,IAAI,CAAC,SAAS,OAAO,KAAK,CAAC,MAAM,QAAQ,QAAQ,OAAO,GAAG;EAC3D,IAAI,QAAQ,QAAQ,MAAM,SAAS,SAAS,IAAI,KAAK,K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-01-kLz8g.mjs";
|
|
2
2
|
import { LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
|
|
3
3
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
4
4
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
@@ -123,4 +123,4 @@ const githubCopilot = createGitHubCopilot();
|
|
|
123
123
|
//#endregion
|
|
124
124
|
export { createCopilotFetch as a, githubCopilot as i, GITHUB_COPILOT_PROVIDER_NAME as n, createGitHubCopilot as r, GITHUB_COPILOT_DEFAULT_BASE_URL as t };
|
|
125
125
|
|
|
126
|
-
//# sourceMappingURL=github-copilot-
|
|
126
|
+
//# sourceMappingURL=github-copilot-eDhLBMfL.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot-SIUCJz1G.mjs","names":[],"sources":["../../src/providers/github-copilot/copilot-fetch.ts","../../src/providers/github-copilot/copilot-provider.ts"],"sourcesContent":["import { LoadAPIKeyError } from \"@ai-sdk/provider\";\nimport { applyCopilotHeaders, type GitHubCopilotInteractionType } from \"./copilot-headers.ts\";\n\nexport type GitHubCopilotApiKey = string | (() => string | PromiseLike<string | undefined> | undefined);\n\nexport type CopilotFetchOptions = {\n\t/** Static token or async resolver — e.g. `() => getGitHubCopilotApiKey()`. */\n\tapiKey?: GitHubCopilotApiKey;\n\t/** Upstream fetch implementation; defaults to `globalThis.fetch`. */\n\tfetch?: typeof globalThis.fetch;\n\t/** Sent as `X-Interaction-Id` so Copilot can group requests by session. */\n\tsessionId?: string;\n\tinteractionType?: GitHubCopilotInteractionType;\n};\n\n// Only the Copilot-specific variable: GITHUB_TOKEN and GH_TOKEN are usually set\n// for git or `gh` and have no Copilot access.\nconst API_KEY_ENV = \"COPILOT_GITHUB_TOKEN\";\n\nasync function resolveToken(apiKey: GitHubCopilotApiKey | undefined): Promise<string> {\n\tconst resolved = typeof apiKey === \"function\" ? await apiKey() : apiKey;\n\tif (resolved) return resolved;\n\tconst fromEnv = typeof process === \"undefined\" ? undefined : process.env[API_KEY_ENV];\n\tif (fromEnv) return fromEnv;\n\tthrow new LoadAPIKeyError({\n\t\tmessage: `GitHub Copilot API key is missing. Set ${API_KEY_ENV}, pass an apiKey, or authenticate with \\`aikit auth --github-copilot\\`.`,\n\t});\n}\n\nfunction parseJson(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Wrap an upstream fetch with Copilot auth and request metadata. The wrapped\n * call replaces adapter-set auth headers, injects the Copilot identity\n * headers, and derives `x-initiator` / `Copilot-Vision-Request` from the\n * serialized JSON body without consuming it.\n */\nexport function createCopilotFetch(options: CopilotFetchOptions = {}): typeof globalThis.fetch {\n\tconst upstream = options.fetch ?? globalThis.fetch;\n\treturn async (input, init) => {\n\t\tconst token = await resolveToken(options.apiKey);\n\t\tconst headers = new Headers(init?.headers);\n\t\tconst url = input instanceof URL ? input.href : typeof input === \"string\" ? input : input.url;\n\t\tconst body = typeof init?.body === \"string\" ? parseJson(init.body) : undefined;\n\t\tapplyCopilotHeaders(headers, {\n\t\t\ttoken,\n\t\t\turl,\n\t\t\tbody,\n\t\t\t...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n\t\t\t...(options.interactionType !== undefined && { interactionType: options.interactionType }),\n\t\t});\n\t\treturn upstream(input, { ...init, headers });\n\t};\n}\n","/**\n * GitHub Copilot provider.\n *\n * Copilot exposes three inference protocols on one host — OpenAI Chat\n * Completions (`/chat/completions`), OpenAI Responses (`/responses`), and\n * Anthropic Messages (`/v1/messages`) — so this provider composes the official\n * AI SDK adapters behind one `ProviderV4` and routes each model through\n * `api.method`. Auth and Copilot request headers are applied inside the shared\n * fetch wrapper, which is why the adapters receive a placeholder key: their\n * headers never reach the wire.\n */\n\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { NoSuchModelError, type LanguageModelV4, type ProviderV4 } from \"@ai-sdk/provider\";\nimport { createCopilotFetch, type GitHubCopilotApiKey } from \"./copilot-fetch.ts\";\nimport type { GitHubCopilotInteractionType } from \"./copilot-headers.ts\";\n\nexport const GITHUB_COPILOT_DEFAULT_BASE_URL = \"https://api.githubcopilot.com\";\nexport const GITHUB_COPILOT_PROVIDER_NAME = \"github-copilot\";\n\nconst PLACEHOLDER_API_KEY = \"github-copilot\";\n\nexport interface GitHubCopilotProvider extends ProviderV4 {\n\t/** Chat Completions — the generic fallback for third-party models. */\n\t(modelId: string): LanguageModelV4;\n\tlanguageModel(modelId: string): LanguageModelV4;\n\t/** `POST /chat/completions` — Gemini, Kimi, and other third-party models. */\n\tchat(modelId: string): LanguageModelV4;\n\t/** `POST /responses` — GPT, Grok, OSWE, and MAI models. */\n\tresponses(modelId: string): LanguageModelV4;\n\t/** `POST /v1/messages` — Claude models. */\n\tmessages(modelId: string): LanguageModelV4;\n}\n\nexport interface GitHubCopilotProviderSettings {\n\t/**\n\t * Copilot API host. Defaults to `https://api.githubcopilot.com`; OAuth\n\t * credentials can carry a plan-specific `apiEndpoint` that overrides this.\n\t */\n\tbaseURL?: string;\n\t/**\n\t * GitHub OAuth token (`ghu_`/`gho_`) or an async resolver, e.g.\n\t * `() => getGitHubCopilotApiKey()`. Falls back to `COPILOT_GITHUB_TOKEN`.\n\t */\n\tapiKey?: GitHubCopilotApiKey;\n\t/** Extra headers merged into every request. */\n\theaders?: Record<string, string>;\n\t/** Custom fetch implementation, applied underneath the Copilot wrapper. */\n\tfetch?: typeof globalThis.fetch;\n\t/** Sent as `X-Interaction-Id` so Copilot can group requests by session. */\n\tsessionId?: string;\n\tinteractionType?: GitHubCopilotInteractionType;\n\t/** Forwarded to the Chat Completions adapter only. */\n\ttransformRequestBody?: (body: Record<string, unknown>) => Record<string, unknown>;\n}\n\nexport function createGitHubCopilot(options: GitHubCopilotProviderSettings = {}): GitHubCopilotProvider {\n\tconst baseURL = (options.baseURL ?? GITHUB_COPILOT_DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n\tconst fetch = createCopilotFetch({\n\t\t...(options.apiKey !== undefined && { apiKey: options.apiKey }),\n\t\t...(options.fetch !== undefined && { fetch: options.fetch }),\n\t\t...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n\t\t...(options.interactionType !== undefined && { interactionType: options.interactionType }),\n\t});\n\tconst headers = options.headers !== undefined ? { headers: options.headers } : {};\n\n\tconst chat = createOpenAICompatible({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\tbaseURL,\n\t\tapiKey: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t\tincludeUsage: true,\n\t\t...(options.transformRequestBody !== undefined && { transformRequestBody: options.transformRequestBody }),\n\t});\n\tconst responses = createOpenAI({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\tbaseURL,\n\t\tapiKey: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t});\n\tconst messages = createAnthropic({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\t// The Anthropic adapter appends /messages to its baseURL.\n\t\tbaseURL: `${baseURL}/v1`,\n\t\tauthToken: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t});\n\n\tconst provider = function (modelId: string): LanguageModelV4 {\n\t\tif (new.target) {\n\t\t\tthrow new Error(\"github copilot model function cannot be called with the new keyword.\");\n\t\t}\n\t\treturn chat.chatModel(modelId);\n\t};\n\tprovider.specificationVersion = \"v4\" as const;\n\tprovider.languageModel = (modelId: string) => chat.chatModel(modelId);\n\tprovider.chat = (modelId: string) => chat.chatModel(modelId);\n\tprovider.responses = (modelId: string) => responses.responses(modelId);\n\tprovider.messages = (modelId: string) => messages.messages(modelId);\n\tprovider.embeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({\n\t\t\tmodelId,\n\t\t\tmodelType: \"embeddingModel\",\n\t\t\tmessage: \"github copilot does not expose embedding models\",\n\t\t});\n\t};\n\tprovider.textEmbeddingModel = provider.embeddingModel;\n\tprovider.imageModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({\n\t\t\tmodelId,\n\t\t\tmodelType: \"imageModel\",\n\t\t\tmessage: \"github copilot does not expose image models\",\n\t\t});\n\t};\n\n\treturn provider;\n}\n\nexport const githubCopilot = createGitHubCopilot();\n"],"mappings":";;;;;;AAiBA,MAAM,cAAc;AAEpB,eAAe,aAAa,QAA0D;CACrF,MAAM,WAAW,OAAO,WAAW,aAAa,MAAM,OAAO,IAAI;CACjE,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,OAAO,YAAY,cAAc,KAAA,IAAY,QAAQ,IAAI;CACzE,IAAI,SAAS,OAAO;CACpB,MAAM,IAAI,gBAAgB,EACzB,SAAS,0CAA0C,YAAY,yEAChE,CAAC;AACF;AAEA,SAAS,UAAU,MAAuB;CACzC,IAAI;EACH,OAAO,KAAK,MAAM,IAAI;CACvB,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,mBAAmB,UAA+B,CAAC,GAA4B;CAC9F,MAAM,WAAW,QAAQ,SAAS,WAAW;CAC7C,OAAO,OAAO,OAAO,SAAS;EAC7B,MAAM,QAAQ,MAAM,aAAa,QAAQ,MAAM;EAC/C,MAAM,UAAU,IAAI,QAAQ,MAAM,OAAO;EACzC,MAAM,MAAM,iBAAiB,MAAM,MAAM,OAAO,OAAO,UAAU,WAAW,QAAQ,MAAM;EAC1F,MAAM,OAAO,OAAO,MAAM,SAAS,WAAW,UAAU,KAAK,IAAI,IAAI,KAAA;EACrE,oBAAoB,SAAS;GAC5B;GACA;GACA;GACA,GAAI,QAAQ,cAAc,KAAA,KAAa,EAAE,WAAW,QAAQ,UAAU;GACtE,GAAI,QAAQ,oBAAoB,KAAA,KAAa,EAAE,iBAAiB,QAAQ,gBAAgB;EACzF,CAAC;EACD,OAAO,SAAS,OAAO;GAAE,GAAG;GAAM;EAAQ,CAAC;CAC5C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;CAClE,SAAS,kBAAkB,YAAoB;EAC9C,MAAM,IAAI,iBAAiB;GAC1B;GACA,WAAW;GACX,SAAS;EACV,CAAC;CACF;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EAC1C,MAAM,IAAI,iBAAiB;GAC1B;GACA,WAAW;GACX,SAAS;EACV,CAAC;CACF;CAEA,OAAO;AACR;AAEA,MAAa,gBAAgB,oBAAoB"}
|
|
1
|
+
{"version":3,"file":"github-copilot-eDhLBMfL.mjs","names":[],"sources":["../../src/providers/github-copilot/copilot-fetch.ts","../../src/providers/github-copilot/copilot-provider.ts"],"sourcesContent":["import { LoadAPIKeyError } from \"@ai-sdk/provider\";\nimport { applyCopilotHeaders, type GitHubCopilotInteractionType } from \"./copilot-headers.ts\";\n\nexport type GitHubCopilotApiKey = string | (() => string | PromiseLike<string | undefined> | undefined);\n\nexport type CopilotFetchOptions = {\n\t/** Static token or async resolver — e.g. `() => getGitHubCopilotApiKey()`. */\n\tapiKey?: GitHubCopilotApiKey;\n\t/** Upstream fetch implementation; defaults to `globalThis.fetch`. */\n\tfetch?: typeof globalThis.fetch;\n\t/** Sent as `X-Interaction-Id` so Copilot can group requests by session. */\n\tsessionId?: string;\n\tinteractionType?: GitHubCopilotInteractionType;\n};\n\n// Only the Copilot-specific variable: GITHUB_TOKEN and GH_TOKEN are usually set\n// for git or `gh` and have no Copilot access.\nconst API_KEY_ENV = \"COPILOT_GITHUB_TOKEN\";\n\nasync function resolveToken(apiKey: GitHubCopilotApiKey | undefined): Promise<string> {\n\tconst resolved = typeof apiKey === \"function\" ? await apiKey() : apiKey;\n\tif (resolved) return resolved;\n\tconst fromEnv = typeof process === \"undefined\" ? undefined : process.env[API_KEY_ENV];\n\tif (fromEnv) return fromEnv;\n\tthrow new LoadAPIKeyError({\n\t\tmessage: `GitHub Copilot API key is missing. Set ${API_KEY_ENV}, pass an apiKey, or authenticate with \\`aikit auth --github-copilot\\`.`,\n\t});\n}\n\nfunction parseJson(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Wrap an upstream fetch with Copilot auth and request metadata. The wrapped\n * call replaces adapter-set auth headers, injects the Copilot identity\n * headers, and derives `x-initiator` / `Copilot-Vision-Request` from the\n * serialized JSON body without consuming it.\n */\nexport function createCopilotFetch(options: CopilotFetchOptions = {}): typeof globalThis.fetch {\n\tconst upstream = options.fetch ?? globalThis.fetch;\n\treturn async (input, init) => {\n\t\tconst token = await resolveToken(options.apiKey);\n\t\tconst headers = new Headers(init?.headers);\n\t\tconst url = input instanceof URL ? input.href : typeof input === \"string\" ? input : input.url;\n\t\tconst body = typeof init?.body === \"string\" ? parseJson(init.body) : undefined;\n\t\tapplyCopilotHeaders(headers, {\n\t\t\ttoken,\n\t\t\turl,\n\t\t\tbody,\n\t\t\t...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n\t\t\t...(options.interactionType !== undefined && { interactionType: options.interactionType }),\n\t\t});\n\t\treturn upstream(input, { ...init, headers });\n\t};\n}\n","/**\n * GitHub Copilot provider.\n *\n * Copilot exposes three inference protocols on one host — OpenAI Chat\n * Completions (`/chat/completions`), OpenAI Responses (`/responses`), and\n * Anthropic Messages (`/v1/messages`) — so this provider composes the official\n * AI SDK adapters behind one `ProviderV4` and routes each model through\n * `api.method`. Auth and Copilot request headers are applied inside the shared\n * fetch wrapper, which is why the adapters receive a placeholder key: their\n * headers never reach the wire.\n */\n\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { NoSuchModelError, type LanguageModelV4, type ProviderV4 } from \"@ai-sdk/provider\";\nimport { createCopilotFetch, type GitHubCopilotApiKey } from \"./copilot-fetch.ts\";\nimport type { GitHubCopilotInteractionType } from \"./copilot-headers.ts\";\n\nexport const GITHUB_COPILOT_DEFAULT_BASE_URL = \"https://api.githubcopilot.com\";\nexport const GITHUB_COPILOT_PROVIDER_NAME = \"github-copilot\";\n\nconst PLACEHOLDER_API_KEY = \"github-copilot\";\n\nexport interface GitHubCopilotProvider extends ProviderV4 {\n\t/** Chat Completions — the generic fallback for third-party models. */\n\t(modelId: string): LanguageModelV4;\n\tlanguageModel(modelId: string): LanguageModelV4;\n\t/** `POST /chat/completions` — Gemini, Kimi, and other third-party models. */\n\tchat(modelId: string): LanguageModelV4;\n\t/** `POST /responses` — GPT, Grok, OSWE, and MAI models. */\n\tresponses(modelId: string): LanguageModelV4;\n\t/** `POST /v1/messages` — Claude models. */\n\tmessages(modelId: string): LanguageModelV4;\n}\n\nexport interface GitHubCopilotProviderSettings {\n\t/**\n\t * Copilot API host. Defaults to `https://api.githubcopilot.com`; OAuth\n\t * credentials can carry a plan-specific `apiEndpoint` that overrides this.\n\t */\n\tbaseURL?: string;\n\t/**\n\t * GitHub OAuth token (`ghu_`/`gho_`) or an async resolver, e.g.\n\t * `() => getGitHubCopilotApiKey()`. Falls back to `COPILOT_GITHUB_TOKEN`.\n\t */\n\tapiKey?: GitHubCopilotApiKey;\n\t/** Extra headers merged into every request. */\n\theaders?: Record<string, string>;\n\t/** Custom fetch implementation, applied underneath the Copilot wrapper. */\n\tfetch?: typeof globalThis.fetch;\n\t/** Sent as `X-Interaction-Id` so Copilot can group requests by session. */\n\tsessionId?: string;\n\tinteractionType?: GitHubCopilotInteractionType;\n\t/** Forwarded to the Chat Completions adapter only. */\n\ttransformRequestBody?: (body: Record<string, unknown>) => Record<string, unknown>;\n}\n\nexport function createGitHubCopilot(options: GitHubCopilotProviderSettings = {}): GitHubCopilotProvider {\n\tconst baseURL = (options.baseURL ?? GITHUB_COPILOT_DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n\tconst fetch = createCopilotFetch({\n\t\t...(options.apiKey !== undefined && { apiKey: options.apiKey }),\n\t\t...(options.fetch !== undefined && { fetch: options.fetch }),\n\t\t...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n\t\t...(options.interactionType !== undefined && { interactionType: options.interactionType }),\n\t});\n\tconst headers = options.headers !== undefined ? { headers: options.headers } : {};\n\n\tconst chat = createOpenAICompatible({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\tbaseURL,\n\t\tapiKey: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t\tincludeUsage: true,\n\t\t...(options.transformRequestBody !== undefined && { transformRequestBody: options.transformRequestBody }),\n\t});\n\tconst responses = createOpenAI({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\tbaseURL,\n\t\tapiKey: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t});\n\tconst messages = createAnthropic({\n\t\tname: GITHUB_COPILOT_PROVIDER_NAME,\n\t\t// The Anthropic adapter appends /messages to its baseURL.\n\t\tbaseURL: `${baseURL}/v1`,\n\t\tauthToken: PLACEHOLDER_API_KEY,\n\t\t...headers,\n\t\tfetch,\n\t});\n\n\tconst provider = function (modelId: string): LanguageModelV4 {\n\t\tif (new.target) {\n\t\t\tthrow new Error(\"github copilot model function cannot be called with the new keyword.\");\n\t\t}\n\t\treturn chat.chatModel(modelId);\n\t};\n\tprovider.specificationVersion = \"v4\" as const;\n\tprovider.languageModel = (modelId: string) => chat.chatModel(modelId);\n\tprovider.chat = (modelId: string) => chat.chatModel(modelId);\n\tprovider.responses = (modelId: string) => responses.responses(modelId);\n\tprovider.messages = (modelId: string) => messages.messages(modelId);\n\tprovider.embeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({\n\t\t\tmodelId,\n\t\t\tmodelType: \"embeddingModel\",\n\t\t\tmessage: \"github copilot does not expose embedding models\",\n\t\t});\n\t};\n\tprovider.textEmbeddingModel = provider.embeddingModel;\n\tprovider.imageModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({\n\t\t\tmodelId,\n\t\t\tmodelType: \"imageModel\",\n\t\t\tmessage: \"github copilot does not expose image models\",\n\t\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GACA,WAAW;GACX,SAAS;EACV,CAAC;CACF;CAEA,OAAO;AACR;AAEA,MAAa,gBAAgB,oBAAoB"}
|
package/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as KnownProviderEnum, c as ThinkingBudgets$1, d as getProviders, f as model_d_exports, i as Info, l as getModel, m as registry, n as ActiveThinkingLevel, o as ProviderToProtocol, p as modelsAreEqual, r as Compatibility, s as TModel, t as APIMethodEnum, u as getModels } from "./model-
|
|
1
|
+
import { a as KnownProviderEnum, c as ThinkingBudgets$1, d as getProviders, f as model_d_exports, i as Info, l as getModel, m as registry, n as ActiveThinkingLevel, o as ProviderToProtocol, p as modelsAreEqual, r as Compatibility, s as TModel, t as APIMethodEnum, u as getModels } from "./model-BetbWJV7.mjs";
|
|
2
2
|
import { t as failure_d_exports } from "./failure-5Wjd-qFH.mjs";
|
|
3
3
|
import Type$2, { Static, Static as Static$1, TSchema, TSchema as TSchema$1, Type, Type as Type$1 } from "typebox";
|
|
4
4
|
import { APICallError, LanguageModelV3, LanguageModelV4, ProviderV3, ProviderV4 } from "@ai-sdk/provider";
|
package/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
-
import { C as NamedError, _ as optionsKey, a as KnownProviderEnumSchema, c as calculateCost, d as getModels, f as getProviders, h as modelsAreEqual, i as KnownProviderEnum, l as clampThinkingLevel, m as model_exports, n as APIMethodEnumSchema, r as ActiveThinkingLevel, s as ThinkingBudgets$1, t as APIMethodEnum, u as getModel, v as registry, y as thinkingTokenBudgetField } from "./model-
|
|
3
|
-
import { C as ToolCallSchema, D as transformMessages, E as resolveJsonSchemaConstraint, S as AssistantMessageSchema, T as message_exports, g as shortHash, n as createOpenAICodex, r as openaiCodex, v as openAICodexTools, w as createAssistantMessage$1, x as resolveOpenAICodexToolConstraint } from "./openai-codex-
|
|
2
|
+
import { C as NamedError, _ as optionsKey, a as KnownProviderEnumSchema, c as calculateCost, d as getModels, f as getProviders, h as modelsAreEqual, i as KnownProviderEnum, l as clampThinkingLevel, m as model_exports, n as APIMethodEnumSchema, r as ActiveThinkingLevel, s as ThinkingBudgets$1, t as APIMethodEnum, u as getModel, v as registry, y as thinkingTokenBudgetField } from "./model-Czo0SKj0.mjs";
|
|
3
|
+
import { C as ToolCallSchema, D as transformMessages, E as resolveJsonSchemaConstraint, S as AssistantMessageSchema, T as message_exports, g as shortHash, n as createOpenAICodex, r as openaiCodex, v as openAICodexTools, w as createAssistantMessage$1, x as resolveOpenAICodexToolConstraint } from "./openai-codex-CpaJcE8Q.mjs";
|
|
4
4
|
import { r as normalize, t as failure_exports } from "./failure-SAPyG-w2.mjs";
|
|
5
|
-
import { i as packageForModel, o as resolveLanguageModel, r as loadProviderFactory } from "./registry-
|
|
6
|
-
import { i as githubCopilot, r as createGitHubCopilot } from "./github-copilot-
|
|
5
|
+
import { i as packageForModel, o as resolveLanguageModel, r as loadProviderFactory } from "./registry-vtzL8QxA.mjs";
|
|
6
|
+
import { i as githubCopilot, r as createGitHubCopilot } from "./github-copilot-eDhLBMfL.mjs";
|
|
7
7
|
import Type$2, { Type, Type as Type$1 } from "typebox";
|
|
8
8
|
import { jsonSchema, streamText } from "ai";
|
|
9
9
|
import { parse } from "partial-json";
|
|
@@ -5,7 +5,7 @@ declare function lazy<T>(fn: () => T): {
|
|
|
5
5
|
reset: () => void;
|
|
6
6
|
};
|
|
7
7
|
declare namespace catalog_d_exports {
|
|
8
|
-
export { GeneratedCatalog, KnownProviderEnum$1 as KnownProviderEnum, KnownProviderEnumSchema$1 as KnownProviderEnumSchema, ModelCatalogLoadError$1 as ModelCatalogLoadError, data, filename, get, load, path, projectRoot };
|
|
8
|
+
export { GeneratedCatalog, KnownProviderEnum$1 as KnownProviderEnum, KnownProviderEnumSchema$1 as KnownProviderEnumSchema, ModelCatalogLoadError$1 as ModelCatalogLoadError, configure, data, filename, get, load, path, projectRoot };
|
|
9
9
|
}
|
|
10
10
|
declare const KnownProviderEnum$1: {
|
|
11
11
|
readonly anthropic: "anthropic";
|
|
@@ -430,12 +430,17 @@ declare const ModelCatalogLoadError$1: {
|
|
|
430
430
|
type ModelCatalogLoadError$1 = InstanceType<typeof ModelCatalogLoadError$1>;
|
|
431
431
|
declare function projectRoot(): string;
|
|
432
432
|
declare const filename = "models.gen.json";
|
|
433
|
+
/**
|
|
434
|
+
* Read the catalog from `catalogPath` instead of `./models.gen.json`, for an
|
|
435
|
+
* embedder that keeps it elsewhere. `CODEWORK_MODELS_FILE` still wins.
|
|
436
|
+
*/
|
|
437
|
+
declare function configure(catalogPath: string): void;
|
|
433
438
|
declare function path(): string;
|
|
434
439
|
declare function load(catalogPath?: string): Promise<GeneratedCatalog>;
|
|
435
440
|
declare const data: LazyGeneratedCatalog;
|
|
436
441
|
declare function get(): Promise<GeneratedCatalog>;
|
|
437
442
|
declare namespace model_d_exports {
|
|
438
|
-
export { APIMetadata, APIMetadataSchema, APIMethodEnum, APIMethodEnumSchema, ActiveThinkingLevel, BuiltInModels, Compatibility, CompatibilitySchema, ExtrasSchema, Info, KnownProviderEnum, KnownProviderEnumSchema, ModelCatalogLoadError, ProviderInfo, ProviderToProtocol, Schema, TModel, ThinkingBudgets, ThinkingLevel, ThinkingLevelEnum, ThinkingLevelMap, ThinkingLevelMapSchema, calculateCost, clampThinkingLevel, getBuiltInModels, getModel, getModels, getProviders, getSupportedThinkingLevels, isAnthropicAdaptiveThinkingModel, modelsAreEqual, normalizeInput, optionsKey, registry, supportsProtocol, thinkingTokenBudgetField };
|
|
443
|
+
export { APIMetadata, APIMetadataSchema, APIMethodEnum, APIMethodEnumSchema, ActiveThinkingLevel, BuiltInModels, Compatibility, CompatibilitySchema, ExtrasSchema, Info, KnownProviderEnum, KnownProviderEnumSchema, ModelCatalogLoadError, ProviderInfo, ProviderToProtocol, Schema, TModel, ThinkingBudgets, ThinkingLevel, ThinkingLevelEnum, ThinkingLevelMap, ThinkingLevelMapSchema, calculateCost, catalogPath, clampThinkingLevel, configureCatalog, getBuiltInModels, getModel, getModels, getProviders, getSupportedThinkingLevels, isAnthropicAdaptiveThinkingModel, modelsAreEqual, normalizeInput, optionsKey, registry, reloadCatalog, supportsProtocol, thinkingTokenBudgetField };
|
|
439
444
|
}
|
|
440
445
|
declare const KnownProviderEnum: {
|
|
441
446
|
readonly anthropic: "anthropic";
|
|
@@ -1129,6 +1134,12 @@ declare function calculateCost(model: Info, usage: {
|
|
|
1129
1134
|
}): void;
|
|
1130
1135
|
type BuiltInModels = Partial<Record<string, Record<string, Info>>>;
|
|
1131
1136
|
declare function normalizeInput(input?: string[]): Array<"text" | "image">;
|
|
1137
|
+
/** Where the catalog is read from: `CODEWORK_MODELS_FILE`, the configured path, or `./models.gen.json`. */
|
|
1138
|
+
declare const catalogPath: typeof path;
|
|
1139
|
+
/** Read the catalog from `path` from now on, dropping whatever was already loaded. */
|
|
1140
|
+
declare function configureCatalog(path: string): void;
|
|
1141
|
+
/** Drop the loaded catalog, so the next lookup re-reads the file -- after it was regenerated. */
|
|
1142
|
+
declare function reloadCatalog(): void;
|
|
1132
1143
|
declare function getBuiltInModels(): Promise<BuiltInModels>;
|
|
1133
1144
|
declare const registry: {
|
|
1134
1145
|
(): Promise<Map<string, Map<string, {
|
|
@@ -1244,4 +1255,4 @@ declare function getSupportedThinkingLevels<TProtocol extends KnownProviderEnum>
|
|
|
1244
1255
|
declare function clampThinkingLevel<TProtocol extends KnownProviderEnum>(model: TModel<TProtocol>, level: ThinkingLevel): ThinkingLevel;
|
|
1245
1256
|
//#endregion
|
|
1246
1257
|
export { KnownProviderEnum as a, ThinkingBudgets as c, getProviders as d, model_d_exports as f, Info as i, getModel as l, registry as m, ActiveThinkingLevel as n, ProviderToProtocol as o, modelsAreEqual as p, Compatibility as r, TModel as s, APIMethodEnum as t, getModels as u };
|
|
1247
|
-
//# sourceMappingURL=model-
|
|
1258
|
+
//# sourceMappingURL=model-BetbWJV7.d.mts.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import Type$1 from "typebox";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
|
+
import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
|
|
4
5
|
import { dirname } from "path";
|
|
5
|
-
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
6
6
|
//#region src/utils/lazy.ts
|
|
7
7
|
function lazy(fn) {
|
|
8
8
|
let value;
|
|
@@ -91,6 +91,20 @@ async function write(path, content, mode) {
|
|
|
91
91
|
async function writeJson(path, data, mode) {
|
|
92
92
|
return write(path, JSON.stringify(data, null, 2), mode);
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Write through a temp file and rename it into place, so a concurrent reader
|
|
96
|
+
* sees either the old content or the new, never a partial file.
|
|
97
|
+
*/
|
|
98
|
+
async function writeJsonAtomic(path, data) {
|
|
99
|
+
const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
100
|
+
try {
|
|
101
|
+
await writeJson(temp, data);
|
|
102
|
+
await rename(temp, path);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
await rm(temp, { force: true });
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
94
108
|
//#endregion
|
|
95
109
|
//#region src/model/catalog.ts
|
|
96
110
|
const KnownProviderEnum$1 = {
|
|
@@ -130,8 +144,17 @@ const ModelCatalogLoadError$1 = NamedError.create("ModelCatalogLoadError", Type$
|
|
|
130
144
|
function projectRoot() {
|
|
131
145
|
return process.cwd();
|
|
132
146
|
}
|
|
147
|
+
let configured;
|
|
148
|
+
/**
|
|
149
|
+
* Read the catalog from `catalogPath` instead of `./models.gen.json`, for an
|
|
150
|
+
* embedder that keeps it elsewhere. `CODEWORK_MODELS_FILE` still wins.
|
|
151
|
+
*/
|
|
152
|
+
function configure(catalogPath) {
|
|
153
|
+
configured = resolve(catalogPath);
|
|
154
|
+
data.reset();
|
|
155
|
+
}
|
|
133
156
|
function path() {
|
|
134
|
-
return resolve(process.env.CODEWORK_MODELS_FILE ?? join(projectRoot(), "models.gen.json"));
|
|
157
|
+
return resolve(process.env.CODEWORK_MODELS_FILE ?? configured ?? join(projectRoot(), "models.gen.json"));
|
|
135
158
|
}
|
|
136
159
|
async function load(catalogPath = path()) {
|
|
137
160
|
let content;
|
|
@@ -186,7 +209,9 @@ var model_exports = /* @__PURE__ */ __exportAll({
|
|
|
186
209
|
ThinkingLevelEnum: () => ThinkingLevelEnum,
|
|
187
210
|
ThinkingLevelMapSchema: () => ThinkingLevelMapSchema,
|
|
188
211
|
calculateCost: () => calculateCost,
|
|
212
|
+
catalogPath: () => catalogPath,
|
|
189
213
|
clampThinkingLevel: () => clampThinkingLevel,
|
|
214
|
+
configureCatalog: () => configureCatalog,
|
|
190
215
|
getBuiltInModels: () => getBuiltInModels,
|
|
191
216
|
getModel: () => getModel,
|
|
192
217
|
getModels: () => getModels,
|
|
@@ -197,6 +222,7 @@ var model_exports = /* @__PURE__ */ __exportAll({
|
|
|
197
222
|
normalizeInput: () => normalizeInput,
|
|
198
223
|
optionsKey: () => optionsKey,
|
|
199
224
|
registry: () => registry,
|
|
225
|
+
reloadCatalog: () => reloadCatalog,
|
|
200
226
|
supportsProtocol: () => supportsProtocol,
|
|
201
227
|
thinkingTokenBudgetField: () => thinkingTokenBudgetField
|
|
202
228
|
});
|
|
@@ -389,6 +415,18 @@ function normalizeInput(input) {
|
|
|
389
415
|
if (normalized.size === 0) normalized.add("text");
|
|
390
416
|
return [...normalized];
|
|
391
417
|
}
|
|
418
|
+
/** Where the catalog is read from: `CODEWORK_MODELS_FILE`, the configured path, or `./models.gen.json`. */
|
|
419
|
+
const catalogPath = path;
|
|
420
|
+
/** Read the catalog from `path` from now on, dropping whatever was already loaded. */
|
|
421
|
+
function configureCatalog(path) {
|
|
422
|
+
configure(path);
|
|
423
|
+
registry.reset();
|
|
424
|
+
}
|
|
425
|
+
/** Drop the loaded catalog, so the next lookup re-reads the file -- after it was regenerated. */
|
|
426
|
+
function reloadCatalog() {
|
|
427
|
+
data.reset();
|
|
428
|
+
registry.reset();
|
|
429
|
+
}
|
|
392
430
|
async function getBuiltInModels() {
|
|
393
431
|
return await get();
|
|
394
432
|
}
|
|
@@ -477,6 +515,6 @@ function clampThinkingLevel(model, level) {
|
|
|
477
515
|
return availableLevels[0] ?? "off";
|
|
478
516
|
}
|
|
479
517
|
//#endregion
|
|
480
|
-
export { NamedError as C,
|
|
518
|
+
export { NamedError as C, writeJsonAtomic as S, optionsKey as _, KnownProviderEnumSchema as a, path as b, calculateCost as c, getModels as d, getProviders as f, normalizeInput as g, modelsAreEqual as h, KnownProviderEnum as i, clampThinkingLevel as l, model_exports as m, APIMethodEnumSchema as n, ProviderInfo as o, isAnthropicAdaptiveThinkingModel as p, ActiveThinkingLevel as r, ThinkingBudgets as s, APIMethodEnum as t, getModel as u, registry as v, readJson as x, thinkingTokenBudgetField as y };
|
|
481
519
|
|
|
482
|
-
//# sourceMappingURL=model-
|
|
520
|
+
//# sourceMappingURL=model-Czo0SKj0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-Czo0SKj0.mjs","names":["KnownProviderEnum","KnownProviderEnumSchema","Type","ModelCatalogLoadError","Filesystem.readText","ModelCatalog.KnownProviderEnum","ModelCatalog.KnownProviderEnumSchema","ModelCatalog.ModelCatalogLoadError","Type","ModelCatalog.path","ModelCatalog.get"],"sources":["../../src/utils/lazy.ts","../../src/utils/error.ts","../../src/utils/filesystem.ts","../../src/model/catalog.ts","../../src/model/model.ts"],"sourcesContent":["export function lazy<T>(fn: () => T) {\n\tlet value: T | undefined;\n\tlet loaded = false;\n\n\tconst result = (): T => {\n\t\tif (loaded) return value as T;\n\t\tvalue = fn();\n\t\tloaded = true;\n\t\treturn value as T;\n\t};\n\n\tresult.reset = () => {\n\t\tloaded = false;\n\t\tvalue = undefined;\n\t};\n\n\treturn result;\n}\n","import type { Static, TSchema } from \"typebox\";\n\ntype SchemaLike = TSchema;\ntype StaticData<Data extends SchemaLike> = Static<Data>;\n\nexport abstract class NamedError extends Error {\n\tabstract schema(): SchemaLike;\n\tabstract toObject(): { name: string; data: unknown };\n\n\tstatic create<Name extends string, Data extends SchemaLike>(name: Name, data: Data) {\n\t\tconst schema = {\n\t\t\t$id: name,\n\t\t\ttype: \"object\",\n\t\t\trequired: [\"name\", \"data\"],\n\t\t\tproperties: {\n\t\t\t\tname: {\n\t\t\t\t\tconst: name,\n\t\t\t\t},\n\t\t\t\tdata,\n\t\t\t},\n\t\t} as const;\n\n\t\tconst result = class extends NamedError {\n\t\t\tpublic static readonly Schema = schema;\n\n\t\t\tpublic override readonly name = name as Name;\n\n\t\t\tpublic readonly data: StaticData<Data>;\n\n\t\t\tconstructor(data: StaticData<Data>, options?: ErrorOptions) {\n\t\t\t\tsuper(name, options);\n\t\t\t\tthis.data = data;\n\t\t\t\tthis.name = name;\n\t\t\t}\n\n\t\t\tstatic isInstance(input: unknown): input is InstanceType<typeof result> {\n\t\t\t\treturn typeof input === \"object\" && input !== null && \"name\" in input && input.name === name;\n\t\t\t}\n\n\t\t\tschema() {\n\t\t\t\treturn schema;\n\t\t\t}\n\n\t\t\ttoObject() {\n\t\t\t\treturn {\n\t\t\t\t\tname,\n\t\t\t\t\tdata: this.data,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tObject.defineProperty(result, \"name\", { value: name });\n\t\treturn result;\n\t}\n\n\tpublic static readonly Unknown = NamedError.create(\"UnknownError\", {\n\t\ttype: \"object\",\n\t\trequired: [\"message\"],\n\t\tproperties: {\n\t\t\tmessage: {\n\t\t\t\ttype: \"string\",\n\t\t\t},\n\t\t},\n\t});\n}\n","import { mkdir, readFile, rename, rm, writeFile } from \"fs/promises\";\nimport { dirname } from \"path\";\n\nexport async function readText(path: string): Promise<string> {\n\treturn readFile(path, \"utf-8\");\n}\n\nexport async function readJson<T = unknown>(path: string): Promise<T> {\n\treturn JSON.parse(await readFile(path, \"utf-8\"));\n}\n\nfunction isEnoent(error: unknown): error is { code: \"ENOENT\" } {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code: string }).code === \"ENOENT\"\n\t);\n}\n\nexport async function write(path: string, content: string | Buffer | Uint8Array, mode?: number): Promise<void> {\n\ttry {\n\t\tif (mode) {\n\t\t\tawait writeFile(path, content, { mode });\n\t\t} else {\n\t\t\tawait writeFile(path, content);\n\t\t}\n\t} catch (error) {\n\t\tif (isEnoent(error)) {\n\t\t\tawait mkdir(dirname(path), { recursive: true });\n\t\t\tif (mode) {\n\t\t\t\tawait writeFile(path, content, { mode });\n\t\t\t} else {\n\t\t\t\tawait writeFile(path, content);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function writeJson(path: string, data: unknown, mode?: number): Promise<void> {\n\treturn write(path, JSON.stringify(data, null, 2), mode);\n}\n\n/**\n * Write through a temp file and rename it into place, so a concurrent reader\n * sees either the old content or the new, never a partial file.\n */\nexport async function writeJsonAtomic(path: string, data: unknown): Promise<void> {\n\tconst temp = `${path}.${process.pid}.${Date.now()}.tmp`;\n\ttry {\n\t\tawait writeJson(temp, data);\n\t\tawait rename(temp, path);\n\t} catch (error) {\n\t\tawait rm(temp, { force: true });\n\t\tthrow error;\n\t}\n}\n","import { join, resolve } from \"node:path\";\nimport Type, { type Static } from \"typebox\";\nimport { NamedError } from \"../utils/error.ts\";\nimport * as Filesystem from \"../utils/filesystem.ts\";\nimport { lazy } from \"../utils/lazy.ts\";\n\n// known AI SDK LLM providers\n// used as the public protocol discriminator for the AI SDK transport layer\nexport const KnownProviderEnum = {\n\tanthropic: \"anthropic\",\n\tgoogle: \"google\",\n\tgoogleVertex: \"google-vertex\",\n\tgoogleVertexAnthropic: \"google-vertex-anthropic\",\n\tgithubCopilot: \"github-copilot\",\n\topenai: \"openai\",\n\topenaiCompatible: \"openai-compatible\",\n\topenaiCodex: \"openai-codex\",\n\topenrouter: \"openrouter\",\n\txai: \"xai\",\n} as const;\nexport const KnownProviderEnumSchema = Type.Union([\n\tType.Literal(KnownProviderEnum.anthropic),\n\tType.Literal(KnownProviderEnum.google),\n\tType.Literal(KnownProviderEnum.googleVertex),\n\tType.Literal(KnownProviderEnum.googleVertexAnthropic),\n\tType.Literal(KnownProviderEnum.githubCopilot),\n\tType.Literal(KnownProviderEnum.openai),\n\tType.Literal(KnownProviderEnum.openaiCompatible),\n\tType.Literal(KnownProviderEnum.openaiCodex),\n\tType.Literal(KnownProviderEnum.openrouter),\n\tType.Literal(KnownProviderEnum.xai),\n]);\nexport type KnownProviderEnum = Static<typeof KnownProviderEnumSchema>;\n\nexport type GeneratedCatalog = Partial<Record<string, Record<string, unknown>>>;\ntype LazyGeneratedCatalog = ReturnType<typeof lazy<Promise<GeneratedCatalog>>>;\n\nexport const ModelCatalogLoadError = NamedError.create(\n\t\"ModelCatalogLoadError\",\n\tType.Object({\n\t\tpath: Type.String(),\n\t\treason: Type.Union([\n\t\t\tType.Literal(\"missing\"),\n\t\t\tType.Literal(\"unreadable\"),\n\t\t\tType.Literal(\"empty\"),\n\t\t\tType.Literal(\"invalid\"),\n\t\t]),\n\t\tmessage: Type.String(),\n\t}),\n);\nexport type ModelCatalogLoadError = InstanceType<typeof ModelCatalogLoadError>;\n\nexport function projectRoot(): string {\n\treturn process.cwd();\n}\n\nexport const filename = \"models.gen.json\";\n\nlet configured: string | undefined;\n\n/**\n * Read the catalog from `catalogPath` instead of `./models.gen.json`, for an\n * embedder that keeps it elsewhere. `CODEWORK_MODELS_FILE` still wins.\n */\nexport function configure(catalogPath: string): void {\n\tconfigured = resolve(catalogPath);\n\tdata.reset();\n}\n\nexport function path(): string {\n\treturn resolve(process.env.CODEWORK_MODELS_FILE ?? configured ?? join(projectRoot(), filename));\n}\n\nexport async function load(catalogPath = path()): Promise<GeneratedCatalog> {\n\tlet content: string;\n\ttry {\n\t\tcontent = await Filesystem.readText(catalogPath);\n\t} catch (cause) {\n\t\tconst value =\n\t\t\ttypeof cause === \"object\" && cause !== null && \"code\" in cause && typeof cause.code === \"string\"\n\t\t\t\t? cause.code\n\t\t\t\t: undefined;\n\t\tconst reason = value === \"ENOENT\" ? \"missing\" : \"unreadable\";\n\t\tthrow new ModelCatalogLoadError(\n\t\t\t{\n\t\t\t\tpath: catalogPath,\n\t\t\t\treason,\n\t\t\t\tmessage:\n\t\t\t\t\treason === \"missing\"\n\t\t\t\t\t\t? `model catalog not found at ${catalogPath}`\n\t\t\t\t\t\t: `model catalog could not be read at ${catalogPath}`,\n\t\t\t},\n\t\t\t{ cause },\n\t\t);\n\t}\n\tif (!content.trim()) {\n\t\tthrow new ModelCatalogLoadError({\n\t\t\tpath: catalogPath,\n\t\t\treason: \"empty\",\n\t\t\tmessage: `model catalog is empty at ${catalogPath}`,\n\t\t});\n\t}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(content);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) throw new Error(\"expected an object\");\n\t\treturn parsed as GeneratedCatalog;\n\t} catch (cause) {\n\t\tthrow new ModelCatalogLoadError(\n\t\t\t{\n\t\t\t\tpath: catalogPath,\n\t\t\t\treason: \"invalid\",\n\t\t\t\tmessage: `model catalog contains invalid json at ${catalogPath}`,\n\t\t\t},\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\nexport const data: LazyGeneratedCatalog = lazy(() => load());\n\nexport async function get(): Promise<GeneratedCatalog> {\n\treturn data();\n}\n","import Type, { type Static } from \"typebox\";\nimport { lazy } from \"../utils/lazy.ts\";\nimport * as ModelCatalog from \"./catalog.ts\";\n\n// re-export\nexport const KnownProviderEnum = ModelCatalog.KnownProviderEnum;\nexport const KnownProviderEnumSchema = ModelCatalog.KnownProviderEnumSchema;\nexport type KnownProviderEnum = ModelCatalog.KnownProviderEnum;\n\nexport const ModelCatalogLoadError = ModelCatalog.ModelCatalogLoadError;\nexport type ModelCatalogLoadError = ModelCatalog.ModelCatalogLoadError;\n\n// Common reasoning-effort levels used by adapters that expose model reasoning,\n// thinking, or deliberation controls. Protocol-specific layers can map these\n// values to native fields like OpenAI `reasoning_effort`, Anthropic `thinking`,\n// or Gemini `thinkingConfig`.\nexport const ThinkingLevelEnum = {\n\t// Disable explicit reasoning controls when the provider supports turning them off.\n\toff: \"off\",\n\t// Smallest reasoning budget/effort above off; useful for fastest low-cost responses.\n\tminimal: \"minimal\",\n\t// Light reasoning for simple tasks that still benefit from some deliberation.\n\tlow: \"low\",\n\t// Balanced default for general tasks.\n\tmedium: \"medium\",\n\t// Higher reasoning effort for complex coding, analysis, or planning.\n\thigh: \"high\",\n\t// Extra-high reasoning effort for difficult tasks when supported by the model.\n\txhigh: \"xhigh\",\n\t// Maximum provider-defined effort above xhigh when explicitly supported by the model.\n\tmax: \"max\",\n} as const;\n\nexport const ThinkingLevel = Type.Union([\n\tType.Literal(ThinkingLevelEnum.off),\n\tType.Literal(ThinkingLevelEnum.minimal),\n\tType.Literal(ThinkingLevelEnum.low),\n\tType.Literal(ThinkingLevelEnum.medium),\n\tType.Literal(ThinkingLevelEnum.high),\n\tType.Literal(ThinkingLevelEnum.xhigh),\n\tType.Literal(ThinkingLevelEnum.max),\n]);\nexport type ThinkingLevel = Static<typeof ThinkingLevel>;\n\nexport const ActiveThinkingLevel = Type.Union([\n\tType.Literal(ThinkingLevelEnum.minimal),\n\tType.Literal(ThinkingLevelEnum.low),\n\tType.Literal(ThinkingLevelEnum.medium),\n\tType.Literal(ThinkingLevelEnum.high),\n\tType.Literal(ThinkingLevelEnum.xhigh),\n\tType.Literal(ThinkingLevelEnum.max),\n]);\nexport type ActiveThinkingLevel = Static<typeof ActiveThinkingLevel>;\n\nexport const ThinkingBudgets = Type.Partial(Type.Record(ActiveThinkingLevel, Type.Number()));\nexport type ThinkingBudgets = Static<typeof ThinkingBudgets>;\n\n// Note: order of entries matters!\nconst ACTIVE_THINKING_LEVELS = [\n\tThinkingLevelEnum.minimal,\n\tThinkingLevelEnum.low,\n\tThinkingLevelEnum.medium,\n\tThinkingLevelEnum.high,\n\tThinkingLevelEnum.xhigh,\n\tThinkingLevelEnum.max,\n] as const satisfies readonly ActiveThinkingLevel[];\nconst MODEL_THINKING_LEVELS = [\n\tThinkingLevelEnum.off,\n\t...ACTIVE_THINKING_LEVELS,\n] as const satisfies readonly ThinkingLevel[];\n\nexport const ProviderInfo = Type.Object({\n\tid: Type.String(),\n\tname: Type.String(),\n\tsource: Type.Enum([\"env\", \"config\", \"custom\", \"api\", \"unknown\"]),\n\tenv: Type.Array(Type.String()),\n\tkey: Type.Optional(Type.String()), // runtime api/oauth key\n\toptions: Type.Optional(Type.Record(Type.String(), Type.Any())),\n});\nexport type ProviderInfo = Static<typeof ProviderInfo>;\n\nconst InputSchema = Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]));\nconst CostRatesSchema = Type.Object({\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n});\nconst CostTierSchema = Type.Object({\n\t...CostRatesSchema.properties,\n\tinputTokensAbove: Type.Number(),\n});\nconst CostSchema = Type.Object({\n\t...CostRatesSchema.properties,\n\ttiers: Type.Optional(Type.Array(CostTierSchema)),\n\tserviceTierMultipliers: Type.Optional(Type.Record(Type.String(), Type.Number())),\n});\nconst SupportedProtocolsSchema = Type.Partial(\n\tType.Object({\n\t\tanthropic: KnownProviderEnumSchema,\n\t\tgoogle: KnownProviderEnumSchema,\n\t\tgoogleVertex: KnownProviderEnumSchema,\n\t\tgoogleVertexAnthropic: KnownProviderEnumSchema,\n\t\tgithubCopilot: KnownProviderEnumSchema,\n\t\topenai: KnownProviderEnumSchema,\n\t\topenaiCompatible: KnownProviderEnumSchema,\n\t\topenaiCodex: KnownProviderEnumSchema,\n\t\topenrouter: KnownProviderEnumSchema,\n\t\txai: KnownProviderEnumSchema,\n\t}),\n);\n\nexport const APIMethodEnum = {\n\tlanguageModel: \"languageModel\",\n\tchat: \"chat\",\n\tcompletion: \"completion\",\n\tcompletionModel: \"completionModel\",\n\tmessages: \"messages\",\n\tresponses: \"responses\",\n} as const;\nexport const APIMethodEnumSchema = Type.Union([\n\tType.Literal(APIMethodEnum.languageModel),\n\tType.Literal(APIMethodEnum.chat),\n\tType.Literal(APIMethodEnum.completion),\n\tType.Literal(APIMethodEnum.completionModel),\n\tType.Literal(APIMethodEnum.messages),\n\tType.Literal(APIMethodEnum.responses),\n]);\nexport type APIMethodEnum = Static<typeof APIMethodEnumSchema>;\n\nexport const APIMetadataSchema = Type.Object({\n\tid: Type.Optional(Type.String()),\n\turl: Type.Optional(Type.String()),\n\tmethod: Type.Optional(APIMethodEnumSchema),\n});\nexport type APIMetadata = Static<typeof APIMetadataSchema>;\n\nexport const ThinkingLevelMapSchema = Type.Partial(\n\tType.Record(\n\t\tThinkingLevel, // Safe key validation\n\t\tType.Union([Type.String(), Type.Null()]), // Allowed values\n\t),\n);\nexport type ThinkingLevelMap = Static<typeof ThinkingLevelMapSchema>;\n\nexport const CompatibilitySchema = Type.Object({\n\t/** The Google protocol accepts thinking levels rather than a token budget. */\n\tsupportsThinkingLevel: Type.Optional(Type.Boolean()),\n\tsupportsToolSearch: Type.Optional(Type.Boolean()),\n\tsupportsAdditionalTools: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\t/** The model takes a thinking-token budget as a top-level request field. */\n\tsupportsThinkingTokenBudget: Type.Optional(Type.Boolean()),\n\t/** Claude model that sizes its own thinking, driven by `effort` instead of a token budget. */\n\tforceAdaptiveThinking: Type.Optional(Type.Boolean()),\n\t/** Name of that field, when it is not the conventional `thinking_token_budget`. */\n\tthinkingTokenBudgetField: Type.Optional(Type.String()),\n});\nexport type Compatibility = Static<typeof CompatibilitySchema>;\n\n/**\n * Claude models that decide their own thinking depth.\n *\n * These take an `effort` level and let the model size each turn's reasoning; the\n * older models take a fixed `budget_tokens` instead. Sending a budget to an\n * adaptive model pins it to one depth for every turn, which is the thing adaptive\n * thinking exists to avoid.\n */\nexport function isAnthropicAdaptiveThinkingModel(modelId: string): boolean {\n\treturn [\n\t\t\"opus-4-6\",\n\t\t\"opus-4.6\",\n\t\t\"opus-4-7\",\n\t\t\"opus-4.7\",\n\t\t\"opus-4-8\",\n\t\t\"opus-4.8\",\n\t\t\"opus-5\",\n\t\t\"opus.5\",\n\t\t\"sonnet-4-6\",\n\t\t\"sonnet-4.6\",\n\t\t\"sonnet-5\",\n\t\t\"sonnet.5\",\n\t\t\"fable-5\",\n\t].some((needle) => modelId.includes(needle));\n}\n\nexport const Schema = Type.Object({\n\tid: Type.String(),\n\tname: Type.String(),\n\tprovider: ProviderInfo,\n\tbaseUrl: Type.String(),\n\treasoning: Type.Boolean(),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\t/** Default budgets; request-level thinkingBudgets take precedence. */\n\tthinkingBudgets: Type.Optional(ThinkingBudgets),\n\tinput: InputSchema,\n\tcost: CostSchema,\n\tcontextWindow: Type.Number(),\n\tmaxTokens: Type.Number(),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tnpm: Type.Optional(Type.String()),\n\tapi: Type.Optional(APIMetadataSchema),\n\tproviderOptionsKey: Type.Optional(Type.String()),\n\toptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\tproviderOptions: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n\tcompat: Type.Optional(CompatibilitySchema),\n\tprotocol: KnownProviderEnumSchema, // provider as the underlying protocol\n\tsupportedProtocols: Type.Optional(SupportedProtocolsSchema), // provider as the underlying supported protocols\n});\n\nexport const ExtrasSchema = Type.Object({});\n\nexport const Info = Type.Evaluate(Type.Intersect([Schema, ExtrasSchema]));\nexport type Info = Static<typeof Info>;\nexport type TModel<TProtocol extends KnownProviderEnum> = Omit<Info, \"protocol\"> & { protocol: TProtocol };\n\nexport function calculateCost(\n\tmodel: Info,\n\tusage: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcacheWrite1h?: number;\n\t\tcost: {\n\t\t\tinput: number;\n\t\t\toutput: number;\n\t\t\tcacheRead: number;\n\t\t\tcacheWrite: number;\n\t\t\ttotal: number;\n\t\t};\n\t},\n): void {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes; `cost.cacheWrite` is the 5m rate.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\n\tusage.cost.input = (usage.input / 1_000_000) * rates.input;\n\tusage.cost.output = (usage.output / 1_000_000) * rates.output;\n\tusage.cost.cacheRead = (usage.cacheRead / 1_000_000) * rates.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1_000_000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n\nexport type BuiltInModels = Partial<Record<string, Record<string, Info>>>;\n\nexport function normalizeInput(input?: string[]): Array<\"text\" | \"image\"> {\n\tconst normalized = new Set<\"text\" | \"image\">();\n\tfor (const modality of input ?? [\"text\"]) {\n\t\tif (modality === \"text\" || modality === \"image\") {\n\t\t\tnormalized.add(modality);\n\t\t}\n\t}\n\tif (normalized.size === 0) normalized.add(\"text\");\n\treturn [...normalized];\n}\n\n/** Where the catalog is read from: `CODEWORK_MODELS_FILE`, the configured path, or `./models.gen.json`. */\nexport const catalogPath = ModelCatalog.path;\n\n/** Read the catalog from `path` from now on, dropping whatever was already loaded. */\nexport function configureCatalog(path: string): void {\n\tModelCatalog.configure(path);\n\tregistry.reset();\n}\n\n/** Drop the loaded catalog, so the next lookup re-reads the file -- after it was regenerated. */\nexport function reloadCatalog(): void {\n\tModelCatalog.data.reset();\n\tregistry.reset();\n}\n\nexport async function getBuiltInModels(): Promise<BuiltInModels> {\n\treturn (await ModelCatalog.get()) as BuiltInModels;\n}\n\nexport const registry = lazy(async () => {\n\tconst registry: Map<string, Map<string, Info>> = new Map();\n\tconst models = await getBuiltInModels();\n\tfor (const [provider, value] of Object.entries(models) as Array<[string, Record<string, Info>]>) {\n\t\tconst providerModels = new Map<string, Info>();\n\t\tfor (const [id, model] of Object.entries(value)) {\n\t\t\tproviderModels.set(id, model);\n\t\t}\n\t\tregistry.set(provider, providerModels);\n\t}\n\treturn registry;\n});\n\n/**\n * The key a provider's own option bag is filed under.\n *\n * Providers that speak another provider's protocol still carry their own option\n * namespace, so this is not always the protocol.\n */\n/**\n * The request-body field a model takes its thinking-token budget in, if any.\n *\n * OpenAI-compatible endpoints have no standard place for this, so each one names\n * its own field; a bare `supportsThinkingTokenBudget` means the conventional name.\n */\nexport function thinkingTokenBudgetField(model: Info): string | undefined {\n\tif (model.compat?.thinkingTokenBudgetField) return model.compat.thinkingTokenBudgetField;\n\treturn model.compat?.supportsThinkingTokenBudget ? \"thinking_token_budget\" : undefined;\n}\n\nexport function optionsKey(model: Info): string {\n\treturn model.providerOptionsKey ?? model.protocol;\n}\n\nexport function supportsProtocol(model: Info, protocol: KnownProviderEnum): boolean {\n\tif (model.protocol === protocol) return true;\n\treturn Object.values(model.supportedProtocols ?? {}).includes(protocol);\n}\n\nexport type ProviderToProtocol<TProvider extends string> = TProvider extends KnownProviderEnum\n\t? TProvider\n\t: KnownProviderEnum;\n\nexport async function getModel<\n\tTProvider extends string,\n\tTProtocol extends KnownProviderEnum = ProviderToProtocol<TProvider>,\n>(\n\tprovider: TProvider,\n\tmodel: string,\n\toverrides?: Partial<Info> & { protocol?: TProtocol },\n): Promise<TModel<TProtocol> | undefined> {\n\tconst data = await registry();\n\tconst providerModels = data.get(provider);\n\tconst result = providerModels?.get(model);\n\tif (result && overrides) {\n\t\tif (overrides.protocol && !supportsProtocol(result, overrides.protocol)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\t...result,\n\t\t\t...overrides,\n\t\t} as TModel<TProtocol>;\n\t}\n\treturn result as TModel<TProtocol> | undefined;\n}\n\nexport async function getProviders(): Promise<string[]> {\n\tconst data = await registry();\n\treturn Array.from(data.keys());\n}\n\nexport async function getModels<TProvider extends string>(provider: TProvider): Promise<Info[]> {\n\tconst data = await registry();\n\tconst models = data.get(provider);\n\treturn models ? Array.from(models.values()) : [];\n}\n\n/**\n * Check if two models are equal by comparing both their id and provider id.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual(a: Info | null | undefined, b: Info | null | undefined): boolean {\n\tif (!a || !b) return false;\n\treturn a.id === b.id && a.provider.id === b.provider.id;\n}\n\nexport function getSupportedThinkingLevels<TProtocol extends KnownProviderEnum>(\n\tmodel: TModel<TProtocol>,\n): ThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn MODEL_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TProtocol extends KnownProviderEnum>(\n\tmodel: TModel<TProtocol>,\n\tlevel: ThinkingLevel,\n): ThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = MODEL_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\t// walk up the ladder from the point and pick first supported\n\t// biased to avail more thinking, then less not round to nearest.\n\tfor (let i = requestedIndex; i < MODEL_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = MODEL_THINKING_LEVELS[i]!;\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\t// otherwise walk down from the point\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = MODEL_THINKING_LEVELS[i]!;\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n"],"mappings":";;;;;;AAAA,SAAgB,KAAQ,IAAa;CACpC,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,eAAkB;EACvB,IAAI,QAAQ,OAAO;EACnB,QAAQ,GAAG;EACX,SAAS;EACT,OAAO;CACR;CAEA,OAAO,cAAc;EACpB,SAAS;EACT,QAAQ,KAAA;CACT;CAEA,OAAO;AACR;;;ACZA,IAAsB,aAAtB,MAAsB,mBAAmB,MAAM;CAI9C,OAAO,OAAqD,MAAY,MAAY;EACnF,MAAM,SAAS;GACd,KAAK;GACL,MAAM;GACN,UAAU,CAAC,QAAQ,MAAM;GACzB,YAAY;IACX,MAAM,EACL,OAAO,KACR;IACA;GACD;EACD;EAEA,MAAM,SAAS,cAAc,WAAW;GACvC,OAAuB,SAAS;GAEhC,OAAgC;GAEhC;GAEA,YAAY,MAAwB,SAAwB;IAC3D,MAAM,MAAM,OAAO;IACnB,KAAK,OAAO;IACZ,KAAK,OAAO;GACb;GAEA,OAAO,WAAW,OAAsD;IACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;GACzF;GAEA,SAAS;IACR,OAAO;GACR;GAEA,WAAW;IACV,OAAO;KACN;KACA,MAAM,KAAK;IACZ;GACD;EACD;EAEA,OAAO,eAAe,QAAQ,QAAQ,EAAE,OAAO,KAAK,CAAC;EACrD,OAAO;CACR;CAEA,OAAuB,UAAU,WAAW,OAAO,gBAAgB;EAClE,MAAM;EACN,UAAU,CAAC,SAAS;EACpB,YAAY,EACX,SAAS,EACR,MAAM,SACP,EACD;CACD,CAA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