@codeworksh/aikit 0.10.0 → 0.11.0-dev.20261012163102
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-bFammM5T.mjs → copilot-JLgwmznn.mjs} +2 -2
- package/{copilot-bFammM5T.mjs.map → copilot-JLgwmznn.mjs.map} +1 -1
- package/{copilot-headers-01-kLz8g.mjs → copilot-headers-BvQ3FFn-.mjs} +2 -2
- package/{copilot-headers-01-kLz8g.mjs.map → copilot-headers-BvQ3FFn-.mjs.map} +1 -1
- package/{failure-CN0horoO.mjs → failure-DFQNKc-O.mjs} +23 -6
- package/failure-DFQNKc-O.mjs.map +1 -0
- package/{github-copilot-eDhLBMfL.mjs → github-copilot-C7oJ2Tfp.mjs} +2 -2
- package/{github-copilot-eDhLBMfL.mjs.map → github-copilot-C7oJ2Tfp.mjs.map} +1 -1
- package/github-copilot-CLJx-bcP.mjs +3 -0
- package/index.d.mts +46 -6
- package/index.mjs +238 -16
- package/index.mjs.map +1 -1
- package/llm/failure.mjs +1 -1
- package/{model-Czo0SKj0.mjs → model-D-FoGzVN.mjs} +5 -3
- package/model-D-FoGzVN.mjs.map +1 -0
- package/{model-yhqJA3dm.d.mts → model-DCfjY0fS.d.mts} +2 -2
- package/{modelgen-BHm-jA64.mjs → modelgen-D6UBM1fq.mjs} +5 -5
- package/modelgen-D6UBM1fq.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-CIBVNhQx.mjs +2 -0
- package/{openai-codex-MpxV35tx.mjs → openai-codex-Dj0oh0UV.mjs} +26 -15
- package/openai-codex-Dj0oh0UV.mjs.map +1 -0
- package/package.json +1 -1
- package/{registry-CZtcfRPL.mjs → registry-CfGgGfSs.mjs} +4 -4
- package/{registry-CZtcfRPL.mjs.map → registry-CfGgGfSs.mjs.map} +1 -1
- package/failure-CN0horoO.mjs.map +0 -1
- package/github-copilot-gMaBI_-X.mjs +0 -3
- package/model-Czo0SKj0.mjs.map +0 -1
- package/modelgen-BHm-jA64.mjs.map +0 -1
- package/openai-codex-CvdfMYoU.mjs +0 -2
- package/openai-codex-MpxV35tx.mjs.map +0 -1
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-D6UBM1fq.mjs";
|
|
4
|
+
import { i as JsonGitHubCopilotAuthStorage, r as GitHubCopilotOAuthClient } from "./copilot-JLgwmznn.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.
|
|
10
|
+
var version = "0.11.0";
|
|
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-BvQ3FFn-.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-JLgwmznn.mjs.map
|
|
@@ -1 +1 @@
|
|
|
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,QADY,QAAQ,SAAS,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,IAAI,IAAI,WAAW,SAAS,EAAA,CAC1E;CACZ,QAAQ;EACP;CACD;AACD;;AAGA,SAAgB,gBAAgB,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QAAQ,QAAQ,OAAO;GAC9D,CAAC;GACD,oBAAoB,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAI,qBAAqB,CAAC,GAAI,GAAG,OAAO,CAAC,CAAC;EAC5E;EAEA,MAAM,cAA6C;GAClD;GACA,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-JLgwmznn.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,S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UAAU;AACxD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as isAnthropicAdaptiveThinkingModel } from "./model-D-FoGzVN.mjs";
|
|
2
2
|
//#region src/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-BvQ3FFn-.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-headers-
|
|
1
|
+
{"version":3,"file":"copilot-headers-BvQ3FFn-.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,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,OAAO,gBAAgB;CAEjC;AACD"}
|
|
@@ -76,13 +76,30 @@ const apiMetadata = (error) => {
|
|
|
76
76
|
};
|
|
77
77
|
};
|
|
78
78
|
const includes = (value, terms) => value !== void 0 && terms.some((term) => value.toLowerCase().includes(term));
|
|
79
|
+
/**
|
|
80
|
+
* Account limits that reset in hours or need a payment, not a backoff. Codes cover OpenAI's
|
|
81
|
+
* `insufficient_quota`, Codex's `subscription_sharing_usage_limit_exceeded` and OpenCode's
|
|
82
|
+
* `GoUsageLimitError`/`FreeUsageLimitError`; the prose covers providers that only say it in words,
|
|
83
|
+
* except when they describe a per-minute window, which is throttling however it is phrased.
|
|
84
|
+
*/
|
|
85
|
+
const QUOTA_CODE_TERMS = [
|
|
86
|
+
"quota",
|
|
87
|
+
"billing",
|
|
88
|
+
"credit",
|
|
89
|
+
"usage_limit",
|
|
90
|
+
"usagelimit"
|
|
91
|
+
];
|
|
92
|
+
const QUOTA_MESSAGE = /usage limit|quota exceeded|insufficient (?:quota|credits?)|credit balance|billing|out of budget|available balance/i;
|
|
93
|
+
const RATE_LIMIT_CODE_TERMS = ["rate_limit", "ratelimit"];
|
|
94
|
+
const RATE_WINDOW_MESSAGE = /per[- ](?:second|minute)|\b[rt]pm\b/i;
|
|
95
|
+
const isQuota = (details) => {
|
|
96
|
+
if (includes(details.code, RATE_LIMIT_CODE_TERMS)) return false;
|
|
97
|
+
if (includes(details.code, QUOTA_CODE_TERMS)) return true;
|
|
98
|
+
return QUOTA_MESSAGE.test(details.message) && !RATE_WINDOW_MESSAGE.test(details.message);
|
|
99
|
+
};
|
|
79
100
|
/** Classify by provider error code, then HTTP status; shared by request and in-stream failures. */
|
|
80
101
|
const classify = (statusCode, details) => {
|
|
81
|
-
if (
|
|
82
|
-
"quota",
|
|
83
|
-
"billing",
|
|
84
|
-
"credit"
|
|
85
|
-
])) return {
|
|
102
|
+
if (isQuota(details)) return {
|
|
86
103
|
_tag: "Quota",
|
|
87
104
|
...details
|
|
88
105
|
};
|
|
@@ -228,4 +245,4 @@ function fromMessage(message) {
|
|
|
228
245
|
//#endregion
|
|
229
246
|
export { fromMessage as n, normalize as r, failure_exports as t };
|
|
230
247
|
|
|
231
|
-
//# sourceMappingURL=failure-
|
|
248
|
+
//# sourceMappingURL=failure-DFQNKc-O.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"failure-DFQNKc-O.mjs","names":[],"sources":["../../src/llm/failure.ts"],"sourcesContent":["import {\n\tAPICallError,\n\tEmptyResponseBodyError,\n\tInvalidArgumentError,\n\tInvalidPromptError,\n\tInvalidResponseDataError,\n\tJSONParseError,\n\tLoadAPIKeyError,\n\tLoadSettingError,\n\tNoContentGeneratedError,\n\tNoSuchModelError,\n\tTypeValidationError,\n\tUnsupportedFunctionalityError,\n} from \"@ai-sdk/provider\";\nimport { RetryError, StreamProviderError } from \"ai\";\nimport type { Failure } from \"./failure/schema.ts\";\n\nexport * from \"./failure/schema.ts\";\n\ntype Metadata = Omit<Failure, \"_tag\" | \"reason\">;\n\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n\nconst normalizeMessage = (message: string): string => {\n\tconst trimmed = message.trim().replace(/[.!?]+$/u, \"\");\n\treturn trimmed.replace(/^[A-Za-z]+/u, (word) => word.toLowerCase());\n};\n\nconst errorMessage = (error: unknown): string => {\n\tconst value = record(error);\n\tconst data = record(value?.data);\n\tif (value?.name === \"ProtocolAuthError\") {\n\t\treturn normalizeMessage(nonEmptyString(data?.message) ?? \"provider credentials are missing\");\n\t}\n\tif (error instanceof Error) return normalizeMessage(nonEmptyString(error.message) ?? error.name);\n\treturn normalizeMessage(nonEmptyString(error) ?? \"the provider request failed for an unknown reason\");\n};\n\nconst isProtocolAuthError = (error: unknown): boolean => {\n\tconst value = record(error);\n\treturn value?.name === \"ProtocolAuthError\";\n};\n\nconst errorCode = (data: unknown): string | undefined => {\n\tconst top = record(data);\n\tconst nested = record(top?.error);\n\treturn (\n\t\tnonEmptyString(top?.code) ??\n\t\tnonEmptyString(top?.type) ??\n\t\tnonEmptyString(nested?.code) ??\n\t\tnonEmptyString(nested?.type)\n\t);\n};\n\nconst header = (headers: Record<string, string> | undefined, name: string): string | undefined => {\n\tif (headers === undefined) return undefined;\n\tconst expected = name.toLowerCase();\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (key.toLowerCase() === expected) return nonEmptyString(value);\n\t}\n};\n\n/** The server's requested wait, in the three forms providers send: `retry-after-ms`, seconds, or an HTTP date. */\nconst retryAfter = (headers: Record<string, string> | undefined): number | undefined => {\n\tconst millis = Number(header(headers, \"retry-after-ms\"));\n\tif (Number.isFinite(millis) && millis >= 0) return millis;\n\tconst value = header(headers, \"retry-after\");\n\tif (value === undefined) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1_000;\n\tconst date = Date.parse(value);\n\tif (Number.isFinite(date)) return Math.max(0, date - Date.now());\n};\n\nconst apiMetadata = (error: APICallError): Metadata => {\n\tconst code = errorCode(error.data);\n\tconst data = record(error.data);\n\tconst nested = record(data?.error);\n\tconst structuredMessage = nonEmptyString(data?.message) ?? nonEmptyString(nested?.message);\n\tconst message = normalizeMessage(\n\t\tstructuredMessage ??\n\t\t\t(error.responseBody !== undefined && error.message.includes(error.responseBody)\n\t\t\t\t? `provider request failed${error.statusCode === undefined ? \"\" : ` with http ${error.statusCode}`}`\n\t\t\t\t: errorMessage(error)),\n\t);\n\tconst requestId =\n\t\theader(error.responseHeaders, \"x-request-id\") ??\n\t\theader(error.responseHeaders, \"x-oai-request-id\") ??\n\t\theader(error.responseHeaders, \"request-id\") ??\n\t\theader(error.responseHeaders, \"cf-ray\");\n\tconst retryAfterMs = retryAfter(error.responseHeaders);\n\treturn {\n\t\tmessage,\n\t\tretryable: error.isRetryable,\n\t\t...(error.statusCode === undefined ? {} : { status: error.statusCode }),\n\t\t...(code === undefined ? {} : { code }),\n\t\t...(requestId === undefined ? {} : { requestId }),\n\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t};\n};\n\nconst includes = (value: string | undefined, terms: ReadonlyArray<string>): boolean =>\n\tvalue !== undefined && terms.some((term) => value.toLowerCase().includes(term));\n\n/**\n * Account limits that reset in hours or need a payment, not a backoff. Codes cover OpenAI's\n * `insufficient_quota`, Codex's `subscription_sharing_usage_limit_exceeded` and OpenCode's\n * `GoUsageLimitError`/`FreeUsageLimitError`; the prose covers providers that only say it in words,\n * except when they describe a per-minute window, which is throttling however it is phrased.\n */\nconst QUOTA_CODE_TERMS = [\"quota\", \"billing\", \"credit\", \"usage_limit\", \"usagelimit\"];\nconst QUOTA_MESSAGE =\n\t/usage limit|quota exceeded|insufficient (?:quota|credits?)|credit balance|billing|out of budget|available balance/i;\nconst RATE_LIMIT_CODE_TERMS = [\"rate_limit\", \"ratelimit\"];\nconst RATE_WINDOW_MESSAGE = /per[- ](?:second|minute)|\\b[rt]pm\\b/i;\n\nconst isQuota = (details: Metadata): boolean => {\n\tif (includes(details.code, RATE_LIMIT_CODE_TERMS)) return false;\n\tif (includes(details.code, QUOTA_CODE_TERMS)) return true;\n\treturn QUOTA_MESSAGE.test(details.message) && !RATE_WINDOW_MESSAGE.test(details.message);\n};\n\n/** Classify by provider error code, then HTTP status; shared by request and in-stream failures. */\nconst classify = (statusCode: number | undefined, details: Metadata): Failure => {\n\tif (isQuota(details)) return { _tag: \"Quota\", ...details };\n\tif (\n\t\tincludes(details.code, [\n\t\t\t\"content_filter\",\n\t\t\t\"content_policy\",\n\t\t\t\"safety\",\n\t\t\t\"cyber_policy\",\n\t\t\t\"bio_policy\",\n\t\t\t\"misalignment_policy\",\n\t\t])\n\t) {\n\t\treturn { _tag: \"ContentPolicy\", ...details };\n\t}\n\tif (statusCode === 401) return { _tag: \"Authentication\", reason: \"invalid\", ...details };\n\tif (statusCode === 403) return { _tag: \"Authorization\", ...details };\n\tif (statusCode === 404) return { _tag: \"ModelUnavailable\", ...details };\n\tif (statusCode === 408) return { _tag: \"Timeout\", ...details };\n\tif (statusCode === 429) return { _tag: \"RateLimit\", ...details };\n\tif (statusCode !== undefined && statusCode >= 500) return { _tag: \"Unavailable\", ...details };\n\tif (statusCode === undefined) return { _tag: \"Transport\", ...details };\n\tif (statusCode >= 400 && statusCode < 500) return { _tag: \"InvalidRequest\", ...details };\n\treturn { _tag: \"Unknown\", ...details };\n};\n\n/**\n * A failure the provider reported after the stream started, e.g. OpenAI's\n * `context_length_exceeded` event, which it sends instead of an HTTP 400 at random.\n */\nconst fromStreamProvider = (error: StreamProviderError): Failure => {\n\t// Like apiMetadata: providers put the discriminator in `code`, or only in `type`.\n\tconst code = error.code === undefined ? error.type : String(error.code);\n\treturn classify(error.statusCode, {\n\t\tmessage: normalizeMessage(errorMessage(error)),\n\t\tretryable: error.isRetryable,\n\t\t...(error.statusCode === undefined ? {} : { status: error.statusCode }),\n\t\t...(code === undefined ? {} : { code }),\n\t});\n};\n\nconst resemblesTimeout = (error: unknown): boolean => {\n\tconst value = error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\treturn /timeout|timed out/i.test(value);\n};\n\nconst resemblesTransportFailure = (error: unknown): boolean => {\n\tif (error instanceof TypeError) return true;\n\tconst value = error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\treturn /fetch|network|socket|connection|econn|dns/i.test(value);\n};\n\n/** Normalize AI SDK and provider exceptions without retaining request bodies, response bodies, or headers. */\nexport function normalize(error: unknown): Failure {\n\tif (RetryError.isInstance(error) && error.lastError !== undefined && error.lastError !== error) {\n\t\treturn normalize(error.lastError);\n\t}\n\tif (LoadAPIKeyError.isInstance(error) || isProtocolAuthError(error)) {\n\t\treturn { _tag: \"Authentication\", reason: \"missing\", message: errorMessage(error), retryable: false };\n\t}\n\tif (LoadSettingError.isInstance(error)) {\n\t\treturn { _tag: \"Configuration\", message: errorMessage(error), retryable: false };\n\t}\n\tif (NoSuchModelError.isInstance(error)) {\n\t\treturn { _tag: \"ModelUnavailable\", message: errorMessage(error), retryable: false };\n\t}\n\tif (APICallError.isInstance(error)) return classify(error.statusCode, apiMetadata(error));\n\tif (StreamProviderError.isInstance(error)) return fromStreamProvider(error);\n\tif (\n\t\tInvalidPromptError.isInstance(error) ||\n\t\tInvalidArgumentError.isInstance(error) ||\n\t\tUnsupportedFunctionalityError.isInstance(error)\n\t) {\n\t\treturn { _tag: \"InvalidRequest\", message: errorMessage(error), retryable: false };\n\t}\n\tif (\n\t\tInvalidResponseDataError.isInstance(error) ||\n\t\tJSONParseError.isInstance(error) ||\n\t\tEmptyResponseBodyError.isInstance(error) ||\n\t\tNoContentGeneratedError.isInstance(error) ||\n\t\tTypeValidationError.isInstance(error)\n\t) {\n\t\treturn { _tag: \"InvalidResponse\", message: errorMessage(error), retryable: false };\n\t}\n\tif (resemblesTimeout(error)) return { _tag: \"Timeout\", message: errorMessage(error), retryable: true };\n\tif (resemblesTransportFailure(error)) {\n\t\treturn { _tag: \"Transport\", message: errorMessage(error), retryable: true };\n\t}\n\treturn { _tag: \"Unknown\", message: errorMessage(error), retryable: false };\n}\n\n/** Best-effort compatibility for terminal messages written before structured failures existed. */\nexport function fromMessage(message: string): Failure {\n\tconst normalized = normalizeMessage(message);\n\tif (/api key/i.test(normalized) && /missing|required|not set/i.test(normalized)) {\n\t\treturn { _tag: \"Authentication\", reason: \"missing\", message: normalized, retryable: false };\n\t}\n\tif (/api key|credential|token/i.test(normalized) && /invalid|expired|unauthorized/i.test(normalized)) {\n\t\treturn {\n\t\t\t_tag: \"Authentication\",\n\t\t\treason: /expired/i.test(normalized) ? \"expired\" : \"invalid\",\n\t\t\tmessage: normalized,\n\t\t\tretryable: false,\n\t\t};\n\t}\n\treturn { _tag: \"Unknown\", message: normalized, retryable: false };\n}\n"],"mappings":";;;;;;;;;;;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
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-C7oJ2Tfp.mjs.map
|
|
@@ -1 +1 @@
|
|
|
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\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;AACD;;;;;;;;;;;;;;ACx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oB;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-C7oJ2Tfp.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;\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ACV,CAAC;CACF;CAEA,OAAO;AACR;AAEA,MAAa,gBAAgB,oBAAoB"}
|
package/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as ProviderToProtocol, c as getModel, d as model_d_exports, f as modelsAreEqual, i as KnownProviderEnum, l as getModels, n as ActiveThinkingLevel, o as TModel, p as registry, r as Info, s as ThinkingBudgets$1, t as APIMethodEnum, u as getProviders } from "./model-DCfjY0fS.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";
|
|
@@ -51,6 +51,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
51
51
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
52
52
|
}>;
|
|
53
53
|
model: Type$2.TString;
|
|
54
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
55
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
54
56
|
usage: Type$2.TObject<{
|
|
55
57
|
input: Type$2.TNumber;
|
|
56
58
|
output: Type$2.TNumber;
|
|
@@ -355,6 +357,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
355
357
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
356
358
|
}>;
|
|
357
359
|
model: Type$2.TString;
|
|
360
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
361
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
358
362
|
usage: Type$2.TObject<{
|
|
359
363
|
input: Type$2.TNumber;
|
|
360
364
|
output: Type$2.TNumber;
|
|
@@ -660,6 +664,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
660
664
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
661
665
|
}>;
|
|
662
666
|
model: Type$2.TString;
|
|
667
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
668
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
663
669
|
usage: Type$2.TObject<{
|
|
664
670
|
input: Type$2.TNumber;
|
|
665
671
|
output: Type$2.TNumber;
|
|
@@ -965,6 +971,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
965
971
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
966
972
|
}>;
|
|
967
973
|
model: Type$2.TString;
|
|
974
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
975
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
968
976
|
usage: Type$2.TObject<{
|
|
969
977
|
input: Type$2.TNumber;
|
|
970
978
|
output: Type$2.TNumber;
|
|
@@ -1269,6 +1277,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
1269
1277
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
1270
1278
|
}>;
|
|
1271
1279
|
model: Type$2.TString;
|
|
1280
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
1281
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
1272
1282
|
usage: Type$2.TObject<{
|
|
1273
1283
|
input: Type$2.TNumber;
|
|
1274
1284
|
output: Type$2.TNumber;
|
|
@@ -1574,6 +1584,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
1574
1584
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
1575
1585
|
}>;
|
|
1576
1586
|
model: Type$2.TString;
|
|
1587
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
1588
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
1577
1589
|
usage: Type$2.TObject<{
|
|
1578
1590
|
input: Type$2.TNumber;
|
|
1579
1591
|
output: Type$2.TNumber;
|
|
@@ -1879,6 +1891,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
1879
1891
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
1880
1892
|
}>;
|
|
1881
1893
|
model: Type$2.TString;
|
|
1894
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
1895
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
1882
1896
|
usage: Type$2.TObject<{
|
|
1883
1897
|
input: Type$2.TNumber;
|
|
1884
1898
|
output: Type$2.TNumber;
|
|
@@ -2183,6 +2197,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
2183
2197
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
2184
2198
|
}>;
|
|
2185
2199
|
model: Type$2.TString;
|
|
2200
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
2201
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
2186
2202
|
usage: Type$2.TObject<{
|
|
2187
2203
|
input: Type$2.TNumber;
|
|
2188
2204
|
output: Type$2.TNumber;
|
|
@@ -2488,6 +2504,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
2488
2504
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
2489
2505
|
}>;
|
|
2490
2506
|
model: Type$2.TString;
|
|
2507
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
2508
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
2491
2509
|
usage: Type$2.TObject<{
|
|
2492
2510
|
input: Type$2.TNumber;
|
|
2493
2511
|
output: Type$2.TNumber;
|
|
@@ -2936,6 +2954,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
2936
2954
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
2937
2955
|
}>;
|
|
2938
2956
|
model: Type$2.TString;
|
|
2957
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
2958
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
2939
2959
|
usage: Type$2.TObject<{
|
|
2940
2960
|
input: Type$2.TNumber;
|
|
2941
2961
|
output: Type$2.TNumber;
|
|
@@ -3384,6 +3404,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
3384
3404
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
3385
3405
|
}>;
|
|
3386
3406
|
model: Type$2.TString;
|
|
3407
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
3408
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
3387
3409
|
usage: Type$2.TObject<{
|
|
3388
3410
|
input: Type$2.TNumber;
|
|
3389
3411
|
output: Type$2.TNumber;
|
|
@@ -3688,6 +3710,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
3688
3710
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
3689
3711
|
}>;
|
|
3690
3712
|
model: Type$2.TString;
|
|
3713
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
3714
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
3691
3715
|
usage: Type$2.TObject<{
|
|
3692
3716
|
input: Type$2.TNumber;
|
|
3693
3717
|
output: Type$2.TNumber;
|
|
@@ -3992,6 +4016,8 @@ declare const LLMMessageEventSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
3992
4016
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
3993
4017
|
}>;
|
|
3994
4018
|
model: Type$2.TString;
|
|
4019
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
4020
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
3995
4021
|
usage: Type$2.TObject<{
|
|
3996
4022
|
input: Type$2.TNumber;
|
|
3997
4023
|
output: Type$2.TNumber;
|
|
@@ -4301,7 +4327,7 @@ type LLM = {
|
|
|
4301
4327
|
};
|
|
4302
4328
|
export declare const llm: LLM;
|
|
4303
4329
|
declare namespace message_d_exports {
|
|
4304
|
-
export { AssistantMessage, AssistantMessageSchema, ConstrainedSampling, ConstrainedSamplingSchema, Context, ContextSchema, GrammarVariants, GrammarVariantsSchema, ImageContent, ImageContentSchema, Message, MessageSchema, StopReason, StopReasonSchema, TextContent, TextContentSchema, ThinkingContent, ThinkingContentSchema, Tool, ToolAbortedSchema, ToolArguments, ToolCall, ToolCallAbortedPart, ToolCallAbortedPartSchema, ToolCallBaseSchema, ToolCallCompletedPart, ToolCallCompletedPartSchema, ToolCallErrorPart, ToolCallErrorPartSchema, ToolCallInFlight, ToolCallInFlightSchema, ToolCallPendingPart, ToolCallPendingPartSchema, ToolCallRunningPart, ToolCallRunningPartSchema, ToolCallSchema, ToolCallSkippedPart, ToolCallSkippedPartSchema, ToolCallTerminalPart, ToolCallTerminalPartSchema, ToolCompletedSchema, ToolErrorResult, ToolErrorSchema, ToolRunningPartial, ToolRunningSchema, ToolSchema, ToolSkippedSchema, ToolStatusEnum, ToolSuccessResult, Usage, UsageSchema, UserMessage, UserMessageSchema, createAssistantMessage, createMessageId, createUserMessage, defineTool,
|
|
4330
|
+
export { AssistantMessage, AssistantMessageSchema, ConstrainedSampling, ConstrainedSamplingSchema, Context, ContextSchema, GrammarVariants, GrammarVariantsSchema, ImageContent, ImageContentSchema, Message, MessageSchema, StopReason, StopReasonSchema, TextContent, TextContentSchema, ThinkingContent, ThinkingContentSchema, Tool, ToolAbortedSchema, ToolArguments, ToolCall, ToolCallAbortedPart, ToolCallAbortedPartSchema, ToolCallBaseSchema, ToolCallCompletedPart, ToolCallCompletedPartSchema, ToolCallErrorPart, ToolCallErrorPartSchema, ToolCallInFlight, ToolCallInFlightSchema, ToolCallPendingPart, ToolCallPendingPartSchema, ToolCallRunningPart, ToolCallRunningPartSchema, ToolCallSchema, ToolCallSkippedPart, ToolCallSkippedPartSchema, ToolCallTerminalPart, ToolCallTerminalPartSchema, ToolCompletedSchema, ToolErrorResult, ToolErrorSchema, ToolRunningPartial, ToolRunningSchema, ToolSchema, ToolSkippedSchema, ToolStatusEnum, ToolSuccessResult, Usage, UsageSchema, UserMessage, UserMessageSchema, createAssistantMessage, createMessageId, createUserMessage, defineTool, transformMessages };
|
|
4305
4331
|
}
|
|
4306
4332
|
declare const TextContentSchema: Type$2.TObject<{
|
|
4307
4333
|
type: Type$2.TLiteral<"text">;
|
|
@@ -4928,6 +4954,10 @@ declare const AssistantMessageSchema: Type$2.TObject<{
|
|
|
4928
4954
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
4929
4955
|
}>;
|
|
4930
4956
|
model: Type$2.TString;
|
|
4957
|
+
/** Thinking level the caller requested, before aikit fits it to the model. */
|
|
4958
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
4959
|
+
/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */
|
|
4960
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
4931
4961
|
usage: Type$2.TObject<{
|
|
4932
4962
|
input: Type$2.TNumber;
|
|
4933
4963
|
output: Type$2.TNumber;
|
|
@@ -5255,6 +5285,10 @@ declare const MessageSchema: Type$2.TUnion<[Type$2.TObject<{
|
|
|
5255
5285
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
5256
5286
|
}>;
|
|
5257
5287
|
model: Type$2.TString;
|
|
5288
|
+
/** Thinking level the caller requested, before aikit fits it to the model. */
|
|
5289
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
5290
|
+
/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */
|
|
5291
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
5258
5292
|
usage: Type$2.TObject<{
|
|
5259
5293
|
input: Type$2.TNumber;
|
|
5260
5294
|
output: Type$2.TNumber;
|
|
@@ -5621,10 +5655,6 @@ interface Tool<TParameters extends TSchema$1 = TSchema$1> {
|
|
|
5621
5655
|
}
|
|
5622
5656
|
type ToolArguments<T extends Tool> = Static$1<T["parameters"]>;
|
|
5623
5657
|
declare function defineTool<TParameters extends TSchema$1>(tool: Tool<TParameters>): Tool<TParameters>;
|
|
5624
|
-
declare function resolveJsonSchemaConstraint(tool: Tool, compat?: Pick<Compatibility, "supportsStrictMode">): {
|
|
5625
|
-
type: "json_schema";
|
|
5626
|
-
strict: true;
|
|
5627
|
-
} | undefined;
|
|
5628
5658
|
declare const ContextSchema: Type$2.TObject<{
|
|
5629
5659
|
systemPrompt: Type$2.TOptional<Type$2.TString>;
|
|
5630
5660
|
messages: Type$2.TArray<Type$2.TUnion<[Type$2.TObject<{
|
|
@@ -5654,6 +5684,10 @@ declare const ContextSchema: Type$2.TObject<{
|
|
|
5654
5684
|
options: Type$2.TOptional<Type$2.TRecord<"^.*$", Type$2.TAny>>;
|
|
5655
5685
|
}>;
|
|
5656
5686
|
model: Type$2.TString;
|
|
5687
|
+
/** Thinking level the caller requested, before aikit fits it to the model. */
|
|
5688
|
+
thinkingLevel: Type$2.TUnion<[Type$2.TLiteral<"off">, Type$2.TLiteral<"minimal">, Type$2.TLiteral<"low">, Type$2.TLiteral<"medium">, Type$2.TLiteral<"high">, Type$2.TLiteral<"xhigh">, Type$2.TLiteral<"max">]>;
|
|
5689
|
+
/** Provider-native thinking value the request carried. Absent for budget-only or unmanaged reasoning. */
|
|
5690
|
+
providerThinkingLevel: Type$2.TOptional<Type$2.TString>;
|
|
5657
5691
|
usage: Type$2.TObject<{
|
|
5658
5692
|
input: Type$2.TNumber;
|
|
5659
5693
|
output: Type$2.TNumber;
|
|
@@ -6179,6 +6213,7 @@ declare const SharedOptions: Type$1.TObject<{
|
|
|
6179
6213
|
apiKey: Type$1.TOptional<Type$1.TString>;
|
|
6180
6214
|
cacheRetention: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"none">, Type$1.TLiteral<"short">, Type$1.TLiteral<"long">]>>;
|
|
6181
6215
|
headers: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TString>>;
|
|
6216
|
+
idleTimeoutMs: Type$1.TOptional<Type$1.TNumber>;
|
|
6182
6217
|
maxRetries: Type$1.TOptional<Type$1.TNumber>;
|
|
6183
6218
|
maxTokens: Type$1.TOptional<Type$1.TNumber>;
|
|
6184
6219
|
metadata: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnknown>>;
|
|
@@ -7465,6 +7500,11 @@ type StreamCallable = {
|
|
|
7465
7500
|
export declare const stream: StreamCallable;
|
|
7466
7501
|
//#endregion
|
|
7467
7502
|
//#region src/utils/validation.d.ts
|
|
7503
|
+
/**
|
|
7504
|
+
* Drop `null` from optional properties whose schema does not accept null, in place. Strict constrained sampling
|
|
7505
|
+
* makes every property required and nullable, so the model answers an omitted optional argument with `null`.
|
|
7506
|
+
*/
|
|
7507
|
+
export declare function normalizeOptionalNulls(value: unknown, schema: unknown): void;
|
|
7468
7508
|
/**
|
|
7469
7509
|
* Validates an arbitrary value against a TypeBox schema and returns the coerced value.
|
|
7470
7510
|
*/
|