@draht/ai 2026.7.7 → 2026.7.12-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 (340) hide show
  1. package/dist/api/anthropic-messages.d.ts.map +1 -1
  2. package/dist/api/anthropic-messages.js +7 -4
  3. package/dist/api/anthropic-messages.js.map +1 -1
  4. package/dist/api/anthropic-messages.lazy.d.ts.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts +1 -1
  6. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  7. package/dist/api/azure-openai-responses.js +2 -3
  8. package/dist/api/azure-openai-responses.js.map +1 -1
  9. package/dist/api/azure-openai-responses.lazy.d.ts.map +1 -1
  10. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  11. package/dist/api/bedrock-converse-stream.js +1 -1
  12. package/dist/api/bedrock-converse-stream.js.map +1 -1
  13. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -1
  14. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
  15. package/dist/api/cloudflare.d.ts.map +1 -1
  16. package/dist/api/cloudflare.js.map +1 -1
  17. package/dist/api/github-copilot-headers.d.ts.map +1 -1
  18. package/dist/api/github-copilot-headers.js.map +1 -1
  19. package/dist/api/google-generative-ai.d.ts.map +1 -1
  20. package/dist/api/google-generative-ai.js.map +1 -1
  21. package/dist/api/google-generative-ai.lazy.d.ts.map +1 -1
  22. package/dist/api/google-shared.d.ts.map +1 -1
  23. package/dist/api/google-shared.js.map +1 -1
  24. package/dist/api/google-vertex.d.ts.map +1 -1
  25. package/dist/api/google-vertex.js.map +1 -1
  26. package/dist/api/google-vertex.lazy.d.ts.map +1 -1
  27. package/dist/api/lazy.d.ts.map +1 -1
  28. package/dist/api/lazy.js.map +1 -1
  29. package/dist/api/mistral-conversations.d.ts.map +1 -1
  30. package/dist/api/mistral-conversations.js.map +1 -1
  31. package/dist/api/mistral-conversations.lazy.d.ts.map +1 -1
  32. package/dist/api/openai-codex-responses.d.ts +1 -1
  33. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  34. package/dist/api/openai-codex-responses.js +2 -9
  35. package/dist/api/openai-codex-responses.js.map +1 -1
  36. package/dist/api/openai-codex-responses.lazy.d.ts.map +1 -1
  37. package/dist/api/openai-completions.d.ts +1 -1
  38. package/dist/api/openai-completions.d.ts.map +1 -1
  39. package/dist/api/openai-completions.js +2 -3
  40. package/dist/api/openai-completions.js.map +1 -1
  41. package/dist/api/openai-completions.lazy.d.ts.map +1 -1
  42. package/dist/api/openai-prompt-cache.d.ts.map +1 -1
  43. package/dist/api/openai-prompt-cache.js.map +1 -1
  44. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  45. package/dist/api/openai-responses-shared.js +6 -4
  46. package/dist/api/openai-responses-shared.js.map +1 -1
  47. package/dist/api/openai-responses.d.ts +1 -1
  48. package/dist/api/openai-responses.d.ts.map +1 -1
  49. package/dist/api/openai-responses.js +2 -3
  50. package/dist/api/openai-responses.js.map +1 -1
  51. package/dist/api/openai-responses.lazy.d.ts.map +1 -1
  52. package/dist/api/openrouter-images.d.ts.map +1 -1
  53. package/dist/api/openrouter-images.js.map +1 -1
  54. package/dist/api/openrouter-images.lazy.d.ts.map +1 -1
  55. package/dist/api/simple-options.d.ts +0 -5
  56. package/dist/api/simple-options.d.ts.map +1 -1
  57. package/dist/api/simple-options.js +1 -7
  58. package/dist/api/simple-options.js.map +1 -1
  59. package/dist/api/transform-messages.d.ts.map +1 -1
  60. package/dist/api/transform-messages.js.map +1 -1
  61. package/dist/auth/context.d.ts.map +1 -1
  62. package/dist/auth/context.js.map +1 -1
  63. package/dist/auth/credential-store.d.ts.map +1 -1
  64. package/dist/auth/credential-store.js +4 -2
  65. package/dist/auth/credential-store.js.map +1 -1
  66. package/dist/auth/helpers.d.ts.map +1 -1
  67. package/dist/auth/helpers.js.map +1 -1
  68. package/dist/auth/resolve.d.ts.map +1 -1
  69. package/dist/auth/resolve.js +0 -1
  70. package/dist/auth/resolve.js.map +1 -1
  71. package/dist/auth/types.d.ts.map +1 -1
  72. package/dist/bedrock-provider.d.ts.map +1 -1
  73. package/dist/cli.d.ts.map +1 -1
  74. package/dist/cli.js.map +1 -1
  75. package/dist/compat.d.ts.map +1 -1
  76. package/dist/compat.js.map +1 -1
  77. package/dist/env-api-keys.d.ts.map +1 -1
  78. package/dist/env-api-keys.js.map +1 -1
  79. package/dist/image-models.d.ts.map +1 -1
  80. package/dist/image-models.generated.d.ts.map +1 -1
  81. package/dist/image-models.js.map +1 -1
  82. package/dist/images-api-registry.d.ts.map +1 -1
  83. package/dist/images-api-registry.js.map +1 -1
  84. package/dist/images-models.d.ts.map +1 -1
  85. package/dist/images-models.js +1 -3
  86. package/dist/images-models.js.map +1 -1
  87. package/dist/images.d.ts.map +1 -1
  88. package/dist/images.js.map +1 -1
  89. package/dist/index.d.ts.map +1 -1
  90. package/dist/legacy-api-aliases.d.ts.map +1 -1
  91. package/dist/models.d.ts.map +1 -1
  92. package/dist/models.generated.d.ts +1108 -269
  93. package/dist/models.generated.d.ts.map +1 -1
  94. package/dist/models.js +15 -8
  95. package/dist/models.js.map +1 -1
  96. package/dist/oauth.d.ts.map +1 -1
  97. package/dist/providers/all.d.ts.map +1 -1
  98. package/dist/providers/all.js.map +1 -1
  99. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  100. package/dist/providers/amazon-bedrock.js.map +1 -1
  101. package/dist/providers/amazon-bedrock.models.d.ts +62 -5
  102. package/dist/providers/amazon-bedrock.models.d.ts.map +1 -1
  103. package/dist/providers/amazon-bedrock.models.js +32 -20
  104. package/dist/providers/amazon-bedrock.models.js.map +1 -1
  105. package/dist/providers/ant-ling.d.ts.map +1 -1
  106. package/dist/providers/ant-ling.js.map +1 -1
  107. package/dist/providers/ant-ling.models.d.ts.map +1 -1
  108. package/dist/providers/anthropic.d.ts.map +1 -1
  109. package/dist/providers/anthropic.js.map +1 -1
  110. package/dist/providers/anthropic.models.d.ts +11 -1
  111. package/dist/providers/anthropic.models.d.ts.map +1 -1
  112. package/dist/providers/anthropic.models.js +6 -4
  113. package/dist/providers/anthropic.models.js.map +1 -1
  114. package/dist/providers/azure-openai-responses.d.ts.map +1 -1
  115. package/dist/providers/azure-openai-responses.js.map +1 -1
  116. package/dist/providers/azure-openai-responses.models.d.ts +83 -0
  117. package/dist/providers/azure-openai-responses.models.d.ts.map +1 -1
  118. package/dist/providers/azure-openai-responses.models.js +71 -0
  119. package/dist/providers/azure-openai-responses.models.js.map +1 -1
  120. package/dist/providers/cerebras.d.ts.map +1 -1
  121. package/dist/providers/cerebras.js.map +1 -1
  122. package/dist/providers/cerebras.models.d.ts.map +1 -1
  123. package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
  124. package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
  125. package/dist/providers/cloudflare-ai-gateway.models.d.ts +11 -1
  126. package/dist/providers/cloudflare-ai-gateway.models.d.ts.map +1 -1
  127. package/dist/providers/cloudflare-ai-gateway.models.js +6 -4
  128. package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
  129. package/dist/providers/cloudflare-auth.d.ts.map +1 -1
  130. package/dist/providers/cloudflare-auth.js.map +1 -1
  131. package/dist/providers/cloudflare-workers-ai.d.ts.map +1 -1
  132. package/dist/providers/cloudflare-workers-ai.js.map +1 -1
  133. package/dist/providers/cloudflare-workers-ai.models.d.ts.map +1 -1
  134. package/dist/providers/deepseek.d.ts.map +1 -1
  135. package/dist/providers/deepseek.js.map +1 -1
  136. package/dist/providers/deepseek.models.d.ts +2 -2
  137. package/dist/providers/deepseek.models.d.ts.map +1 -1
  138. package/dist/providers/deepseek.models.js +2 -2
  139. package/dist/providers/deepseek.models.js.map +1 -1
  140. package/dist/providers/faux.d.ts.map +1 -1
  141. package/dist/providers/faux.js.map +1 -1
  142. package/dist/providers/fireworks.d.ts.map +1 -1
  143. package/dist/providers/fireworks.js.map +1 -1
  144. package/dist/providers/fireworks.models.d.ts +2 -2
  145. package/dist/providers/fireworks.models.d.ts.map +1 -1
  146. package/dist/providers/fireworks.models.js +3 -3
  147. package/dist/providers/fireworks.models.js.map +1 -1
  148. package/dist/providers/github-copilot.d.ts.map +1 -1
  149. package/dist/providers/github-copilot.js.map +1 -1
  150. package/dist/providers/github-copilot.models.d.ts +95 -2
  151. package/dist/providers/github-copilot.models.d.ts.map +1 -1
  152. package/dist/providers/github-copilot.models.js +68 -10
  153. package/dist/providers/github-copilot.models.js.map +1 -1
  154. package/dist/providers/google-vertex.d.ts.map +1 -1
  155. package/dist/providers/google-vertex.js.map +1 -1
  156. package/dist/providers/google-vertex.models.d.ts.map +1 -1
  157. package/dist/providers/google.d.ts.map +1 -1
  158. package/dist/providers/google.js.map +1 -1
  159. package/dist/providers/google.models.d.ts.map +1 -1
  160. package/dist/providers/groq.d.ts.map +1 -1
  161. package/dist/providers/groq.js.map +1 -1
  162. package/dist/providers/groq.models.d.ts.map +1 -1
  163. package/dist/providers/huggingface.d.ts.map +1 -1
  164. package/dist/providers/huggingface.js.map +1 -1
  165. package/dist/providers/huggingface.models.d.ts.map +1 -1
  166. package/dist/providers/images/register-builtins.d.ts.map +1 -1
  167. package/dist/providers/images/register-builtins.js.map +1 -1
  168. package/dist/providers/kimi-coding.d.ts.map +1 -1
  169. package/dist/providers/kimi-coding.js.map +1 -1
  170. package/dist/providers/kimi-coding.models.d.ts.map +1 -1
  171. package/dist/providers/minimax-cn.d.ts.map +1 -1
  172. package/dist/providers/minimax-cn.js.map +1 -1
  173. package/dist/providers/minimax-cn.models.d.ts.map +1 -1
  174. package/dist/providers/minimax.d.ts.map +1 -1
  175. package/dist/providers/minimax.js.map +1 -1
  176. package/dist/providers/minimax.models.d.ts.map +1 -1
  177. package/dist/providers/mistral.d.ts.map +1 -1
  178. package/dist/providers/mistral.js.map +1 -1
  179. package/dist/providers/mistral.models.d.ts.map +1 -1
  180. package/dist/providers/moonshotai-cn.d.ts.map +1 -1
  181. package/dist/providers/moonshotai-cn.js.map +1 -1
  182. package/dist/providers/moonshotai-cn.models.d.ts.map +1 -1
  183. package/dist/providers/moonshotai.d.ts.map +1 -1
  184. package/dist/providers/moonshotai.js.map +1 -1
  185. package/dist/providers/moonshotai.models.d.ts.map +1 -1
  186. package/dist/providers/nvidia.d.ts.map +1 -1
  187. package/dist/providers/nvidia.js.map +1 -1
  188. package/dist/providers/nvidia.models.d.ts.map +1 -1
  189. package/dist/providers/openai-codex.d.ts.map +1 -1
  190. package/dist/providers/openai-codex.js.map +1 -1
  191. package/dist/providers/openai-codex.models.d.ts +101 -0
  192. package/dist/providers/openai-codex.models.d.ts.map +1 -1
  193. package/dist/providers/openai-codex.models.js +59 -0
  194. package/dist/providers/openai-codex.models.js.map +1 -1
  195. package/dist/providers/openai.d.ts.map +1 -1
  196. package/dist/providers/openai.js.map +1 -1
  197. package/dist/providers/openai.models.d.ts +132 -0
  198. package/dist/providers/openai.models.d.ts.map +1 -1
  199. package/dist/providers/openai.models.js +78 -0
  200. package/dist/providers/openai.models.js.map +1 -1
  201. package/dist/providers/opencode-go.d.ts.map +1 -1
  202. package/dist/providers/opencode-go.js.map +1 -1
  203. package/dist/providers/opencode-go.models.d.ts +3 -3
  204. package/dist/providers/opencode-go.models.d.ts.map +1 -1
  205. package/dist/providers/opencode-go.models.js +3 -3
  206. package/dist/providers/opencode-go.models.js.map +1 -1
  207. package/dist/providers/opencode.d.ts.map +1 -1
  208. package/dist/providers/opencode.js.map +1 -1
  209. package/dist/providers/opencode.models.d.ts +124 -4
  210. package/dist/providers/opencode.models.d.ts.map +1 -1
  211. package/dist/providers/opencode.models.js +99 -7
  212. package/dist/providers/opencode.models.js.map +1 -1
  213. package/dist/providers/openrouter-images.d.ts.map +1 -1
  214. package/dist/providers/openrouter-images.js.map +1 -1
  215. package/dist/providers/openrouter.d.ts.map +1 -1
  216. package/dist/providers/openrouter.js.map +1 -1
  217. package/dist/providers/openrouter.models.d.ts +284 -85
  218. package/dist/providers/openrouter.models.d.ts.map +1 -1
  219. package/dist/providers/openrouter.models.js +296 -144
  220. package/dist/providers/openrouter.models.js.map +1 -1
  221. package/dist/providers/together.d.ts.map +1 -1
  222. package/dist/providers/together.js.map +1 -1
  223. package/dist/providers/together.models.d.ts.map +1 -1
  224. package/dist/providers/vercel-ai-gateway.d.ts.map +1 -1
  225. package/dist/providers/vercel-ai-gateway.js.map +1 -1
  226. package/dist/providers/vercel-ai-gateway.models.d.ts +139 -1
  227. package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
  228. package/dist/providers/vercel-ai-gateway.models.js +132 -8
  229. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  230. package/dist/providers/xai.d.ts.map +1 -1
  231. package/dist/providers/xai.js +6 -2
  232. package/dist/providers/xai.js.map +1 -1
  233. package/dist/providers/xai.models.d.ts +22 -0
  234. package/dist/providers/xai.models.d.ts.map +1 -1
  235. package/dist/providers/xai.models.js +18 -0
  236. package/dist/providers/xai.models.js.map +1 -1
  237. package/dist/providers/xiaomi-token-plan-ams.d.ts.map +1 -1
  238. package/dist/providers/xiaomi-token-plan-ams.js.map +1 -1
  239. package/dist/providers/xiaomi-token-plan-ams.models.d.ts +0 -42
  240. package/dist/providers/xiaomi-token-plan-ams.models.d.ts.map +1 -1
  241. package/dist/providers/xiaomi-token-plan-ams.models.js +9 -45
  242. package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -1
  243. package/dist/providers/xiaomi-token-plan-cn.d.ts.map +1 -1
  244. package/dist/providers/xiaomi-token-plan-cn.js.map +1 -1
  245. package/dist/providers/xiaomi-token-plan-cn.models.d.ts +0 -42
  246. package/dist/providers/xiaomi-token-plan-cn.models.d.ts.map +1 -1
  247. package/dist/providers/xiaomi-token-plan-cn.models.js +9 -45
  248. package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -1
  249. package/dist/providers/xiaomi-token-plan-sgp.d.ts.map +1 -1
  250. package/dist/providers/xiaomi-token-plan-sgp.js.map +1 -1
  251. package/dist/providers/xiaomi-token-plan-sgp.models.d.ts +0 -42
  252. package/dist/providers/xiaomi-token-plan-sgp.models.d.ts.map +1 -1
  253. package/dist/providers/xiaomi-token-plan-sgp.models.js +9 -45
  254. package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -1
  255. package/dist/providers/xiaomi.d.ts.map +1 -1
  256. package/dist/providers/xiaomi.js.map +1 -1
  257. package/dist/providers/xiaomi.models.d.ts.map +1 -1
  258. package/dist/providers/zai-coding-cn.d.ts.map +1 -1
  259. package/dist/providers/zai-coding-cn.js.map +1 -1
  260. package/dist/providers/zai-coding-cn.models.d.ts +1 -1
  261. package/dist/providers/zai-coding-cn.models.d.ts.map +1 -1
  262. package/dist/providers/zai-coding-cn.models.js +1 -1
  263. package/dist/providers/zai-coding-cn.models.js.map +1 -1
  264. package/dist/providers/zai.d.ts.map +1 -1
  265. package/dist/providers/zai.js.map +1 -1
  266. package/dist/providers/zai.models.d.ts +1 -1
  267. package/dist/providers/zai.models.d.ts.map +1 -1
  268. package/dist/providers/zai.models.js +1 -1
  269. package/dist/providers/zai.models.js.map +1 -1
  270. package/dist/session-resources.d.ts.map +1 -1
  271. package/dist/session-resources.js.map +1 -1
  272. package/dist/types.d.ts +15 -6
  273. package/dist/types.d.ts.map +1 -1
  274. package/dist/types.js.map +1 -1
  275. package/dist/utils/abort-signals.d.ts.map +1 -1
  276. package/dist/utils/abort-signals.js.map +1 -1
  277. package/dist/utils/diagnostics.d.ts.map +1 -1
  278. package/dist/utils/diagnostics.js.map +1 -1
  279. package/dist/utils/error-body.d.ts.map +1 -1
  280. package/dist/utils/error-body.js.map +1 -1
  281. package/dist/utils/estimate.d.ts +3 -3
  282. package/dist/utils/estimate.d.ts.map +1 -1
  283. package/dist/utils/estimate.js +17 -9
  284. package/dist/utils/estimate.js.map +1 -1
  285. package/dist/utils/event-stream.d.ts.map +1 -1
  286. package/dist/utils/event-stream.js +3 -7
  287. package/dist/utils/event-stream.js.map +1 -1
  288. package/dist/utils/hash.d.ts.map +1 -1
  289. package/dist/utils/hash.js.map +1 -1
  290. package/dist/utils/headers.d.ts.map +1 -1
  291. package/dist/utils/headers.js.map +1 -1
  292. package/dist/utils/json-parse.d.ts.map +1 -1
  293. package/dist/utils/json-parse.js.map +1 -1
  294. package/dist/utils/node-http-proxy.d.ts.map +1 -1
  295. package/dist/utils/node-http-proxy.js.map +1 -1
  296. package/dist/utils/oauth/anthropic.d.ts.map +1 -1
  297. package/dist/utils/oauth/anthropic.js.map +1 -1
  298. package/dist/utils/oauth/device-code.d.ts.map +1 -1
  299. package/dist/utils/oauth/device-code.js.map +1 -1
  300. package/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  301. package/dist/utils/oauth/github-copilot.js.map +1 -1
  302. package/dist/utils/oauth/google-antigravity.d.ts.map +1 -1
  303. package/dist/utils/oauth/google-antigravity.js.map +1 -1
  304. package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -1
  305. package/dist/utils/oauth/google-gemini-cli.js.map +1 -1
  306. package/dist/utils/oauth/index.d.ts +1 -0
  307. package/dist/utils/oauth/index.d.ts.map +1 -1
  308. package/dist/utils/oauth/index.js +4 -0
  309. package/dist/utils/oauth/index.js.map +1 -1
  310. package/dist/utils/oauth/load.d.ts +1 -0
  311. package/dist/utils/oauth/load.d.ts.map +1 -1
  312. package/dist/utils/oauth/load.js +1 -0
  313. package/dist/utils/oauth/load.js.map +1 -1
  314. package/dist/utils/oauth/oauth-page.d.ts.map +1 -1
  315. package/dist/utils/oauth/oauth-page.js.map +1 -1
  316. package/dist/utils/oauth/openai-codex.d.ts.map +1 -1
  317. package/dist/utils/oauth/openai-codex.js.map +1 -1
  318. package/dist/utils/oauth/opencode-go.d.ts.map +1 -1
  319. package/dist/utils/oauth/opencode-go.js.map +1 -1
  320. package/dist/utils/oauth/pkce.d.ts.map +1 -1
  321. package/dist/utils/oauth/pkce.js.map +1 -1
  322. package/dist/utils/oauth/types.d.ts.map +1 -1
  323. package/dist/utils/oauth/xai.d.ts +34 -0
  324. package/dist/utils/oauth/xai.d.ts.map +1 -0
  325. package/dist/utils/oauth/xai.js +339 -0
  326. package/dist/utils/oauth/xai.js.map +1 -0
  327. package/dist/utils/overflow.d.ts.map +1 -1
  328. package/dist/utils/overflow.js.map +1 -1
  329. package/dist/utils/provider-env.d.ts.map +1 -1
  330. package/dist/utils/provider-env.js.map +1 -1
  331. package/dist/utils/retry.d.ts.map +1 -1
  332. package/dist/utils/retry.js +3 -0
  333. package/dist/utils/retry.js.map +1 -1
  334. package/dist/utils/sanitize-unicode.d.ts.map +1 -1
  335. package/dist/utils/sanitize-unicode.js.map +1 -1
  336. package/dist/utils/typebox-helpers.d.ts.map +1 -1
  337. package/dist/utils/typebox-helpers.js.map +1 -1
  338. package/dist/utils/validation.d.ts.map +1 -1
  339. package/dist/utils/validation.js.map +1 -1
  340. package/package.json +4 -4
@@ -13,6 +13,7 @@ export function buildBaseOptions(model, context, options, apiKey) {
13
13
  maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),
14
14
  signal: options?.signal,
15
15
  apiKey: apiKey || options?.apiKey,
16
+ transport: options?.transport,
16
17
  cacheRetention: options?.cacheRetention,
17
18
  sessionId: options?.sessionId,
18
19
  headers: options?.headers,
@@ -31,13 +32,6 @@ export function clampReasoning(effort) {
31
32
  return "high";
32
33
  return effort;
33
34
  }
34
- /**
35
- * Clamp `max` down to `xhigh` while leaving everything else untouched.
36
- * Used by providers (e.g. OpenAI families) that support up to xhigh but not max.
37
- */
38
- export function clampToXhigh(effort) {
39
- return effort === "max" ? "xhigh" : effort;
40
- }
41
35
  export function adjustMaxTokensForThinking(
42
36
  // Undefined means no explicit caller cap. Use the model cap and fit thinking inside it.
43
37
  baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
@@ -1 +1 @@
1
- {"version":3,"file":"simple-options.js","sourceRoot":"","sources":["../../src/api/simple-options.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,MAAM,qBAAqB,G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U,cAAc,CAAC,MAAiC,EAAuD;IACtH,IAAI,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,KAAK;QAAE,OAAO,MAAM,CAAC;IAC1D,OAAO,MAAM,CAAC;AAAA,CACd;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiC,EAA6C;IAC1G,OAAO,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;AAAA,CAC3C;AAED,MAAM,UAAU,0BAA0B;AACzC,wFAAwF;AACxF,aAAiC,EACjC,cAAsB,EACtB,cAA6B,EAC7B,aAA+B,EACiB;IAChD,MAAM,cAAc,GAAoB;QACvC,OAAO,EAAE,IAAI;QACb,GAAG,EAAE,IAAI;QACT,MAAM,EAAE,IAAI;QACZ,IAAI,EAAE,KAAK;KACX,CAAC;IACF,MAAM,OAAO,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,aAAa,EAAE,CAAC;IAExD,MAAM,eAAe,GAAG,IAAI,CAAC;IAC7B,MAAM,KAAK,GAAG,cAAc,CAAC,cAAc,CAAE,CAAC;IAC9C,IAAI,cAAc,GAAG,OAAO,CAAC,KAAK,CAAE,CAAC;IACrC,MAAM,SAAS,GACd,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,GAAG,cAAc,EAAE,cAAc,CAAC,CAAC;IAEzG,IAAI,SAAS,IAAI,cAAc,EAAE,CAAC;QACjC,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,eAAe,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;AAAA,CACrC","sourcesContent":["import type {\n\tApi,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tThinkingBudgets,\n\tThinkingLevel,\n} from \"../types.ts\";\nimport { estimateContextTokens } from \"../utils/estimate.ts\";\n\nconst CONTEXT_SAFETY_TOKENS = 4096;\nconst MIN_MAX_TOKENS = 1;\n\nexport function clampMaxTokensToContext(model: Model<Api>, context: Context, maxTokens: number): number {\n\tif (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);\n\tconst available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;\n\treturn Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));\n}\n\nexport function buildBaseOptions(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n\tapiKey?: string,\n): StreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),\n\t\tsignal: options?.signal,\n\t\tapiKey: apiKey || options?.apiKey,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\theaders: options?.headers,\n\t\tonPayload: options?.onPayload,\n\t\tonResponse: options?.onResponse,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\tmetadata: options?.metadata,\n\t\tenv: options?.env,\n\t};\n}\n\nexport function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, \"xhigh\" | \"max\"> | undefined {\n\tif (effort === \"xhigh\" || effort === \"max\") return \"high\";\n\treturn effort;\n}\n\n/**\n * Clamp `max` down to `xhigh` while leaving everything else untouched.\n * Used by providers (e.g. OpenAI families) that support up to xhigh but not max.\n */\nexport function clampToXhigh(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, \"max\"> | undefined {\n\treturn effort === \"max\" ? \"xhigh\" : effort;\n}\n\nexport function adjustMaxTokensForThinking(\n\t// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it.\n\tbaseMaxTokens: number | undefined,\n\tmodelMaxTokens: number,\n\treasoningLevel: ThinkingLevel,\n\tcustomBudgets?: ThinkingBudgets,\n): { maxTokens: number; thinkingBudget: number } {\n\tconst defaultBudgets: ThinkingBudgets = {\n\t\tminimal: 1024,\n\t\tlow: 2048,\n\t\tmedium: 8192,\n\t\thigh: 16384,\n\t};\n\tconst budgets = { ...defaultBudgets, ...customBudgets };\n\n\tconst minOutputTokens = 1024;\n\tconst level = clampReasoning(reasoningLevel)!;\n\tlet thinkingBudget = budgets[level]!;\n\tconst maxTokens =\n\t\tbaseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t}\n\n\treturn { maxTokens, thinkingBudget };\n}\n"]}
1
+ {"version":3,"file":"simple-options.js","sourceRoot":"","sources":["../../src/api/simple-options.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,cAAc,GAAG,CAAC,CAAC;AAEzB,MAAM,UAAU,uBAAuB,CAAC,KAAiB,EAAE,OAAgB,EAAE,SAAiB;IAC7F,IAAI,KAAK,CAAC,aAAa,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;IACzE,MAAM,SAAS,GAAG,KAAK,CAAC,aAAa,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,qBAAqB,CAAC;IACtG,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC,CAAC;AACjE,CAAC;AAED,MAAM,UAAU,gBAAgB,CAC/B,KAAiB,EACjB,OAAgB,EAChB,OAA6B,EAC7B,MAAe;IAEf,OAAO;QACN,WAAW,EAAE,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cAAc,GAAG,OAAO,CAAC,KAAK,CAAE,CAAC;IACrC,MAAM,SAAS,GACd,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,GAAG,cAAc,EAAE,cAAc,CAAC,CAAC;IAEzG,IAAI,SAAS,IAAI,cAAc,EAAE,CAAC;QACjC,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,eAAe,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import type {\n\tApi,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tThinkingBudgets,\n\tThinkingLevel,\n} from \"../types.ts\";\nimport { estimateContextTokens } from \"../utils/estimate.ts\";\n\nconst CONTEXT_SAFETY_TOKENS = 4096;\nconst MIN_MAX_TOKENS = 1;\n\nexport function clampMaxTokensToContext(model: Model<Api>, context: Context, maxTokens: number): number {\n\tif (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);\n\tconst available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;\n\treturn Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));\n}\n\nexport function buildBaseOptions(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n\tapiKey?: string,\n): StreamOptions {\n\treturn {\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),\n\t\tsignal: options?.signal,\n\t\tapiKey: apiKey || options?.apiKey,\n\t\ttransport: options?.transport,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\theaders: options?.headers,\n\t\tonPayload: options?.onPayload,\n\t\tonResponse: options?.onResponse,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\tmetadata: options?.metadata,\n\t\tenv: options?.env,\n\t};\n}\n\nexport function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, \"xhigh\" | \"max\"> | undefined {\n\tif (effort === \"xhigh\" || effort === \"max\") return \"high\";\n\treturn effort;\n}\n\nexport function adjustMaxTokensForThinking(\n\t// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it.\n\tbaseMaxTokens: number | undefined,\n\tmodelMaxTokens: number,\n\treasoningLevel: ThinkingLevel,\n\tcustomBudgets?: ThinkingBudgets,\n): { maxTokens: number; thinkingBudget: number } {\n\tconst defaultBudgets: ThinkingBudgets = {\n\t\tminimal: 1024,\n\t\tlow: 2048,\n\t\tmedium: 8192,\n\t\thigh: 16384,\n\t};\n\tconst budgets = { ...defaultBudgets, ...customBudgets };\n\n\tconst minOutputTokens = 1024;\n\tconst level = clampReasoning(reasoningLevel)!;\n\tlet thinkingBudget = budgets[level]!;\n\tconst maxTokens =\n\t\tbaseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);\n\n\tif (maxTokens <= thinkingBudget) {\n\t\tthinkingBudget = Math.max(0, maxTokens - minOutputTokens);\n\t}\n\n\treturn { maxTokens, thinkingBudget };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transform-messages.d.ts","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,OAAO,EACP,KAAK,EAIL,MAAM,aAAa,CAAC;AAiDrB;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,SAAS,GAAG,EACjD,QAAQ,EAAE,OAAO,EAAE,EACnB,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,mBAAmB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,gBAAgB,KAAK,MAAM,GACxF,OAAO,EAAE,CA2JX","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"]}
1
+ {"version":3,"file":"transform-messages.d.ts","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,OAAO,EACP,KAAK,EAIL,MAAM,aAAa,CAAC;AAiDrB;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,SAAS,GAAG,EACjD,QAAQ,EAAE,OAAO,EAAE,EACnB,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,mBAAmB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,gBAAgB,KAAK,MAAM,GACxF,OAAO,EAAE,CA2JX"}
@@ -1 +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,CAA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,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"]}
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;IACjG,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;AACf,CAAC;AAED,SAAS,0BAA0B,CAAmB,QAAmB,EAAE,KAAkB;IAC5F,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;QAC3B,IAAI,GAAG,C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AAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,UAAU,CAAe,CAAC;YAC1F,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;AACf,CAAC","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"]}
@@ -1 +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"]}
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"}
@@ -1 +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"]}
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;IACrB,MAAM,IAAI,GAAI,UAAyE,CAAC,OAAO,CAAC;IAChG,OAAO,IAAI,EAAE,GAAG,CAAC;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B;IACzC,OAAO;QACN,KAAK,CAAC,GAAG,CAAC,IAAY;YACrB,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;QACjF,CAAC;QAED,KAAK,CAAC,UAAU,CAAC,IAAY;YAC5B,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;QACF,CAAC;KACD,CAAC;AACH,CAAC","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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE9D;;;;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;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, 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\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"]}
1
+ {"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE9D;;;;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;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"}
@@ -4,8 +4,10 @@
4
4
  * Writes are serialized per provider through a promise chain.
5
5
  */
6
6
  export class InMemoryCredentialStore {
7
- credentials = new Map();
8
- chains = new Map();
7
+ constructor() {
8
+ this.credentials = new Map();
9
+ this.chains = new Map();
10
+ }
9
11
  /** Serialize tasks per provider id. */
10
12
  enqueue(providerId, task) {
11
13
  const previous = this.chains.get(providerId) ?? Promise.resolve();
@@ -1 +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,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC,CAAC;YAC/B,OAAO,IAAI,EAAE,CAAC;QAAA,CACd,CAAC,EAAE,CAAC;QACL,IAAI,CAAC,MAAM,CAAC,GAAG,CACd,UAAU,EACV,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC,CACpB,CAAC;QACF,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,KAAK,CAAC,IAAI,CAAC,UAAkB,EAAmC;QAC/D,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAAA,CACxC;IAED,MAAM,CACL,UAAkB,EAClB,EAAwE,EACtC;QAClC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,IAAI,EAAE,CAAC;YAC3C,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACjD,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;YAC/B,IAAI,IAAI,KAAK,SAAS;gBAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;YAC/D,OAAO,IAAI,IAAI,OAAO,CAAC;QAAA,CACvB,CAAC,CAAC;IAAA,CACH;IAED,MAAM,CAAC,UAAkB,EAAiB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,IAAI,EAAE,CAAC;YAC3C,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAAA,CACpC,CAAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import type { Credential, 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\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"]}
1
+ {"version":3,"file":"credential-store.js","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAApC;QACS,gBAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;QAC5C,WAAM,GAAG,IAAI,GAAG,EAA4B,CAAC;IAqCtD,CAAC;IAnCA,uCAAuC;IAC/B,OAAO,CAAI,UAAkB,EAAE,IAAsB;QAC5D,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;YACxB,MAAM,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAC/B,OAAO,IAAI,EAAE,CAAC;QACf,CAAC,CAAC,EAAE,CAAC;QACL,IAAI,CAAC,MAAM,CAAC,GAAG,CACd,UAAU,EACV,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CACpB,CAAC;QACF,OAAO,IAAI,CAAC;IACb,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,UAAkB;QAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,CACL,UAAkB,EAClB,EAAwE;QAExE,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,IAAI,EAAE;YAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACjD,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;YAC/B,IAAI,IAAI,KAAK,SAAS;gBAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;YAC/D,OAAO,IAAI,IAAI,OAAO,CAAC;QACxB,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,UAAkB;QACxB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,IAAI,EAAE;YAC1C,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { Credential, 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\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"]}
@@ -1 +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,CAgBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAA;CAAE,GAAG,SAAS,CAY5F","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 (callbacks) => {\n\t\t\tconst key = await callbacks.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) return { auth: { apiKey: credential.key }, source: \"stored credential\" };\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; 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\tlogin: async (callbacks) => (await loaded()).login(callbacks),\n\t\trefresh: async (credential) => (await loaded()).refresh(credential),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
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,CAgBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAA;CAAE,GAAG,SAAS,CAY5F"}
@@ -1 +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,SAAS,EAAE,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACjF,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;gBAAE,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,mBAAmB,EAAE,CAAC;YAC9F,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,KAAuD,EAAa;IAC7F,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,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;QAC7D,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 (callbacks) => {\n\t\t\tconst key = await callbacks.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) return { auth: { apiKey: credential.key }, source: \"stored credential\" };\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; 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\tlogin: async (callbacks) => (await loaded()).login(callbacks),\n\t\trefresh: async (credential) => (await loaded()).refresh(credential),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE;YAC1B,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACjF,OAAO,E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uth } 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 (callbacks) => {\n\t\t\tconst key = await callbacks.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) return { auth: { apiKey: credential.key }, source: \"stored credential\" };\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; 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\tlogin: async (callbacks) => (await loaded()).login(callbacks),\n\t\trefresh: async (credential) => (await loaded()).refresh(credential),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,KAAK,EAGX,WAAW,EACX,UAAU,EAEV,eAAe,EAGf,YAAY,EACZ,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,eAAe,GAAG,cAAc,GAAG,kBAAkB,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAE7G,MAAM,WAAW,uBAAuB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,WAAW,CAAC;CAClB;AAED,qBAAa,WAAY,SAAQ,KAAK;IACrC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAE/B,YAAY,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIhF;CACD;AAED,6EAA6E;AAC7E,MAAM,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;AAE5D;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACxC,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,EAC5C,KAAK,EAAE,SAAS,EAChB,WAAW,EAAE,eAAe,EAC5B,WAAW,EAAE,WAAW,EACxB,SAAS,CAAC,EAAE,uBAAuB,GACjC,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAyBjC","sourcesContent":["import type { Api, ImagesApi, ImagesModel, Model, ProviderEnv } from \"../types.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Model shape auth resolution receives: chat or image-generation models. */\nexport type AuthModel = Model<Api> | ImagesModel<ImagesApi>;\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport async function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tmodel: AuthModel,\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, {\n\t\t\ttype: \"api_key\",\n\t\t\tkey: overrides.apiKey,\n\t\t\tenv: overrides.env,\n\t\t});\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, credential);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, model, undefined) : undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\n/**\n * OAuth resolution with double-checked locking (same pattern as today's\n * AuthStorage): valid tokens cost zero locks; expired tokens lock, re-check\n * expiry under the lock, refresh once globally, and persist the rotated\n * credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n): Promise<AuthResult | undefined> {\n\tlet credential = stored;\n\n\tif (Date.now() >= credential.expires) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(providerId, async (current) => {\n\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\tif (Date.now() < current.expires) return undefined; // another process/request refreshed\n\t\t\t\ttry {\n\t\t\t\t\treturn await oauth.refresh(current);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tmodel: AuthModel,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ model, ctx: authContext, credential });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${model.provider}`, { cause: error });\n\t}\n}\n\nasync function readCredential(credentials: CredentialStore, providerId: string): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId);\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,KAAK,EAGX,WAAW,EACX,UAAU,EAEV,eAAe,EAGf,YAAY,EACZ,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,eAAe,GAAG,cAAc,GAAG,kBAAkB,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAE7G,MAAM,WAAW,uBAAuB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,WAAW,CAAC;CAClB;AAED,qBAAa,WAAY,SAAQ,KAAK;IACrC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAE/B,YAAY,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIhF;CACD;AAED,6EAA6E;AAC7E,MAAM,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;AAE5D;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACxC,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,EAC5C,KAAK,EAAE,SAAS,EAChB,WAAW,EAAE,eAAe,EAC5B,WAAW,EAAE,WAAW,EACxB,SAAS,CAAC,EAAE,uBAAuB,GACjC,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAyBjC"}
@@ -1,5 +1,4 @@
1
1
  export class ModelsError extends Error {
2
- code;
3
2
  constructor(code, message, options) {
4
3
  super(message, options);
5
4
  this.name = "ModelsError";
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAoBA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC5B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B,EAAE;QAClF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAKD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACxC,QAA4C,EAC5C,KAAgB,EAChB,WAA4B,EAC5B,WAAwB,EACxB,SAAmC,EACD;IAClC,MAAM,kBAAkB,GAAG,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,qBAAqB,CAAC,WAAW,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;IAE5G,IAAI,SAAS,EAAE,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC7D,OAAO,aAAa,CAAC,kBAAkB,EAAE,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE;YACrE,IAAI,EAAE,SAAS;YACf,GAAG,EAAE,SAAS,CAAC,MAAM;YACrB,GAAG,EAAE,SAAS,CAAC,GAAG;SAClB,CAAC,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC9D,IAAI,MAAM,EAAE,CAAC;QACZ,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YACp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oC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACpG,CAAC;AAAA,CACD;AAED,KAAK,UAAU,aAAa,CAC3B,WAAwB,EACxB,MAAkB,EAClB,KAAgB,EAChB,UAAwC,EACN;IAClC,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACvG,CAAC;AAAA,CACD;AAED,KAAK,UAAU,cAAc,CAAC,WAA4B,EAAE,UAAkB,EAAmC;IAChH,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD","sourcesContent":["import type { Api, ImagesApi, ImagesModel, Model, ProviderEnv } from \"../types.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Model shape auth resolution receives: chat or image-generation models. */\nexport type AuthModel = Model<Api> | ImagesModel<ImagesApi>;\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport async function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tmodel: AuthModel,\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, {\n\t\t\ttype: \"api_key\",\n\t\t\tkey: overrides.apiKey,\n\t\t\tenv: overrides.env,\n\t\t});\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, credential);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, model, undefined) : undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\n/**\n * OAuth resolution with double-checked locking (same pattern as today's\n * AuthStorage): valid tokens cost zero locks; expired tokens lock, re-check\n * expiry under the lock, refresh once globally, and persist the rotated\n * credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n): Promise<AuthResult | undefined> {\n\tlet credential = stored;\n\n\tif (Date.now() >= credential.expires) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(providerId, async (current) => {\n\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\tif (Date.now() < current.expires) return undefined; // another process/request refreshed\n\t\t\t\ttry {\n\t\t\t\t\treturn await oauth.refresh(current);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tmodel: AuthModel,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ model, ctx: authContext, credential });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${model.provider}`, { cause: error });\n\t}\n}\n\nasync function readCredential(credentials: CredentialStore, providerId: string): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId);\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
1
+ {"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAoBA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAGrC,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B;QAChF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAKD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACxC,QAA4C,EAC5C,KAAgB,EAChB,WAA4B,EAC5B,WAAwB,EACxB,SAAmC;IAEnC,MAAM,kBAAkB,GAAG,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,qBAAqB,CAAC,WAAW,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;IAE5G,IAAI,SAAS,EAAE,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC7D,OAAO,aAAa,CAAC,kBAAkB,EAAE,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE;YACrE,IAAI,EAAE,SAAS;YACf,GAAG,EAAE,SAAS,CAAC,MAAM;YACrB,GAAG,EAAE,SAAS,CAAC,GAAG;SAClB,CAAC,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC9D,IAAI,MAAM,EAAE,CAAC;QACZ,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YACpD,OAAO,kBAAkB,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,EAAE,QAAQ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CAAC;AAED,KAAK,UAAU,aAAa,CAC3B,WAAwB,EACxB,MAAkB,EAClB,KAAgB,EAChB,UAAwC;IAExC,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACvG,CAAC;AACF,CAAC;AAED,KAAK,UAAU,cAAc,CAAC,WAA4B,EAAE,UAAkB;IAC7E,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AACF,CAAC","sourcesContent":["import type { Api, ImagesApi, ImagesModel, Model, ProviderEnv } from \"../types.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Model shape auth resolution receives: chat or image-generation models. */\nexport type AuthModel = Model<Api> | ImagesModel<ImagesApi>;\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport async function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tmodel: AuthModel,\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, {\n\t\t\ttype: \"api_key\",\n\t\t\tkey: overrides.apiKey,\n\t\t\tenv: overrides.env,\n\t\t});\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, model, credential);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, model, undefined) : undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\n/**\n * OAuth resolution with double-checked locking (same pattern as today's\n * AuthStorage): valid tokens cost zero locks; expired tokens lock, re-check\n * expiry under the lock, refresh once globally, and persist the rotated\n * credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n): Promise<AuthResult | undefined> {\n\tlet credential = stored;\n\n\tif (Date.now() >= credential.expires) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(providerId, async (current) => {\n\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\tif (Date.now() < current.expires) return undefined; // another process/request refreshed\n\t\t\t\ttry {\n\t\t\t\t\treturn await oauth.refresh(current);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tmodel: AuthModel,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ model, ctx: authContext, credential });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${model.provider}`, { cause: error });\n\t}\n}\n\nasync function readCredential(credentials: CredentialStore, providerId: string): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId);\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
@@ -1 +1 @@
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agesApi, ImagesModel, Model, ProviderEnv, ProviderHeaders } from \"../types.ts\";\nimport type { OAuthCredentials } from \"../utils/oauth/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/** Stored OAuth credential (`access`, `refresh`, `expires` from OAuthCredentials). */\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/**\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): Promise<Credential | undefined>;\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): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string): 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\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 type AuthEvent =\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 AuthLoginCallbacks {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\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?(callbacks: AuthLoginCallbacks): Promise<ApiKeyCredential>;\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. Receives the chat or image-generation model\n\t * the request is for (both carry `provider` and `baseUrl`).\n\t */\n\tresolve(input: {\n\t\tmodel: Model<Api> | ImagesModel<ImagesApi>;\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t}): Promise<AuthResult | undefined>;\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\tlogin(callbacks: AuthLoginCallbacks): 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): 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.d.ts","s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ts","sourceRoot":"","sources":["../src/bedrock-provider.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB;;;CAGjC,CAAC","sourcesContent":["import { stream, streamSimple } from \"./api/bedrock-converse-stream.ts\";\n\nexport const bedrockProviderModule = {\n\tstream,\n\tstreamSimple,\n};\n"]}
1
+ {"version":3,"file":"bedrock-provider.d.ts","sourceRoot":"","sources":["../src/bedrock-provider.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB;;;CAGjC,CAAC"}
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"","sourcesContent":["#!/usr/bin/env node\n\nimport { createInterface } from \"node:readline\";\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { getOAuthProvider, getOAuthProviders } from \"./utils/oauth/index.ts\";\nimport type { OAuthCredentials, OAuthProviderId } from \"./utils/oauth/types.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = getOAuthProviders();\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, { type: \"oauth\" } & OAuthCredentials> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\"));\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, { type: \"oauth\" } & OAuthCredentials>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function login(providerId: OAuthProviderId): Promise<void> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tconsole.error(`Unknown provider: ${providerId}`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\tconst promptFn = (msg: string) => prompt(rl, `${msg} `);\n\n\ttry {\n\t\tconst credentials = await provider.login({\n\t\t\tonAuth: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.url}`);\n\t\t\t\tif (info.instructions) console.log(info.instructions);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonDeviceCode: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.verificationUri}`);\n\t\t\t\tconsole.log(`Enter code: ${info.userCode}`);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonPrompt: async (p) => {\n\t\t\t\treturn await promptFn(`${p.message}${p.placeholder ? ` (${p.placeholder})` : \"\"}:`);\n\t\t\t},\n\t\t\tonSelect: async (p) => {\n\t\t\t\tconsole.log(`\\n${p.message}`);\n\t\t\t\tfor (let i = 0; i < p.options.length; i++) {\n\t\t\t\t\tconsole.log(` ${i + 1}. ${p.options[i].label}`);\n\t\t\t\t}\n\t\t\t\tconst choice = await promptFn(`Enter number (1-${p.options.length}):`);\n\t\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\t\treturn p.options[index]?.id;\n\t\t\t},\n\t\t\tonProgress: (msg) => console.log(msg),\n\t\t});\n\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = { type: \"oauth\", ...credentials };\n\t\tsaveAuth(auth);\n\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((p) => ` ${p.id.padEnd(20)} ${p.name}`).join(\"\\n\");\n\t\tconsole.log(`Usage: npx @draht/ai <command> [provider]\n\nCommands:\n login [provider] Login to an OAuth provider\n list List available providers\n\nProviders:\n${providerList}\n\nExamples:\n npx @draht/ai login # interactive provider selection\n npx @draht/ai login anthropic # login to specific provider\n npx @draht/ai list # list providers\n`);\n\t\treturn;\n\t}\n\n\tif (command === \"list\") {\n\t\tconsole.log(\"Available OAuth providers:\\n\");\n\t\tfor (const p of PROVIDERS) {\n\t\t\tconsole.log(` ${p.id.padEnd(20)} ${p.name}`);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (command === \"login\") {\n\t\tlet provider = args[1] as OAuthProviderId | undefined;\n\n\t\tif (!provider) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\tconsole.log(\"Select a provider:\\n\");\n\t\t\tfor (let i = 0; i < PROVIDERS.length; i++) {\n\t\t\t\tconsole.log(` ${i + 1}. ${PROVIDERS[i].name}`);\n\t\t\t}\n\t\t\tconsole.log();\n\n\t\t\tconst choice = await prompt(rl, `Enter number (1-${PROVIDERS.length}): `);\n\t\t\trl.close();\n\n\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\tif (index < 0 || index >= PROVIDERS.length) {\n\t\t\t\tconsole.error(\"Invalid selection\");\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tprovider = PROVIDERS[index].id;\n\t\t}\n\n\t\tif (!PROVIDERS.some((p) => p.id === provider)) {\n\t\t\tconsole.error(`Unknown provider: ${provider}`);\n\t\t\tconsole.error(`Use 'npx @draht/ai list' to see available providers`);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconsole.log(`Logging in to ${provider}...`);\n\t\tawait login(provider);\n\t\treturn;\n\t}\n\n\tconsole.error(`Unknown command: ${command}`);\n\tconsole.error(`Use 'npx @draht/ai --help' for usage`);\n\tprocess.exit(1);\n}\n\nmain().catch((err) => {\n\tconsole.error(\"Error:\", err.message);\n\tprocess.exit(1);\n});\n"]}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,eAAe,EAAE,M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KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;gBAC5C,OAAO,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACjB,CAAC;YACD,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QAChC,CAAC;QAED,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,QAAQ,CAAC,EAAE,CAAC;YAC/C,OAAO,CAAC,KAAK,CAAC,qBAAqB,QAAQ,EAAE,CAAC,CAAC;YAC/C,OAAO,CAAC,KAAK,CAAC,qDAAqD,CAAC,CAAC;YACrE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,iBAAiB,QAAQ,KAAK,CAAC,CAAC;QAC5C,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;QACtB,OAAO;IACR,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;IAC7C,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAAA,CAChB;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IACrB,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAAA,CAChB,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { createInterface } from \"node:readline\";\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { getOAuthProvider, getOAuthProviders } from \"./utils/oauth/index.ts\";\nimport type { OAuthCredentials, OAuthProviderId } from \"./utils/oauth/types.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = getOAuthProviders();\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, { type: \"oauth\" } & OAuthCredentials> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\"));\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, { type: \"oauth\" } & OAuthCredentials>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function login(providerId: OAuthProviderId): Promise<void> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tconsole.error(`Unknown provider: ${providerId}`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\tconst promptFn = (msg: string) => prompt(rl, `${msg} `);\n\n\ttry {\n\t\tconst credentials = await provider.login({\n\t\t\tonAuth: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.url}`);\n\t\t\t\tif (info.instructions) console.log(info.instructions);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonDeviceCode: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.verificationUri}`);\n\t\t\t\tconsole.log(`Enter code: ${info.userCode}`);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonPrompt: async (p) => {\n\t\t\t\treturn await promptFn(`${p.message}${p.placeholder ? ` (${p.placeholder})` : \"\"}:`);\n\t\t\t},\n\t\t\tonSelect: async (p) => {\n\t\t\t\tconsole.log(`\\n${p.message}`);\n\t\t\t\tfor (let i = 0; i < p.options.length; i++) {\n\t\t\t\t\tconsole.log(` ${i + 1}. ${p.options[i].label}`);\n\t\t\t\t}\n\t\t\t\tconst choice = await promptFn(`Enter number (1-${p.options.length}):`);\n\t\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\t\treturn p.options[index]?.id;\n\t\t\t},\n\t\t\tonProgress: (msg) => console.log(msg),\n\t\t});\n\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = { type: \"oauth\", ...credentials };\n\t\tsaveAuth(auth);\n\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((p) => ` ${p.id.padEnd(20)} ${p.name}`).join(\"\\n\");\n\t\tconsole.log(`Usage: npx @draht/ai <command> [provider]\n\nCommands:\n login [provider] Login to an OAuth provider\n list List available providers\n\nProviders:\n${providerList}\n\nExamples:\n npx @draht/ai login # interactive provider selection\n npx @draht/ai login anthropic # login to specific provider\n npx @draht/ai list # list providers\n`);\n\t\treturn;\n\t}\n\n\tif (command === \"list\") {\n\t\tconsole.log(\"Available OAuth providers:\\n\");\n\t\tfor (const p of PROVIDERS) {\n\t\t\tconsole.log(` ${p.id.padEnd(20)} ${p.name}`);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (command === \"login\") {\n\t\tlet provider = args[1] as OAuthProviderId | undefined;\n\n\t\tif (!provider) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\tconsole.log(\"Select a provider:\\n\");\n\t\t\tfor (let i = 0; i < PROVIDERS.length; i++) {\n\t\t\t\tconsole.log(` ${i + 1}. ${PROVIDERS[i].name}`);\n\t\t\t}\n\t\t\tconsole.log();\n\n\t\t\tconst choice = await prompt(rl, `Enter number (1-${PROVIDERS.length}): `);\n\t\t\trl.close();\n\n\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\tif (index < 0 || index >= PROVIDERS.length) {\n\t\t\t\tconsole.error(\"Invalid selection\");\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tprovider = PROVIDERS[index].id;\n\t\t}\n\n\t\tif (!PROVIDERS.some((p) => p.id === provider)) {\n\t\t\tconsole.error(`Unknown provider: ${provider}`);\n\t\t\tconsole.error(`Use 'npx @draht/ai list' to see available providers`);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconsole.log(`Logging in to ${provider}...`);\n\t\tawait login(provider);\n\t\treturn;\n\t}\n\n\tconsole.error(`Unknown command: ${command}`);\n\tconsole.error(`Use 'npx @draht/ai --help' for usage`);\n\tprocess.exit(1);\n}\n\nmain().catch((err) => {\n\tconsole.error(\"Error:\", err.message);\n\tprocess.exit(1);\n});\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG7E,MAAM,SAAS,GAAG,WAAW,CAAC;AAC9B,MAAM,SAAS,GAAG,iBAAiB,EAAE,CAAC;AAEtC,SAAS,MAAM,CAAC,EAAsC,EAAE,QAAgB;IACvE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AACjE,CAAC;AAED,SAAS,QAAQ;IAChB,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,OAAO,EAAE,CAAC;IACtC,IAAI,CAAC;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AAED,SAAS,QAA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AAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACpB,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { createInterface } from \"node:readline\";\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { getOAuthProvider, getOAuthProviders } from \"./utils/oauth/index.ts\";\nimport type { OAuthCredentials, OAuthProviderId } from \"./utils/oauth/types.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = getOAuthProviders();\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, { type: \"oauth\" } & OAuthCredentials> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\"));\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, { type: \"oauth\" } & OAuthCredentials>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function login(providerId: OAuthProviderId): Promise<void> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tconsole.error(`Unknown provider: ${providerId}`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\tconst promptFn = (msg: string) => prompt(rl, `${msg} `);\n\n\ttry {\n\t\tconst credentials = await provider.login({\n\t\t\tonAuth: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.url}`);\n\t\t\t\tif (info.instructions) console.log(info.instructions);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonDeviceCode: (info) => {\n\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${info.verificationUri}`);\n\t\t\t\tconsole.log(`Enter code: ${info.userCode}`);\n\t\t\t\tconsole.log();\n\t\t\t},\n\t\t\tonPrompt: async (p) => {\n\t\t\t\treturn await promptFn(`${p.message}${p.placeholder ? ` (${p.placeholder})` : \"\"}:`);\n\t\t\t},\n\t\t\tonSelect: async (p) => {\n\t\t\t\tconsole.log(`\\n${p.message}`);\n\t\t\t\tfor (let i = 0; i < p.options.length; i++) {\n\t\t\t\t\tconsole.log(` ${i + 1}. ${p.options[i].label}`);\n\t\t\t\t}\n\t\t\t\tconst choice = await promptFn(`Enter number (1-${p.options.length}):`);\n\t\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\t\treturn p.options[index]?.id;\n\t\t\t},\n\t\t\tonProgress: (msg) => console.log(msg),\n\t\t});\n\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = { type: \"oauth\", ...credentials };\n\t\tsaveAuth(auth);\n\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((p) => ` ${p.id.padEnd(20)} ${p.name}`).join(\"\\n\");\n\t\tconsole.log(`Usage: npx @draht/ai <command> [provider]\n\nCommands:\n login [provider] Login to an OAuth provider\n list List available providers\n\nProviders:\n${providerList}\n\nExamples:\n npx @draht/ai login # interactive provider selection\n npx @draht/ai login anthropic # login to specific provider\n npx @draht/ai list # list providers\n`);\n\t\treturn;\n\t}\n\n\tif (command === \"list\") {\n\t\tconsole.log(\"Available OAuth providers:\\n\");\n\t\tfor (const p of PROVIDERS) {\n\t\t\tconsole.log(` ${p.id.padEnd(20)} ${p.name}`);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (command === \"login\") {\n\t\tlet provider = args[1] as OAuthProviderId | undefined;\n\n\t\tif (!provider) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\tconsole.log(\"Select a provider:\\n\");\n\t\t\tfor (let i = 0; i < PROVIDERS.length; i++) {\n\t\t\t\tconsole.log(` ${i + 1}. ${PROVIDERS[i].name}`);\n\t\t\t}\n\t\t\tconsole.log();\n\n\t\t\tconst choice = await prompt(rl, `Enter number (1-${PROVIDERS.length}): `);\n\t\t\trl.close();\n\n\t\t\tconst index = parseInt(choice, 10) - 1;\n\t\t\tif (index < 0 || index >= PROVIDERS.length) {\n\t\t\t\tconsole.error(\"Invalid selection\");\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tprovider = PROVIDERS[index].id;\n\t\t}\n\n\t\tif (!PROVIDERS.some((p) => p.id === provider)) {\n\t\t\tconsole.error(`Unknown provider: ${provider}`);\n\t\t\tconsole.error(`Use 'npx @draht/ai list' to see available providers`);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconsole.log(`Logging in to ${provider}...`);\n\t\tawait login(provider);\n\t\treturn;\n\t}\n\n\tconsole.error(`Unknown command: ${command}`);\n\tconsole.error(`Use 'npx @draht/ai --help' for usage`);\n\tprocess.exit(1);\n}\n\nmain().catch((err) => {\n\tconsole.error(\"Error:\", err.message);\n\tprocess.exit(1);\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kCAAkC,CAAC;AACjD,cAAc,sCAAsC,CAAC;AACrD,cAAc,uCAAuC,CAAC;AACtD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,kCAAkC,CAAC;AACjD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GAAG,EACpD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@draht/ai\" to\n * \"@draht/ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@draht/ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@draht/ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@draht/ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport type ApiStreamFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: StreamOptions,\n) => AssistantMessageEventStream;\n\nexport type ApiStreamSimpleFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream;\n\nexport interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {\n\tapi: TApi;\n\tstream: StreamFunction<TApi, TOptions>;\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>;\n}\n\ninterface ApiProviderInternal {\n\tapi: Api;\n\tstream: ApiStreamFunction;\n\tstreamSimple: ApiStreamSimpleFunction;\n}\n\ntype RegisteredApiProvider = {\n\tprovider: ApiProviderInternal;\n\tsourceId?: string;\n};\n\nconst apiProviderRegistry = new Map<string, RegisteredApiProvider>();\n\nfunction wrapStream<TApi extends Api, TOptions extends StreamOptions>(\n\tapi: TApi,\n\tstream: StreamFunction<TApi, TOptions>,\n): ApiStreamFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn stream(model as Model<TApi>, context, options as TOptions);\n\t};\n}\n\nfunction wrapStreamSimple<TApi extends Api>(\n\tapi: TApi,\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>,\n): ApiStreamSimpleFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn streamSimple(model as Model<TApi>, context, options);\n\t};\n}\n\nexport function registerApiProvider<TApi extends Api, TOptions extends StreamOptions>(\n\tprovider: ApiProvider<TApi, TOptions>,\n\tsourceId?: string,\n): void {\n\tapiProviderRegistry.set(provider.api, {\n\t\tprovider: {\n\t\t\tapi: provider.api,\n\t\t\tstream: wrapStream(provider.api, provider.stream),\n\t\t\tstreamSimple: wrapStreamSimple(provider.api, provider.streamSimple),\n\t\t},\n\t\tsourceId,\n\t});\n}\n\nexport function getApiProvider(api: Api): ApiProviderInternal | undefined {\n\treturn apiProviderRegistry.get(api)?.provider;\n}\n\nexport function getApiProviders(): ApiProviderInternal[] {\n\treturn Array.from(apiProviderRegistry.values(), (entry) => entry.provider);\n}\n\nexport function unregisterApiProviders(sourceId: string): void {\n\tfor (const [api, entry] of apiProviderRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tapiProviderRegistry.delete(api);\n\t\t}\n\t}\n}\n\nfunction clearApiProviders(): void {\n\tapiProviderRegistry.clear();\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction shouldUseBuiltinModels(model: Model<Api>): boolean {\n\tconst builtin = compatModels.getModel(model.provider, model.id);\n\treturn builtin?.api === model.api && getApiProvider(model.api) === builtinApiProviderInstances.get(model.api);\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.stream(model, context, options as ApiStreamOptions<TApi> | undefined);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.streamSimple(model, context, options);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
1
+ {"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kCAAkC,CAAC;AACjD,cAAc,sCAAsC,CAAC;AACrD,cAAc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AC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAC5E;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B,EACD;IAC5B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AAAA,CAClB","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@draht/ai\" to\n * \"@draht/ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@draht/ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@draht/ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@draht/ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport type ApiStreamFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: StreamOptions,\n) => AssistantMessageEventStream;\n\nexport type ApiStreamSimpleFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream;\n\nexport interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {\n\tapi: TApi;\n\tstream: StreamFunction<TApi, TOptions>;\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>;\n}\n\ninterface ApiProviderInternal {\n\tapi: Api;\n\tstream: ApiStreamFunction;\n\tstreamSimple: ApiStreamSimpleFunction;\n}\n\ntype RegisteredApiProvider = {\n\tprovider: ApiProviderInternal;\n\tsourceId?: string;\n};\n\nconst apiProviderRegistry = new Map<string, RegisteredApiProvider>();\n\nfunction wrapStream<TApi extends Api, TOptions extends StreamOptions>(\n\tapi: TApi,\n\tstream: StreamFunction<TApi, TOptions>,\n): ApiStreamFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn stream(model as Model<TApi>, context, options as TOptions);\n\t};\n}\n\nfunction wrapStreamSimple<TApi extends Api>(\n\tapi: TApi,\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>,\n): ApiStreamSimpleFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn streamSimple(model as Model<TApi>, context, options);\n\t};\n}\n\nexport function registerApiProvider<TApi extends Api, TOptions extends StreamOptions>(\n\tprovider: ApiProvider<TApi, TOptions>,\n\tsourceId?: string,\n): void {\n\tapiProviderRegistry.set(provider.api, {\n\t\tprovider: {\n\t\t\tapi: provider.api,\n\t\t\tstream: wrapStream(provider.api, provider.stream),\n\t\t\tstreamSimple: wrapStreamSimple(provider.api, provider.streamSimple),\n\t\t},\n\t\tsourceId,\n\t});\n}\n\nexport function getApiProvider(api: Api): ApiProviderInternal | undefined {\n\treturn apiProviderRegistry.get(api)?.provider;\n}\n\nexport function getApiProviders(): ApiProviderInternal[] {\n\treturn Array.from(apiProviderRegistry.values(), (entry) => entry.provider);\n}\n\nexport function unregisterApiProviders(sourceId: string): void {\n\tfor (const [api, entry] of apiProviderRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tapiProviderRegistry.delete(api);\n\t\t}\n\t}\n}\n\nfunction clearApiProviders(): void {\n\tapiProviderRegistry.clear();\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction shouldUseBuiltinModels(model: Model<Api>): boolean {\n\tconst builtin = compatModels.getModel(model.provider, model.id);\n\treturn builtin?.api === model.api && getApiProvider(model.api) === builtinApiProviderInstances.get(model.api);\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.stream(model, context, options as ApiStreamOptions<TApi> | undefined);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.streamSimple(model, context, options);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s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K,CAAC,EAAE,CAAC;QACnC,OAAO,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAA6C,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAkB,CAAC,CAAC;AACxF,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC7B,KAAkB,EAClB,OAAgB,EAChB,OAA+B;IAE/B,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1C,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,YAAY,CAC3B,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,IAAI,sBAAsB,CAAC,KAAK,CAAC,EAAE,CAAC;QACnC,OAAO,YAAY,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;IACD,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@draht/ai\" to\n * \"@draht/ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@draht/ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@draht/ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@draht/ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport type ApiStreamFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: StreamOptions,\n) => AssistantMessageEventStream;\n\nexport type ApiStreamSimpleFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream;\n\nexport interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {\n\tapi: TApi;\n\tstream: StreamFunction<TApi, TOptions>;\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>;\n}\n\ninterface ApiProviderInternal {\n\tapi: Api;\n\tstream: ApiStreamFunction;\n\tstreamSimple: ApiStreamSimpleFunction;\n}\n\ntype RegisteredApiProvider = {\n\tprovider: ApiProviderInternal;\n\tsourceId?: string;\n};\n\nconst apiProviderRegistry = new Map<string, RegisteredApiProvider>();\n\nfunction wrapStream<TApi extends Api, TOptions extends StreamOptions>(\n\tapi: TApi,\n\tstream: StreamFunction<TApi, TOptions>,\n): ApiStreamFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn stream(model as Model<TApi>, context, options as TOptions);\n\t};\n}\n\nfunction wrapStreamSimple<TApi extends Api>(\n\tapi: TApi,\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>,\n): ApiStreamSimpleFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn streamSimple(model as Model<TApi>, context, options);\n\t};\n}\n\nexport function registerApiProvider<TApi extends Api, TOptions extends StreamOptions>(\n\tprovider: ApiProvider<TApi, TOptions>,\n\tsourceId?: string,\n): void {\n\tapiProviderRegistry.set(provider.api, {\n\t\tprovider: {\n\t\t\tapi: provider.api,\n\t\t\tstream: wrapStream(provider.api, provider.stream),\n\t\t\tstreamSimple: wrapStreamSimple(provider.api, provider.streamSimple),\n\t\t},\n\t\tsourceId,\n\t});\n}\n\nexport function getApiProvider(api: Api): ApiProviderInternal | undefined {\n\treturn apiProviderRegistry.get(api)?.provider;\n}\n\nexport function getApiProviders(): ApiProviderInternal[] {\n\treturn Array.from(apiProviderRegistry.values(), (entry) => entry.provider);\n}\n\nexport function unregisterApiProviders(sourceId: string): void {\n\tfor (const [api, entry] of apiProviderRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tapiProviderRegistry.delete(api);\n\t\t}\n\t}\n}\n\nfunction clearApiProviders(): void {\n\tapiProviderRegistry.clear();\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction shouldUseBuiltinModels(model: Model<Api>): boolean {\n\tconst builtin = compatModels.getModel(model.provider, model.id);\n\treturn builtin?.api === model.api && getApiProvider(model.api) === builtinApiProviderInstances.get(model.api);\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.stream(model, context, options as ApiStreamOptions<TApi> | undefined);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tif (shouldUseBuiltinModels(model)) {\n\t\treturn compatModels.streamSimple(model, context, options);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"env-api-keys.d.ts","sourceRoot":"","sources":["../src/env-api-keys.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAsF7D;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AAC9F,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AASvF;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAC7F,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC","sourcesContent":["// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _existsSync: typeof import(\"node:fs\").existsSync | null = null;\nlet _homedir: typeof import(\"node:os\").homedir | null = null;\nlet _join: typeof import(\"node:path\").join | null = null;\n\ntype DynamicImport = (specifier: string) => Promise<unknown>;\n\nconst dynamicImport: DynamicImport = (specifier) => import(specifier);\nconst NODE_FS_SPECIFIER = \"node:\" + \"fs\";\nconst NODE_OS_SPECIFIER = \"node:\" + \"os\";\nconst NODE_PATH_SPECIFIER = \"node:\" + \"path\";\n\n// Eagerly load in Node.js/Bun environment only\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\tdynamicImport(NODE_FS_SPECIFIER).then((m) => {\n\t\t_existsSync = (m as typeof import(\"node:fs\")).existsSync;\n\t});\n\tdynamicImport(NODE_OS_SPECIFIER).then((m) => {\n\t\t_homedir = (m as typeof import(\"node:os\")).homedir;\n\t});\n\tdynamicImport(NODE_PATH_SPECIFIER).then((m) => {\n\t\t_join = (m as typeof import(\"node:path\")).join;\n\t});\n}\n\nimport type { KnownProvider, ProviderEnv } from \"./types.ts\";\nimport { getProviderEnvValue } from \"./utils/provider-env.ts\";\n\nlet cachedVertexAdcCredentialsExists: boolean | null = null;\n\nfunction hasVertexAdcCredentials(env?: ProviderEnv): boolean {\n\tconst explicitCredentialsPath = env?.GOOGLE_APPLICATION_CREDENTIALS;\n\tif (explicitCredentialsPath) {\n\t\treturn _existsSync ? _existsSync(explicitCredentialsPath) : false;\n\t}\n\n\tif (cachedVertexAdcCredentialsExists === null) {\n\t\t// If node modules haven't loaded yet (async import race at startup),\n\t\t// return false WITHOUT caching so the next call retries once they're ready.\n\t\t// Only cache false permanently in a browser environment where fs is never available.\n\t\tif (!_existsSync || !_homedir || !_join) {\n\t\t\tconst isNode = typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun);\n\t\t\tif (!isNode) {\n\t\t\t\t// Definitively in a browser — safe to cache false permanently\n\t\t\t\tcachedVertexAdcCredentialsExists = false;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Check GOOGLE_APPLICATION_CREDENTIALS env var first (standard way)\n\t\tconst gacPath = getProviderEnvValue(\"GOOGLE_APPLICATION_CREDENTIALS\", env);\n\t\tif (gacPath) {\n\t\t\tcachedVertexAdcCredentialsExists = _existsSync(gacPath);\n\t\t} else {\n\t\t\t// Fall back to default ADC path (lazy evaluation)\n\t\t\tcachedVertexAdcCredentialsExists = _existsSync(\n\t\t\t\t_join(_homedir(), \".config\", \"gcloud\", \"application_default_credentials.json\"),\n\t\t\t);\n\t\t}\n\t}\n\treturn cachedVertexAdcCredentialsExists;\n}\n\nfunction getApiKeyEnvVars(provider: string): readonly string[] | undefined {\n\tif (provider === \"github-copilot\") {\n\t\treturn [\"COPILOT_GITHUB_TOKEN\"];\n\t}\n\n\t// ANTHROPIC_OAUTH_TOKEN takes precedence over ANTHROPIC_API_KEY\n\tif (provider === \"anthropic\") {\n\t\treturn [\"ANTHROPIC_OAUTH_TOKEN\", \"ANTHROPIC_API_KEY\"];\n\t}\n\n\tconst envMap: Record<string, string> = {\n\t\t\"ant-ling\": \"ANT_LING_API_KEY\",\n\t\topenai: \"OPENAI_API_KEY\",\n\t\t\"azure-openai-responses\": \"AZURE_OPENAI_API_KEY\",\n\t\tnvidia: \"NVIDIA_API_KEY\",\n\t\tdeepseek: \"DEEPSEEK_API_KEY\",\n\t\tgoogle: \"GEMINI_API_KEY\",\n\t\t\"google-vertex\": \"GOOGLE_CLOUD_API_KEY\",\n\t\tgroq: \"GROQ_API_KEY\",\n\t\tcerebras: \"CEREBRAS_API_KEY\",\n\t\txai: \"XAI_API_KEY\",\n\t\topenrouter: \"OPENROUTER_API_KEY\",\n\t\t\"vercel-ai-gateway\": \"AI_GATEWAY_API_KEY\",\n\t\tzai: \"ZAI_API_KEY\",\n\t\t\"zai-coding-cn\": \"ZAI_CODING_CN_API_KEY\",\n\t\tmistral: \"MISTRAL_API_KEY\",\n\t\tminimax: \"MINIMAX_API_KEY\",\n\t\t\"minimax-cn\": \"MINIMAX_CN_API_KEY\",\n\t\tmoonshotai: \"MOONSHOT_API_KEY\",\n\t\t\"moonshotai-cn\": \"MOONSHOT_API_KEY\",\n\t\thuggingface: \"HF_TOKEN\",\n\t\tfireworks: \"FIREWORKS_API_KEY\",\n\t\ttogether: \"TOGETHER_API_KEY\",\n\t\topencode: \"OPENCODE_API_KEY\",\n\t\t\"opencode-go\": \"OPENCODE_API_KEY\",\n\t\t\"kimi-coding\": \"KIMI_API_KEY\",\n\t\t\"cloudflare-workers-ai\": \"CLOUDFLARE_API_KEY\",\n\t\t\"cloudflare-ai-gateway\": \"CLOUDFLARE_API_KEY\",\n\t\txiaomi: \"XIAOMI_API_KEY\",\n\t\t\"xiaomi-token-plan-cn\": \"XIAOMI_TOKEN_PLAN_CN_API_KEY\",\n\t\t\"xiaomi-token-plan-ams\": \"XIAOMI_TOKEN_PLAN_AMS_API_KEY\",\n\t\t\"xiaomi-token-plan-sgp\": \"XIAOMI_TOKEN_PLAN_SGP_API_KEY\",\n\t};\n\n\tconst envVar = envMap[provider];\n\treturn envVar ? [envVar] : undefined;\n}\n\n/**\n * Find configured environment variables that can provide an API key for a provider.\n *\n * This only reports actual API key variables. It intentionally excludes ambient\n * credential sources such as AWS profiles, AWS IAM credentials, and Google\n * Application Default Credentials.\n */\nexport function findEnvKeys(provider: KnownProvider, env?: ProviderEnv): string[] | undefined;\nexport function findEnvKeys(provider: string, env?: ProviderEnv): string[] | undefined;\nexport function findEnvKeys(provider: string, env?: ProviderEnv): string[] | undefined {\n\tconst envVars = getApiKeyEnvVars(provider);\n\tif (!envVars) return undefined;\n\n\tconst found = envVars.filter((envVar) => !!getProviderEnvValue(envVar, env));\n\treturn found.length > 0 ? found : undefined;\n}\n\n/**\n * Get API key for provider from known environment variables, e.g. OPENAI_API_KEY.\n *\n * Will not return API keys for providers that require OAuth tokens.\n */\nexport function getEnvApiKey(provider: KnownProvider, env?: ProviderEnv): string | undefined;\nexport function getEnvApiKey(provider: string, env?: ProviderEnv): string | undefined;\nexport function getEnvApiKey(provider: string, env?: ProviderEnv): string | undefined {\n\tconst envKeys = findEnvKeys(provider, env);\n\tif (envKeys?.[0]) {\n\t\treturn getProviderEnvValue(envKeys[0], env);\n\t}\n\n\t// Vertex AI supports either an explicit API key or Application Default Credentials.\n\t// Auth is configured via `gcloud auth application-default login`.\n\tif (provider === \"google-vertex\") {\n\t\tconst hasCredentials = hasVertexAdcCredentials(env);\n\t\tconst hasProject = !!(\n\t\t\tgetProviderEnvValue(\"GOOGLE_CLOUD_PROJECT\", env) || getProviderEnvValue(\"GCLOUD_PROJECT\", env)\n\t\t);\n\t\tconst hasLocation = !!getProviderEnvValue(\"GOOGLE_CLOUD_LOCATION\", env);\n\n\t\tif (hasCredentials && hasProject && hasLocation) {\n\t\t\treturn \"<authenticated>\";\n\t\t}\n\t}\n\n\tif (provider === \"amazon-bedrock\") {\n\t\t// Amazon Bedrock supports multiple credential sources:\n\t\t// 1. AWS_PROFILE - named profile from ~/.aws/credentials\n\t\t// 2. AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY - standard IAM keys\n\t\t// 3. AWS_BEARER_TOKEN_BEDROCK - Bedrock bearer token\n\t\t// 4. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI - ECS task roles\n\t\t// 5. AWS_CONTAINER_CREDENTIALS_FULL_URI - ECS task roles (full URI)\n\t\t// 6. AWS_WEB_IDENTITY_TOKEN_FILE - IRSA (IAM Roles for Service Accounts)\n\t\tif (\n\t\t\tgetProviderEnvValue(\"AWS_PROFILE\", env) ||\n\t\t\t(getProviderEnvValue(\"AWS_ACCESS_KEY_ID\", env) && getProviderEnvValue(\"AWS_SECRET_ACCESS_KEY\", env)) ||\n\t\t\tgetProviderEnvValue(\"AWS_BEARER_TOKEN_BEDROCK\", env) ||\n\t\t\tgetProviderEnvValue(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\", env) ||\n\t\t\tgetProviderEnvValue(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\", env) ||\n\t\t\tgetProviderEnvValue(\"AWS_WEB_IDENTITY_TOKEN_FILE\", env)\n\t\t) {\n\t\t\treturn \"<authenticated>\";\n\t\t}\n\t}\n\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"env-api-keys.d.ts","sourceRoot":"","sources":["../src/env-api-keys.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAsF7D;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AAC9F,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AASvF;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAC7F,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC"}