@bastani/pi-ai 0.9.25 → 0.9.26-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/NOTICE.md +1 -1
  3. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  4. package/dist/api/openai-responses-shared.js +6 -5
  5. package/dist/api/openai-responses-shared.js.map +1 -1
  6. package/dist/auth/helpers.d.ts +1 -0
  7. package/dist/auth/helpers.d.ts.map +1 -1
  8. package/dist/auth/helpers.js +1 -0
  9. package/dist/auth/helpers.js.map +1 -1
  10. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  11. package/dist/auth/oauth/anthropic.js +1 -0
  12. package/dist/auth/oauth/anthropic.js.map +1 -1
  13. package/dist/auth/oauth/oauth-page.js +1 -1
  14. package/dist/auth/oauth/oauth-page.js.map +1 -1
  15. package/dist/auth/oauth/openai-chatgpt.d.ts.map +1 -1
  16. package/dist/auth/oauth/openai-chatgpt.js +1 -0
  17. package/dist/auth/oauth/openai-chatgpt.js.map +1 -1
  18. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  19. package/dist/auth/oauth/openai-codex.js +1 -0
  20. package/dist/auth/oauth/openai-codex.js.map +1 -1
  21. package/dist/auth/oauth/openrouter.d.ts.map +1 -1
  22. package/dist/auth/oauth/openrouter.js +1 -0
  23. package/dist/auth/oauth/openrouter.js.map +1 -1
  24. package/dist/auth/types.d.ts +1 -0
  25. package/dist/auth/types.d.ts.map +1 -1
  26. package/dist/auth/types.js.map +1 -1
  27. package/dist/providers/anthropic.d.ts.map +1 -1
  28. package/dist/providers/anthropic.js +1 -0
  29. package/dist/providers/anthropic.js.map +1 -1
  30. package/dist/providers/data/.manifest.json +1 -1
  31. package/dist/providers/data/fireworks.json +1 -1
  32. package/dist/providers/data/nvidia.json +1 -1
  33. package/dist/providers/data/opencode.json +1 -1
  34. package/dist/providers/data/openrouter.json +1 -1
  35. package/dist/providers/data/together.json +1 -1
  36. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  37. package/dist/providers/openai-codex.d.ts.map +1 -1
  38. package/dist/providers/openai-codex.js +1 -0
  39. package/dist/providers/openai-codex.js.map +1 -1
  40. package/dist/providers/openai.d.ts.map +1 -1
  41. package/dist/providers/openai.js +1 -0
  42. package/dist/providers/openai.js.map +1 -1
  43. package/dist/providers/openrouter.d.ts.map +1 -1
  44. package/dist/providers/openrouter.js +1 -0
  45. package/dist/providers/openrouter.js.map +1 -1
  46. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-page.js","sourceRoot":"","sources":["../../../src/auth/oauth/oauth-page.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,2LAA2L,CAAC;AAE7M,SAAS,UAAU,CAAC,KAAa;IAChC,OAAO,KAAK;SACV,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;SACxB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC;SACvB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC;SACvB,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC;SACzB,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAC5B,CAAC;AAED,SAAS,UAAU,CAAC,OAA8E;IACjG,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAE1E,OAAO;;;;;WAKG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA8DQ,QAAQ;UACtB,OAAO;SACR,OAAO;MACV,OAAO,CAAC,CAAC,CAAC,wBAAwB,OAAO,QAAQ,CAAC,CAAC,CAAC,EAAE;;;QAGpD,CAAC;AACT,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC/C,OAAO,UAAU,CAAC;QACjB,KAAK,EAAE,2BAA2B;QAClC,OAAO,EAAE,2BAA2B;QACpC,OAAO;KACP,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,OAAgB;IAC/D,OAAO,UAAU,CAAC;QACjB,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,uBAAuB;QAChC,OAAO;QACP,OAAO;KACP,CAAC,CAAC;AACJ,CAAC","sourcesContent":["const LOGO_SVG = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 80 80\" aria-hidden=\"true\"><text x=\"40\" y=\"62\" text-anchor=\"middle\" font-family=\"monospace\" font-size=\"72\" fill=\"#fff\">∀</text></svg>`;\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#39;\");\n}\n\nfunction renderPage(options: { title: string; heading: string; message: string; details?: string }): string {\n\tconst title = escapeHtml(options.title);\n\tconst heading = escapeHtml(options.heading);\n\tconst message = escapeHtml(options.message);\n\tconst details = options.details ? escapeHtml(options.details) : undefined;\n\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n <style>\n :root {\n --text: #fafafa;\n --text-dim: #a1a1aa;\n --page-bg: #09090b;\n --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n * { box-sizing: border-box; }\n html { color-scheme: dark; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: var(--page-bg);\n color: var(--text);\n font-family: var(--font-sans);\n text-align: center;\n }\n main {\n width: 100%;\n max-width: 560px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n }\n .logo {\n width: 72px;\n height: 72px;\n display: block;\n margin-bottom: 24px;\n }\n h1 {\n margin: 0 0 10px;\n font-size: 28px;\n line-height: 1.15;\n font-weight: 650;\n color: var(--text);\n }\n p {\n margin: 0;\n line-height: 1.7;\n color: var(--text-dim);\n font-size: 15px;\n }\n .details {\n margin-top: 16px;\n font-family: var(--font-mono);\n font-size: 13px;\n color: var(--text-dim);\n white-space: pre-wrap;\n word-break: break-word;\n }\n </style>\n</head>\n<body>\n <main>\n <div class=\"logo\">${LOGO_SVG}</div>\n <h1>${heading}</h1>\n <p>${message}</p>\n ${details ? `<div class=\"details\">${details}</div>` : \"\"}\n </main>\n</body>\n</html>`;\n}\n\nexport function oauthSuccessHtml(message: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication successful\",\n\t\theading: \"Authentication successful\",\n\t\tmessage,\n\t});\n}\n\nexport function oauthErrorHtml(message: string, details?: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication failed\",\n\t\theading: \"Authentication failed\",\n\t\tmessage,\n\t\tdetails,\n\t});\n}\n"]}
1
+ {"version":3,"file":"oauth-page.js","sourceRoot":"","sources":["../../../src/auth/oauth/oauth-page.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,8LAA8L,CAAC;AAEhN,SAAS,UAAU,CAAC,KAAa;IAChC,OAAO,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=\"0 0 80 80\" aria-hidden=\"true\"><text x=\"40\" y=\"62\" text-anchor=\"middle\" font-family=\"monospace\" font-size=\"72\" fill=\"#89b4fa\">∀</text></svg>`;\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#39;\");\n}\n\nfunction renderPage(options: { title: string; heading: string; message: string; details?: string }): string {\n\tconst title = escapeHtml(options.title);\n\tconst heading = escapeHtml(options.heading);\n\tconst message = escapeHtml(options.message);\n\tconst details = options.details ? escapeHtml(options.details) : undefined;\n\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n <style>\n :root {\n --text: #fafafa;\n --text-dim: #a1a1aa;\n --page-bg: #09090b;\n --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n * { box-sizing: border-box; }\n html { color-scheme: dark; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: var(--page-bg);\n color: var(--text);\n font-family: var(--font-sans);\n text-align: center;\n }\n main {\n width: 100%;\n max-width: 560px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n }\n .logo {\n width: 72px;\n height: 72px;\n display: block;\n margin-bottom: 24px;\n }\n h1 {\n margin: 0 0 10px;\n font-size: 28px;\n line-height: 1.15;\n font-weight: 650;\n color: var(--text);\n }\n p {\n margin: 0;\n line-height: 1.7;\n color: var(--text-dim);\n font-size: 15px;\n }\n .details {\n margin-top: 16px;\n font-family: var(--font-mono);\n font-size: 13px;\n color: var(--text-dim);\n white-space: pre-wrap;\n word-break: break-word;\n }\n </style>\n</head>\n<body>\n <main>\n <div class=\"logo\">${LOGO_SVG}</div>\n <h1>${heading}</h1>\n <p>${message}</p>\n ${details ? `<div class=\"details\">${details}</div>` : \"\"}\n </main>\n</body>\n</html>`;\n}\n\nexport function oauthSuccessHtml(message: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication successful\",\n\t\theading: \"Authentication successful\",\n\t\tmessage,\n\t});\n}\n\nexport function oauthErrorHtml(message: string, details?: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication failed\",\n\t\theading: \"Authentication failed\",\n\t\tmessage,\n\t\tdetails,\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-chatgpt.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAgB,SAAS,EAA4C,MAAM,aAAa,CAAC;AAsQrG,eAAO,MAAM,kBAAkB,EAAE,SAShC,CAAC"}
1
+ {"version":3,"file":"openai-chatgpt.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAgB,SAAS,EAA4C,MAAM,aAAa,CAAC;AAsQrG,eAAO,MAAM,kBAAkB,EAAE,SAUhC,CAAC"}
@@ -239,6 +239,7 @@ async function loginOpenAIChatGPT(interaction, options) {
239
239
  }
240
240
  export const openaiChatGPTOAuth = {
241
241
  name: "OpenAI (ChatGPT subscription)",
242
+ usesCallbackServer: true,
242
243
  isSubscription: true,
243
244
  loginLabel: "Sign in with ChatGPT",
244
245
  login: loginOpenAIChatGPT,
@@ -1 +1 @@
1
- {"version":3,"file":"openai-chatgpt.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-ch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,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,6CAA6C,EAAE,CAAC,CAAC;QACjG,OAAO,MAAM,yBAAyB,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACpG,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACnE,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,WAAW,CAAC,KAAK,EAAE,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;QACzB,+EAA+E;QAC/E,QAAQ,EAAE,MAAM,CAAC,mBAAmB,EAAE,CAAC;IACxC,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC5C,IAAI,EAAE,+BAA+B;IACrC,cAAc,EAAE,IAAI;IACpB,UAAU,EAAE,sBAAsB;IAClC,KAAK,EAAE,kBAAkB;IACzB,OAAO,EAAE,kBAAkB;IAC3B,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/** Direct OpenAI Responses API token sharing through Sign in with ChatGPT. */\nimport { randomBytes } from \"node:crypto\";\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"../../utils/oauth-page.ts\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst DYNAMIC_CLIENT_ID = \"dynamic_agent_client\";\nconst AGENT_NAME_HINT = \"Atomic\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst AUTHORIZE_URL = \"https://auth.openai.com/api/accounts/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/api/accounts/oauth/token\";\nconst RESOURCE = \"https://api.openai.com/v1\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 1455;\nconst CALLBACK_PATH = \"/auth/callback\";\nconst REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst DIRECT_TOKEN_SCOPE = \"chatgpt.tokens.use.direct\";\nconst SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;\nconst EXPIRY_MARGIN_MS = 3 * 60 * 1000;\n\ntype AuthorizationResult = { code: string; clientId: string };\ntype CallbackServer = { server: Server; result: Promise<AuthorizationResult> };\ntype TokenResponse = {\n\taccess_token?: unknown;\n\trefresh_token?: unknown;\n\texpires_in?: unknown;\n\tid_token?: unknown;\n\tscope?: unknown;\n};\n\nfunction randomValue(): string {\n\treturn randomBytes(32).toString(\"base64url\");\n}\n\nfunction authorizationResultFromCallback(url: URL, expectedState: string): AuthorizationResult {\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"Missing authorization code\");\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state) throw new Error(\"Missing OAuth state\");\n\tif (state !== expectedState) throw new Error(\"OAuth state mismatch\");\n\tconst clientId = url.searchParams.get(\"client_id\")?.trim();\n\tif (!clientId) throw new Error(\"OpenAI OAuth registration callback did not contain an issued client ID\");\n\treturn { code, clientId };\n}\n\nfunction authorizationResultFromManualInput(input: string, expectedState: string): AuthorizationResult {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Paste the full callback URL from the browser\");\n\t}\n\tconst expected = new URL(REDIRECT_URI);\n\tif (url.origin !== expected.origin || url.pathname !== expected.pathname) {\n\t\tthrow new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(`ChatGPT authorization failed: ${error}`);\n\treturn authorizationResultFromCallback(url, expectedState);\n}\n\nfunction sendHtml(response: ServerResponse, status: number, body: string): void {\n\tresponse.writeHead(status, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\tresponse.end(body);\n}\n\nfunction startCallbackServer(expectedState: string): Promise<CallbackServer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet resolveResult!: (result: AuthorizationResult) => void;\n\t\tlet rejectResult!: (error: Error) => void;\n\t\tconst result = new Promise<AuthorizationResult>((resolveAuthorization, rejectAuthorization) => {\n\t\t\tresolveResult = resolveAuthorization;\n\t\t\trejectResult = rejectAuthorization;\n\t\t});\n\t\tconst server = createServer((request, response) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(request.url || \"\", REDIRECT_URI);\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\t\t\t\tif (error) {\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"ChatGPT was not connected.\", `Error: ${error}`));\n\t\t\t\t\trejectResult(new Error(`ChatGPT authorization failed: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet authorizationResult: AuthorizationResult;\n\t\t\t\ttry {\n\t\t\t\t\tauthorizationResult = authorizationResultFromCallback(url, expectedState);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Invalid callback\";\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(message));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"ChatGPT authentication completed. You can close this window.\"));\n\t\t\t\tresolveResult(authorizationResult);\n\t\t\t} catch {\n\t\t\t\tsendHtml(response, 500, oauthErrorHtml(\"Internal error while processing the callback.\"));\n\t\t\t}\n\t\t});\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tserver.on(\"error\", rejectResult);\n\t\t\tresolve({ server, result });\n\t\t});\n\t});\n}\n\nasync function requestToken(body: URLSearchParams, signal: AbortSignal): Promise<TokenResponse> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\tbody,\n\t\tsignal,\n\t});\n\tif (!response.ok) {\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\tthrow new Error(\"OpenAI OAuth token response must be an object\");\n\t}\n\treturn data as TokenResponse;\n}\n\nfunction requireTokenString(value: unknown, field: \"access_token\" | \"refresh_token\" | \"scope\"): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`OpenAI OAuth token response has invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction credentialFromTokenResponse(token: TokenResponse, clientId: string): OAuthCredential {\n\tconst access = requireTokenString(token.access_token, \"access_token\");\n\tconst refresh = requireTokenString(token.refresh_token, \"refresh_token\");\n\tconst scope = requireTokenString(token.scope, \"scope\");\n\tif (typeof token.expires_in !== \"number\" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response has invalid expires_in\");\n\t}\n\tconst scopes = scope.trim().split(/\\s+/).filter(Boolean);\n\tif (!scopes.includes(DIRECT_TOKEN_SCOPE)) {\n\t\tthrow new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);\n\t}\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,\n\t\tclientId,\n\t\tscopes,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tclientId: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: clientId,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\t// The ID token is required by the response contract, but is not used for profile data.\n\tif (typeof token.id_token !== \"string\" || token.id_token.trim().length === 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response did not contain an ID token\");\n\t}\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nasync function refreshAccessToken(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst clientId = credential.clientId;\n\tif (typeof clientId !== \"string\" || clientId.trim().length === 0) {\n\t\tthrow new Error(\"Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT\");\n\t}\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: clientId,\n\t\t\trefresh_token: credential.refresh,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nfunction agentHostId(deviceId: string | undefined): string {\n\tif (!deviceId || !UUID_PATTERN.test(deviceId)) {\n\t\tthrow new Error(\"Sign in with ChatGPT requires a device ID (UUID) for this installation\");\n\t}\n\treturn `urn:uuid:${deviceId.toLowerCase()}`;\n}\n\nasync function loginOpenAIChatGPT(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst hostId = agentHostId(options?.getDeviceId?.());\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = randomValue();\n\tconst nonce = randomValue();\n\tlet callback: CallbackServer | undefined;\n\ttry {\n\t\tcallback = await startCallbackServer(state);\n\t} catch (error) {\n\t\tinteraction.notify({\n\t\t\ttype: \"info\",\n\t\t\tmessage: `Could not listen on ${REDIRECT_URI}; paste the final redirect URL to continue. ${error instanceof Error ? error.message : String(error)}`,\n\t\t});\n\t}\n\tconst authorizationUrl = new URL(AUTHORIZE_URL);\n\tauthorizationUrl.search = new URLSearchParams({\n\t\tclient_id: DYNAMIC_CLIENT_ID,\n\t\tagent_name_hint: AGENT_NAME_HINT,\n\t\text_agent_host_id: hostId,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: REDIRECT_URI,\n\t\tresource: RESOURCE,\n\t\tscope: SCOPE,\n\t\tstate,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tnonce,\n\t}).toString();\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizationUrl.toString(),\n\t\tinstructions:\n\t\t\t\"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.\",\n\t});\n\tconst manualAbort = new AbortController();\n\tconst manualCode = interaction\n\t\t.prompt({\n\t\t\ttype: \"manual_code\",\n\t\t\tmessage: \"Complete login in your browser, or paste the final redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t\tsignal: AbortSignal.any([manualAbort.signal, interaction.signal]),\n\t\t})\n\t\t.then((input) => authorizationResultFromManualInput(input, state));\n\ttry {\n\t\tconst result = await (callback ? Promise.race([callback.result, manualCode]) : manualCode);\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);\n\t} catch (error) {\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow error;\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback?.server.close();\n\t\t// Spare browser connections must not deliver a later login to this old server.\n\t\tcallback?.server.closeAllConnections();\n\t}\n}\n\nexport const openaiChatGPTOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with ChatGPT\",\n\tlogin: loginOpenAIChatGPT,\n\trefresh: refreshAccessToken,\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"openai-chatgpt.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,iBAAiB,GAAG,sBAAsB,CAAC;AACjD,MAAM,eAAe,GAAG,QAAQ,CAAC;AACjC,MAAM,YAAY,GAAG,iEAAiE,CAAC;AACvF,MAAM,aAAa,GAAG,gDAAgD,CAAC;AACvE,MAAM,SAAS,GAAG,kDAAkD,CAAC;AACrE,MAAM,QAAQ,GAAG,2BAA2B,CAAC;AAC7C,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,gBAAgB,CAAC;AACvC,MAAM,YAAY,GAAG,oBAAoB,aAAa,GAAG,aAAa,EAAE,CAAC;AACzE,MAAM,kBAAkB,GAAG,2BAA2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AAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/** Direct OpenAI Responses API token sharing through Sign in with ChatGPT. */\nimport { randomBytes } from \"node:crypto\";\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"../../utils/oauth-page.ts\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst DYNAMIC_CLIENT_ID = \"dynamic_agent_client\";\nconst AGENT_NAME_HINT = \"Atomic\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst AUTHORIZE_URL = \"https://auth.openai.com/api/accounts/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/api/accounts/oauth/token\";\nconst RESOURCE = \"https://api.openai.com/v1\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 1455;\nconst CALLBACK_PATH = \"/auth/callback\";\nconst REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst DIRECT_TOKEN_SCOPE = \"chatgpt.tokens.use.direct\";\nconst SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;\nconst EXPIRY_MARGIN_MS = 3 * 60 * 1000;\n\ntype AuthorizationResult = { code: string; clientId: string };\ntype CallbackServer = { server: Server; result: Promise<AuthorizationResult> };\ntype TokenResponse = {\n\taccess_token?: unknown;\n\trefresh_token?: unknown;\n\texpires_in?: unknown;\n\tid_token?: unknown;\n\tscope?: unknown;\n};\n\nfunction randomValue(): string {\n\treturn randomBytes(32).toString(\"base64url\");\n}\n\nfunction authorizationResultFromCallback(url: URL, expectedState: string): AuthorizationResult {\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"Missing authorization code\");\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state) throw new Error(\"Missing OAuth state\");\n\tif (state !== expectedState) throw new Error(\"OAuth state mismatch\");\n\tconst clientId = url.searchParams.get(\"client_id\")?.trim();\n\tif (!clientId) throw new Error(\"OpenAI OAuth registration callback did not contain an issued client ID\");\n\treturn { code, clientId };\n}\n\nfunction authorizationResultFromManualInput(input: string, expectedState: string): AuthorizationResult {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Paste the full callback URL from the browser\");\n\t}\n\tconst expected = new URL(REDIRECT_URI);\n\tif (url.origin !== expected.origin || url.pathname !== expected.pathname) {\n\t\tthrow new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(`ChatGPT authorization failed: ${error}`);\n\treturn authorizationResultFromCallback(url, expectedState);\n}\n\nfunction sendHtml(response: ServerResponse, status: number, body: string): void {\n\tresponse.writeHead(status, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\tresponse.end(body);\n}\n\nfunction startCallbackServer(expectedState: string): Promise<CallbackServer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet resolveResult!: (result: AuthorizationResult) => void;\n\t\tlet rejectResult!: (error: Error) => void;\n\t\tconst result = new Promise<AuthorizationResult>((resolveAuthorization, rejectAuthorization) => {\n\t\t\tresolveResult = resolveAuthorization;\n\t\t\trejectResult = rejectAuthorization;\n\t\t});\n\t\tconst server = createServer((request, response) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(request.url || \"\", REDIRECT_URI);\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\t\t\t\tif (error) {\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"ChatGPT was not connected.\", `Error: ${error}`));\n\t\t\t\t\trejectResult(new Error(`ChatGPT authorization failed: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet authorizationResult: AuthorizationResult;\n\t\t\t\ttry {\n\t\t\t\t\tauthorizationResult = authorizationResultFromCallback(url, expectedState);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Invalid callback\";\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(message));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"ChatGPT authentication completed. You can close this window.\"));\n\t\t\t\tresolveResult(authorizationResult);\n\t\t\t} catch {\n\t\t\t\tsendHtml(response, 500, oauthErrorHtml(\"Internal error while processing the callback.\"));\n\t\t\t}\n\t\t});\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tserver.on(\"error\", rejectResult);\n\t\t\tresolve({ server, result });\n\t\t});\n\t});\n}\n\nasync function requestToken(body: URLSearchParams, signal: AbortSignal): Promise<TokenResponse> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\tbody,\n\t\tsignal,\n\t});\n\tif (!response.ok) {\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\tthrow new Error(\"OpenAI OAuth token response must be an object\");\n\t}\n\treturn data as TokenResponse;\n}\n\nfunction requireTokenString(value: unknown, field: \"access_token\" | \"refresh_token\" | \"scope\"): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`OpenAI OAuth token response has invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction credentialFromTokenResponse(token: TokenResponse, clientId: string): OAuthCredential {\n\tconst access = requireTokenString(token.access_token, \"access_token\");\n\tconst refresh = requireTokenString(token.refresh_token, \"refresh_token\");\n\tconst scope = requireTokenString(token.scope, \"scope\");\n\tif (typeof token.expires_in !== \"number\" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response has invalid expires_in\");\n\t}\n\tconst scopes = scope.trim().split(/\\s+/).filter(Boolean);\n\tif (!scopes.includes(DIRECT_TOKEN_SCOPE)) {\n\t\tthrow new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);\n\t}\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,\n\t\tclientId,\n\t\tscopes,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tclientId: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: clientId,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\t// The ID token is required by the response contract, but is not used for profile data.\n\tif (typeof token.id_token !== \"string\" || token.id_token.trim().length === 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response did not contain an ID token\");\n\t}\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nasync function refreshAccessToken(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst clientId = credential.clientId;\n\tif (typeof clientId !== \"string\" || clientId.trim().length === 0) {\n\t\tthrow new Error(\"Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT\");\n\t}\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: clientId,\n\t\t\trefresh_token: credential.refresh,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nfunction agentHostId(deviceId: string | undefined): string {\n\tif (!deviceId || !UUID_PATTERN.test(deviceId)) {\n\t\tthrow new Error(\"Sign in with ChatGPT requires a device ID (UUID) for this installation\");\n\t}\n\treturn `urn:uuid:${deviceId.toLowerCase()}`;\n}\n\nasync function loginOpenAIChatGPT(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst hostId = agentHostId(options?.getDeviceId?.());\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = randomValue();\n\tconst nonce = randomValue();\n\tlet callback: CallbackServer | undefined;\n\ttry {\n\t\tcallback = await startCallbackServer(state);\n\t} catch (error) {\n\t\tinteraction.notify({\n\t\t\ttype: \"info\",\n\t\t\tmessage: `Could not listen on ${REDIRECT_URI}; paste the final redirect URL to continue. ${error instanceof Error ? error.message : String(error)}`,\n\t\t});\n\t}\n\tconst authorizationUrl = new URL(AUTHORIZE_URL);\n\tauthorizationUrl.search = new URLSearchParams({\n\t\tclient_id: DYNAMIC_CLIENT_ID,\n\t\tagent_name_hint: AGENT_NAME_HINT,\n\t\text_agent_host_id: hostId,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: REDIRECT_URI,\n\t\tresource: RESOURCE,\n\t\tscope: SCOPE,\n\t\tstate,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tnonce,\n\t}).toString();\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizationUrl.toString(),\n\t\tinstructions:\n\t\t\t\"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.\",\n\t});\n\tconst manualAbort = new AbortController();\n\tconst manualCode = interaction\n\t\t.prompt({\n\t\t\ttype: \"manual_code\",\n\t\t\tmessage: \"Complete login in your browser, or paste the final redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t\tsignal: AbortSignal.any([manualAbort.signal, interaction.signal]),\n\t\t})\n\t\t.then((input) => authorizationResultFromManualInput(input, state));\n\ttry {\n\t\tconst result = await (callback ? Promise.race([callback.result, manualCode]) : manualCode);\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);\n\t} catch (error) {\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow error;\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback?.server.close();\n\t\t// Spare browser connections must not deliver a later login to this old server.\n\t\tcallback?.server.closeAllConnections();\n\t}\n}\n\nexport const openaiChatGPTOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT subscription)\",\n\tusesCallbackServer: true,\n\tisSubscription: true,\n\tloginLabel: \"Sign in with ChatGPT\",\n\tlogin: loginOpenAIChatGPT,\n\trefresh: refreshAccessToken,\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAqYvF,eAAO,MAAM,gBAAgB,EAAE,SA6B9B,CAAC"}
1
+ {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAqYvF,eAAO,MAAM,gBAAgB,EAAE,SA8B9B,CAAC"}
@@ -320,6 +320,7 @@ async function refreshOpenAICodexToken(refreshToken, signal) {
320
320
  }
321
321
  export const openaiCodexOAuth = {
322
322
  name: "OpenAI (ChatGPT Plus/Pro)",
323
+ usesCallbackServer: true,
323
324
  isSubscription: true,
324
325
  async login(interaction) {
325
326
  const method = await interaction.prompt({
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,kEAAkE;AAClE,IAAI,YAAY,GAAoD,IAAI,CAAC;AACzE,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;IACzF,MAAM,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;QAChC,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9B,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,SAAS,GAAG,8BAA8B,CAAC;AACjD,MAAM,aAAa,GAAG,yBAAyB,CAAC;AAChD,MAAM,aAAa,GAAG,GAAG,aAAa,kBAAkB,CAAC;AACzD,MAAM,SAAS,GAAG,GAAG,aAAa,cAAc,CAAC;AACjD,MAAM,YAAY,GAAG,qCAAqC,CAAC;AAC3D,MAAM,oBAAoB,GAAG,GAAG,aAAa,mCAAmC,CAAC;AACjF,MAAM,gBAAgB,G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E,CAAC;YACtD,OAAO,0BAA0B,CAAC,WAAW,CAAC,CAAC;QAChD,CAAC;QACD,IAAI,MAAM,KAAK,iCAAiC,EAAE,CAAC;YAClD,MAAM,IAAI,KAAK,CAAC,sCAAsC,MAAM,EAAE,CAAC,CAAC;QACjE,CAAC;QAED,OAAO,gBAAgB,CAAC,WAAW,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAEpF,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _randomBytes: typeof import(\"node:crypto\").randomBytes | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:crypto\").then((m) => {\n\t\t_randomBytes = m.randomBytes;\n\t});\n}\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTH_BASE_URL = \"https://auth.openai.com\";\nconst AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;\nconst TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;\nconst DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nconst OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = \"device_code\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\n\ntype OAuthToken = { access: string; refresh: string; expires: number };\ntype TokenOperation = \"exchange\" | \"refresh\";\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype DeviceAuthInfo = {\n\tdeviceAuthId: string;\n\tuserCode: string;\n\tintervalSeconds: number;\n};\n\ntype DeviceTokenSuccess = {\n\tauthorizationCode: string;\n\tcodeVerifier: 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\nfunction createState(): string {\n\tif (!_randomBytes) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\treturn _randomBytes(16).toString(\"hex\");\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\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 { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\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\tconst payload = parts[1] ?? \"\";\n\t\tconst decoded = atob(payload);\n\t\treturn JSON.parse(decoded) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function fetchWithLoginCancellation(input: string, init: RequestInit): Promise<Response> {\n\ttry {\n\t\treturn await fetch(input, init);\n\t} catch (error) {\n\t\tif (init.signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function readTokenResponse(response: Response, operation: TokenOperation): Promise<OAuthToken> {\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\taccess_token?: string;\n\t\trefresh_token?: string;\n\t\texpires_in?: number;\n\t} | null;\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\taccess: json.access_token,\n\t\trefresh: json.refresh_token,\n\t\texpires: Date.now() + json.expires_in * 1000,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthToken> {\n\tconst response = await fetchWithLoginCancellation(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: redirectUri,\n\t\t}),\n\t\tsignal,\n\t});\n\n\treturn readTokenResponse(response, \"exchange\");\n}\n\nasync function refreshAccessToken(refreshToken: string, signal: AbortSignal): Promise<OAuthToken> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = 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\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(`OpenAI Codex token refresh error: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\n\treturn readTokenResponse(response, \"refresh\");\n}\n\nasync function startOpenAICodexDeviceAuth(signal: AbortSignal): Promise<DeviceAuthInfo> {\n\tconst response = await fetchWithLoginCancellation(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,\n\t});\n\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 enabled for this server. Use browser login or verify the server URL.\",\n\t\t\t);\n\t\t}\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\tdevice_auth_id?: string;\n\t\tuser_code?: string;\n\t\tinterval?: number | string;\n\t} | null;\n\tconst intervalSeconds = typeof json?.interval === \"string\" ? Number(json.interval.trim()) : json?.interval;\n\tif (\n\t\t!json?.device_auth_id ||\n\t\t!json.user_code ||\n\t\ttypeof intervalSeconds !== \"number\" ||\n\t\t!Number.isFinite(intervalSeconds) ||\n\t\tintervalSeconds < 0\n\t) {\n\t\tthrow new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\tdeviceAuthId: json.device_auth_id,\n\t\tuserCode: json.user_code,\n\t\tintervalSeconds,\n\t};\n}\n\nasync function pollOpenAICodexDeviceAuth(device: DeviceAuthInfo, signal: AbortSignal): Promise<DeviceTokenSuccess> {\n\treturn pollOAuthDeviceCodeFlow<DeviceTokenSuccess>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await fetchWithLoginCancellation(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({\n\t\t\t\t\tdevice_auth_id: device.deviceAuthId,\n\t\t\t\t\tuser_code: device.userCode,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tconst rawJson = await response.json();\n\t\t\t\tconst json = rawJson as { authorization_code?: string; code_verifier?: string } | null;\n\t\t\t\tif (!json?.authorization_code || !json.code_verifier) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tvalue: { authorizationCode: json.authorization_code, codeVerifier: json.code_verifier },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (response.status === 403 || response.status === 404) {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\n\t\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(responseBody) as { error?: string | { code?: string } } | null;\n\t\t\t\tconst error = json?.error;\n\t\t\t\terrorCode = typeof error === \"object\" ? error?.code : error;\n\t\t\t} catch {}\n\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (errorCode === \"slow_down\") {\n\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\nasync function createAuthorizationFlow(\n\toriginator: string = \"pi\",\n): Promise<{ verifier: string; state: string; url: string }> {\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\", REDIRECT_URI);\n\turl.searchParams.set(\"scope\", 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\", originator);\n\n\treturn { verifier, state, url: url.toString() };\n}\n\nfunction getAccountId(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\nfunction credentialsFromToken(token: OAuthToken): OAuthCredential {\n\tconst accountId = getAccountId(token.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: token.access,\n\t\trefresh: token.refresh,\n\t\texpires: token.expires,\n\t\taccountId,\n\t};\n}\n\nasync function exchangeAuthorizationCodeForCredentials(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\nasync function loginOpenAICodexDeviceCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await startOpenAICodexDeviceAuth(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: DEVICE_VERIFICATION_URI,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t});\n\tconst code = await pollOpenAICodexDeviceAuth(device, interaction.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\nasync function loginOpenAICodex(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, state, url } = await createAuthorizationFlow();\n\t// Port 1455 is shared with Codex CLI. Fall back to a pasted URL when occupied.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenAI\",\n\t\thost: getCallbackHost(),\n\t\tport: 1455,\n\t\tpath: \"/auth/callback\",\n\t\tstate,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl,\n\t\tinstructions: \"A browser window should open. Complete login to finish.\",\n\t});\n\n\ttry {\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== 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\t\treturn await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nasync function refreshOpenAICodexToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await refreshAccessToken(refreshToken, signal));\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select OpenAI Codex login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: \"Device code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode(interaction);\n\t\t}\n\t\tif (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${method}`);\n\t\t}\n\n\t\treturn loginOpenAICodex(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"openai-codex.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names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AO,EAAE,MAAM,CAAC;IAEpF,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _randomBytes: typeof import(\"node:crypto\").randomBytes | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:crypto\").then((m) => {\n\t\t_randomBytes = m.randomBytes;\n\t});\n}\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTH_BASE_URL = \"https://auth.openai.com\";\nconst AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;\nconst TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;\nconst DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nconst OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = \"device_code\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\n\ntype OAuthToken = { access: string; refresh: string; expires: number };\ntype TokenOperation = \"exchange\" | \"refresh\";\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype DeviceAuthInfo = {\n\tdeviceAuthId: string;\n\tuserCode: string;\n\tintervalSeconds: number;\n};\n\ntype DeviceTokenSuccess = {\n\tauthorizationCode: string;\n\tcodeVerifier: 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\nfunction createState(): string {\n\tif (!_randomBytes) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\treturn _randomBytes(16).toString(\"hex\");\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\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 { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\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\tconst payload = parts[1] ?? \"\";\n\t\tconst decoded = atob(payload);\n\t\treturn JSON.parse(decoded) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function fetchWithLoginCancellation(input: string, init: RequestInit): Promise<Response> {\n\ttry {\n\t\treturn await fetch(input, init);\n\t} catch (error) {\n\t\tif (init.signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function readTokenResponse(response: Response, operation: TokenOperation): Promise<OAuthToken> {\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\taccess_token?: string;\n\t\trefresh_token?: string;\n\t\texpires_in?: number;\n\t} | null;\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\taccess: json.access_token,\n\t\trefresh: json.refresh_token,\n\t\texpires: Date.now() + json.expires_in * 1000,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthToken> {\n\tconst response = await fetchWithLoginCancellation(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: redirectUri,\n\t\t}),\n\t\tsignal,\n\t});\n\n\treturn readTokenResponse(response, \"exchange\");\n}\n\nasync function refreshAccessToken(refreshToken: string, signal: AbortSignal): Promise<OAuthToken> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = 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\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(`OpenAI Codex token refresh error: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\n\treturn readTokenResponse(response, \"refresh\");\n}\n\nasync function startOpenAICodexDeviceAuth(signal: AbortSignal): Promise<DeviceAuthInfo> {\n\tconst response = await fetchWithLoginCancellation(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,\n\t});\n\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 enabled for this server. Use browser login or verify the server URL.\",\n\t\t\t);\n\t\t}\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\tdevice_auth_id?: string;\n\t\tuser_code?: string;\n\t\tinterval?: number | string;\n\t} | null;\n\tconst intervalSeconds = typeof json?.interval === \"string\" ? Number(json.interval.trim()) : json?.interval;\n\tif (\n\t\t!json?.device_auth_id ||\n\t\t!json.user_code ||\n\t\ttypeof intervalSeconds !== \"number\" ||\n\t\t!Number.isFinite(intervalSeconds) ||\n\t\tintervalSeconds < 0\n\t) {\n\t\tthrow new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\tdeviceAuthId: json.device_auth_id,\n\t\tuserCode: json.user_code,\n\t\tintervalSeconds,\n\t};\n}\n\nasync function pollOpenAICodexDeviceAuth(device: DeviceAuthInfo, signal: AbortSignal): Promise<DeviceTokenSuccess> {\n\treturn pollOAuthDeviceCodeFlow<DeviceTokenSuccess>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await fetchWithLoginCancellation(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({\n\t\t\t\t\tdevice_auth_id: device.deviceAuthId,\n\t\t\t\t\tuser_code: device.userCode,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tconst rawJson = await response.json();\n\t\t\t\tconst json = rawJson as { authorization_code?: string; code_verifier?: string } | null;\n\t\t\t\tif (!json?.authorization_code || !json.code_verifier) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tvalue: { authorizationCode: json.authorization_code, codeVerifier: json.code_verifier },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (response.status === 403 || response.status === 404) {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\n\t\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(responseBody) as { error?: string | { code?: string } } | null;\n\t\t\t\tconst error = json?.error;\n\t\t\t\terrorCode = typeof error === \"object\" ? error?.code : error;\n\t\t\t} catch {}\n\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (errorCode === \"slow_down\") {\n\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\nasync function createAuthorizationFlow(\n\toriginator: string = \"pi\",\n): Promise<{ verifier: string; state: string; url: string }> {\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\", REDIRECT_URI);\n\turl.searchParams.set(\"scope\", 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\", originator);\n\n\treturn { verifier, state, url: url.toString() };\n}\n\nfunction getAccountId(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\nfunction credentialsFromToken(token: OAuthToken): OAuthCredential {\n\tconst accountId = getAccountId(token.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: token.access,\n\t\trefresh: token.refresh,\n\t\texpires: token.expires,\n\t\taccountId,\n\t};\n}\n\nasync function exchangeAuthorizationCodeForCredentials(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\nasync function loginOpenAICodexDeviceCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await startOpenAICodexDeviceAuth(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: DEVICE_VERIFICATION_URI,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t});\n\tconst code = await pollOpenAICodexDeviceAuth(device, interaction.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\nasync function loginOpenAICodex(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, state, url } = await createAuthorizationFlow();\n\t// Port 1455 is shared with Codex CLI. Fall back to a pasted URL when occupied.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenAI\",\n\t\thost: getCallbackHost(),\n\t\tport: 1455,\n\t\tpath: \"/auth/callback\",\n\t\tstate,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl,\n\t\tinstructions: \"A browser window should open. Complete login to finish.\",\n\t});\n\n\ttry {\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== 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\t\treturn await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nasync function refreshOpenAICodexToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await refreshAccessToken(refreshToken, signal));\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\tusesCallbackServer: true,\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select OpenAI Codex login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: \"Device code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode(interaction);\n\t\t}\n\t\tif (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${method}`);\n\t\t}\n\n\t\treturn loginOpenAICodex(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openrouter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAgJvF,eAAO,MAAM,eAAe,EAAE,SAU7B,CAAC"}
1
+ {"version":3,"file":"openrouter.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openrouter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAgJvF,eAAO,MAAM,eAAe,EAAE,SAW7B,CAAC"}
@@ -146,6 +146,7 @@ async function loginOpenRouter(interaction) {
146
146
  }
147
147
  export const openRouterOAuth = {
148
148
  name: "OpenRouter OAuth",
149
+ usesCallbackServer: true,
149
150
  loginLabel: "Sign in with OpenRouter",
150
151
  login: loginOpenRouter,
151
152
  async refresh(credential, _signal) {
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter.js","sourceRoot":"","sources":["../../../src/auth/oauth/openrouter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,aAAa,GAAG,4BAA4B,CAAC;AACnD,MAAM,SAAS,GAAG,wCAAwC,CAAC;AAC3D,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AACvC,MAAM,yBAAyB,GAAG,MAAM,CAAC;AAEzC,SAAS,eAAe;IACvB,OAAO,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACrE,CAAC;AAID,SAAS,uBAAuB,CAAC,KAAa;IAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC3B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAE7B,IAAI,CAAC;QACJ,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC;IAC7D,CAAC;IAAC,MAAM,CAAC;QACR,YAAY;IACb,CAAC;IAED,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7B,OAAO,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,M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enRouter OAuth PKCE flow.\n *\n * OpenRouter exchanges an authorization code for a permanent, user-controlled\n * API key rather than an expiring access/refresh token pair. The callback is\n * handled by a one-shot loopback server on an ephemeral port, raced against a\n * manual prompt so remote/headless sessions can paste the redirect URL when\n * the browser cannot reach the loopback server.\n *\n * NOTE: This module uses node:http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst AUTHORIZE_URL = \"https://openrouter.ai/auth\";\nconst TOKEN_URL = \"https://openrouter.ai/api/v1/auth/keys\";\nconst LOGIN_TIMEOUT_MS = 5 * 60 * 1000;\nconst TOKEN_EXCHANGE_TIMEOUT_MS = 30_000;\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype JsonObject = Record<string, unknown>;\n\nfunction parseAuthorizationInput(input: string): string | undefined {\n\tconst value = input.trim();\n\tif (!value) return undefined;\n\n\ttry {\n\t\treturn new URL(value).searchParams.get(\"code\") ?? undefined;\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\treturn new URLSearchParams(value).get(\"code\") ?? undefined;\n\t}\n\n\treturn value;\n}\n\nfunction errorDetail(body: JsonObject): string | undefined {\n\tif (typeof body.error_description === \"string\") return body.error_description;\n\tif (typeof body.message === \"string\") return body.message;\n\tif (typeof body.error === \"string\") return body.error;\n\tif (body.error && typeof body.error === \"object\" && !Array.isArray(body.error)) {\n\t\tconst message = (body.error as JsonObject).message;\n\t\tif (typeof message === \"string\") return message;\n\t}\n\treturn undefined;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\tconst controller = new AbortController();\n\tconst onAbort = () => controller.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\tconst timeout = setTimeout(\n\t\t() => controller.abort(new Error(\"OpenRouter OAuth token exchange timed out\")),\n\t\tTOKEN_EXCHANGE_TIMEOUT_MS,\n\t);\n\n\tlet response: Response;\n\tlet body: JsonObject = {};\n\ttry {\n\t\tresponse = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: \"S256\" }),\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\ttry {\n\t\t\tconst parsed = (await response.json()) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) body = parsed as JsonObject;\n\t\t} catch {\n\t\t\tif (response.ok) throw new Error(\"OpenRouter OAuth returned invalid JSON\");\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\t\tif (controller.signal.aborted) throw new Error(\"OpenRouter OAuth token exchange timed out\");\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n\n\tif (!response.ok) {\n\t\tconst detail = errorDetail(body);\n\t\tthrow new Error(`OpenRouter OAuth key exchange failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n\t}\n\n\tif (typeof body.key !== \"string\" || body.key.length === 0) {\n\t\tthrow new Error('OpenRouter OAuth response carries no \"key\"');\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: body.key,\n\t\trefresh: \"\",\n\t\texpires: Number.MAX_SAFE_INTEGER,\n\t};\n}\n\nasync function loginOpenRouter(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\t// OpenRouter sends no state. The random path guards against stray callbacks.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenRouter\",\n\t\thost: getCallbackHost(),\n\t\tport: 0,\n\t\tpath: `/oauth/callback/${crypto.randomUUID()}`,\n\t\tcomplete: (code) => exchangeAuthorizationCode(code, verifier, interaction.signal),\n\t\tsignal: interaction.signal,\n\t\ttimeoutMs: LOGIN_TIMEOUT_MS,\n\t});\n\n\ttry {\n\t\tconst authorizeUrl = new URL(AUTHORIZE_URL);\n\t\tauthorizeUrl.search = new URLSearchParams({\n\t\t\tcallback_url: callback.redirectUri,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t}).toString();\n\n\t\tinteraction.notify({\n\t\t\ttype: \"progress\",\n\t\t\tmessage: `Listening for OpenRouter OAuth callback on ${callback.redirectUri}`,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: authorizeUrl.toString(),\n\t\t\tinstructions:\n\t\t\t\t\"Complete sign-in in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete sign-in in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: callback.redirectUri,\n\t\t});\n\t\tif (result.type === \"callback\") return result.value;\n\t\tconst code = parseAuthorizationInput(result.input);\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for an API key...\" });\n\t\treturn await exchangeAuthorizationCode(code, verifier, interaction.signal);\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nexport const openRouterOAuth: OAuthAuth = {\n\tname: \"OpenRouter OAuth\",\n\tloginLabel: \"Sign in with OpenRouter\",\n\tlogin: loginOpenRouter,\n\tasync refresh(credential, _signal) {\n\t\treturn credential;\n\t},\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n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AAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,4BAA4B,CAAC,WAAW,EAAE,QAAQ,EAAE;YACxE,OAAO,EAAE,wFAAwF;YACjG,WAAW,EAAE,QAAQ,CAAC,WAAW;SACjC,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU;YAAE,OAAO,MAAM,CAAC,KAAK,CAAC;QACpD,MAAM,IAAI,GAAG,uBAAuB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnD,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;QACzD,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,iDAAiD,EAAE,CAAC,CAAC;QACrG,OAAO,MAAM,yBAAyB,CAAC,IAAI,EAAE,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5E,CAAC;YAAS,CAAC;QACV,QAAQ,CAAC,KAAK,EAAE,CAAC;IAClB,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAc;IACzC,IAAI,EAAE,kBAAkB;IACxB,kBAAkB,EAAE,IAAI;IACxB,UAAU,EAAE,yBAAyB;IACrC,KAAK,EAAE,eAAe;IACtB,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO;QAChC,OAAO,UAAU,CAAC;IACnB,CAAC;IACD,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenRouter OAuth PKCE flow.\n *\n * OpenRouter exchanges an authorization code for a permanent, user-controlled\n * API key rather than an expiring access/refresh token pair. The callback is\n * handled by a one-shot loopback server on an ephemeral port, raced against a\n * manual prompt so remote/headless sessions can paste the redirect URL when\n * the browser cannot reach the loopback server.\n *\n * NOTE: This module uses node:http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst AUTHORIZE_URL = \"https://openrouter.ai/auth\";\nconst TOKEN_URL = \"https://openrouter.ai/api/v1/auth/keys\";\nconst LOGIN_TIMEOUT_MS = 5 * 60 * 1000;\nconst TOKEN_EXCHANGE_TIMEOUT_MS = 30_000;\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype JsonObject = Record<string, unknown>;\n\nfunction parseAuthorizationInput(input: string): string | undefined {\n\tconst value = input.trim();\n\tif (!value) return undefined;\n\n\ttry {\n\t\treturn new URL(value).searchParams.get(\"code\") ?? undefined;\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\treturn new URLSearchParams(value).get(\"code\") ?? undefined;\n\t}\n\n\treturn value;\n}\n\nfunction errorDetail(body: JsonObject): string | undefined {\n\tif (typeof body.error_description === \"string\") return body.error_description;\n\tif (typeof body.message === \"string\") return body.message;\n\tif (typeof body.error === \"string\") return body.error;\n\tif (body.error && typeof body.error === \"object\" && !Array.isArray(body.error)) {\n\t\tconst message = (body.error as JsonObject).message;\n\t\tif (typeof message === \"string\") return message;\n\t}\n\treturn undefined;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\tconst controller = new AbortController();\n\tconst onAbort = () => controller.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\tconst timeout = setTimeout(\n\t\t() => controller.abort(new Error(\"OpenRouter OAuth token exchange timed out\")),\n\t\tTOKEN_EXCHANGE_TIMEOUT_MS,\n\t);\n\n\tlet response: Response;\n\tlet body: JsonObject = {};\n\ttry {\n\t\tresponse = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: \"S256\" }),\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\ttry {\n\t\t\tconst parsed = (await response.json()) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) body = parsed as JsonObject;\n\t\t} catch {\n\t\t\tif (response.ok) throw new Error(\"OpenRouter OAuth returned invalid JSON\");\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\t\tif (controller.signal.aborted) throw new Error(\"OpenRouter OAuth token exchange timed out\");\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n\n\tif (!response.ok) {\n\t\tconst detail = errorDetail(body);\n\t\tthrow new Error(`OpenRouter OAuth key exchange failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n\t}\n\n\tif (typeof body.key !== \"string\" || body.key.length === 0) {\n\t\tthrow new Error('OpenRouter OAuth response carries no \"key\"');\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: body.key,\n\t\trefresh: \"\",\n\t\texpires: Number.MAX_SAFE_INTEGER,\n\t};\n}\n\nasync function loginOpenRouter(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\t// OpenRouter sends no state. The random path guards against stray callbacks.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenRouter\",\n\t\thost: getCallbackHost(),\n\t\tport: 0,\n\t\tpath: `/oauth/callback/${crypto.randomUUID()}`,\n\t\tcomplete: (code) => exchangeAuthorizationCode(code, verifier, interaction.signal),\n\t\tsignal: interaction.signal,\n\t\ttimeoutMs: LOGIN_TIMEOUT_MS,\n\t});\n\n\ttry {\n\t\tconst authorizeUrl = new URL(AUTHORIZE_URL);\n\t\tauthorizeUrl.search = new URLSearchParams({\n\t\t\tcallback_url: callback.redirectUri,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t}).toString();\n\n\t\tinteraction.notify({\n\t\t\ttype: \"progress\",\n\t\t\tmessage: `Listening for OpenRouter OAuth callback on ${callback.redirectUri}`,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: authorizeUrl.toString(),\n\t\t\tinstructions:\n\t\t\t\t\"Complete sign-in in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete sign-in in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: callback.redirectUri,\n\t\t});\n\t\tif (result.type === \"callback\") return result.value;\n\t\tconst code = parseAuthorizationInput(result.input);\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for an API key...\" });\n\t\treturn await exchangeAuthorizationCode(code, verifier, interaction.signal);\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nexport const openRouterOAuth: OAuthAuth = {\n\tname: \"OpenRouter OAuth\",\n\tusesCallbackServer: true,\n\tloginLabel: \"Sign in with OpenRouter\",\n\tlogin: loginOpenRouter,\n\tasync refresh(credential, _signal) {\n\t\treturn credential;\n\t},\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -211,6 +211,7 @@ export interface OAuthAuth {
211
211
  isSubscription?: boolean;
212
212
  /** Selector label for the OAuth login option, e.g. "Sign in with SuperGrok or X Premium". */
213
213
  loginLabel?: string;
214
+ usesCallbackServer?: boolean;
214
215
  login(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;
215
216
  /**
216
217
  * Exchange the refresh token. Network call; throws on failure
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,WAAW,CAAC;CAClB;AAED,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,yCAAyC;AACzC,MAAM,WAAW,eAAgB,SAAQ,gBAAgB;IACxD,IAAI,EAAE,OAAO,CAAC;CACd;AAED,gFAAgF;AAChF,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAE5D,qEAAqE;AACrE,MAAM,WAAW,cAAc;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;CACzB;AAED,uEAAuE;AACvE,MAAM,WAAW,oBAAoB;IACpC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,eAAe;IAC/B;;;OAGG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;IA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C,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9F;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAEpF;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tusesCallbackServer?: boolean;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAcA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAuD7D,wBAAgB,iBAAiB,IAAI,QAAQ,CAAC,oBAAoB,CAAC,CAgBlE"}
1
+ {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAcA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAuD7D,wBAAgB,iBAAiB,IAAI,QAAQ,CAAC,oBAAoB,CAAC,CAiBlE"}
@@ -63,6 +63,7 @@ export function anthropicProvider() {
63
63
  apiKey: anthropicApiKeyAuth(),
64
64
  oauth: lazyOAuth({
65
65
  name: "Anthropic (Claude Pro/Max)",
66
+ usesCallbackServer: true,
66
67
  isSubscription: true,
67
68
  load: loadAnthropicOAuth,
68
69
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EACN,qBAAqB,EACrB,wBAAwB,EACxB,gCAAgC,EAChC,iCAAiC,EACjC,yBAAyB,EACzB,6BAA6B,EAC7B,gCAAgC,EAChC,0BAA0B,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAiB,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,SA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AC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadAnthropicOAuth } from \"../auth/oauth/load.ts\";\nimport type { ApiKeyAuth } from \"../auth/types.ts\";\nimport {\n\tANTHROPIC_API_KEY_ENV,\n\tANTHROPIC_AUTH_TOKEN_ENV,\n\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\tANTHROPIC_OAUTH_TOKEN_ENV,\n\tANTHROPIC_ORGANIZATION_ID_ENV,\n\tANTHROPIC_SERVICE_ACCOUNT_ID_ENV,\n\tANTHROPIC_WORKSPACE_ID_ENV,\n} from \"../env-api-keys.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport type { ProviderEnv } from \"../types.ts\";\nimport { ANTHROPIC_MODELS } from \"./anthropic.models.ts\";\n\nfunction anthropicApiKeyAuth(): ApiKeyAuth {\n\treturn {\n\t\tname: \"Anthropic API key\",\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: \"Enter Anthropic API key\" });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\n\t\t\tconst authToken = await ctx.env(ANTHROPIC_AUTH_TOKEN_ENV);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (authToken) {\n\t\t\t\treturn {\n\t\t\t\t\tauth: { headers: { Authorization: `Bearer ${authToken}` } },\n\t\t\t\t\tsource: ANTHROPIC_AUTH_TOKEN_ENV,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const envVar of [ANTHROPIC_OAUTH_TOKEN_ENV, ANTHROPIC_API_KEY_ENV]) {\n\t\t\t\tconst apiKey = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (apiKey) return { auth: { apiKey }, source: envVar };\n\t\t\t}\n\n\t\t\tconst federation: ProviderEnv = {};\n\t\t\tfor (const envVar of [\n\t\t\t\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\t\t\t\tANTHROPIC_ORGANIZATION_ID_ENV,\n\t\t\t\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\t\t\t]) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (!value) return undefined;\n\t\t\t\tfederation[envVar] = value;\n\t\t\t}\n\t\t\tfor (const envVar of [ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, ANTHROPIC_WORKSPACE_ID_ENV]) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) federation[envVar] = value;\n\t\t\t}\n\t\t\treturn { auth: {}, env: federation, source: \"workload identity federation\" };\n\t\t},\n\t};\n}\n\nexport function anthropicProvider(): Provider<\"anthropic-messages\"> {\n\treturn createProvider({\n\t\tid: \"anthropic\",\n\t\tname: \"Anthropic\",\n\t\tbaseUrl: \"https://api.anthropic.com\",\n\t\tauth: {\n\t\t\tapiKey: anthropicApiKeyAuth(),\n\t\t\toauth: lazyOAuth({\n\t\t\t\tname: \"Anthropic (Claude Pro/Max)\",\n\t\t\t\tisSubscription: true,\n\t\t\t\tload: loadAnthropicOAuth,\n\t\t\t}),\n\t\t},\n\t\tmodels: Object.values(ANTHROPIC_MODELS),\n\t\tapi: anthropicMessagesApi(),\n\t});\n}\n"]}
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,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O,cAAc,CAAC;QACrB,EAAE,EAAE,WAAW;QACf,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,2BAA2B;QACpC,IAAI,EAAE;YACL,MAAM,EAAE,mBAAmB,EAAE;YAC7B,KAAK,EAAE,SAAS,CAAC;gBAChB,IAAI,EAAE,4BAA4B;gBAClC,kBAAkB,EAAE,IAAI;gBACxB,cAAc,EAAE,IAAI;gBACpB,IAAI,EAAE,kBAAkB;aACxB,CAAC;SACF;QACD,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC;QACvC,GAAG,EAAE,oBAAoB,EAAE;KAC3B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { anthropicMessagesApi } from \"../api/anthropic-messages.lazy.ts\";\nimport { lazyOAuth } from \"../auth/helpers.ts\";\nimport { loadAnthropicOAuth } from \"../auth/oauth/load.ts\";\nimport type { ApiKeyAuth } from \"../auth/types.ts\";\nimport {\n\tANTHROPIC_API_KEY_ENV,\n\tANTHROPIC_AUTH_TOKEN_ENV,\n\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\tANTHROPIC_OAUTH_TOKEN_ENV,\n\tANTHROPIC_ORGANIZATION_ID_ENV,\n\tANTHROPIC_SERVICE_ACCOUNT_ID_ENV,\n\tANTHROPIC_WORKSPACE_ID_ENV,\n} from \"../env-api-keys.ts\";\nimport { createProvider, type Provider } from \"../models.ts\";\nimport type { ProviderEnv } from \"../types.ts\";\nimport { ANTHROPIC_MODELS } from \"./anthropic.models.ts\";\n\nfunction anthropicApiKeyAuth(): ApiKeyAuth {\n\treturn {\n\t\tname: \"Anthropic API key\",\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: \"Enter Anthropic API key\" });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\n\t\t\tconst authToken = await ctx.env(ANTHROPIC_AUTH_TOKEN_ENV);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (authToken) {\n\t\t\t\treturn {\n\t\t\t\t\tauth: { headers: { Authorization: `Bearer ${authToken}` } },\n\t\t\t\t\tsource: ANTHROPIC_AUTH_TOKEN_ENV,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const envVar of [ANTHROPIC_OAUTH_TOKEN_ENV, ANTHROPIC_API_KEY_ENV]) {\n\t\t\t\tconst apiKey = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (apiKey) return { auth: { apiKey }, source: envVar };\n\t\t\t}\n\n\t\t\tconst federation: ProviderEnv = {};\n\t\t\tfor (const envVar of [\n\t\t\t\tANTHROPIC_FEDERATION_RULE_ID_ENV,\n\t\t\t\tANTHROPIC_ORGANIZATION_ID_ENV,\n\t\t\t\tANTHROPIC_IDENTITY_TOKEN_FILE_ENV,\n\t\t\t]) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (!value) return undefined;\n\t\t\t\tfederation[envVar] = value;\n\t\t\t}\n\t\t\tfor (const envVar of [ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, ANTHROPIC_WORKSPACE_ID_ENV]) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) federation[envVar] = value;\n\t\t\t}\n\t\t\treturn { auth: {}, env: federation, source: \"workload identity federation\" };\n\t\t},\n\t};\n}\n\nexport function anthropicProvider(): Provider<\"anthropic-messages\"> {\n\treturn createProvider({\n\t\tid: \"anthropic\",\n\t\tname: \"Anthropic\",\n\t\tbaseUrl: \"https://api.anthropic.com\",\n\t\tauth: {\n\t\t\tapiKey: anthropicApiKeyAuth(),\n\t\t\toauth: lazyOAuth({\n\t\t\t\tname: \"Anthropic (Claude Pro/Max)\",\n\t\t\t\tusesCallbackServer: true,\n\t\t\t\tisSubscription: true,\n\t\t\t\tload: loadAnthropicOAuth,\n\t\t\t}),\n\t\t},\n\t\tmodels: Object.values(ANTHROPIC_MODELS),\n\t\tapi: anthropicMessagesApi(),\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"schemaVersion":6,"generatedAt":"2026-10-01T15:22:35.819Z","structureHash":"013f6e15be3a5cc2ce1033d8612d08eeeff85f84bfd529371b11882af9e00b39","files":{"amazon-bedrock.json":"d1e91cffcaa338ce0574ecfae1a52271c4c4944b3e8e7581c5d7bc4154a396bb","ant-ling.json":"628feab3ef6c7d80ce96f75999804e1d9f05fec3851e5302e30fff3b69db90f6","anthropic.json":"c436c0f1f984e0a04f9d472533c20ce38c8da101d23484d6d7fe7892cdaa6830","azure-openai-responses.json":"bddff8380252746bbf6ee9901d6299e00ec0cc38facb6013b46b43c6ef231fdd","baseten.json":"b04d1423d6958bec857ffccc36726f091ec1a8f3a09cf0836b64cc94b0ee697d","cerebras.json":"3eccb58c5de3d0dc7ba49dc6e477ba29f00cb3150ce0a35cc90d59e6b5ab368e","cloudflare-ai-gateway.json":"5f9dbc3e5f4ef2ea7aa659f3fa28d77b5127e309305906bae47b25638931ba73","cloudflare-workers-ai.json":"b9f76cc83756a05920a8a7046c515919a1de918331b860a211f309bb716c4bb0","deepseek.json":"10a296fb3e898f7715c80890c8af0af4f5fd58f22dbcd6612fdc5d762157ccdc","fireworks.json":"d6144ba451bd7a0617669527bec1898f97a633f7d7ea5035d8e03234550340c0","github-copilot.json":"2362c7f129b6fca87ac45e06463ddb0f080477f820fd4eba55c150b0aeb99cba","google-vertex.json":"40090c680538bc867f2624d986a449f361be4dfa6ba96d7a27402050f036e009","google.json":"c0f5a633e5e5a5044432db3e537f4bc674d4de18df09325c6349547fcc13cabe","groq.json":"910952ad9dad07856983459d63fce0148dba1203edd7b10d801a77c5824f3405","huggingface.json":"1b8604bd31a5e05fe43a40ec1ec6dfc1a51a28b0b020151ef057fab43f57c923","kimi-coding.json":"582250b920454d98940da3e7e99d30b807edbea28f2eb8ac15f658d2ef41e8fc","meta.json":"0c7e9a370a7005c5a89dc94f0f93bc67b8935c3f802de324f11af6ff56fff429","minimax-cn.json":"f962c20ee6a6a342820f778e9dc363a18a524bf11998f6e2c57f2989915d62e5","minimax.json":"17a432f80d0ea6dd26eade80a4314250d3a855678601728a5f70dd8fa0d21dd2","mistral.json":"10f33bff9adf1248f7e6848e5890c265399f1f94e5b42cfdc28c109d547af98d","moonshotai-cn.json":"79c9585dc84ee525ebaebbc78b3c55f3d369ec884d4f943488f1e0b14e3587f5","moonshotai.json":"1da2c4e34f22aef17a07c974d85bdee8e1b68b6dc712e3769c935b3f1e7dadca","nvidia.json":"3b4e7b799bf3eaacd1af0491eef77fe33147ea7f72a3a9fa54d77af0e7eacf4c","openai-codex.json":"0c6c33c094d3175641a64a13215aa3b8c229964bb2c896e04cac1e2d2edf4a63","openai.json":"31e704f9e0ce46d0c2265eacd51a8d80e64ac52d5f3ca9679880fc0e0d79e057","opencode-go.json":"d05b3eb87b81c6e5a94801484e668e660fe60c68f06a972b716d581c3bbd7c25","opencode.json":"7996b45788b8c3892d474194661a70dc63a4f59470ea50b00cbd902859a262b5","openrouter.json":"35c8352b26532de10ee1b312cf998f00bc5d2454a689dd5c16335d631cad1a67","qwen-token-plan-cn.json":"2469a4091c474ec3db0a49a9962d8d2726c074ad9065b96bc4e0c87861c4c6c5","qwen-token-plan-individual.json":"0fb7cf64faf39d1a3b0a884210a86c87084b805eda15644f5f39293287b959dd","qwen-token-plan.json":"eff10620cb577142de4ec02698d5961a71fda2fe4f6ae7ea9432bad9d6844176","radius.json":"d9158329af6688b83afb5bdf3916dc91115af2a85f97bfffa72449a29450a52f","together.json":"94ec3839972061405885d64f5fdbde48eb1f29a159be5e607e9770befd54e28e","typesafe.json":"a4429a2f696d5cc5273969af61a7310bda07d6bdcd27bf9ac9c76c534cc43716","vercel-ai-gateway.json":"1790cf122b681d418c01f1f4c6a6f0f9ad741502c032727b31dad43c84f96e7d","xai.json":"879c49b78b663a52a220ac4ee013e726b10c4f50aaa03bc58ee53a4b54c76928","xiaomi-token-plan-ams.json":"ca65178f4525d9705bc8d085ed136cecbe149c4080e857ea6a64ae643d2ac00a","xiaomi-token-plan-cn.json":"b065326926681c2262084e59c1c19ebdaf146c07107b5242c76b456becf74db0","xiaomi-token-plan-sgp.json":"92c3d6d707f81fd9cd2b6d1fb57dc431d90ba51e10fe49d97bc8806035c23492","xiaomi.json":"b81d01a374f7b558728c78d81f4168efa9c8996e6e2b5618409a8094b083c759","zai-coding-cn.json":"ee5ee705fb6e413a6088db5e3616c27fce802a8ece6c355f1db35490d787f610","zai.json":"58e6642fdfb736f0b9a4a277c760c536a3cea66a030abbfb2615f7b2851d5c6f"}}
1
+ {"schemaVersion":6,"generatedAt":"2026-10-02T07:56:29.323Z","structureHash":"e6db10109d3768f68ea5ceb49124a9a095c55a1d288aa7cea19e98e2a46a871b","files":{"amazon-bedrock.json":"d1e91cffcaa338ce0574ecfae1a52271c4c4944b3e8e7581c5d7bc4154a396bb","ant-ling.json":"628feab3ef6c7d80ce96f75999804e1d9f05fec3851e5302e30fff3b69db90f6","anthropic.json":"c436c0f1f984e0a04f9d472533c20ce38c8da101d23484d6d7fe7892cdaa6830","azure-openai-responses.json":"bddff8380252746bbf6ee9901d6299e00ec0cc38facb6013b46b43c6ef231fdd","baseten.json":"b04d1423d6958bec857ffccc36726f091ec1a8f3a09cf0836b64cc94b0ee697d","cerebras.json":"3eccb58c5de3d0dc7ba49dc6e477ba29f00cb3150ce0a35cc90d59e6b5ab368e","cloudflare-ai-gateway.json":"5f9dbc3e5f4ef2ea7aa659f3fa28d77b5127e309305906bae47b25638931ba73","cloudflare-workers-ai.json":"b9f76cc83756a05920a8a7046c515919a1de918331b860a211f309bb716c4bb0","deepseek.json":"10a296fb3e898f7715c80890c8af0af4f5fd58f22dbcd6612fdc5d762157ccdc","fireworks.json":"8db3c11f65a5d76260d5040a5dc5a9ef0f35b92de8505a30907c2355c2837b36","github-copilot.json":"2362c7f129b6fca87ac45e06463ddb0f080477f820fd4eba55c150b0aeb99cba","google-vertex.json":"40090c680538bc867f2624d986a449f361be4dfa6ba96d7a27402050f036e009","google.json":"c0f5a633e5e5a5044432db3e537f4bc674d4de18df09325c6349547fcc13cabe","groq.json":"910952ad9dad07856983459d63fce0148dba1203edd7b10d801a77c5824f3405","huggingface.json":"1b8604bd31a5e05fe43a40ec1ec6dfc1a51a28b0b020151ef057fab43f57c923","kimi-coding.json":"582250b920454d98940da3e7e99d30b807edbea28f2eb8ac15f658d2ef41e8fc","meta.json":"0c7e9a370a7005c5a89dc94f0f93bc67b8935c3f802de324f11af6ff56fff429","minimax-cn.json":"f962c20ee6a6a342820f778e9dc363a18a524bf11998f6e2c57f2989915d62e5","minimax.json":"17a432f80d0ea6dd26eade80a4314250d3a855678601728a5f70dd8fa0d21dd2","mistral.json":"10f33bff9adf1248f7e6848e5890c265399f1f94e5b42cfdc28c109d547af98d","moonshotai-cn.json":"79c9585dc84ee525ebaebbc78b3c55f3d369ec884d4f943488f1e0b14e3587f5","moonshotai.json":"1da2c4e34f22aef17a07c974d85bdee8e1b68b6dc712e3769c935b3f1e7dadca","nvidia.json":"a75e963dc81779e3eec01c051b12277c15ec37c5b94ab51ece9e9ccb3b16407c","openai-codex.json":"0c6c33c094d3175641a64a13215aa3b8c229964bb2c896e04cac1e2d2edf4a63","openai.json":"31e704f9e0ce46d0c2265eacd51a8d80e64ac52d5f3ca9679880fc0e0d79e057","opencode-go.json":"d05b3eb87b81c6e5a94801484e668e660fe60c68f06a972b716d581c3bbd7c25","opencode.json":"920238188bd2683e9bf616982d17c5ecb67fd61692a3064128af42ad2dc792b5","openrouter.json":"7291d89a23747f591d99334ce5d847010b3631057887ecaaba51a0ec40a9223d","qwen-token-plan-cn.json":"2469a4091c474ec3db0a49a9962d8d2726c074ad9065b96bc4e0c87861c4c6c5","qwen-token-plan-individual.json":"0fb7cf64faf39d1a3b0a884210a86c87084b805eda15644f5f39293287b959dd","qwen-token-plan.json":"eff10620cb577142de4ec02698d5961a71fda2fe4f6ae7ea9432bad9d6844176","radius.json":"d9158329af6688b83afb5bdf3916dc91115af2a85f97bfffa72449a29450a52f","together.json":"52293df62191c8e799ae3632f8ab1b3f52ee626aee0280677086627b32864bf7","typesafe.json":"a4429a2f696d5cc5273969af61a7310bda07d6bdcd27bf9ac9c76c534cc43716","vercel-ai-gateway.json":"ab93dd9bc260c85cb0082be8bd4a55021d6773f7a459a63a4b6491eeb69a988b","xai.json":"879c49b78b663a52a220ac4ee013e726b10c4f50aaa03bc58ee53a4b54c76928","xiaomi-token-plan-ams.json":"ca65178f4525d9705bc8d085ed136cecbe149c4080e857ea6a64ae643d2ac00a","xiaomi-token-plan-cn.json":"b065326926681c2262084e59c1c19ebdaf146c07107b5242c76b456becf74db0","xiaomi-token-plan-sgp.json":"92c3d6d707f81fd9cd2b6d1fb57dc431d90ba51e10fe49d97bc8806035c23492","xiaomi.json":"b81d01a374f7b558728c78d81f4168efa9c8996e6e2b5618409a8094b083c759","zai-coding-cn.json":"ee5ee705fb6e413a6088db5e3616c27fce802a8ece6c355f1db35490d787f610","zai.json":"58e6642fdfb736f0b9a4a277c760c536a3cea66a030abbfb2615f7b2851d5c6f"}}