@fractaal/pi-ai 0.86.8 → 1.4.1

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 (250) hide show
  1. package/README.md +105 -45
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +180 -141
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  6. package/dist/api/azure-openai-responses.js +8 -10
  7. package/dist/api/azure-openai-responses.js.map +1 -1
  8. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  9. package/dist/api/bedrock-converse-stream.js +130 -96
  10. package/dist/api/bedrock-converse-stream.js.map +1 -1
  11. package/dist/api/classifier-shared.d.ts +21 -0
  12. package/dist/api/classifier-shared.d.ts.map +1 -0
  13. package/dist/api/classifier-shared.js +99 -0
  14. package/dist/api/classifier-shared.js.map +1 -0
  15. package/dist/api/cloudflare-workers-ai-system-one.d.ts.map +1 -1
  16. package/dist/api/cloudflare-workers-ai-system-one.js +10 -1
  17. package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
  18. package/dist/api/constrained-sampling.d.ts +11 -1
  19. package/dist/api/constrained-sampling.d.ts.map +1 -1
  20. package/dist/api/constrained-sampling.js +33 -18
  21. package/dist/api/constrained-sampling.js.map +1 -1
  22. package/dist/api/google-generative-ai.d.ts.map +1 -1
  23. package/dist/api/google-generative-ai.js +4 -10
  24. package/dist/api/google-generative-ai.js.map +1 -1
  25. package/dist/api/google-shared.d.ts +2 -1
  26. package/dist/api/google-shared.d.ts.map +1 -1
  27. package/dist/api/google-shared.js +60 -3
  28. package/dist/api/google-shared.js.map +1 -1
  29. package/dist/api/google-vertex.d.ts.map +1 -1
  30. package/dist/api/google-vertex.js +9 -15
  31. package/dist/api/google-vertex.js.map +1 -1
  32. package/dist/api/lazy.d.ts +7 -2
  33. package/dist/api/lazy.d.ts.map +1 -1
  34. package/dist/api/lazy.js +28 -8
  35. package/dist/api/lazy.js.map +1 -1
  36. package/dist/api/llama-cpp-classify.d.ts.map +1 -1
  37. package/dist/api/llama-cpp-classify.js +4 -1
  38. package/dist/api/llama-cpp-classify.js.map +1 -1
  39. package/dist/api/mistral-conversations.d.ts.map +1 -1
  40. package/dist/api/mistral-conversations.js +50 -60
  41. package/dist/api/mistral-conversations.js.map +1 -1
  42. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  43. package/dist/api/openai-codex-responses.js +23 -14
  44. package/dist/api/openai-codex-responses.js.map +1 -1
  45. package/dist/api/openai-completions.d.ts.map +1 -1
  46. package/dist/api/openai-completions.js +83 -87
  47. package/dist/api/openai-completions.js.map +1 -1
  48. package/dist/api/openai-decisions.d.ts +4 -0
  49. package/dist/api/openai-decisions.d.ts.map +1 -0
  50. package/dist/api/openai-decisions.js +162 -0
  51. package/dist/api/openai-decisions.js.map +1 -0
  52. package/dist/api/openai-decisions.lazy.d.ts +3 -0
  53. package/dist/api/openai-decisions.lazy.d.ts.map +1 -0
  54. package/dist/api/openai-decisions.lazy.js +4 -0
  55. package/dist/api/openai-decisions.lazy.js.map +1 -0
  56. package/dist/api/openai-responses-shared.d.ts +26 -0
  57. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  58. package/dist/api/openai-responses-shared.js +132 -66
  59. package/dist/api/openai-responses-shared.js.map +1 -1
  60. package/dist/api/openai-responses.d.ts.map +1 -1
  61. package/dist/api/openai-responses.js +38 -19
  62. package/dist/api/openai-responses.js.map +1 -1
  63. package/dist/api/openrouter-images.d.ts.map +1 -1
  64. package/dist/api/openrouter-images.js +5 -3
  65. package/dist/api/openrouter-images.js.map +1 -1
  66. package/dist/api/pi-messages.d.ts +2 -0
  67. package/dist/api/pi-messages.d.ts.map +1 -1
  68. package/dist/api/pi-messages.js +18 -12
  69. package/dist/api/pi-messages.js.map +1 -1
  70. package/dist/api/simple-options.d.ts.map +1 -1
  71. package/dist/api/simple-options.js +2 -1
  72. package/dist/api/simple-options.js.map +1 -1
  73. package/dist/api/system-one-shared.d.ts +29 -3
  74. package/dist/api/system-one-shared.d.ts.map +1 -1
  75. package/dist/api/system-one-shared.js +54 -86
  76. package/dist/api/system-one-shared.js.map +1 -1
  77. package/dist/api/transform-messages.d.ts +16 -1
  78. package/dist/api/transform-messages.d.ts.map +1 -1
  79. package/dist/api/transform-messages.js +28 -15
  80. package/dist/api/transform-messages.js.map +1 -1
  81. package/dist/api/typesafe-system-one.d.ts.map +1 -1
  82. package/dist/api/typesafe-system-one.js +12 -1
  83. package/dist/api/typesafe-system-one.js.map +1 -1
  84. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  85. package/dist/auth/oauth/anthropic.js +14 -6
  86. package/dist/auth/oauth/anthropic.js.map +1 -1
  87. package/dist/auth/oauth/openai-chatgpt.js +1 -1
  88. package/dist/auth/oauth/openai-chatgpt.js.map +1 -1
  89. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  90. package/dist/auth/oauth/openai-codex.js +4 -4
  91. package/dist/auth/oauth/openai-codex.js.map +1 -1
  92. package/dist/auth/types.d.ts +9 -0
  93. package/dist/auth/types.d.ts.map +1 -1
  94. package/dist/auth/types.js.map +1 -1
  95. package/dist/compat/extension-oauth-types.d.ts +4 -0
  96. package/dist/compat/extension-oauth-types.d.ts.map +1 -1
  97. package/dist/compat/extension-oauth-types.js.map +1 -1
  98. package/dist/index.d.ts +3 -1
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +3 -1
  101. package/dist/index.js.map +1 -1
  102. package/dist/models.d.ts +9 -0
  103. package/dist/models.d.ts.map +1 -1
  104. package/dist/models.js +23 -7
  105. package/dist/models.js.map +1 -1
  106. package/dist/providers/compat-schema.d.ts +509 -0
  107. package/dist/providers/compat-schema.d.ts.map +1 -0
  108. package/dist/providers/compat-schema.js +396 -0
  109. package/dist/providers/compat-schema.js.map +1 -0
  110. package/dist/providers/data/.manifest.json +1 -1
  111. package/dist/providers/data/amazon-bedrock.json +1 -1
  112. package/dist/providers/data/anthropic.json +1 -1
  113. package/dist/providers/data/azure.json +1 -1
  114. package/dist/providers/data/baseten.json +1 -1
  115. package/dist/providers/data/cerebras.json +1 -1
  116. package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  117. package/dist/providers/data/cloudflare-workers-ai.json +1 -1
  118. package/dist/providers/data/fireworks.json +1 -1
  119. package/dist/providers/data/github-copilot.json +1 -1
  120. package/dist/providers/data/google-vertex.json +1 -1
  121. package/dist/providers/data/google.json +1 -1
  122. package/dist/providers/data/groq.json +1 -1
  123. package/dist/providers/data/huggingface.json +1 -1
  124. package/dist/providers/data/kimi-coding.json +1 -1
  125. package/dist/providers/data/meta.json +1 -1
  126. package/dist/providers/data/minimax-cn.json +1 -1
  127. package/dist/providers/data/minimax.json +1 -1
  128. package/dist/providers/data/mistral.json +1 -1
  129. package/dist/providers/data/moonshotai-cn.json +1 -1
  130. package/dist/providers/data/moonshotai.json +1 -1
  131. package/dist/providers/data/nvidia.json +1 -1
  132. package/dist/providers/data/openai-codex.json +1 -1
  133. package/dist/providers/data/openai.json +1 -1
  134. package/dist/providers/data/opencode-go.json +1 -1
  135. package/dist/providers/data/opencode.json +1 -1
  136. package/dist/providers/data/openrouter.json +1 -1
  137. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  138. package/dist/providers/data/qwen-token-plan.json +1 -1
  139. package/dist/providers/data/radius.json +1 -1
  140. package/dist/providers/data/together.json +1 -1
  141. package/dist/providers/data/typesafe.json +1 -1
  142. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  143. package/dist/providers/data/xai.json +1 -1
  144. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  145. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  146. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  147. package/dist/providers/data/xiaomi.json +1 -1
  148. package/dist/providers/data/zai-coding-cn.json +1 -1
  149. package/dist/providers/faux.d.ts.map +1 -1
  150. package/dist/providers/faux.js +31 -9
  151. package/dist/providers/faux.js.map +1 -1
  152. package/dist/providers/kimi-coding.d.ts +1 -1
  153. package/dist/providers/kimi-coding.js +3 -3
  154. package/dist/providers/kimi-coding.js.map +1 -1
  155. package/dist/providers/model-schema.d.ts +91 -0
  156. package/dist/providers/model-schema.d.ts.map +1 -0
  157. package/dist/providers/model-schema.js +57 -0
  158. package/dist/providers/model-schema.js.map +1 -0
  159. package/dist/providers/openai.d.ts.map +1 -1
  160. package/dist/providers/openai.js +12 -3
  161. package/dist/providers/openai.js.map +1 -1
  162. package/dist/providers/opencode-go.d.ts +3 -1
  163. package/dist/providers/opencode-go.d.ts.map +1 -1
  164. package/dist/providers/opencode-go.js +2 -0
  165. package/dist/providers/opencode-go.js.map +1 -1
  166. package/dist/providers/openrouter-api.d.ts +40 -0
  167. package/dist/providers/openrouter-api.d.ts.map +1 -0
  168. package/dist/providers/openrouter-api.js +41 -0
  169. package/dist/providers/openrouter-api.js.map +1 -0
  170. package/dist/providers/openrouter.d.ts +11 -1
  171. package/dist/providers/openrouter.d.ts.map +1 -1
  172. package/dist/providers/openrouter.js +52 -1
  173. package/dist/providers/openrouter.js.map +1 -1
  174. package/dist/providers/radius-config.d.ts.map +1 -1
  175. package/dist/providers/radius-config.js +2 -1
  176. package/dist/providers/radius-config.js.map +1 -1
  177. package/dist/providers/radius.d.ts.map +1 -1
  178. package/dist/providers/radius.js +4 -12
  179. package/dist/providers/radius.js.map +1 -1
  180. package/dist/telemetry.d.ts +288 -0
  181. package/dist/telemetry.d.ts.map +1 -0
  182. package/dist/telemetry.js +192 -0
  183. package/dist/telemetry.js.map +1 -0
  184. package/dist/types.d.ts +44 -307
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js.map +1 -1
  187. package/dist/utils/error-body.d.ts.map +1 -1
  188. package/dist/utils/error-body.js +2 -1
  189. package/dist/utils/error-body.js.map +1 -1
  190. package/dist/utils/estimate.js +1 -1
  191. package/dist/utils/estimate.js.map +1 -1
  192. package/dist/utils/event-stream.d.ts +10 -1
  193. package/dist/utils/event-stream.d.ts.map +1 -1
  194. package/dist/utils/event-stream.js +25 -0
  195. package/dist/utils/event-stream.js.map +1 -1
  196. package/dist/utils/identity.d.ts +65 -0
  197. package/dist/utils/identity.d.ts.map +1 -0
  198. package/dist/utils/identity.js +141 -0
  199. package/dist/utils/identity.js.map +1 -0
  200. package/dist/utils/json-parse.d.ts +10 -0
  201. package/dist/utils/json-parse.d.ts.map +1 -1
  202. package/dist/utils/json-parse.js +26 -1
  203. package/dist/utils/json-parse.js.map +1 -1
  204. package/dist/utils/model-operations.d.ts +3 -1
  205. package/dist/utils/model-operations.d.ts.map +1 -1
  206. package/dist/utils/model-operations.js +6 -0
  207. package/dist/utils/model-operations.js.map +1 -1
  208. package/dist/utils/openrouter-cost.d.ts +24 -0
  209. package/dist/utils/openrouter-cost.d.ts.map +1 -0
  210. package/dist/utils/openrouter-cost.js +34 -0
  211. package/dist/utils/openrouter-cost.js.map +1 -0
  212. package/dist/utils/overflow.d.ts +1 -0
  213. package/dist/utils/overflow.d.ts.map +1 -1
  214. package/dist/utils/overflow.js +6 -1
  215. package/dist/utils/overflow.js.map +1 -1
  216. package/dist/utils/provider-retry.d.ts +2 -0
  217. package/dist/utils/provider-retry.d.ts.map +1 -1
  218. package/dist/utils/provider-retry.js +2 -0
  219. package/dist/utils/provider-retry.js.map +1 -1
  220. package/dist/utils/retry.d.ts.map +1 -1
  221. package/dist/utils/retry.js +26 -10
  222. package/dist/utils/retry.js.map +1 -1
  223. package/dist/utils/streaming-json.d.ts +84 -0
  224. package/dist/utils/streaming-json.d.ts.map +1 -0
  225. package/dist/utils/streaming-json.js +513 -0
  226. package/dist/utils/streaming-json.js.map +1 -0
  227. package/dist/utils/text.d.ts +7 -0
  228. package/dist/utils/text.d.ts.map +1 -1
  229. package/dist/utils/text.js +9 -0
  230. package/dist/utils/text.js.map +1 -1
  231. package/dist/utils/transcript.d.ts +22 -8
  232. package/dist/utils/transcript.d.ts.map +1 -1
  233. package/dist/utils/transcript.js +29 -18
  234. package/dist/utils/transcript.js.map +1 -1
  235. package/dist/utils/validation.d.ts.map +1 -1
  236. package/dist/utils/validation.js +3 -0
  237. package/dist/utils/validation.js.map +1 -1
  238. package/dist/utils/version.d.ts +2 -0
  239. package/dist/utils/version.d.ts.map +1 -0
  240. package/dist/utils/version.js +3 -0
  241. package/dist/utils/version.js.map +1 -0
  242. package/package.json +3 -3
  243. package/dist/utils/assistant-message-frame.d.ts +0 -77
  244. package/dist/utils/assistant-message-frame.d.ts.map +0 -1
  245. package/dist/utils/assistant-message-frame.js +0 -425
  246. package/dist/utils/assistant-message-frame.js.map +0 -1
  247. package/dist/utils/pi-user-agent.d.ts +0 -2
  248. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  249. package/dist/utils/pi-user-agent.js +0 -12
  250. package/dist/utils/pi-user-agent.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,SAAS,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC;AAC7E,MAAM,aAAa,GAAG,mCAAmC,CAAC;AAC1D,MAAM,SAAS,GAAG,4CAA4C,CAAC;AAC/D,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,YAAY,GAAG,oBAAoB,aAAa,GAAG,aAA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AAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst COPY_CODE_REDIRECT_URI = \"https://platform.claude.com/oauth/code/callback\";\nconst ANTHROPIC_BROWSER_LOGIN_METHOD = \"browser\";\nconst ANTHROPIC_COPY_CODE_LOGIN_METHOD = \"copy_code\";\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\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 formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function postJson(url: string, body: Record<string, string | number>, signal: AbortSignal): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tstate,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Anthropic\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate: verifier,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tlet state = verifier;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\nasync function loginAnthropicCopyCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst authParams = new URLSearchParams({\n\t\tcode: \"true\",\n\t\tclient_id: CLIENT_ID,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: COPY_CODE_REDIRECT_URI,\n\t\tscope: SCOPES,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tstate: verifier,\n\t});\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\tinstructions: \"Complete login in your browser, then copy the code Anthropic shows and paste it here.\",\n\t});\n\n\tconst input = await interaction.prompt({\n\t\ttype: \"manual_code\",\n\t\tmessage: \"Paste the code Anthropic shows after you sign in:\",\n\t\tplaceholder: \"code#state\",\n\t\tsignal: interaction.signal,\n\t});\n\tconst parsed = parseAuthorizationInput(input);\n\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\tif (!parsed.code) throw new Error(\"Missing authorization code\");\n\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\treturn await exchangeAuthorizationCode(\n\t\tparsed.code,\n\t\tparsed.state ?? verifier,\n\t\tverifier,\n\t\tCOPY_CODE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select Anthropic login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: ANTHROPIC_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: ANTHROPIC_COPY_CODE_LOGIN_METHOD, label: \"Copy code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === ANTHROPIC_COPY_CODE_LOGIN_METHOD) {\n\t\t\treturn loginAnthropicCopyCode(interaction);\n\t\t}\n\t\tif (method !== ANTHROPIC_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown Anthropic login method: ${method}`);\n\t\t}\n\n\t\treturn loginAnthropic(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,SAAS,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC;AAC7E,MAAM,aAAa,GAAG,mCAAmC,CAAC;AAC1D,MAAM,SAAS,GAAG,4CAA4C,CAAC;AAC/D,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,2GAA2G;AAC3G,6EAA6E;AAC7E,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,YAAY,GAAG,oBAAoB,aAAa,GAAG,aAAa,EAAE,CAAC;AACzE,MAAM,sBAAsB,GAAG,iDAAiD,CAAC;AACjF,MAAM,8BAA8B,GAAG,SAAS,CAAC;AACjD,MAAM,gCAAgC,GAAG,WAAW,CAAC;AACrD,MAAM,MAAM,GACX,4GAA4G,CAAC;AAE9G,SAAS,uBAAu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,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n// Preferred so the port can be forwarded into containers or over SSH. Anthropic accepts any loopback port,\n// so login falls back to a free port when this one cannot be bound (#10571).\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst COPY_CODE_REDIRECT_URI = \"https://platform.claude.com/oauth/code/callback\";\nconst ANTHROPIC_BROWSER_LOGIN_METHOD = \"browser\";\nconst ANTHROPIC_COPY_CODE_LOGIN_METHOD = \"copy_code\";\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\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 formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function postJson(url: string, body: Record<string, string | number>, signal: AbortSignal): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tstate,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst startCallbackServer = (port: number) =>\n\t\tstartOAuthCallbackServer({\n\t\t\tproviderName: \"Anthropic\",\n\t\t\thost: CALLBACK_HOST,\n\t\t\tport,\n\t\t\tpath: CALLBACK_PATH,\n\t\t\tredirectHost: \"localhost\",\n\t\t\tstate: verifier,\n\t\t\tcomplete: async (code) => code,\n\t\t\tsignal: interaction.signal,\n\t\t});\n\t// Without a callback server, login continues with the pasted redirect URL.\n\tconst callback = await startCallbackServer(CALLBACK_PORT)\n\t\t.catch(() => startCallbackServer(0))\n\t\t.catch(() => undefined);\n\tconst redirectUri = callback?.redirectUri ?? REDIRECT_URI;\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: redirectUri,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: redirectUri,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tlet state = verifier;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(code, state, verifier, redirectUri, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\nasync function loginAnthropicCopyCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst authParams = new URLSearchParams({\n\t\tcode: \"true\",\n\t\tclient_id: CLIENT_ID,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: COPY_CODE_REDIRECT_URI,\n\t\tscope: SCOPES,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tstate: verifier,\n\t});\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\tinstructions: \"Complete login in your browser, then copy the code Anthropic shows and paste it here.\",\n\t});\n\n\tconst input = await interaction.prompt({\n\t\ttype: \"manual_code\",\n\t\tmessage: \"Paste the code Anthropic shows after you sign in:\",\n\t\tplaceholder: \"code#state\",\n\t\tsignal: interaction.signal,\n\t});\n\tconst parsed = parseAuthorizationInput(input);\n\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\tif (!parsed.code) throw new Error(\"Missing authorization code\");\n\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\treturn await exchangeAuthorizationCode(\n\t\tparsed.code,\n\t\tparsed.state ?? verifier,\n\t\tverifier,\n\t\tCOPY_CODE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select Anthropic login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: ANTHROPIC_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: ANTHROPIC_COPY_CODE_LOGIN_METHOD, label: \"Copy code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === ANTHROPIC_COPY_CODE_LOGIN_METHOD) {\n\t\t\treturn loginAnthropicCopyCode(interaction);\n\t\t}\n\t\tif (method !== ANTHROPIC_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown Anthropic login method: ${method}`);\n\t\t}\n\n\t\treturn loginAnthropic(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -204,7 +204,7 @@ async function loginOpenAIChatGPT(interaction, options) {
204
204
  const authorizationUrl = new URL(AUTHORIZE_URL);
205
205
  authorizationUrl.search = new URLSearchParams({
206
206
  client_id: DYNAMIC_CLIENT_ID,
207
- agent_name_hint: AGENT_NAME_HINT,
207
+ agent_name_hint: options?.agentName ?? AGENT_NAME_HINT,
208
208
  ext_agent_host_id: hostId,
209
209
  response_type: "code",
210
210
  redirect_uri: REDIRECT_URI,
@@ -1 +1 @@
1
- {"version":3,"file":"openai-chatgpt.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAA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,KAAK,EAAE,CAAC;QAChB,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACnE,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,WAAW,CAAC,KAAK,EAAE,CAAC;QACpB,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,yFAAyF;QACzF,wFAAwF;QACxF,0FAA0F;QAC1F,0FAA0F;QAC1F,sFAAsF;QACtF,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;IACvC,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC5C,IAAI,EAAE,+BAA+B;IACrC,cAAc,EAAE,IAAI;IACpB,UAAU,EAAE,sBAAsB;IAClC,KAAK,EAAE,kBAAkB;IACzB,OAAO,EAAE,kBAAkB;IAC3B,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Responses API token sharing through Sign in with ChatGPT.\n *\n * This public-client flow uses no client secret and sends the resulting user\n * access token directly to api.openai.com.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"../../utils/oauth-page.ts\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\n// every login registers a new client with this ID; OpenAI returns the issued client ID in the callback\nconst DYNAMIC_CLIENT_ID = \"dynamic_agent_client\";\nconst AGENT_NAME_HINT = \"Pi\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst AUTHORIZE_URL = \"https://auth.openai.com/api/accounts/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/api/accounts/oauth/token\";\nconst RESOURCE = \"https://api.openai.com/v1\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 1455;\nconst CALLBACK_PATH = \"/auth/callback\";\nconst REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst DIRECT_TOKEN_SCOPE = \"chatgpt.tokens.use.direct\";\nconst SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;\n// Refresh this long before the real expiry so a request never starts with a token about to expire.\nconst EXPIRY_MARGIN_MS = 3 * 60 * 1000;\n\ntype AuthorizationResult = {\n\tcode: string;\n\tclientId: string;\n};\n\ntype CallbackServer = {\n\tserver: Server;\n\tresult: Promise<AuthorizationResult>;\n};\n\ntype TokenResponse = {\n\taccess_token?: unknown;\n\trefresh_token?: unknown;\n\texpires_in?: unknown;\n\tid_token?: unknown;\n\tscope?: unknown;\n};\n\nfunction randomValue(): string {\n\treturn randomBytes(32).toString(\"base64url\");\n}\n\nfunction authorizationResultFromCallback(url: URL, expectedState: string): AuthorizationResult {\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"Missing authorization code\");\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state) throw new Error(\"Missing OAuth state\");\n\tif (state !== expectedState) throw new Error(\"OAuth state mismatch\");\n\tconst clientId = url.searchParams.get(\"client_id\")?.trim();\n\tif (!clientId) throw new Error(\"OpenAI OAuth registration callback did not contain an issued client ID\");\n\treturn { code, clientId };\n}\n\nfunction authorizationResultFromManualInput(input: string, expectedState: string): AuthorizationResult {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Paste the full callback URL from the browser\");\n\t}\n\tconst expected = new URL(REDIRECT_URI);\n\tif (url.origin !== expected.origin || url.pathname !== expected.pathname) {\n\t\tthrow new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(`ChatGPT authorization failed: ${error}`);\n\treturn authorizationResultFromCallback(url, expectedState);\n}\n\nfunction sendHtml(response: ServerResponse, status: number, body: string): void {\n\tresponse.writeHead(status, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\tresponse.end(body);\n}\n\nfunction startCallbackServer(expectedState: string): Promise<CallbackServer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet resolveResult!: (result: AuthorizationResult) => void;\n\t\tlet rejectResult!: (error: Error) => void;\n\t\tconst result = new Promise<AuthorizationResult>((resolveAuthorization, rejectAuthorization) => {\n\t\t\tresolveResult = resolveAuthorization;\n\t\t\trejectResult = rejectAuthorization;\n\t\t});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(request.url || \"\", REDIRECT_URI);\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\t\t\t\tif (error) {\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"ChatGPT was not connected.\", `Error: ${error}`));\n\t\t\t\t\trejectResult(new Error(`ChatGPT authorization failed: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet authorizationResult: AuthorizationResult;\n\t\t\t\ttry {\n\t\t\t\t\tauthorizationResult = authorizationResultFromCallback(url, expectedState);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Invalid callback\";\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(message));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"ChatGPT authentication completed. You can close this window.\"));\n\t\t\t\tresolveResult(authorizationResult);\n\t\t\t} catch {\n\t\t\t\tsendHtml(response, 500, oauthErrorHtml(\"Internal error while processing the callback.\"));\n\t\t\t}\n\t\t});\n\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tserver.on(\"error\", rejectResult);\n\t\t\tresolve({ server, result });\n\t\t});\n\t});\n}\n\nasync function requestToken(body: URLSearchParams, signal: AbortSignal): Promise<TokenResponse> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\taccept: \"application/json\",\n\t\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\t},\n\t\tbody,\n\t\tsignal,\n\t});\n\tif (!response.ok) {\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\tthrow new Error(\"OpenAI OAuth token response must be an object\");\n\t}\n\treturn data as TokenResponse;\n}\n\nfunction requireTokenString(value: unknown, field: \"access_token\" | \"refresh_token\" | \"scope\"): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`OpenAI OAuth token response has invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction credentialFromTokenResponse(token: TokenResponse, clientId: string): OAuthCredential {\n\tconst access = requireTokenString(token.access_token, \"access_token\");\n\tconst refresh = requireTokenString(token.refresh_token, \"refresh_token\");\n\tconst scope = requireTokenString(token.scope, \"scope\");\n\tif (typeof token.expires_in !== \"number\" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response has invalid expires_in\");\n\t}\n\tconst scopes = scope.trim().split(/\\s+/).filter(Boolean);\n\tif (!scopes.includes(DIRECT_TOKEN_SCOPE)) {\n\t\tthrow new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);\n\t}\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,\n\t\tclientId,\n\t\tscopes,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tclientId: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: clientId,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\t// Pi does not use the ID token to identify the user or read profile data.\n\t// Keep the presence check as part of the token-response contract.\n\tif (typeof token.id_token !== \"string\" || token.id_token.trim().length === 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response did not contain an ID token\");\n\t}\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nasync function refreshAccessToken(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst clientId = credential.clientId;\n\tif (typeof clientId !== \"string\" || clientId.trim().length === 0) {\n\t\tthrow new Error(\"Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT\");\n\t}\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: clientId,\n\t\t\trefresh_token: credential.refresh,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\n/** OpenAI identifies each installation (\"agent host\") by a stable URI such as `urn:uuid:<uuid>`. */\nfunction agentHostId(deviceId: string | undefined): string {\n\tif (!deviceId || !UUID_PATTERN.test(deviceId)) {\n\t\tthrow new Error(\"Sign in with ChatGPT requires a device ID (UUID) for this installation\");\n\t}\n\treturn `urn:uuid:${deviceId.toLowerCase()}`;\n}\n\nasync function loginOpenAIChatGPT(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst hostId = agentHostId(options?.getDeviceId?.());\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = randomValue();\n\tconst nonce = randomValue();\n\t// Without this server, the browser's callback would reach whatever else holds the port (another\n\t// pending login or the Codex CLI), which rejects it as a state mismatch. Fail with a clear error instead.\n\tconst callback = await startCallbackServer(state).catch((error: unknown) => {\n\t\tif (!(error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\")) throw error;\n\t\tthrow new Error(\n\t\t\t`Port ${CALLBACK_PORT} is in use, probably by an unfinished login in another pi session or by the Codex CLI. Cancel that login and try again.`,\n\t\t);\n\t});\n\n\tconst authorizationUrl = new URL(AUTHORIZE_URL);\n\tauthorizationUrl.search = new URLSearchParams({\n\t\tclient_id: DYNAMIC_CLIENT_ID,\n\t\tagent_name_hint: AGENT_NAME_HINT,\n\t\text_agent_host_id: hostId,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: REDIRECT_URI,\n\t\tresource: RESOURCE,\n\t\tscope: SCOPE,\n\t\tstate,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tnonce,\n\t}).toString();\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizationUrl.toString(),\n\t\tinstructions:\n\t\t\t\"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.\",\n\t});\n\n\tconst manualAbort = new AbortController();\n\tconst manualCode = interaction\n\t\t.prompt({\n\t\t\ttype: \"manual_code\",\n\t\t\tmessage: \"Complete login in your browser, or paste the final redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t\tsignal: AbortSignal.any([manualAbort.signal, interaction.signal]),\n\t\t})\n\t\t.then((input) => authorizationResultFromManualInput(input, state));\n\n\ttry {\n\t\tconst result = await Promise.race([callback.result, manualCode]);\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);\n\t} catch (error) {\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow error;\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback.server.close();\n\t\t// close() only stops accepting new connections. Browsers open spare connections ahead of\n\t\t// time, and one that has not sent a request yet stays open and attached to this server.\n\t\t// A later login in the same process starts a new server with a new state, but the browser\n\t\t// may send that login's callback over the spare connection. This server would then handle\n\t\t// it and reject it with \"OAuth state mismatch\", and the new login would never see it.\n\t\tcallback.server.closeAllConnections();\n\t}\n}\n\nexport const openaiChatGPTOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with ChatGPT\",\n\tlogin: loginOpenAIChatGPT,\n\trefresh: refreshAccessToken,\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"openai-chatgpt.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,uGAAuG;AACvG,MAAM,iBAAiB,GAAG,sBAAsB,CAAC;AACjD,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,MAAM,YAAY,GAAG,iEAAiE,CAAC;AACvF,MAAM,aAAa,G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MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,yFAAyF;QACzF,wFAAwF;QACxF,0FAA0F;QAC1F,0FAA0F;QAC1F,sFAAsF;QACtF,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;IACvC,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC5C,IAAI,EAAE,+BAA+B;IACrC,cAAc,EAAE,IAAI;IACpB,UAAU,EAAE,sBAAsB;IAClC,KAAK,EAAE,kBAAkB;IACzB,OAAO,EAAE,kBAAkB;IAC3B,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Responses API token sharing through Sign in with ChatGPT.\n *\n * This public-client flow uses no client secret and sends the resulting user\n * access token directly to api.openai.com.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"../../utils/oauth-page.ts\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\n// every login registers a new client with this ID; OpenAI returns the issued client ID in the callback\nconst DYNAMIC_CLIENT_ID = \"dynamic_agent_client\";\nconst AGENT_NAME_HINT = \"Pi\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst AUTHORIZE_URL = \"https://auth.openai.com/api/accounts/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/api/accounts/oauth/token\";\nconst RESOURCE = \"https://api.openai.com/v1\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 1455;\nconst CALLBACK_PATH = \"/auth/callback\";\nconst REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst DIRECT_TOKEN_SCOPE = \"chatgpt.tokens.use.direct\";\nconst SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;\n// Refresh this long before the real expiry so a request never starts with a token about to expire.\nconst EXPIRY_MARGIN_MS = 3 * 60 * 1000;\n\ntype AuthorizationResult = {\n\tcode: string;\n\tclientId: string;\n};\n\ntype CallbackServer = {\n\tserver: Server;\n\tresult: Promise<AuthorizationResult>;\n};\n\ntype TokenResponse = {\n\taccess_token?: unknown;\n\trefresh_token?: unknown;\n\texpires_in?: unknown;\n\tid_token?: unknown;\n\tscope?: unknown;\n};\n\nfunction randomValue(): string {\n\treturn randomBytes(32).toString(\"base64url\");\n}\n\nfunction authorizationResultFromCallback(url: URL, expectedState: string): AuthorizationResult {\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"Missing authorization code\");\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state) throw new Error(\"Missing OAuth state\");\n\tif (state !== expectedState) throw new Error(\"OAuth state mismatch\");\n\tconst clientId = url.searchParams.get(\"client_id\")?.trim();\n\tif (!clientId) throw new Error(\"OpenAI OAuth registration callback did not contain an issued client ID\");\n\treturn { code, clientId };\n}\n\nfunction authorizationResultFromManualInput(input: string, expectedState: string): AuthorizationResult {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Paste the full callback URL from the browser\");\n\t}\n\tconst expected = new URL(REDIRECT_URI);\n\tif (url.origin !== expected.origin || url.pathname !== expected.pathname) {\n\t\tthrow new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(`ChatGPT authorization failed: ${error}`);\n\treturn authorizationResultFromCallback(url, expectedState);\n}\n\nfunction sendHtml(response: ServerResponse, status: number, body: string): void {\n\tresponse.writeHead(status, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\tresponse.end(body);\n}\n\nfunction startCallbackServer(expectedState: string): Promise<CallbackServer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet resolveResult!: (result: AuthorizationResult) => void;\n\t\tlet rejectResult!: (error: Error) => void;\n\t\tconst result = new Promise<AuthorizationResult>((resolveAuthorization, rejectAuthorization) => {\n\t\t\tresolveResult = resolveAuthorization;\n\t\t\trejectResult = rejectAuthorization;\n\t\t});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(request.url || \"\", REDIRECT_URI);\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\t\t\t\tif (error) {\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"ChatGPT was not connected.\", `Error: ${error}`));\n\t\t\t\t\trejectResult(new Error(`ChatGPT authorization failed: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet authorizationResult: AuthorizationResult;\n\t\t\t\ttry {\n\t\t\t\t\tauthorizationResult = authorizationResultFromCallback(url, expectedState);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Invalid callback\";\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(message));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"ChatGPT authentication completed. You can close this window.\"));\n\t\t\t\tresolveResult(authorizationResult);\n\t\t\t} catch {\n\t\t\t\tsendHtml(response, 500, oauthErrorHtml(\"Internal error while processing the callback.\"));\n\t\t\t}\n\t\t});\n\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tserver.on(\"error\", rejectResult);\n\t\t\tresolve({ server, result });\n\t\t});\n\t});\n}\n\nasync function requestToken(body: URLSearchParams, signal: AbortSignal): Promise<TokenResponse> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\taccept: \"application/json\",\n\t\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\t},\n\t\tbody,\n\t\tsignal,\n\t});\n\tif (!response.ok) {\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\tthrow new Error(\"OpenAI OAuth token response must be an object\");\n\t}\n\treturn data as TokenResponse;\n}\n\nfunction requireTokenString(value: unknown, field: \"access_token\" | \"refresh_token\" | \"scope\"): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`OpenAI OAuth token response has invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction credentialFromTokenResponse(token: TokenResponse, clientId: string): OAuthCredential {\n\tconst access = requireTokenString(token.access_token, \"access_token\");\n\tconst refresh = requireTokenString(token.refresh_token, \"refresh_token\");\n\tconst scope = requireTokenString(token.scope, \"scope\");\n\tif (typeof token.expires_in !== \"number\" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response has invalid expires_in\");\n\t}\n\tconst scopes = scope.trim().split(/\\s+/).filter(Boolean);\n\tif (!scopes.includes(DIRECT_TOKEN_SCOPE)) {\n\t\tthrow new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);\n\t}\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,\n\t\tclientId,\n\t\tscopes,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tclientId: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: clientId,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\t// Pi does not use the ID token to identify the user or read profile data.\n\t// Keep the presence check as part of the token-response contract.\n\tif (typeof token.id_token !== \"string\" || token.id_token.trim().length === 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response did not contain an ID token\");\n\t}\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nasync function refreshAccessToken(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst clientId = credential.clientId;\n\tif (typeof clientId !== \"string\" || clientId.trim().length === 0) {\n\t\tthrow new Error(\"Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT\");\n\t}\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: clientId,\n\t\t\trefresh_token: credential.refresh,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\n/** OpenAI identifies each installation (\"agent host\") by a stable URI such as `urn:uuid:<uuid>`. */\nfunction agentHostId(deviceId: string | undefined): string {\n\tif (!deviceId || !UUID_PATTERN.test(deviceId)) {\n\t\tthrow new Error(\"Sign in with ChatGPT requires a device ID (UUID) for this installation\");\n\t}\n\treturn `urn:uuid:${deviceId.toLowerCase()}`;\n}\n\nasync function loginOpenAIChatGPT(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst hostId = agentHostId(options?.getDeviceId?.());\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = randomValue();\n\tconst nonce = randomValue();\n\t// Without this server, the browser's callback would reach whatever else holds the port (another\n\t// pending login or the Codex CLI), which rejects it as a state mismatch. Fail with a clear error instead.\n\tconst callback = await startCallbackServer(state).catch((error: unknown) => {\n\t\tif (!(error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\")) throw error;\n\t\tthrow new Error(\n\t\t\t`Port ${CALLBACK_PORT} is in use, probably by an unfinished login in another pi session or by the Codex CLI. Cancel that login and try again.`,\n\t\t);\n\t});\n\n\tconst authorizationUrl = new URL(AUTHORIZE_URL);\n\tauthorizationUrl.search = new URLSearchParams({\n\t\tclient_id: DYNAMIC_CLIENT_ID,\n\t\tagent_name_hint: options?.agentName ?? AGENT_NAME_HINT,\n\t\text_agent_host_id: hostId,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: REDIRECT_URI,\n\t\tresource: RESOURCE,\n\t\tscope: SCOPE,\n\t\tstate,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tnonce,\n\t}).toString();\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizationUrl.toString(),\n\t\tinstructions:\n\t\t\t\"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.\",\n\t});\n\n\tconst manualAbort = new AbortController();\n\tconst manualCode = interaction\n\t\t.prompt({\n\t\t\ttype: \"manual_code\",\n\t\t\tmessage: \"Complete login in your browser, or paste the final redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t\tsignal: AbortSignal.any([manualAbort.signal, interaction.signal]),\n\t\t})\n\t\t.then((input) => authorizationResultFromManualInput(input, state));\n\n\ttry {\n\t\tconst result = await Promise.race([callback.result, manualCode]);\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);\n\t} catch (error) {\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow error;\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback.server.close();\n\t\t// close() only stops accepting new connections. Browsers open spare connections ahead of\n\t\t// time, and one that has not sent a request yet stays open and attached to this server.\n\t\t// A later login in the same process starts a new server with a new state, but the browser\n\t\t// may send that login's callback over the spare connection. This server would then handle\n\t\t// it and reject it with \"OAuth state mismatch\", and the new login would never see it.\n\t\tcallback.server.closeAllConnections();\n\t}\n}\n\nexport const openaiChatGPTOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with ChatGPT\",\n\tlogin: loginOpenAIChatGPT,\n\trefresh: refreshAccessToken,\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA4cvF,eAAO,MAAM,gBAAgB,EAAE,SA6B9B,CAAC"}
1
+ {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAgB,SAAS,EAA4C,MAAM,aAAa,CAAC;AA+crG,eAAO,MAAM,gBAAgB,EAAE,SA6B9B,CAAC"}
@@ -315,8 +315,8 @@ async function loginOpenAICodexDeviceCode(interaction) {
315
315
  const code = await pollOpenAICodexDeviceAuth(device, interaction.signal);
316
316
  return exchangeAuthorizationCodeForCredentials(code.authorizationCode, code.codeVerifier, DEVICE_REDIRECT_URI, interaction.signal);
317
317
  }
318
- async function loginOpenAICodex(interaction) {
319
- const { verifier, state, url } = await createAuthorizationFlow();
318
+ async function loginOpenAICodex(interaction, options) {
319
+ const { verifier, state, url } = await createAuthorizationFlow(options?.agentName);
320
320
  // Port 1455 is shared with the Codex CLI; when it is taken, fall back to the pasted redirect URL.
321
321
  const callback = await startOAuthCallbackServer({
322
322
  providerName: "OpenAI",
@@ -371,7 +371,7 @@ async function refreshOpenAICodexToken(refreshToken, signal) {
371
371
  export const openaiCodexOAuth = {
372
372
  name: "OpenAI (ChatGPT Plus/Pro)",
373
373
  isSubscription: true,
374
- async login(interaction) {
374
+ async login(interaction, options) {
375
375
  const method = await interaction.prompt({
376
376
  type: "select",
377
377
  message: "Select OpenAI Codex login method:",
@@ -386,7 +386,7 @@ export const openaiCodexOAuth = {
386
386
  if (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {
387
387
  throw new Error(`Unknown OpenAI Codex login method: ${method}`);
388
388
  }
389
- return loginOpenAICodex(interaction);
389
+ return loginOpenAICodex(interaction, options);
390
390
  },
391
391
  refresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),
392
392
  async toAuth(credential) {
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,kEAAkE;AAClE,IAAI,YAAY,GAAoD,IAAI,CAAC;AACzE,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;IACzF,MAAM,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;QAChC,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9B,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,O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;QAChD,CAAC;QACD,IAAI,MAAM,KAAK,iCAAiC,EAAE,CAAC;YAClD,MAAM,IAAI,KAAK,CAAC,sCAAsC,MAAM,EAAE,CAAC,CAAC;QACjE,CAAC;QAED,OAAO,gBAAgB,CAAC,WAAW,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAEpF,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http (via callback-server.ts) 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;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:crypto\").then((m) => {\n\t\t_randomBytes = m.randomBytes;\n\t});\n}\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { OpenAICodexOAuthRefreshError } from \"./openai-codex-errors.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTH_BASE_URL = \"https://auth.openai.com\";\nconst AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;\nconst TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;\nconst DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nconst OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = \"device_code\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\n\ntype OAuthToken = { access: string; refresh: string; expires: number };\ntype TokenOperation = \"exchange\" | \"refresh\";\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype DeviceAuthInfo = {\n\tdeviceAuthId: string;\n\tuserCode: string;\n\tintervalSeconds: number;\n};\n\ntype DeviceTokenSuccess = {\n\tauthorizationCode: string;\n\tcodeVerifier: string;\n};\n\ntype JwtPayload = {\n\t[JWT_CLAIM_PATH]?: {\n\t\tchatgpt_account_id?: string;\n\t};\n\t[key: string]: unknown;\n};\n\nfunction createState(): string {\n\tif (!_randomBytes) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\treturn _randomBytes(16).toString(\"hex\");\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) return null;\n\t\tconst payload = parts[1] ?? \"\";\n\t\tconst decoded = atob(payload);\n\t\treturn JSON.parse(decoded) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function fetchWithLoginCancellation(input: string, init: RequestInit): Promise<Response> {\n\ttry {\n\t\treturn await fetch(input, init);\n\t} catch (error) {\n\t\tif (init.signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function readTokenResponse(response: Response, operation: TokenOperation): Promise<OAuthToken> {\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\taccess_token?: string;\n\t\trefresh_token?: string;\n\t\texpires_in?: number;\n\t} | null;\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\taccess: json.access_token,\n\t\trefresh: json.refresh_token,\n\t\texpires: Date.now() + json.expires_in * 1000,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthToken> {\n\tconst response = await fetchWithLoginCancellation(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: redirectUri,\n\t\t}),\n\t\tsignal,\n\t});\n\n\treturn readTokenResponse(response, \"exchange\");\n}\n\nasync function readRefreshErrorCode(response: Response): Promise<string | undefined> {\n\ttry {\n\t\tconst json = (await response.json()) as {\n\t\t\terror?: string | { code?: unknown; type?: unknown };\n\t\t} | null;\n\t\tif (typeof json?.error === \"string\") return json.error;\n\t\tif (json?.error && typeof json.error === \"object\") {\n\t\t\tif (typeof json.error.code === \"string\") return json.error.code;\n\t\t\tif (typeof json.error.type === \"string\") return json.error.type;\n\t\t}\n\t} catch {}\n\treturn undefined;\n}\n\nasync function refreshAccessToken(refreshToken: string, signal: AbortSignal): Promise<OAuthToken> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t}),\n\t\t\tsignal,\n\t\t});\n\t} catch {\n\t\tif (signal.aborted) {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\"aborted\", \"OpenAI Codex token refresh was cancelled\");\n\t\t}\n\t\tthrow new OpenAICodexOAuthRefreshError(\"transient\", \"OpenAI Codex token refresh request failed\");\n\t}\n\n\tif (!response.ok) {\n\t\tconst oauthCode = await readRefreshErrorCode(response);\n\t\tif (response.status === 401 || response.status === 403 || oauthCode === \"invalid_grant\") {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\t\"reauth_required\",\n\t\t\t\t\"OpenAI Codex authentication must be renewed\",\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\t\tif (response.status === 429 || response.status >= 500) {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\t\"transient\",\n\t\t\t\t\"OpenAI Codex token refresh is temporarily unavailable\",\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh was rejected\",\n\t\t\tresponse.status,\n\t\t);\n\t}\n\n\tlet json: { access_token?: string; refresh_token?: string; expires_in?: number } | null;\n\ttry {\n\t\tjson = (await response.json()) as typeof json;\n\t} catch {\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh returned invalid JSON\",\n\t\t\tresponse.status,\n\t\t);\n\t}\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh response was missing required fields\",\n\t\t\tresponse.status,\n\t\t);\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 startOpenAICodexDeviceAuth(signal: AbortSignal): Promise<DeviceAuthInfo> {\n\tconst response = await fetchWithLoginCancellation(DEVICE_USER_CODE_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({ client_id: CLIENT_ID }),\n\t\tsignal,\n\t});\n\n\tif (!response.ok) {\n\t\tif (response.status === 404) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.\",\n\t\t\t);\n\t\t}\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\tdevice_auth_id?: string;\n\t\tuser_code?: string;\n\t\tinterval?: number | string;\n\t} | null;\n\tconst intervalSeconds = typeof json?.interval === \"string\" ? Number(json.interval.trim()) : json?.interval;\n\tif (\n\t\t!json?.device_auth_id ||\n\t\t!json.user_code ||\n\t\ttypeof intervalSeconds !== \"number\" ||\n\t\t!Number.isFinite(intervalSeconds) ||\n\t\tintervalSeconds < 0\n\t) {\n\t\tthrow new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\tdeviceAuthId: json.device_auth_id,\n\t\tuserCode: json.user_code,\n\t\tintervalSeconds,\n\t};\n}\n\nasync function pollOpenAICodexDeviceAuth(device: DeviceAuthInfo, signal: AbortSignal): Promise<DeviceTokenSuccess> {\n\treturn pollOAuthDeviceCodeFlow<DeviceTokenSuccess>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await fetchWithLoginCancellation(DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tdevice_auth_id: device.deviceAuthId,\n\t\t\t\t\tuser_code: device.userCode,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tconst rawJson = await response.json();\n\t\t\t\tconst json = rawJson as { authorization_code?: string; code_verifier?: string } | null;\n\t\t\t\tif (!json?.authorization_code || !json.code_verifier) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tvalue: { authorizationCode: json.authorization_code, codeVerifier: json.code_verifier },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (response.status === 403 || response.status === 404) {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\n\t\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(responseBody) as { error?: string | { code?: string } } | null;\n\t\t\t\tconst error = json?.error;\n\t\t\t\terrorCode = typeof error === \"object\" ? error?.code : error;\n\t\t\t} catch {}\n\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (errorCode === \"slow_down\") {\n\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\nasync function createAuthorizationFlow(\n\toriginator: string = \"pi\",\n): Promise<{ verifier: string; state: string; url: string }> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = createState();\n\n\tconst url = new URL(AUTHORIZE_URL);\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", CLIENT_ID);\n\turl.searchParams.set(\"redirect_uri\", REDIRECT_URI);\n\turl.searchParams.set(\"scope\", SCOPE);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"state\", state);\n\turl.searchParams.set(\"id_token_add_organizations\", \"true\");\n\turl.searchParams.set(\"codex_cli_simplified_flow\", \"true\");\n\turl.searchParams.set(\"originator\", originator);\n\n\treturn { verifier, state, url: url.toString() };\n}\n\nfunction getAccountId(accessToken: string): string | null {\n\tconst payload = decodeJwt(accessToken);\n\tconst auth = payload?.[JWT_CLAIM_PATH];\n\tconst accountId = auth?.chatgpt_account_id;\n\treturn typeof accountId === \"string\" && accountId.length > 0 ? accountId : null;\n}\n\nfunction credentialsFromToken(token: OAuthToken): OAuthCredential {\n\tconst accountId = getAccountId(token.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: token.access,\n\t\trefresh: token.refresh,\n\t\texpires: token.expires,\n\t\taccountId,\n\t};\n}\n\nasync function exchangeAuthorizationCodeForCredentials(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\nasync function loginOpenAICodexDeviceCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await startOpenAICodexDeviceAuth(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: DEVICE_VERIFICATION_URI,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t});\n\tconst code = await pollOpenAICodexDeviceAuth(device, interaction.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\nasync function loginOpenAICodex(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, state, url } = await createAuthorizationFlow();\n\t// Port 1455 is shared with the Codex CLI; when it is taken, fall back to the pasted redirect URL.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenAI\",\n\t\thost: getCallbackHost(),\n\t\tport: 1455,\n\t\tpath: \"/auth/callback\",\n\t\tstate,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl,\n\t\tinstructions: \"A browser window should open. Complete login to finish.\",\n\t});\n\n\ttry {\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== state) throw new Error(\"State mismatch\");\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\treturn await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nasync function refreshOpenAICodexToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\ttry {\n\t\treturn credentialsFromToken(await refreshAccessToken(refreshToken, signal));\n\t} catch (error) {\n\t\tif (error instanceof OpenAICodexOAuthRefreshError) throw error;\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh returned an invalid credential\",\n\t\t);\n\t}\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select OpenAI Codex login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: \"Device code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode(interaction);\n\t\t}\n\t\tif (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${method}`);\n\t\t}\n\n\t\treturn loginOpenAICodex(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"openai-codex.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,kEAAkE;AAClE,IAAI,YAAY,GAAoD,IAAI,CAAC;AACzE,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;IACzF,MAAM,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;QAChC,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9B,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,SAAS,GAAG,8BAA8B,CAAC;AACjD,MAAM,aAAa,GAAG,yBAAyB,CAAC;AAChD,MAAM,aAAa,GAAG,GAAG,aAAa,kBAAkB,CAAC;AACzD,MAAM,SAAS,GAAG,GAAG,aAAa,cAAc,CAAC;AACjD,MAAM,YAAY,GAAG,qCAAqC,CAAC;AAC3D,MAAM,oBAAoB,GAAG,GAAG,aAAa,mCAAmC,CAAC;AACjF,MAAM,gBAAgB,GAAG,G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C,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http (via callback-server.ts) 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;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:crypto\").then((m) => {\n\t\t_randomBytes = m.randomBytes;\n\t});\n}\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { OpenAICodexOAuthRefreshError } from \"./openai-codex-errors.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTH_BASE_URL = \"https://auth.openai.com\";\nconst AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;\nconst TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;\nconst DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;\nconst DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;\nconst DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst OPENAI_CODEX_BROWSER_LOGIN_METHOD = \"browser\";\nconst OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = \"device_code\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\n\ntype OAuthToken = { access: string; refresh: string; expires: number };\ntype TokenOperation = \"exchange\" | \"refresh\";\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype DeviceAuthInfo = {\n\tdeviceAuthId: string;\n\tuserCode: string;\n\tintervalSeconds: number;\n};\n\ntype DeviceTokenSuccess = {\n\tauthorizationCode: string;\n\tcodeVerifier: string;\n};\n\ntype JwtPayload = {\n\t[JWT_CLAIM_PATH]?: {\n\t\tchatgpt_account_id?: string;\n\t};\n\t[key: string]: unknown;\n};\n\nfunction createState(): string {\n\tif (!_randomBytes) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\treturn _randomBytes(16).toString(\"hex\");\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) return null;\n\t\tconst payload = parts[1] ?? \"\";\n\t\tconst decoded = atob(payload);\n\t\treturn JSON.parse(decoded) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function fetchWithLoginCancellation(input: string, init: RequestInit): Promise<Response> {\n\ttry {\n\t\treturn await fetch(input, init);\n\t} catch (error) {\n\t\tif (init.signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function readTokenResponse(response: Response, operation: TokenOperation): Promise<OAuthToken> {\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\taccess_token?: string;\n\t\trefresh_token?: string;\n\t\texpires_in?: number;\n\t} | null;\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\taccess: json.access_token,\n\t\trefresh: json.refresh_token,\n\t\texpires: Date.now() + json.expires_in * 1000,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthToken> {\n\tconst response = await fetchWithLoginCancellation(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: redirectUri,\n\t\t}),\n\t\tsignal,\n\t});\n\n\treturn readTokenResponse(response, \"exchange\");\n}\n\nasync function readRefreshErrorCode(response: Response): Promise<string | undefined> {\n\ttry {\n\t\tconst json = (await response.json()) as {\n\t\t\terror?: string | { code?: unknown; type?: unknown };\n\t\t} | null;\n\t\tif (typeof json?.error === \"string\") return json.error;\n\t\tif (json?.error && typeof json.error === \"object\") {\n\t\t\tif (typeof json.error.code === \"string\") return json.error.code;\n\t\t\tif (typeof json.error.type === \"string\") return json.error.type;\n\t\t}\n\t} catch {}\n\treturn undefined;\n}\n\nasync function refreshAccessToken(refreshToken: string, signal: AbortSignal): Promise<OAuthToken> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t}),\n\t\t\tsignal,\n\t\t});\n\t} catch {\n\t\tif (signal.aborted) {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\"aborted\", \"OpenAI Codex token refresh was cancelled\");\n\t\t}\n\t\tthrow new OpenAICodexOAuthRefreshError(\"transient\", \"OpenAI Codex token refresh request failed\");\n\t}\n\n\tif (!response.ok) {\n\t\tconst oauthCode = await readRefreshErrorCode(response);\n\t\tif (response.status === 401 || response.status === 403 || oauthCode === \"invalid_grant\") {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\t\"reauth_required\",\n\t\t\t\t\"OpenAI Codex authentication must be renewed\",\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\t\tif (response.status === 429 || response.status >= 500) {\n\t\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\t\"transient\",\n\t\t\t\t\"OpenAI Codex token refresh is temporarily unavailable\",\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh was rejected\",\n\t\t\tresponse.status,\n\t\t);\n\t}\n\n\tlet json: { access_token?: string; refresh_token?: string; expires_in?: number } | null;\n\ttry {\n\t\tjson = (await response.json()) as typeof json;\n\t} catch {\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh returned invalid JSON\",\n\t\t\tresponse.status,\n\t\t);\n\t}\n\tif (!json?.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh response was missing required fields\",\n\t\t\tresponse.status,\n\t\t);\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 startOpenAICodexDeviceAuth(signal: AbortSignal): Promise<DeviceAuthInfo> {\n\tconst response = await fetchWithLoginCancellation(DEVICE_USER_CODE_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({ client_id: CLIENT_ID }),\n\t\tsignal,\n\t});\n\n\tif (!response.ok) {\n\t\tif (response.status === 404) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.\",\n\t\t\t);\n\t\t}\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(\n\t\t\t`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t);\n\t}\n\n\tconst rawJson = await response.json();\n\tconst json = rawJson as {\n\t\tdevice_auth_id?: string;\n\t\tuser_code?: string;\n\t\tinterval?: number | string;\n\t} | null;\n\tconst intervalSeconds = typeof json?.interval === \"string\" ? Number(json.interval.trim()) : json?.interval;\n\tif (\n\t\t!json?.device_auth_id ||\n\t\t!json.user_code ||\n\t\ttypeof intervalSeconds !== \"number\" ||\n\t\t!Number.isFinite(intervalSeconds) ||\n\t\tintervalSeconds < 0\n\t) {\n\t\tthrow new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);\n\t}\n\n\treturn {\n\t\tdeviceAuthId: json.device_auth_id,\n\t\tuserCode: json.user_code,\n\t\tintervalSeconds,\n\t};\n}\n\nasync function pollOpenAICodexDeviceAuth(device: DeviceAuthInfo, signal: AbortSignal): Promise<DeviceTokenSuccess> {\n\treturn pollOAuthDeviceCodeFlow<DeviceTokenSuccess>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await fetchWithLoginCancellation(DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tdevice_auth_id: device.deviceAuthId,\n\t\t\t\t\tuser_code: device.userCode,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (response.ok) {\n\t\t\t\tconst rawJson = await response.json();\n\t\t\t\tconst json = rawJson as { authorization_code?: string; code_verifier?: string } | null;\n\t\t\t\tif (!json?.authorization_code || !json.code_verifier) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tvalue: { authorizationCode: json.authorization_code, codeVerifier: json.code_verifier },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (response.status === 403 || response.status === 404) {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\n\t\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(responseBody) as { error?: string | { code?: string } } | null;\n\t\t\t\tconst error = json?.error;\n\t\t\t\terrorCode = typeof error === \"object\" ? error?.code : error;\n\t\t\t} catch {}\n\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (errorCode === \"slow_down\") {\n\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\nasync function createAuthorizationFlow(\n\toriginator: string = \"pi\",\n): Promise<{ verifier: string; state: string; url: string }> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = createState();\n\n\tconst url = new URL(AUTHORIZE_URL);\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", CLIENT_ID);\n\turl.searchParams.set(\"redirect_uri\", REDIRECT_URI);\n\turl.searchParams.set(\"scope\", SCOPE);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"state\", state);\n\turl.searchParams.set(\"id_token_add_organizations\", \"true\");\n\turl.searchParams.set(\"codex_cli_simplified_flow\", \"true\");\n\turl.searchParams.set(\"originator\", originator);\n\n\treturn { verifier, state, url: url.toString() };\n}\n\nfunction getAccountId(accessToken: string): string | null {\n\tconst payload = decodeJwt(accessToken);\n\tconst auth = payload?.[JWT_CLAIM_PATH];\n\tconst accountId = auth?.chatgpt_account_id;\n\treturn typeof accountId === \"string\" && accountId.length > 0 ? accountId : null;\n}\n\nfunction credentialsFromToken(token: OAuthToken): OAuthCredential {\n\tconst accountId = getAccountId(token.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: token.access,\n\t\trefresh: token.refresh,\n\t\texpires: token.expires,\n\t\taccountId,\n\t};\n}\n\nasync function exchangeAuthorizationCodeForCredentials(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\treturn credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));\n}\n\nasync function loginOpenAICodexDeviceCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await startOpenAICodexDeviceAuth(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: DEVICE_VERIFICATION_URI,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,\n\t});\n\tconst code = await pollOpenAICodexDeviceAuth(device, interaction.signal);\n\treturn exchangeAuthorizationCodeForCredentials(\n\t\tcode.authorizationCode,\n\t\tcode.codeVerifier,\n\t\tDEVICE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\nasync function loginOpenAICodex(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst { verifier, state, url } = await createAuthorizationFlow(options?.agentName);\n\t// Port 1455 is shared with the Codex CLI; when it is taken, fall back to the pasted redirect URL.\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"OpenAI\",\n\t\thost: getCallbackHost(),\n\t\tport: 1455,\n\t\tpath: \"/auth/callback\",\n\t\tstate,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl,\n\t\tinstructions: \"A browser window should open. Complete login to finish.\",\n\t});\n\n\ttry {\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== state) throw new Error(\"State mismatch\");\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\treturn await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nasync function refreshOpenAICodexToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\ttry {\n\t\treturn credentialsFromToken(await refreshAccessToken(refreshToken, signal));\n\t} catch (error) {\n\t\tif (error instanceof OpenAICodexOAuthRefreshError) throw error;\n\t\tthrow new OpenAICodexOAuthRefreshError(\n\t\t\t\"invalid_response\",\n\t\t\t\"OpenAI Codex token refresh returned an invalid credential\",\n\t\t);\n\t}\n}\n\nexport const openaiCodexOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT Plus/Pro)\",\n\tisSubscription: true,\n\n\tasync login(interaction, options) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select OpenAI Codex login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: \"Device code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {\n\t\t\treturn loginOpenAICodexDeviceCode(interaction);\n\t\t}\n\t\tif (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown OpenAI Codex login method: ${method}`);\n\t\t}\n\n\t\treturn loginOpenAICodex(interaction, options);\n\t},\n\n\trefresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -141,6 +141,10 @@ export type AuthEvent = {
141
141
  type: "device_code";
142
142
  userCode: string;
143
143
  verificationUri: string;
144
+ /** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */
145
+ openBrowserOnConfirm?: boolean;
146
+ /** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */
147
+ copyCodeOnConfirm?: boolean;
144
148
  intervalSeconds?: number;
145
149
  expiresInSeconds?: number;
146
150
  } | {
@@ -202,6 +206,11 @@ export interface LoginOptions {
202
206
  * the ID on first use and must return the same ID on every later call.
203
207
  */
204
208
  getDeviceId?: () => string;
209
+ /**
210
+ * Name this app introduces itself with during login, e.g. OpenAI's agent name hint and
211
+ * Codex originator. Defaults to pi's own name.
212
+ */
213
+ agentName?: string;
205
214
  }
206
215
  /**
207
216
  * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,WAAW,CAAC;CAClB;AAED,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,yCAAyC;AACzC,MAAM,WAAW,eAAgB,SAAQ,gBAAgB;IACxD,IAAI,EAAE,OAAO,CAAC;CACd;AAED,gFAAgF;AAChF,MAAM,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E;QACd,GAAG,EAAE,WAAW,CAAC;QACjB,UAAU,CAAC,EAAE,gBAAgB,CAAC;QAC9B,MAAM,EAAE,WAAW,CAAC;KACpB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;CACpC;AAED,+CAA+C;AAC/C,MAAM,WAAW,YAAY;IAC5B;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,MAAM,CAAC;IAC3B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACzB,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IAEb,oFAAoF;IACpF,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,KAAK,CAAC,WAAW,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9F;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAEpF;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App-supplied context for `Models.login`. */\nexport interface LoginOptions {\n\t/**\n\t * Returns the stable ID of this app installation, e.g. sent to OpenAI as its\n\t * agent host ID. Called only by login flows that need it, so apps can create\n\t * the ID on first use and must return the same ID on every later call.\n\t */\n\tgetDeviceId?: () => string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App-supplied context for `Models.login`. */\nexport interface LoginOptions {\n\t/**\n\t * Returns the stable ID of this app installation, e.g. sent to OpenAI as its\n\t * agent host ID. Called only by login flows that need it, so apps can create\n\t * the ID on first use and must return the same ID on every later call.\n\t */\n\tgetDeviceId?: () => string;\n\t/**\n\t * Name this app introduces itself with during login, e.g. OpenAI's agent name hint and\n\t * Codex originator. Defaults to pi's own name.\n\t */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
@@ -14,6 +14,10 @@ export interface OAuthAuthInfo {
14
14
  export interface OAuthDeviceCodeInfo {
15
15
  userCode: string;
16
16
  verificationUri: string;
17
+ /** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */
18
+ openBrowserOnConfirm?: boolean;
19
+ /** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */
20
+ copyCodeOnConfirm?: boolean;
17
21
  intervalSeconds?: number;
18
22
  expiresInSeconds?: number;
19
23
  }
@@ -1 +1 @@
1
- {"version":3,"file":"extension-oauth-types.d.ts","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,uDAAuD;AACvD,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC7B;AAED,+EAA+E;AAC/E,MAAM,WAAW,mBAAmB;IACnC,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;IAClC,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,UAAU,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjE,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
1
+ {"version":3,"file":"extension-oauth-types.d.ts","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,uDAAuD;AACvD,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,uGAAuG;IACvG,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,iGAAiG;IACjG,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC7B;AAED,+EAA+E;AAC/E,MAAM,WAAW,mBAAmB;IACnC,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;IAClC,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,UAAU,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,iBAAiB,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjE,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"extension-oauth-types.js","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OAuthCredentials } from \"../auth/types.ts\";\n\n/** Legacy extension OAuth prompt. */\nexport interface OAuthPrompt {\n\tmessage: string;\n\tplaceholder?: string;\n\tallowEmpty?: boolean;\n}\n\n/** Legacy extension OAuth authorization link. */\nexport interface OAuthAuthInfo {\n\turl: string;\n\tinstructions?: string;\n}\n\n/** Legacy extension OAuth device-code notification. */\nexport interface OAuthDeviceCodeInfo {\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n}\n\nexport interface OAuthSelectOption {\n\tid: string;\n\tlabel: string;\n}\n\nexport interface OAuthSelectPrompt {\n\tmessage: string;\n\toptions: OAuthSelectOption[];\n}\n\n/** Callback surface retained only for coding-agent extension compatibility. */\nexport interface OAuthLoginCallbacks {\n\tonAuth(info: OAuthAuthInfo): void;\n\tonDeviceCode(info: OAuthDeviceCodeInfo): void;\n\tonPrompt(prompt: OAuthPrompt): Promise<string>;\n\tonProgress?(message: string): void;\n\tonManualCodeInput?(): Promise<string>;\n\tonSelect(prompt: OAuthSelectPrompt): Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}\n\nexport type { OAuthCredentials };\n"]}
1
+ {"version":3,"file":"extension-oauth-types.js","sourceRoot":"","sources":["../../src/compat/extension-oauth-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OAuthCredentials } from \"../auth/types.ts\";\n\n/** Legacy extension OAuth prompt. */\nexport interface OAuthPrompt {\n\tmessage: string;\n\tplaceholder?: string;\n\tallowEmpty?: boolean;\n}\n\n/** Legacy extension OAuth authorization link. */\nexport interface OAuthAuthInfo {\n\turl: string;\n\tinstructions?: string;\n}\n\n/** Legacy extension OAuth device-code notification. */\nexport interface OAuthDeviceCodeInfo {\n\tuserCode: string;\n\tverificationUri: string;\n\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\topenBrowserOnConfirm?: boolean;\n\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\tcopyCodeOnConfirm?: boolean;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n}\n\nexport interface OAuthSelectOption {\n\tid: string;\n\tlabel: string;\n}\n\nexport interface OAuthSelectPrompt {\n\tmessage: string;\n\toptions: OAuthSelectOption[];\n}\n\n/** Callback surface retained only for coding-agent extension compatibility. */\nexport interface OAuthLoginCallbacks {\n\tonAuth(info: OAuthAuthInfo): void;\n\tonDeviceCode(info: OAuthDeviceCodeInfo): void;\n\tonPrompt(prompt: OAuthPrompt): Promise<string>;\n\tonProgress?(message: string): void;\n\tonManualCodeInput?(): Promise<string>;\n\tonSelect(prompt: OAuthSelectPrompt): Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}\n\nexport type { OAuthCredentials };\n"]}
package/dist/index.d.ts CHANGED
@@ -22,15 +22,17 @@ export * from "./models-store.ts";
22
22
  export * from "./providers/faux.ts";
23
23
  export * from "./session-resources.ts";
24
24
  export * from "./types.ts";
25
- export * from "./utils/assistant-message-frame.ts";
26
25
  export * from "./utils/diagnostics.ts";
27
26
  export * from "./utils/event-stream.ts";
27
+ export * from "./utils/identity.ts";
28
28
  export * from "./utils/json-parse.ts";
29
29
  export * from "./utils/overflow.ts";
30
30
  export * from "./utils/retry.ts";
31
+ export * from "./utils/streaming-json.ts";
31
32
  export { contentText, getSystemMessageText, renderSystemMessageUpdate } from "./utils/text.ts";
32
33
  export * from "./utils/transcript.ts";
33
34
  export * from "./utils/typebox-helpers.ts";
34
35
  export { uuidv7 } from "./utils/uuid.ts";
35
36
  export * from "./utils/validation.ts";
37
+ export { PI_AI_VERSION } from "./utils/version.ts";
36
38
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO/B,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC/G,YAAY,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AACnF,YAAY,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC/F,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,YAAY,EAAE,sBAAsB,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAClG,YAAY,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClE,cAAc,eAAe,CAAC;AAC9B,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,YAAY,EAAE,2BAA2B,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACnH,YAAY,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,YAAY,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxE,YAAY,EAAE,eAAe,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACxG,cAAc,mBAAmB,CAAC;AAClC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,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AAC9B,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,YAAY,EAAE,2BAA2B,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACnH,YAAY,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,YAAY,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxE,YAAY,EAAE,eAAe,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACxG,cAAc,mBAAmB,CAAC;AAClC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,YAAY,EACX,aAAa,EACb,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,GACjB,MAAM,mCAAmC,CAAC;AAC3C,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC;AAC3B,cAAc,wBAAwB,CAAC;AACvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -9,15 +9,17 @@ export * from "./models-store.js";
9
9
  export * from "./providers/faux.js";
10
10
  export * from "./session-resources.js";
11
11
  export * from "./types.js";
12
- export * from "./utils/assistant-message-frame.js";
13
12
  export * from "./utils/diagnostics.js";
14
13
  export * from "./utils/event-stream.js";
14
+ export * from "./utils/identity.js";
15
15
  export * from "./utils/json-parse.js";
16
16
  export * from "./utils/overflow.js";
17
17
  export * from "./utils/retry.js";
18
+ export * from "./utils/streaming-json.js";
18
19
  export { contentText, getSystemMessageText, renderSystemMessageUpdate } from "./utils/text.js";
19
20
  export * from "./utils/transcript.js";
20
21
  export * from "./utils/typebox-helpers.js";
21
22
  export { uuidv7 } from "./utils/uuid.js";
22
23
  export * from "./utils/validation.js";
24
+ export { PI_AI_VERSION } from "./utils/version.js";
23
25
  //# sourceMappingURL=index.js.map