@codeworksh/aikit 0.12.1 → 0.13.0-canary.103.1.g9c7d425f
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 +5 -5
- package/{codex-CLDBTrFm.mjs → codex-DvULd3EJ.mjs} +2 -56
- package/codex-DvULd3EJ.mjs.map +1 -0
- package/{copilot-DvUXC6Kx.mjs → copilot-D9T1jbpu.mjs} +13 -3
- package/copilot-D9T1jbpu.mjs.map +1 -0
- package/{copilot-headers-BLnBaJyp.mjs → copilot-headers-I-AOoDed.mjs} +2 -2
- package/{copilot-headers-BLnBaJyp.mjs.map → copilot-headers-I-AOoDed.mjs.map} +1 -1
- package/{failure-5Wjd-qFH.d.mts → failure-CCCRfhCf.d.mts} +6 -3
- package/{failure-DFQNKc-O.mjs → failure-D0qEqOsO.mjs} +37 -5
- package/failure-D0qEqOsO.mjs.map +1 -0
- package/github-copilot-C75m0xwW.mjs +3 -0
- package/{github-copilot-BcmOr0jd.mjs → github-copilot-CdkIxdQS.mjs} +31 -15
- package/github-copilot-CdkIxdQS.mjs.map +1 -0
- package/index.d.mts +540 -237
- package/index.mjs +566 -103
- package/index.mjs.map +1 -1
- package/interactive-c0deRdi7.mjs +115 -0
- package/interactive-c0deRdi7.mjs.map +1 -0
- package/llm/failure.d.mts +2 -2
- package/llm/failure.mjs +2 -2
- package/{model-Cjp-Dr8V.mjs → model-BZZZAySN.mjs} +564 -617
- package/{model-Cjp-Dr8V.mjs.map → model-BZZZAySN.mjs.map} +1 -1
- package/{model-D3wc9-u4.d.mts → model-Dgf7E5gc.d.mts} +20 -1
- package/{openai-codex-C1Yb02kM.mjs → model-av44O6GQ.mjs} +340 -355
- package/model-av44O6GQ.mjs.map +1 -0
- package/{modelgen-DXMmI80T.mjs → modelgen-f3yv7FiK.mjs} +50 -17
- package/modelgen-f3yv7FiK.mjs.map +1 -0
- package/modelgen.d.mts +1 -1
- package/modelgen.mjs +2 -2
- package/oauth/github/copilot.d.mts +10 -0
- package/oauth/github/copilot.mjs +2 -2
- package/oauth/interactive.d.mts +6 -1
- package/oauth/interactive.mjs +2 -2
- package/oauth/openai/codex.mjs +1 -1
- package/openai-codex-BGNrJzTb.mjs +2 -0
- package/openai-codex-DL0lqVuN.mjs +117 -0
- package/openai-codex-DL0lqVuN.mjs.map +1 -0
- package/package.json +1 -1
- package/{registry-u49t0S4S.mjs → registry-BULNTLAP.mjs} +10 -6
- package/{registry-u49t0S4S.mjs.map → registry-BULNTLAP.mjs.map} +1 -1
- package/codex-CLDBTrFm.mjs.map +0 -1
- package/copilot-DvUXC6Kx.mjs.map +0 -1
- package/failure-DFQNKc-O.mjs.map +0 -1
- package/github-copilot-BcmOr0jd.mjs.map +0 -1
- package/github-copilot-llyP2NK4.mjs +0 -3
- package/interactive-eoNnscGB.mjs +0 -57
- package/interactive-eoNnscGB.mjs.map +0 -1
- package/modelgen-DXMmI80T.mjs.map +0 -1
- package/openai-codex-C1Yb02kM.mjs.map +0 -1
- package/openai-codex-CHxShIN3.mjs +0 -2
package/oauth/github/copilot.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as createGitHubCopilotDeviceFlow, c as fetchGitHubCopilotUser, d as
|
|
2
|
-
export { GITHUB_COPILOT_API_KEY_ENV, GITHUB_COPILOT_PROVIDER_ID, GitHubCopilotOAuthClient, JsonGitHubCopilotAuthStorage, createGitHubCopilotDeviceFlow, enableGitHubCopilotModels, fetchGitHubCopilotModels, fetchGitHubCopilotUser, getGitHubCopilotApiKey, gitHubApiDomain, gitHubCopilotBaseUrl, gitHubCopilotEntitlementError, gitHubCopilotHeaders, normalizeGitHubDomain, pollGitHubCopilotDeviceToken };
|
|
1
|
+
import { a as createGitHubCopilotDeviceFlow, c as fetchGitHubCopilotUser, d as gitHubApiDomain, f as gitHubCopilotBaseUrl, g as pollGitHubCopilotDeviceToken, h as normalizeGitHubDomain, i as JsonGitHubCopilotAuthStorage, l as filterGitHubCopilotModels, m as gitHubCopilotHeaders, n as GITHUB_COPILOT_PROVIDER_ID, o as enableGitHubCopilotModels, p as gitHubCopilotEntitlementError, r as GitHubCopilotOAuthClient, s as fetchGitHubCopilotModels, t as GITHUB_COPILOT_API_KEY_ENV, u as getGitHubCopilotApiKey } from "../../copilot-D9T1jbpu.mjs";
|
|
2
|
+
export { GITHUB_COPILOT_API_KEY_ENV, GITHUB_COPILOT_PROVIDER_ID, GitHubCopilotOAuthClient, JsonGitHubCopilotAuthStorage, createGitHubCopilotDeviceFlow, enableGitHubCopilotModels, fetchGitHubCopilotModels, fetchGitHubCopilotUser, filterGitHubCopilotModels, getGitHubCopilotApiKey, gitHubApiDomain, gitHubCopilotBaseUrl, gitHubCopilotEntitlementError, gitHubCopilotHeaders, normalizeGitHubDomain, pollGitHubCopilotDeviceToken };
|
package/oauth/interactive.d.mts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
//#region src/oauth/interactive.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* Terminal affordances an interactive OAuth login needs: open the
|
|
4
|
-
* authorization URL,
|
|
4
|
+
* authorization URL, read a pasted code back, and the page the browser
|
|
5
|
+
* shows after the callback.
|
|
5
6
|
*
|
|
6
7
|
* Shared so the aikit CLI and anything built on these flows behave the same —
|
|
7
8
|
* they previously kept private copies, and the copies drifted.
|
|
@@ -17,5 +18,9 @@
|
|
|
17
18
|
export declare function openBrowser(url: string, onError?: (error: Error) => void): Promise<void>;
|
|
18
19
|
/** Read one line from stdin, prompting on stdout. */
|
|
19
20
|
export declare function promptLine(message: string): Promise<string>;
|
|
21
|
+
/** The browser page an OAuth callback answers with after a sign-in. */
|
|
22
|
+
export declare function oauthSuccessHtml(message: string): string;
|
|
23
|
+
/** The browser page an OAuth callback answers with when a sign-in failed. */
|
|
24
|
+
export declare function oauthErrorHtml(message: string, details?: string): string;
|
|
20
25
|
//#endregion
|
|
21
26
|
//# sourceMappingURL=interactive.d.mts.map
|
package/oauth/interactive.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { openBrowser, promptLine };
|
|
1
|
+
import { i as promptLine, n as oauthSuccessHtml, r as openBrowser, t as oauthErrorHtml } from "../interactive-c0deRdi7.mjs";
|
|
2
|
+
export { oauthErrorHtml, oauthSuccessHtml, openBrowser, promptLine };
|
package/oauth/openai/codex.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as createOpenAICodexDeviceAuth, c as getOpenAICodexApiKey, d as pollOpenAICodexDeviceAuth, f as refreshOpenAICodexToken, i as createOpenAICodexAuthorizationFlow, l as openAICodexHeaders, n as OPENAI_CODEX_API_KEY_ENV, o as exchangeOpenAICodexAuthorizationCode, r as OpenAICodexOAuthClient, s as getOpenAICodexAccountId, t as JsonOpenAICodexAuthStorage, u as parseOpenAICodexAuthorizationInput } from "../../codex-
|
|
1
|
+
import { a as createOpenAICodexDeviceAuth, c as getOpenAICodexApiKey, d as pollOpenAICodexDeviceAuth, f as refreshOpenAICodexToken, i as createOpenAICodexAuthorizationFlow, l as openAICodexHeaders, n as OPENAI_CODEX_API_KEY_ENV, o as exchangeOpenAICodexAuthorizationCode, r as OpenAICodexOAuthClient, s as getOpenAICodexAccountId, t as JsonOpenAICodexAuthStorage, u as parseOpenAICodexAuthorizationInput } from "../../codex-DvULd3EJ.mjs";
|
|
2
2
|
export { JsonOpenAICodexAuthStorage, OPENAI_CODEX_API_KEY_ENV, OpenAICodexOAuthClient, createOpenAICodexAuthorizationFlow, createOpenAICodexDeviceAuth, exchangeOpenAICodexAuthorizationCode, getOpenAICodexAccountId, getOpenAICodexApiKey, openAICodexHeaders, parseOpenAICodexAuthorizationInput, pollOpenAICodexDeviceAuth, refreshOpenAICodexToken };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { n as clampPromptCacheKey, t as ResponsesLanguageModel } from "./model-av44O6GQ.mjs";
|
|
2
|
+
import { s as getOpenAICodexAccountId } from "./codex-DvULd3EJ.mjs";
|
|
3
|
+
import { LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
|
|
4
|
+
//#region src/providers/openai-codex/codex-provider.ts
|
|
5
|
+
const OPENAI_CODEX_API_KEY_ENV = "OPENAI_CODEX_API_KEY";
|
|
6
|
+
const OPENAI_CODEX_DEFAULT_BASE_URL = "https://chatgpt.com/backend-api";
|
|
7
|
+
/**
|
|
8
|
+
* The ChatGPT Codex backend requires `instructions`, rejects `max_output_tokens`, and
|
|
9
|
+
* takes a zstd-compressed body.
|
|
10
|
+
*/
|
|
11
|
+
const CODEX_REQUEST = {
|
|
12
|
+
systemPrompt: "instructions",
|
|
13
|
+
maxOutputTokens: false,
|
|
14
|
+
encryptedReasoning: "always",
|
|
15
|
+
compress: true,
|
|
16
|
+
toolDefaults: true,
|
|
17
|
+
textVerbosity: "low"
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the Codex responses endpoint from a base URL that may already
|
|
21
|
+
* include the `/codex` or `/codex/responses` suffix.
|
|
22
|
+
*/
|
|
23
|
+
function resolveOpenAICodexUrl(baseUrl) {
|
|
24
|
+
const normalized = (baseUrl?.trim() ? baseUrl : OPENAI_CODEX_DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
25
|
+
if (normalized.endsWith("/codex/responses")) return normalized;
|
|
26
|
+
if (normalized.endsWith("/codex")) return `${normalized}/responses`;
|
|
27
|
+
return `${normalized}/codex/responses`;
|
|
28
|
+
}
|
|
29
|
+
/** Tool helpers for Responses-only tool kinds. */
|
|
30
|
+
const openAICodexTools = { custom(args) {
|
|
31
|
+
return {
|
|
32
|
+
name: args.name,
|
|
33
|
+
description: args.description,
|
|
34
|
+
parameters: args.parameters,
|
|
35
|
+
constrainedSampling: {
|
|
36
|
+
type: "grammar",
|
|
37
|
+
variants: args.format.syntax === "lark" ? { openai_lark: args.format.definition } : { openai_regex: args.format.definition }
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
} };
|
|
41
|
+
const DEFAULT_ORIGINATOR = "codework";
|
|
42
|
+
async function resolveApiKey(settings) {
|
|
43
|
+
const apiKey = typeof settings.apiKey === "function" ? await settings.apiKey() : settings.apiKey ?? (typeof process === "undefined" ? void 0 : process.env["OPENAI_CODEX_API_KEY"]);
|
|
44
|
+
if (!apiKey) throw new LoadAPIKeyError({ message: `OpenAI Codex API key is missing. Pass it using the 'apiKey' option or the ${OPENAI_CODEX_API_KEY_ENV} environment variable.` });
|
|
45
|
+
return apiKey;
|
|
46
|
+
}
|
|
47
|
+
function resolveAccountId(settings, apiKey) {
|
|
48
|
+
const accountId = settings.accountId ?? getOpenAICodexAccountId(apiKey);
|
|
49
|
+
if (!accountId) throw new LoadAPIKeyError({ message: "Failed to extract the ChatGPT account id from the OpenAI Codex access token. Provide it using the 'accountId' option or pass a valid ChatGPT OAuth JWT as the API key." });
|
|
50
|
+
return accountId;
|
|
51
|
+
}
|
|
52
|
+
function createOpenAICodex(options = {}) {
|
|
53
|
+
const baseURL = options.baseURL?.replace(/\/+$/, "") || "https://chatgpt.com/backend-api";
|
|
54
|
+
const sessionId = clampPromptCacheKey(options.sessionId);
|
|
55
|
+
const getHeaders = async () => {
|
|
56
|
+
const apiKey = await resolveApiKey(options);
|
|
57
|
+
const accountId = resolveAccountId(options, apiKey);
|
|
58
|
+
return {
|
|
59
|
+
Authorization: `Bearer ${apiKey}`,
|
|
60
|
+
"chatgpt-account-id": accountId,
|
|
61
|
+
"OpenAI-Beta": "responses=experimental",
|
|
62
|
+
originator: options.originator ?? DEFAULT_ORIGINATOR,
|
|
63
|
+
accept: "text/event-stream",
|
|
64
|
+
"content-type": "application/json",
|
|
65
|
+
...sessionId ? {
|
|
66
|
+
"session-id": sessionId,
|
|
67
|
+
"x-client-request-id": sessionId
|
|
68
|
+
} : {},
|
|
69
|
+
...options.headers
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
const createLanguageModel = (modelId) => new ResponsesLanguageModel(modelId, {
|
|
73
|
+
provider: "openai-codex",
|
|
74
|
+
label: "OpenAI Codex",
|
|
75
|
+
url: resolveOpenAICodexUrl(baseURL),
|
|
76
|
+
headers: getHeaders,
|
|
77
|
+
request: CODEX_REQUEST,
|
|
78
|
+
...options.fetch !== void 0 && { fetch: options.fetch },
|
|
79
|
+
...sessionId !== void 0 && { promptCacheKey: sessionId },
|
|
80
|
+
...options.serviceTier !== void 0 && { serviceTier: options.serviceTier },
|
|
81
|
+
...options.compat !== void 0 && { compat: options.compat }
|
|
82
|
+
});
|
|
83
|
+
const provider = function(modelId) {
|
|
84
|
+
if (new.target) throw new Error("openAI codex model function cannot be called with the new keyword.");
|
|
85
|
+
return createLanguageModel(modelId);
|
|
86
|
+
};
|
|
87
|
+
provider.specificationVersion = "v3";
|
|
88
|
+
provider.languageModel = createLanguageModel;
|
|
89
|
+
provider.responses = createLanguageModel;
|
|
90
|
+
provider.embeddingModel = (modelId) => {
|
|
91
|
+
throw new NoSuchModelError({
|
|
92
|
+
modelId,
|
|
93
|
+
modelType: "embeddingModel"
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
provider.textEmbeddingModel = (modelId) => {
|
|
97
|
+
throw new NoSuchModelError({
|
|
98
|
+
modelId,
|
|
99
|
+
modelType: "embeddingModel"
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
provider.imageModel = (modelId) => {
|
|
103
|
+
throw new NoSuchModelError({
|
|
104
|
+
modelId,
|
|
105
|
+
modelType: "imageModel"
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
return provider;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Default provider instance using `OPENAI_CODEX_API_KEY`.
|
|
112
|
+
*/
|
|
113
|
+
const openaiCodex = createOpenAICodex();
|
|
114
|
+
//#endregion
|
|
115
|
+
export { openaiCodex as a, openAICodexTools as i, OPENAI_CODEX_DEFAULT_BASE_URL as n, resolveOpenAICodexUrl as o, createOpenAICodex as r, OPENAI_CODEX_API_KEY_ENV as t };
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=openai-codex-DL0lqVuN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-codex-DL0lqVuN.mjs","names":[],"sources":["../../src/providers/openai-codex/codex-provider.ts"],"sourcesContent":["import { LoadAPIKeyError, NoSuchModelError, type LanguageModelV3, type ProviderV3 } from \"@ai-sdk/provider\";\nimport type { TSchema } from \"typebox\";\nimport type * as Message from \"../../message/message.ts\";\nimport { getOpenAICodexAccountId } from \"../../oauth/openai/codex.ts\";\nimport {\n\tResponsesLanguageModel,\n\tclampPromptCacheKey,\n\ttype ResponsesCompatibility,\n\ttype ResponsesRequestProfile,\n\ttype ResponsesServiceTier,\n} from \"../responses/model.ts\";\n\nexport const OPENAI_CODEX_API_KEY_ENV = \"OPENAI_CODEX_API_KEY\";\nexport const OPENAI_CODEX_DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\n\nexport type OpenAICodexModelId =\n\t| \"gpt-5.3-codex-spark\"\n\t| \"gpt-5.4\"\n\t| \"gpt-5.4-mini\"\n\t| \"gpt-5.5\"\n\t| \"gpt-5.6-luna\"\n\t| \"gpt-5.6-sol\"\n\t| \"gpt-5.6-terra\"\n\t| (string & {});\n\nexport type OpenAICodexCompatibility = ResponsesCompatibility;\n\n/**\n * The ChatGPT Codex backend requires `instructions`, rejects `max_output_tokens`, and\n * takes a zstd-compressed body.\n */\nconst CODEX_REQUEST: ResponsesRequestProfile = {\n\tsystemPrompt: \"instructions\",\n\tmaxOutputTokens: false,\n\tencryptedReasoning: \"always\",\n\tcompress: true,\n\ttoolDefaults: true,\n\ttextVerbosity: \"low\",\n};\n\n/**\n * Resolve the Codex responses endpoint from a base URL that may already\n * include the `/codex` or `/codex/responses` suffix.\n */\nexport function resolveOpenAICodexUrl(baseUrl?: string): string {\n\tconst raw = baseUrl?.trim() ? baseUrl : OPENAI_CODEX_DEFAULT_BASE_URL;\n\tconst normalized = raw.replace(/\\/+$/, \"\");\n\tif (normalized.endsWith(\"/codex/responses\")) return normalized;\n\tif (normalized.endsWith(\"/codex\")) return `${normalized}/responses`;\n\treturn `${normalized}/codex/responses`;\n}\n\n/** Tool helpers for Responses-only tool kinds. */\nexport const openAICodexTools = {\n\tcustom<TParameters extends TSchema>(args: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: TParameters;\n\t\tformat: { type: \"grammar\"; syntax: \"lark\" | \"regex\"; definition: string };\n\t}): Message.Tool<TParameters> {\n\t\treturn {\n\t\t\tname: args.name,\n\t\t\tdescription: args.description,\n\t\t\tparameters: args.parameters,\n\t\t\tconstrainedSampling: {\n\t\t\t\ttype: \"grammar\",\n\t\t\t\tvariants:\n\t\t\t\t\targs.format.syntax === \"lark\"\n\t\t\t\t\t\t? { openai_lark: args.format.definition }\n\t\t\t\t\t\t: { openai_regex: args.format.definition },\n\t\t\t},\n\t\t};\n\t},\n};\n\nconst DEFAULT_ORIGINATOR = \"codework\";\n\nexport interface OpenAICodexProvider extends ProviderV3 {\n\t(modelId: OpenAICodexModelId): LanguageModelV3;\n\n\tlanguageModel(modelId: OpenAICodexModelId): LanguageModelV3;\n\n\t/** Alias for `languageModel`; the Codex API only speaks the Responses protocol. */\n\tresponses(modelId: OpenAICodexModelId): LanguageModelV3;\n}\n\nexport interface OpenAICodexProviderSettings {\n\t/**\n\t * Base URL for the Codex backend.\n\t * Defaults to `https://chatgpt.com/backend-api`.\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * ChatGPT OAuth access token (JWT) used as the API key.\n\t * Defaults to the `OPENAI_CODEX_API_KEY` environment variable.\n\t * A function can be passed to resolve a fresh token per request.\n\t */\n\tapiKey?: string | (() => string | PromiseLike<string>);\n\n\t/**\n\t * ChatGPT account id sent as the `chatgpt-account-id` header.\n\t * Extracted from the JWT access token when omitted.\n\t */\n\taccountId?: string;\n\n\t/** Custom headers merged into every request. */\n\theaders?: Record<string, string>;\n\n\t/** Custom fetch implementation. */\n\tfetch?: typeof globalThis.fetch;\n\n\t/** Session id used for request identity, the `session-id` header, and prompt cache affinity. */\n\tsessionId?: string;\n\n\t/** Default service tier for requests. */\n\tserviceTier?: ResponsesServiceTier;\n\n\t/** `originator` header value; defaults to `codework`. */\n\toriginator?: string;\n\n\t/** Model capabilities supplied by aikit or the direct caller; absent flags are disabled. */\n\tcompat?: OpenAICodexCompatibility;\n}\n\nasync function resolveApiKey(settings: OpenAICodexProviderSettings): Promise<string> {\n\tconst apiKey =\n\t\ttypeof settings.apiKey === \"function\"\n\t\t\t? await settings.apiKey()\n\t\t\t: (settings.apiKey ?? (typeof process === \"undefined\" ? undefined : process.env[OPENAI_CODEX_API_KEY_ENV]));\n\n\tif (!apiKey) {\n\t\tthrow new LoadAPIKeyError({\n\t\t\tmessage: `OpenAI Codex API key is missing. Pass it using the 'apiKey' option or the ${OPENAI_CODEX_API_KEY_ENV} environment variable.`,\n\t\t});\n\t}\n\n\treturn apiKey;\n}\n\nfunction resolveAccountId(settings: OpenAICodexProviderSettings, apiKey: string): string {\n\tconst accountId = settings.accountId ?? getOpenAICodexAccountId(apiKey);\n\tif (!accountId) {\n\t\tthrow new LoadAPIKeyError({\n\t\t\tmessage:\n\t\t\t\t\"Failed to extract the ChatGPT account id from the OpenAI Codex access token. \" +\n\t\t\t\t\"Provide it using the 'accountId' option or pass a valid ChatGPT OAuth JWT as the API key.\",\n\t\t});\n\t}\n\treturn accountId;\n}\n\nexport function createOpenAICodex(options: OpenAICodexProviderSettings = {}): OpenAICodexProvider {\n\tconst baseURL = options.baseURL?.replace(/\\/+$/, \"\") || OPENAI_CODEX_DEFAULT_BASE_URL;\n\tconst sessionId = clampPromptCacheKey(options.sessionId);\n\n\tconst getHeaders = async (): Promise<Record<string, string | undefined>> => {\n\t\tconst apiKey = await resolveApiKey(options);\n\t\tconst accountId = resolveAccountId(options, apiKey);\n\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\"OpenAI-Beta\": \"responses=experimental\",\n\t\t\toriginator: options.originator ?? DEFAULT_ORIGINATOR,\n\t\t\taccept: \"text/event-stream\",\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t...(sessionId ? { \"session-id\": sessionId, \"x-client-request-id\": sessionId } : {}),\n\t\t\t...options.headers,\n\t\t};\n\t};\n\n\tconst createLanguageModel = (modelId: OpenAICodexModelId) =>\n\t\tnew ResponsesLanguageModel(modelId, {\n\t\t\tprovider: \"openai-codex\",\n\t\t\tlabel: \"OpenAI Codex\",\n\t\t\turl: resolveOpenAICodexUrl(baseURL),\n\t\t\theaders: getHeaders,\n\t\t\trequest: CODEX_REQUEST,\n\t\t\t...(options.fetch !== undefined && { fetch: options.fetch }),\n\t\t\t...(sessionId !== undefined && { promptCacheKey: sessionId }),\n\t\t\t...(options.serviceTier !== undefined && { serviceTier: options.serviceTier }),\n\t\t\t...(options.compat !== undefined && { compat: options.compat }),\n\t\t});\n\n\tconst provider = function (modelId: OpenAICodexModelId) {\n\t\tif (new.target) {\n\t\t\tthrow new Error(\"openAI codex model function cannot be called with the new keyword.\");\n\t\t}\n\t\treturn createLanguageModel(modelId);\n\t};\n\n\tprovider.specificationVersion = \"v3\" as const;\n\tprovider.languageModel = createLanguageModel;\n\tprovider.responses = createLanguageModel;\n\n\tprovider.embeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n\t};\n\tprovider.textEmbeddingModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n\t};\n\tprovider.imageModel = (modelId: string) => {\n\t\tthrow new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n\t};\n\n\treturn provider as OpenAICodexProvider;\n}\n\n/**\n * Default provider instance using `OPENAI_CODEX_API_KEY`.\n */\nexport const openaiCodex = createOpenAICodex();\n"],"mappings":";;;;AAYA,MAAa,2BAA2B;AACxC,MAAa,gCAAgC;;;;;AAkB7C,MAAM,gBAAy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d425f",
|
|
4
4
|
"description": "TypeScript SDK that provides a unified API for working with multiple LLM providers, automatic model discovery, and more.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as KnownProviderEnum, t as APIMethodEnum } from "./model-
|
|
1
|
+
import { i as KnownProviderEnum, t as APIMethodEnum } from "./model-BZZZAySN.mjs";
|
|
2
2
|
//#region src/llm/registry.ts
|
|
3
3
|
const DEFAULT_AI_SDK_FALLBACK = "@ai-sdk/openai-compatible";
|
|
4
4
|
const AI_SDK_PACKAGE_TO_PROTOCOL = {
|
|
@@ -22,8 +22,8 @@ const PROVIDER_LOADERS = {
|
|
|
22
22
|
"@ai-sdk/openai-compatible": () => import("@ai-sdk/openai-compatible").then((m) => m.createOpenAICompatible),
|
|
23
23
|
"@openrouter/ai-sdk-provider": () => import("@openrouter/ai-sdk-provider").then((m) => m.createOpenRouter),
|
|
24
24
|
"@ai-sdk/xai": () => import("@ai-sdk/xai").then((m) => m.createXai),
|
|
25
|
-
"@codeworksh/ai-sdk-openai-codex": () => import("./openai-codex-
|
|
26
|
-
"@codeworksh/ai-sdk-github-copilot": () => import("./github-copilot-
|
|
25
|
+
"@codeworksh/ai-sdk-openai-codex": () => import("./openai-codex-BGNrJzTb.mjs").then((m) => m.createOpenAICodex),
|
|
26
|
+
"@codeworksh/ai-sdk-github-copilot": () => import("./github-copilot-C75m0xwW.mjs").then((m) => m.createGitHubCopilot)
|
|
27
27
|
};
|
|
28
28
|
function isAISDKPackage(value) {
|
|
29
29
|
return value in AI_SDK_PACKAGE_TO_PROTOCOL;
|
|
@@ -43,9 +43,13 @@ function defaultMethodForModel(model) {
|
|
|
43
43
|
if (model.protocol === KnownProviderEnum.openai || model.protocol === KnownProviderEnum.openaiCodex || model.protocol === KnownProviderEnum.xai) return APIMethodEnum.responses;
|
|
44
44
|
return APIMethodEnum.languageModel;
|
|
45
45
|
}
|
|
46
|
+
/** The endpoint method a model is called through: the request's override, the catalog's, or the default. */
|
|
47
|
+
function resolveMethod(model, methodOverride) {
|
|
48
|
+
return methodOverride ?? model.api?.method ?? defaultMethodForModel(model);
|
|
49
|
+
}
|
|
46
50
|
function resolveLanguageModel(provider, model, methodOverride) {
|
|
47
51
|
const modelId = model.api?.id ?? model.id;
|
|
48
|
-
const method =
|
|
52
|
+
const method = resolveMethod(model, methodOverride);
|
|
49
53
|
const callable = provider;
|
|
50
54
|
if (method === APIMethodEnum.responses && callable.responses) return callable.responses(modelId);
|
|
51
55
|
if (method === APIMethodEnum.messages && callable.messages) return callable.messages(modelId);
|
|
@@ -62,6 +66,6 @@ function resolveLanguageModel(provider, model, methodOverride) {
|
|
|
62
66
|
return callable(modelId);
|
|
63
67
|
}
|
|
64
68
|
//#endregion
|
|
65
|
-
export { protocolForPackage as a, packageForModel as i, isAISDKPackage as n, resolveLanguageModel as o, loadProviderFactory as r, DEFAULT_AI_SDK_FALLBACK as t };
|
|
69
|
+
export { protocolForPackage as a, packageForModel as i, isAISDKPackage as n, resolveLanguageModel as o, loadProviderFactory as r, resolveMethod as s, DEFAULT_AI_SDK_FALLBACK as t };
|
|
66
70
|
|
|
67
|
-
//# sourceMappingURL=registry-
|
|
71
|
+
//# sourceMappingURL=registry-BULNTLAP.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry-
|
|
1
|
+
{"version":3,"file":"registry-BULNTLAP.mjs","names":[],"sources":["../../src/llm/registry.ts"],"sourcesContent":["import type { LanguageModel } from \"ai\";\nimport * as Model from \"../model/model.ts\";\n\nexport const DEFAULT_AI_SDK_FALLBACK = \"@ai-sdk/openai-compatible\";\n\nexport const AI_SDK_PACKAGE_TO_PROTOCOL = {\n\t\"@ai-sdk/anthropic\": Model.KnownProviderEnum.anthropic,\n\t\"@ai-sdk/google\": Model.KnownProviderEnum.google,\n\t\"@ai-sdk/google-vertex\": Model.KnownProviderEnum.googleVertex,\n\t\"@ai-sdk/google-vertex/anthropic\": Model.KnownProviderEnum.googleVertexAnthropic,\n\t\"@ai-sdk/openai\": Model.KnownProviderEnum.openai,\n\t\"@ai-sdk/openai-compatible\": Model.KnownProviderEnum.openaiCompatible,\n\t\"@codeworksh/ai-sdk-openai-codex\": Model.KnownProviderEnum.openaiCodex, // custom provider npm ID\n\t\"@codeworksh/ai-sdk-github-copilot\": Model.KnownProviderEnum.githubCopilot, // custom provider npm ID\n\t\"@openrouter/ai-sdk-provider\": Model.KnownProviderEnum.openrouter,\n\t\"@ai-sdk/xai\": Model.KnownProviderEnum.xai,\n} as const;\n\nexport type AISDKPackage = keyof typeof AI_SDK_PACKAGE_TO_PROTOCOL;\nexport type AISDKProtocol = (typeof AI_SDK_PACKAGE_TO_PROTOCOL)[AISDKPackage];\n\ntype ProviderFactory = (options?: Record<string, unknown>) => unknown;\n\nconst PROVIDER_LOADERS: Record<AISDKPackage, () => Promise<ProviderFactory>> = {\n\t\"@ai-sdk/anthropic\": () => import(\"@ai-sdk/anthropic\").then((m) => m.createAnthropic as ProviderFactory),\n\t\"@ai-sdk/google\": () => import(\"@ai-sdk/google\").then((m) => m.createGoogleGenerativeAI as ProviderFactory),\n\t\"@ai-sdk/google-vertex\": () => import(\"@ai-sdk/google-vertex\").then((m) => m.createVertex as ProviderFactory),\n\t\"@ai-sdk/google-vertex/anthropic\": () =>\n\t\timport(\"@ai-sdk/google-vertex/anthropic\").then((m) => m.createVertexAnthropic as ProviderFactory),\n\t\"@ai-sdk/openai\": () => import(\"@ai-sdk/openai\").then((m) => m.createOpenAI as ProviderFactory),\n\t\"@ai-sdk/openai-compatible\": () =>\n\t\timport(\"@ai-sdk/openai-compatible\").then((m) => m.createOpenAICompatible as unknown as ProviderFactory),\n\t\"@openrouter/ai-sdk-provider\": () =>\n\t\timport(\"@openrouter/ai-sdk-provider\").then((m) => m.createOpenRouter as ProviderFactory),\n\t\"@ai-sdk/xai\": () => import(\"@ai-sdk/xai\").then((m) => m.createXai as ProviderFactory),\n\t// Local provider for OpenAI Codex subscriptions (ChatGPT OAuth); the package\n\t// name is virtual and resolves to src/providers/openai-codex.\n\t\"@codeworksh/ai-sdk-openai-codex\": () =>\n\t\timport(\"../providers/openai-codex/index.ts\").then((m) => m.createOpenAICodex as ProviderFactory),\n\t// Local provider for GitHub Copilot; the package name is virtual and resolves\n\t// to src/providers/github-copilot.\n\t\"@codeworksh/ai-sdk-github-copilot\": () =>\n\t\timport(\"../providers/github-copilot/index.ts\").then((m) => m.createGitHubCopilot as ProviderFactory),\n};\n\nexport function isAISDKPackage(value: string): value is AISDKPackage {\n\treturn value in AI_SDK_PACKAGE_TO_PROTOCOL;\n}\n\nexport function packageForModel(model: Model.Info): AISDKPackage {\n\tconst npm = model.npm ?? DEFAULT_AI_SDK_FALLBACK;\n\treturn isAISDKPackage(npm) ? npm : DEFAULT_AI_SDK_FALLBACK;\n}\n\nexport function protocolForPackage(npm: string | undefined): AISDKProtocol {\n\tconst resolved = npm && isAISDKPackage(npm) ? npm : DEFAULT_AI_SDK_FALLBACK;\n\treturn AI_SDK_PACKAGE_TO_PROTOCOL[resolved];\n}\n\nexport async function loadProviderFactory(npm: AISDKPackage): Promise<ProviderFactory> {\n\treturn PROVIDER_LOADERS[npm]();\n}\n\ntype ProviderWithMethods = {\n\t(modelId: string): LanguageModel;\n\tlanguageModel?: (modelId: string) => LanguageModel;\n\tchat?: (modelId: string) => LanguageModel;\n\tchatModel?: (modelId: string) => LanguageModel;\n\tcompletion?: (modelId: string) => LanguageModel;\n\tcompletionModel?: (modelId: string) => LanguageModel;\n\tmessages?: (modelId: string) => LanguageModel;\n\tresponses?: (modelId: string) => LanguageModel;\n};\n\nfunction defaultMethodForModel(model: Model.Info): Model.APIMethodEnum {\n\tif (\n\t\tmodel.protocol === Model.KnownProviderEnum.openai ||\n\t\tmodel.protocol === Model.KnownProviderEnum.openaiCodex ||\n\t\tmodel.protocol === Model.KnownProviderEnum.xai\n\t) {\n\t\treturn Model.APIMethodEnum.responses;\n\t}\n\treturn Model.APIMethodEnum.languageModel;\n}\n\n/** The endpoint method a model is called through: the request's override, the catalog's, or the default. */\nexport function resolveMethod(model: Model.Info, methodOverride?: Model.APIMethodEnum): Model.APIMethodEnum {\n\treturn methodOverride ?? model.api?.method ?? defaultMethodForModel(model);\n}\n\nexport function resolveLanguageModel(\n\tprovider: unknown,\n\tmodel: Model.Info,\n\tmethodOverride?: Model.APIMethodEnum,\n): LanguageModel {\n\tconst modelId = model.api?.id ?? model.id;\n\tconst method = resolveMethod(model, methodOverride);\n\tconst callable = provider as ProviderWithMethods;\n\n\tif (method === Model.APIMethodEnum.responses && callable.responses) return callable.responses(modelId);\n\tif (method === Model.APIMethodEnum.messages && callable.messages) return callable.messages(modelId);\n\tif (method === Model.APIMethodEnum.chat) {\n\t\tif (callable.chat) return callable.chat(modelId);\n\t\tif (callable.chatModel) return callable.chatModel(modelId);\n\t}\n\tif (method === Model.APIMethodEnum.completion) {\n\t\tif (callable.completion) return callable.completion(modelId);\n\t\tif (callable.completionModel) return callable.completionModel(modelId);\n\t}\n\tif (method === Model.APIMethodEnum.completionModel && callable.completionModel) {\n\t\treturn callable.completionModel(modelId);\n\t}\n\tif (callable.languageModel) return callable.languageModel(modelId);\n\treturn callable(modelId);\n}\n"],"mappings":";;AAGA,MAAa,0BAA0B;AAEvC,MAAa,6BAA6B;CACzC,qBAAA,kBAA6C;CAC7C,kBAAA,kBAA0C;CAC1C,yBAAA,kBAAiD;CACjD,mCAAA,kBAA2D;CAC3D,kBAAA,kBAA0C;CAC1C,6BAAA,kBAAqD;CACrD,mCAAA,kBAA2D;CAC3D,qCAAA,kBAA6D;CAC7D,+BAAA,kBAAuD;CACvD,eAAA,kBAAuC;AACxC;AAOA,MAAM,mBAAyE;CAC9E,2BAA2B,OAAO,oBAAoB,CAAC,MAAM,MAAM,EAAE,eAAkC;CACvG,wBAAwB,OAAO,iBAAiB,CAAC,MAAM,MAAM,EAAE,wBAA2C;CAC1G,+BAA+B,OAAO,wBAAwB,CAAC,MAAM,MAAM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AI,WAAA,cAA+B,YAAY,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO;CAClG,IAAI,WAAA,cAA+B,MAAM;EACxC,IAAI,SAAS,MAAM,OAAO,SAAS,KAAK,OAAO;EAC/C,IAAI,SAAS,WAAW,OAAO,SAAS,UAAU,OAAO;CAC1D;CACA,IAAI,WAAA,cAA+B,YAAY;EAC9C,IAAI,SAAS,YAAY,OAAO,SAAS,WAAW,OAAO;EAC3D,IAAI,SAAS,iBAAiB,OAAO,SAAS,gBAAgB,OAAO;CACtE;CACA,IAAI,WAAA,cAA+B,mBAAmB,SAAS,iBAC9D,OAAO,SAAS,gBAAgB,OAAO;CAExC,IAAI,SAAS,eAAe,OAAO,SAAS,cAAc,OAAO;CACjE,OAAO,SAAS,OAAO;AACxB"}
|
package/codex-CLDBTrFm.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"codex-CLDBTrFm.mjs","names":[],"sources":["../../src/oauth/openai/codex.ts"],"sourcesContent":["/**\n * OpenAI Codex OAuth.\n *\n * Public interface, by use case:\n *\n * 1. Server OAuth integration (storage-free, bring your own routes):\n * `createOpenAICodexAuthorizationFlow`, `exchangeOpenAICodexAuthorizationCode`,\n * `parseOpenAICodexAuthorizationInput`, `refreshOpenAICodexToken`, `getOpenAICodexAccountId`.\n * 2. CLI / interactive login (localhost callback server, persisted credentials):\n * `OpenAICodexOAuthClient`, `JsonOpenAICodexAuthStorage`, `OpenAICodexAuthStorage`.\n * 3. Application credential access (get key, auto-refresh, request headers):\n * `getOpenAICodexApiKey`, `OpenAICodexOAuthClient.getCredentials/getApiKey/getHeaders`,\n * `openAICodexHeaders`, `OPENAI_CODEX_API_KEY_ENV`.\n *\n * Everything else in this module is an implementation detail and intentionally\n * not exported.\n */\n\nimport dedent from \"dedent\";\n\nimport { pollDeviceCode } from \"../devcode.ts\";\nimport { JsonAuthStorage, isObject, readEnv } from \"../storage.ts\";\n\nconst CODEWORK_OAUTH_CALLBACK_HOST = \"CODEWORK_OAUTH_CALLBACK_HOST\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTHORIZE_URL = \"https://auth.openai.com/oauth/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/oauth/token\";\nconst DEFAULT_REDIRECT_URI = \"http://localhost:1455/auth/callback\";\n// Device code: no local port, so it works over SSH, in a container, and when\n// something else already holds 1455. The server mints the PKCE verifier and\n// redeems the code against its own callback.\nconst DEVICE_USER_CODE_URL = \"https://auth.openai.com/api/accounts/deviceauth/usercode\";\nconst DEVICE_TOKEN_URL = \"https://auth.openai.com/api/accounts/deviceauth/token\";\nconst DEVICE_VERIFICATION_URI = \"https://auth.openai.com/codex/device\";\nconst DEVICE_REDIRECT_URI = \"https://auth.openai.com/deviceauth/callback\";\nconst DEVICE_TIMEOUT_SECONDS = 15 * 60;\nconst DEFAULT_SCOPE = \"openid profile email offline_access\";\nconst DEFAULT_ORIGINATOR = \"codework\";\nconst DEFAULT_PROVIDER_ID = \"openai-codex\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\nconst REFRESH_SKEW_MS = 60 * 1000;\n\nexport type OpenAICodexOAuthCredentials = {\n\taccess: string;\n\trefresh: string;\n\texpires: number;\n\taccountId: string;\n};\n\nexport type OpenAICodexTokenSuccess = {\n\ttype: \"success\";\n\taccess: string;\n\trefresh: string;\n\texpires: number;\n};\n\nexport type OpenAICodexTokenFailure = {\n\ttype: \"failed\";\n\tmessage: string;\n\tstatus?: number;\n};\n\nexport type OpenAICodexTokenResult = OpenAICodexTokenSuccess | OpenAICodexTokenFailure;\n\nexport type OpenAICodexAuthorizationFlow = {\n\turl: string;\n\tverifier: string;\n\tstate: string;\n\tredirectUri: string;\n};\n\nexport type OpenAICodexAuthorizationOptions = {\n\toriginator?: string;\n\tredirectUri?: string;\n\tscope?: string;\n};\n\nexport type OpenAICodexLoginPrompt = {\n\tmessage: string;\n\tplaceholder?: string;\n\tallowEmpty?: boolean;\n};\n\nexport type OpenAICodexDeviceAuth = {\n\tdeviceAuthId: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds: number;\n};\n\nexport type OpenAICodexLoginOptions = OpenAICodexAuthorizationOptions & {\n\t/** Use the device-code flow instead of the localhost browser callback. */\n\tdevice?: boolean | undefined;\n\tsignal?: AbortSignal | undefined;\n\tonAuth: (info: { url: string; userCode?: string | undefined; instructions?: string | undefined }) => void;\n\tonPrompt: (prompt: OpenAICodexLoginPrompt) => Promise<string>;\n\tonProgress?: (message: string) => void;\n};\n\nexport interface OpenAICodexAuthStorage {\n\tget(): Promise<OpenAICodexOAuthCredentials | undefined>;\n\tset(credentials: OpenAICodexOAuthCredentials): Promise<void>;\n\tclear(): Promise<void>;\n}\n\nexport type JsonOpenAICodexAuthStorageOptions = {\n\tpath?: string;\n\tproviderId?: string;\n};\n\ntype JwtPayload = {\n\t[JWT_CLAIM_PATH]?: {\n\t\tchatgpt_account_id?: string;\n\t};\n\t[key: string]: unknown;\n};\n\ntype OAuthServerInfo = {\n\tclose: () => Promise<void>;\n\twaitForCode: () => Promise<{ code: string } | null>;\n\t/** Set when the callback port could not be bound; login falls back to pasting. */\n\tlistenError?: Error;\n};\n\ntype TokenEndpointPayload = {\n\taccess_token?: string;\n\trefresh_token?: string;\n\texpires_in?: number;\n};\n\nfunction isOpenAICodexCredentials(value: unknown): value is OpenAICodexOAuthCredentials {\n\tif (!isObject(value)) return false;\n\treturn (\n\t\ttypeof value.access === \"string\" &&\n\t\ttypeof value.refresh === \"string\" &&\n\t\ttypeof value.expires === \"number\" &&\n\t\ttypeof value.accountId === \"string\"\n\t);\n}\n\nfunction redactOAuthSecrets(value: string, secrets: readonly string[] = []): string {\n\tlet redacted = value;\n\tfor (const secret of secrets.filter(Boolean).sort((left, right) => right.length - left.length)) {\n\t\tredacted = redacted.replaceAll(secret, \"[REDACTED]\");\n\t}\n\treturn redacted\n\t\t.replace(\n\t\t\t/((?:\"?(?:access_token|refresh_token|id_token|code|code_verifier)\"?)\\s*[:=]\\s*)(?:\"[^\"]*\"|'[^']*'|[^&\\s,}]+)/gi,\n\t\t\t'$1\"[REDACTED]\"',\n\t\t)\n\t\t.replace(/Bearer\\s+\\S+/gi, \"Bearer [REDACTED]\");\n}\n\nfunction tokenEndpointResult(payload: TokenEndpointPayload, operation: \"exchange\" | \"refresh\"): OpenAICodexTokenResult {\n\tconst missing = [\n\t\t!payload.access_token && \"access_token\",\n\t\t!payload.refresh_token && \"refresh_token\",\n\t\ttypeof payload.expires_in !== \"number\" && \"expires_in\",\n\t].filter((field): field is string => Boolean(field));\n\tif (missing.length > 0) {\n\t\treturn {\n\t\t\ttype: \"failed\",\n\t\t\tmessage: `OpenAI Codex token ${operation} response missing fields: ${missing.join(\", \")}`,\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: \"success\",\n\t\taccess: payload.access_token!,\n\t\trefresh: payload.refresh_token!,\n\t\texpires: Date.now() + payload.expires_in! * 1000,\n\t};\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction base64UrlDecode(value: string): string {\n\tconst base64 = value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n\tconst padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n\treturn atob(padded);\n}\n\ntype WebCrypto = typeof globalThis.crypto;\n\nfunction getCrypto(): WebCrypto {\n\tif (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {\n\t\tthrow new Error(\"openAI codex OAuth requires web crypto support\");\n\t}\n\treturn globalThis.crypto;\n}\n\nfunction createState(): string {\n\tconst bytes = new Uint8Array(16);\n\tgetCrypto().getRandomValues(bytes);\n\treturn Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nasync function generatePKCE(): Promise<{\n\tverifier: string;\n\tchallenge: string;\n}> {\n\tconst bytes = new Uint8Array(32);\n\tgetCrypto().getRandomValues(bytes);\n\tconst verifier = base64UrlEncode(bytes);\n\n\tconst data = new TextEncoder().encode(verifier);\n\tconst hash = await getCrypto().subtle.digest(\"SHA-256\", data);\n\tconst challenge = base64UrlEncode(new Uint8Array(hash));\n\n\treturn { verifier, challenge };\n}\n\nfunction authorizationInput(code: string | null | undefined, state: string | null | undefined) {\n\treturn {\n\t\t...(code != null && { code }),\n\t\t...(state != null && { state }),\n\t};\n}\n\nexport function parseOpenAICodexAuthorizationInput(input: string): {\n\tcode?: string;\n\tstate?: string;\n} {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn authorizationInput(url.searchParams.get(\"code\"), url.searchParams.get(\"state\"));\n\t} catch {\n\t\t// Not a URL.\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn authorizationInput(code, state);\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn authorizationInput(params.get(\"code\"), params.get(\"state\"));\n\t}\n\n\treturn { code: value };\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) return null;\n\t\treturn JSON.parse(base64UrlDecode(parts[1] ?? \"\")) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function getOpenAICodexAccountId(accessToken: string): string | null {\n\tconst payload = decodeJwt(accessToken);\n\tconst auth = payload?.[JWT_CLAIM_PATH];\n\tconst accountId = auth?.chatgpt_account_id;\n\treturn typeof accountId === \"string\" && accountId.length > 0 ? accountId : null;\n}\n\nexport async function createOpenAICodexAuthorizationFlow(\n\toptions: OpenAICodexAuthorizationOptions = {},\n): Promise<OpenAICodexAuthorizationFlow> {\n\tconst redirectUri = options.redirectUri ?? DEFAULT_REDIRECT_URI;\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = createState();\n\n\tconst url = new URL(AUTHORIZE_URL);\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", CLIENT_ID);\n\turl.searchParams.set(\"redirect_uri\", redirectUri);\n\turl.searchParams.set(\"scope\", options.scope ?? DEFAULT_SCOPE);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"state\", state);\n\turl.searchParams.set(\"id_token_add_organizations\", \"true\");\n\turl.searchParams.set(\"codex_cli_simplified_flow\", \"true\");\n\turl.searchParams.set(\"originator\", options.originator ?? DEFAULT_ORIGINATOR);\n\n\treturn { verifier, state, redirectUri, url: url.toString() };\n}\n\nexport async function exchangeOpenAICodexAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string = DEFAULT_REDIRECT_URI,\n): Promise<OpenAICodexTokenResult> {\n\ttry {\n\t\tconst response = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t}),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\treturn {\n\t\t\t\ttype: \"failed\",\n\t\t\t\tstatus: response.status,\n\t\t\t\tmessage: `OpenAI Codex token exchange failed (${response.status}): ${redactOAuthSecrets(\n\t\t\t\t\ttext || response.statusText,\n\t\t\t\t\t[code, verifier],\n\t\t\t\t)}`,\n\t\t\t};\n\t\t}\n\n\t\treturn tokenEndpointResult((await response.json()) as TokenEndpointPayload, \"exchange\");\n\t} catch (error) {\n\t\treturn {\n\t\t\ttype: \"failed\",\n\t\t\tmessage: `OpenAI Codex token exchange error: ${redactOAuthSecrets(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t[code, verifier],\n\t\t\t)}`,\n\t\t};\n\t}\n}\n\nasync function refreshAccessToken(refreshToken: string): Promise<OpenAICodexTokenResult> {\n\ttry {\n\t\tconst response = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t}),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\treturn {\n\t\t\t\ttype: \"failed\",\n\t\t\t\tstatus: response.status,\n\t\t\t\tmessage: `OpenAI Codex token refresh failed (${response.status}): ${redactOAuthSecrets(\n\t\t\t\t\ttext || response.statusText,\n\t\t\t\t\t[refreshToken],\n\t\t\t\t)}`,\n\t\t\t};\n\t\t}\n\n\t\treturn tokenEndpointResult((await response.json()) as TokenEndpointPayload, \"refresh\");\n\t} catch (error) {\n\t\treturn {\n\t\t\ttype: \"failed\",\n\t\t\tmessage: `OpenAI Codex token refresh error: ${redactOAuthSecrets(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t[refreshToken],\n\t\t\t)}`,\n\t\t};\n\t}\n}\n\nfunction oauthPage(options: { title: string; heading: string; message: string; details?: string }): string {\n\tconst escapeHtml = (value: string) =>\n\t\tvalue\n\t\t\t.replaceAll(\"&\", \"&\")\n\t\t\t.replaceAll(\"<\", \"<\")\n\t\t\t.replaceAll(\">\", \">\")\n\t\t\t.replaceAll('\"', \""\")\n\t\t\t.replaceAll(\"'\", \"'\");\n\tconst details = options.details ? escapeHtml(options.details) : undefined;\n\n\treturn dedent`\n\t<!doctype html>\n\t<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\" />\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\t\t<title>${escapeHtml(options.title)}</title>\n\t\t<style>\n\t\t\thtml { color-scheme: dark; }\n\t\t\tbody {\n\t\t\tmargin: 0;\n\t\t\tmin-height: 100vh;\n\t\t\tdisplay: grid;\n\t\t\tplace-items: center;\n\t\t\tpadding: 24px;\n\t\t\tbackground: #09090b;\n\t\t\tcolor: #fafafa;\n\t\t\tfont-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n\t\t\ttext-align: center;\n\t\t\t}\n\t\t\tmain { width: 100%; max-width: 560px; }\n\t\t\th1 { margin: 0 0 10px; font-size: 28px; line-height: 1.15; font-weight: 650; }\n\t\t\tp { margin: 0; line-height: 1.7; color: #a1a1aa; font-size: 15px; }\n\t\t\t.details { margin-top: 16px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; color: #a1a1aa; white-space: pre-wrap; word-break: break-word; }\n\t\t</style>\n\t</head>\n\t<body>\n\t\t<main>\n\t\t\t<h1>${escapeHtml(options.heading)}</h1>\n\t\t\t<p>${escapeHtml(options.message)}</p>\n\t\t\t${details ? `<div class=\"details\">${details}</div>` : \"\"}\n\t\t</main>\n\t</body>\n\t</html>\n\t`;\n}\n\nfunction oauthSuccessHtml(message: string): string {\n\treturn oauthPage({\n\t\ttitle: \"Authentication successful\",\n\t\theading: \"Authentication successful\",\n\t\tmessage,\n\t});\n}\n\nfunction oauthErrorHtml(message: string, details?: string): string {\n\treturn oauthPage({\n\t\ttitle: \"Authentication failed\",\n\t\theading: \"Authentication failed\",\n\t\tmessage,\n\t\t...(details !== undefined && { details }),\n\t});\n}\n\nasync function startLocalOAuthServer(state: string, redirectUri: string): Promise<OAuthServerInfo> {\n\t// The port and path are the ones the authorization server will redirect to:\n\t// binding anything else means the callback arrives somewhere we are not.\n\tconst callback = new URL(redirectUri);\n\tconst port = Number(callback.port || (callback.protocol === \"https:\" ? 443 : 80));\n\n\tconst http = await import(\"node:http\").catch(() => undefined);\n\tif (!http) {\n\t\tthrow new Error(\"openAI codex OAuth callback server is only available in Node.js environments\");\n\t}\n\n\tlet settleWait: ((value: { code: string } | null) => void) | undefined;\n\tconst waitForCodePromise = new Promise<{ code: string } | null>((resolve) => {\n\t\tlet settled = false;\n\t\tsettleWait = (value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tresolve(value);\n\t\t};\n\t});\n\n\tconst server = http.createServer((req, res) => {\n\t\ttry {\n\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\tif (url.pathname !== callback.pathname) {\n\t\t\t\tres.statusCode = 404;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url.searchParams.get(\"state\") !== state) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\tif (!code) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(oauthSuccessHtml(\"OpenAI authentication completed. You can close this window.\"));\n\t\t\tsettleWait?.({ code });\n\t\t} catch (error) {\n\t\t\tres.statusCode = 500;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(\n\t\t\t\toauthErrorHtml(\n\t\t\t\t\t\"Internal error while processing OAuth callback.\",\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t});\n\tconst close = async (): Promise<void> => {\n\t\tif (!server.listening) return;\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve());\n\t\t\tserver.closeAllConnections();\n\t\t});\n\t};\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(port, readEnv(CODEWORK_OAUTH_CALLBACK_HOST) || \"127.0.0.1\", () => {\n\t\t\t\tresolve({\n\t\t\t\t\tclose,\n\t\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on(\"error\", (error: Error) => {\n\t\t\t\tsettleWait?.(null);\n\t\t\t\tresolve({\n\t\t\t\t\tclose,\n\t\t\t\t\twaitForCode: async () => null,\n\t\t\t\t\tlistenError: error,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n\n// Internal: the public login entry point is `OpenAICodexOAuthClient#login`,\n// which persists the credentials. Server integrations should use the\n// storage-free authorization helpers instead of this localhost-callback flow.\nasync function loginOpenAICodex(options: OpenAICodexLoginOptions): Promise<OpenAICodexOAuthCredentials> {\n\tif (options.device) return loginOpenAICodexDeviceCode(options);\n\n\tconst flow = await createOpenAICodexAuthorizationFlow(options);\n\tconst server = await startLocalOAuthServer(flow.state, flow.redirectUri);\n\n\toptions.onAuth({\n\t\turl: flow.url,\n\t\tinstructions: \"Complete the browser login to finish OpenAI Codex authentication.\",\n\t});\n\n\tif (server.listenError) {\n\t\t// The redirect URI is registered against the OAuth client, so the port\n\t\t// cannot move. Whatever holds it -- usually another Codex login already in\n\t\t// progress -- will receive this callback instead of us.\n\t\toptions.onProgress?.(\n\t\t\t`Could not listen on ${flow.redirectUri}: ${server.listenError.message}. ` +\n\t\t\t\t\"Another sign-in is probably already running on that port and would receive the callback. \" +\n\t\t\t\t\"Finish the login in the browser, then paste the redirect URL here.\",\n\t\t);\n\t}\n\n\tlet code: string | undefined;\n\ttry {\n\t\tconst result = await server.waitForCode();\n\t\tif (result?.code) code = result.code;\n\n\t\t// The callback never arrived -- the port was taken, or the browser could\n\t\t// not reach us. Ask for the redirect URL instead.\n\t\tif (!code) {\n\t\t\tconst input = await options.onPrompt({\n\t\t\t\tmessage: \"Paste the authorization code or full redirect URL:\",\n\t\t\t});\n\t\t\tconst parsed = parseOpenAICodexAuthorizationInput(input);\n\t\t\tif (parsed.state && parsed.state !== flow.state) throw new Error(\"state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) throw new Error(\"missing authorization code\");\n\n\t\treturn await credentialsFromCode(code, flow.verifier, flow.redirectUri);\n\t} finally {\n\t\tawait server.close();\n\t}\n}\n\n/** The step both flows share: redeem the code, then read the account off the JWT. */\nasync function credentialsFromCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n): Promise<OpenAICodexOAuthCredentials> {\n\tconst tokenResult = await exchangeOpenAICodexAuthorizationCode(code, verifier, redirectUri);\n\tif (tokenResult.type !== \"success\") throw new Error(tokenResult.message);\n\n\tconst accountId = getOpenAICodexAccountId(tokenResult.access);\n\tif (!accountId) throw new Error(\"failed to extract accountId from token\");\n\n\treturn {\n\t\taccess: tokenResult.access,\n\t\trefresh: tokenResult.refresh,\n\t\texpires: tokenResult.expires,\n\t\taccountId,\n\t};\n}\n\n/** Ask for a user code to type at {@link DEVICE_VERIFICATION_URI}. */\nexport async function createOpenAICodexDeviceAuth(\n\toptions: { signal?: AbortSignal | undefined } = {},\n): Promise<OpenAICodexDeviceAuth> {\n\tconst response = await fetch(DEVICE_USER_CODE_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({ client_id: CLIENT_ID }),\n\t\tsignal: options.signal ?? null,\n\t});\n\tif (!response.ok) {\n\t\tif (response.status === 404) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI Codex device code login is not available for this account. Use the browser login instead.\",\n\t\t\t);\n\t\t}\n\t\tconst body = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`OpenAI Codex device code request failed (${response.status})${body ? `: ${redactOAuthSecrets(body)}` : \"\"}`,\n\t\t);\n\t}\n\n\tconst data: unknown = await response.json();\n\tif (!isObject(data)) throw new Error(\"Invalid OpenAI Codex device code response\");\n\tconst interval = typeof data.interval === \"string\" ? Number(data.interval.trim()) : data.interval;\n\tif (\n\t\ttypeof data.device_auth_id !== \"string\" ||\n\t\ttypeof data.user_code !== \"string\" ||\n\t\ttypeof interval !== \"number\" ||\n\t\t!Number.isFinite(interval) ||\n\t\tinterval < 0\n\t) {\n\t\tthrow new Error(\"Invalid OpenAI Codex device code response fields\");\n\t}\n\n\treturn {\n\t\tdeviceAuthId: data.device_auth_id,\n\t\tuserCode: data.user_code,\n\t\tverificationUri: DEVICE_VERIFICATION_URI,\n\t\tintervalSeconds: interval,\n\t};\n}\n\n/** Wait for the code to be approved; the server returns the code and its verifier. */\nexport async function pollOpenAICodexDeviceAuth(\n\tdevice: OpenAICodexDeviceAuth,\n\toptions: { signal?: AbortSignal | undefined } = {},\n): Promise<{ authorizationCode: string; codeVerifier: string }> {\n\treturn pollDeviceCode({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_TIMEOUT_SECONDS,\n\t\t...(options.signal !== undefined && { signal: options.signal }),\n\t\tpoll: async () => {\n\t\t\tconst response = await fetch(DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ device_auth_id: device.deviceAuthId, user_code: device.userCode }),\n\t\t\t\tsignal: options.signal ?? null,\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tconst data: unknown = await response.json();\n\t\t\t\tif (\n\t\t\t\t\t!isObject(data) ||\n\t\t\t\t\ttypeof data.authorization_code !== \"string\" ||\n\t\t\t\t\ttypeof data.code_verifier !== \"string\"\n\t\t\t\t) {\n\t\t\t\t\treturn { status: \"failed\", message: \"Invalid OpenAI Codex device auth token response\" };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tvalue: { authorizationCode: data.authorization_code, codeVerifier: data.code_verifier },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// The endpoint answers 403/404 while the code is still unclaimed.\n\t\t\tif (response.status === 403 || response.status === 404) return { status: \"pending\" };\n\n\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(body);\n\t\t\t\tconst error = isObject(parsed) ? parsed.error : undefined;\n\t\t\t\terrorCode = isObject(error) ? error.code : error;\n\t\t\t} catch {\n\t\t\t\t// Not JSON; fall through to the generic failure below.\n\t\t\t}\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") return { status: \"pending\" };\n\t\t\tif (errorCode === \"slow_down\") return { status: \"slow_down\" };\n\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `OpenAI Codex device authorization failed (${response.status})${\n\t\t\t\t\tbody ? `: ${redactOAuthSecrets(body)}` : \"\"\n\t\t\t\t}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\nasync function loginOpenAICodexDeviceCode(options: OpenAICodexLoginOptions): Promise<OpenAICodexOAuthCredentials> {\n\tconst device = await createOpenAICodexDeviceAuth(options);\n\toptions.onAuth({\n\t\turl: device.verificationUri,\n\t\tuserCode: device.userCode,\n\t\tinstructions: \"Open the URL and enter the code to finish OpenAI Codex authentication.\",\n\t});\n\n\tconst { authorizationCode, codeVerifier } = await pollOpenAICodexDeviceAuth(device, options);\n\treturn credentialsFromCode(authorizationCode, codeVerifier, DEVICE_REDIRECT_URI);\n}\n\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OpenAICodexOAuthCredentials> {\n\tconst result = await refreshAccessToken(refreshToken);\n\tif (result.type !== \"success\") {\n\t\tthrow new Error(result.message);\n\t}\n\n\tconst accountId = getOpenAICodexAccountId(result.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\taccess: result.access,\n\t\trefresh: result.refresh,\n\t\texpires: result.expires,\n\t\taccountId,\n\t};\n}\n\nexport function openAICodexHeaders(credentials: OpenAICodexOAuthCredentials): Record<string, string> {\n\treturn {\n\t\tAuthorization: `Bearer ${credentials.access}`,\n\t\t\"chatgpt-account-id\": credentials.accountId,\n\t\t\"OpenAI-Beta\": \"responses=experimental\",\n\t};\n}\n\nexport class JsonOpenAICodexAuthStorage implements OpenAICodexAuthStorage {\n\tprivate readonly storage: JsonAuthStorage<OpenAICodexOAuthCredentials>;\n\n\tconstructor(options: JsonOpenAICodexAuthStorageOptions = {}) {\n\t\tthis.storage = new JsonAuthStorage({\n\t\t\tproviderId: options.providerId ?? DEFAULT_PROVIDER_ID,\n\t\t\tisCredentials: isOpenAICodexCredentials,\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<OpenAICodexOAuthCredentials | undefined> {\n\t\treturn this.storage.get();\n\t}\n\n\tset(credentials: OpenAICodexOAuthCredentials): 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 OpenAICodexOAuthClientOptions = {\n\tstorage?: OpenAICodexAuthStorage;\n\trefreshSkewMs?: number;\n};\n\nexport class OpenAICodexOAuthClient {\n\treadonly storage: OpenAICodexAuthStorage;\n\treadonly refreshSkewMs: number;\n\n\tconstructor(options: OpenAICodexOAuthClientOptions = {}) {\n\t\tthis.storage = options.storage ?? new JsonOpenAICodexAuthStorage();\n\t\tthis.refreshSkewMs = options.refreshSkewMs ?? REFRESH_SKEW_MS;\n\t}\n\n\tasync login(options: OpenAICodexLoginOptions): Promise<OpenAICodexOAuthCredentials> {\n\t\tconst credentials = await loginOpenAICodex(options);\n\t\tawait this.storage.set(credentials);\n\t\treturn credentials;\n\t}\n\n\tasync getCredentials(): Promise<OpenAICodexOAuthCredentials | undefined> {\n\t\tconst credentials = await this.storage.get();\n\t\tif (!credentials) return undefined;\n\n\t\tif (credentials.expires > Date.now() + this.refreshSkewMs) {\n\t\t\treturn credentials;\n\t\t}\n\n\t\tconst refreshed = await refreshOpenAICodexToken(credentials.refresh);\n\t\tawait this.storage.set(refreshed);\n\t\treturn refreshed;\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 ? openAICodexHeaders(credentials) : undefined;\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tawait this.storage.clear();\n\t}\n}\n\nexport const OPENAI_CODEX_API_KEY_ENV = \"OPENAI_CODEX_API_KEY\";\n\n/**\n * Resolve the OpenAI Codex API key the same way other provider API keys are\n * resolved: prefer the OPENAI_CODEX_API_KEY environment variable, then fall\n * back to stored OAuth credentials (refreshing them when close to expiry).\n *\n * The result can be passed directly as `apiKey` to the runtime options or to\n * `createOpenAICodex`. Returns undefined when no key is available.\n */\nexport async function getOpenAICodexApiKey(options: OpenAICodexOAuthClientOptions = {}): Promise<string | undefined> {\n\tconst envKey = readEnv(OPENAI_CODEX_API_KEY_ENV);\n\tif (envKey) return envKey;\n\n\treturn new OpenAICodexOAuthClient(options).getApiKey();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,+BAA+B;AAErC,MAAM,YAAY;AAClB,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,uBAAuB;AAI7B,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,0BAA0B;AA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I,SAAS;EAChC,OAAO;CACR;CAEA,MAAM,YAAyC;EAC9C,QAAQ,MAAM,KAAK,eAAe,EAAA,EAAI;CACvC;CAEA,MAAM,aAA0D;EAC/D,MAAM,cAAc,MAAM,KAAK,eAAe;EAC9C,OAAO,cAAc,mBAAmB,WAAW,IAAI,KAAA;CACxD;CAEA,MAAM,SAAwB;EAC7B,MAAM,KAAK,QAAQ,MAAM;CAC1B;AACD;AAEA,MAAa,2BAA2B;;;;;;;;;AAUxC,eAAsB,qBAAqB,UAAyC,CAAC,GAAgC;CACpH,MAAM,SAAS,QAAQ,wBAAwB;CAC/C,IAAI,QAAQ,OAAO;CAEnB,OAAO,IAAI,uBAAuB,OAAO,CAAC,CAAC,UAAU;AACtD"}
|
package/copilot-DvUXC6Kx.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-DvUXC6Kx.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,QAAwB;CACvD,OAAO,WAAW,iBAAiB,mBAAmB,OAAO;AAC9D;;AAGA,SAAgB,qBAAqB,SAG1B;CACV,MAAM,cAAc,SAAS;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G,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"}
|
package/failure-DFQNKc-O.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,UAAU,UACf,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAC/D,QACD,KAAA;AAEJ,MAAM,kBAAkB,UACvB,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,IAAI,MAAM,KAAK,IAAI,KAAA;AAEvE,MAAM,oBAAoB,YAA4B;CAErD,OADgB,QAAQ,KAAK,CAAC,CAAC,QAAQ,YAAY,EACtC,CAAC,CAAC,QAAQ,gBAAgB,SAAS,KAAK,YAAY,CAAC;AACnE;AAEA,MAAM,gBAAgB,UAA2B;CAChD,MAAM,QAAQ,OAAO,KAAK;CAC1B,MAAM,OAAO,OAAO,OAAO,IAAI;CAC/B,IAAI,OAAO,SAAS,qBACnB,OAAO,iBAAiB,eAAe,MAAM,OAAO,KAAK,kCAAkC;CAE5F,IAAI,iBAAiB,OA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E,MAAM;EAAa,SAAS,aAAa,KAAK;EAAG,WAAW;CAAK;CAE3E,OAAO;EAAE,MAAM;EAAW,SAAS,aAAa,KAAK;EAAG,WAAW;CAAM;AAC1E;;AAGA,SAAgB,YAAY,SAA0B;CACrD,MAAM,aAAa,iBAAiB,OAAO;CAC3C,IAAI,WAAW,KAAK,UAAU,KAAK,4BAA4B,KAAK,UAAU,GAC7E,OAAO;EAAE,MAAM;EAAkB,QAAQ;EAAW,SAAS;EAAY,WAAW;CAAM;CAE3F,IAAI,4BAA4B,KAAK,UAAU,KAAK,gCAAgC,KAAK,UAAU,GAClG,OAAO;EACN,MAAM;EACN,QAAQ,WAAW,KAAK,UAAU,IAAI,YAAY;EAClD,SAAS;EACT,WAAW;CACZ;CAED,OAAO;EAAE,MAAM;EAAW,SAAS;EAAY,WAAW;CAAM;AACjE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot-BcmOr0jd.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,iB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,OAAO;CAC3D,SAAS,aAAa,YAAoB,UAAU,UAAU,OAAO;CACrE,SAAS,YAAY,YAAoB,SAAS,SAAS,OAAO;CAClE,SAAS,kBAAkB,YAAoB;EAC9C,MAAM,IAAI,iBAAiB;GAC1B;GACA,WAAW;GACX,SAAS;EACV,CAAC;CACF;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EAC1C,MAAM,IAAI,iBAAiB;GAC1B;GACA,WAAW;GACX,SAAS;EACV,CAAC;CACF;CAEA,OAAO;AACR;AAEA,MAAa,gBAAgB,oBAAoB"}
|
package/interactive-eoNnscGB.mjs
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
//#region src/oauth/interactive.ts
|
|
2
|
-
/**
|
|
3
|
-
* Terminal affordances an interactive OAuth login needs: open the
|
|
4
|
-
* authorization URL, and read a pasted code back.
|
|
5
|
-
*
|
|
6
|
-
* Shared so the aikit CLI and anything built on these flows behave the same —
|
|
7
|
-
* they previously kept private copies, and the copies drifted.
|
|
8
|
-
*/
|
|
9
|
-
/**
|
|
10
|
-
* Open a URL in the platform browser.
|
|
11
|
-
*
|
|
12
|
-
* `spawn` reports a missing launcher asynchronously, as an `error` event rather
|
|
13
|
-
* than a throw or a rejected promise, so an unhandled one takes the process
|
|
14
|
-
* down — on a box without `xdg-open`, printing a URL would become a crash.
|
|
15
|
-
* `onError` receives that instead.
|
|
16
|
-
*/
|
|
17
|
-
async function openBrowser(url, onError) {
|
|
18
|
-
const { spawn } = await import("node:child_process");
|
|
19
|
-
const command = process.platform === "darwin" ? {
|
|
20
|
-
file: "open",
|
|
21
|
-
args: [url]
|
|
22
|
-
} : process.platform === "win32" ? {
|
|
23
|
-
file: "cmd",
|
|
24
|
-
args: [
|
|
25
|
-
"/c",
|
|
26
|
-
"start",
|
|
27
|
-
"",
|
|
28
|
-
url
|
|
29
|
-
]
|
|
30
|
-
} : {
|
|
31
|
-
file: "xdg-open",
|
|
32
|
-
args: [url]
|
|
33
|
-
};
|
|
34
|
-
const child = spawn(command.file, command.args, {
|
|
35
|
-
detached: true,
|
|
36
|
-
stdio: "ignore"
|
|
37
|
-
});
|
|
38
|
-
child.on("error", (error) => onError?.(error));
|
|
39
|
-
child.unref();
|
|
40
|
-
}
|
|
41
|
-
/** Read one line from stdin, prompting on stdout. */
|
|
42
|
-
async function promptLine(message) {
|
|
43
|
-
const { createInterface } = await import("node:readline/promises");
|
|
44
|
-
const readline = createInterface({
|
|
45
|
-
input: process.stdin,
|
|
46
|
-
output: process.stdout
|
|
47
|
-
});
|
|
48
|
-
try {
|
|
49
|
-
return await readline.question(`${message} `);
|
|
50
|
-
} finally {
|
|
51
|
-
readline.close();
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
//#endregion
|
|
55
|
-
export { promptLine as n, openBrowser as t };
|
|
56
|
-
|
|
57
|
-
//# sourceMappingURL=interactive-eoNnscGB.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-eoNnscGB.mjs","names":[],"sources":["../../src/oauth/interactive.ts"],"sourcesContent":["/**\n * Terminal affordances an interactive OAuth login needs: open the\n * authorization URL, and read a pasted code back.\n *\n * Shared so the aikit CLI and anything built on these flows behave the same —\n * they previously kept private copies, and the copies drifted.\n */\n\n/**\n * Open a URL in the platform browser.\n *\n * `spawn` reports a missing launcher asynchronously, as an `error` event rather\n * than a throw or a rejected promise, so an unhandled one takes the process\n * down — on a box without `xdg-open`, printing a URL would become a crash.\n * `onError` receives that instead.\n */\nexport async function openBrowser(url: string, onError?: (error: Error) => void): Promise<void> {\n\tconst { spawn } = await import(\"node:child_process\");\n\tconst command =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? { file: \"open\", args: [url] }\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? { file: \"cmd\", args: [\"/c\", \"start\", \"\", url] }\n\t\t\t\t: { file: \"xdg-open\", args: [url] };\n\n\tconst child = spawn(command.file, command.args, { detached: true, stdio: \"ignore\" });\n\tchild.on(\"error\", (error) => onError?.(error));\n\tchild.unref();\n}\n\n/** Read one line from stdin, prompting on stdout. */\nexport async function promptLine(message: string): Promise<string> {\n\tconst { createInterface } = await import(\"node:readline/promises\");\n\tconst readline = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\treturn await readline.question(`${message} `);\n\t} finally {\n\t\treadline.close();\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,eAAsB,YAAY,KAAa,SAAiD;CAC/F,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,UACL,QAAQ,aAAa,WAClB;EAAE,MAAM;EAAQ,MAAM,CAAC,GAAG;CAAE,IAC5B,QAAQ,aAAa,UACpB;EAAE,MAAM;EAAO,MAAM;GAAC;GAAM;GAAS;GAAI;EAAG;CAAE,IAC9C;EAAE,MAAM;EAAY,MAAM,CAAC,GAAG;CAAE;CAErC,MAAM,QAAQ,MAAM,QAAQ,MAAM,QAAQ,MAAM;EAAE,UAAU;EAAM,OAAO;CAAS,CAAC;CACnF,MAAM,GAAG,UAAU,UAAU,UAAU,KAAK,CAAC;CAC7C,MAAM,MAAM;AACb;;AAGA,eAAsB,WAAW,SAAkC;CAClE,MAAM,EAAE,oBAAoB,MAAM,OAAO;CACzC,MAAM,WAAW,gBAAgB;EAAE,OAAO,QAAQ;EAAO,QAAQ,QAAQ;CAAO,CAAC;CACjF,IAAI;EACH,OAAO,MAAM,SAAS,SAAS,GAAG,QAAQ,EAAE;CAC7C,UAAU;EACT,SAAS,MAAM;CAChB;AACD"}
|