@handy_wote/pi-ai 0.81.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 (346) hide show
  1. package/README.md +1623 -0
  2. package/dist/api/anthropic-messages.d.ts +71 -0
  3. package/dist/api/anthropic-messages.d.ts.map +1 -0
  4. package/dist/api/anthropic-messages.js +1024 -0
  5. package/dist/api/anthropic-messages.js.map +1 -0
  6. package/dist/api/anthropic-messages.lazy.d.ts +3 -0
  7. package/dist/api/anthropic-messages.lazy.d.ts.map +1 -0
  8. package/dist/api/anthropic-messages.lazy.js +3 -0
  9. package/dist/api/anthropic-messages.lazy.js.map +1 -0
  10. package/dist/api/azure-openai-responses.d.ts +15 -0
  11. package/dist/api/azure-openai-responses.d.ts.map +1 -0
  12. package/dist/api/azure-openai-responses.js +221 -0
  13. package/dist/api/azure-openai-responses.js.map +1 -0
  14. package/dist/api/azure-openai-responses.lazy.d.ts +3 -0
  15. package/dist/api/azure-openai-responses.lazy.d.ts.map +1 -0
  16. package/dist/api/azure-openai-responses.lazy.js +3 -0
  17. package/dist/api/azure-openai-responses.lazy.js.map +1 -0
  18. package/dist/api/bedrock-converse-stream.d.ts +38 -0
  19. package/dist/api/bedrock-converse-stream.d.ts.map +1 -0
  20. package/dist/api/bedrock-converse-stream.js +883 -0
  21. package/dist/api/bedrock-converse-stream.js.map +1 -0
  22. package/dist/api/bedrock-converse-stream.lazy.d.ts +9 -0
  23. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -0
  24. package/dist/api/bedrock-converse-stream.lazy.js +30 -0
  25. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -0
  26. package/dist/api/cloudflare.d.ts +9 -0
  27. package/dist/api/cloudflare.d.ts.map +1 -0
  28. package/dist/api/cloudflare.js +9 -0
  29. package/dist/api/cloudflare.js.map +1 -0
  30. package/dist/api/github-copilot-headers.d.ts +8 -0
  31. package/dist/api/github-copilot-headers.d.ts.map +1 -0
  32. package/dist/api/github-copilot-headers.js +29 -0
  33. package/dist/api/github-copilot-headers.js.map +1 -0
  34. package/dist/api/google-generative-ai.d.ts +13 -0
  35. package/dist/api/google-generative-ai.d.ts.map +1 -0
  36. package/dist/api/google-generative-ai.js +407 -0
  37. package/dist/api/google-generative-ai.js.map +1 -0
  38. package/dist/api/google-generative-ai.lazy.d.ts +3 -0
  39. package/dist/api/google-generative-ai.lazy.d.ts.map +1 -0
  40. package/dist/api/google-generative-ai.lazy.js +3 -0
  41. package/dist/api/google-generative-ai.lazy.js.map +1 -0
  42. package/dist/api/google-shared.d.ts +70 -0
  43. package/dist/api/google-shared.d.ts.map +1 -0
  44. package/dist/api/google-shared.js +329 -0
  45. package/dist/api/google-shared.js.map +1 -0
  46. package/dist/api/google-vertex.d.ts +15 -0
  47. package/dist/api/google-vertex.d.ts.map +1 -0
  48. package/dist/api/google-vertex.js +456 -0
  49. package/dist/api/google-vertex.js.map +1 -0
  50. package/dist/api/google-vertex.lazy.d.ts +3 -0
  51. package/dist/api/google-vertex.lazy.d.ts.map +1 -0
  52. package/dist/api/google-vertex.lazy.js +3 -0
  53. package/dist/api/google-vertex.lazy.js.map +1 -0
  54. package/dist/api/lazy.d.ts +15 -0
  55. package/dist/api/lazy.d.ts.map +1 -0
  56. package/dist/api/lazy.js +58 -0
  57. package/dist/api/lazy.js.map +1 -0
  58. package/dist/api/mistral-conversations.d.ts +25 -0
  59. package/dist/api/mistral-conversations.d.ts.map +1 -0
  60. package/dist/api/mistral-conversations.js +555 -0
  61. package/dist/api/mistral-conversations.js.map +1 -0
  62. package/dist/api/mistral-conversations.lazy.d.ts +3 -0
  63. package/dist/api/mistral-conversations.lazy.d.ts.map +1 -0
  64. package/dist/api/mistral-conversations.lazy.js +3 -0
  65. package/dist/api/mistral-conversations.lazy.js.map +1 -0
  66. package/dist/api/openai-codex-responses.d.ts +31 -0
  67. package/dist/api/openai-codex-responses.d.ts.map +1 -0
  68. package/dist/api/openai-codex-responses.js +1222 -0
  69. package/dist/api/openai-codex-responses.js.map +1 -0
  70. package/dist/api/openai-codex-responses.lazy.d.ts +3 -0
  71. package/dist/api/openai-codex-responses.lazy.d.ts.map +1 -0
  72. package/dist/api/openai-codex-responses.lazy.js +3 -0
  73. package/dist/api/openai-codex-responses.lazy.js.map +1 -0
  74. package/dist/api/openai-completions.d.ts +20 -0
  75. package/dist/api/openai-completions.d.ts.map +1 -0
  76. package/dist/api/openai-completions.js +1120 -0
  77. package/dist/api/openai-completions.js.map +1 -0
  78. package/dist/api/openai-completions.lazy.d.ts +3 -0
  79. package/dist/api/openai-completions.lazy.d.ts.map +1 -0
  80. package/dist/api/openai-completions.lazy.js +3 -0
  81. package/dist/api/openai-completions.lazy.js.map +1 -0
  82. package/dist/api/openai-prompt-cache.d.ts +3 -0
  83. package/dist/api/openai-prompt-cache.d.ts.map +1 -0
  84. package/dist/api/openai-prompt-cache.js +10 -0
  85. package/dist/api/openai-prompt-cache.js.map +1 -0
  86. package/dist/api/openai-responses-shared.d.ts +20 -0
  87. package/dist/api/openai-responses-shared.d.ts.map +1 -0
  88. package/dist/api/openai-responses-shared.js +535 -0
  89. package/dist/api/openai-responses-shared.js.map +1 -0
  90. package/dist/api/openai-responses.d.ts +14 -0
  91. package/dist/api/openai-responses.d.ts.map +1 -0
  92. package/dist/api/openai-responses.js +246 -0
  93. package/dist/api/openai-responses.js.map +1 -0
  94. package/dist/api/openai-responses.lazy.d.ts +3 -0
  95. package/dist/api/openai-responses.lazy.d.ts.map +1 -0
  96. package/dist/api/openai-responses.lazy.js +3 -0
  97. package/dist/api/openai-responses.lazy.js.map +1 -0
  98. package/dist/api/openrouter-images.d.ts +3 -0
  99. package/dist/api/openrouter-images.d.ts.map +1 -0
  100. package/dist/api/openrouter-images.js +126 -0
  101. package/dist/api/openrouter-images.js.map +1 -0
  102. package/dist/api/openrouter-images.lazy.d.ts +3 -0
  103. package/dist/api/openrouter-images.lazy.d.ts.map +1 -0
  104. package/dist/api/openrouter-images.lazy.js +4 -0
  105. package/dist/api/openrouter-images.lazy.js.map +1 -0
  106. package/dist/api/pi-messages.d.ts +97 -0
  107. package/dist/api/pi-messages.d.ts.map +1 -0
  108. package/dist/api/pi-messages.js +307 -0
  109. package/dist/api/pi-messages.js.map +1 -0
  110. package/dist/api/pi-messages.lazy.d.ts +3 -0
  111. package/dist/api/pi-messages.lazy.d.ts.map +1 -0
  112. package/dist/api/pi-messages.lazy.js +3 -0
  113. package/dist/api/pi-messages.lazy.js.map +1 -0
  114. package/dist/api/simple-options.d.ts +9 -0
  115. package/dist/api/simple-options.d.ts.map +1 -0
  116. package/dist/api/simple-options.js +52 -0
  117. package/dist/api/simple-options.js.map +1 -0
  118. package/dist/api/transform-messages.d.ts +8 -0
  119. package/dist/api/transform-messages.d.ts.map +1 -0
  120. package/dist/api/transform-messages.js +187 -0
  121. package/dist/api/transform-messages.js.map +1 -0
  122. package/dist/auth/context.d.ts +7 -0
  123. package/dist/auth/context.d.ts.map +1 -0
  124. package/dist/auth/context.js +42 -0
  125. package/dist/auth/context.js.map +1 -0
  126. package/dist/auth/credential-store.d.ts +17 -0
  127. package/dist/auth/credential-store.d.ts.map +1 -0
  128. package/dist/auth/credential-store.js +40 -0
  129. package/dist/auth/credential-store.js.map +1 -0
  130. package/dist/auth/helpers.d.ts +21 -0
  131. package/dist/auth/helpers.d.ts.map +1 -0
  132. package/dist/auth/helpers.js +48 -0
  133. package/dist/auth/helpers.js.map +1 -0
  134. package/dist/auth/oauth/anthropic.d.ts +9 -0
  135. package/dist/auth/oauth/anthropic.d.ts.map +1 -0
  136. package/dist/auth/oauth/anthropic.js +302 -0
  137. package/dist/auth/oauth/anthropic.js.map +1 -0
  138. package/dist/auth/oauth/device-code.d.ts +23 -0
  139. package/dist/auth/oauth/device-code.d.ts.map +1 -0
  140. package/dist/auth/oauth/device-code.js +69 -0
  141. package/dist/auth/oauth/device-code.js.map +1 -0
  142. package/dist/auth/oauth/github-copilot.d.ts +6 -0
  143. package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
  144. package/dist/auth/oauth/github-copilot.js +313 -0
  145. package/dist/auth/oauth/github-copilot.js.map +1 -0
  146. package/dist/auth/oauth/load.d.ts +23 -0
  147. package/dist/auth/oauth/load.d.ts.map +1 -0
  148. package/dist/auth/oauth/load.js +49 -0
  149. package/dist/auth/oauth/load.js.map +1 -0
  150. package/dist/auth/oauth/oauth-page.d.ts +3 -0
  151. package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
  152. package/dist/auth/oauth/oauth-page.js +105 -0
  153. package/dist/auth/oauth/oauth-page.js.map +1 -0
  154. package/dist/auth/oauth/openai-codex.d.ts +9 -0
  155. package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
  156. package/dist/auth/oauth/openai-codex.js +443 -0
  157. package/dist/auth/oauth/openai-codex.js.map +1 -0
  158. package/dist/auth/oauth/pkce.d.ts +13 -0
  159. package/dist/auth/oauth/pkce.d.ts.map +1 -0
  160. package/dist/auth/oauth/pkce.js +31 -0
  161. package/dist/auth/oauth/pkce.js.map +1 -0
  162. package/dist/auth/oauth/radius.d.ts +16 -0
  163. package/dist/auth/oauth/radius.d.ts.map +1 -0
  164. package/dist/auth/oauth/radius.js +321 -0
  165. package/dist/auth/oauth/radius.js.map +1 -0
  166. package/dist/auth/oauth/xai.d.ts +6 -0
  167. package/dist/auth/oauth/xai.d.ts.map +1 -0
  168. package/dist/auth/oauth/xai.js +189 -0
  169. package/dist/auth/oauth/xai.js.map +1 -0
  170. package/dist/auth/resolve.d.ts +24 -0
  171. package/dist/auth/resolve.d.ts.map +1 -0
  172. package/dist/auth/resolve.js +103 -0
  173. package/dist/auth/resolve.js.map +1 -0
  174. package/dist/auth/types.d.ts +219 -0
  175. package/dist/auth/types.d.ts.map +1 -0
  176. package/dist/auth/types.js +2 -0
  177. package/dist/auth/types.js.map +1 -0
  178. package/dist/bedrock-provider.d.ts +5 -0
  179. package/dist/bedrock-provider.d.ts.map +1 -0
  180. package/dist/bedrock-provider.js +6 -0
  181. package/dist/bedrock-provider.js.map +1 -0
  182. package/dist/bun-oauth.d.ts +3 -0
  183. package/dist/bun-oauth.d.ts.map +1 -0
  184. package/dist/bun-oauth.js +17 -0
  185. package/dist/bun-oauth.js.map +1 -0
  186. package/dist/cli.d.ts +3 -0
  187. package/dist/cli.d.ts.map +1 -0
  188. package/dist/cli.js +115 -0
  189. package/dist/cli.js.map +1 -0
  190. package/dist/compat/extension-oauth-types.d.ts +39 -0
  191. package/dist/compat/extension-oauth-types.d.ts.map +1 -0
  192. package/dist/compat/extension-oauth-types.js +2 -0
  193. package/dist/compat/extension-oauth-types.js.map +1 -0
  194. package/dist/compat.d.ts +70 -0
  195. package/dist/compat.d.ts.map +1 -0
  196. package/dist/compat.js +189 -0
  197. package/dist/compat.js.map +1 -0
  198. package/dist/env-api-keys.d.ts +18 -0
  199. package/dist/env-api-keys.d.ts.map +1 -0
  200. package/dist/env-api-keys.js +148 -0
  201. package/dist/env-api-keys.js.map +1 -0
  202. package/dist/image-models.d.ts +10 -0
  203. package/dist/image-models.d.ts.map +1 -0
  204. package/dist/image-models.js +24 -0
  205. package/dist/image-models.js.map +1 -0
  206. package/dist/images-api-registry.d.ts +14 -0
  207. package/dist/images-api-registry.d.ts.map +1 -0
  208. package/dist/images-api-registry.js +22 -0
  209. package/dist/images-api-registry.js.map +1 -0
  210. package/dist/images-models.d.ts +95 -0
  211. package/dist/images-models.d.ts.map +1 -0
  212. package/dist/images-models.js +142 -0
  213. package/dist/images-models.js.map +1 -0
  214. package/dist/images.d.ts +4 -0
  215. package/dist/images.d.ts.map +1 -0
  216. package/dist/images.js +14 -0
  217. package/dist/images.js.map +1 -0
  218. package/dist/index.d.ts +35 -0
  219. package/dist/index.d.ts.map +1 -0
  220. package/dist/index.js +22 -0
  221. package/dist/index.js.map +1 -0
  222. package/dist/legacy-api-aliases.d.ts +42 -0
  223. package/dist/legacy-api-aliases.d.ts.map +1 -0
  224. package/dist/legacy-api-aliases.js +49 -0
  225. package/dist/legacy-api-aliases.js.map +1 -0
  226. package/dist/models-store.d.ts +27 -0
  227. package/dist/models-store.d.ts.map +1 -0
  228. package/dist/models-store.js +14 -0
  229. package/dist/models-store.js.map +1 -0
  230. package/dist/models.d.ts +178 -0
  231. package/dist/models.d.ts.map +1 -0
  232. package/dist/models.js +432 -0
  233. package/dist/models.js.map +1 -0
  234. package/dist/oauth.d.ts +3 -0
  235. package/dist/oauth.d.ts.map +1 -0
  236. package/dist/oauth.js +2 -0
  237. package/dist/oauth.js.map +1 -0
  238. package/dist/providers/all.d.ts +6 -0
  239. package/dist/providers/all.d.ts.map +1 -0
  240. package/dist/providers/all.js +9 -0
  241. package/dist/providers/all.js.map +1 -0
  242. package/dist/providers/anthropic-compat.d.ts +10 -0
  243. package/dist/providers/anthropic-compat.d.ts.map +1 -0
  244. package/dist/providers/anthropic-compat.js +20 -0
  245. package/dist/providers/anthropic-compat.js.map +1 -0
  246. package/dist/providers/faux.d.ts +97 -0
  247. package/dist/providers/faux.d.ts.map +1 -0
  248. package/dist/providers/faux.js +395 -0
  249. package/dist/providers/faux.js.map +1 -0
  250. package/dist/providers/images/register-builtins.d.ts +4 -0
  251. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  252. package/dist/providers/images/register-builtins.js +34 -0
  253. package/dist/providers/images/register-builtins.js.map +1 -0
  254. package/dist/providers/openai-compat.d.ts +10 -0
  255. package/dist/providers/openai-compat.d.ts.map +1 -0
  256. package/dist/providers/openai-compat.js +24 -0
  257. package/dist/providers/openai-compat.js.map +1 -0
  258. package/dist/providers/openrouter-images.d.ts +3 -0
  259. package/dist/providers/openrouter-images.d.ts.map +1 -0
  260. package/dist/providers/openrouter-images.js +15 -0
  261. package/dist/providers/openrouter-images.js.map +1 -0
  262. package/dist/providers/radius.d.ts +9 -0
  263. package/dist/providers/radius.d.ts.map +1 -0
  264. package/dist/providers/radius.js +70 -0
  265. package/dist/providers/radius.js.map +1 -0
  266. package/dist/session-resources.d.ts +4 -0
  267. package/dist/session-resources.d.ts.map +1 -0
  268. package/dist/session-resources.js +22 -0
  269. package/dist/session-resources.js.map +1 -0
  270. package/dist/types.d.ts +629 -0
  271. package/dist/types.d.ts.map +1 -0
  272. package/dist/types.js +2 -0
  273. package/dist/types.js.map +1 -0
  274. package/dist/utils/abort-signals.d.ts +6 -0
  275. package/dist/utils/abort-signals.d.ts.map +1 -0
  276. package/dist/utils/abort-signals.js +34 -0
  277. package/dist/utils/abort-signals.js.map +1 -0
  278. package/dist/utils/deferred-tools.d.ts +9 -0
  279. package/dist/utils/deferred-tools.d.ts.map +1 -0
  280. package/dist/utils/deferred-tools.js +36 -0
  281. package/dist/utils/deferred-tools.js.map +1 -0
  282. package/dist/utils/diagnostics.d.ts +19 -0
  283. package/dist/utils/diagnostics.d.ts.map +1 -0
  284. package/dist/utils/diagnostics.js +25 -0
  285. package/dist/utils/diagnostics.js.map +1 -0
  286. package/dist/utils/error-body.d.ts +25 -0
  287. package/dist/utils/error-body.d.ts.map +1 -0
  288. package/dist/utils/error-body.js +109 -0
  289. package/dist/utils/error-body.js.map +1 -0
  290. package/dist/utils/estimate.d.ts +17 -0
  291. package/dist/utils/estimate.d.ts.map +1 -0
  292. package/dist/utils/estimate.js +116 -0
  293. package/dist/utils/estimate.js.map +1 -0
  294. package/dist/utils/event-stream.d.ts +21 -0
  295. package/dist/utils/event-stream.d.ts.map +1 -0
  296. package/dist/utils/event-stream.js +81 -0
  297. package/dist/utils/event-stream.js.map +1 -0
  298. package/dist/utils/hash.d.ts +3 -0
  299. package/dist/utils/hash.d.ts.map +1 -0
  300. package/dist/utils/hash.js +14 -0
  301. package/dist/utils/hash.js.map +1 -0
  302. package/dist/utils/headers.d.ts +4 -0
  303. package/dist/utils/headers.d.ts.map +1 -0
  304. package/dist/utils/headers.js +18 -0
  305. package/dist/utils/headers.js.map +1 -0
  306. package/dist/utils/json-parse.d.ts +16 -0
  307. package/dist/utils/json-parse.d.ts.map +1 -0
  308. package/dist/utils/json-parse.js +113 -0
  309. package/dist/utils/json-parse.js.map +1 -0
  310. package/dist/utils/node-http-proxy.d.ts +4 -0
  311. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  312. package/dist/utils/node-http-proxy.js +92 -0
  313. package/dist/utils/node-http-proxy.js.map +1 -0
  314. package/dist/utils/overflow.d.ts +59 -0
  315. package/dist/utils/overflow.d.ts.map +1 -0
  316. package/dist/utils/overflow.js +161 -0
  317. package/dist/utils/overflow.js.map +1 -0
  318. package/dist/utils/provider-env.d.ts +7 -0
  319. package/dist/utils/provider-env.d.ts.map +1 -0
  320. package/dist/utils/provider-env.js +44 -0
  321. package/dist/utils/provider-env.js.map +1 -0
  322. package/dist/utils/retry.d.ts +53 -0
  323. package/dist/utils/retry.d.ts.map +1 -0
  324. package/dist/utils/retry.js +170 -0
  325. package/dist/utils/retry.js.map +1 -0
  326. package/dist/utils/sanitize-unicode.d.ts +22 -0
  327. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  328. package/dist/utils/sanitize-unicode.js +26 -0
  329. package/dist/utils/sanitize-unicode.js.map +1 -0
  330. package/dist/utils/text.d.ts +6 -0
  331. package/dist/utils/text.d.ts.map +1 -0
  332. package/dist/utils/text.js +10 -0
  333. package/dist/utils/text.js.map +1 -0
  334. package/dist/utils/typebox-helpers.d.ts +17 -0
  335. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  336. package/dist/utils/typebox-helpers.js +21 -0
  337. package/dist/utils/typebox-helpers.js.map +1 -0
  338. package/dist/utils/uuid.d.ts +3 -0
  339. package/dist/utils/uuid.d.ts.map +1 -0
  340. package/dist/utils/uuid.js +46 -0
  341. package/dist/utils/uuid.js.map +1 -0
  342. package/dist/utils/validation.d.ts +18 -0
  343. package/dist/utils/validation.d.ts.map +1 -0
  344. package/dist/utils/validation.js +269 -0
  345. package/dist/utils/validation.js.map +1 -0
  346. package/package.json +95 -0
@@ -0,0 +1,187 @@
1
+ const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
2
+ const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
3
+ function replaceImagesWithPlaceholder(content, placeholder) {
4
+ const result = [];
5
+ let previousWasPlaceholder = false;
6
+ for (const block of content) {
7
+ if (block.type === "image") {
8
+ if (!previousWasPlaceholder) {
9
+ result.push({ type: "text", text: placeholder });
10
+ }
11
+ previousWasPlaceholder = true;
12
+ continue;
13
+ }
14
+ result.push(block);
15
+ previousWasPlaceholder = block.text === placeholder;
16
+ }
17
+ return result;
18
+ }
19
+ function downgradeUnsupportedImages(messages, model) {
20
+ if (model.input.includes("image")) {
21
+ return messages;
22
+ }
23
+ return messages.map((msg) => {
24
+ if (msg.role === "user" && Array.isArray(msg.content)) {
25
+ return {
26
+ ...msg,
27
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),
28
+ };
29
+ }
30
+ if (msg.role === "toolResult") {
31
+ return {
32
+ ...msg,
33
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),
34
+ };
35
+ }
36
+ return msg;
37
+ });
38
+ }
39
+ /**
40
+ * Normalize tool call ID for cross-provider compatibility.
41
+ * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.
42
+ * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).
43
+ */
44
+ export function transformMessages(messages, model, normalizeToolCallId) {
45
+ // Build a map of original tool call IDs to normalized IDs
46
+ const toolCallIdMap = new Map();
47
+ // Normalize null/undefined content from untyped callers (custom tools, hand-built
48
+ // histories, old session files) so downstream code can rely on the type contract.
49
+ const normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));
50
+ const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);
51
+ // First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)
52
+ const transformed = imageAwareMessages.map((msg) => {
53
+ // User messages pass through unchanged
54
+ if (msg.role === "user") {
55
+ return msg;
56
+ }
57
+ // Handle toolResult messages - normalize toolCallId if we have a mapping
58
+ if (msg.role === "toolResult") {
59
+ const normalizedId = toolCallIdMap.get(msg.toolCallId);
60
+ if (normalizedId && normalizedId !== msg.toolCallId) {
61
+ return { ...msg, toolCallId: normalizedId };
62
+ }
63
+ return msg;
64
+ }
65
+ // Assistant messages need transformation check
66
+ if (msg.role === "assistant") {
67
+ const assistantMsg = msg;
68
+ const isSameModel = assistantMsg.provider === model.provider &&
69
+ assistantMsg.api === model.api &&
70
+ assistantMsg.model === model.id;
71
+ const transformedContent = assistantMsg.content.flatMap((block) => {
72
+ if (block.type === "thinking") {
73
+ // Redacted thinking is opaque encrypted content, only valid for the same model.
74
+ // Drop it for cross-model to avoid API errors.
75
+ if (block.redacted) {
76
+ return isSameModel ? block : [];
77
+ }
78
+ // For same model: keep thinking blocks with signatures (needed for replay)
79
+ // even if the thinking text is empty (OpenAI encrypted reasoning)
80
+ if (isSameModel && block.thinkingSignature)
81
+ return block;
82
+ // Skip empty thinking blocks, convert others to plain text
83
+ if (!block.thinking || block.thinking.trim() === "")
84
+ return [];
85
+ if (isSameModel)
86
+ return block;
87
+ return {
88
+ type: "text",
89
+ text: block.thinking,
90
+ };
91
+ }
92
+ if (block.type === "text") {
93
+ if (isSameModel)
94
+ return block;
95
+ return {
96
+ type: "text",
97
+ text: block.text,
98
+ };
99
+ }
100
+ if (block.type === "toolCall") {
101
+ const toolCall = block;
102
+ let normalizedToolCall = toolCall;
103
+ if (!isSameModel && toolCall.thoughtSignature) {
104
+ normalizedToolCall = { ...toolCall };
105
+ delete normalizedToolCall.thoughtSignature;
106
+ }
107
+ if (!isSameModel && normalizeToolCallId) {
108
+ const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
109
+ if (normalizedId !== toolCall.id) {
110
+ toolCallIdMap.set(toolCall.id, normalizedId);
111
+ normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
112
+ }
113
+ }
114
+ return normalizedToolCall;
115
+ }
116
+ return block;
117
+ });
118
+ return {
119
+ ...assistantMsg,
120
+ content: transformedContent,
121
+ };
122
+ }
123
+ return msg;
124
+ });
125
+ // Second pass: insert synthetic empty tool results for orphaned tool calls
126
+ // This preserves thinking signatures and satisfies API requirements
127
+ const result = [];
128
+ let pendingToolCalls = [];
129
+ let existingToolResultIds = new Set();
130
+ const insertSyntheticToolResults = () => {
131
+ if (pendingToolCalls.length > 0) {
132
+ for (const tc of pendingToolCalls) {
133
+ if (!existingToolResultIds.has(tc.id)) {
134
+ result.push({
135
+ role: "toolResult",
136
+ toolCallId: tc.id,
137
+ toolName: tc.name,
138
+ content: [{ type: "text", text: "No result provided" }],
139
+ isError: true,
140
+ timestamp: Date.now(),
141
+ });
142
+ }
143
+ }
144
+ pendingToolCalls = [];
145
+ existingToolResultIds = new Set();
146
+ }
147
+ };
148
+ for (let i = 0; i < transformed.length; i++) {
149
+ const msg = transformed[i];
150
+ if (msg.role === "assistant") {
151
+ // If we have pending orphaned tool calls from a previous assistant, insert synthetic results now
152
+ insertSyntheticToolResults();
153
+ // Skip errored/aborted assistant messages entirely.
154
+ // These are incomplete turns that shouldn't be replayed:
155
+ // - May have partial content (reasoning without message, incomplete tool calls)
156
+ // - Replaying them can cause API errors (e.g., OpenAI "reasoning without following item")
157
+ // - The model should retry from the last valid state
158
+ const assistantMsg = msg;
159
+ if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
160
+ continue;
161
+ }
162
+ // Track tool calls from this assistant message
163
+ const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
164
+ if (toolCalls.length > 0) {
165
+ pendingToolCalls = toolCalls;
166
+ existingToolResultIds = new Set();
167
+ }
168
+ result.push(msg);
169
+ }
170
+ else if (msg.role === "toolResult") {
171
+ existingToolResultIds.add(msg.toolCallId);
172
+ result.push(msg);
173
+ }
174
+ else if (msg.role === "user") {
175
+ // User message interrupts tool flow - insert synthetic results for orphaned calls
176
+ insertSyntheticToolResults();
177
+ result.push(msg);
178
+ }
179
+ else {
180
+ result.push(msg);
181
+ }
182
+ }
183
+ // If the conversation ends with unresolved tool calls, synthesize results now.
184
+ insertSyntheticToolResults();
185
+ return result;
186
+ }
187
+ //# sourceMappingURL=transform-messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAWA,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAEhG,SAAS,4BAA4B,CAAC,OAAuC,EAAE,WAAmB,EAAiB;IAClH,MAAM,MAAM,GAAkB,EAAE,CAAC;IACjC,IAAI,sBAAsB,GAAG,KAAK,CAAC;IAEnC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,sBAAsB,EAAE,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;YAClD,CAAC;YACD,sBAAsB,GAAG,IAAI,CAAC;YAC9B,SAAS;QACV,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,sBAAsB,GAAG,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC;IACrD,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd;AAED,SAAS,0BAA0B,CAAmB,QAAmB,EAAE,KAAkB,EAAa;IACzG,IAAI,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACnC,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAA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IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC1B,gBAAgB,GAAG,SAAS,CAAC;gBAC7B,qBAAqB,GAAG,IAAI,GAAG,EAAE,CAAC;YACnC,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACtC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChC,kFAAkF;YAClF,0BAA0B,EAAE,CAAC;YAC7B,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+EAA+E;IAC/E,0BAA0B,EAAE,CAAC;IAE7B,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\n\nfunction replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"image\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking is opaque encrypted content, only valid for the same model.\n\t\t\t\t\t// Drop it for cross-model to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn isSameModel ? block : [];\n\t\t\t\t\t}\n\t\t\t\t\t// For same model: keep thinking blocks with signatures (needed for replay)\n\t\t\t\t\t// even if the thinking text is empty (OpenAI encrypted reasoning)\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\tconst insertSyntheticToolResults = () => {\n\t\tif (pendingToolCalls.length > 0) {\n\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\tresult.push({\n\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingToolCalls = [];\n\t\t\texistingToolResultIds = new Set();\n\t\t}\n\t};\n\n\tfor (let i = 0; i < transformed.length; i++) {\n\t\tconst msg = transformed[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tinsertSyntheticToolResults();\n\n\t\t\t// Skip errored/aborted assistant messages entirely.\n\t\t\t// These are incomplete turns that shouldn't be replayed:\n\t\t\t// - May have partial content (reasoning without message, incomplete tool calls)\n\t\t\t// - Replaying them can cause API errors (e.g., OpenAI \"reasoning without following item\")\n\t\t\t// - The model should retry from the last valid state\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// User message interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tinsertSyntheticToolResults();\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\t// If the conversation ends with unresolved tool calls, synthesize results now.\n\tinsertSyntheticToolResults();\n\n\treturn result;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { AuthContext } from "./types.ts";
2
+ /**
3
+ * Default auth context: env vars from `process.env` (undefined in browsers),
4
+ * file existence via node:fs (always false in browsers).
5
+ */
6
+ export declare function defaultProviderAuthContext(): AuthContext;
7
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/auth/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAkB9C;;;GAGG;AACH,wBAAgB,0BAA0B,IAAI,WAAW,CAsBxD","sourcesContent":["import type { AuthContext } from \"./types.ts\";\n\ninterface NodeFsModule {\n\taccess(path: string): Promise<void>;\n}\n\ninterface NodeOsModule {\n\thomedir(): string;\n}\n\n// Variable specifier so browser bundlers do not try to resolve node builtins.\nconst importNodeModule = (specifier: string): Promise<unknown> => import(specifier);\n\nfunction getProcessEnv(): Record<string, string | undefined> | undefined {\n\tconst proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n\treturn proc?.env;\n}\n\n/**\n * Default auth context: env vars from `process.env` (undefined in browsers),\n * file existence via node:fs (always false in browsers).\n */\nexport function defaultProviderAuthContext(): AuthContext {\n\treturn {\n\t\tasync env(name: string): Promise<string | undefined> {\n\t\t\tconst value = getProcessEnv()?.[name];\n\t\t\treturn typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n\t\t},\n\n\t\tasync fileExists(path: string): Promise<boolean> {\n\t\t\ttry {\n\t\t\t\tconst fs = (await importNodeModule(\"node:fs/promises\")) as NodeFsModule;\n\t\t\t\tlet resolved = path;\n\t\t\t\tif (resolved.startsWith(\"~\")) {\n\t\t\t\t\tconst os = (await importNodeModule(\"node:os\")) as NodeOsModule;\n\t\t\t\t\tresolved = os.homedir() + resolved.slice(1);\n\t\t\t\t}\n\t\t\t\tawait fs.access(resolved);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,42 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // Variable specifier so browser bundlers do not try to resolve node builtins.
10
+ const importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
11
+ function getProcessEnv() {
12
+ const proc = globalThis.process;
13
+ return proc?.env;
14
+ }
15
+ /**
16
+ * Default auth context: env vars from `process.env` (undefined in browsers),
17
+ * file existence via node:fs (always false in browsers).
18
+ */
19
+ export function defaultProviderAuthContext() {
20
+ return {
21
+ async env(name) {
22
+ const value = getProcessEnv()?.[name];
23
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
24
+ },
25
+ async fileExists(path) {
26
+ try {
27
+ const fs = (await importNodeModule("node:fs/promises"));
28
+ let resolved = path;
29
+ if (resolved.startsWith("~")) {
30
+ const os = (await importNodeModule("node:os"));
31
+ resolved = os.homedir() + resolved.slice(1);
32
+ }
33
+ await fs.access(resolved);
34
+ return true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ },
40
+ };
41
+ }
42
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/auth/context.ts"],"names":[],"mappings":";;;;;;;;AAUA,8EAA8E;AAC9E,MAAM,gBAAgB,GAAG,CAAC,SAAiB,EAAoB,EAAE,CAAC,MAAM,kCAAC,SAAS,EAAC,CAAC;AAEpF,SAAS,aAAa,GAAmD;IACxE,MAAM,IAAI,GAAI,UAAyE,CAAC,OAAO,CAAC;IAChG,OAAO,IAAI,EAAE,GAAG,CAAC;AAAA,CACjB;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B,GAAgB;IACzD,OAAO;QACN,KAAK,CAAC,GAAG,CAAC,IAAY,EAA+B;YACpD,MAAM,KAAK,GAAG,aAAa,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;QAAA,CAChF;QAED,KAAK,CAAC,UAAU,CAAC,IAAY,EAAoB;YAChD,IAAI,CAAC;gBACJ,MAAM,EAAE,GAAG,CAAC,MAAM,gBAAgB,CAAC,kBAAkB,CAAC,CAAiB,CAAC;gBACxE,IAAI,QAAQ,GAAG,IAAI,CAAC;gBACpB,IAAI,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;oBAC9B,MAAM,EAAE,GAAG,CAAC,MAAM,gBAAgB,CAAC,SAAS,CAAC,CAAiB,CAAC;oBAC/D,QAAQ,GAAG,EAAE,CAAC,OAAO,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC;gBACD,MAAM,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC1B,OAAO,IAAI,CAAC;YACb,CAAC;YAAC,MAAM,CAAC;gBACR,OAAO,KAAK,CAAC;YACd,CAAC;QAAA,CACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { AuthContext } from \"./types.ts\";\n\ninterface NodeFsModule {\n\taccess(path: string): Promise<void>;\n}\n\ninterface NodeOsModule {\n\thomedir(): string;\n}\n\n// Variable specifier so browser bundlers do not try to resolve node builtins.\nconst importNodeModule = (specifier: string): Promise<unknown> => import(specifier);\n\nfunction getProcessEnv(): Record<string, string | undefined> | undefined {\n\tconst proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n\treturn proc?.env;\n}\n\n/**\n * Default auth context: env vars from `process.env` (undefined in browsers),\n * file existence via node:fs (always false in browsers).\n */\nexport function defaultProviderAuthContext(): AuthContext {\n\treturn {\n\t\tasync env(name: string): Promise<string | undefined> {\n\t\t\tconst value = getProcessEnv()?.[name];\n\t\t\treturn typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n\t\t},\n\n\t\tasync fileExists(path: string): Promise<boolean> {\n\t\t\ttry {\n\t\t\t\tconst fs = (await importNodeModule(\"node:fs/promises\")) as NodeFsModule;\n\t\t\t\tlet resolved = path;\n\t\t\t\tif (resolved.startsWith(\"~\")) {\n\t\t\t\t\tconst os = (await importNodeModule(\"node:os\")) as NodeOsModule;\n\t\t\t\t\tresolved = os.homedir() + resolved.slice(1);\n\t\t\t\t}\n\t\t\t\tawait fs.access(resolved);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,17 @@
1
+ import type { Credential, CredentialInfo, CredentialStore } from "./types.ts";
2
+ /**
3
+ * Default in-memory credential store. Apps inject persistent stores.
4
+ * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
5
+ * Writes are serialized per provider through a promise chain.
6
+ */
7
+ export declare class InMemoryCredentialStore implements CredentialStore {
8
+ private credentials;
9
+ private chains;
10
+ /** Serialize tasks per provider id. */
11
+ private enqueue;
12
+ read(providerId: string): Promise<Credential | undefined>;
13
+ list(): Promise<readonly CredentialInfo[]>;
14
+ modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>): Promise<Credential | undefined>;
15
+ delete(providerId: string): Promise<void>;
16
+ }
17
+ //# sourceMappingURL=credential-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE9E;;;;GAIG;AACH,qBAAa,uBAAwB,YAAW,eAAe;IAC9D,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,MAAM,CAAuC;IAErD,uCAAuC;IACvC,OAAO,CAAC,OAAO;IAaT,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAE9D;IAEK,IAAI,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAE/C;IAED,MAAM,CACL,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,GACtE,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAOjC;IAED,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAIxC;CACD","sourcesContent":["import type { Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst next = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\treturn task();\n\t\t})();\n\t\tthis.chains.set(\n\t\t\tproviderId,\n\t\t\tnext.catch(() => {}),\n\t\t);\n\t\treturn next;\n\t}\n\n\tasync read(providerId: string): Promise<Credential | undefined> {\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(providerId, async () => {\n\t\t\tconst current = this.credentials.get(providerId);\n\t\t\tconst next = await fn(current);\n\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\treturn next ?? current;\n\t\t});\n\t}\n\n\tdelete(providerId: string): Promise<void> {\n\t\treturn this.enqueue(providerId, async () => {\n\t\t\tthis.credentials.delete(providerId);\n\t\t});\n\t}\n}\n"]}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Default in-memory credential store. Apps inject persistent stores.
3
+ * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
4
+ * Writes are serialized per provider through a promise chain.
5
+ */
6
+ export class InMemoryCredentialStore {
7
+ credentials = new Map();
8
+ chains = new Map();
9
+ /** Serialize tasks per provider id. */
10
+ enqueue(providerId, task) {
11
+ const previous = this.chains.get(providerId) ?? Promise.resolve();
12
+ const next = (async () => {
13
+ await previous.catch(() => { });
14
+ return task();
15
+ })();
16
+ this.chains.set(providerId, next.catch(() => { }));
17
+ return next;
18
+ }
19
+ async read(providerId) {
20
+ return this.credentials.get(providerId);
21
+ }
22
+ async list() {
23
+ return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));
24
+ }
25
+ modify(providerId, fn) {
26
+ return this.enqueue(providerId, async () => {
27
+ const current = this.credentials.get(providerId);
28
+ const next = await fn(current);
29
+ if (next !== undefined)
30
+ this.credentials.set(providerId, next);
31
+ return next ?? current;
32
+ });
33
+ }
34
+ delete(providerId) {
35
+ return this.enqueue(providerId, async () => {
36
+ this.credentials.delete(providerId);
37
+ });
38
+ }
39
+ }
40
+ //# sourceMappingURL=credential-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-store.js","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAC3B,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC5C,MAAM,GAAG,IAAI,GAAG,EAA4B,CAAC;IAErD,uCAAuC;IAC/B,OAAO,CAAI,UAAkB,EAAE,IAAsB,EAAc;QAC1E,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QAClE,MAAM,IAAI,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC;YACzB,MAAM,QAAQ,CAAC,KAAK,CAAC,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AAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import type { Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst next = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\treturn task();\n\t\t})();\n\t\tthis.chains.set(\n\t\t\tproviderId,\n\t\t\tnext.catch(() => {}),\n\t\t);\n\t\treturn next;\n\t}\n\n\tasync read(providerId: string): Promise<Credential | undefined> {\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(providerId, async () => {\n\t\t\tconst current = this.credentials.get(providerId);\n\t\t\tconst next = await fn(current);\n\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\treturn next ?? current;\n\t\t});\n\t}\n\n\tdelete(providerId: string): Promise<void> {\n\t\treturn this.enqueue(providerId, async () => {\n\t\t\tthis.credentials.delete(providerId);\n\t\t});\n\t}\n}\n"]}
@@ -0,0 +1,21 @@
1
+ import type { ApiKeyAuth, OAuthAuth } from "./types.ts";
2
+ /**
3
+ * Standard api-key auth: a stored credential key wins, otherwise the first
4
+ * set env var resolves. Includes a `login` that prompts for the key.
5
+ * Providers with non-standard resolution (provider env, ambient files, IAM)
6
+ * write their own `ApiKeyAuth`.
7
+ */
8
+ export declare function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth;
9
+ /**
10
+ * Wraps a dynamically imported `OAuthAuth` so provider definitions can
11
+ * advertise OAuth without importing the implementation. The flow loads on
12
+ * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out
13
+ * of bundles by loading through a bundler-opaque dynamic import (variable
14
+ * specifier, see the bedrock lazy wrapper).
15
+ */
16
+ export declare function lazyOAuth(input: {
17
+ name: string;
18
+ loginLabel?: string;
19
+ load: () => Promise<OAuthAuth>;
20
+ }): OAuthAuth;
21
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAExD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAkBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAA;CAAE,GAAG,SAAS,CAajH","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential }) => {\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: { name: string; loginLabel?: string; load: () => Promise<OAuthAuth> }): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction) => (await loaded()).login(interaction),\n\t\trefresh: async (credential) => (await loaded()).refresh(credential),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Standard api-key auth: a stored credential key wins, otherwise the first
3
+ * set env var resolves. Includes a `login` that prompts for the key.
4
+ * Providers with non-standard resolution (provider env, ambient files, IAM)
5
+ * write their own `ApiKeyAuth`.
6
+ */
7
+ export function envApiKeyAuth(name, envVars) {
8
+ return {
9
+ name,
10
+ login: async (interaction) => {
11
+ const key = await interaction.prompt({ type: "secret", message: `Enter ${name}` });
12
+ return { type: "api_key", key };
13
+ },
14
+ resolve: async ({ ctx, credential }) => {
15
+ if (credential?.key) {
16
+ return { auth: { apiKey: credential.key }, env: credential.env, source: "stored credential" };
17
+ }
18
+ for (const envVar of envVars) {
19
+ const value = await ctx.env(envVar);
20
+ if (value)
21
+ return { auth: { apiKey: value }, source: envVar };
22
+ }
23
+ return undefined;
24
+ },
25
+ };
26
+ }
27
+ /**
28
+ * Wraps a dynamically imported `OAuthAuth` so provider definitions can
29
+ * advertise OAuth without importing the implementation. The flow loads on
30
+ * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out
31
+ * of bundles by loading through a bundler-opaque dynamic import (variable
32
+ * specifier, see the bedrock lazy wrapper).
33
+ */
34
+ export function lazyOAuth(input) {
35
+ let promise;
36
+ const loaded = () => {
37
+ promise ??= input.load();
38
+ return promise;
39
+ };
40
+ return {
41
+ name: input.name,
42
+ loginLabel: input.loginLabel,
43
+ login: async (interaction) => (await loaded()).login(interaction),
44
+ refresh: async (credential) => (await loaded()).refresh(credential),
45
+ toAuth: async (credential) => (await loaded()).toAuth(credential),
46
+ };
47
+ }
48
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B,EAAc;IACnF,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC;YAC7B,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACnF,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;QAAA,CAChC;QACD,OAAO,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;YACvC,IAAI,UAAU,EAAE,GAAG,EAAE,CAAC;gBACrB,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,mBAAmB,EAAE,CAAC;YAC/F,CAAC;YACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;gBAC9B,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBACpC,IAAI,KAAK;oBAAE,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;YAC/D,CAAC;YACD,OAAO,SAAS,CAAC;QAAA,CACjB;KACD,CAAC;AAAA,CACF;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,KAA4E,EAAa;IAClH,IAAI,OAAuC,CAAC;IAC5C,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC;QACpB,OAAO,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC;IAAA,CACf,CAAC;IACF,OAAO;QACN,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC;QACjE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC;QACnE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;KACjE,CAAC;AAAA,CACF","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential }) => {\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: { name: string; loginLabel?: string; load: () => Promise<OAuthAuth> }): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction) => (await loaded()).login(interaction),\n\t\trefresh: async (credential) => (await loaded()).refresh(credential),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Anthropic OAuth flow (Claude Pro/Max)
3
+ *
4
+ * NOTE: This module uses Node.js http.createServer for the OAuth callback server.
5
+ * It is only intended for CLI use, not browser environments.
6
+ */
7
+ import type { OAuthAuth } from "../types.ts";
8
+ export declare const anthropicOAuth: OAuthAuth;
9
+ //# sourceMappingURL=anthropic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAmB,SAAS,EAAmB,MAAM,aAAa,CAAC;AA4U/E,eAAO,MAAM,cAAc,EAAE,SAQ5B,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 type { Server } from \"node:http\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\ntype CallbackServerInfo = {\n\tserver: Server;\n\tredirectUri: string;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string; state: string } | null>;\n};\n\ntype NodeApis = {\n\tcreateServer: typeof import(\"node:http\").createServer;\n};\n\nlet nodeApis: NodeApis | null = null;\nlet nodeApisPromise: Promise<NodeApis> | null = null;\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 SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\nasync function getNodeApis(): Promise<NodeApis> {\n\tif (nodeApis) return nodeApis;\n\tif (!nodeApisPromise) {\n\t\tif (typeof process === \"undefined\" || (!process.versions?.node && !process.versions?.bun)) {\n\t\t\tthrow new Error(\"Anthropic OAuth is only available in Node.js environments\");\n\t\t}\n\t\tnodeApisPromise = import(\"node:http\").then((httpModule) => ({\n\t\t\tcreateServer: httpModule.createServer,\n\t\t}));\n\t}\n\tnodeApis = await nodeApisPromise;\n\treturn nodeApis;\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 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 startCallbackServer(expectedState: string): Promise<CallbackServerInfo> {\n\tconst { createServer } = await getNodeApis();\n\n\treturn new Promise((resolve, reject) => {\n\t\tlet settleWait: ((value: { code: string; state: string } | null) => void) | undefined;\n\t\tconst waitForCodePromise = new Promise<{ code: string; state: string } | null>((resolveWait) => {\n\t\t\tlet settled = false;\n\t\t\tsettleWait = (value) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolveWait(value);\n\t\t\t};\n\t\t});\n\n\t\tconst server = createServer((req, res) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tres.writeHead(404, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\t\tconst state = url.searchParams.get(\"state\");\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Anthropic authentication did not complete.\", `Error: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!code || !state) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Missing code or state parameter.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (state !== expectedState) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthSuccessHtml(\"Anthropic authentication completed. You can close this window.\"));\n\t\t\t\tsettleWait?.({ code, state });\n\t\t\t} catch {\n\t\t\t\tres.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n\t\t\t\tres.end(\"Internal error\");\n\t\t\t}\n\t\t});\n\n\t\tserver.on(\"error\", (err) => {\n\t\t\treject(err);\n\t\t});\n\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tresolve({\n\t\t\t\tserver,\n\t\t\t\tredirectUri: REDIRECT_URI,\n\t\t\t\tcancelWait: () => {\n\t\t\t\t\tsettleWait?.(null);\n\t\t\t\t},\n\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t});\n\t\t});\n\t});\n}\n\nasync function postJson(url: string, body: Record<string, string | number>): 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.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): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(TOKEN_URL, {\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tstate,\n\t\t\tredirect_uri: redirectUri,\n\t\t\tcode_verifier: verifier,\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: AuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst server = await startCallbackServer(verifier);\n\tconst manualAbort = new AbortController();\n\tlet code: string | undefined;\n\tlet state: string | undefined;\n\tlet manualInput: string | undefined;\n\tlet manualError: Error | 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 manualPromise = interaction\n\t\t\t.prompt({\n\t\t\t\ttype: \"manual_code\",\n\t\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\tplaceholder: REDIRECT_URI,\n\t\t\t\tsignal: manualAbort.signal,\n\t\t\t})\n\t\t\t.then((input) => {\n\t\t\t\tmanualInput = input;\n\t\t\t\tserver.cancelWait();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tmanualError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tserver.cancelWait();\n\t\t\t});\n\n\t\tconst result = await server.waitForCode();\n\t\tif (manualError) throw manualError;\n\t\tif (result?.code) {\n\t\t\tcode = result.code;\n\t\t\tstate = result.state;\n\t\t} else if (manualInput) {\n\t\t\tconst parsed = parseAuthorizationInput(manualInput);\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) {\n\t\t\tawait manualPromise;\n\t\t\tif (manualError) throw manualError;\n\t\t\tif (manualInput) {\n\t\t\t\tconst parsed = parseAuthorizationInput(manualInput);\n\t\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\t\tcode = parsed.code;\n\t\t\t\tstate = parsed.state ?? verifier;\n\t\t\t}\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tif (!state) throw new Error(\"Missing OAuth state\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI);\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tserver.server.close();\n\t}\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(TOKEN_URL, {\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\trefresh_token: refreshToken,\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\tlogin: loginAnthropic,\n\trefresh: (credential) => refreshAnthropicToken(credential.refresh),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}