@earendil-works/pi-ai 0.80.7 → 0.80.8

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 (189) hide show
  1. package/README.md +76 -22
  2. package/dist/api/lazy.d.ts.map +1 -1
  3. package/dist/api/lazy.js +9 -10
  4. package/dist/api/lazy.js.map +1 -1
  5. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  6. package/dist/api/openai-codex-responses.js +3 -2
  7. package/dist/api/openai-codex-responses.js.map +1 -1
  8. package/dist/api/openai-responses.d.ts.map +1 -1
  9. package/dist/api/openai-responses.js +2 -0
  10. package/dist/api/openai-responses.js.map +1 -1
  11. package/dist/auth/credential-store.d.ts +2 -1
  12. package/dist/auth/credential-store.d.ts.map +1 -1
  13. package/dist/auth/credential-store.js +3 -0
  14. package/dist/auth/credential-store.js.map +1 -1
  15. package/dist/auth/helpers.d.ts.map +1 -1
  16. package/dist/auth/helpers.js +3 -3
  17. package/dist/auth/helpers.js.map +1 -1
  18. package/dist/auth/oauth/anthropic.d.ts +9 -0
  19. package/dist/auth/oauth/anthropic.d.ts.map +1 -0
  20. package/dist/{utils → auth}/oauth/anthropic.js +51 -116
  21. package/dist/auth/oauth/anthropic.js.map +1 -0
  22. package/dist/auth/oauth/device-code.d.ts.map +1 -0
  23. package/dist/auth/oauth/device-code.js.map +1 -0
  24. package/dist/auth/oauth/github-copilot.d.ts +6 -0
  25. package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
  26. package/dist/{utils → auth}/oauth/github-copilot.js +18 -77
  27. package/dist/auth/oauth/github-copilot.js.map +1 -0
  28. package/dist/auth/oauth/load.d.ts +23 -0
  29. package/dist/auth/oauth/load.d.ts.map +1 -0
  30. package/dist/auth/oauth/load.js +49 -0
  31. package/dist/auth/oauth/load.js.map +1 -0
  32. package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
  33. package/dist/auth/oauth/oauth-page.js.map +1 -0
  34. package/dist/auth/oauth/openai-codex.d.ts +9 -0
  35. package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
  36. package/dist/{utils → auth}/oauth/openai-codex.js +61 -155
  37. package/dist/auth/oauth/openai-codex.js.map +1 -0
  38. package/dist/auth/oauth/pkce.d.ts.map +1 -0
  39. package/dist/auth/oauth/pkce.js.map +1 -0
  40. package/dist/auth/oauth/radius.d.ts +16 -0
  41. package/dist/auth/oauth/radius.d.ts.map +1 -0
  42. package/dist/{utils → auth}/oauth/radius.js +31 -128
  43. package/dist/auth/oauth/radius.js.map +1 -0
  44. package/dist/auth/oauth/xai.d.ts +6 -0
  45. package/dist/auth/oauth/xai.d.ts.map +1 -0
  46. package/dist/auth/oauth/xai.js +184 -0
  47. package/dist/auth/oauth/xai.js.map +1 -0
  48. package/dist/auth/resolve.d.ts +2 -4
  49. package/dist/auth/resolve.d.ts.map +1 -1
  50. package/dist/auth/resolve.js +9 -7
  51. package/dist/auth/resolve.js.map +1 -1
  52. package/dist/auth/types.d.ts +47 -10
  53. package/dist/auth/types.d.ts.map +1 -1
  54. package/dist/auth/types.js.map +1 -1
  55. package/dist/bun-oauth.d.ts +3 -0
  56. package/dist/bun-oauth.d.ts.map +1 -0
  57. package/dist/bun-oauth.js +17 -0
  58. package/dist/bun-oauth.js.map +1 -0
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +58 -76
  61. package/dist/cli.js.map +1 -1
  62. package/dist/compat/extension-oauth-types.d.ts +39 -0
  63. package/dist/compat/extension-oauth-types.d.ts.map +1 -0
  64. package/dist/compat/extension-oauth-types.js +2 -0
  65. package/dist/compat/extension-oauth-types.js.map +1 -0
  66. package/dist/compat.d.ts.map +1 -1
  67. package/dist/compat.js +20 -7
  68. package/dist/compat.js.map +1 -1
  69. package/dist/env-api-keys.d.ts.map +1 -1
  70. package/dist/env-api-keys.js +1 -1
  71. package/dist/env-api-keys.js.map +1 -1
  72. package/dist/images-models.d.ts +4 -2
  73. package/dist/images-models.d.ts.map +1 -1
  74. package/dist/images-models.js +5 -4
  75. package/dist/images-models.js.map +1 -1
  76. package/dist/index.d.ts +2 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +1 -0
  79. package/dist/index.js.map +1 -1
  80. package/dist/models-store.d.ts +25 -0
  81. package/dist/models-store.d.ts.map +1 -0
  82. package/dist/models-store.js +14 -0
  83. package/dist/models-store.js.map +1 -0
  84. package/dist/models.d.ts +66 -30
  85. package/dist/models.d.ts.map +1 -1
  86. package/dist/models.generated.d.ts +93 -4
  87. package/dist/models.generated.d.ts.map +1 -1
  88. package/dist/models.js +214 -29
  89. package/dist/models.js.map +1 -1
  90. package/dist/oauth.d.ts +2 -1
  91. package/dist/oauth.d.ts.map +1 -1
  92. package/dist/oauth.js +1 -1
  93. package/dist/oauth.js.map +1 -1
  94. package/dist/providers/all.d.ts +2 -1
  95. package/dist/providers/all.d.ts.map +1 -1
  96. package/dist/providers/all.js +3 -0
  97. package/dist/providers/all.js.map +1 -1
  98. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  99. package/dist/providers/amazon-bedrock.js +51 -10
  100. package/dist/providers/amazon-bedrock.js.map +1 -1
  101. package/dist/providers/anthropic.d.ts.map +1 -1
  102. package/dist/providers/anthropic.js +1 -1
  103. package/dist/providers/anthropic.js.map +1 -1
  104. package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
  105. package/dist/providers/cloudflare-ai-gateway.js +4 -3
  106. package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
  107. package/dist/providers/cloudflare-auth.d.ts.map +1 -1
  108. package/dist/providers/cloudflare-auth.js +13 -20
  109. package/dist/providers/cloudflare-auth.js.map +1 -1
  110. package/dist/providers/cloudflare-stream.d.ts +8 -0
  111. package/dist/providers/cloudflare-stream.d.ts.map +1 -0
  112. package/dist/providers/cloudflare-stream.js +21 -0
  113. package/dist/providers/cloudflare-stream.js.map +1 -0
  114. package/dist/providers/cloudflare-workers-ai.d.ts.map +1 -1
  115. package/dist/providers/cloudflare-workers-ai.js +2 -1
  116. package/dist/providers/cloudflare-workers-ai.js.map +1 -1
  117. package/dist/providers/github-copilot.d.ts.map +1 -1
  118. package/dist/providers/github-copilot.js +11 -1
  119. package/dist/providers/github-copilot.js.map +1 -1
  120. package/dist/providers/google-vertex.d.ts.map +1 -1
  121. package/dist/providers/google-vertex.js +56 -5
  122. package/dist/providers/google-vertex.js.map +1 -1
  123. package/dist/providers/kimi-coding.models.d.ts +20 -0
  124. package/dist/providers/kimi-coding.models.d.ts.map +1 -1
  125. package/dist/providers/kimi-coding.models.js +18 -0
  126. package/dist/providers/kimi-coding.models.js.map +1 -1
  127. package/dist/providers/openai-codex.d.ts.map +1 -1
  128. package/dist/providers/openai-codex.js +1 -1
  129. package/dist/providers/openai-codex.js.map +1 -1
  130. package/dist/providers/openrouter.models.d.ts.map +1 -1
  131. package/dist/providers/openrouter.models.js +135 -135
  132. package/dist/providers/openrouter.models.js.map +1 -1
  133. package/dist/providers/radius-config.d.ts +26 -0
  134. package/dist/providers/radius-config.d.ts.map +1 -0
  135. package/dist/providers/radius-config.js +59 -0
  136. package/dist/providers/radius-config.js.map +1 -0
  137. package/dist/providers/radius.d.ts +9 -0
  138. package/dist/providers/radius.d.ts.map +1 -0
  139. package/dist/providers/radius.js +54 -0
  140. package/dist/providers/radius.js.map +1 -0
  141. package/dist/providers/vercel-ai-gateway.models.d.ts +67 -0
  142. package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
  143. package/dist/providers/vercel-ai-gateway.models.js +57 -2
  144. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  145. package/dist/providers/xai.d.ts +1 -1
  146. package/dist/providers/xai.d.ts.map +1 -1
  147. package/dist/providers/xai.js +11 -3
  148. package/dist/providers/xai.js.map +1 -1
  149. package/dist/providers/xai.models.d.ts +6 -4
  150. package/dist/providers/xai.models.d.ts.map +1 -1
  151. package/dist/providers/xai.models.js +3 -2
  152. package/dist/providers/xai.models.js.map +1 -1
  153. package/package.json +6 -1
  154. package/dist/utils/oauth/anthropic.d.ts +0 -27
  155. package/dist/utils/oauth/anthropic.d.ts.map +0 -1
  156. package/dist/utils/oauth/anthropic.js.map +0 -1
  157. package/dist/utils/oauth/device-code.d.ts.map +0 -1
  158. package/dist/utils/oauth/device-code.js.map +0 -1
  159. package/dist/utils/oauth/github-copilot.d.ts +0 -32
  160. package/dist/utils/oauth/github-copilot.d.ts.map +0 -1
  161. package/dist/utils/oauth/github-copilot.js.map +0 -1
  162. package/dist/utils/oauth/index.d.ts +0 -59
  163. package/dist/utils/oauth/index.d.ts.map +0 -1
  164. package/dist/utils/oauth/index.js +0 -131
  165. package/dist/utils/oauth/index.js.map +0 -1
  166. package/dist/utils/oauth/load.d.ts +0 -5
  167. package/dist/utils/oauth/load.d.ts.map +0 -1
  168. package/dist/utils/oauth/load.js +0 -22
  169. package/dist/utils/oauth/load.js.map +0 -1
  170. package/dist/utils/oauth/oauth-page.d.ts.map +0 -1
  171. package/dist/utils/oauth/oauth-page.js.map +0 -1
  172. package/dist/utils/oauth/openai-codex.d.ts +0 -45
  173. package/dist/utils/oauth/openai-codex.d.ts.map +0 -1
  174. package/dist/utils/oauth/openai-codex.js.map +0 -1
  175. package/dist/utils/oauth/pkce.d.ts.map +0 -1
  176. package/dist/utils/oauth/pkce.js.map +0 -1
  177. package/dist/utils/oauth/radius.d.ts +0 -39
  178. package/dist/utils/oauth/radius.d.ts.map +0 -1
  179. package/dist/utils/oauth/radius.js.map +0 -1
  180. package/dist/utils/oauth/types.d.ts +0 -64
  181. package/dist/utils/oauth/types.d.ts.map +0 -1
  182. package/dist/utils/oauth/types.js +0 -2
  183. package/dist/utils/oauth/types.js.map +0 -1
  184. /package/dist/{utils → auth}/oauth/device-code.d.ts +0 -0
  185. /package/dist/{utils → auth}/oauth/device-code.js +0 -0
  186. /package/dist/{utils → auth}/oauth/oauth-page.d.ts +0 -0
  187. /package/dist/{utils → auth}/oauth/oauth-page.js +0 -0
  188. /package/dist/{utils → auth}/oauth/pkce.d.ts +0 -0
  189. /package/dist/{utils → auth}/oauth/pkce.js +0 -0
@@ -1,131 +0,0 @@
1
- /**
2
- * OAuth credential management for AI providers.
3
- *
4
- * This module handles login, token refresh, and credential storage
5
- * for OAuth-based providers:
6
- * - Anthropic (Claude Pro/Max)
7
- * - GitHub Copilot
8
- */
9
- // Anthropic
10
- export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
11
- export * from "./device-code.js";
12
- // GitHub Copilot
13
- export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
14
- // OpenAI Codex (ChatGPT OAuth)
15
- export { loginOpenAICodex, loginOpenAICodexDeviceCode, OPENAI_CODEX_BROWSER_LOGIN_METHOD, OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, openaiCodexOAuthProvider, refreshOpenAICodexToken, } from "./openai-codex.js";
16
- // Radius (pi-messages gateway)
17
- export { createRadiusOAuthProvider, DEFAULT_RADIUS_GATEWAY, } from "./radius.js";
18
- export * from "./types.js";
19
- // ============================================================================
20
- // Provider Registry
21
- // ============================================================================
22
- import { getProviderEnvValue } from "../provider-env.js";
23
- import { anthropicOAuthProvider } from "./anthropic.js";
24
- import { githubCopilotOAuthProvider } from "./github-copilot.js";
25
- import { openaiCodexOAuthProvider } from "./openai-codex.js";
26
- import { createRadiusOAuthProvider, DEFAULT_RADIUS_GATEWAY } from "./radius.js";
27
- const BUILT_IN_OAUTH_PROVIDERS = [
28
- anthropicOAuthProvider,
29
- githubCopilotOAuthProvider,
30
- openaiCodexOAuthProvider,
31
- createRadiusOAuthProvider({
32
- id: "radius",
33
- name: "Radius",
34
- gateway: getProviderEnvValue("PI_GATEWAY") || DEFAULT_RADIUS_GATEWAY,
35
- }),
36
- ];
37
- const oauthProviderRegistry = new Map(BUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]));
38
- /**
39
- * Get an OAuth provider by ID
40
- */
41
- export function getOAuthProvider(id) {
42
- return oauthProviderRegistry.get(id);
43
- }
44
- /**
45
- * Register a custom OAuth provider
46
- */
47
- export function registerOAuthProvider(provider) {
48
- oauthProviderRegistry.set(provider.id, provider);
49
- }
50
- /**
51
- * Unregister an OAuth provider.
52
- *
53
- * If the provider is built-in, restores the built-in implementation.
54
- * Custom providers are removed completely.
55
- */
56
- export function unregisterOAuthProvider(id) {
57
- const builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);
58
- if (builtInProvider) {
59
- oauthProviderRegistry.set(id, builtInProvider);
60
- return;
61
- }
62
- oauthProviderRegistry.delete(id);
63
- }
64
- /**
65
- * Reset OAuth providers to built-ins.
66
- */
67
- export function resetOAuthProviders() {
68
- oauthProviderRegistry.clear();
69
- for (const provider of BUILT_IN_OAUTH_PROVIDERS) {
70
- oauthProviderRegistry.set(provider.id, provider);
71
- }
72
- }
73
- /**
74
- * Get all registered OAuth providers
75
- */
76
- export function getOAuthProviders() {
77
- return Array.from(oauthProviderRegistry.values());
78
- }
79
- /**
80
- * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]
81
- */
82
- export function getOAuthProviderInfoList() {
83
- return getOAuthProviders().map((p) => ({
84
- id: p.id,
85
- name: p.name,
86
- available: true,
87
- }));
88
- }
89
- // ============================================================================
90
- // High-level API (uses provider registry)
91
- // ============================================================================
92
- /**
93
- * Refresh token for any OAuth provider.
94
- * @deprecated Use getOAuthProvider(id).refreshToken() instead
95
- */
96
- export async function refreshOAuthToken(providerId, credentials) {
97
- const provider = getOAuthProvider(providerId);
98
- if (!provider) {
99
- throw new Error(`Unknown OAuth provider: ${providerId}`);
100
- }
101
- return provider.refreshToken(credentials);
102
- }
103
- /**
104
- * Get API key for a provider from OAuth credentials.
105
- * Automatically refreshes expired tokens.
106
- *
107
- * @returns API key string and updated credentials, or null if no credentials
108
- * @throws Error if refresh fails
109
- */
110
- export async function getOAuthApiKey(providerId, credentials) {
111
- const provider = getOAuthProvider(providerId);
112
- if (!provider) {
113
- throw new Error(`Unknown OAuth provider: ${providerId}`);
114
- }
115
- let creds = credentials[providerId];
116
- if (!creds) {
117
- return null;
118
- }
119
- // Refresh if expired
120
- if (Date.now() >= creds.expires) {
121
- try {
122
- creds = await provider.refreshToken(creds);
123
- }
124
- catch (_error) {
125
- throw new Error(`Failed to refresh OAuth token for ${providerId}`);
126
- }
127
- }
128
- const apiKey = provider.getApiKey(creds);
129
- return { newCredentials: creds, apiKey };
130
- }
131
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY;AACZ,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC/F,cAAc,kBAAkB,CAAC;AACjC,iBAAiB;AACjB,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,yBAAyB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,+BAA+B;AAC/B,OAAO,EACN,gBAAgB,EAChB,0BAA0B,EAC1B,iCAAiC,EACjC,qCAAqC,EACrC,wBAAwB,EACxB,uBAAuB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,+BAA+B;AAC/B,OAAO,EACN,yBAAyB,EACzB,sBAAsB,GAKtB,MAAM,aAAa,CAAC;AACrB,cAAc,YAAY,CAAC;AAE3B,+EAA+E;AAC/E,oBAAoB;AACpB,+EAA+E;AAE/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,M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,EAAE,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QACjC,IAAI,CAAC;YACJ,KAAK,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAC5C,CAAC;QAAC,OAAO,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,qCAAqC,UAAU,EAAE,CAAC,CAAC;QACpE,CAAC;IACF,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAAA,CACzC","sourcesContent":["/**\n * OAuth credential management for AI providers.\n *\n * This module handles login, token refresh, and credential storage\n * for OAuth-based providers:\n * - Anthropic (Claude Pro/Max)\n * - GitHub Copilot\n */\n\n// Anthropic\nexport { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from \"./anthropic.ts\";\nexport * from \"./device-code.ts\";\n// GitHub Copilot\nexport {\n\tgetGitHubCopilotBaseUrl,\n\tgithubCopilotOAuthProvider,\n\tloginGitHubCopilot,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n} from \"./github-copilot.ts\";\n// OpenAI Codex (ChatGPT OAuth)\nexport {\n\tloginOpenAICodex,\n\tloginOpenAICodexDeviceCode,\n\tOPENAI_CODEX_BROWSER_LOGIN_METHOD,\n\tOPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD,\n\topenaiCodexOAuthProvider,\n\trefreshOpenAICodexToken,\n} from \"./openai-codex.ts\";\n\n// Radius (pi-messages gateway)\nexport {\n\tcreateRadiusOAuthProvider,\n\tDEFAULT_RADIUS_GATEWAY,\n\ttype RadiusGatewayConfig,\n\ttype RadiusGatewayModel,\n\ttype RadiusOAuthCredentials,\n\ttype RadiusOAuthProviderOptions,\n} from \"./radius.ts\";\nexport * from \"./types.ts\";\n\n// ============================================================================\n// Provider Registry\n// ============================================================================\n\nimport { getProviderEnvValue } from \"../provider-env.ts\";\nimport { anthropicOAuthProvider } from \"./anthropic.ts\";\nimport { githubCopilotOAuthProvider } from \"./github-copilot.ts\";\nimport { openaiCodexOAuthProvider } from \"./openai-codex.ts\";\nimport { createRadiusOAuthProvider, DEFAULT_RADIUS_GATEWAY } from \"./radius.ts\";\nimport type { OAuthCredentials, OAuthProviderId, OAuthProviderInfo, OAuthProviderInterface } from \"./types.ts\";\n\nconst BUILT_IN_OAUTH_PROVIDERS: OAuthProviderInterface[] = [\n\tanthropicOAuthProvider,\n\tgithubCopilotOAuthProvider,\n\topenaiCodexOAuthProvider,\n\tcreateRadiusOAuthProvider({\n\t\tid: \"radius\",\n\t\tname: \"Radius\",\n\t\tgateway: getProviderEnvValue(\"PI_GATEWAY\") || DEFAULT_RADIUS_GATEWAY,\n\t}),\n];\n\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>(\n\tBUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]),\n);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n\treturn oauthProviderRegistry.get(id);\n}\n\n/**\n * Register a custom OAuth provider\n */\nexport function registerOAuthProvider(provider: OAuthProviderInterface): void {\n\toauthProviderRegistry.set(provider.id, provider);\n}\n\n/**\n * Unregister an OAuth provider.\n *\n * If the provider is built-in, restores the built-in implementation.\n * Custom providers are removed completely.\n */\nexport function unregisterOAuthProvider(id: string): void {\n\tconst builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);\n\tif (builtInProvider) {\n\t\toauthProviderRegistry.set(id, builtInProvider);\n\t\treturn;\n\t}\n\toauthProviderRegistry.delete(id);\n}\n\n/**\n * Reset OAuth providers to built-ins.\n */\nexport function resetOAuthProviders(): void {\n\toauthProviderRegistry.clear();\n\tfor (const provider of BUILT_IN_OAUTH_PROVIDERS) {\n\t\toauthProviderRegistry.set(provider.id, provider);\n\t}\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n\treturn Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]\n */\nexport function getOAuthProviderInfoList(): OAuthProviderInfo[] {\n\treturn getOAuthProviders().map((p) => ({\n\t\tid: p.id,\n\t\tname: p.name,\n\t\tavailable: true,\n\t}));\n}\n\n// ============================================================================\n// High-level API (uses provider registry)\n// ============================================================================\n\n/**\n * Refresh token for any OAuth provider.\n * @deprecated Use getOAuthProvider(id).refreshToken() instead\n */\nexport async function refreshOAuthToken(\n\tproviderId: OAuthProviderId,\n\tcredentials: OAuthCredentials,\n): Promise<OAuthCredentials> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\treturn provider.refreshToken(credentials);\n}\n\n/**\n * Get API key for a provider from OAuth credentials.\n * Automatically refreshes expired tokens.\n *\n * @returns API key string and updated credentials, or null if no credentials\n * @throws Error if refresh fails\n */\nexport async function getOAuthApiKey(\n\tproviderId: OAuthProviderId,\n\tcredentials: Record<string, OAuthCredentials>,\n): Promise<{ newCredentials: OAuthCredentials; apiKey: string } | null> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\n\tlet creds = credentials[providerId];\n\tif (!creds) {\n\t\treturn null;\n\t}\n\n\t// Refresh if expired\n\tif (Date.now() >= creds.expires) {\n\t\ttry {\n\t\t\tcreds = await provider.refreshToken(creds);\n\t\t} catch (_error) {\n\t\t\tthrow new Error(`Failed to refresh OAuth token for ${providerId}`);\n\t\t}\n\t}\n\n\tconst apiKey = provider.getApiKey(creds);\n\treturn { newCredentials: creds, apiKey };\n}\n"]}
@@ -1,5 +0,0 @@
1
- import type { OAuthAuth } from "../../auth/types.ts";
2
- export declare const loadAnthropicOAuth: () => Promise<OAuthAuth>;
3
- export declare const loadOpenAICodexOAuth: () => Promise<OAuthAuth>;
4
- export declare const loadGitHubCopilotOAuth: () => Promise<OAuthAuth>;
5
- //# sourceMappingURL=load.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/load.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAarD,eAAO,MAAM,kBAAkB,0BAC+D,CAAC;AAE/F,eAAO,MAAM,oBAAoB,0BACoE,CAAC;AAEtG,eAAO,MAAM,sBAAsB,0BACwE,CAAC","sourcesContent":["import type { OAuthAuth } from \"../../auth/types.ts\";\n\n/**\n * Loads an OAuth flow module through a variable specifier so bundlers cannot\n * follow the import into Node-only flow code (`node:http` callback servers,\n * `node:crypto` PKCE). The `.ts`/`.js` rewrite keeps the trick working from\n * both source and built output.\n */\nconst importOAuthModule = (specifier: string): Promise<unknown> => {\n\tconst runtimeSpecifier = import.meta.url.endsWith(\".js\") ? specifier.replace(/\\.ts$/, \".js\") : specifier;\n\treturn import(runtimeSpecifier);\n};\n\nexport const loadAnthropicOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./anthropic.ts\")) as { anthropicOAuth: OAuthAuth }).anthropicOAuth;\n\nexport const loadOpenAICodexOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./openai-codex.ts\")) as { openaiCodexOAuth: OAuthAuth }).openaiCodexOAuth;\n\nexport const loadGitHubCopilotOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./github-copilot.ts\")) as { githubCopilotOAuth: OAuthAuth }).githubCopilotOAuth;\n"]}
@@ -1,22 +0,0 @@
1
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
- });
6
- }
7
- return path;
8
- };
9
- /**
10
- * Loads an OAuth flow module through a variable specifier so bundlers cannot
11
- * follow the import into Node-only flow code (`node:http` callback servers,
12
- * `node:crypto` PKCE). The `.ts`/`.js` rewrite keeps the trick working from
13
- * both source and built output.
14
- */
15
- const importOAuthModule = (specifier) => {
16
- const runtimeSpecifier = import.meta.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
17
- return import(__rewriteRelativeImportExtension(runtimeSpecifier));
18
- };
19
- export const loadAnthropicOAuth = async () => (await importOAuthModule("./anthropic.ts")).anthropicOAuth;
20
- export const loadOpenAICodexOAuth = async () => (await importOAuthModule("./openai-codex.ts")).openaiCodexOAuth;
21
- export const loadGitHubCopilotOAuth = async () => (await importOAuthModule("./github-copilot.ts")).githubCopilotOAuth;
22
- //# sourceMappingURL=load.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"load.js","sourceRoot":"","sources":["../../../src/utils/oauth/load.ts"],"names":[],"mappings":";;;;;;;;AAEA;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,CAAC,SAAiB,EAAoB,EAAE,CAAC;IAClE,MAAM,gBAAgB,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACzG,OAAO,MAAM,kCAAC,gBAAgB,EAAC,CAAC;AAAA,CAChC,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,IAAwB,EAAE,CAC/D,CAAC,MAAM,iBAAiB,CAAC,gBAAgB,CAAC,CAAmC,CAAC,cAAc,CAAC;AAE/F,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,IAAwB,EAAE,CACjE,CAAC,MAAM,iBAAiB,CAAC,mBAAmB,CAAC,CAAqC,CAAC,gBAAgB,CAAC;AAEtG,MAAM,CAAC,MAAM,sBAAsB,GAAG,KAAK,IAAwB,EAAE,CACnE,CAAC,MAAM,iBAAiB,CAAC,qBAAqB,CAAC,CAAuC,CAAC,kBAAkB,CAAC","sourcesContent":["import type { OAuthAuth } from \"../../auth/types.ts\";\n\n/**\n * Loads an OAuth flow module through a variable specifier so bundlers cannot\n * follow the import into Node-only flow code (`node:http` callback servers,\n * `node:crypto` PKCE). The `.ts`/`.js` rewrite keeps the trick working from\n * both source and built output.\n */\nconst importOAuthModule = (specifier: string): Promise<unknown> => {\n\tconst runtimeSpecifier = import.meta.url.endsWith(\".js\") ? specifier.replace(/\\.ts$/, \".js\") : specifier;\n\treturn import(runtimeSpecifier);\n};\n\nexport const loadAnthropicOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./anthropic.ts\")) as { anthropicOAuth: OAuthAuth }).anthropicOAuth;\n\nexport const loadOpenAICodexOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./openai-codex.ts\")) as { openaiCodexOAuth: OAuthAuth }).openaiCodexOAuth;\n\nexport const loadGitHubCopilotOAuth = async (): Promise<OAuthAuth> =>\n\t((await importOAuthModule(\"./github-copilot.ts\")) as { githubCopilotOAuth: OAuthAuth }).githubCopilotOAuth;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"oauth-page.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/oauth-page.ts"],"names":[],"mappings":"AA6FA,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAMxD;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAOxE","sourcesContent":["const LOGO_SVG = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 800 800\" aria-hidden=\"true\"><path fill=\"#fff\" fill-rule=\"evenodd\" d=\"M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z\"/><path fill=\"#fff\" d=\"M517.36 400 H634.72 V634.72 H517.36 Z\"/></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 +0,0 @@
1
- {"version":3,"file":"oauth-page.js","sourceRoot":"","sources":["../../../src/utils/oauth/oauth-page.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,uSAAuS,CAAC;AAEzT,SAAS,UAAU,CAAC,KAAa,EAAU;IAC1C,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;AAAA,CAC3B;AAED,SAAS,UAAU,CAAC,OAA8E,EAAU;IAC3G,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;AAAA,CACR;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAU;IACzD,OAAO,UAAU,CAAC;QACjB,KAAK,EAAE,2BAA2B;QAClC,OAAO,EAAE,2BAA2B;QACpC,OAAO;KACP,CAAC,CAAC;AAAA,CACH;AAED,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,OAAgB,EAAU;IACzE,OAAO,UAAU,CAAC;QACjB,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,uBAAuB;QAChC,OAAO;QACP,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["const LOGO_SVG = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 800 800\" aria-hidden=\"true\"><path fill=\"#fff\" fill-rule=\"evenodd\" d=\"M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z\"/><path fill=\"#fff\" d=\"M517.36 400 H634.72 V634.72 H517.36 Z\"/></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,45 +0,0 @@
1
- /**
2
- * OpenAI Codex (ChatGPT OAuth) flow
3
- *
4
- * NOTE: This module uses Node.js crypto and http for the OAuth callback.
5
- * It is only intended for CLI use, not browser environments.
6
- */
7
- import type { OAuthAuth } from "../../auth/types.ts";
8
- import type { OAuthCredentials, OAuthDeviceCodeInfo, OAuthPrompt, OAuthProviderInterface } from "./types.ts";
9
- export declare const OPENAI_CODEX_BROWSER_LOGIN_METHOD = "browser";
10
- export declare const OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = "device_code";
11
- /**
12
- * Login with OpenAI Codex OAuth using the Codex device-code flow.
13
- */
14
- export declare function loginOpenAICodexDeviceCode(options: {
15
- onDeviceCode: (info: OAuthDeviceCodeInfo) => void;
16
- signal?: AbortSignal;
17
- }): Promise<OAuthCredentials>;
18
- /**
19
- * Login with OpenAI Codex OAuth
20
- *
21
- * @param options.onAuth - Called with URL and instructions when auth starts
22
- * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
23
- * @param options.onProgress - Optional progress messages
24
- * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
25
- * Races with browser callback - whichever completes first wins.
26
- * Useful for showing paste input immediately alongside browser flow.
27
- * @param options.originator - OAuth originator parameter (defaults to "pi")
28
- */
29
- export declare function loginOpenAICodex(options: {
30
- onAuth: (info: {
31
- url: string;
32
- instructions?: string;
33
- }) => void;
34
- onPrompt: (prompt: OAuthPrompt) => Promise<string>;
35
- onProgress?: (message: string) => void;
36
- onManualCodeInput?: () => Promise<string>;
37
- originator?: string;
38
- }): Promise<OAuthCredentials>;
39
- /**
40
- * Refresh OpenAI Codex OAuth token
41
- */
42
- export declare function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials>;
43
- export declare const openaiCodexOAuth: OAuthAuth;
44
- export declare const openaiCodexOAuthProvider: OAuthProviderInterface;
45
- //# sourceMappingURL=openai-codex.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAcH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAKrD,OAAO,KAAK,EACX,gBAAgB,EAChB,mBAAmB,EAEnB,WAAW,EACX,sBAAsB,EACtB,MAAM,YAAY,CAAC;AAYpB,eAAO,MAAM,iCAAiC,YAAY,CAAC;AAC3D,eAAO,MAAM,qCAAqC,gBAAgB,CAAC;AAoYnE;;GAEG;AACH,wBAAsB,0BAA0B,CAAC,OAAO,EAAE;IACzD,YAAY,EAAE,CAAC,IAAI,EAAE,mBAAmB,KAAK,IAAI,CAAC;IAClD,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAe5B;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE;IAC/C,MAAM,EAAE,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/D,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACnD,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAoF5B;AAED;;GAEG;AACH,wBAAsB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAE7F;AAED,eAAO,MAAM,gBAAgB,EAAE,SAsD9B,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,sBA2CtC,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http for the OAuth callback.\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;\nlet _http: typeof import(\"node:http\") | 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\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { OAuthAuth } from \"../../auth/types.ts\";\nimport { getProviderEnvValue } from \"../provider-env.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport type {\n\tOAuthCredentials,\n\tOAuthDeviceCodeInfo,\n\tOAuthLoginCallbacks,\n\tOAuthPrompt,\n\tOAuthProviderInterface,\n} from \"./types.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;\nexport const OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nexport const 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 = REDIRECT_URI,\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): 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});\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\ntype OAuthServerInfo = {\n\tclose: () => void;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string } | null>;\n};\n\nfunction startLocalOAuthServer(state: string): Promise<OAuthServerInfo> {\n\tif (!_http) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settleWait: ((value: { code: string } | null) => void) | undefined;\n\tconst waitForCodePromise = new Promise<{ code: string } | null>((resolve) => {\n\t\tlet settled = false;\n\t\tsettleWait = (value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tresolve(value);\n\t\t};\n\t});\n\n\tconst server = _http.createServer((req, res) => {\n\t\ttry {\n\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\tif (url.pathname !== \"/auth/callback\") {\n\t\t\t\tres.statusCode = 404;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (url.searchParams.get(\"state\") !== state) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\tif (!code) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(oauthSuccessHtml(\"OpenAI authentication completed. You can close this window.\"));\n\t\t\tsettleWait?.({ code });\n\t\t} catch {\n\t\t\tres.statusCode = 500;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(oauthErrorHtml(\"Internal error while processing OAuth callback.\"));\n\t\t}\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(1455, getCallbackHost(), () => {\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => server.close(),\n\t\t\t\t\tcancelWait: () => {\n\t\t\t\t\t\tsettleWait?.(null);\n\t\t\t\t\t},\n\t\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on(\"error\", (_err: NodeJS.ErrnoException) => {\n\t\t\t\tsettleWait?.(null);\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// ignore\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcancelWait: () => {},\n\t\t\t\t\twaitForCode: async () => null,\n\t\t\t\t});\n\t\t\t});\n\t});\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): OAuthCredentials {\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\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<OAuthCredentials> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\n/**\n * Login with OpenAI Codex OAuth using the Codex device-code flow.\n */\nexport async function loginOpenAICodexDeviceCode(options: {\n\tonDeviceCode: (info: OAuthDeviceCodeInfo) => void;\n\tsignal?: AbortSignal;\n}): Promise<OAuthCredentials> {\n\tconst device = await startOpenAICodexDeviceAuth(options.signal);\n\toptions.onDeviceCode({\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, options.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\toptions.signal,\n\t);\n}\n\n/**\n * Login with OpenAI Codex OAuth\n *\n * @param options.onAuth - Called with URL and instructions when auth starts\n * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)\n * @param options.onProgress - Optional progress messages\n * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.\n * Races with browser callback - whichever completes first wins.\n * Useful for showing paste input immediately alongside browser flow.\n * @param options.originator - OAuth originator parameter (defaults to \"pi\")\n */\nexport async function loginOpenAICodex(options: {\n\tonAuth: (info: { url: string; instructions?: string }) => void;\n\tonPrompt: (prompt: OAuthPrompt) => Promise<string>;\n\tonProgress?: (message: string) => void;\n\tonManualCodeInput?: () => Promise<string>;\n\toriginator?: string;\n}): Promise<OAuthCredentials> {\n\tconst { verifier, state, url } = await createAuthorizationFlow(options.originator);\n\tconst server = await startLocalOAuthServer(state);\n\n\toptions.onAuth({ url, instructions: \"A browser window should open. Complete login to finish.\" });\n\n\tlet code: string | undefined;\n\ttry {\n\t\tif (options.onManualCodeInput) {\n\t\t\t// Race between browser callback and manual input\n\t\t\tlet manualCode: string | undefined;\n\t\t\tlet manualError: Error | undefined;\n\t\t\tconst manualPromise = options\n\t\t\t\t.onManualCodeInput()\n\t\t\t\t.then((input) => {\n\t\t\t\t\tmanualCode = input;\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tmanualError = err instanceof Error ? err : new Error(String(err));\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t});\n\n\t\t\tconst result = await server.waitForCode();\n\n\t\t\t// If manual input was cancelled, throw that error\n\t\t\tif (manualError) {\n\t\t\t\tthrow manualError;\n\t\t\t}\n\n\t\t\tif (result?.code) {\n\t\t\t\t// Browser callback won\n\t\t\t\tcode = result.code;\n\t\t\t} else if (manualCode) {\n\t\t\t\t// Manual input won (or callback timed out and user had entered code)\n\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t}\n\t\t\t\tcode = parsed.code;\n\t\t\t}\n\n\t\t\t// If still no code, wait for manual promise to complete and try that\n\t\t\tif (!code) {\n\t\t\t\tawait manualPromise;\n\t\t\t\tif (manualError) {\n\t\t\t\t\tthrow manualError;\n\t\t\t\t}\n\t\t\t\tif (manualCode) {\n\t\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t\t}\n\t\t\t\t\tcode = parsed.code;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Original flow: wait for callback, then prompt if needed\n\t\t\tconst result = await server.waitForCode();\n\t\t\tif (result?.code) {\n\t\t\t\tcode = result.code;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to onPrompt if still no code\n\t\tif (!code) {\n\t\t\tconst input = await options.onPrompt({\n\t\t\t\tmessage: \"Paste the authorization code (or full redirect URL):\",\n\t\t\t});\n\t\t\tconst parsed = parseAuthorizationInput(input);\n\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t}\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) {\n\t\t\tthrow new Error(\"Missing authorization code\");\n\t\t}\n\n\t\treturn exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI);\n\t} finally {\n\t\tserver.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials> {\n\treturn credentialsFromToken(await refreshAccessToken(refreshToken));\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\n\tasync login(callbacks) {\n\t\tconst method = await callbacks.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\tconst credentials = await loginOpenAICodexDeviceCode({\n\t\t\t\tonDeviceCode: (info) => callbacks.notify({ type: \"device_code\", ...info }),\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t\treturn { ...credentials, type: \"oauth\" };\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\t// The manual_code prompt races the local callback server; abort it once\n\t\t// the flow settles so the UI can dismiss the pending input.\n\t\tconst manualAbort = new AbortController();\n\t\ttry {\n\t\t\tconst credentials = await loginOpenAICodex({\n\t\t\t\tonAuth: (info) => callbacks.notify({ type: \"auth_url\", url: info.url, instructions: info.instructions }),\n\t\t\t\tonProgress: (message) => callbacks.notify({ type: \"progress\", message }),\n\t\t\t\tonPrompt: (prompt) =>\n\t\t\t\t\tcallbacks.prompt({ type: \"text\", message: prompt.message, placeholder: prompt.placeholder }),\n\t\t\t\tonManualCodeInput: () =>\n\t\t\t\t\tcallbacks.prompt({\n\t\t\t\t\t\ttype: \"manual_code\",\n\t\t\t\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\t\t\tplaceholder: REDIRECT_URI,\n\t\t\t\t\t\tsignal: manualAbort.signal,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t\treturn { ...credentials, type: \"oauth\" };\n\t\t} finally {\n\t\t\tmanualAbort.abort();\n\t\t}\n\t},\n\n\tasync refresh(credential) {\n\t\treturn { ...(await refreshOpenAICodexToken(credential.refresh)), type: \"oauth\" };\n\t},\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n\nexport const openaiCodexOAuthProvider: OAuthProviderInterface = {\n\tid: \"openai-codex\",\n\tname: \"ChatGPT Plus/Pro (Codex Subscription)\",\n\tusesCallbackServer: true,\n\n\tasync login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\t\tconst loginMethod = await callbacks.onSelect({\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\t\tif (!loginMethod) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\n\t\tif (loginMethod === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode({\n\t\t\t\tonDeviceCode: callbacks.onDeviceCode,\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t}\n\n\t\tif (loginMethod !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${loginMethod}`);\n\t\t}\n\n\t\treturn loginOpenAICodex({\n\t\t\tonAuth: callbacks.onAuth,\n\t\t\tonPrompt: callbacks.onPrompt,\n\t\t\tonProgress: callbacks.onProgress,\n\t\t\tonManualCodeInput: callbacks.onManualCodeInput,\n\t\t});\n\t},\n\n\tasync refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n\t\treturn refreshOpenAICodexToken(credentials.refresh);\n\t},\n\n\tgetApiKey(credentials: OAuthCredentials): string {\n\t\treturn credentials.access;\n\t},\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"openai-codex.js","sourceRoot":"","sources":["../../../src/utils/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,kEAAkE;AAClE,IAAI,YAAY,GAAoD,IAAI,CAAC;AACzE,IAA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,EAAE;aACpF;SACD,CAAC,CAAC;QACH,IAAI,CAAC,WAAW,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACpC,CAAC;QAED,IAAI,WAAW,KAAK,qCAAqC,EAAE,CAAC;YAC3D,OAAO,0BAA0B,CAAC;gBACjC,YAAY,EAAE,SAAS,CAAC,YAAY;gBACpC,MAAM,EAAE,SAAS,CAAC,MAAM;aACxB,CAAC,CAAC;QACJ,CAAC;QAED,IAAI,WAAW,KAAK,iCAAiC,EAAE,CAAC;YACvD,MAAM,IAAI,KAAK,CAAC,sCAAsC,WAAW,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,OAAO,gBAAgB,CAAC;YACvB,MAAM,EAAE,SAAS,CAAC,MAAM;YACxB,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC9C,CAAC,CAAC;IAAA,CACH;IAED,KAAK,CAAC,YAAY,CAAC,WAA6B,EAA6B;QAC5E,OAAO,uBAAuB,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAAA,CACpD;IAED,SAAS,CAAC,WAA6B,EAAU;QAChD,OAAO,WAAW,CAAC,MAAM,CAAC;IAAA,CAC1B;CACD,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http for the OAuth callback.\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;\nlet _http: typeof import(\"node:http\") | 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\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { OAuthAuth } from \"../../auth/types.ts\";\nimport { getProviderEnvValue } from \"../provider-env.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport type {\n\tOAuthCredentials,\n\tOAuthDeviceCodeInfo,\n\tOAuthLoginCallbacks,\n\tOAuthPrompt,\n\tOAuthProviderInterface,\n} from \"./types.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;\nexport const OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nexport const 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 = REDIRECT_URI,\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): 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});\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\ntype OAuthServerInfo = {\n\tclose: () => void;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string } | null>;\n};\n\nfunction startLocalOAuthServer(state: string): Promise<OAuthServerInfo> {\n\tif (!_http) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settleWait: ((value: { code: string } | null) => void) | undefined;\n\tconst waitForCodePromise = new Promise<{ code: string } | null>((resolve) => {\n\t\tlet settled = false;\n\t\tsettleWait = (value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tresolve(value);\n\t\t};\n\t});\n\n\tconst server = _http.createServer((req, res) => {\n\t\ttry {\n\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\tif (url.pathname !== \"/auth/callback\") {\n\t\t\t\tres.statusCode = 404;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (url.searchParams.get(\"state\") !== state) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\tif (!code) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\t\tres.end(oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(oauthSuccessHtml(\"OpenAI authentication completed. You can close this window.\"));\n\t\t\tsettleWait?.({ code });\n\t\t} catch {\n\t\t\tres.statusCode = 500;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(oauthErrorHtml(\"Internal error while processing OAuth callback.\"));\n\t\t}\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(1455, getCallbackHost(), () => {\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => server.close(),\n\t\t\t\t\tcancelWait: () => {\n\t\t\t\t\t\tsettleWait?.(null);\n\t\t\t\t\t},\n\t\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on(\"error\", (_err: NodeJS.ErrnoException) => {\n\t\t\t\tsettleWait?.(null);\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// ignore\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcancelWait: () => {},\n\t\t\t\t\twaitForCode: async () => null,\n\t\t\t\t});\n\t\t\t});\n\t});\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): OAuthCredentials {\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\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<OAuthCredentials> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\n/**\n * Login with OpenAI Codex OAuth using the Codex device-code flow.\n */\nexport async function loginOpenAICodexDeviceCode(options: {\n\tonDeviceCode: (info: OAuthDeviceCodeInfo) => void;\n\tsignal?: AbortSignal;\n}): Promise<OAuthCredentials> {\n\tconst device = await startOpenAICodexDeviceAuth(options.signal);\n\toptions.onDeviceCode({\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, options.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\toptions.signal,\n\t);\n}\n\n/**\n * Login with OpenAI Codex OAuth\n *\n * @param options.onAuth - Called with URL and instructions when auth starts\n * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)\n * @param options.onProgress - Optional progress messages\n * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.\n * Races with browser callback - whichever completes first wins.\n * Useful for showing paste input immediately alongside browser flow.\n * @param options.originator - OAuth originator parameter (defaults to \"pi\")\n */\nexport async function loginOpenAICodex(options: {\n\tonAuth: (info: { url: string; instructions?: string }) => void;\n\tonPrompt: (prompt: OAuthPrompt) => Promise<string>;\n\tonProgress?: (message: string) => void;\n\tonManualCodeInput?: () => Promise<string>;\n\toriginator?: string;\n}): Promise<OAuthCredentials> {\n\tconst { verifier, state, url } = await createAuthorizationFlow(options.originator);\n\tconst server = await startLocalOAuthServer(state);\n\n\toptions.onAuth({ url, instructions: \"A browser window should open. Complete login to finish.\" });\n\n\tlet code: string | undefined;\n\ttry {\n\t\tif (options.onManualCodeInput) {\n\t\t\t// Race between browser callback and manual input\n\t\t\tlet manualCode: string | undefined;\n\t\t\tlet manualError: Error | undefined;\n\t\t\tconst manualPromise = options\n\t\t\t\t.onManualCodeInput()\n\t\t\t\t.then((input) => {\n\t\t\t\t\tmanualCode = input;\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tmanualError = err instanceof Error ? err : new Error(String(err));\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t});\n\n\t\t\tconst result = await server.waitForCode();\n\n\t\t\t// If manual input was cancelled, throw that error\n\t\t\tif (manualError) {\n\t\t\t\tthrow manualError;\n\t\t\t}\n\n\t\t\tif (result?.code) {\n\t\t\t\t// Browser callback won\n\t\t\t\tcode = result.code;\n\t\t\t} else if (manualCode) {\n\t\t\t\t// Manual input won (or callback timed out and user had entered code)\n\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t}\n\t\t\t\tcode = parsed.code;\n\t\t\t}\n\n\t\t\t// If still no code, wait for manual promise to complete and try that\n\t\t\tif (!code) {\n\t\t\t\tawait manualPromise;\n\t\t\t\tif (manualError) {\n\t\t\t\t\tthrow manualError;\n\t\t\t\t}\n\t\t\t\tif (manualCode) {\n\t\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t\t}\n\t\t\t\t\tcode = parsed.code;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Original flow: wait for callback, then prompt if needed\n\t\t\tconst result = await server.waitForCode();\n\t\t\tif (result?.code) {\n\t\t\t\tcode = result.code;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to onPrompt if still no code\n\t\tif (!code) {\n\t\t\tconst input = await options.onPrompt({\n\t\t\t\tmessage: \"Paste the authorization code (or full redirect URL):\",\n\t\t\t});\n\t\t\tconst parsed = parseAuthorizationInput(input);\n\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t}\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) {\n\t\t\tthrow new Error(\"Missing authorization code\");\n\t\t}\n\n\t\treturn exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI);\n\t} finally {\n\t\tserver.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials> {\n\treturn credentialsFromToken(await refreshAccessToken(refreshToken));\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\n\tasync login(callbacks) {\n\t\tconst method = await callbacks.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\tconst credentials = await loginOpenAICodexDeviceCode({\n\t\t\t\tonDeviceCode: (info) => callbacks.notify({ type: \"device_code\", ...info }),\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t\treturn { ...credentials, type: \"oauth\" };\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\t// The manual_code prompt races the local callback server; abort it once\n\t\t// the flow settles so the UI can dismiss the pending input.\n\t\tconst manualAbort = new AbortController();\n\t\ttry {\n\t\t\tconst credentials = await loginOpenAICodex({\n\t\t\t\tonAuth: (info) => callbacks.notify({ type: \"auth_url\", url: info.url, instructions: info.instructions }),\n\t\t\t\tonProgress: (message) => callbacks.notify({ type: \"progress\", message }),\n\t\t\t\tonPrompt: (prompt) =>\n\t\t\t\t\tcallbacks.prompt({ type: \"text\", message: prompt.message, placeholder: prompt.placeholder }),\n\t\t\t\tonManualCodeInput: () =>\n\t\t\t\t\tcallbacks.prompt({\n\t\t\t\t\t\ttype: \"manual_code\",\n\t\t\t\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\t\t\tplaceholder: REDIRECT_URI,\n\t\t\t\t\t\tsignal: manualAbort.signal,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t\treturn { ...credentials, type: \"oauth\" };\n\t\t} finally {\n\t\t\tmanualAbort.abort();\n\t\t}\n\t},\n\n\tasync refresh(credential) {\n\t\treturn { ...(await refreshOpenAICodexToken(credential.refresh)), type: \"oauth\" };\n\t},\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n\nexport const openaiCodexOAuthProvider: OAuthProviderInterface = {\n\tid: \"openai-codex\",\n\tname: \"ChatGPT Plus/Pro (Codex Subscription)\",\n\tusesCallbackServer: true,\n\n\tasync login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\t\tconst loginMethod = await callbacks.onSelect({\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\t\tif (!loginMethod) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\n\t\tif (loginMethod === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode({\n\t\t\t\tonDeviceCode: callbacks.onDeviceCode,\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t}\n\n\t\tif (loginMethod !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${loginMethod}`);\n\t\t}\n\n\t\treturn loginOpenAICodex({\n\t\t\tonAuth: callbacks.onAuth,\n\t\t\tonPrompt: callbacks.onPrompt,\n\t\t\tonProgress: callbacks.onProgress,\n\t\t\tonManualCodeInput: callbacks.onManualCodeInput,\n\t\t});\n\t},\n\n\tasync refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n\t\treturn refreshOpenAICodexToken(credentials.refresh);\n\t},\n\n\tgetApiKey(credentials: OAuthCredentials): string {\n\t\treturn credentials.access;\n\t},\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pkce.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/pkce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH;;;GAGG;AACH,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAarF","sourcesContent":["/**\n * PKCE utilities using Web Crypto API.\n * Works in both Node.js 20+ and browsers.\n */\n\n/**\n * Encode bytes as base64url string.\n */\nfunction base64urlEncode(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n\n/**\n * Generate PKCE code verifier and challenge.\n * Uses Web Crypto API for cross-platform compatibility.\n */\nexport async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {\n\t// Generate random verifier\n\tconst verifierBytes = new Uint8Array(32);\n\tcrypto.getRandomValues(verifierBytes);\n\tconst verifier = base64urlEncode(verifierBytes);\n\n\t// Compute SHA-256 challenge\n\tconst encoder = new TextEncoder();\n\tconst data = encoder.encode(verifier);\n\tconst hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n\tconst challenge = base64urlEncode(new Uint8Array(hashBuffer));\n\n\treturn { verifier, challenge };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pkce.js","sourceRoot":"","sources":["../../../src/utils/oauth/pkce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,SAAS,eAAe,CAAC,KAAiB,EAAU;IACnD,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAAA,CAC9E;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,GAAqD;IACtF,2BAA2B;IAC3B,MAAM,aAAa,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACzC,MAAM,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,eAAe,CAAC,aAAa,CAAC,CAAC;IAEhD,4BAA4B;IAC5B,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtC,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;IAE9D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;AAAA,CAC/B","sourcesContent":["/**\n * PKCE utilities using Web Crypto API.\n * Works in both Node.js 20+ and browsers.\n */\n\n/**\n * Encode bytes as base64url string.\n */\nfunction base64urlEncode(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n\n/**\n * Generate PKCE code verifier and challenge.\n * Uses Web Crypto API for cross-platform compatibility.\n */\nexport async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {\n\t// Generate random verifier\n\tconst verifierBytes = new Uint8Array(32);\n\tcrypto.getRandomValues(verifierBytes);\n\tconst verifier = base64urlEncode(verifierBytes);\n\n\t// Compute SHA-256 challenge\n\tconst encoder = new TextEncoder();\n\tconst data = encoder.encode(verifier);\n\tconst hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n\tconst challenge = base64urlEncode(new Uint8Array(hashBuffer));\n\n\treturn { verifier, challenge };\n}\n"]}
@@ -1,39 +0,0 @@
1
- /**
2
- * Radius gateway OAuth flow and model catalog loading.
3
- *
4
- * Radius is a pi-messages gateway. OAuth endpoints are discovered from the
5
- * gateway (`/v1/oauth`); the model catalog comes from `/v1/config` and is
6
- * cached on the stored credential (`gatewayConfig`) so models are available
7
- * at startup and refreshed whenever the token refreshes.
8
- *
9
- * NOTE: This module uses node:http for the OAuth callback server.
10
- * It is only intended for CLI use, not browser environments.
11
- */
12
- import type { Api, Model, ThinkingLevelMap } from "../../types.ts";
13
- import type { OAuthCredentials, OAuthProviderInterface } from "./types.ts";
14
- export declare const DEFAULT_RADIUS_GATEWAY = "https://radius.pi.dev";
15
- /** Model metadata served by the gateway config endpoint. */
16
- export type RadiusGatewayModel = {
17
- id: string;
18
- name: string;
19
- reasoning: boolean;
20
- thinkingLevelMap?: ThinkingLevelMap;
21
- input: ("text" | "image")[];
22
- cost: Model<Api>["cost"];
23
- contextWindow: number;
24
- maxTokens: number;
25
- };
26
- export type RadiusGatewayConfig = {
27
- baseUrl: string;
28
- models: RadiusGatewayModel[];
29
- };
30
- export type RadiusOAuthCredentials = OAuthCredentials & {
31
- gatewayConfig?: RadiusGatewayConfig;
32
- };
33
- export interface RadiusOAuthProviderOptions {
34
- id: string;
35
- name: string;
36
- gateway: string;
37
- }
38
- export declare function createRadiusOAuthProvider(options: RadiusOAuthProviderOptions): OAuthProviderInterface;
39
- //# sourceMappingURL=radius.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"radius.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAInE,OAAO,KAAK,EAAE,gBAAgB,EAAuB,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEhG,eAAO,MAAM,sBAAsB,0BAA0B,CAAC;AAU9D,4DAA4D;AAC5D,MAAM,MAAM,kBAAkB,GAAG;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;IACnB,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IACpC,KAAK,EAAE,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC;IAC5B,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IACzB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,kBAAkB,EAAE,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG;IACvD,aAAa,CAAC,EAAE,mBAAmB,CAAC;CACpC,CAAC;AAmaF,MAAM,WAAW,0BAA0B;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,GAAG,sBAAsB,CA4ErG","sourcesContent":["/**\n * Radius gateway OAuth flow and model catalog loading.\n *\n * Radius is a pi-messages gateway. OAuth endpoints are discovered from the\n * gateway (`/v1/oauth`); the model catalog comes from `/v1/config` and is\n * cached on the stored credential (`gatewayConfig`) so models are available\n * at startup and refreshed whenever the token refreshes.\n *\n * NOTE: This module uses node:http for the OAuth callback server.\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 _http: typeof import(\"node:http\") | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { Api, Model, ThinkingLevelMap } from \"../../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from \"./types.ts\";\n\nexport const DEFAULT_RADIUS_GATEWAY = \"https://radius.pi.dev\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\n\n/** Model metadata served by the gateway config endpoint. */\nexport type RadiusGatewayModel = {\n\tid: string;\n\tname: string;\n\treasoning: boolean;\n\tthinkingLevelMap?: ThinkingLevelMap;\n\tinput: (\"text\" | \"image\")[];\n\tcost: Model<Api>[\"cost\"];\n\tcontextWindow: number;\n\tmaxTokens: number;\n};\n\nexport type RadiusGatewayConfig = {\n\tbaseUrl: string;\n\tmodels: RadiusGatewayModel[];\n};\n\nexport type RadiusOAuthCredentials = OAuthCredentials & {\n\tgatewayConfig?: RadiusGatewayConfig;\n};\n\ntype RadiusOAuthConfig = {\n\tissuer: string;\n\tauthorizationEndpoint: string;\n\ttokenEndpoint: string;\n\tdeviceAuthorizationEndpoint: string;\n\tdeviceAuthorizationEventsEndpoint: string;\n\tverificationEndpoint: string;\n\tclientId: string;\n\tscope: string;\n\tdeviceCodeGrantType: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri?: string;\n\tverification_uri_complete?: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction normalizeRadiusGatewayUrl(value: string): string {\n\tconst withScheme = /^https?:\\/\\//iu.test(value) ? value : `https://${value}`;\n\treturn withScheme.replace(/\\/+$/u, \"\");\n}\n\n// The gateway is a trusted first-party service. The shape checks below only\n// guard against version skew and stale credential caches: malformed entries\n// are dropped rather than failing the whole catalog, and nested fields (e.g.\n// `input` members, `cost` rates) are intentionally not validated in depth.\n// Do not turn this into strict validation.\nfunction isRadiusGatewayModel(value: unknown): value is RadiusGatewayModel {\n\tif (!isRecord(value)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.name === \"string\" &&\n\t\ttypeof value.reasoning === \"boolean\" &&\n\t\tArray.isArray(value.input) &&\n\t\tisRecord(value.cost) &&\n\t\ttypeof value.contextWindow === \"number\" &&\n\t\ttypeof value.maxTokens === \"number\"\n\t);\n}\n\nfunction sanitizeRadiusGatewayConfig(config: unknown): RadiusGatewayConfig | undefined {\n\tif (!isRecord(config)) {\n\t\treturn undefined;\n\t}\n\tconst baseUrl = config.baseUrl;\n\tconst models = config.models;\n\tif (typeof baseUrl !== \"string\" || !Array.isArray(models)) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tbaseUrl,\n\t\tmodels: models.filter(isRadiusGatewayModel).map((model) => ({ ...model })),\n\t};\n}\n\nfunction getRadiusCredentialConfig(credentials: OAuthCredentials | undefined): RadiusGatewayConfig | undefined {\n\treturn sanitizeRadiusGatewayConfig((credentials as RadiusOAuthCredentials | undefined)?.gatewayConfig);\n}\n\nfunction truncateHttpBody(body: string): string {\n\tconst trimmed = body.trim();\n\treturn trimmed.length > 512 ? `${trimmed.slice(0, 512)}…` : trimmed;\n}\n\nasync function loadRadiusGatewayConfig(gateway: string, apiKey?: string): Promise<RadiusGatewayConfig> {\n\tconst headers: Record<string, string> = { accept: \"application/json\" };\n\tif (apiKey) {\n\t\theaders.authorization = `Bearer ${apiKey}`;\n\t}\n\n\tconst response = await fetch(new URL(\"/v1/config\", gateway), { headers });\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius config from ${gateway}: ${response.status}: ${truncateHttpBody(await response.text())}`,\n\t\t);\n\t}\n\n\tconst config = sanitizeRadiusGatewayConfig(await response.json());\n\tif (!config) {\n\t\tthrow new Error(`Invalid Radius config from ${gateway}`);\n\t}\n\treturn config;\n}\n\nasync function loadRadiusOAuthConfig(gateway: string): Promise<RadiusOAuthConfig> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\treturn (await response.json()) as RadiusOAuthConfig;\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\toauth: RadiusOAuthConfig,\n\tbody: URLSearchParams,\n\tsignal?: AbortSignal,\n): Promise<OAuthCredentials> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.tokenEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\ntype OAuthCallbackServer = {\n\twaitForCode(): Promise<string | null>;\n\tclose(): void;\n};\n\nfunction startOAuthCallbackServer(\n\texpectedState: string,\n\tsignal: AbortSignal | undefined,\n): Promise<OAuthCallbackServer> {\n\tif (!_http) {\n\t\tthrow new Error(\"Radius OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settle: (code: string | null) => void = () => {};\n\tlet settled = false;\n\tconst wait = new Promise<string | null>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tconst finish = (code: string | null) => {\n\t\tif (settled) {\n\t\t\treturn;\n\t\t}\n\t\tsettled = true;\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\tsettle(code);\n\t};\n\tconst onAbort = () => finish(null);\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst sendPage = (response: import(\"node:http\").ServerResponse, status: number, html: string) => {\n\t\tresponse.statusCode = status;\n\t\tresponse.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n\t\tresponse.end(html);\n\t};\n\n\tconst server = _http.createServer((request, response) => {\n\t\tconst url = new URL(request.url ?? \"/\", REDIRECT_URI);\n\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\tsendPage(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (url.searchParams.get(\"state\") !== expectedState) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"OAuth state mismatch.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(url.searchParams.get(\"error_description\") ?? error));\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tsendPage(response, 200, oauthSuccessHtml(\"Signed in to Radius. You may now close this page.\"));\n\t\tfinish(code);\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\t\tresolve({\n\t\t\t\t\twaitForCode: () => wait,\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\tfinish(null);\n\t\t\t\t\t\tserver.close();\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t})\n\t\t\t.once(\"error\", () => {\n\t\t\t\tfinish(null);\n\t\t\t\tresolve({ waitForCode: async () => null, close: () => {} });\n\t\t\t});\n\t});\n}\n\nasync function loginWithBrowser(oauth: RadiusOAuthConfig, callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(oauth.authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: oauth.clientId,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: oauth.scope,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callbackServer = await startOAuthCallbackServer(state, callbacks.signal);\n\tcallbacks.onProgress?.(`Listening for OAuth callback on ${REDIRECT_URI}`);\n\tcallbacks.onAuth({\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst code = await callbackServer.waitForCode();\n\t\tif (!code) {\n\t\t\tif (callbacks.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\t\t\tthrow new Error(\"OAuth callback did not complete.\");\n\t\t}\n\t\treturn await requestOAuthToken(\n\t\t\toauth,\n\t\t\tnew URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\tcode,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t}),\n\t\t\tcallbacks.signal,\n\t\t);\n\t} finally {\n\t\tcallbackServer.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(\n\toauth: RadiusOAuthConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.deviceAuthorizationEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: oauth.clientId, scope: oauth.scope }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: data.verification_uri,\n\t\tverification_uri_complete: data.verification_uri_complete,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(\n\toauth: RadiusOAuthConfig,\n\tcallbacks: OAuthLoginCallbacks,\n): Promise<OAuthCredentials> {\n\tconst device = await requestDeviceAuthorization(oauth, callbacks.signal);\n\tcallbacks.onDeviceCode({\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri || oauth.verificationEndpoint,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredentials>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: callbacks.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\toauth,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: oauth.deviceCodeGrantType,\n\t\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tcallbacks.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nasync function attachGatewayConfig(\n\tgateway: string,\n\tcredentials: OAuthCredentials,\n\tprevious?: OAuthCredentials,\n): Promise<RadiusOAuthCredentials> {\n\ttry {\n\t\tconst config = await loadRadiusGatewayConfig(gateway, credentials.access);\n\t\treturn { ...credentials, gatewayConfig: config };\n\t} catch (error) {\n\t\t// Keep the previous catalog so models do not vanish on transient\n\t\t// config failures; the next token refresh retries.\n\t\tconst previousConfig = getRadiusCredentialConfig(previous);\n\t\tif (previousConfig) {\n\t\t\treturn { ...credentials, gatewayConfig: previousConfig };\n\t\t}\n\t\t// No catalog to retain (e.g. initial login): fail loudly instead of\n\t\t// completing a sign-in that would register no models.\n\t\tthrow error;\n\t}\n}\n\nexport interface RadiusOAuthProviderOptions {\n\tid: string;\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuthProvider(options: RadiusOAuthProviderOptions): OAuthProviderInterface {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tid: options.id,\n\t\tname: options.name,\n\n\t\tasync login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst loginMethod = await callbacks.onSelect({\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\t\t\tif (!loginMethod) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\n\t\t\tlet credentials: OAuthCredentials;\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\tcredentials = await loginWithDeviceCode(oauth, callbacks);\n\t\t\t} else if (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tcredentials = await loginWithBrowser(oauth, callbacks);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t\t}\n\n\t\t\treturn attachGatewayConfig(gateway, credentials);\n\t\t},\n\n\t\tasync refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\toauth,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\trefresh_token: credentials.refresh,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn attachGatewayConfig(gateway, refreshed, credentials);\n\t\t},\n\n\t\tgetApiKey(credentials: OAuthCredentials): string {\n\t\t\treturn credentials.access;\n\t\t},\n\n\t\tmodifyModels(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[] {\n\t\t\tconst config = getRadiusCredentialConfig(credentials);\n\t\t\tif (!config) {\n\t\t\t\treturn models;\n\t\t\t}\n\n\t\t\t// Keep models already registered for this provider (e.g. models.json\n\t\t\t// custom entries) and add catalog models that are not present.\n\t\t\tconst existingIds = new Set(models.filter((model) => model.provider === options.id).map((model) => model.id));\n\t\t\tconst added = config.models\n\t\t\t\t.filter((model) => !existingIds.has(model.id))\n\t\t\t\t.map(\n\t\t\t\t\t(model) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\t...model,\n\t\t\t\t\t\t\tapi: \"pi-messages\",\n\t\t\t\t\t\t\tprovider: options.id,\n\t\t\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\t\t}) as Model<Api>,\n\t\t\t\t);\n\n\t\t\treturn [...models, ...added];\n\t\t},\n\t};\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/utils/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,kEAAkE;AAClE,IAAI,KAAK,GAAsC,IAAI,CAAC;AACpD,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;IACzF,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QAC/B,KAAK,GAAG,CAAC,CAAC;IAAA,CACV,CAAC,CAAC;AACJ,CAAC;AAGD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM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C,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;QAAA,CAC5D;QAED,SAAS,CAAC,WAA6B,EAAU;YAChD,OAAO,WAAW,CAAC,MAAM,CAAC;QAAA,CAC1B;QAED,YAAY,CAAC,MAAoB,EAAE,WAA6B,EAAgB;YAC/E,MAAM,MAAM,GAAG,yBAAyB,CAAC,WAAW,CAAC,CAAC;YACtD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,OAAO,MAAM,CAAC;YACf,CAAC;YAED,qEAAqE;YACrE,+DAA+D;YAC/D,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;YAC9G,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM;iBACzB,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;iBAC7C,GAAG,CACH,CAAC,KAAK,EAAE,EAAE,CACT,CAAC;gBACA,GAAG,KAAK;gBACR,GAAG,EAAE,aAAa;gBAClB,QAAQ,EAAE,OAAO,CAAC,EAAE;gBACpB,OAAO,EAAE,MAAM,CAAC,OAAO;aACvB,CAAe,CACjB,CAAC;YAEH,OAAO,CAAC,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC;QAAA,CAC7B;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Radius gateway OAuth flow and model catalog loading.\n *\n * Radius is a pi-messages gateway. OAuth endpoints are discovered from the\n * gateway (`/v1/oauth`); the model catalog comes from `/v1/config` and is\n * cached on the stored credential (`gatewayConfig`) so models are available\n * at startup and refreshed whenever the token refreshes.\n *\n * NOTE: This module uses node:http for the OAuth callback server.\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 _http: typeof import(\"node:http\") | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { Api, Model, ThinkingLevelMap } from \"../../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from \"./types.ts\";\n\nexport const DEFAULT_RADIUS_GATEWAY = \"https://radius.pi.dev\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\n\n/** Model metadata served by the gateway config endpoint. */\nexport type RadiusGatewayModel = {\n\tid: string;\n\tname: string;\n\treasoning: boolean;\n\tthinkingLevelMap?: ThinkingLevelMap;\n\tinput: (\"text\" | \"image\")[];\n\tcost: Model<Api>[\"cost\"];\n\tcontextWindow: number;\n\tmaxTokens: number;\n};\n\nexport type RadiusGatewayConfig = {\n\tbaseUrl: string;\n\tmodels: RadiusGatewayModel[];\n};\n\nexport type RadiusOAuthCredentials = OAuthCredentials & {\n\tgatewayConfig?: RadiusGatewayConfig;\n};\n\ntype RadiusOAuthConfig = {\n\tissuer: string;\n\tauthorizationEndpoint: string;\n\ttokenEndpoint: string;\n\tdeviceAuthorizationEndpoint: string;\n\tdeviceAuthorizationEventsEndpoint: string;\n\tverificationEndpoint: string;\n\tclientId: string;\n\tscope: string;\n\tdeviceCodeGrantType: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri?: string;\n\tverification_uri_complete?: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction normalizeRadiusGatewayUrl(value: string): string {\n\tconst withScheme = /^https?:\\/\\//iu.test(value) ? value : `https://${value}`;\n\treturn withScheme.replace(/\\/+$/u, \"\");\n}\n\n// The gateway is a trusted first-party service. The shape checks below only\n// guard against version skew and stale credential caches: malformed entries\n// are dropped rather than failing the whole catalog, and nested fields (e.g.\n// `input` members, `cost` rates) are intentionally not validated in depth.\n// Do not turn this into strict validation.\nfunction isRadiusGatewayModel(value: unknown): value is RadiusGatewayModel {\n\tif (!isRecord(value)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.name === \"string\" &&\n\t\ttypeof value.reasoning === \"boolean\" &&\n\t\tArray.isArray(value.input) &&\n\t\tisRecord(value.cost) &&\n\t\ttypeof value.contextWindow === \"number\" &&\n\t\ttypeof value.maxTokens === \"number\"\n\t);\n}\n\nfunction sanitizeRadiusGatewayConfig(config: unknown): RadiusGatewayConfig | undefined {\n\tif (!isRecord(config)) {\n\t\treturn undefined;\n\t}\n\tconst baseUrl = config.baseUrl;\n\tconst models = config.models;\n\tif (typeof baseUrl !== \"string\" || !Array.isArray(models)) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tbaseUrl,\n\t\tmodels: models.filter(isRadiusGatewayModel).map((model) => ({ ...model })),\n\t};\n}\n\nfunction getRadiusCredentialConfig(credentials: OAuthCredentials | undefined): RadiusGatewayConfig | undefined {\n\treturn sanitizeRadiusGatewayConfig((credentials as RadiusOAuthCredentials | undefined)?.gatewayConfig);\n}\n\nfunction truncateHttpBody(body: string): string {\n\tconst trimmed = body.trim();\n\treturn trimmed.length > 512 ? `${trimmed.slice(0, 512)}…` : trimmed;\n}\n\nasync function loadRadiusGatewayConfig(gateway: string, apiKey?: string): Promise<RadiusGatewayConfig> {\n\tconst headers: Record<string, string> = { accept: \"application/json\" };\n\tif (apiKey) {\n\t\theaders.authorization = `Bearer ${apiKey}`;\n\t}\n\n\tconst response = await fetch(new URL(\"/v1/config\", gateway), { headers });\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius config from ${gateway}: ${response.status}: ${truncateHttpBody(await response.text())}`,\n\t\t);\n\t}\n\n\tconst config = sanitizeRadiusGatewayConfig(await response.json());\n\tif (!config) {\n\t\tthrow new Error(`Invalid Radius config from ${gateway}`);\n\t}\n\treturn config;\n}\n\nasync function loadRadiusOAuthConfig(gateway: string): Promise<RadiusOAuthConfig> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\treturn (await response.json()) as RadiusOAuthConfig;\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\toauth: RadiusOAuthConfig,\n\tbody: URLSearchParams,\n\tsignal?: AbortSignal,\n): Promise<OAuthCredentials> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.tokenEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\ntype OAuthCallbackServer = {\n\twaitForCode(): Promise<string | null>;\n\tclose(): void;\n};\n\nfunction startOAuthCallbackServer(\n\texpectedState: string,\n\tsignal: AbortSignal | undefined,\n): Promise<OAuthCallbackServer> {\n\tif (!_http) {\n\t\tthrow new Error(\"Radius OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settle: (code: string | null) => void = () => {};\n\tlet settled = false;\n\tconst wait = new Promise<string | null>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tconst finish = (code: string | null) => {\n\t\tif (settled) {\n\t\t\treturn;\n\t\t}\n\t\tsettled = true;\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\tsettle(code);\n\t};\n\tconst onAbort = () => finish(null);\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst sendPage = (response: import(\"node:http\").ServerResponse, status: number, html: string) => {\n\t\tresponse.statusCode = status;\n\t\tresponse.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n\t\tresponse.end(html);\n\t};\n\n\tconst server = _http.createServer((request, response) => {\n\t\tconst url = new URL(request.url ?? \"/\", REDIRECT_URI);\n\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\tsendPage(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (url.searchParams.get(\"state\") !== expectedState) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"OAuth state mismatch.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(url.searchParams.get(\"error_description\") ?? error));\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tsendPage(response, 200, oauthSuccessHtml(\"Signed in to Radius. You may now close this page.\"));\n\t\tfinish(code);\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\t\tresolve({\n\t\t\t\t\twaitForCode: () => wait,\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\tfinish(null);\n\t\t\t\t\t\tserver.close();\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t})\n\t\t\t.once(\"error\", () => {\n\t\t\t\tfinish(null);\n\t\t\t\tresolve({ waitForCode: async () => null, close: () => {} });\n\t\t\t});\n\t});\n}\n\nasync function loginWithBrowser(oauth: RadiusOAuthConfig, callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(oauth.authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: oauth.clientId,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: oauth.scope,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callbackServer = await startOAuthCallbackServer(state, callbacks.signal);\n\tcallbacks.onProgress?.(`Listening for OAuth callback on ${REDIRECT_URI}`);\n\tcallbacks.onAuth({\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst code = await callbackServer.waitForCode();\n\t\tif (!code) {\n\t\t\tif (callbacks.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\t\t\tthrow new Error(\"OAuth callback did not complete.\");\n\t\t}\n\t\treturn await requestOAuthToken(\n\t\t\toauth,\n\t\t\tnew URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\tcode,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t}),\n\t\t\tcallbacks.signal,\n\t\t);\n\t} finally {\n\t\tcallbackServer.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(\n\toauth: RadiusOAuthConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.deviceAuthorizationEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: oauth.clientId, scope: oauth.scope }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: data.verification_uri,\n\t\tverification_uri_complete: data.verification_uri_complete,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(\n\toauth: RadiusOAuthConfig,\n\tcallbacks: OAuthLoginCallbacks,\n): Promise<OAuthCredentials> {\n\tconst device = await requestDeviceAuthorization(oauth, callbacks.signal);\n\tcallbacks.onDeviceCode({\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri || oauth.verificationEndpoint,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredentials>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: callbacks.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\toauth,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: oauth.deviceCodeGrantType,\n\t\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tcallbacks.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nasync function attachGatewayConfig(\n\tgateway: string,\n\tcredentials: OAuthCredentials,\n\tprevious?: OAuthCredentials,\n): Promise<RadiusOAuthCredentials> {\n\ttry {\n\t\tconst config = await loadRadiusGatewayConfig(gateway, credentials.access);\n\t\treturn { ...credentials, gatewayConfig: config };\n\t} catch (error) {\n\t\t// Keep the previous catalog so models do not vanish on transient\n\t\t// config failures; the next token refresh retries.\n\t\tconst previousConfig = getRadiusCredentialConfig(previous);\n\t\tif (previousConfig) {\n\t\t\treturn { ...credentials, gatewayConfig: previousConfig };\n\t\t}\n\t\t// No catalog to retain (e.g. initial login): fail loudly instead of\n\t\t// completing a sign-in that would register no models.\n\t\tthrow error;\n\t}\n}\n\nexport interface RadiusOAuthProviderOptions {\n\tid: string;\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuthProvider(options: RadiusOAuthProviderOptions): OAuthProviderInterface {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tid: options.id,\n\t\tname: options.name,\n\n\t\tasync login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst loginMethod = await callbacks.onSelect({\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\t\t\tif (!loginMethod) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\n\t\t\tlet credentials: OAuthCredentials;\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\tcredentials = await loginWithDeviceCode(oauth, callbacks);\n\t\t\t} else if (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tcredentials = await loginWithBrowser(oauth, callbacks);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t\t}\n\n\t\t\treturn attachGatewayConfig(gateway, credentials);\n\t\t},\n\n\t\tasync refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\toauth,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\trefresh_token: credentials.refresh,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn attachGatewayConfig(gateway, refreshed, credentials);\n\t\t},\n\n\t\tgetApiKey(credentials: OAuthCredentials): string {\n\t\t\treturn credentials.access;\n\t\t},\n\n\t\tmodifyModels(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[] {\n\t\t\tconst config = getRadiusCredentialConfig(credentials);\n\t\t\tif (!config) {\n\t\t\t\treturn models;\n\t\t\t}\n\n\t\t\t// Keep models already registered for this provider (e.g. models.json\n\t\t\t// custom entries) and add catalog models that are not present.\n\t\t\tconst existingIds = new Set(models.filter((model) => model.provider === options.id).map((model) => model.id));\n\t\t\tconst added = config.models\n\t\t\t\t.filter((model) => !existingIds.has(model.id))\n\t\t\t\t.map(\n\t\t\t\t\t(model) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\t...model,\n\t\t\t\t\t\t\tapi: \"pi-messages\",\n\t\t\t\t\t\t\tprovider: options.id,\n\t\t\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\t\t}) as Model<Api>,\n\t\t\t\t);\n\n\t\t\treturn [...models, ...added];\n\t\t},\n\t};\n}\n"]}